text
stringlengths 184
4.48M
|
---|
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
// esquemas de mogoose
let Schema = mongoose.Schema;
let rolesValidos = {
values: ['ADMIN_ROLE', 'USER_ROLE', 'INVITED_ROLE'],
message: '{VALUE} no es un rol valido'
};
let personSchema = new Schema({
password: {
type: String,
required: [true, 'la contrasena es obligatoria']
},
name: {
type: String,
required: [true, 'El nombre es necesario']
},
last_name: {
type: String,
required: [true, 'El apellido es necesario']
},
email: {
type: String,
unique: true,
required: [true, 'El correo es necesario']
},
degree: {
type: String,
required: false,
},
description: {
type: String,
required: false
},
url_image: {
type: String,
required: false
},
type_inscription: {
type: String,
required: false
},
career: {
type: String,
required: false
},
gender: {
type: String,
required: false
},
role: {
type: String,
default: 'USER_ROLE',
enum: rolesValidos
},
status: {
type: Boolean,
default: true
},
google: {
type: Boolean,
default: false
}
});
personSchema.methods.toJSON = function() {
let user = this;
let userObject = user.toObject();
delete userObject.password;
return userObject;
}
personSchema.plugin(uniqueValidator, { message: '{PATH} debe de ser unico' });
module.exports = mongoose.model('Person', personSchema);
|
import React, { useMemo } from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import { Sheet } from '@mui/joy'
import { Container } from './container'
import { useScrolling } from '../hooks'
import { Link } from './link'
import { Menu } from './menu'
const Header = ({ siteTitle, menuOptions }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
themeYaml {
metadata {
title
}
}
}
`)
const { scrollPosition } = useScrolling()
// reduce header after user has scrolled down an bit,
// at least through the hero.
const reducedHeader = useMemo(() => {
return scrollPosition > 500
}, [scrollPosition])
return (
<Sheet
component="header"
sx={{
backgroundColor: reducedHeader ? '#fffc' : '#fff4',
'&:hover': {
backgroundColor: '#ffff',
},
filter: reducedHeader ? 'drop-shadow(0 0 8px #0003)' : '',
transition: 'filter 250ms 100ms, min-height 350ms, background-color 250ms 100ms',
backdropFilter: 'blur(3px)',
zIndex: 9,
position: 'fixed',
width: '100%',
display: 'flex',
justifyContent: 'center',
'.header-container': {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-start',
},
px: 1,
minHeight: reducedHeader ? '3rem' : '5rem',
'.brand': {
p: 1,
alignSelf:'stretch',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
}}
>
<Container className="header-container">
<Link to="/" className="brand">{ data.themeYaml.metadata.title }</Link>
<Menu options={ menuOptions } />
</Container>
</Sheet>
)
}
export default Header
|
package plugin
import (
"net/rpc"
"github.com/hashicorp/go-plugin"
)
// Greeter is the interface that we're exposing as a plugin.
type Greeter interface {
Greet() string
}
type GreeterPlugin struct{
PluginFunc Greeter
}
func (p *GreeterPlugin) Server(*plugin.MuxBroker) (interface{}, error) {
return &GreeterRPCServer{Impl: p.PluginFunc}, nil
}
func (GreeterPlugin) Client(b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) {
return &GreeterRPC{client: c}, nil
}
// Here is an implementation that talks over RPC
type GreeterRPC struct{ client *rpc.Client }
func (g *GreeterRPC) Greet() string {
var resp string
err := g.client.Call("Plugin.Greet", new(interface{}), &resp)
if err != nil {
// You usually want your interfaces to return errors. If they don't,
// there isn't much other choice here.
panic(err)
}
return resp
}
// Here is the RPC server that GreeterRPC talks to, conforming to
// the requirements of net/rpc
type GreeterRPCServer struct {
// This is the real implementation
Impl Greeter
}
func (s *GreeterRPCServer) Greet(args interface{}, resp *string) error {
*resp = s.Impl.Greet()
return nil
}
|
import { IPostRepository } from '@/domain';
import { isDevelopment } from '@/extension';
import { PostRepository, PostResponse } from '@/infrastructure';
export class FetchPostSlugsUseCase {
private readonly postRepository: IPostRepository;
constructor() {
this.postRepository = new PostRepository();
}
private async makePosts(posts: PostResponse[]): Promise<PostResponse[]> {
const response = await this.postRepository.getPosts(100, posts.length);
if (response.length < 100 || isDevelopment()) {
return [...posts, ...response];
}
return this.makePosts([...posts, ...response]);
}
public async execute(): Promise<string[]> {
const posts = await this.makePosts([]);
return posts.map((post) => post.slug);
}
}
|
# Operational Challenges for SCIM Servers
## Table of Contents
- [What is SCIM?](#what-is-scim)
- [The Key Operational Challenges](#the-key-operational-challenges)
* [No Load Limits](#no-load-limits)
* [All Requests Must be Synchronously Handled](#all-requests-must-be-synchronously-handled)
- [Downstream Consequences when Faced with “Scale”](#downstream-consequences-when-faced-with-scale)
* [Performance Problems with 3rd Party SCIM Libraries](#performance-problems-with-3rd-party-scim-libraries)
* [ORM Problems Leading to Database Performance Problems Leading to Other ORM Problems](#orm-problems-leading-to-database-performance-problems-leading-to-other-orm-problems)
* [Inability to Throttle Requests](#inability-to-throttle-requests)
* [Inability to Queue Requests](#inability-to-queue-requests)
* [Inability to Horizontally Scale](#inability-to-horizontally-scale)
- [Takeaways](#takeaways)
* [Targeted Avoidance of the ORM-to-SCIM-to-ORM Pattern is Valuable](#targeted-avoidance-of-the-orm-to-scim-to-orm-pattern-is-valuable)
* [Threading is Potentially Valuable, Maybe](#threading-is-potentially-valuable-maybe)
* [Pre-Production Load Testing of SCIM Servers is Valuable](#pre-production-load-testing-of-scim-servers-is-valuable)
* [Recording Failed SCIM Requests in Production Telemetry is Valuable](#recording-failed-scim-requests-in-production-telemetry-is-valuable)
## What is SCIM?
SCIM (System for Cross-domain Identity Management) is an open standard for user provisioning.
For example, it allows an organization that is a customer of a SaaS product to easily sync all of their users’ identity information into the SaaS’s databases.
The organization’s users’ identity information will often be stored in a 3rd party identity provider like Okta or Azure Active Directory (Azure AD). The identity provider will act as a SCIM client, sending requests with provisioning data to a SCIM server managed by the SaaS product.
Building a conformant and operational SCIM server however is a non-trivial task.
## The Key Operational Challenges
There are 2 inherent operational difficulties all SCIM server implementations must face.
### No Load Limits
A SCIM client has no restrictions on how quickly it can send requests to your SCIM server.
In theory, this means that your SCIM server needs to be able to handle arbitrary requests at arbitrary concurrency.
In practice, this means that your SCIM server needs to be able to handle the load of “the worst” SCIM client out there (Azure AD’s SCIM client has been observed to send somewhere just shy of 1000 requests per minute at peak load)
### All Requests Must be Synchronously Handled
SCIM clients rely on the status code of responses to determine whether or not to retry a request (e.g. a client may retry all 500-level errors until it succeeds).
This means that all request processing has to be done synchronously (i.e. it can’t be offloaded to consumers of a separate queue).
## Downstream Consequences when Faced with “Scale”
When faced with increased load and larger customers, several different types of problems can arise for a SCIM server implementation.
### Performance Problems with 3rd Party SCIM Libraries
Handling SCIM requests means writing the logic for applying a request’s changes to a SCIM resource (e.g. PATCH-ing a group).
Depending on your runtime, there may be existing libraries that already have this logic ready for re-use (e.g. [scim-patch](https://www.npmjs.com/package/scim-patch) for PATCH requests in Node.js). However, a library’s code may not necessarily be optimized for performance in every case.
For example, a library function’s execution time may sometimes scale quadratically with the size of the request and/or SCIM resource (e.g. for groups with a large number of users). This can drastically slow down response times (think 10s of seconds) and hog server CPU (a lethal problem for single-threaded runtimes like Node.js).
### ORM Problems Leading to Database Performance Problems Leading to Other ORM Problems
If you’re using an ORM (Object Relational Mapping), all of your PATCH or PUT SCIM endpoints may work as follows
1. Load the ORM’s representation of the SCIM resource from the database
2. Transform the ORM’s representation into a SCIM representation expected by the SCIM library
3. Apply the request to the SCIM representation using the SCIM library
4. Transform the updated SCIM representation back into an ORM representation of the resource
5. Save the ORM representation back to the database
The problem with this can occur in Step 5, as the ORM has no idea of what exactly changed and so can in certain cases end up recreating the database records from scratch.
For example, consider PATCH-ing a very large group (10,000 or more users) to add 1 user to the group, where in the database users in a group are represented in a join table between the Groups and Users tables. In Step 5, the ORM isn’t aware that 1 user was added, so instead it generates SQL to delete all the existing users from the group and then re-insert them all plus the 1 new user.
This can become extremely problematic when these requests happen at high concurrency (e.g. Azure AD sending a huge number of near parallel requests to add 1 user at a time to a group). Every request requires an exclusive lock on the join table because of the deletes, so the transactions end up being processed 1 at a time at the database-level, leading to very slow query times.
Because of these delays in database processing, ORM operations will start to back up in their queue and time out. ORM database connection pools will become maxed out as well. This will cause a massive percentage (e.g. 95+%) of the requests to fail. So many that no amount of retrying from the SCIM client will fix things.

### Inability to Throttle Requests
Because of the severe slowdown and serialization in request processing under this high concurrency, throttling is ineffective as it will just lead to timeouts at the gateway instead (e.g. 504s from the load balancer fronting the SCIM server replicas) .
### Inability to Queue Requests
Because SCIM requires that requests be synchronous, putting the requests onto a separate queue (e.g. an SQS queue) to avoid all of the aforementioned problems won’t work because if a queue consumer fails to process a request for some reason there’s no way to indicate that to the SCIM client so it knows to retry.
### Inability to Horizontally Scale
SCIM clients’ barrage of requests can start suddenly and end just as quickly (think minutes) which isn’t enough time for traditional autoscaling tools to respond by creating more replicas of the SCIM servers.
Also in the case of the database lock contention issue mentioned before, more replicas (and hence more available database connections) can actually make things worse, as the line of concurrent transactions waiting on the database lock will grow even longer.
## Takeaways
Stepping back, there are a few high-level things to take away from the previous pessimism.
### Targeted Avoidance of the ORM-to-SCIM-to-ORM Pattern is Valuable
In the large group scenario from before, if all of the requests happen to be adding or removing 1 user from a group, making that 1 change directly to the database (via the ORM) rather than creating an intermediate SCIM representation of the group that the ORM then has to save back to the database can avoid all of the aforementioned problems.
### Threading is Potentially Valuable, Maybe
As an alternative to using a separate queue, using separate runtime threads and an in-memory request queue may help avoid saturation in the specific case of a server CPU bottleneck coming from request processing.
### Pre-Production Load Testing of SCIM Servers is Valuable
Simulating the type and concurrency of requests that SCIM clients may deliver should be a valuable exercise, as it may unearth several bottlenecks in the SCIM server that may not become otherwise apparent until production.
You might try forking https://github.com/wso2-incubator/scim2-compliance-test-suite and adjusting it to be able to send requests at high concurrency towards this end.
### Recording Failed SCIM Requests in Production Telemetry is Valuable
The first step in addressing a novel operational problem happening with your SCIM servers in production is usually to develop some understanding of it.
On top of your usual sources of telemetry (e.g. OpenTelemetry, Application Performance Monitoring tools, RDS Performance Monitoring) recording the raw SCIM request data of failed requests in your telemetry (e.g. logs, traces) can be very helpful in figuring out what exactly is going on.
|
import React, { useState } from 'react';
import Link from '../Link/Link';
import { MenuIcon, XIcon } from '@heroicons/react/solid'
const Navbar = () => {
const [open, setOpen] = useState(false)
const routs = [
{ id: 1, name: 'home', link: '/ home' },
{ id: 2, name: 'shop', link: '/shop' },
{ id: 3, name: 'contact', link: '/contact' },
{ id: 4, name: 'about', link: '/about' },
]
return (
<nav className='bg-indigo-200'>
<div onClick={() => setOpen(!open)} className='w-6 h-6 md:hidden'>
{open ? <XIcon></XIcon> : <MenuIcon></MenuIcon>}
</div>
<ul className={`md:flex justify-center md:static bg-indigo-200 w-full absolute duration-500 ease-in ${open ? 'top-6' : 'top-[-170px]'} `} >
{
routs.map(rout => <Link key={rout.id} name={rout.name} link={rout.link} rout={rout}></Link>)
}
</ul>
</nav>
);
};
export default Navbar;
|
import "stream-chat-react/dist/css/index.css";
import React, { useEffect, useState } from "react";
import { StreamChat } from "stream-chat";
import {
Chat,
Channel,
ChannelList,
MessageInput,
MessageList,
Window
} from "stream-chat-react";
import MessagingChannelPreview from "./MessagingChannelPreview";
import MessagingChannelHeader from "./MessagingChannelHeader";
import MessagingChannelList from "./MessagingChannelList";
import CreateChannel from "./CreateChannel";
import './chat.scss'
const stream = require("getstream");
const secret = process.env.REACT_APP_SECRET_KEY;
const key = process.env.REACT_APP_KEY;
const chatClient = StreamChat.getInstance(key);
export default function Application() {
const [channel, setChannel] = useState(null);
const [isCreating, setIsCreating] = useState(false);
useEffect(() => {
const loadChat = async (id) => {
await chatClient.connectUser({
id: id,
name: id,
image: "../lucy-angel.png"
},
chatClient.devToken(id)
);
const channel = chatClient.channel("messaging", "convo6", {
name: "Let's go to LA"
})
await channel.create("convo6");
if (!channel.state.members[id]) await channel.addMembers([id]);
await channel.watch();
setChannel(channel);
}
loadChat("Lucy");
return () => chatClient.disconnectUser();
}, []);
// const initChat = async function (id) { //this function creates users, that's stored in the API
// // await chatClient.disconnectUser();
// await chatClient.connectUser(
// {
// id: id,
// name: id,
// image: "https://bit.ly/2u9Vc0r"
// },
// chatClient.devToken(id)
// );
// return chatClient;
// };
// //clients that have been created: Lucy, Ramon, Jackie, Violet, Carrie, Melissa, Kamil, Alexis, Aaron, Toby
// initChat("Aaron"); //right now this is who is online
// chatClient.disconnectUser("Lucy"); // this only works in a useeffect? must be await
//channelIds created: nothing, convoID, convo2, convo3, convo4, elephant-lovers
// const channel = chatClient.channel("messaging", "convo4", {
// name: "Yoga Retreat TEAM",
// members: [ "Ramon", "Jackie", "Violet", "Carrie", "Melissa", "Kamil", "Alexis"], //these members were all "created" when called> initChat("name")
// }
// );
// channel.create("convo4"); //call function that generates the convo, based on the 2nd param
// channel.addMembers(["Aaron"]) //clients must be created before they are added, run initChat FIRST with this commented out, then run it again with this line
// const channel = chatClient.channel("messaging", { //cannot "add members" to this type, this is one on one convo
// members: ["Ramon", "Melissa"],
// });
// channel.create()
const sort = { last_message_at: -1 };
return (
<div className="chatcontainer">
<Chat client={chatClient} theme="messaging light">
<ChannelList
sort={sort}
List={(props) => (
<MessagingChannelList {...props} onCreateChannel={() => setIsCreating(!isCreating)} />
)}
Preview={(props) => <MessagingChannelPreview {...props} {...{ setIsCreating }} />}
/>
<Channel>
{isCreating && (
<CreateChannel onClose={() => setIsCreating(false)} />
)}
<Window>
<MessagingChannelHeader />
<MessageList />
<MessageInput />
</Window>
</Channel>
</Chat>
</div>
);
}
|
import { IsString, Matches } from 'class-validator';
export class PasswordDto {
@IsString()
@Matches(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
{
message:
'Password need to be have minimum 8 characters, at least one uppercase letter, one lowercase letter, one number character and one special character',
},
)
password: string;
}
export default PasswordDto;
|
import "utils/env";
import { accountRouter } from "account/router";
import { authRouter } from "auth/router";
import cookieParser from "cookie-parser";
import cors from "cors";
import { courseRouter } from "course/router";
import { examRouter } from "exam/router";
import express, { Express } from "express";
import { rateLimit } from "express-rate-limit";
import { handleError } from "middlewares/handle-error";
import { reviewRouter } from "review/router";
import { rootRouter } from "root/router";
import { scoreRouter } from "score/router";
import { CORS_ORIGIN } from "utils/env";
export const app: Express = express();
app.use(cors({ origin: CORS_ORIGIN, credentials: true }));
app.use(
rateLimit({
windowMs: 60 * 1000,
max: 100,
message: { error: "请求过于频繁,请稍后再试" },
legacyHeaders: false,
standardHeaders: true,
})
);
app.use(cookieParser());
app.use(express.json());
app.use("/", rootRouter);
app.use("/accounts", accountRouter);
app.use("/auth", authRouter);
app.use("/courses", courseRouter);
app.use("/exams", examRouter);
app.use("/reviews", reviewRouter);
app.use("/scores", scoreRouter);
app.use(handleError);
|
import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {addUser} from '../../Actions/UserActions';
import classnames from 'classnames';
class Register extends Component {
constructor() {
super();
this.state = {
username: "",
password: "",
userType: "",
errors: {}
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({errors: nextProps.errors});
}
}
onChange(e) {
this.setState({[e.target.name]: e.target.value});
}
onSubmit(e) {
e.preventDefault();
const newUser = {
username: this.state.username,
password: this.state.password,
userType: this.state.userType
};
this.props.addUser(newUser, this.props.history);
}
render() {
const {errors} = this.state;
return(
<div className = "Register">
<Link className = "Back Button Link" to = "/">
<button className = "Back Button">Back</button>
</Link>
<h1 className = "Header Text">Register</h1>
<form className = "Form" onSubmit = {this.onSubmit}>
<div className = "Form Group">
<input className = {classnames("Username Input", {"is-invalid": errors.username})}
type = "Text" name = "username" placeholder = "Username" value = {this.state.username}
onChange = {this.onChange}/>
{
errors.username && (<div className = "Invalid Feedback">{errors.username}</div>)
}
</div>
<div className = "Form Group">
<input className = {classnames("Password Input", {"is-invalid": errors.password})}
type = "Password" name = "password" placeholder = "Password" value = {this.state.password}
onChange = {this.onChange}/>
{
errors.password && (<div className = "Invalid Feedback">{errors.password}</div>)
}
</div>
<div className = "Form Group">
<input className = "User Type Input" type = "Text" name = "userType" placeholder = "User Type"
value = {this.state.userType} onChange = {this.onChange}/>
</div>
<button className = "Submit Register" type = "Submit">Register</button>
</form><br/><hr/>
<p className = "Paragraph Text">Already have an account?</p>
<Link className = "Login Button Link" to = "/login">
<button className = "Login Button">Login</button>
</Link>
</div>
);
}
}
Register.propTypes = {
addUser: PropTypes.func.isRequired,
errors: PropTypes.object.isRequired
}
const mapStateToProps = state => ({
errors: state.errors
})
export default connect(mapStateToProps, {addUser})(Register);
|
## Approach
To traverse through a path we can do a rabbit/turtle pointers.
Essentially a pointer that travels twice as fast a slower pointer.
Since the fast pointer is twice faster, by the time the pointer reaches the end the slower pointer should be halfway across the path so return the slower pointer.
## Code
``` python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
```
## Runtime/Memory
Runtime: O(n) n being the length of the linked list
Memory: O(1) rabbit/turtle pointers are just O(1) each
|
"""
Template file for simple.py module.
"""
import sys
import curses
from store import *
class Strategy:
"""Implementation of the simple strategy."""
_time: int
_log: Logger
_store: Store
def __init__(self, width: int, log_path: str):
self._log = Logger(log_path, "SimpleStrategy", width)
self._store = Store(width)
self._time = 0
def cash(self) -> int:
"""Returns the store's cash at that moment"""
return self._store.cash()
def time(self) -> int:
"""Returns the time we are at that moment"""
return self._time
def update_time(self) -> None:
"""Updates the time once an action is done"""
self._time += 1
def det_position_first_container(self, c_size: int) -> Position:
"""Returns the position that has to go the container that arrives
to the store based on its size"""
assert c_size <= 4
if c_size == 1: return 0
elif c_size == 2: return 2
elif c_size == 3: return 6
else: return 12 #c_size == 4
def det_next_position(self, p: Position) -> Position:
"""Returns the next position in which the program has to
operate based on the position it is operating"""
if p == 0: return 1
elif p == 1: return 2
elif p == 2: return 4
elif p == 4: return 6
elif p == 6: return 9
elif p == 9: return 12
elif p == 12: return 16
else: return 0 #p == 16
def add_first_container(self, c: Container) -> None:
"""Adds the continer that arrives to the store the appropiate position
The action is added to the logger."""
p = self.det_position_first_container(c.size)
self._store.add(c, p)
self._log.add(self._time, c, p)
self.update_time()
def expired(self, c: Container) -> bool:
"""Returs if a container is expired at that moment"""
return self.time() >= c.delivery.end
def deliverable(self, c: Container) -> bool:
"""Returns if a container is deliverable at that moment"""
return c.delivery.start <= self.time() and self.time() < c.delivery.end
def remove_expired(self, c: Container) -> None:
"""
Removes the continer c from the store without adding it's cash to the store.
The actions are added to the logger.
Pre: c is expired
"""
self._store.remove(c)
self._log.remove(self.time(), c)
self._log.cash(self.time(), self.cash())
def remove_deliverable(self, c: Container) -> None:
"""
Removes de continer c from the store adding it's value to the store's cash.
The actions are added to the logger.
Pre: c is deliverable
"""
self._store.add_cash(c.value)
self._store.remove(c)
self._log.remove(self.time(), c)
self._log.cash(self.time(), self.cash())
def move_next_or_before(self, c: Container, p: Position, second: bool) -> None:
"""
Moves the contanier c to the second stack or the the first stack
of it's size depending on the bool "second".
The action is added to the logger.
Pre: c can be moved because is the top continer of the position of it's size
"""
if second:
self._store.move(c, p + c.size)
self._log.move(self.time(), c, p + c.size)
else:
self._store.move(c, p - c.size)
self._log.move(self.time(), c, p - c.size)
def move_container_pila(self, c: Container, p: Position, second: bool) -> None:
"""
If the container is explired or can be delivered it is removed from the
container properly. If not it is moved to the second stack or the first
stack of it's size depending on the bool "second".
Pre: c can be removed because is the top continer of the position of it's size
"""
if self.expired(c):
self.remove_expired(c)
elif self.deliverable(c):
self.remove_deliverable(c)
else: #the top container of the position cannot be delivered neither is expired
self.move_next_or_before(c, p, second)
self.update_time()
def exec(self, c: Container):
"""Apliquem l'excecució simple"""
assert self._store.width() >= 20
#we make sure that the with of the store is 20 (if is smaller we cannot apply the simple strategy)
self.add_first_container(c)
p = 0 #we start the algorithm in the first position
#after we do an action we have to stop the algorithm if the next container arrives
while self._time < c.arrival.end:
if self._store.empty(): #if the store is empty we don't have to do anything until the next container arrives
self._time = c.arrival.end
else: #until the position is empty we get all the containers from top to the bottom and follow the simple algorithm
top_c = self._store.top_container(p)
while top_c is not None and self._time < c.arrival.end: #we move all the containers from the first stack of the containers' size to the second
self.move_container_pila(top_c, p, True) #we write the bool True because we want to move the container second stack of it's size
top_c = self._store.top_container(p)
p = self.det_next_position(p) #determines the next position we have to operate based in the position we are
top_c = self._store.top_container(p)
while top_c is not None and self._time < c.arrival.end: #we move all the containers from the second stack of the containers' size to the first
self.move_container_pila(top_c, p, False) #we write the bool False because we want to move the container first stack of it's size
top_c = self._store.top_container(p)
p = self.det_next_position(p) #determines the next position we have to operate based in the position we are
def init_curses():
"""Initializes the curses library to get fancy colors and whatnots."""
curses.curs_set(0)
curses.start_color()
curses.use_default_colors()
for i in range(0, curses.COLORS):
curses.init_pair(i + 1, curses.COLOR_WHITE, i)
def execute_strategy(containers_path: str, log_path: str, width: int):
"""Execute the strategy on an empty store of a certain width reading containers from containers_path and logging to log_path."""
containers = read_containers(containers_path)
strategy = Strategy(width, log_path)
for container in containers:
strategy.exec(container)
def main(stdscr: curses.window):
"""main script"""
init_curses()
containers_path = sys.argv[1]
log_path = sys.argv[2]
width = int(sys.argv[3])
execute_strategy(containers_path, log_path, width)
check_and_show(containers_path, log_path, stdscr)
# start main script when program executed
if __name__ == '__main__':
curses.wrapper(main)
|
---
title: Creating a tiering policy
excerpt: How to create a tiering policy
product: [ cloud ]
keywords: [ tiered storage, tiering ]
tags: [ storage, data management ]
---
# Creating a tiering policy
To automate the archival of data not actively accessed, create a tiering policy that
automatically moves data to the object storage tier. Any chunks that only contain data
older than the `move_after` threshold are moved. This works similarly to a
[data retention policy](https://docs.timescale.com/use-timescale/latest/data-retention/), but chunks are moved rather than deleted.
The tiering policy schedules a job that runs periodically to migrate
eligible chunks. The migration is asynchronous.
The chunks are tiered once they appear in the timescaledb_osm.tiered_chunks view.
Tiering does not influence your ability to query the chunks.
To add a tiering policy, use the `add_tiering_policy` function:
```sql
SELECT add_tiering_policy(hypertable REGCLASS, move_after INTERVAL);
```
In this example, you use a hypertable called example, and tier chunks older than three days.
<Procedure>
### Adding a tiering policy
1. At the psql prompt, select the hypertable and duration:
```sql
SELECT add_tiering_policy('example', INTERVAL '3 days');
```
</Procedure>
To remove an existing tiering policy, use the `remove_tiering_policy` function:
```sql
SELECT remove_tiering_policy(hypertable REGCLASS, if_exists BOOL = false);
```
<Procedure>
### Removing a tiering policy
1. At the psql prompt, select the hypertable to remove the policy from:
```sql
SELECT remove_tiering_policy('example');
```
</Procedure>
If you remove a tiering policy, the removal automatically prevents scheduled chunks from being tiered in the future.
Any chunks that were already tiered won't be untiered automatically. You can use the [untier_chunk][untier-data] procedure
to untier chunks to local storage that have already been tiered.
## List tiered chunks
<Highlight type="info">
Tiering a chunk schedules the chunk for migration to the object storage tier but, won't be tiered immediately.
It may take some time tiering to complete. You can continue to query a chunk during migration.
</Highlight>
To see which chunks are tiered into the object storage tier, use the `tiered_chunks`
informational view:
```sql
SELECT * FROM timescaledb_osm.tiered_chunks;
```
If you need to untier your data, see the
[manually untier data][untier-data] section.
[untier-data]: /use-timescale/:currentVersion:/data-tiering/untier-data/
|
/**
* @file Debug.h
* @author rohit S
* @brief header File for Debug Class implementation, Singleton design implementation
* @version 0.1
* @date 2023-12-11
*
* @copyright Copyright (c) 2023 Volansys Technologies
*
*/
#ifndef DEBUG_H_
#define DEBUG_H_
#include "Movie.h"
#include "Movies.h"
/**
* @brief Debug class to print statements in colored format on terminal
* @class Debug
*
*/
class Debug
{
private:
/**
* @brief Construct a new Debug object
*
*/
Debug();
// Private copy constructor to prevent copying
Debug(const Debug &);
// Private assignment operator to prevent assignment
Debug &operator=(const Debug &);
public:
/**
* @brief Static method to get the instance of the singleton class
*
* @return Debug&
*/
static Debug& getInstance()
{
// Static instance of the singleton class
static Debug instance;
return instance;
}
/**
* @brief Display a template in red color on terminal
*
* @tparam T
* @param str
*/
template <typename T>
void display_red(T str);
/**
* @brief Display a template in Green color on terminal
*
* @tparam T
* @param str
*/
template <typename T>
void display_green(T str);
/**
* @brief Display a template in yellow color on terminal
*
* @tparam T
* @param str
*/
template <typename T>
void display_yellow(T str);
/**
* @brief Display a template in blue color on terminal
*
* @tparam T
* @param str
*/
template <typename T>
void display_blue(T str);
/**
* @brief Display the decorator to make output more organized
*
*/
void display_decorator();
/**
* @brief Destroy the Debug object
*
*/
~Debug();
};
#endif
|
import { acceptHMRUpdate, defineStore } from 'pinia';
import ls from '@/utils/local-storage';
import { STORAGE_TOKEN_KEY } from './app';
import type { LoginParams, Role, UserInfo } from '@/api/user/login';
import { postLogout, getCurrentUser, postAccountLogin } from '@/api/user/login';
import type { RouteRecordRaw } from 'vue-router';
import { filterChildRoute, hasAuthority } from '@/utils/authority';
import { filterMenu } from '@/utils/menu-util';
import { default as router, routes } from '@/router';
import type { MenuDataItem } from '@/router/typing';
import { generatorDynamicRouter } from '@/router/generator-routers';
export interface UserState {
token?: string;
username: string;
nickname: string;
avatar: string;
role?: Role;
allowRouters: RouteRecordRaw[];
extra: {
[key: string]: any;
};
[key: string]: any;
}
export const LOGIN = 'LOGIN';
export const LOGOUT = 'LOGOUT';
export const GET_INFO = 'GET_INFO';
export const GENERATE_ROUTES = 'GENERATE_ROUTES';
export const GENERATE_ROUTES_DYNAMIC = 'GENERATE_ROUTES_DYNAMIC';
export const SET_TOKEN = 'SET_TOKEN';
export const SET_AVATAR = 'SET_AVATAR';
export const SET_ROLE = 'SET_ROLE';
export const SET_INFO = 'SET_INFO';
export const SET_ROUTERS = 'SET_ROUTERS';
export const RESET_CURRENT_USER = 'RESET_CURRENT_USER';
export const initState = (): UserState => ({
token: '',
username: '',
nickname: '',
avatar: '',
extra: {},
role: undefined,
allowRouters: [],
});
export const useUserStore = defineStore('user', {
state: initState,
getters: {
info: state => state.extra,
currentUser: state => state,
},
actions: {
[SET_TOKEN](token: string) {
this.token = token;
ls.set(STORAGE_TOKEN_KEY, token);
},
[SET_INFO](info: Partial<UserInfo> & { userid?: string }) {
if (info.role) {
this.role = info.role;
}
if (info.userid) {
this.username = info.userid;
this.nickname = info.userid;
}
if (info.name) {
this.nickname = info.name;
}
if (info.avatar) {
this.avatar = info.avatar;
}
this.extra = { ...info };
},
[SET_ROLE](role: UserState['role']) {
this.role = role;
},
[SET_AVATAR](avatar: UserState['avatar']) {
this.avatar = avatar;
},
[SET_ROUTERS](allowRoutes: UserState['allowRouters']) {
this.allowRouters = allowRoutes;
},
[RESET_CURRENT_USER]() {
this.$reset();
},
async [LOGIN](info: LoginParams) {
return new Promise((resolve, reject) => {
debugger;
// call ajax
postAccountLogin(info)
.then(res => {
this.SET_TOKEN(res.token);
resolve(res);
})
.catch(error => {
reject(error);
});
});
},
async [GET_INFO](): Promise<UserInfo> {
return new Promise((resolve, reject) => {
getCurrentUser()
.then((res: UserInfo) => {
this.SET_INFO(res);
resolve(res);
})
.catch(err => {
// 获取登录用户信息后,直接清理掉当前 token 并强制让流程走到登录页
this.SET_TOKEN(null);
reject(err);
});
});
},
// 从路由表构建路由(前端对比后端权限字段过滤静态路由表)
async [GENERATE_ROUTES](info: UserInfo) {
return new Promise<RouteRecordRaw[]>(resolve => {
// 修改这里可以进行接口返回的对象结构进行改变
// 亦或是去掉 info.role 使用别的属性替代
// 任何方案都可以,只需要将最后拼接构建好的路由数组使用
// router.addRoute() 添加到当前运行时的路由中即可
const { permissions } = (info.role || {}) as Role;
const allRoutes = filterMenu(routes);
const permissionsKey = permissions?.map(permission => permission.name);
const allowRoutes = !permissionsKey
? allRoutes
: allRoutes.filter(route => {
// parnent route filter
const hasAllow = hasAuthority(route as MenuDataItem, permissionsKey!);
if (hasAllow && route.children && route.children.length > 0) {
// current route children filter
route.children = filterChildRoute(route as MenuDataItem, permissionsKey!);
}
return hasAllow;
});
console.log('allowRoutes', allowRoutes);
// 添加到路由表
const {
// eslint-disable-next-line
children: _,
...mainRoute
} = routes[0];
const route = {
...mainRoute,
children: allowRoutes,
};
router.addRoute(route as RouteRecordRaw);
this.SET_ROUTERS(allowRoutes as RouteRecordRaw[]);
resolve(allowRoutes as RouteRecordRaw[]);
});
},
// 从后端获取路由表结构体,并构建前端路由
async [GENERATE_ROUTES_DYNAMIC]() {
return new Promise(resolve => {
generatorDynamicRouter()
.then(routes => {
const allowRoutes = routes.children || [];
// 添加到路由表
router.addRoute(routes as RouteRecordRaw);
this.SET_ROUTERS(allowRoutes);
resolve(routes);
})
.catch(err => {
console.error('generatorDynamicRouter', err);
});
});
},
async [LOGOUT]() {
return new Promise<void>(resolve => {
postLogout().finally(() => {
this.SET_TOKEN(null);
this.RESET_CURRENT_USER();
resolve();
});
});
},
},
});
const hot = import.meta.webpackHot || (import.meta as any).hot;
if (hot) {
hot.accept(acceptHMRUpdate(useUserStore, hot));
}
|
import 'dart:async';
import 'dart:io';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lane_dane/app_controller.dart';
import 'package:lane_dane/controllers/all_transaction_controller.dart';
import 'package:lane_dane/controllers/sms_controller.dart';
import 'package:lane_dane/errors/request_error.dart';
import 'package:lane_dane/errors/unauthorized_error.dart';
import 'package:lane_dane/helpers/android_alarm_manager_helper.dart';
import 'package:lane_dane/helpers/auth.dart';
import 'package:lane_dane/helpers/telephony_background_sms_helper.dart';
import 'package:lane_dane/models/all_transaction.dart';
import 'package:lane_dane/models/transactions.dart';
import 'package:lane_dane/objectbox.g.dart';
import 'package:lane_dane/views/pages/authentication/enter_phone_screen.dart';
import 'package:lane_dane/views/pages/sms_permission_view.dart';
import 'package:lane_dane/views/pages/transaction/transaction_details.dart';
import 'package:lane_dane/views/shared/snack-bar.dart';
import 'package:lane_dane/views/widgets/all_transaction_list_builder.dart';
import 'package:logger/logger.dart';
import 'package:lane_dane/utils/log_printer.dart';
class AllTransaction extends StatefulWidget {
static const String routeName = 'all-transaction-screen';
const AllTransaction({Key? key}) : super(key: key);
@override
State<AllTransaction> createState() => _AllTransactionState();
}
class _AllTransactionState extends State<AllTransaction> {
late final Logger log;
late final AppController appController = Get.find();
late List<AllTransactionObjectBox> allTransactionList;
late StreamSubscription stream;
@override
void initState() {
super.initState();
FirebaseAnalytics.instance.setCurrentScreen(
screenName: AllTransaction.routeName,
);
log = getLogger('AllTransaction');
allTransactionList =
appController.allTransactionController.retrieveAllSmsTransactions();
stream = appController.allTransactionController
.streamAllSmsTransactions()
.listen(updateAllTransactionList);
transactionListFetchProcess();
appController.resendFailedTransactions();
appController.resendFailedGroupTransactions();
}
@override
void dispose() {
stream.cancel();
super.dispose();
}
void updateAllTransactionList(Query<AllTransactionObjectBox> query) {
if (mounted) {
allTransactionList = query.find();
setState(() {});
}
}
Future<void> refresh() async {
await appController.retrieveTransactionsFromServer();
appController.resendFailedTransactions();
}
Future<void> transactionListFetchProcess() async {
if (!appController.permissions.contactReadPermission) {
await appController.permissions.requestContactsReadPermission();
}
if (!appController.permissions.contactReadPermission) {
return;
}
if (!appController.permissions.smsReadPermission) {
await appController.permissions
.requestSmsReadPermission()
.then((bool granted) {
if (granted) {
setupTelephony();
AndroidAlarmManagerHelper().setupDailySmsAlarm();
}
});
}
if (mounted) {
setState(() {});
}
try {
log.d('Fetching contacts');
appController.parseAndStoreTransactionSms();
log.d('Done Safely');
} on SocketException catch (err) {
showSnackBar(context, err.message);
log.e('Failed to make a socket connection: ${err.toString()}');
log.e('Host address: ${err.address}');
} on RequestError catch (err) {
showSnackBar(context, err.message);
log.e('Failed to fetch contacts: ${err.toString()}');
log.e('Response body: ${err.responseBody}');
} on UnauthorizedError catch (err) {
showSnackBar(context, err.message);
Auth().logout();
Navigator.of(context).pushReplacementNamed(EnterPhoneScreen.routeName);
} catch (err) {
if (kDebugMode) {
showSnackBar(context, 'Unknown error occurred');
}
FirebaseCrashlytics.instance.log(
'''An unknown error occurred while fetching launch data: ${err.toString()}
Launch data includes, fetching contacts, SMS parsing, fetching remote transactions
''');
log.e('An error occurred: ${err.toString()}');
}
}
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: refresh,
child: Builder(
builder: (BuildContext context) {
if (allTransactionList.isNotEmpty &&
appController.permissions.smsReadPermission) {
return AllTransactionLoader(
alltransactionList: allTransactionList,
);
} else if (SmsController.smsParsed) {
return Center(
child: Text('all_transaction_empty_message'.tr,
style: const TextStyle(fontSize: 18, color: Colors.grey)),
);
} else if (appController.permissions.smsReadPermission) {
return const SmsLoadingView();
} else {
return SmsPermissionView(
onPressed: transactionListFetchProcess,
);
}
},
),
);
}
}
class AllTransactionLoader extends StatelessWidget {
final List<AllTransactionObjectBox> alltransactionList;
AllTransactionLoader({
Key? key,
required this.alltransactionList,
}) : super(key: key);
final Logger log = getLogger('AllTransactionLoader');
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final double topPadding =
Get.statusBarHeight + kToolbarHeight + kToolbarHeight;
return Container(
height: size.height,
alignment: Alignment.topCenter,
child: ListView.builder(
shrinkWrap: true,
itemCount: alltransactionList.length,
itemBuilder: (context, index) {
AllTransactionObjectBox alltransaction = alltransactionList[index];
bool isSms = alltransaction.transactionId.targetId == 0;
TransactionsModel? transaction = alltransaction.transactionId.target;
return AllTransactionListTile(
alltransaction: alltransaction,
isSms: isSms,
navigationCallback: () {
Navigator.of(context).pushNamed(
TransactionDetails.routeName,
arguments: {
'transaction': alltransaction.transactionId.target,
'alltransaction': alltransaction,
'contact': transaction?.user.target,
},
);
},
);
},
),
);
}
}
|
import * as fs from 'fs';
import * as path from 'path';
import OSS from 'ali-oss';
import ExifReader from 'exifreader';
import * as dotenv from 'dotenv';
import { v4 as uuidv4 } from 'uuid';
dotenv.config();
// 阿里云 OSS 相关配置
const ossClient = new OSS({
accessKeyId: process.env.OSS_ACCESS_KEY_ID || '',
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || '',
bucket: process.env.OSS_BUCKET,
region: process.env.OSS_REGION,
});
// 指定目录路径和文件后缀名
const dirPath = '/Users/tzwm/Downloads/tmp/梗图修改_v2.zip/cai/';
const fileExt = /\.(png|jpg|jpeg)$/i;
const ossBasePath = process.env.OSS_BASE_PATH;
const originalOSSUrl = process.env.OSS_ORIGINAL_OSS_URL || '';
const ossBaseUrl = process.env.OSS_BASE_URL || '';
let data: {[key: string]: any} = {};
async function uploadFileToOSS(filename: string): Promise<string> {
const filePath = path.join(dirPath, filename);
let ret: OSS.PutObjectResult;
try {
ret = await ossClient.put(ossBasePath + filename, fs.createReadStream(filePath));
console.log(`${filename} uploaded to OSS successfully.`);
} catch (err) {
console.error(err);
return '';
}
return ret.url.replace(originalOSSUrl, ossBaseUrl);
}
async function readITXtChunk(filename: string): Promise<string> {
const fileDir = path.join(dirPath, filename);
//const buffer = fs.readFileSync(fileDir);
const tags = await ExifReader.load(fileDir);
if (tags['parameters']) {
return tags['parameters'].description;
} else {
return '';
}
}
function getParameters(key: string): string {
const dd = data[key];
let ret = dd['output'];
for (const i in dd['controlnet']) {
ret += `,\nControlNet-${i} Image: ${dd['controlnet'][i]}`;
}
return ret;
}
function paramsToJSON(key: string) {
const params = data[key]['output'].split("\n")
.filter((s: string) => s.trim() != "");
const json = {
'prompt': params[0],
'negative': params[1].split(':')[1].trim(),
}
const regex = /(\w+\s?[\d\w]+): (("[^"]*")|\S+)/g;
const args: { [key: string]: string } = {};
let match: RegExpExecArray | null;
while ((match = regex.exec(params[2])) !== null) {
const key = match[1];
const value = match[2].trim().replace(/"/g, '').replace(/,$/, '');
args[key] = value;
}
for (const i in [0, 1, 2, 3, 4]) {
const preStr = `ControlNet ${i}`;
if (!args[preStr]) {
continue;
}
args[preStr] = args[preStr];
//.replace('starting/ending', 'starting_ending');
const regex = /(\w+[ \/]?\w+): ((?:\([^)]*\)|\[[^\]]*\]|[^,])+)(?:, )?/g;
const cn: any = {};
let match;
while ((match = regex.exec(args[preStr]))) {
const key = match[1];
const value = match[2];
cn[key] = value;
}
if (cn['starting/ending']) {
const regex = /\d+\.?\d*/g;
const matches = cn['starting/ending'].match(regex);
if (matches) {
const numbers = matches.map(parseFloat);
cn['starting'] = numbers[0];
cn['ending'] = numbers[1];
}
}
args[preStr] = cn;
}
return { ...json, ...args };
}
function jsonToTargetPrompts(key: string): object {
return {
'prompt': data[key]['json']['prompt'],
'negative': data[key]['json']['negative'],
};
}
function jsonToTargetParams(key: string): object {
const d = data[key]['json'];
const [width, height] = d['Size'].split('x');
let controlnetUnits = [];
for (const i in [0, 1, 2, 3, 4]) {
const preStr = `ControlNet ${i}`;
if (!data[key]['output'].match(preStr)) {
continue;
}
let cn = d[preStr];
let inputImage = data[key]['controlnet'][i.toString()] || data[key]['original'];
let module = 'none'; // cn['preprocessor'];
//if (module == 'tile_resample' || module == '') {
//module = 'none';
//if (!inputImage) {
//inputImage = data[key]['original'];
//}
//}
controlnetUnits.push({
"mask": "",
"module": module,
"lowvram": false,
//"guessmode": false,
"resize_mode": cn['resize mode'],
"guidance_start": +cn['starting'],
"guidance_end": +cn['ending'],
"model": cn['model'],
"weight": +cn['weight'],
"control_mode": cn['control mode'],
"pixel_perfect": cn['pixel perfect'] == "True" ? true : false,
"input_image": inputImage,
});
}
let sampler = d['Sampler'];
if (sampler == 'DPM++') {
sampler = 'DPM++ SDE Karras';
}
let baseModel = d['Model'];
if (baseModel == 'AnythingV5V3_v5PrtRE') {
baseModel = 'AnythingV5_v5PrtRE';
}
let ret: {[key: string]: any} = {
"extra_jobs": "",
"task_name": "make_image_with_webui",
"steps": +d['Steps'] > 20 ? 20 : +d['Steps'],
"sampler_index": sampler,
"cfg_scale": +d['CFG scale'],
"width": +width,
"height": +height,
"base_model_name": baseModel,
"controlnet_units": controlnetUnits,
};
if (d['Hires upscale']) {
ret['enable_hr'] = true;
ret['hr_upscaler'] = d['Hires upscaler'];
ret['hr_scale'] = +d['Hires upscale'];
ret['denoising_strength'] = +d['Denoising strength'];
ret['hr_second_pass_steps'] = +d['Hires steps'];
}
return ret;
}
function validParameters(key: string): Array<string> {
const dd = data[key];
let errors = [];
// check controlnet
for (const i in dd['controlnet']) {
let str = `ControlNet-${i}`;
if (dd['output'].indexOf(str) < 0) {
errors.push(`not found ControlNet-${i} in the parameters`);
}
}
// check width and height
const MAX_SIZE = 512;
if (dd['targetParams']['width'] > MAX_SIZE && dd['targetParams']['height'] > MAX_SIZE) {
errors.push(`the width and height are larger than ${MAX_SIZE}`);
}
return errors;
}
async function writeParameters(key: string) {
const dd = data[key];
const output = [
'errors: ' + dd['errors'].join("\n"),
dd['original'],
getParameters(key),
JSON.stringify(dd['targetPrompts'], null, 2),
JSON.stringify(dd['targetParams'], null, 2),
JSON.stringify(dd['styleConfig'], null, 2),
].join("\n\n");
fs.writeFile(`${dirPath}/${key}.txt`, output, (error) => {
if (error) throw error;
//console.log(`${key}.txt written successfully!`);
});
}
function getStyleConfig(key: string) {
return {
uuid: uuidv4(),
name: '这一刻,想说点什么..',
value: '梗:key',
cover: data[key]['original'],
width: data[key]['targetParams']['width'],
height: data[key]['targetParams']['height'],
type: 'style',
}
}
async function main() {
const files = await fs.promises.readdir(dirPath);
for (let i = 0; i < files.length; i++) {
if (!fileExt.test(files[i])) {
continue;
}
const parts = files[i].split(/[\._]/);
const key = [parts[0], parts[1]].join('_');
const type = parts[2];
if (!data[key]) {
data[key] = {};
}
switch(type) {
case 'original':
data[key][type] = await uploadFileToOSS(files[i]);
break;
case 'output':
data[key][type] = await readITXtChunk(files[i]);
break;
case 'controlnet':
if (!data[key][type]) {
data[key][type] = {};
}
data[key][type][parts[3]] = await uploadFileToOSS(files[i]);
break;
default:
delete data[key];
console.log(`wrong filename: ${files[i]}`);
continue;
}
if (!data[key]['controlnet']) {
data[key]['controlnet'] = {};
}
}
for (const key in data) {
data[key]['json'] = paramsToJSON(key);
data[key]['targetParams'] = jsonToTargetParams(key);
data[key]['targetPrompts'] = jsonToTargetPrompts(key);
data[key]['styleConfig'] = getStyleConfig(key);
data[key]['errors'] = validParameters(key);
if (data[key]['errors'].length > 0) {
console.log('error:', key, data[key]['errors']);
}
writeParameters(key);
}
}
main();
|
import { useState, useRef } from "react";
import { Link } from "react-router-dom";
import emailjs from "@emailjs/browser";
import toast from "react-hot-toast";
// import config from "../../config";
const Contact = () => {
const [formData, setFormData] = useState({
name: "",
lastName: "",
email: "",
message: "",
});
const form = useRef();
const { name, lastName, email, message } = formData;
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
emailjs
.sendForm(
import.meta.env.VITE_SERVICE,
import.meta.env.VITE_TEMPLATE,
form.current,
import.meta.env.VITE_PUBLIC_KEY
)
.then(
(result) => {
console.log(result.text);
toast.success("Email enviado correctamente");
},
(error) => {
console.log(error.text);
toast.success("Error al enviar el email. Inténtalo de nuevo");
}
);
setFormData({
name: "",
lastName: "",
email: "",
message: "",
});
};
return (
<div className="flex flex-col h-screen max-w-md md:max-w-2xl mx-auto p-6 py-18">
<Link to="/">
<i className="fa-solid fa-arrow-left fa-lg text-gray-800 my-10"></i>
</Link>
<h1 className="text-2xl mb-6 text-start text-gray-800 font-semibold">
Contacta conmigo
</h1>
<form ref={form} onSubmit={handleSubmit}>
<div className="mb-4 flex space-x-4">
<div className="w-1/2">
<label
className="block text-gray-700 text-sm font-semibold mb-2 pt-4"
htmlFor="name"
>
Nombre*
</label>
<input
className="w-full px-3 py-2 text-gray-700 border rounded-md focus:outline-none"
type="text"
name="name"
placeholder="Tu nombre"
value={name}
onChange={handleChange}
required
/>
</div>
<div className="w-1/2">
<label
className="block text-gray-700 text-sm font-semibold mb-2 pt-4"
htmlFor="lastName"
>
Apellido*
</label>
<input
className="w-full px-3 py-2 text-gray-700 border rounded-md focus:outline-none"
type="text"
name="lastName"
placeholder="Tu apellido"
value={lastName}
onChange={handleChange}
required
/>
</div>
</div>
<div className="mb-4">
<label
className="block text-gray-700 text-sm font-semibold mb-2 pt-4"
htmlFor="email"
>
Email*
</label>
<input
className="w-full px-3 py-2 text-gray-700 border rounded-md focus:outline-none"
type="email"
name="email"
placeholder="[email protected]"
value={email}
onChange={handleChange}
required
/>
</div>
<div className="mb-4">
<label
className="block text-gray-700 text-sm font-semibold mb-2 pt-4"
htmlFor="message"
>
Mensaje*
</label>
<textarea
className="w-full h-24 px-3 py-2 text-gray-700 border rounded-md focus:outline-none"
name="message"
placeholder="Escribe tu mensaje para Sandra"
value={message}
onChange={handleChange}
required
></textarea>
</div>
<div className="flex justify-start">
<button
type="submit"
className="px-4 py-2 bg-blue-400 text-white rounded-[50px] hover:bg-blue-500 focus:outline-none shadow-lg"
>
Enviar
</button>
</div>
</form>
</div>
);
};
export default Contact;
|
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package proto
import (
"time"
)
// task state machine
//
// Note: if a task fails during running, it will end with `reverted` state.
// The `failed` state is used to mean the framework cannot run the task, such as
// invalid task type, scheduler init error(fatal), etc.
//
// ┌────────┐
// ┌───────────│resuming│◄────────┐
// │ └────────┘ │
// ┌──────┐ │ ┌───────┐ ┌──┴───┐
// │failed│ │ ┌────────►│pausing├──────►│paused│
// └──────┘ │ │ └───────┘ └──────┘
// ▲ ▼ │
// ┌──┴────┐ ┌───┴───┐ ┌────────┐
// │pending├────►│running├────►│succeed │
// └──┬────┘ └──┬┬───┘ └────────┘
// │ ││ ┌─────────┐ ┌────────┐
// │ │└────────►│reverting├────►│reverted│
// │ ▼ └─────────┘ └────────┘
// │ ┌──────────┐ ▲
// └─────────►│cancelling├────┘
// └──────────┘
const (
TaskStatePending TaskState = "pending"
TaskStateRunning TaskState = "running"
TaskStateSucceed TaskState = "succeed"
TaskStateFailed TaskState = "failed"
TaskStateReverting TaskState = "reverting"
TaskStateReverted TaskState = "reverted"
TaskStateCancelling TaskState = "cancelling"
TaskStatePausing TaskState = "pausing"
TaskStatePaused TaskState = "paused"
TaskStateResuming TaskState = "resuming"
)
type (
// TaskState is the state of task.
TaskState string
// TaskType is the type of task.
TaskType string
)
func (t TaskType) String() string {
return string(t)
}
func (s TaskState) String() string {
return string(s)
}
const (
// TaskIDLabelName is the label name of task id.
TaskIDLabelName = "task_id"
// NormalPriority represents the normal priority of task.
NormalPriority = 512
)
// MaxConcurrentTask is the max concurrency of task.
// TODO: remove this limit later.
var MaxConcurrentTask = 4
// Task represents the task of distributed framework.
// tasks are run in the order of: priority asc, create_time asc, id asc.
type Task struct {
ID int64
Key string
Type TaskType
State TaskState
Step Step
// Priority is the priority of task, the smaller value means the higher priority.
// valid range is [1, 1024], default is NormalPriority.
Priority int
// Concurrency controls the max resource usage of the task, i.e. the max number
// of slots the task can use on each node.
Concurrency int
CreateTime time.Time
// depends on query, below fields might not be filled.
// SchedulerID is not used now.
SchedulerID string
StartTime time.Time
StateUpdateTime time.Time
Meta []byte
Error error
}
// IsDone checks if the task is done.
func (t *Task) IsDone() bool {
return t.State == TaskStateSucceed || t.State == TaskStateReverted ||
t.State == TaskStateFailed
}
var (
// EmptyMeta is the empty meta of task/subtask.
EmptyMeta = []byte("{}")
)
// Compare compares two tasks by task order.
// returns < 0 represents priority of t is higher than other.
func (t *Task) Compare(other *Task) int {
if t.Priority != other.Priority {
return t.Priority - other.Priority
}
if t.CreateTime != other.CreateTime {
if t.CreateTime.Before(other.CreateTime) {
return -1
}
return 1
}
return int(t.ID - other.ID)
}
|
# Information Retrieval Projects
This repository contains a collection of projects related to Information Retrieval (IR), implemented using Python. Each project focuses on different aspects of IR, ranging from building basic search systems to incorporating advanced techniques like spelling correction, document ranking, and machine learning for text classification.
Furthermore, you can explore other related Information Retrieval projects I've worked on, specifically focusing on BERT transformer models, at: [Bert-Information-Retrieval](https://github.com/proshir/Bert-Information-Retrieval).
## Project List:
1. **Basic IR System with Boolean and Proximity Queries**: Implements an IR system supporting Boolean and proximity queries, with preprocessing, indexing, and query processing functionalities.
2. **Spelling Correction and Wildcard Queries**: Enhances the IR system by adding spelling correction and wildcard query support, leveraging techniques like Levenshtein distance and Permuterm indexing.
3. **BSBI Algorithm for Inverted Indexing**: Implements the Block-Sorted Based Indexing algorithm for building inverted indexes, with a focus on efficient storage using gamma coding.
4. **Document Ranking Strategies**: Implements three different document ranking approaches (vector space model, binary independence model, and language model) and compares their performance using evaluation metrics.
5. **Text Classification with Naive Bayes, Word Embeddings, LSA, and SVM**: Utilizes machine learning techniques for text classification within the domain of IR, including Naive Bayes, word embeddings, Latent Semantic Analysis (LSA), and Support Vector Machine (SVM) classifiers.
Each project includes comprehensive documentation, code implementations, and reports summarizing key findings, challenges faced, and enhancements made during development.
Feel free to explore each project for detailed insights into different aspects of Information Retrieval!
|
package top
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/nicklaw5/helix/v2"
"github.com/samber/lo"
"github.com/satont/twir/apps/parser/internal/types"
model "github.com/satont/twir/libs/gomodels"
"github.com/satont/twir/libs/twitch"
)
var EmotesUsers = &types.Variable{
Name: "top.emotes.users",
Description: lo.ToPtr("Top users by emotes. Prints counts of used emotes"),
Example: lo.ToPtr("top.emotes.users|10"),
Handler: func(
ctx context.Context, parseCtx *types.VariableParseContext, variableData *types.VariableData,
) (*types.VariableHandlerResult, error) {
result := &types.VariableHandlerResult{}
twitchClient, err := twitch.NewAppClientWithContext(
ctx,
*parseCtx.Services.Config,
parseCtx.Services.GrpcClients.Tokens,
)
if err != nil {
parseCtx.Services.Logger.Sugar().Error(err)
return nil, err
}
limit := 10
if variableData.Params != nil {
newLimit, err := strconv.Atoi(*variableData.Params)
if err == nil {
limit = newLimit
}
}
if limit > 50 {
limit = 10
}
var usages []*model.ChannelEmoteUsageWithCount
err = parseCtx.Services.Gorm.
Model(&model.ChannelEmoteUsageWithCount{}).
Select(`"userId", COUNT(*) as count`).
Where(`"channelId" = ?`, parseCtx.Channel.ID).
Group(`"userId"`).
Order("count DESC").
Limit(10).
Scan(&usages).
WithContext(ctx).
Error
if err != nil {
return nil, err
}
twitchUsers, err := twitchClient.GetUsers(
&helix.UsersParams{
IDs: lo.Map(
usages, func(item *model.ChannelEmoteUsageWithCount, _ int) string {
return item.UserID
},
),
},
)
if err != nil {
parseCtx.Services.Logger.Sugar().Error(err)
return nil, err
}
mappedTop := []string{}
for _, usage := range usages {
user, ok := lo.Find(
twitchUsers.Data.Users, func(item helix.User) bool {
return item.ID == usage.UserID
},
)
if !ok {
continue
}
mappedTop = append(
mappedTop, fmt.Sprintf(
"%s × %v",
user.Login,
usage.Count,
),
)
}
result.Result = strings.Join(mappedTop, " · ")
return result, nil
},
}
|
import { fork } from "node:child_process";
import { realpathSync } from "node:fs";
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { useState, useEffect, useRef } from "react";
import onExit from "signal-exit";
import { registerWorker } from "../dev-registry";
import useInspector from "../inspect";
import { logger } from "../logger";
import { DEFAULT_MODULE_RULES } from "../module-collection";
import { waitForPortToBeAvailable } from "../proxy";
import type { Config } from "../config";
import type { WorkerRegistry } from "../dev-registry";
import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli";
import type { AssetPaths } from "../sites";
import type { CfWorkerInit, CfScriptFormat } from "../worker";
import type { EsbuildBundle } from "./use-esbuild";
import type { MiniflareOptions } from "miniflare";
import type { ChildProcess } from "node:child_process";
interface LocalProps {
name: string | undefined;
bundle: EsbuildBundle | undefined;
format: CfScriptFormat | undefined;
compatibilityDate: string;
compatibilityFlags: string[] | undefined;
usageModel: "bundled" | "unbound" | undefined;
bindings: CfWorkerInit["bindings"];
workerDefinitions: WorkerRegistry;
assetPaths: AssetPaths | undefined;
port: number;
ip: string;
rules: Config["rules"];
inspectorPort: number;
enableLocalPersistence: boolean;
liveReload: boolean;
crons: Config["triggers"]["crons"];
localProtocol: "http" | "https";
localUpstream: string | undefined;
inspect: boolean;
onReady: (() => void) | undefined;
logLevel: "none" | "error" | "log" | "warn" | "debug" | undefined;
logPrefix?: string;
enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
}
export function Local(props: LocalProps) {
const { inspectorUrl } = useLocalWorker(props);
useInspector({
inspectorUrl,
port: props.inspectorPort,
logToTerminal: false,
});
return null;
}
function useLocalWorker({
name: workerName,
bundle,
format,
compatibilityDate,
compatibilityFlags,
usageModel,
bindings,
workerDefinitions,
assetPaths,
port,
inspectorPort,
rules,
enableLocalPersistence,
liveReload,
ip,
crons,
localProtocol,
localUpstream,
inspect,
onReady,
logLevel,
logPrefix,
enablePagesAssetsServiceBinding,
}: LocalProps) {
// TODO: pass vars via command line
const local = useRef<ChildProcess>();
const removeSignalExitListener = useRef<() => void>();
const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
// if we're using local persistence for data, we should use the cwd
// as an explicit path, or else it'll use the temp dir
// which disappears when dev ends
const localPersistencePath = enableLocalPersistence
? // Maybe we could make the path configurable as well?
path.join(process.cwd(), "wrangler-local-state")
: // We otherwise choose null, but choose true later
// so that it's persisted in the temp dir across a dev session
// even when we change source and reload
null;
useEffect(() => {
if (bindings.services && bindings.services.length > 0) {
logger.warn(
"⎔ Support for service bindings in local mode is experimental and may change."
);
}
}, [bindings.services]);
useEffect(() => {
const externalDurableObjects = (
bindings.durable_objects?.bindings || []
).filter((binding) => binding.script_name);
if (externalDurableObjects.length > 0) {
logger.warn(
"⎔ Support for external Durable Objects in local mode is experimental and may change."
);
}
}, [bindings.durable_objects?.bindings]);
useEffect(() => {
const abortController = new AbortController();
async function startLocalWorker() {
if (!bundle || !format) return;
// port for the worker
await waitForPortToBeAvailable(port, {
retryPeriod: 200,
timeout: 2000,
abortSignal: abortController.signal,
});
// In local mode, we want to copy all referenced modules into
// the output bundle directory before starting up
for (const module of bundle.modules) {
await writeFile(
path.join(path.dirname(bundle.path), module.name),
module.content
);
}
const scriptPath = realpathSync(bundle.path);
// the wasm_modules/text_blobs/data_blobs bindings are
// relative to process.cwd(), but the actual worker bundle
// is in the temp output directory; so we rewrite the paths to be absolute,
// letting miniflare resolve them correctly
// wasm
const wasmBindings: Record<string, string> = {};
for (const [name, filePath] of Object.entries(
bindings.wasm_modules || {}
)) {
wasmBindings[name] = path.join(process.cwd(), filePath);
}
// text
const textBlobBindings: Record<string, string> = {};
for (const [name, filePath] of Object.entries(
bindings.text_blobs || {}
)) {
textBlobBindings[name] = path.join(process.cwd(), filePath);
}
// data
const dataBlobBindings: Record<string, string> = {};
for (const [name, filePath] of Object.entries(
bindings.data_blobs || {}
)) {
dataBlobBindings[name] = path.join(process.cwd(), filePath);
}
if (format === "service-worker") {
for (const { type, name } of bundle.modules) {
if (type === "compiled-wasm") {
// In service-worker format, .wasm modules are referenced by global identifiers,
// so we convert it here.
// This identifier has to be a valid JS identifier, so we replace all non alphanumeric
// characters with an underscore.
const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
wasmBindings[identifier] = name;
} else if (type === "text") {
// In service-worker format, text modules are referenced by global identifiers,
// so we convert it here.
// This identifier has to be a valid JS identifier, so we replace all non alphanumeric
// characters with an underscore.
const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
textBlobBindings[identifier] = name;
} else if (type === "buffer") {
// In service-worker format, data blobs are referenced by global identifiers,
// so we convert it here.
// This identifier has to be a valid JS identifier, so we replace all non alphanumeric
// characters with an underscore.
const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
dataBlobBindings[identifier] = name;
}
}
}
const upstream =
typeof localUpstream === "string"
? `${localProtocol}://${localUpstream}`
: undefined;
const internalDurableObjects = (
bindings.durable_objects?.bindings || []
).filter((binding) => !binding.script_name);
const externalDurableObjects = (
bindings.durable_objects?.bindings || []
).filter((binding) => binding.script_name);
// TODO: This was already messy with the custom `disableLogs` and `logOptions`.
// It's now getting _really_ messy now with Pages ASSETS binding outside and the external Durable Objects inside.
const options: MiniflareOptions = {
name: workerName,
port,
scriptPath,
https: localProtocol === "https",
host: ip,
modules: format === "modules",
modulesRules: (rules || [])
.concat(DEFAULT_MODULE_RULES)
.map(({ type, globs: include, fallthrough }) => ({
type,
include,
fallthrough,
})),
compatibilityDate,
compatibilityFlags,
usageModel,
kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
r2Buckets: bindings.r2_buckets?.map((r2) => r2.binding),
durableObjects: Object.fromEntries(
internalDurableObjects.map((binding) => [
binding.name,
binding.class_name,
])
),
externalDurableObjects: Object.fromEntries(
externalDurableObjects
.map((binding) => {
const service = workerDefinitions[binding.script_name as string];
if (!service) return [binding.name, undefined];
const name = service.durableObjects.find(
(durableObject) =>
durableObject.className === binding.class_name
)?.name;
if (!name) return [binding.name, undefined];
return [
binding.name,
{
name,
host: service.durableObjectsHost,
port: service.durableObjectsPort,
},
];
})
.filter(([_, details]) => !!details)
),
...(localPersistencePath
? {
cachePersist: path.join(localPersistencePath, "cache"),
durableObjectsPersist: path.join(localPersistencePath, "do"),
kvPersist: path.join(localPersistencePath, "kv"),
r2Persist: path.join(localPersistencePath, "r2"),
}
: {
// We mark these as true, so that they'll
// persist in the temp directory.
// This means they'll persist across a dev session,
// even if we change source and reload,
// and be deleted when the dev session ends
cachePersist: true,
durableObjectsPersist: true,
kvPersist: true,
r2Persist: true,
}),
liveReload,
sitePath: assetPaths?.assetDirectory
? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
: undefined,
siteInclude: assetPaths?.includePatterns.length
? assetPaths?.includePatterns
: undefined,
siteExclude: assetPaths?.excludePatterns.length
? assetPaths.excludePatterns
: undefined,
bindings: bindings.vars,
wasmBindings,
textBlobBindings,
dataBlobBindings,
sourceMap: true,
logUnhandledRejections: true,
crons,
upstream,
disableLogs: logLevel === "none",
logOptions: logPrefix ? { prefix: logPrefix } : undefined,
};
// The path to the Miniflare CLI assumes that this file is being run from
// `wrangler-dist` and that the CLI is found in `miniflare-dist`.
// If either of those paths change this line needs updating.
const miniflareCLIPath = path.resolve(
__dirname,
"../miniflare-dist/index.mjs"
);
const miniflareOptions = JSON.stringify(options, null);
logger.log("⎔ Starting a local server...");
const nodeOptions = [
"--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
"--no-warnings", // hide annoying Node warnings
// "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
];
if (inspect) {
nodeOptions.push("--inspect=" + `${ip}:${inspectorPort}`); // start Miniflare listening for a debugger to attach
}
const forkOptions = [miniflareOptions];
if (enablePagesAssetsServiceBinding) {
forkOptions.push(JSON.stringify(enablePagesAssetsServiceBinding));
}
const child = (local.current = fork(miniflareCLIPath, forkOptions, {
cwd: path.dirname(scriptPath),
execArgv: nodeOptions,
stdio: "pipe",
}));
child.on("message", async (messageString) => {
const message = JSON.parse(messageString as string);
if (message.ready) {
// Let's register our presence in the dev registry
if (workerName) {
await registerWorker(workerName, {
protocol: localProtocol,
mode: "local",
port,
host: ip,
durableObjects: internalDurableObjects.map((binding) => ({
name: binding.name,
className: binding.class_name,
})),
...(message.durableObjectsPort
? {
durableObjectsHost: ip,
durableObjectsPort: message.durableObjectsPort,
}
: {}),
});
}
onReady?.();
}
});
child.on("close", (code) => {
if (code) {
logger.log(`Miniflare process exited with code ${code}`);
}
});
child.stdout?.on("data", (data: Buffer) => {
process.stdout.write(data);
});
// parse the node inspector url (which may be received in chunks) from stderr
let stderrData = "";
let inspectorUrlFound = false;
child.stderr?.on("data", (data: Buffer) => {
if (!inspectorUrlFound) {
stderrData += data.toString();
const matches =
/Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)[\r|\n]/.exec(
stderrData
);
if (matches) {
inspectorUrlFound = true;
setInspectorUrl(matches[1]);
}
}
process.stderr.write(data);
});
child.on("exit", (code) => {
if (code) {
logger.error(`Miniflare process exited with code ${code}`);
}
});
child.on("error", (error: Error) => {
logger.error(`Miniflare process failed to spawn`);
logger.error(error);
});
removeSignalExitListener.current = onExit((_code, _signal) => {
logger.log("⎔ Shutting down local server.");
child.kill();
local.current = undefined;
});
}
startLocalWorker().catch((err) => {
logger.error("local worker:", err);
});
return () => {
abortController.abort();
if (local.current) {
logger.log("⎔ Shutting down local server.");
local.current?.kill();
local.current = undefined;
removeSignalExitListener.current && removeSignalExitListener.current();
removeSignalExitListener.current = undefined;
}
};
}, [
bundle,
workerName,
format,
port,
inspectorPort,
ip,
bindings.durable_objects?.bindings,
bindings.kv_namespaces,
bindings.r2_buckets,
bindings.vars,
bindings.services,
workerDefinitions,
compatibilityDate,
compatibilityFlags,
usageModel,
localPersistencePath,
liveReload,
assetPaths,
rules,
bindings.wasm_modules,
bindings.text_blobs,
bindings.data_blobs,
crons,
localProtocol,
localUpstream,
inspect,
logLevel,
logPrefix,
onReady,
enablePagesAssetsServiceBinding,
]);
return { inspectorUrl };
}
|
package ru.aurorahost.stayraterapp.di
import androidx.paging.ExperimentalPagingApi
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import okhttp3.MediaType
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import ru.aurorahost.stayraterapp.data.local.StayRaterDb
import ru.aurorahost.stayraterapp.data.remote.StayRaterApi
import ru.aurorahost.stayraterapp.data.repository.RemoteDataSourceImpl
import ru.aurorahost.stayraterapp.domain.repository.RemoteDataSource
import ru.aurorahost.stayraterapp.util.Constants.BASE_URL
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@ExperimentalPagingApi
@ExperimentalSerializationApi
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.readTimeout(15, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.build()
}
@Provides
@Singleton
fun provideRetrofitInstance(okHttpClient: OkHttpClient): Retrofit {
val contentType = MediaType.get("application/json")
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(Json.asConverterFactory(contentType))
.build()
}
@Provides
@Singleton
fun provideStayRaterApi(retrofit: Retrofit): StayRaterApi {
return retrofit.create(StayRaterApi::class.java)
}
@Provides
@Singleton
fun provideRemoteDataSource(
stayRaterApi: StayRaterApi,
stayRaterDb: StayRaterDb
): RemoteDataSource {
return RemoteDataSourceImpl(
stayRaterApi = stayRaterApi,
stayRaterDb = stayRaterDb
)
}
}
|
show tables;
create table board2 (
idx int not null auto_increment, /* 게시글의 고유번호 */
nickName varchar(20) not null, /* 게시글을 올린사람의 닉네임 */
title varchar(100) not null, /* 게시글의 글 제목 */
email varchar(100), /* 글쓴이의 메일주소 */
homePage varchar(100), /* 글쓴이의 홈페이지(블로그) 주소 */
content text not null, /* 글 내용 */
wDate datetime default now(), /* 글 올린 날짜 */
readNum int default 0, /* 글 조회수 */
hostIp varchar(50) not null, /* 접속 IP 주소 */
good int default 0, /* '좋아요' 횟수 누적처리 */
mid varchar(20) not null, /* 회원 아이디(게시글 조회시 사용) */
primary key(idx) /* 게시판의 기본키 : 고유번호(idx)*/
);
desc board2;
insert into board2 values (default, '관리투', '게시판 서비스를 시작합니다.', '[email protected]', 'http://blog.daum.net/cjsk1126', '이곳은 게시판입니다.', default, default, '192.168.50.103', default, 'admin');
select * from board2;
select * from board2 where idx = 5 - 1; /*현재글이 5번글일 경우 */
select * from board2 where idx = 20 + 1;
select * from board2 where idx > 5 limit 1; /* 다음글 */
select * from board2 where idx < 5 order by idx desc limit 1; /* 이전글 */
select idx,title from board2 where idx in (
(select idx from board2 where idx > 5 limit 1),
(select idx from board2 where idx < 5 order by idx desc limit 1)
);
select idx,title from board2 where idx in (
(select idx from board2 where idx < 5 order by idx desc limit 1),
(select idx from board2 where idx > 5 limit 1)
);
/* 최근글 출력연습 */
select * from board2 where date_sub(now(), interval 1 month) < wDate order by idx desc;
select count(*) from board2 where date_sub(now(), interval 1 day) < wDate;
select * from board2 where 1 > 2; /*where절 이하가 false가 되어서 데이터가 select되지 않는다.*/
/*
DATEDIFF(날짜1, 날짜2) : '날짜1 - 날짜2'의 결과를 반환한다.
TIMESTAMPDIFF(단위, 날짜1, 날짜2) : '날짜2 - 날짜1'의 결과를 반환한다.
단위 : YEAR(년도 차이) / QUARTER(분기 차이) / MONTH(월 차이) / WEEK(주 차이) / DAY(일 차이) / HOUR(시) / MINUTE(분) / SECOND(초)
-> 결과를 숫자로 반환한다.
*/
select datediff('2022-06-22', '2022-06-01');
select datediff(now(), '2022-06-01');
/* date_add와 date_sub : 결과를 날짜로 반환 */
select date_add(now(), interval 1 day);
select date_sub(now(), interval 1 day);
select * from board order by idx desc;
/*날짜로 비교해서 오늘(interval 0 day) 올린 것, 어제부터(interval 1 day) 올린 것 등을 구해올 수 있다.*/
select * from board where wDate > date_sub(now(), interval 2 day) order by idx desc;
select timestampdiff(YEAR, '2022-06-23', '2022-06-22');
select timestampdiff(MONTH, '2022-05-23', '2022-06-27');
select timestampdiff(MONTH, '2022-05-23', now());
select timestampdiff(DAY, '2022-05-22', now());
select timestampdiff(DAY, '2022-06-22', now());
select timestampdiff(HOUR, '2022-06-22', now());
select timestampdiff(HOUR, '2022-06-22', now()) / 24;
select timestampdiff(MINUTE, '2022-06-22', now());
select timestampdiff(MINUTE, '2022-06-22', now());
select timestampdiff(MINUTE, '2022-06-22', now()) / 60;
select timestampdiff(MINUTE, '2022-06-22', now()) / (60 * 24);
select *, (TIMESTAMPDIFF(MINUTE, wDate, now()) / 60) AS diffTime from board2;
select *, cast(TIMESTAMPDIFF(MINUTE, wDate, now()) / 60 as signed integer) AS diffTime from board2;
/*
외래키(foreign key) : 서로다른 테이블간의 연관관계를 맺어주기위한 키
: 외래키를 설정하려면, 설정하려는 외래키는 다른테이블의 주키(Primary key)이어야 한다.
즉, 외래키로 지정하는 필드는, 해당테이블의 속성과 똑 같아야 한다.(필드명은 달라도 된다.)
*/
/* 댓글 테이블(boardReply2) */
create table boardReply2 (
idx int not null auto_increment, /* 댓글의 고유번호 */
boardIdx int not null, /* 원본글의 고유번호(외래키로 지정함) */
mid varchar(20) not null, /* 댓글 올린이의 아이디 */
nickName varchar(20) not null, /* 댓글 올린이의 닉네임 */
wDate datetime default now(), /* 댓글쓴 날짜 */
hostIp varchar(50) not null, /* 댓글쓴 PC의 IP */
content text not null, /* 댓글 내용 */
level int not null default 0, /* 댓글레벨 - 부모댓글의 레벨은 0 */
levelOrder int not null default 0, /* 댓글의 순서 - 부모댓글의 levelOrder는 0 */
primary key(idx), /* 주키(기본키)는 idx */
foreign key(boardIdx) references board2(idx) /*board테블의 idx를 boardReply2테이블의 외래키(boardIdx)로 설정 */
/* on update cascade 원본테이블에서의 주키의 변경의 영향을 받는다. */
/* on delete restrict 원본테이블에서의 주키를 삭제시키지 못하게 한다.(삭제시는 에러발생하고 원본키를 삭제하지 못함) 게시글에 댓글이 달려있으면 게시글을 못지움. 해당 댓글을 먼저 지우고 게시글을 지워야한다.*/
);
drop table boardReply2;
desc boardReply2;
/*
- 테이블 설계시 제약조건(필드에 대한 제한) - constraint
: 생성시에 설정(creat), 생성 후 변경(alter table)
1. 필드의 값 허용유무? not null
2. 필드의 값을 중복허용하지 않겠다? primary key, unique
3. 필드의 참조유무(다른테이블에서)? foreign key
4. 필드의 값에 기본값을 지정? default
*/
show tables;
/* unique : 필드가 서로다른 값을 갖도록 함.(중복할 수 없도록 제약조건 설정시 사용) */
create table testStudent (
idx int not null auto_increment,
hakbun int not null unique,
mid varchar(20) not null unique,
name varchar(20) not null,
age int default 20,
primary key(idx,hakbun)
);
desc testStudent;
drop table testStudent;
insert into testStudent values (default, 1111, 'hkd1234', '홍길동', default);
insert into testStudent values (default, 2222, 'kms1234', '김말숙', default);
insert into testStudent values (default, 4444, 'ohl1234', '오하늘', default);
insert into testStudent values (default, 3333, 'ohl1234', '오하늘', default);
select * from testStudent;
/*
sub query
: 쿼리안에 쿼리를 삽입하는 방법(위치는 상황에 따라서 사용자가 지정해준다.) - select 문과 함께 사용...
예) select 필드명, (서브쿼리) from 테이블명 ~ where 조건절 ~~~ ...
select 필드리스트 from (서브쿼리) ~~~ where 조건절 ~~~ ...
select 필드리스트 from 테이블명 where (서브쿼리) ~~ ....
*/
-- board 테이블의 목록 모두 보여주기(idx 역순으로, 출력자료의 개수는 5개)
select * from board order by idx desc limit 5;
-- boardReply2 테이블의 구조?
desc boardReply2;
-- board 테이블의 idx 29번글에 적혀있는 댓글(boardReply2테이블)의 개수는?
select count(*) from boardReply2 where boardIdx = 29;
-- board 테이블의 idx 29번글에 적혀있는 댓글(boardReply2테이블)의 개수는?(단, 출력은 부모글의 고유번호와 댓글개수를 출력)
select boardIdx as '부모고유번호', count(*) as '댓글개수' from boardReply2 where boardIdx = 29;
-- board 테이블의 idx 29번글에 적혀있는 댓글(boardReply2테이블)의 개수는?(단, 출력은 부모글의 고유번호와 댓글개수, 게시글을 쓴 사람의 nickName 까지)
select (select nickName from board where idx = 29) as 닉네임, boardIdx as 부모고유번호, count(*) as 댓글개수 from boardReply2 where boardIdx = 29;
-- board 테이블의 29번의 작성자의 아이디와 현재글(부모글 29번)에 달려있는 댓글 사용자의 닉네임을 출력하시오.
select (select mid from board where idx = 29) as 작성자아이디, nickName from boardReply2 where boardIdx = 29;
-- 부모관점에서 자료를 select 해오면.. 1:多 관계라서, 댓글이 2개 이상이면..에러가 난다.(아이디는 1개가 출력.댓글은 2개 출력이기 때문에..)
select mid, (select nickName from boardReply2 where boardIdx = 29) as 작성자닉네임 from board where idx = 29;
-- board 테이블의 29번의 작성자의 아이디와 현재글(부모글 29번)에 달려있는 댓글의 갯수를 출력하시오.
select mid, (select count(*) from boardReply2 where boardIdx = 29) as 댓글개수 from board where idx = 29;
-- 부모테이블(board)에 있는 자료 중 뒤에서 5개를 출력하되(아이디,닉네임), 부모테이블에 달려있는 댓글(boardReply2)의 수와 함께 출력하시오.
select idx,mid,nickName,(select count(*) from boardReply2 where boardIdx = board.idx) as replyCount from board order by idx desc limit 5;
|
import React from "react";
import { Flex, Image, Box, Heading, Text } from "@chakra-ui/react";
function Footer() {
return (
<Flex
as={"footer"}
flexDirection={{ base: "column", lg: "row" }}
justifyContent={"space-evenly"}
background={
"linear-gradient(90.07deg, rgba(30, 42, 93, 0.04) 30.91%, rgba(48, 62, 130, 0.04) 64.79%, rgba(60, 80, 157, 0.04) 91.94%);"
}
// alignItems={"center"}
>
<Image
src="/images/logo.png"
alt="page logo"
mb={"2em"}
margin={{ base: "0 auto", lg: "5%" }}
h={{ base: "58px", lg: "125px" }}
w={{ base: "75px", lg: "161px" }}
/>
<Flex
flexDirection={{ base: "column", lg: "column" }}
justifyContent={"space-evenly"}
textAlign={"left"}
padding={"2em"}
>
<Box
color={"#0E2368"}
fontSize={"16px"}
fontStyle={"normal"}
fontWeight={"600"}
lineHeight={"35px"}
letterSpacing={".03em"}
>
Contact Us
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
mb={".8em"}
>
Lorem Ipsum Pvt Ltd.5/1, Magalton Road, Phartosh Gate near YTM Market,
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
mb={".8em"}
>
XYZ-343434
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
mb={".8em"}
>
[email protected]
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
>
(91)343434675867
</Box>
</Flex>
<Flex
flexDirection={{ base: "column", lg: "column" }}
justifyContent={"space-evenly"}
textAlign={"left"}
padding={"2em"}
justifyItems={"left"}
>
<Box
color={"#0E2368"}
fontSize={"16px"}
fontStyle={"normal"}
fontWeight={"600"}
lineHeight={"35px"}
letterSpacing={".03em"}
>
More
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
mb={".8em"}
>
About Us
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
mb={".8em"}
>
Products
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
mb={".8em"}
>
Careers
</Box>
<Box
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
>
Contact Us
</Box>
</Flex>
<Flex
flexDirection={{ base: "column", lg: "column-reverse" }}
textAlign={"left"}
justify={"space-evenly"}
alignItems={{ base: "center", lg: "flex-end" }}
>
<Flex>
<Text
color={"#646874"}
fontStyle={"normal"}
fontWeight={"400"}
fontSize={"12px"}
lineHeight={"12px"}
>
© 2023 Food Truck Example
</Text>
</Flex>
<Flex flexDirection={"row"}
my={{base:"1em", lg:"0"}}
>
<a>
<Image src="/icons/insta.png" />
</a>
<a>
<Image
marginLeft={"1em"}
marginRight={"1em"}
src="/icons/twitter.png"
/>
</a>
<a>
<Image src="/icons/fb.png" />
</a>
</Flex>
<Box
display={{ base: "none", lg: "block" }}
color={"#0E2368"}
fontSize={"16px"}
fontStyle={"normal"}
fontWeight={"600"}
lineHeight={"35px"}
letterSpacing={".03em"}
>
Social Links
</Box>
</Flex>
</Flex>
);
}
export default Footer;
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;
class ColorType extends AbstractType
{
/**
* @see https://www.w3.org/TR/html52/sec-forms.html#color-state-typecolor
*/
private const HTML5_PATTERN = '/^#[0-9a-f]{6}$/i';
private $translator;
public function __construct(TranslatorInterface $translator = null)
{
$this->translator = $translator;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (!$options['html5']) {
return;
}
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$value = $event->getData();
if (null === $value || '' === $value) {
return;
}
if (\is_string($value) && preg_match(self::HTML5_PATTERN, $value)) {
return;
}
$messageTemplate = 'This value is not a valid HTML5 color.';
$messageParameters = [
'{{ value }}' => \is_scalar($value) ? (string) $value : \gettype($value),
];
$message = $this->translator ? $this->translator->trans($messageTemplate, $messageParameters, 'validators') : $messageTemplate;
$event->getForm()->addError(new FormError($message, $messageTemplate, $messageParameters));
});
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'html5' => false,
'invalid_message' => function (Options $options, $previousValue) {
return ($options['legacy_error_messages'] ?? true)
? $previousValue
: 'Please select a valid color.';
},
]);
$resolver->setAllowedTypes('html5', 'bool');
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return TextType::class;
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'color';
}
}
|
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<!-- CSS Stylesheet -->
<link rel="stylesheet" href="css/styles.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
crossorigin="anonymous">
<title>The HUD</title>
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="index.html">THE HUD</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="gaming.html">Gaming</a>
</li>
<li class="nav-item">
<a class="nav-link" href="interviews.html">Interviews</a>
</li>
<li class="nav-item">
<a class="nav-link" href="learning.html">Learning</a>
</li>
<li class="nav-item">
<a class="nav-link" href="streamers.html">Streamers</a>
</li>
<li class="nav-item">
<a class="nav-link" href="aboutus.html">About Us</a>
</li>
</ul>
</div>
</nav>
<!-- Jumbotron -->
<div class="jumbotron">
<div class="container">
<div class="row row-border">
<div class="col-sm-6 btn-holder">
<h1 class="display-2">This is THE HUD!</h1>
<p class="lead">Here you will find reviews, interviews, blogs, games, tech, streamers and links to
all the
best programming courses on the web.</p>
<hr class="my-4">
<p>Follow us on...</p>
<div class="contact">
<a href="https://www.facebook.com/"><i class="fab fa-facebook-f fa-2x logo"></i></a>
<a href="https://twitter.com/"><i class="fab fa-twitter fa-2x logo"></i></a>
<a href="https://www.instagram.com/"><i class="fab fa-instagram fa-2x logo"></i></a>
</div>
<br>
<a class="btn btn-primary btn-lg" href="contactus.html" role="button">Contact Us</a>
<div class="col-sm-6 btn-holder">
</div>
<br>
</div>
</div>
</div>
</div>
<!-- Cards -->
<section id="cards">
<h3 class="display-4">Check the links often for updated content.</h3>
<div class="container ">
<div class="cards">
<div class="row">
<div class="card-space col-lg-4 col-md-6 d-flex justify-content-center">
<div class="card">
<img src="images/gaming.jpg" class="card-img-top" alt="Gaming Image">
<div class="card-body">
<h5 class="card-title">Gaming</h5>
<p class="card-text">Upcoming titles, what's hot and what's not, reviews, trailers and
more.</p>
<a href="gaming.html" class="btn btn-primary">More...</a>
</div>
</div>
</div>
<div class="card-space col-lg-4 col-md-6 d-flex justify-content-center">
<div class="card">
<img src="images/interview.jpg" class="card-img-top" alt="Interview Image">
<div class="card-body">
<h5 class="card-title">Interviews</h5>
<p class="card-text">Interviews from some of the top people in their fields, from
teachers to streamers.</p>
<a href="interviews.html" class="btn btn-primary">More...</a>
</div>
</div>
</div>
<div class="card-space col-lg-4 d-flex justify-content-center">
<div class="card">
<img src="images/learn.jpg" class="card-img-top" alt="Learning Image">
<div class="card-body">
<h5 class="card-title">Learning</h5>
<p class="card-text">Want to learn to code? We can point you in the right direction.</p>
<a href="learning.html" class="btn btn-primary">More...</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Credits -->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
|
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Checkout.aspx.cs" Inherits="Reedham_Bookstore.WebForm5" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="master2" runat="server">
<div class="container">
<main>
<form id="form1" runat="server" class="form-horizontal"
defaultfocus="txtEmail1" defaultbutton="btnCheckOut">
<h1 style="text-align: center">Check Out Page</h1>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="summary text-danger" Headertext="Please correct these entries:" />
<%-- contact info --%>
<h3>Contact Information</h3>
<div class="container">
<div class="form-group">
<label class="control-label col-sm-3">Email Address:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtEmail1" runat="server" CssClass="form-control" TextMode="Email"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvEmail1" runat="server"
ErrorMessage="Email address" ForeColor="Red"
Display="Dynamic" ControlToValidate="txtEmail1">Required</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail1" runat="server"
ErrorMessage="Email address" CssClass="text-warning"
Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="txtEmail1">Must be a valid email address</asp:RegularExpressionValidator>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Email Re-entry:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtEmail2" runat="server" CssClass="form-control" TextMode="Email"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvEmail2" runat="server" ForeColor="Red"
ErrorMessage="Email re-entry"
Display="Dynamic" ControlToValidate="txtEmail2">Required</asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvEmail2" runat="server"
ErrorMessage="Email re-entry" CssClass="text-warning" Display="Dynamic"
ControlToValidate="txtEmail2" ControlToCompare="txtEmail1">Must match first email address</asp:CompareValidator>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">First Name:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ForeColor="Red"
ErrorMessage="First name"
Display="Dynamic" ControlToValidate="txtFirstName">Required</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Last Name:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtLastName" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvLastName" runat="server" ForeColor="Red"
ErrorMessage="Last name"
Display="Dynamic" ControlToValidate="txtLastName">Required</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Phone Number:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtPhone" runat="server" CssClass="form-control" TextMode="Phone"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvphone" runat="server" ForeColor="Red"
ErrorMessage="Phone number"
Display="Dynamic" ControlToValidate="txtPhone">Required</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ControlToValidate="txtPhone" CssClass="text-warning" Display="Dynamic" ValidationExpression="^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$">use this formate 999-999-9999 or 999 999 9999 or (999) 999 9999 or 999.999.9999</asp:RegularExpressionValidator>
</div>
</div>
</div>
<%-- billing info --%>
<h3>Billing Address</h3>
<div class="container">
<div class="form-group">
<label class="control-label col-sm-3">Address:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtAddress" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvStreetAddress" runat="server" ForeColor="Red"
ErrorMessage="Billing address" Text="Required"
Display="Dynamic"
ControlToValidate="txtAddress"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">City:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtCity" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvCity" runat="server" ForeColor="Red"
ErrorMessage="Billing city" Text="Required"
Display="Dynamic" ControlToValidate="txtCity"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">State:</label>
<div class="col-sm-3">
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="form-select">
<asp:ListItem>ontario</asp:ListItem>
<asp:ListItem>nova scotia</asp:ListItem>
<asp:ListItem>manitoba</asp:ListItem>
<asp:ListItem>british columbia</asp:ListItem>
<asp:ListItem>alberta</asp:ListItem>
<asp:ListItem>Qubec</asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-sm-3">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Zip code:</label>
<div class="col-sm-3">
<asp:TextBox ID="txtZip" runat="server" CssClass="form-control" MaxLength="10"></asp:TextBox>
</div>
<div class="col-sm-3">
<asp:RequiredFieldValidator ID="rfvZip" runat="server" ForeColor="Red"
ErrorMessage="Billing zip code" Text="Required"
Display="Dynamic" ControlToValidate="txtZip"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="" CssClass="text-warning"
Display="Dynamic" ValidationExpression="^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)"
ControlToValidate="txtZip">Use this format: A1B3C4</asp:RegularExpressionValidator>
</div>
</div>
</div>
<%-- Optional Data --%>
<h3>Optional Data</h3>
<div class="container">
<h6>Please let me know about:</h6>
<div class="container">
<asp:CheckBox ID="CheckBox1" runat="server" Text="New Products" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="New Editions" />
<br />
<asp:CheckBox ID="CheckBox3" runat="server" Text="Special Offers" />
<asp:CheckBox ID="CheckBox4" runat="server" Text="Local Events" />
</div>
<h6>please contact me via:</h6>
<div class="container">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" >
<asp:ListItem>Twitter</asp:ListItem>
<asp:ListItem>Facebook</asp:ListItem>
<asp:ListItem>Text Message</asp:ListItem>
<asp:ListItem>Email</asp:ListItem>
</asp:RadioButtonList>
</div>
</div>
<div class="form-group mt-3">
<div class="col-sm-offset-3 col-sm-9">
<asp:Button ID="btnCheckOut" runat="server" Text="Check Out" CssClass="btn btn-primary" OnClick="btnCheckOut_Click"
/>
<asp:Button ID="btnCancel" runat="server" Text="Cancel Order" CssClass="btn btn-primary"
CausesValidation="False" OnClick="btnCancel_Click" />
<asp:LinkButton ID="lbtnContinueShopping" runat="server" CssClass="btn-primary text-decoration-none cn"
PostBackUrl="~/Products.aspx" CausesValidation="False" OnClick="lbtnContinueShopping_Click">Continue Shopping</asp:LinkButton>
</div>
</div>
</form>
</main>
</div>
</asp:Content>
|
package com.example.SpringSecurityJWT.service;
import com.example.SpringSecurityJWT.dto.RequestDTO;
import com.example.SpringSecurityJWT.model.Person;
import com.example.SpringSecurityJWT.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private BlockingService blockingService;
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.info(String.format("A user named %s logs in", username));
Person person = userRepository.findByUsername(username)
.orElseThrow(() -> {
logger.warn(String.format("User name %s not found", username));
return new UsernameNotFoundException("Person not found");
});
if (blockingService.isBlockedPerson(person)) {
throw new LockedException("Person is blocked");
}
return new User(person.getUsername(), person.getPassword(), person.getAuthorities());
}
public Person createPerson(RequestDTO signupDTO) {
Person person = null;
if (signupDTO.role() == null) {
person = new Person(
signupDTO.username(), passwordEncoder.encode(signupDTO.password()), "ROLE_USER");
return userRepository.save(person);
}
person = new Person(
signupDTO.username(), passwordEncoder.encode(signupDTO.password()), signupDTO.role());
return userRepository.save(person);
}
public Person findByUsername(String username) {
return userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("Person not found"));
}
public boolean checkPassword(String requestPassword, String password) {
return passwordEncoder.matches(requestPassword, password);
}
public boolean checkingUserForBlocking(Person person) {
return blockingService.isBlockedPerson(person);
}
public void resetCountAttempt(Person person) {
blockingService.resetCountAttempt(person);
}
public void unsuccessfulAttempt(Person person) {
blockingService.unsuccessfulAttempt(person);
}
}
|
//
// PlacesViewController.swift
// FoursquareClone
//
// Created by Marcus Vinicius Galdino Medeiros on 04/01/20.
// Copyright © 2020 Marcus Vinicius Galdino Medeiros. All rights reserved.
//
import UIKit
import Parse
class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var placesNameArray = [String]()
var placesIdArray = [String]()
var selectedPlaceId = ""
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(addButtonClicked))
navigationController?.navigationBar.topItem?.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: UIBarButtonItem.Style.plain, target: self, action: #selector(logoutButtonClicked))
tableView.delegate = self
tableView.dataSource = self
getDataFromParse()
}
@objc func addButtonClicked(){
self.performSegue(withIdentifier: "toAddPlaceVC", sender: nil)
}
@objc func logoutButtonClicked(){
PFUser.logOutInBackground { (error) in
if error != nil {
self.makeAlert(title: "Error", message: error?.localizedDescription ?? "Error Logout")
}else {
self.performSegue(withIdentifier: "toSignVC", sender: nil)
}
}
}
func getDataFromParse(){
let query = PFQuery(className: "Places")
query.findObjectsInBackground { (objects, error) in
if error != nil {
self.makeAlert(title: "Error", message: error?.localizedDescription ?? "Error Logout")
}else {
if objects != nil {
self.placesNameArray.removeAll(keepingCapacity: false)
self.placesIdArray.removeAll(keepingCapacity: false)
for object in objects! {
if let placeName = object.object(forKey: "name") as? String {
if let placeId = object.objectId {
self.placesNameArray.append(placeName)
self.placesIdArray.append(placeId)
}
}
}
self.tableView.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return placesNameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = placesNameArray[indexPath.row]
return cell
}
func makeAlert(title:String, message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
let okButton = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(okButton)
present(alert, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetailsVC"{
let destinationVC = segue.destination as! DetailsViewController
destinationVC.chosenPlaceId = selectedPlaceId
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlaceId = placesIdArray[indexPath.row]
self.performSegue(withIdentifier: "toDetailsVC", sender: nil)
}
}
|
import React, { useState, useEffect } from "react";
import { ethers } from "ethers";
import { useStateContext } from "../context";
import { money } from "../assets";
import { CustomButton, FormField, Loader } from "../components";
import { checkIfImage } from "../utils";
import { useLocation, useNavigate } from "react-router-dom";
// import 'react-responsive-modal/styles.css';
// import { Modal } from 'react-responsive-modal';
const UpdateCampaign = () => {
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(false);
const { updateCampaign } = useStateContext();
const { state } = useLocation();
//console.log("State", state);
const [form, setForm] = useState({
id: state.id,
name: state.name,
title: state.title,
category: state.category,
description: state.description,
target: state.target,
deadline: state.deadline,
image: state.image,
});
//console.log("Form", form);
const handleFormFieldChange = (fieldName, e) => {
setForm({ ...form, [fieldName]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
checkIfImage(form.image, async (exists) => {
if (exists) {
setIsLoading(true);
console.log("form", form);
console.log("target", form.target);
await updateCampaign({
...form,
target: ethers.utils.parseUnits(form.target, 18),
});
setIsLoading(false);
navigate("/");
} else {
alert("Provide valid image URL");
setForm({ ...form, image: "" });
}
});
};
return (
<div className="bg-[#1c1c24] flex justify-center items-center flex-col rounded-[10px] sm:p-10 p-4">
{isLoading && <Loader />}
<div className="flex justify-center items-center p-[16px] sm:min-w-[380px] bg-[#3a3a43] rounded-[10px]">
<h1 className="font-epilogue font-bold sm:text-[25px] text-[18px] leading-[38px] text-white">
Edit Campaign
</h1>
</div>
<form
onSubmit={handleSubmit}
className="w-full mt-[65px] flex flex-col gap-[30px]"
>
<div className="flex flex-wrap gap-[40px]">
<FormField
labelName="YourName *"
placeholder="John Doe"
inputType="text"
value={form.name}
handleChange={(e) => handleFormFieldChange("name", e)}
/>
<FormField
labelName="Campaign Title *"
placeholder="Write a title"
inputType="text"
value={form.title}
handleChange={(e) => handleFormFieldChange("title", e)}
/>
<FormField
labelName="Select Category *"
placeholder="Select..."
isCategory
value={form.category}
handleChange={(e) => handleFormFieldChange("category", e)}
/>
</div>
<FormField
labelName="Story *"
placeholder="Write a your story"
isTextArea
value={form.description}
handleChange={(e) => handleFormFieldChange("description", e)}
/>
<div className="w-full flex justify-start items-center p-4 bg-[#8c6dfd] rounded-[10px]">
<img
src={money}
alt="money"
className="w-[40px] h-[40px] object-contain"
/>
<h4 className="font-epilogue font-bold text-[25px] text-white ml-[20px]">
You will get (100 - platformFee)% of the raised amount
</h4>
</div>
<div className="flex flex-wrap gap-[40px]">
<FormField
labelName="Goal *"
placeholder="ETH 0.50"
inputType="text"
value={form.target}
handleChange={(e) => handleFormFieldChange("target", e)}
/>
<FormField
labelName="End Date *"
placeholder="End Date"
inputType="date"
value={form.deadline}
handleChange={(e) => handleFormFieldChange("deadline", e)}
/>
</div>
<FormField
labelName="Campaign image *"
placeholder="Place image URL of your campaign"
inputType="url"
value={form.image}
handleChange={(e) => handleFormFieldChange("image", e)}
/>
<div className="flex justify-center items-center mt-[40px]">
<CustomButton
btnType="submit"
title="Update campaign"
styles="bg-[#1dc071]"
/>
</div>
</form>
</div>
);
};
export default UpdateCampaign;
|
"use client";
import Buttons from "@/Components/Buttons";
import Formule from "@/Components/Formule";
import ArrowLeftIcon from "@/Components/Icons/ArrowLeftIcon";
import ArrowRightIcon from "@/Components/Icons/ArrowRightIcon";
import PlusMinusIcon from "@/Components/Icons/PlusMinusIcon";
import EqualsIcon from "@/Components/Icons/EqualsIcon";
import React, { useState } from "react";
import CalcResult from "@/Scripts/CalcCamp";
const Calculator = () => {
const [selectedIndex, setSelectedIndex] = useState(0);
const [Charge, setChargeValue] = useState("\\boxed{}");
const [ExpCharge, setExpChargeValue] = useState("\\boxed{}");
const [Radius, setRadiusValue] = useState("\\boxed{}");
const [ExpRadius, setExpRadiusValue] = useState("\\boxed{}");
const [Result, setResult] = useState("\\color{lightgray}{\\boxed{}}");
const Change = (value: string) => {
switch (selectedIndex) {
case 0:
if (Charge.charAt(0) == "-") {
setChargeValue("-" + value);
break;
}
setChargeValue(value);
break;
case 1:
if (ExpCharge.charAt(0) == "-") {
setExpChargeValue("-" + value);
break;
}
setExpChargeValue(value);
break;
case 2:
if (Radius.charAt(0) == "-") {
setRadiusValue("-" + value);
break;
}
setRadiusValue(value);
break;
case 3:
if (ExpRadius.charAt(0) == "-") {
setExpRadiusValue("-" + value);
break;
}
setExpRadiusValue(value);
break;
}
};
const ChangeSign = () => {
switch (selectedIndex) {
case 0:
if (Charge.charAt(0) == "-") {
setChargeValue(Charge.substring(1));
break;
}
setChargeValue("-" + Charge);
break;
case 1:
if (ExpCharge.charAt(0) == "-") {
setExpChargeValue(ExpCharge.substring(1));
break;
}
setExpChargeValue("-" + ExpCharge);
break;
case 2:
break;
case 3:
if (ExpRadius.charAt(0) == "-") {
setExpRadiusValue(ExpRadius.substring(1));
break;
}
setExpRadiusValue("-" + ExpRadius);
break;
}
};
return (
<div className="my-auto h-max w-[90vw] rounded-2xl bg-[#A2D2FF] p-8 text-center dark:bg-[#282F44] md:w-[85vw]">
<section className="grid h-28 place-content-center rounded-lg bg-[#8eb5db] dark:bg-[#1d2231] md:p-10">
<Formule
boxedIndex={selectedIndex}
Charge={Charge}
ExpCharge={ExpCharge}
Radius={Radius}
ExpRadius={ExpRadius}
Result={Result}
/>
</section>
<section className="mt-5 grid grid-cols-3 gap-8">
{[...Array(9)].map((x, i) => (
<Buttons
className="rounded-md bg-[#8eb5db] p-3 text-3xl text-[#474747] dark:bg-[#1d2231] dark:text-white"
value={`${i + 1}`}
onClick={() => {
Change(`${i + 1}`);
}}
/>
))}
<Buttons
className="p-3 text-xl text-[#474747] dark:text-white"
value={"C"}
onClick={() => {
setChargeValue("\\boxed{}");
setExpChargeValue("\\boxed{}");
setRadiusValue("\\boxed{}");
setExpRadiusValue("\\boxed{}");
setResult("\\color{lightgray}{\\boxed{}}");
}}
/>
<Buttons
className="rounded-md bg-[#8eb5db] p-3 text-3xl text-[#474747] dark:bg-[#1d2231] dark:text-white"
value={"0"}
onClick={() => {
Change("0");
}}
/>
<Buttons
className="p-3 text-xl text-[#474747] dark:text-white"
value="Del"
onClick={() => {
Change("\\boxed{}");
}}
/>
<Buttons
value={
<ArrowLeftIcon className="mx-auto w-[20px] fill-[#47474783] dark:fill-[#1d2231] lg:w-[25px]" />
}
onClick={() =>
setSelectedIndex(selectedIndex == 0 ? 3 : selectedIndex - 1)
}
/>
<Buttons
value={
<PlusMinusIcon className="mx-auto w-[10px] fill-[#47474783] dark:fill-[#1d2231] lg:w-[15px]" />
}
onClick={() => {
ChangeSign();
}}
/>
<Buttons
value={
<ArrowRightIcon className="mx-auto w-[20px] fill-[#47474783] dark:fill-[#1d2231] lg:w-[25px]" />
}
onClick={() =>
setSelectedIndex(selectedIndex == 3 ? 0 : selectedIndex + 1)
}
/>
<Buttons
className="col-span-3 rounded-md bg-[#47474749] p-3 text-2xl dark:bg-[#453a499f]"
value={
<EqualsIcon className="mx-auto w-[20px] fill-[#474747] dark:fill-[#1d2231] lg:w-[25px]" />
}
onClick={() => {
if (
Charge.length <= 2 &&
ExpCharge.length <= 2 &&
Radius.length <= 2 &&
ExpRadius.length <= 2
) {
setResult(CalcResult(Charge, ExpCharge, Radius, ExpRadius));
}
}}
/>
</section>
</div>
);
};
export default Calculator;
|
import type { NextApiRequest, NextApiResponse } from "next";
import loadStytch from "@/lib/loadStytch";
import {
SESSION_DURATION_MINUTES,
setIntermediateSession,
setSession,
} from "@/lib/sessionService";
const stytchClient = loadStytch();
export async function handler(req: NextApiRequest, res: NextApiResponse) {
const slug = req.query.slug;
try {
const exchangeResult = await exchangeToken(req);
// TODO: Should we return the slug here?
if (exchangeResult.kind === "login") {
setSession(req, res, exchangeResult.token);
return res.redirect(307, `/${slug}/dashboard`);
} else {
setIntermediateSession(req, res, exchangeResult.token);
return res.redirect(307, `/select-organization`);
}
} catch (error) {
console.error("Could not authenticate in callback", error);
return res.redirect(307, "/");
}
}
type ExchangeResult = { kind: "discovery" | "login"; token: string };
async function exchangeToken(req: NextApiRequest): Promise<ExchangeResult> {
if (
req.query.stytch_token_type === "multi_tenant_magic_links" &&
req.query.token
) {
return await handleMagicLinkCallback(req);
}
if (req.query.stytch_token_type === "sso" && req.query.token) {
return await handleSSOCallback(req);
}
if (req.query.stytch_token_type === "discovery" && req.query.token) {
return await handleEmailMagicLinksDiscoveryCallback(req);
}
if (req.query.stytch_token_type === "discovery_oauth" && req.query.token) {
return await handleOAuthDiscoveryCallback(req);
}
if (req.query.stytch_token_type === "oauth" && req.query.token) {
return await handleOAuthCallback(req);
}
console.log("No token found in req.query", req.query);
throw Error("No token found");
}
async function handleMagicLinkCallback(
req: NextApiRequest
): Promise<ExchangeResult> {
const authRes = await stytchClient.magicLinks.authenticate({
magic_links_token: req.query.token as string,
session_duration_minutes: SESSION_DURATION_MINUTES,
});
return {
kind: "login",
token: authRes.session_jwt as string,
};
}
async function handleSSOCallback(req: NextApiRequest): Promise<ExchangeResult> {
const authRes = await stytchClient.sso.authenticate({
sso_token: req.query.token as string,
session_duration_minutes: SESSION_DURATION_MINUTES,
});
return {
kind: "login",
token: authRes.session_jwt as string,
};
}
async function handleEmailMagicLinksDiscoveryCallback(
req: NextApiRequest
): Promise<ExchangeResult> {
const authRes = await stytchClient.magicLinks.discovery.authenticate({
discovery_magic_links_token: req.query.token as string,
});
return {
kind: "discovery",
token: authRes.intermediate_session_token as string,
};
}
async function handleOAuthDiscoveryCallback(
req: NextApiRequest
): Promise<ExchangeResult> {
const authRes = await stytchClient.oauth.discovery.authenticate({
discovery_oauth_token: req.query.token as string,
});
return {
kind: "discovery",
token: authRes.intermediate_session_token as string,
};
}
async function handleOAuthCallback(
req: NextApiRequest
): Promise<ExchangeResult> {
const authRes = await stytchClient.oauth.authenticate({
oauth_token: req.query.token as string,
session_duration_minutes: SESSION_DURATION_MINUTES,
});
return {
kind: "login",
token: authRes.session_jwt as string,
};
}
export default handler;
|
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <signal.h>
#include <filesystem>
#include "util.h"
#include "log.h"
#include "fiber.h"
namespace DW{
Logger::ptr g_logger = DW_LOG_NAME("system");
uint32_t GetThreadId(){
return (pid_t)syscall(__NR_gettid);
}
uint32_t GetFiberId(){
//return 0;
return Fiber::GetFiberId();
}
void Backtrace(std::vector<std::string>& bt, int size, int skip) {
//堆上创建空间
void** array = (void**)malloc((sizeof(void*) * size));
size_t s = ::backtrace(array, size);
char** strings = backtrace_symbols(array, s);
if(strings == nullptr) {
DW_LOG_ERROR(g_logger, __FILE__, __LINE__, TOSTRING("backtrace_synbols error"));
free(array);
return;
}
for(size_t i = skip; i < s; ++i) {
bt.push_back(strings[i]);
}
free(strings);
free(array);
}
std::string BacktraceToString(int size, int skip, const std::string& prefix) {
std::vector<std::string> bt;
Backtrace(bt, size, skip);
std::stringstream ss;
for(size_t i = 0; i < bt.size(); ++i) {
ss << prefix << bt[i] << std::endl;
}
return ss.str();
}
uint64_t GetCurrentMS() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000ul + tv.tv_usec / 1000;
}
uint64_t GetCurrentUS() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000 * 1000ul + tv.tv_usec;
}
std::string Time2Str(time_t ts, const std::string& format) {
struct tm tm;
localtime_r(&ts, &tm);
char buf[64];
strftime(buf, sizeof(buf), format.c_str(), &tm);
return buf;
}
time_t Str2Time(const char* str, const char* format) {
struct tm t;
memset(&t, 0, sizeof(t));
if(!strptime(str, format, &t)) {
return 0;
}
return mktime(&t);
}
static int __lstat(const char* file, struct stat* st = nullptr) {
struct stat lst;
int ret = lstat(file, &lst);
if(st) {
*st = lst;
}
return ret;
}
static int __mkdir(const char* dirname) {
if(access(dirname, F_OK) == 0) {
return 0;
}
return mkdir(dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
void FSUtil::ListAllFile(std::vector<std::string>& files
,const std::string& path
,const std::string& subfix) {
for(auto& p: std::filesystem::recursive_directory_iterator(path)){
if(p.is_regular_file() && p.path().extension() == subfix){
files.push_back(p.path());
}
}
// if(access(path.c_str(), 0) != 0) {
// return;
// }
// DIR* dir = opendir(path.c_str());
// if(dir == nullptr) {
// return;
// }
// struct dirent* dp = nullptr;
// while((dp = readdir(dir)) != nullptr) {
// if(dp->d_type == DT_DIR) {
// if(!strcmp(dp->d_name, ".")
// || !strcmp(dp->d_name, "..")) {
// continue;
// }
// ListAllFile(files, path + "/" + dp->d_name, subfix);
// } else if(dp->d_type == DT_REG) {
// std::string filename(dp->d_name);
// if(subfix.empty()) {
// files.push_back(path + "/" + filename);
// } else {
// if(filename.size() < subfix.size()) {
// continue;
// }
// if(filename.substr(filename.length() - subfix.size()) == subfix) {
// files.push_back(path + "/" + filename);
// }
// }
// }
// }
// closedir(dir);
}
bool FSUtil::IsRunningPidfile(const std::string& pidfile) {
if(__lstat(pidfile.c_str()) != 0) {
return false;
}
std::ifstream ifs(pidfile);
std::string line;
if(!ifs || !std::getline(ifs, line)) {
return false;
}
if(line.empty()) {
return false;
}
pid_t pid = atoi(line.c_str());
if(pid <= 1) {
return false;
}
if(kill(pid, 0) != 0) {
return false;
}
return true;
}
bool FSUtil::Mkdir(const std::string& dirname) {
if(__lstat(dirname.c_str()) == 0) {
return true;
}
char* path = strdup(dirname.c_str());
char* ptr = strchr(path + 1, '/');
do {
for(; ptr; *ptr = '/', ptr = strchr(ptr + 1, '/')) {
*ptr = '\0';
if(__mkdir(path) != 0) {
break;
}
}
if(ptr != nullptr) {
break;
} else if(__mkdir(path) != 0) {
break;
}
free(path);
return true;
} while(0);
free(path);
return false;
}
bool FSUtil::Unlink(const std::string& filename, bool exist) {
if(!exist && __lstat(filename.c_str())) {
return true;
}
return ::unlink(filename.c_str()) == 0;
}
bool FSUtil::Rm(const std::string& path) {
struct stat st;
if(lstat(path.c_str(), &st)) {
return true;
}
if(!(st.st_mode & S_IFDIR)) {
return Unlink(path);
}
DIR* dir = opendir(path.c_str());
if(!dir) {
return false;
}
bool ret = true;
struct dirent* dp = nullptr;
while((dp = readdir(dir))) {
if(!strcmp(dp->d_name, ".")
|| !strcmp(dp->d_name, "..")) {
continue;
}
std::string dirname = path + "/" + dp->d_name;
ret = Rm(dirname);
}
closedir(dir);
if(::rmdir(path.c_str())) {
ret = false;
}
return ret;
}
bool FSUtil::Mv(const std::string& from, const std::string& to) {
if(!Rm(to)) {
return false;
}
return rename(from.c_str(), to.c_str()) == 0;
}
bool FSUtil::Realpath(const std::string& path, std::string& rpath) {
if(__lstat(path.c_str())) {
return false;
}
char* ptr = ::realpath(path.c_str(), nullptr);
if(nullptr == ptr) {
return false;
}
std::string(ptr).swap(rpath);
free(ptr);
return true;
}
bool FSUtil::Symlink(const std::string& from, const std::string& to) {
if(!Rm(to)) {
return false;
}
return ::symlink(from.c_str(), to.c_str()) == 0;
}
std::string FSUtil::Dirname(const std::string& filename) {
if(filename.empty()) {
return ".";
}
auto pos = filename.rfind('/');
if(pos == 0) {
return "/";
} else if(pos == std::string::npos) {
return ".";
} else {
return filename.substr(0, pos);
}
}
std::string FSUtil::Basename(const std::string& filename) {
if(filename.empty()) {
return filename;
}
auto pos = filename.rfind('/');
if(pos == std::string::npos) {
return filename;
} else {
return filename.substr(pos + 1);
}
}
bool FSUtil::OpenForRead(std::ifstream& ifs, const std::string& filename
,std::ios_base::openmode mode) {
ifs.open(filename.c_str(), mode);
return ifs.is_open();
}
bool FSUtil::OpenForWrite(std::ofstream& ofs, const std::string& filename
,std::ios_base::openmode mode) {
ofs.open(filename.c_str(), mode);
if(!ofs.is_open()) {
std::string dir = Dirname(filename);
Mkdir(dir);
ofs.open(filename.c_str(), mode);
}
return ofs.is_open();
}
}
|
import { ObjectId } from 'mongodb';
import { getCollection } from '../common';
import type * as Types from './config.types';
export const find = async <C extends object>(id: string) => {
const collection = await getCollection<Types.ConfigData<C, ObjectId>>({
db: 'data-forge',
collection: 'config',
});
return collection.findOne({
_id: { $eq: new ObjectId(id) },
});
};
export const upsert = async <C>({
_id: id,
content,
}: Types.ConfigData<C, string>) => {
const timestamp = new Date().toISOString();
const collection = await getCollection<Types.ConfigData<C, ObjectId>>({
db: 'data-forge',
collection: 'config',
});
const result = await collection.updateOne(
{ _id: { $eq: new ObjectId(id) } },
{ $set: { _id: new ObjectId(id), content, timestamp } },
{ upsert: true }
);
return {
_id: result.upsertedId,
content,
timestamp,
} as Types.ConfigData<C, ObjectId>;
};
export const remove = async <C>(id: string) => {
const collection = await getCollection<Types.ConfigData<C, ObjectId>>({
db: 'data-forge',
collection: 'config',
});
return collection.deleteOne({
_id: { $eq: new ObjectId(id) },
});
};
|
import { useState, useEffect } from "react";
import { Route, Routes, Navigate } from "react-router-dom";
import ChatroomPage from "./pages/ChatroomPage";
import DashboardPage from "./pages/DashboardPage";
import IndexPage from "./pages/IndexPage";
import LoginPage from "./pages/LoginPage";
import RegisterPage from "./pages/RegisterPage";
import { io } from "socket.io-client";
import "./styles/common.css";
import makeToast from "./Toaster";
function App() {
const [socket, setSocket] = useState(null);
const setupSocket = () => {
const token = localStorage.getItem("token");
if (token && token.length > 0 && !socket) {
const socketConn = io("http://localhost:5000", {
transports: ["websocket"],
query: {
token: localStorage.getItem("token"),
},
});
socketConn.on("disconnect", () => {
setSocket(null);
setTimeout(setupSocket, 3000);
makeToast("error", "Socket Disconnected!");
});
socketConn.on("connect", socket => {
makeToast("success", "Socket Connected!");
});
setSocket(socketConn);
}
};
useEffect(() => {
setupSocket();
}, []);
const token = localStorage.getItem("token");
let isLoggedIn;
if (token) {
isLoggedIn = true;
} else {
isLoggedIn = false;
}
return (
<Routes>
<Route path="/" element={<IndexPage />} exact />
<Route
path="/login"
// render={() =>
// isLoggedIn ? (
// <Navigate to="/dashboard" />
// ) : (
// <LoginPage setupSocket={setSocket} />
// )
// }
element={
isLoggedIn ? (
<Navigate to="/dashboard" /> // Navigate is used in place of Redirect
) : (
<LoginPage setupSocket={setupSocket} />
)
}
exact
/>
<Route
path="/register"
element={isLoggedIn ? <Navigate to="/dashboard" /> : <RegisterPage />}
exact
/>
<Route
path="/dashboard"
element={
isLoggedIn ? (
<DashboardPage socket={socket} />
) : (
<Navigate to="/login" />
)
}
exact
/>
<Route
path="/chatroom/:id"
element={
isLoggedIn ? (
<ChatroomPage socket={socket} />
) : (
<Navigate to="/login" />
)
}
exact
/>
</Routes>
);
}
export default App;
|
/*
* Copyright 2008-2009 Xebia and the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.xebia.exercice.spring;
import fr.xebia.exercice.ActionValorisateur;
import fr.xebia.exercice.OptionValorisateur;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import java.util.Date;
@Configurable
class Option implements Titre {
@Autowired
SpringMarketdataRepository marketdataRepository;
@Autowired
OptionValorisateur optionValorisateur;
@Autowired
ActionValorisateur actionValorisateur;
final Integer id;
final Date dateExercice;
final double prixExercice;
final Action sousJacent;
public Option(Integer id, double prixExercice, Date dateExercice, Action sousJacent) {
this.id = id;
this.prixExercice = prixExercice;
this.dateExercice = dateExercice;
this.sousJacent = sousJacent;
}
@Override
public double valorise() {
double prixAction = marketdataRepository.getFixing(sousJacent.id);
double valoAction = actionValorisateur.valoriseAction(prixAction);
double vol = marketdataRepository.getVolatilite(sousJacent.id);
double taux = marketdataRepository.getTaux(id);
return optionValorisateur.valorise(dateExercice, prixExercice, valoAction, vol, taux);
}
}
|
---
title: '[全般] ([データソースのプロパティ] ダイアログボックス) (レポートビルダー) |Microsoft Docs'
ms.custom: ''
ms.date: 06/13/2017
ms.prod: sql-server-2014
ms.reviewer: ''
ms.technology: reporting-services-native
ms.topic: conceptual
f1_keywords:
- "10018"
ms.assetid: b956f43a-8426-4679-acc1-00f405d5ff5b
author: maggiesMSFT
ms.author: maggies
manager: kfile
ms.openlocfilehash: dcfba8346a3519817a36c21b24be1a91a613e098
ms.sourcegitcommit: ad4d92dce894592a259721a1571b1d8736abacdb
ms.translationtype: MT
ms.contentlocale: ja-JP
ms.lasthandoff: 08/04/2020
ms.locfileid: "87631660"
---
# <a name="data-source-properties-dialog-box-general-report-builder"></a>[全般] ([データ ソースのプロパティ] ダイアログ ボックス) (レポート ビルダー)
レポート サーバーから共有データ ソースを選択する場合や、レポートに埋め込まれたデータ ソースの接続情報を作成または変更する場合は、 **[データ ソースのプロパティ]** ダイアログ ボックスの **[全般]** を選択します。
データ ソースへの接続に使用される資格情報の種類は、データ ソースのプロパティで指定します。 レポート サーバーからレポートを開く場合、データ ソースのプロパティに指定された実行時の資格情報は、クエリの作成やレポートのプレビューなどのデザイン時のタスクでは有効でない可能性があります。 たとえば、データ ソースで、自分以外の Windows 資格情報や知らないユーザーのユーザー名とパスワードが使用されることがあります。
レポート ビルダーでは、データ ソースのプロパティに指定された資格情報を使用してデータ ソースに接続できない場合、 **[データ ソースの資格情報の入力]** ダイアログ ボックスが開きます。 通常、これは次の場合に発生します。
- データ ソースが資格情報を要求するように構成されている。
- データ ソースが、保存されている資格情報を使用するように構成されている。 潜在的なセキュリティ上の脅威を最小限に抑えるために、レポート ビルダーは、サーバー上に保存された資格情報を取得しないように設計されています。
**[データ ソースの資格情報の入力]** ダイアログ ボックスを使用すると、デザイン時にレポート ビルダーによって使用された資格情報を変更して、現在の Windows ユーザーとしてデータ ソースに接続したり、ユーザー名とパスワードを入力したりできます。 ユーザー名とパスワードを入力する場合、それらを Windows 資格情報として使用するかどうかを指定できます。
> [!NOTE]
> クエリ デザイナーではデザイン時の資格情報に別の種類の資格情報を指定できますが、レポートのプレビューではデータ ソースに指定されている既存の資格情報オプションのユーザー名とパスワードしか入力できません。
**[接続テスト]** をクリックすると、データ ソースのプロパティの [資格情報] ページで指定された資格情報を使用して、データ ソースへの接続がテストされます。 埋め込みデータ ソースと共有データ ソースへの接続をテストできます。
パスワードが必要など、指定された資格情報が不完全な場合、レポート ビルダーでは、データ ソースへの接続が必要なときに、実行時の資格情報の入力を再度要求します。 デザイン時の資格情報は保存されるため、入力を再度要求されることはありません。
## <a name="options"></a>Options
**名前**
データ ソースの名前を入力します。 データ ソース名はレポート内で一意である必要があります。 既定では、DataSource1 または DataSource2 などの一般的な名前がデータ ソースに割り当てられます。
**[共有接続を使用する]**
レポート サーバーにパブリッシュされた共有データ ソースを参照する場合は、このオプションを選択します。
レポート サーバーからデータ ソースを選択した後は、レポート ビルダーによってこのレポート サーバーへの接続が維持されます。
**[レポートに埋め込まれた接続を使用する]**
このレポートでのみ使用されるデータ ソースを作成する場合は、このオプションを選択します。
**Type**
データ処理拡張機能を選択します。 一覧には、登録されているすべての拡張機能が表示されます。
**接続文字列**
データ ソースの接続文字列を入力します。 **[構築]** をクリックして、 **[接続のプロパティ]** ダイアログ ボックスで接続文字列を生成します。 式を編集するには、 **式** (*[fx]*) ボタンをクリックします。
**[クエリの処理時に単一のトランザクションを使用する]**
このデータ ソースを使用するデータセットが、データベースに対する単一のトランザクションで処理されるように指定する場合は、このオプションを選択します。 同じデータ ソースを使用するサブレポートのトランザクションを含めるには、そのサブレポートを選択し、[プロパティ] ペインで **[MergeTransactions]** を **[True]** に設定します。
**[接続テスト]**
指定された資格情報を使用してデータ ソースに接続できるかどうかを確認する場合にクリックします。 接続できない場合は、資格情報と、サーバーが使用できるかどうかを確認する必要があります。 埋め込みデータ ソースと共有データ ソースへのデータ ソース接続をテストできます。
## <a name="see-also"></a>参照
[レポート (レポートビルダーおよび SSRS)にデータを追加する](report-data/report-datasets-ssrs.md)
[データ接続またはデータソース (レポートビルダーと SSRS)に追加して検証する](report-data/add-and-verify-a-data-connection-report-builder-and-ssrs.md)
[レポートビルダーのデータ接続、データソース、および接続文字列](../../2014/reporting-services/data-connections-data-sources-and-connection-strings-in-report-builder.md)
[[データソースのプロパティ] ダイアログボックスの [資格情報 (レポートビルダー)](../../2014/reporting-services/data-source-properties-dialog-box-credentials-report-builder.md)
[レポート ビルダーのダイアログ ボックス、ペイン、およびウィザードに関するヘルプ](../../2014/reporting-services/report-builder-help-for-dialog-boxes-panes-and-wizards.md)
|
-- inserción de datos:
-- ¿cómo se agregaría un nuevo documento a la base de datos, asegurando que se vincule correctamente con la colección correspondiente?
insert into collection (id_collection, id_room, name_collection, description_collection)
values ('', '', 'colección de historia de cuba', 'libros y documentos sobre la historia de cuba'),
('', '', 'colección de literatura infantil', 'libros de cuentos y novelas para niños'),
('', '', 'colección de música cubana', 'partituras y grabaciones de música cubana'),
('', '', 'colección de arte cubano', 'libros y catálogos de arte cubano');
insert into collection_document (id_collection, id_document)
values (1, 1),
(2, 2),
(3, 3);
insert into "document" (title, created_at, editorial, publication_place, language, format, subject,
summary, is_patrimony, note, type_document)
values ('historia de cuba', '2023-01-01', 'editorial nacional', 'la habana', 'es', 'physical', 'historia',
'un libro sobre la historia de cuba', false, 'book'),
('cuentos para niños', '2023-01-01', 'editorial nacional', 'la habana', 'es', 'physical', 'literatura infantil',
'un libro de cuentos para niños', false, 'el libro esta parcialmente danado', 'book'),
('música cubana', '2023-01-01', 'editorial musical', 'la habana', 'es', 'digital', 'música',
'una grabación de música cubana', false, 'music');
-- ¿cuál sería el proceso para registrar un nuevo autor junto con su respectivo documento?
insert into "author" (name_author, country_author, description_author)
values ('josé martí', 'cuba',
'josé martí was a cuban poet, essayist, and journalist who became a key figure in the fight for cuba''s' ||
' independence from spanish rule. his literary works and political writings had a profound impact on the ' ||
'cultural and political landscape of cuba.'),
('alejo carpentier', 'estados unidos',
'alejo carpentier, born in cuba and later residing in various countries ' ||
'including the united states, was a prominent novelist and musicologist. ' ||
'his works, often associated with magical realism, explore the rich cultural history of latin america'),
('nicolás guillén', 'cuba',
'nicolás guillén, a renowned cuban poet, is considered one of the founders of afro-cuban poetry. ' ||
'his writings often reflect themes of social justice, identity, and the afro-cuban experience, ' ||
'making him a significant figure in caribbean literature'),
('dulce maría loynaz', 'cuba', 'dulce maría loynaz, a cuban poet and narrative writer, was known ' ||
'for her eloquent and introspective works. she received acclaim for ' ||
'her poetic exploration of human emotions and the complexities of the human experience'),
('reinaldo arenas', 'argentina',
'reinaldo arenas, originally from cuba and later exiled to the united states, ' ||
'was a novelist and poet. his works often dealt with themes of freedom, ' ||
'oppression, and his personal experiences, providing a powerful voice against ' ||
'censorship and political persecution.');
insert into document (title, created_at, editorial, publication_place, language, format, subject, summary, is_patrimony,
note, type_document)
values ('cien años de soledad', '1967-05-30', 'editorial sudamericana', 'buenos aires', 'es', 'physical',
'fiction',
'one hundred years of solitude is a landmark novel that tells the multi-generational story of the buendía family in the fictional town of macondo.',
false, 'classic of latin american literature', 'book'),
('guantanamera', '1995-09-01', 'columbia records', 'new york', 'es', 'digital', 'music',
'guantanamera is a famous cuban song, and in this recording, it is performed by celia cruz. the song is a symbol of cuban culture and has gained international recognition.',
false, 'iconic cuban music', 'music'),
('the kingdom of this world', '1949-01-01', 'faber and faber', 'london', 'en', 'physical',
'historical fiction',
'the kingdom of this world, written by alejo carpentier, is a novel that explores the history of haiti and the haitian revolution. carpentier is known for his use of magical realism in literature.',
false, 'magical realism in historical context', 'book'),
('motivational speech', '2022-06-15', 'self-published', 'online', 'en', 'digital', 'motivation',
'a powerful motivational speech by josé martí, encouraging individuals to strive for freedom, justice, and self-improvement.',
false, 'inspiring words for personal growth', 'media'),
('selected poems', '1964-10-20', 'university of minnesota press', 'minneapolis', 'en', 'physical', 'poetry',
'nicolás guillén, one of the most significant poets in cuban literature, presents a collection of his selected poems that reflect his commitment to social justice and the afro-cuban experience.',
true, 'legacy of afro-cuban poetry', 'book');
insert into author_document (id_author, id_document)
values (1, 1), -- josé martí and cien años de soledad
(2, 2), -- alejo carpentier and guantanamera
(2, 3), -- alejo carpentier and the kingdom of this world
(1, 4), -- josé martí and motivational speech
(3, 5);
-- eliminación de datos:
-- ¿cómo se eliminaría un miembro de la biblioteca, considerando todas las tablas relacionadas, como préstamos y servicios asociados?
insert into member (id_member, name, age, country, category)
values (10000000, 'maria rodriguez', 32, 'cuba', 'researcher'),
(20000000, 'john smith', 25, 'united states', 'student'),
(30000000, 'anna lee', 40, 'cuba', 'professional');
insert into researcher (id_member)
values (10000000);
insert into professional (id_member, organization)
values (30000000, 'organizacion');
insert into student (id_member, school)
values (30000000, 'university of arts');
delete
from member
where name in ('maria rodriguez', 'john smith', 'anna lee');
alter table researcher
drop constraint fk_member;
alter table researcher
add constraint fk_member
foreign key (id_member) references member (id_member) on delete cascade;
alter table professional
drop constraint fk_member;
alter table professional
add constraint fk_member
foreign key (id_member) references member (id_member) on delete cascade;
alter table student
drop constraint fk_member;
alter table student
add constraint fk_member
foreign key (id_member) references member (id_member) on delete cascade;
-- actualización de datos:
-- ¿cómo se actualizaría la información de una sala, incluyendo su descripción y ubicación?
insert into room (id_room, id_library, name_room, location_room, description_room, access_method, phone_extension)
values ('abc 1234-5678-0', 1, 'sala de lectura', 'planta baja', 'sala principal para la lectura de libros',
'member card', 1234);
update room
set description_room = 'nueva descripción',
location_room = 'nueva ubicación'
where id_room = 'abc 1234-5678-9';
-- ¿cuál sería el procedimiento para modificar la información de un préstamo en curso, como cambiar el estado o la fecha de devolución?
-- insertamos un servicio
insert into service (id_service, description_service, type_service)
values (10000000, 'préstamo de libros', 'loan');
-- insertamos un documento
insert into document (id_document, title, created_at, editorial, publication_place, language, format, subject, summary,
is_patrimony,
note, type_document)
values (10000000, 'el quijote', '1605-01-01', 'francisco de robles', 'madrid', 'español', 'digital', 'novela',
'resumen de el quijote', false, 'nota sobre el quijote', 'book');
-- insertamos un préstamo
insert into loan (id_service, id_document, term, start_date, end_date, status, type_loan)
values (10000000, 10000000, 30, '2023-11-28', '2023-12-28', 'approved', 'loan_member');
update loan
set status = 'in-loan'
where id_service = 10000000
and id_document = 10000000;
-- consulta de datos:
-- ¿cuál es la lista de documentos disponibles en una colección específica?
insert into collection (id_collection, id_room, name_collection, description_collection)
values ('aaa-1111', 'abc 1234-5678-9', 'colección de historia de cuba',
'libros y documentos sobre la historia de cuba');
insert into "document" (id_document, title, created_at, editorial, publication_place, language, format, subject,
summary, is_patrimony, note, type_document)
values (10000001, 'doc', '2023-01-01', 'editorial nacional', 'la habana', 'es', 'physical', 'historia',
'un libro sobre la historia de cuba', false, 'note', 'book');
insert into collection_document (id_collection, id_document)
values ('aaa-1111', 10000001);
select *
from document
join collection_document on document.id_document = collection_document.id_document
join collection on collection_document.id_collection = collection.id_collection
where collection.name_collection = 'colección de historia de cuba'
order by name_collection
limit 10;
-- ¿cómo se obtendrían los detalles de un préstamo en particular, incluyendo su estado y fechas asociadas?
select *
from loan
where id_service = 10000000
and id_document = 10000000;
-- ¿cuál es la cantidad de documentos disponibles en formato digital en toda la biblioteca?
select count(*)
from document
where format = 'digital';
|
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/",
name: "home",
component: () => import("@/views/HomeView.vue"),
},
{
path: "/courses",
name: "courses",
component: () => import("@/views/CoursesView.vue"),
},
{
path: "/auth",
name: "auth",
component: () => import("@/views/AuthView.vue"),
children: [
{
path: "/auth/login",
name: "login",
component: () => import("@/views/LoginView.vue"),
},
{
path: "/auth/login/by-email",
name: "login-by-email",
component: () => import("@/views/LoginByEmailView.vue"),
},
{
path: "/auth/register",
name: "register",
component: () => import("@/views/RegisterView.vue"),
},
{
path: "/auth/register/by-email",
name: "register-by-email",
component: () => import("@/views/RegisterByEmailView.vue"),
},
],
},
{
path: "/:pathMatch(.*)*",
name: "error",
component: () => import("@/views/ErrorView.vue"),
},
],
});
export default router;
|
# Python - Everything is Object
This project delves into Python's object model, exploring the intricacies of objects, references, and mutability. It aims to deepen the understanding of how Python handles different types of objects and the implications of these mechanisms on Python programming.
## Background Context
This project emphasizes the concept that everything in Python is an object. It challenges preconceived notions about variable assignment, mutability, and object identity in Python through a series of questions and tasks. The project encourages a deeper understanding by discouraging the immediate use of the Python interpreter to answer questions, promoting critical thinking and research instead.
## Resources
**Read or Watch:**
- [9.10. Objects and values](https://docs.python.org/3/tutorial/classes.html#objects-and-values)
- [9.11. Aliasing](https://docs.python.org/3/tutorial/classes.html#aliasing)
- [Immutable vs mutable types](https://docs.python.org/3/glossary.html#term-immutable)
- [Mutation](https://docs.python.org/3/tutorial/classes.html#odds-and-ends)
- [9.12. Cloning lists](https://docs.python.org/3/tutorial/classes.html#copying-lists)
- [Python tuples: immutable but potentially changing](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)
## Learning Objectives
After completing this project, you should be able to explain:
- What an object is in Python
- The difference between a class and an object or instance
- The difference between immutable and mutable objects
- What a reference is, and how assignment works in Python
- The concept of aliasing and its implications
- How to check if two variables are identical
- How to check if two variables are linked to the same object
- How to display the variable identifier (memory address in CPython)
- The distinction between mutable and immutable objects
- The built-in mutable and immutable types in Python
- How Python passes variables to functions
## Requirements
### Python Scripts
- Use Python 3.8.5, with all scripts starting with `#!/usr/bin/python3`.
- Follow PEP 8 styling (version 2.7.*).
- Include a `README.md` at the root of the project directory.
- Ensure all files are executable.
### .txt Answer Files
- Provide answers in one line, with no shebang, and ending with a new line.
## Tasks
The tasks in this project involve answering questions about Python’s object model, including object identity, mutability, and cloning lists. Answers should be provided in `.txt` files, with each task focusing on different aspects of Python's handling of objects.
### Highlights:
- **Who am I?**: Identifying functions for printing the type of an object.
- **Where are you?**: Understanding how to get the variable identifier.
- **List append vs. add**: Exploring the difference between appending to a list and adding lists.
- **Mutable vs. Immutable objects**: Distinguishing between mutable and immutable objects in Python.
## Additional Information
This project encourages a deep dive into Python's object model, promoting an understanding of how Python manages memory and handles variable assignment and modification. It's crucial for Python developers to grasp these concepts to write efficient, effective, and predictable code.
|
import { produce } from "immer";
import { createAction, handleActions } from "redux-actions";
import { todoArray, todoObject } from "types";
const ADD_TODO = "todos/ADD_TODO" as const;
const REMOVE_TODO = "todos/REMOVE_TODO" as const;
const TOGGLE_TODO = "todos/TOGGLE_TODO" as const;
export const addTodo = createAction(ADD_TODO);
export const removeTodo = createAction(REMOVE_TODO);
export const toggleTodo = createAction(TOGGLE_TODO);
export type TodoAction =
| ReturnType<typeof addTodo>
| ReturnType<typeof removeTodo>
| ReturnType<typeof toggleTodo>;
const initialState: todoArray = [];
const todos = handleActions(
{
[ADD_TODO]: (state = initialState, action: TodoAction) => {
return produce(state, (draft: todoArray) => {
draft.unshift({ text: action.payload, id: Date.now(), done: false });
});
},
[REMOVE_TODO]: (state = initialState, action: TodoAction) => {
return produce(state, (draft: todoArray) => {
const index = draft.findIndex((todo: todoObject) => {
return todo.id === action.payload;
});
draft.splice(index, 1);
});
},
[TOGGLE_TODO]: (state = initialState, action: TodoAction) => {
return produce(state, (draft: todoArray) => {
draft.map((todo: todoObject) => {
if (todo.id === action.payload) {
todo.done = !todo.done;
}
});
});
},
},
initialState,
);
export default todos;
|
/***************************************************************************
* NelderimGuard.cs
* -------------------
* Nelderim rel. Piencu 1.0
* http:\\nelderim.org
*
***************************************************************************/
using System;
using System.Collections;
using System.Text.RegularExpressions;
using Server;
using Server.Mobiles;
using Server.ContextMenus;
using Server.Gumps;
using Server.Items;
using Server.Nelderim;
using System.Reflection;
namespace Server.Mobiles
{
public enum GuardType
{
StandardGuard,
ArcherGuard,
HeavyGuard,
MageGuard,
MountedGuard,
EliteGuard,
SpecialGuard
}
public enum WarFlag
{
None,
White,
Black,
Red,
Green,
Blue
}
public class BaseNelderimGuard : BaseCreature
{
private bool m_ConfiguredAccordingToRegion;
private GuardType m_Type;
private string m_RegionName;
private WarFlag m_Flag;
private WarFlag m_Enemy;
private string m_IsEnemyFunction;
[CommandProperty( AccessLevel.Counselor, AccessLevel.GameMaster )]
public string HomeRegionName
{
get
{
return m_RegionName;
}
set
{
m_RegionName = value;
try
{
if ( !RegionsEngine.MakeGuard( this, m_RegionName ) )
m_RegionName = null;
}
catch ( Exception e )
{
Console.WriteLine( e.ToString() );
m_RegionName = null;
}
}
}
public bool IsEnemyOfSpider(Mobile m)
{
// Nie atakuj innych straznikow (obszarowka moze triggerowac walke miedzy nimi)
if (m is BaseNelderimGuard)
return false;
// nie atakuj drowow i obywatelow drowiego miasta
if (BaseAI.IsSpidersFriend(m))
return false;
// atakuj wszystkich graczy
if (m is PlayerMobile)
return true;
if (m is BaseCreature)
{
BaseCreature bc = m as BaseCreature;
// atakuj stworzenia red/krim
if (bc.AlwaysMurderer || bc.Criminal || (!bc.Controlled && bc.FightMode == FightMode.Closest))
return true;
// atakuj pety i przywolance graczy
if ((bc.Controlled && bc.ControlMaster != null && bc.ControlMaster.AccessLevel < AccessLevel.Counselor) ||
(bc.Summoned && bc.SummonMaster != null && bc.SummonMaster.AccessLevel < AccessLevel.Counselor))
return true;
}
return false;
}
public bool IsEnemyOfDefaultGuard(Mobile m)
{
if ( m == null )
return false;
// 07.11.2012 :: zombie :: tymczasowo
if ( m is BaseNelderimGuard )
return false;
// zombie
if ( m.Criminal || m.Kills >= 5 )
return true;
if ( WarOpponentFlag != WarFlag.None && WarOpponentFlag == ( m as BaseNelderimGuard ).WarSideFlag )
return true;
if ( m is BaseCreature )
{
BaseCreature bc = m as BaseCreature;
if ( bc.AlwaysMurderer || ( !bc.Controlled && bc.FightMode == FightMode.Closest ) )
return true;
if ( ( bc.Controlled && bc.ControlMaster != null && bc.ControlMaster.AccessLevel < AccessLevel.Counselor && ( bc.ControlMaster.Criminal || bc.ControlMaster.Kills >= 5 ) ) ||
( bc.Summoned && bc.SummonMaster != null && bc.SummonMaster.AccessLevel < AccessLevel.Counselor && ( bc.SummonMaster.Criminal || bc.SummonMaster.Kills >= 5 ) ) )
return true;
}
return false;
}
public override bool IsEnemy(Mobile m)
{
if (String.IsNullOrEmpty(m_IsEnemyFunction))
{
if (m_ConfiguredAccordingToRegion)
{
// no IsEnemy configuration in region data, set the default behaviour
return IsEnemyOfDefaultGuard(m);
}
else
{
try
{
GuardEngine guardEngine = RegionsEngine.GetGuardEngine(Type, Region.Name);
if (guardEngine != null)
{
m_IsEnemyFunction = guardEngine.IsEnemyFunction;
}
m_ConfiguredAccordingToRegion = true;
}
catch(Exception e)
{
Console.WriteLine("Error setting isEnemyFunction " + e.Message);
}
// region data not processed yet, set harmless behaviour to avoid undesirable attacks
// (this situation only occurs briefly right after guard spawn)
return false;
}
}
else
{
MethodInfo method = typeof(BaseNelderimGuard).GetMethod(m_IsEnemyFunction);
if (method != null)
{
// behaviour configured by region data
return (bool)method.Invoke(this, new[] { m });
}
else
{
// ERROR situation, fallback to default (IsEnemy configured by region data doesn't match any method of NelderimGuard class):
return IsEnemyOfDefaultGuard(m);
}
}
}
public override void CriminalAction( bool message )
{
// Straznik nigdy nie dostanie krima.
// Byl problem, ze gdy straznik atakowal peta/summona gracza-krima to sam dostawal krima.s
return;
}
[CommandProperty( AccessLevel.Counselor, AccessLevel.GameMaster )]
public WarFlag WarSideFlag
{
get { return m_Flag; }
set
{
m_Flag = value;
if ( m_Flag != WarFlag.None && m_Flag == m_Enemy )
m_Enemy = WarFlag.None;
}
}
[CommandProperty( AccessLevel.Counselor, AccessLevel.GameMaster )]
public WarFlag WarOpponentFlag
{
get { return m_Enemy; }
set
{
m_Enemy = value;
if ( m_Enemy != WarFlag.None && m_Flag == m_Enemy )
m_Flag = WarFlag.None;
}
}
public bool IsHuman
{
get { return BodyValue == 400 || BodyValue == 401; }
}
public BaseNelderimGuard( GuardType type ) : this( type, FightMode.Criminal )
{
}
public BaseNelderimGuard( GuardType type, FightMode fmode ) : base( AIType.AI_Melee, fmode, 12, 1, 0.1, 0.4 )
{
m_Type = type;
m_RegionName = null;
m_Flag = WarFlag.None;
m_Enemy = WarFlag.None;
ActiveSpeed = 0.05;
PassiveSpeed = 0.1;
switch (type)
{
case GuardType.MountedGuard:
RangePerception = 16;
AI = AIType.AI_Mounted;
PackGold( 40, 80 );
break;
case GuardType.ArcherGuard:
RangePerception = 16;
RangeFight = 6;
AI = AIType.AI_Archer;
PackGold( 30, 90 );
break;
case GuardType.EliteGuard:
RangePerception = 18;
AI = AIType.AI_Melee;
PackGold( 50, 100 );
break;
case GuardType.SpecialGuard:
RangePerception = 20;
AI = AIType.AI_Melee;
PackGold( 60, 100 );
break;
case GuardType.HeavyGuard:
RangePerception = 16;
AI = AIType.AI_Melee;
PackGold( 40, 80 );
break;
case GuardType.MageGuard:
RangePerception = 16;
AI = AIType.AI_Mage;
PackGold( 40, 80 );
break;
default:
PackGold( 20, 80 );
break;
}
Fame = 5000;
Karma = 5000;
new RaceTimer( this ).Start();
}
public BaseNelderimGuard(Serial serial) : base(serial)
{
}
public override bool AutoDispel{ get{ return true; } }
public override bool Unprovokable{ get{ return true; } }
public override bool Uncalmable{ get{ return true; } }
public override bool BardImmune{ get{ return true; } }
public override Poison PoisonImmune{ get{ return Poison.Greater; } }
public override bool HandlesOnSpeech( Mobile from )
{
return true;
}
public override bool ShowFameTitle
{
get
{
return false;
}
}
public override void AddWeaponAbilities()
{
WeaponAbilities.Add( WeaponAbility.Dismount, 0.2 );
WeaponAbilities.Add( WeaponAbility.BleedAttack, 0.2 );
}
public GuardType Type
{
get { return m_Type; }
}
[CommandProperty(AccessLevel.Counselor, AccessLevel.GameMaster)]
public string IsEnemyFunction
{
get { return m_IsEnemyFunction; }
set { m_IsEnemyFunction = value; }
}
[CommandProperty(AccessLevel.Counselor, AccessLevel.GameMaster)]
public bool ConfiguredAccordingToRegion
{
get { return m_ConfiguredAccordingToRegion; }
set { m_ConfiguredAccordingToRegion = value; }
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) 2);
// v 3
// writer.Write( (string) m_IsEnemyFunction );
// v 2
writer.Write( ( int ) m_Flag );
writer.Write( ( int ) m_Enemy );
// v 1
writer.Write( m_RegionName );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 3:
{
m_IsEnemyFunction = reader.ReadString();
goto case 2;
}
case 2:
{
m_Flag = (WarFlag)reader.ReadInt();
m_Enemy = (WarFlag)reader.ReadInt();
goto case 1;
}
case 1:
{
if (version < 2)
{
m_Flag = WarFlag.None;
m_Enemy = WarFlag.None;
}
m_RegionName = reader.ReadString();
break;
}
default:
{
if (version < 1)
m_RegionName = null;
break;
}
}
}
public override void GenerateLoot()
{
AddLoot( LootPack.Poor );
}
private class RaceTimer : Timer
{
private BaseNelderimGuard m_Target;
public RaceTimer( BaseNelderimGuard target ) : base( TimeSpan.FromMilliseconds( 250 ) )
{
m_Target = target;
Priority = TimerPriority.FiftyMS;
}
protected override void OnTick()
{
try
{
if (!m_Target.Deleted)
{
RegionsEngine.MakeGuard(m_Target);
}
}
catch ( Exception e )
{
Console.WriteLine( e.ToString() );
}
}
}
}
[CorpseName( "zwloki straznika" )]
public class StandardNelderimGuard : BaseNelderimGuard
{
[Constructable]
public StandardNelderimGuard() : base ( GuardType.StandardGuard ) {}
public StandardNelderimGuard(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) 0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[CorpseName( "zwloki straznika" )]
public class MageNelderimGuard : BaseNelderimGuard
{
public override void AddWeaponAbilities()
{
WeaponAbilities.Add( WeaponAbility.ParalyzingBlow, 0.225 );
WeaponAbilities.Add( WeaponAbility.Disarm, 0.225 );
}
[Constructable]
public MageNelderimGuard() : base( GuardType.MageGuard, FightMode.Criminal) { }
public MageNelderimGuard( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int)0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[CorpseName( "zwloki straznika" )]
public class HeavyNelderimGuard : BaseNelderimGuard
{
public override void AddWeaponAbilities()
{
WeaponAbilities.Add( WeaponAbility.WhirlwindAttack, 0.225 );
WeaponAbilities.Add( WeaponAbility.BleedAttack, 0.225 );
}
[Constructable]
public HeavyNelderimGuard() : base( GuardType.HeavyGuard, FightMode.Criminal) { }
public HeavyNelderimGuard( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int)0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[CorpseName( "zwloki straznika" )]
public class MountedNelderimGuard : BaseNelderimGuard
{
public override void AddWeaponAbilities()
{
WeaponAbilities.Add( WeaponAbility.Disarm, 0.225 );
WeaponAbilities.Add( WeaponAbility.BleedAttack, 0.225 );
}
[Constructable]
public MountedNelderimGuard() : base( GuardType.MountedGuard, FightMode.Criminal) { }
public MountedNelderimGuard(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) 0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[CorpseName( "zwloki straznika" )]
public class ArcherNelderimGuard : BaseNelderimGuard
{
public override void AddWeaponAbilities()
{
WeaponAbilities.Add( WeaponAbility.ParalyzingBlow, 0.2 );
WeaponAbilities.Add( WeaponAbility.ArmorIgnore, 0.2 );
}
[Constructable]
public ArcherNelderimGuard() : base( GuardType.ArcherGuard, FightMode.Criminal) { }
public ArcherNelderimGuard(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) 0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[CorpseName( "zwloki straznika" )]
public class EliteNelderimGuard : BaseNelderimGuard
{
public override void AddWeaponAbilities()
{
WeaponAbilities.Add( WeaponAbility.WhirlwindAttack, 0.25 );
WeaponAbilities.Add( WeaponAbility.BleedAttack, 0.25 );
}
[Constructable]
public EliteNelderimGuard() : base ( GuardType.EliteGuard, FightMode.Criminal) {}
public EliteNelderimGuard(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) 0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
[CorpseName( "zwloki straznika" )]
public class SpecialNelderimGuard : BaseNelderimGuard
{
public override void AddWeaponAbilities()
{
WeaponAbilities.Add( WeaponAbility.Disarm, 0.5 );
WeaponAbilities.Add( WeaponAbility.BleedAttack, 0.5 );
}
[Constructable]
public SpecialNelderimGuard() : base ( GuardType.SpecialGuard ) {}
public SpecialNelderimGuard(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) 0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
// async call reference: https://stackoverflow.com/questions/49982058/how-to-call-an-async-function
import React from "react";
import {
generate_entries_of_item_supplier_table,
generate_entries_of_item_table_from_images,
generate_entries_of_order_table,
generate_entries_of_supplier_table,
} from "./test_image_population/image_populator";
import { Outlet, Routes, Route } from "react-router-dom";
import Nav from "./components/Nav";
import Header from "./components/Header";
import Footer from "./components/Footer";
import app from "./componentCSS/app.css";
import Inventory from "./routes/Inventory";
import Login from "./routes/Login";
import Home from "./routes/Home";
import About from "./routes/About";
import Product from "./routes/Product";
import Cart from "./routes/Cart";
import Quotations from "./tables/Quotations";
import User from "./tables/User";
import Items from "./tables/Items";
import Db_pop from "./routes/populate_db";
import Order from "./tables/Order";
import Supplier from "./tables/Supplier";
let GENERATE_TABLE_ENTRIES = 0; //to generate db data using the generation functions below change 0 to 1
const AppLayout1 = () => {
return (
<>
<Nav />
<Outlet />
</>
);
};
const AppLayout2 = () => {
return (
<>
<Nav />
<Header />
<Outlet />
</>
);
};
const App = () => {
console.log("supabase testing start");
if (GENERATE_TABLE_ENTRIES) {
// generate_entries_of_item_supplier_table("item_supplier_t", "Item_t", "supplier_t", 1)
generate_entries_of_item_table_from_images("Item");
generate_entries_of_supplier_table("supplier");
generate_entries_of_item_supplier_table(
"item_supplier",
"Item",
"supplier",
0
);
generate_entries_of_order_table("orders", "item_supplier");
}
console.log("supabase testing ends");
return (
<>
<Routes>
<Route element={<AppLayout1 />}>
<Route path="/" element={<Home />} />
<Route path="/" element={<Home />} />
<Route path="/About" element={<About />} />
<Route path="/items" element={<Items />} />
<Route path="/inventory" element={<Inventory />} />
<Route path="/login" element={<Login />} />
<Route path="/orders" element={<Order />} />
<Route path="/users" element={<User />} />
<Route path="/suppliers" element={<Supplier />} />
<Route path="/quotations" element={<Quotations />} />
</Route>
<Route element={<AppLayout2 />}>
<Route path="/product" element={<Product />} />
<Route path="/cart" element={<Cart />} />
</Route>
</Routes>
</>
);
};
export default App;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Personal Portfolio Website</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.11/typed.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css"/>
</head>
<body>
<div class="scroll-up-btn">
<i class="fas fa-angle-up"></i>
</div>
<nav class="navbar">
<div class="max-width">
<div class="logo"><a href="#">Portfo<span>lio.</span></a></div>
<ul class="menu">
<li><a href="#home" class="menu-btn">Home</a></li>
<li><a href="#about" class="menu-btn">About</a></li>
<li><a href="#services" class="menu-btn">Education</a></li>
<li><a href="#teams" class="menu-btn">Assignments</a></li>
<li><a href="#skills" class="menu-btn">Mini Project</a></li>
<li><a href="#contact" class="menu-btn">Contact</a></li>
</ul>
<div class="menu-btn">
<i class="fas fa-bars"></i>
</div>
</div>
</nav>
<!-- home section start -->
<section class="home" id="home">
<div class="max-width">
<div class="home-content">
<div class="text-1">Hello, my name is</div>
<div class="text-2">Om Kadu</div>
<div class="text-3">And I'm a <span class="typing"></span></div>
<!-- <a href="#">Hire me</a> -->
</div>
</div>
</section>
<!-- about section start -->
<section class="about" id="about">
<div class="max-width">
<h2 class="title">About me</h2>
<div class="about-content">
<div class="column left">
<img src="./ss.jpg" alt="">
</div>
<div class="column right">
<div class="text">I'm Om and I'm a <span class="typing-2"></span></div>
<p>I Am A Fresher In Front End Development. Presently I Am Studyding In 1<sup>st</sup> Year Bachelor Of Engineering In Computer Science And Engineering Branch. Till Now I Acquired Kownledge About HTML,CSS And JS. I Am Planning To Expand My Knowledge In The Web Development. Also I Have Interest In Competitive Programming.</p>
<a href="#">Download CV</a>
</div>
</div>
</div>
</section>
<!-- education section start -->
<section class="services" id="services">
<div class="max-width">
<h2 class="title">My Education</h2>
<div class="serv-content">
<div class="card">
<div class="box">
<i class="fas fa-book-reader"></i>
<div class="text">Secondary School</div>
<p>Completed My 10<sup>th</sup> From Dnyanmata High School,Amravati.</p>
</div>
</div>
<div class="card">
<div class="box">
<i class="fas fa-book-reader"></i>
<div class="text">Higher Secondary School</div>
<p>Completed My 12<sup>th</sup> From Shri Shivaji Science College,Amravati.</p>
</div>
</div>
<div class="card">
<div class="box">
<i class="fas fa-book-reader"></i>
<div class="text">Persuing Graduation</div>
<p> Presently Studying In 1<sup>st</sup> Year Bachelor Of Engineering In CSE Branch.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- projects section start -->
<section class="teams" id="teams">
<div class="max-width">
<h2 class="title">My Assignments</h2>
<div class="carousel owl-carousel">
<div class="card">
<div class="box">
<a href="./OKDocument/shreyas.html"> <img src="./calci.jpg" alt=""></a>
<div class="text">Module 1</div>
<p>A Static Page Of Working Calculator And A Working Website Made With HTML,CSS And JS</p>
</div>
</div>
<div class="card">
<div class="box">
<a href="./Module 2/index.html"> <img src="./Screenshot (11).png" alt=""></a>
<div class="text">Module 2</div>
<p>Computer Aided Design With The Help Of Fusion 360 And Auto-CAD.</p>
</div>
</div>
<div class="card">
<div class="box">
<a href="./Module 3/index.html"> <img src="./assig3.jpg" alt="laser-Cutter"></a>
<div class="text">Module 3</div>
<p>Computer Controlled Cutting With The Help Of Fusion 360,Auto-CAD And Laser-Cad </p>
</div>
</div>
<div class="card">
<div class="box">
<img src="./Proname.jpg" alt="">
<div class="text">Someone name</div>
<p>Description of the Project. Made Using Which Languages.</p>
</div>
</div>
<div class="card">
<div class="box">
<img src="./Proname.jpg" alt="">
<div class="text">Someone name</div>
<p>Description of the Project. Made Using Which Languages.</p>
</div>
</div>
</div>
</div>
</section>
<!-- skills section start -->
<!-- <section class="skills" id="skills">
<div class="max-width">
<h2 class="title">My Skills</h2>
<div class="skills-content">
<div class="column left">
<div class="text">My Creative Skills.</div>
<p>I Am A Fresher In Front End Development. Presently I Am Studyding In 1<sup>st</sup> Year Bachelor Of Engineering In Computer Science And Engineering Branch. Till Now I Acquired Kownledge About HTML,CSS And JS. I Am Planning To Expand My Knowledge In The Web Development. Also I Have Interest In Competitive Programming. My Knowledge Regarding All The Languages Are Shown In Beside Percentage Graph.</p>
<a href="#">Read more</a>
</div>
<div class="column right">
<div class="bars">
<div class="info">
<span>Basic C</span>
<span>90%</span>
</div>
<div class="line html"></div>
</div>
<div class="bars">
<div class="info">
<span>C++</span>
<span>60%</span>
</div>
<div class="line css"></div>
</div>
<div class="bars">
<div class="info">
<span>HTML</span>
<span>60%</span>
</div>
<div class="line js"></div>
</div>
<div class="bars">
<div class="info">
<span>CSS</span>
<span>50%</span>
</div>
<div class="line php"></div>
</div>
<div class="bars">
<div class="info">
<span>JS</span>
<span>30%</span>
</div>
<div class="line mysql"></div>
</div>
</div>
</div>
</div>
</section> -->
<!-- contact section start -->
<section class="contact" id="contact">
<div class="max-width">
<h2 class="title">Contact me</h2>
<div class="contact-content">
<div class="column left">
<div class="text">Get in Touch</div>
<p>It Will Be My Pleasure To Solve All Your Queries Related To My Work.
Dont' Forget To Give Me The Feedback Of My Website.
</p>
<div class="icons">
<div class="row">
<i class="fas fa-user"></i>
<div class="info">
<div class="head">Name</div>
<div class="sub-title">Om Nilesh Kadu</div>
</div>
</div>
<div class="row">
<i class="fas fa-map-marker-alt"></i>
<div class="info">
<div class="head">Address</div>
<div class="sub-title">Amravati,Maharashtra,India</div>
</div>
</div>
<div class="row">
<i class="fas fa-envelope"></i>
<div class="info">
<div class="head">Email</div>
<div class="sub-title">[email protected]</div>
</div>
</div>
</div>
</div>
<div class="column right">
<div class="text">Message me</div>
<form action="#">
<div class="fields">
<div class="field name">
<input type="text" placeholder="Name" required>
</div>
<div class="field email">
<input type="email" placeholder="Email" required>
</div>
</div>
<div class="field">
<input type="text" placeholder="Subject" required>
</div>
<div class="field textarea">
<textarea cols="30" rows="10" placeholder="Message.." required></textarea>
</div>
<div class="button-area">
<button type="submit">Send message</button>
</div>
</form>
</div>
</div>
</div>
</section>
<script src="script.js"></script>
</body>
</html>
|
module abstract-topology {
yang-version 1;
namespace "urn:model:abstract:topology";
prefix "tp";
import ietf-interfaces {
prefix "if";
revision-date 2012-11-15;
}
organization "OPEN DAYLIGHT";
contact "http://www.opendaylight.org/";
description
"This module contains the definitions of elements that creates network
topology i.e. definition of network nodes and links. This module is not designed to be used solely for network representation. This module SHOULD be used as base module in defining the network topology.";
revision "2013-02-08" {
reference "~~~ WILL BE DEFINED LATER";
}
revision "2013-01-01" {
reference "~~~ WILL BE DEFINED LATER";
}
typedef node-id-ref {
type leafref {
path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id";
}
description "This type is used for leafs that reference network node instance.";
}
typedef link-id-ref {
type leafref {
path "/tp:topology/tp:network-links/tp:network-link/tp:link-id";
}
description "This type is used for leafs that reference network link instance.";
}
typedef interface-id-ref {
type leafref {
path "/tp:topology/tp:interfaces/tp:interface/tp:interface-id";
}
}
container topology {
description "This is the model of abstract topology which contains only Network Nodes and Network Links. Each topology MUST be identified by unique topology-id for reason that the store could contain many topologies.";
leaf topology-id {
type string;
description "It is presumed that datastore will contain many topologies. To distinguish between topologies it is vital to have
UNIQUE topology identifier.";
}
container network-nodes {
list network-node {
key "node-id";
leaf node-id {
type string;
description "The Topology identifier of network-node.";
}
container attributes {
description "Aditional attributes that can Network Node contains.";
}
description "The list of network nodes defined for topology.";
}
}
container interfaces {
list interface {
key "interface-id";
leaf interface-id {
type leafref {
path "/if:interfaces/if:interface/if:name";
}
}
leaf-list higher-layer-if {
type leafref {
path "/if:interfaces/if:interface/if:higher-layer-if";
}
}
leaf oper-status {
type leafref {
path "/if:interfaces/if:interface/if:oper-status";
}
}
leaf link-up-down-trap-enable {
type leafref {
path "/if:interfaces/if:interface/if:link-up-down-trap-enable";
}
}
}
}
container network-links {
list network-link {
key "link-id";
leaf link-id {
type string;
description "";
}
container source-node {
leaf id {
type node-id-ref;
description "Source node identifier.";
}
}
container destination-node {
leaf id {
type node-id-ref;
description "Destination node identifier.";
}
}
container tunnels {
list tunnel {
key "tunnel-id";
leaf tunnel-id {
type leafref {
path "../../../link-id";
}
}
}
}
leaf interface {
type interface-id-ref;
}
container attributes {
description "Aditional attributes that can Network Link contains.";
}
description "The Network Link which is defined by Local (Source) and Remote (Destination) Network Nodes. Every link MUST be defined either by identifier and
his local and remote Network Nodes (In real applications it is common that many links are originated from one node and end up in same remote node). To ensure that we would always know to distinguish between links, every link SHOULD have identifier.";
}
}
}
}
|
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
onlyActive,
onlyComplete,
showAll,
deleteTodo,
} from "../features/todos/todosSlice";
const Menu = ({ todoLength }) => {
const dispatch = useDispatch();
const { isLoading, isUpdate, isError, message, onlyCompleted } = useSelector(
(state) => state.todos
);
const [currentFilter, setCurrentFilter] = useState("all");
const onClick = (e) => {
if (e.target.id === "active") {
dispatch(onlyActive());
setCurrentFilter("active");
}
if (e.target.id === "completed") {
dispatch(onlyComplete());
setCurrentFilter("completed");
}
if (e.target.id === "all") {
dispatch(showAll());
setCurrentFilter("all");
}
};
const deleteCompleted = () => {
onlyCompleted.map((todo) => dispatch(deleteTodo(todo._id)));
};
useEffect(() => {
dispatch(showAll());
setCurrentFilter("all");
}, [dispatch, isLoading, isUpdate, isError]);
return (
<div className="absolute bottom-0 flex flex-col items-center justify-center w-full h-[50px] text-very_dark_grayish_blue dark:text-very_dark_grayish_blue">
<hr className="absolute top-0 w-full opacity-25" />
<div className="flex w-full items-center justify-around text-[10px] md:text-[14px] font-bold">
<h3 className="text-very_dark_grayish_blue">{todoLength}</h3>
<div className="flex items-center space-x-[10px] ">
<h3
className={
currentFilter === "all"
? "cursor-pointer text-bright_blue"
: "cursor-pointer active:text-light_grayish_blue"
}
onClick={onClick}
id="all"
>
All
</h3>
<h3
className={
currentFilter === "active"
? "cursor-pointer text-bright_blue"
: "cursor-pointer active:text-light_grayish_blue"
}
onClick={onClick}
id="active"
>
Active
</h3>
<h3
className={
currentFilter === "completed"
? "cursor-pointer text-bright_blue"
: "cursor-pointer active:text-light_grayish_blue"
}
onClick={onClick}
id="completed"
>
Completed
</h3>
</div>
<h3
className="cursor-pointer active:text-light_grayish_blue"
onClick={deleteCompleted}
>
Clear completed
</h3>
</div>
</div>
);
};
export default Menu;
|
export const availableFilterTypes = [
'childAttr',
'childArrayAttr',
'existence',
'string',
'array',
'minDate',
'maxDate',
'dateRange',
'dateTimeRange',
'minNum',
'minNumber',
'maxNumber',
'maxNum',
'strict',
'laxTrue',
'laxFalse',
'emptiness',
'lax',
'arrayIncludes',
'arrayIncludesArray',
'arrayIncludesArrayStrict',
];
export type FilterType =
'childAttr' |
'childArrayAttr' |
'existence' |
'string' |
'array' |
'minDate' |
'maxDate' |
'dateRange' |
'dateTimeRange' |
'minNum' |
'minNumber' |
'maxNumber' |
'maxNum' |
'strict' |
'laxTrue' |
'laxFalse' |
'emptiness' |
'lax' |
'arrayIncludes' |
'arrayIncludesArray' |
'arrayIncludesArrayStrict'
type CustomDateFilter = {
type: 'dateRange',
value: 'custom',
field: 'string',
data: {
from: string | number | Date,
until: string | number | Date,
}
}
type DateFilter = {
field: 'string',
type: 'dateRange',
value?: 'today' | 'yesterday' | '7days' | 'month' | 'last_month' | '_any'
} | CustomDateFilter
type DateTimeFilter = {
field: string,
type: 'dateTimeRange',
value?: string,
data: {
from: string | number | Date,
until: string | number | Date,
}
}
type GenericFilter = {
field: string,
type: FilterType,
value?: any,
}
type ChildFilter = {
type: 'childAttr' | 'childArrayAttr'
field: 'string',
value?: any,
data: {
child: Filter & {
data?: any,
},
}
}
export type Filter = GenericFilter | DateFilter | DateTimeFilter | ChildFilter;
const convertIntoDateIfNotObject = (value: string | number | Date) => {
return typeof value === 'object' ? value : new Date(value);
};
const numSafeToLowerCase = (input: string | number) => {
return String(input).toLowerCase();
};
export const convertDateRangeValueToBeComparable = (filter: DateFilter) => {
let from, until;
const today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
const year = today.getFullYear();
const month = today.getMonth();
switch (filter.value) {
case ('today'):
from = today;
until = new Date(from.getTime() + 8.64e+7);
break;
case ('yesterday'):
until = today;
from = new Date(until.getTime() - 8.64e+7);
break;
case ('7days'):
until = new Date(today.getTime() + 8.64e+7);
from = new Date(until.getTime() - 6.048e+8);
break;
case ('month'):
from = new Date(year, month, 1, 0, 0, 0, 0);
until = new Date(year, month + 1, 1, 0, 0, 0, 0);
break;
case ('last_month'):
from = new Date(year, month - 1, 1, 0, 0, 0, 0);
until = new Date(year, month, 1, 0, 0, 0, 0);
break;
case ('custom'):
from = new Date(filter.data.from);
until = new Date(filter.data.until);
// Ignore filter if from or until are malformed
// @ts-ignore next
if (isNaN(from) || isNaN(until)) {
return true;
}
until.setHours(23);
until.setMinutes(59);
until.setSeconds(59);
until.setMilliseconds(999);
break;
case ('_any'):
return true;
default:
console.error('Filter date range ' + filter.value + ' not implemented. Skipping filter.');
return true;
}
return [from, until];
};
const checkDateRangeFilter = (filter: DateFilter, value: string|number|Date) => {
const comparable = convertDateRangeValueToBeComparable(filter);
if (comparable === true) {
return true;
}
return (comparable[0] <= value && comparable[1] >= value);
};
export const checkDateTimeRangeValueToBeComparable = (filter: DateTimeFilter) => {
if (filter.value === '_any') {
return false;
}
const from = new Date(filter.data.from);
const until = new Date(filter.data.until);
// @ts-ignore next
if (isNaN(from) || isNaN(until)) {
return false;
}
return [from, until];
};
const checkDateTimeRangeFilter = (filter: DateTimeFilter, value: string|number|Date) => {
const comparable = checkDateTimeRangeValueToBeComparable(filter);
if (comparable === false) {
return true;
}
return (comparable[0] <= value && comparable[1] >= value);
};
const buildChildFilter = (filter: ChildFilter) => {
return {
type: filter.data.child.type,
field: filter.data.child.field,
value: filter.data.child.value,
data: filter.data.child.data,
};
};
const checkFilter = (filter: Filter, valueRow: {[key:string]: any}, skipUndefined?: boolean): boolean => {
if ((filter.value === undefined && filter.type !== 'laxTrue' && filter.type !== 'laxFalse' && filter.type !== 'childAttr' && filter.type !== 'childArrayAttr') || filter.field === undefined) {
return true;
}
const value = valueRow?.[filter.field];
if (value === undefined) {
if (filter.type === 'existence') {
if (typeof filter.value === 'boolean' && filter.value) {
return false;
} else if (filter.value.length === 1 && filter.value[0] === true) {
return false;
}
return true;
} else if (filter.type === 'emptiness') {
let filterVal;
if (typeof filter.value === 'boolean') {
filterVal = filter.value;
} else if (filter.value.length === 1) {
filterVal = filter.value[0];
}
if (filterVal !== undefined) {
return filterVal;
}
} else {
return Boolean(skipUndefined);
}
}
switch (filter.type) {
case ('string'): {
const lowerCaseValue = numSafeToLowerCase(value);
if (lowerCaseValue.search(numSafeToLowerCase(filter.value)) === -1) {
return false;
}
break;
}
case ('array'): {
if (filter.value !== '_any' && filter.value[0] !== '_any' && filter.value.indexOf(value) === -1) {
return false;
}
break;
}
case ('arrayIncludes'): {
if (value.indexOf(filter.value) === -1) {
return false;
}
break;
}
case ('arrayIncludesArray'): {
if (filter.value !== '_any' && filter.value[0] !== '_any') {
let found = false;
for (const filterValue of filter.value) {
if (value.indexOf(filterValue) !== -1) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
break;
}
case('arrayIncludesArrayStrict'): {
if (filter.value !== '_any' && filter.value[0] !== '_any') {
let lost = false;
for (const filterValue of filter.value) {
if (value.indexOf(filterValue) === -1) {
lost = true;
break;
}
}
if (lost) {
return false;
}
}
break;
}
case ('minDate'): {
if (new Date(filter.value) > convertIntoDateIfNotObject(value)) {
return false;
}
break;
}
case ('maxDate'): {
if (new Date(filter.value) < convertIntoDateIfNotObject(value)) {
return false;
}
break;
}
case ('dateRange'): {
if (!checkDateRangeFilter(filter as DateFilter, convertIntoDateIfNotObject(value))) {
return false;
}
break;
}
case ('dateTimeRange'): {
if (!checkDateTimeRangeFilter(filter as DateTimeFilter, convertIntoDateIfNotObject(value))) {
return false;
}
break;
}
case('minNumber'):
case ('minNum'): {
if (value < filter.value) {
return false;
}
break;
}
case('maxNumber'):
case ('maxNum'): {
if (value > filter.value) {
return false;
}
break;
}
case ('strict'): {
if (value !== filter.value) {
return false;
}
break;
}
case ('lax'): {
if (value != filter.value) {
return false;
}
break;
}
case ('laxTrue'): {
if (!value) {
return false;
}
break;
}
case ('laxFalse'): {
if (value) {
return false;
}
break;
}
case ('existence'): {
if (typeof filter.value === 'boolean') {
if ((!filter.value && !(value === null || value === '')) || (filter.value && value === '')) {
return false;
}
} else if (filter.value.length === 1) {
if ((filter.value[0] === false && !(value === null || value === '')) || (filter.value[0] === true && value === '')) {
return false;
}
}
break;
}
case ('emptiness'): {
let filterVal;
if (typeof filter.value === 'boolean') {
filterVal = filter.value;
} else if (filter.value.length === 1) {
filterVal = filter.value[0];
}
if (filterVal !== undefined) {
if ((filterVal === true && !(value === null || value === '' || value?.length === 0))
|| (filterVal === false && (value === '' || value === null || value?.length === 0))) {
return false;
}
}
break;
}
case('childAttr'): {
// @ts-ignore next
if (!filter.data || !filter.data.child) {
console.warn('Filter has childAttr type but no data set. Ignoring filter.');
return true;
}
const childFilter = buildChildFilter(filter as ChildFilter);
return checkFilter(childFilter, value, skipUndefined);
}
case('childArrayAttr'): {
// @ts-ignore next
if (!filter.data || !filter.data.child) {
console.warn('Filter has childArrayAttr type but no data set. Ignoring filter.');
return true;
}
if (skipUndefined && !value?.length) {
return true;
}
const childFilters = [buildChildFilter(filter as ChildFilter)];
return applyFilters(childFilters, value, skipUndefined).length > 0;
}
default: {
// @ts-ignore next
console.warn('Filter type not implemented: ' + filter?.type + '. Ignoring filter.');
}
}
return true;
};
export const applyFilters = (filters: Array<Filter>, values: Array<{[key:string]: any}>, skipUndefined = true) => {
if (!Array.isArray(values)) {
values = Object.values(values);
}
return values.filter((valueRow) => {
for (const filter of filters) {
if (!checkFilter(filter, valueRow, skipUndefined)) {
return false;
}
}
return true;
});
};
export default applyFilters;
|
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"CnC/service/api"
"CnC/service/database"
"github.com/ardanlabs/conf"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
if err := run(); err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Error running the app: ", err)
}
}
func run() error {
cfg, err := loadConfig()
if err != nil {
if errors.Is(err, conf.ErrHelpWanted) {
return nil
}
return err
}
logger := logrus.New()
if cfg.Debug {
logger.SetLevel(logrus.DebugLevel)
} else {
logger.SetLevel(logrus.InfoLevel)
}
logger.Infof("Application Initializing...")
var db database.AppDatabase
if cfg.DevRun {
logger.Println("Initializing Database Support")
dbconn := options.Client().ApplyURI("mongodb://localhost:27017/")
client, err := mongo.Connect(context.TODO(), dbconn)
if err != nil {
logger.WithError(err).Error("error connetting to mongo DB")
return fmt.Errorf("opening mongoDb: %w", err)
}
defer func() {
logger.Debug("database stopping")
_ = client.Disconnect(context.TODO())
}()
db, err = database.InitDatabase(client)
if err != nil {
logger.WithError(err).Error("error creating mongo DB")
return fmt.Errorf("opening mongoDb: %w", err)
}
} else {
db = nil
}
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
serverErrors := make(chan error, 1)
apirouter, err := api.NewServer(api.Config{
Logger: logger,
Database: db,
})
if err != nil {
logger.WithError(err).Error("error creating the API server instance")
return fmt.Errorf("creating the API server instance: %w", err)
}
router := apirouter.Handler()
router, err = registerWebUI(router)
if err != nil {
logger.WithError(err).Error("error registering web UI handler")
return fmt.Errorf("registering web UI handler: %w", err)
}
router = applyCORSHandler(router)
apiserver := http.Server{
Addr: cfg.WebAPI.ServerAddr,
Handler: router,
ReadTimeout: cfg.WebAPI.ServerConfig.ReadTimeout,
ReadHeaderTimeout: cfg.WebAPI.ServerConfig.ReadTimeout,
WriteTimeout: cfg.WebAPI.ServerConfig.WriteTimeout,
}
go func() {
logger.Infof("API listening on port: %d", cfg.WebAPI.ServerPort)
serverErrors <- apiserver.ListenAndServe()
logger.Infof("stopping API server")
}()
select {
case err := <-serverErrors:
return fmt.Errorf("server error: %w", err)
case sig := <-shutdown:
logger.Infof("signal %v received, start shutdown", sig)
err := apirouter.Close()
if err != nil {
logger.WithError(err).Warning("graceful shutdown of apirouter error")
}
ctx, cancel := context.WithTimeout(context.Background(), cfg.WebAPI.ServerConfig.ShutdownTimeout)
defer cancel()
err = apiserver.Shutdown(ctx)
if err != nil {
logger.WithError(err).Warning("error during graceful shutdown of HTTP server")
err = apiserver.Close()
}
switch {
case sig == syscall.SIGSTOP:
return errors.New("integrity issue caused shutdown")
case err != nil:
return fmt.Errorf("could not stop server gracefully: %w", err)
}
}
return nil
}
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\City;
use App\Models\Doctor;
use App\Models\Speciality;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class DoctorRegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::DOCTOR;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
public function getRegister(){
$cities=City::get();
$specs=Speciality::get();
return view('doctor.register',compact(['cities','specs']));
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:50'],
'username' => ['required', 'string', 'max:50','unique:doctors,username'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:doctors,email'],
'mobile' => ['required', 'string', 'max:20', 'unique:doctors,mobile'],
'city' => ['required','exists:cities,id'],
'speciality_id' => ['required','exists:specialties,id'],
'gender' => ['required','in:0,1'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
],[
'required'=>'this :attribute is required',
'string'=>'this :attribute must be string',
'name.max'=>':attribute must be less than 50 chars',
'unique'=>'this :attribute belongs to another patient',
'username.max'=>':attribute must be less than 50 chars',
'email'=>':attribute must be like [email protected]',
'mobile.max'=>':attribute must be less than 20 chars',
'exists'=>'please select correct :attribute',
'in'=>'please choose from list only',
'confirmed'=>'the password doesn\'t matched' ,
'password.min'=>'the :attribute must be at least 8 chars',
],['speciality_id'=>'speciality']);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return Doctor::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'mobile' => $data['mobile'],
'city' => $data['city'],
'gender' => $data['gender'],
'specialty_id' => $data['speciality_id'],
'password' => Hash::make($data['password']),
]);
}
}
|
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/base}">
<head>
<meta charset="UTF-8">
<title>ItemView</title>
<link rel="stylesheet" href="/css/review.css">
<style>
.item-review-more {
cursor: pointer;
}
.item-box {
width: 80%;
display: flex;
flex-direction: column;
}
</style>
</head>
<body>
<th:block layout:fragment="content">
<input type="hidden" id="itemIdx" th:value="${itemIdx}">
<div class="item-box">
<div class="item-box-in">
<div class="item-img-box">
<img th:src="${img ?: 'https://via.placeholder.com/150'}" th:alt="${name}">
</div>
<div class="item-info">
<p th:text="${name}"></p>
<p th:text="${price}"></p>
<p th:text="${description}"></p>
<p th:text="|재고 : ${quantity}|"></p>
<input type="number" id="itemCount" value="1" min="1" th:max="${quantity < 999 ?: 999}">
<button id="buy">구매하기</button>
<button id="addCart">카트 담기</button>
</div>
</div>
<div class="item-review">
<div class="review-total"></div>
<div class="review-write">
<input type="hidden" id="reviewId" th:value="${reviewIdx}">
<div>
점수
<th:block th:each="num : ${#numbers.sequence(1,5)}">
<label th:for="|score${num}|" th:text="${num}"></label>
<input type="radio" class="review-score" name="score" th:id="|score${num}|" th:value="${num}" th:checked="${num == score}">
</th:block>
</div>
<label>
리뷰
<textarea class="review-comment" th:text="${comment}"></textarea>
<button class="review-submit">작성</button>
<th:block th:if="${reviewIdx != null}">
<button class="review-delete">삭제</button>
</th:block>
</label>
</div>
<div class="review-list"></div>
</div>
<div class="item-review-more">리뷰 더보기</div>
</div>
<script>
let page = 0;
let reviewAjax = true;
document.querySelector("#itemCount").addEventListener("focusout", minCount);
document.querySelector(".item-review-more").addEventListener("click",showReview);
$(".review-submit").on("click", restReview);
$(".review-delete").on("click", () => restReview("DELETE"));
$("#addCart").on("click", addCart);
$("#buy").on("click", buy);
showReview();
function restReview(method) {
let requestUrl = '/review';
let type = "POST";
let obj = {
idx : $("#reviewId").val(),
score : $(".review-score:checked").val(),
comment: $(".review-comment").val(),
itemIdx: $("#itemIdx").val()
}
if (obj.idx !== "") {
type = "PATCH";
requestUrl += `/${obj.idx}`;
}
if (method === "DELETE") {
if (confirm("정말로 삭제하시겠습니까?")) {
type = "DELETE";
} else {
return false;
}
}
$.ajax({
url:requestUrl,
type: `${type}`,
data: JSON.stringify(obj),
contentType: 'application/json',
success: function (data) {
if (data === 200) {
alert("정상적으로 처리되었습니다.");
location.reload();
} else if(data === 403) {
alert("로그인이 필요합니다.");
location.href = "/login";
} else {
alert(`에러가 발생하였습니다. (${data})`);
}
}
})
}
function addCart() {
$.ajax({
url: `/api/shopping/cart`,
type: `POST`,
contentType: 'application/json',
data: JSON.stringify({
'itemIdx': $('#itemIdx').val(),
'amount': $('#itemCount').val()
}),
success: function (result) {
if (result.code === 400) {
alert(result.message);
location.href = "/login";
} else {
alert(result.message);
}
}
})
}
function minCount(e) {
if (e.target.value < 1) {
alert("최소 수량은 1입니다.");
e.target.value = 1;
}
}
function showReview() {
let html = "";
let requestUrl = `/review/item/${$('#itemIdx').val()}`;
let reviewFrom = `<div class="total-score">
<p class="score">TOTAL_SCORE</p>
<p class="count">TOTAL_COUNT명 참여</p>
</div>`;
let reviewList = `
<div class="reply">
<div class="user-info">
<div class="score">USER_SCORE</div>
<div class="reply-id">USER_ID</div>
<div class="reply-date">USER_DATE</div>
</div>
<div class="comment">USER_COMMENT</div>
</div>`;
if (page > 0) {
requestUrl += `?page=${page}`;
}
if (reviewAjax) {
reviewAjax = false;
$.ajax({
url: requestUrl,
success: function (data) {
console.log(data);
// 전체 점수
let avg = data.totalScore.avg === null ? '아직 평가되지 않았습니다.' : data.totalScore.avg.toFixed(2);
reviewFrom = reviewFrom.replace("TOTAL_SCORE",avg)
.replace("TOTAL_COUNT",data.totalScore.count);
$(".review-total").append(reviewFrom);
// 리뷰 리스트
data.review.forEach((data) => {
let reviewDate = "";
let regDt = data.regDate;
let updDt = data.updDate;
regDt = (regDt != null && regDt.length >=6) ? `${regDt.substr(0,4)}/${regDt.substr(4,2)}/${regDt.substr(6,2)}` : '';
updDt = (updDt != null && updDt.length >=6) ? `${updDt.substr(0,4)}/${updDt.substr(4,2)}/${updDt.substr(6,2)}` : '';
reviewDate = updDt.length > 0 ? `수정일 ${updDt}` : `작성일 ${regDt}`;
html = reviewList
.replace("USER_SCORE",data.score)
.replace("USER_ID",data.memberId)
.replace("USER_DATE",reviewDate)
.replace("USER_COMMENT",data.comment);
$(".review-list").append(html);
})
page++;
}
}).done(()=>reviewAjax=true)
}
}
function buy() {
location.href=`/item/buy?itemIdx=${document.querySelector("#itemIdx").value}&amount=${document.querySelector("#itemCount").value}`;
}
</script>
</th:block>
</body>
</html>
|
# File src/library/base/R/namespace.R
# Part of the R package, http://www.R-project.org
#
# 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 2 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.
#
# A copy of the GNU General Public License is available at
# http://www.r-project.org/Licenses/
## give the base namespace a table for registered methods
".__S3MethodsTable__." <- new.env(hash = TRUE, parent = baseenv())
getNamespace <- function(name) {
ns <- .Internal(getRegisteredNamespace(as.name(name)))
if (! is.null(ns)) ns
else tryCatch(loadNamespace(name), error = function(e) stop(e))
}
loadedNamespaces <- function()
ls(.Internal(getNamespaceRegistry()), all.names = TRUE)
getNamespaceName <- function(ns) {
ns <- asNamespace(ns)
if (isBaseNamespace(ns)) "base"
else getNamespaceInfo(ns, "spec")["name"]
}
getNamespaceVersion <- function(ns) {
ns <- asNamespace(ns)
if (isBaseNamespace(ns))
c(version = paste(R.version$major, R.version$minor, sep = "."))
else getNamespaceInfo(ns, "spec")["version"]
}
getNamespaceExports <- function(ns) {
ns <- asNamespace(ns)
if (isBaseNamespace(ns)) ls(.BaseNamespaceEnv, all.names = TRUE)
else ls(getNamespaceInfo(ns, "exports"), all.names = TRUE)
}
getNamespaceImports <- function(ns) {
ns <- asNamespace(ns)
if (isBaseNamespace(ns)) NULL
else getNamespaceInfo(ns, "imports")
}
getNamespaceUsers <- function(ns) {
nsname <- getNamespaceName(asNamespace(ns))
users <- character(0L)
for (n in loadedNamespaces()) {
inames <- names(getNamespaceImports(n))
if (match(nsname, inames, 0L))
users <- c(n, users)
}
users
}
getExportedValue <- function(ns, name) {
getInternalExportName <- function(name, ns) {
exports <- getNamespaceInfo(ns, "exports")
if (! exists(name, envir = exports, inherits = FALSE))
stop(gettextf("'%s' is not an exported object from 'namespace:%s'",
name, getNamespaceName(ns)),
call. = FALSE, domain = NA)
get(name, envir = exports, inherits = FALSE)
}
ns <- asNamespace(ns)
if (isBaseNamespace(ns)) get(name, envir = ns, inherits = FALSE)
else get(getInternalExportName(name, ns), envir = ns)
}
"::" <- function(pkg, name) {
pkg <- as.character(substitute(pkg))
name <- as.character(substitute(name))
ns <- tryCatch(asNamespace(pkg), hasNoNamespaceError = function(e) NULL)
if (is.null(ns)) {
pos <- match(paste("package", pkg, sep=":"), search(), 0L)
if (pos == 0)
stop(gettextf(paste("package '%s' has no name space and",
"is not on the search path"), pkg),
domain = NA)
get(name, pos = pos, inherits = FALSE)
}
else getExportedValue(pkg, name)
}
":::" <- function(pkg, name) {
pkg <- as.character(substitute(pkg))
name <- as.character(substitute(name))
get(name, envir = asNamespace(pkg), inherits = FALSE)
}
attachNamespace <- function(ns, pos = 2, dataPath = NULL) {
runHook <- function(hookname, env, ...) {
if (exists(hookname, envir = env, inherits = FALSE)) {
fun <- get(hookname, envir = env, inherits = FALSE)
if (! is.null(try( { fun(...); NULL })))
stop(gettextf("%s failed in 'attachNamespace'", hookname),
call. = FALSE)
}
}
ns <- asNamespace(ns, base.OK = FALSE)
nsname <- getNamespaceName(ns)
nspath <- getNamespaceInfo(ns, "path")
attname <- paste("package", nsname, sep = ":")
if (attname %in% search())
stop("name space is already attached")
env <- attach(NULL, pos = pos, name = attname)
on.exit(detach(pos = pos))
attr(env, "path") <- nspath
exports <- getNamespaceExports(ns)
importIntoEnv(env, exports, ns, exports)
if(!is.null(dataPath)) {
dbbase <- file.path(dataPath, "Rdata")
if(file.exists(paste(dbbase, ".rdb", sep = ""))) lazyLoad(dbbase, env)
}
runHook(".onAttach", ns, dirname(nspath), nsname)
lockEnvironment(env, TRUE)
on.exit()
invisible(env)
}
loadNamespace <- function (package, lib.loc = NULL,
keep.source = getOption("keep.source.pkgs"),
partial = FALSE, declarativeOnly = FALSE) {
## eventually allow version as second component; ignore for now.
package <- as.character(package)[[1L]]
## check for cycles
dynGet <- function(name,
notFound = stop(gettextf("%s not found", name),
domain = NA))
{
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
loading <- dynGet("__NameSpacesLoading__", NULL)
if (match(package, loading, 0L))
stop("cyclic name space dependencies are not supported")
"__NameSpacesLoading__" <- c(package, loading)
ns <- .Internal(getRegisteredNamespace(as.name(package)))
if (! is.null(ns))
ns
else {
runHook <- function(hookname, pkgname, env, ...) {
if (exists(hookname, envir = env, inherits = FALSE)) {
fun <- get(hookname, envir = env, inherits = FALSE)
if (! is.null(try( { fun(...); NULL })))
stop(gettextf("%s failed in 'loadNamespace' for '%s'",
hookname, pkgname),
call. = FALSE, domain = NA)
}
}
runUserHook <- function(pkgname, pkgpath) {
hook <- getHook(packageEvent(pkgname, "onLoad")) # might be list()
for(fun in hook) try(fun(pkgname, pkgpath))
}
makeNamespace <- function(name, version = NULL, lib = NULL) {
impenv <- new.env(parent = .BaseNamespaceEnv, hash = TRUE)
attr(impenv, "name") <- paste("imports", name, sep=":")
env <- new.env(parent = impenv, hash = TRUE)
name <- as.character(as.name(name))
version <- as.character(version)
info <- new.env(hash = TRUE, parent = baseenv())
assign(".__NAMESPACE__.", info, envir = env)
assign("spec", c(name = name,version = version), envir = info)
setNamespaceInfo(env, "exports", new.env(hash = TRUE, parent = baseenv()))
setNamespaceInfo(env, "imports", list("base" = TRUE))
setNamespaceInfo(env, "path", file.path(lib, name))
setNamespaceInfo(env, "dynlibs", NULL)
setNamespaceInfo(env, "S3methods", matrix(NA_character_, 0L, 3L))
assign(".__S3MethodsTable__.",
new.env(hash = TRUE, parent = baseenv()),
envir = env)
.Internal(registerNamespace(name, env))
env
}
sealNamespace <- function(ns) {
namespaceIsSealed <- function(ns)
environmentIsLocked(ns)
ns <- asNamespace(ns, base.OK = FALSE)
if (namespaceIsSealed(ns))
stop(gettextf("namespace '%s' is already sealed in loadNamespace",
getNamespaceName(ns)),
call. = FALSE, domain = NA)
lockEnvironment(ns, TRUE)
lockEnvironment(parent.env(ns), TRUE)
}
addNamespaceDynLibs <- function(ns, newlibs) {
dynlibs <- getNamespaceInfo(ns, "dynlibs")
setNamespaceInfo(ns, "dynlibs", c(dynlibs, newlibs))
}
bindTranslations <- function(pkgname, pkgpath)
{
popath <- file.path(pkgpath, "po")
if(!file.exists(popath)) return()
bindtextdomain(pkgname, popath)
bindtextdomain(paste("R", pkgname, sep = "-"), popath)
}
assignNativeRoutines <- function(dll, lib, env, nativeRoutines) {
if(length(nativeRoutines) == 0L)
return(NULL)
if(nativeRoutines$useRegistration) {
## Use the registration information to register ALL the symbols
fixes <- nativeRoutines$registrationFixes
routines <- getDLLRegisteredRoutines.DLLInfo(dll, addNames = FALSE)
lapply(routines,
function(type) {
lapply(type,
function(sym) {
varName <- paste(fixes[1L], sym$name, fixes[2L], sep = "")
if(exists(varName, envir = env))
warning("failed to assign RegisteredNativeSymbol for ",
sym$name,
paste(" to", varName),
" since ", varName,
" is already defined in the ", package,
" namespace")
else
assign(varName, sym, envir = env)
})
})
}
symNames <- nativeRoutines$symbolNames
if(length(symNames) == 0L)
return(NULL)
symbols <- getNativeSymbolInfo(symNames, dll, unlist = FALSE,
withRegistrationInfo = TRUE)
sapply(seq_along(symNames),
function(i) {
## could vectorize this outside of the loop
## and assign to different variable to
## maintain the original names.
varName <- names(symNames)[i]
origVarName <- symNames[i]
if(exists(varName, envir = env))
warning("failed to assign NativeSymbolInfo for ",
origVarName,
ifelse(origVarName != varName,
paste(" to", varName), ""),
" since ", varName,
" is already defined in the ", package,
" namespace")
else
assign(varName, symbols[[origVarName]],
envir = env)
})
symbols
}
## find package and check it has a name space
pkgpath <- .find.package(package, lib.loc, quiet = TRUE)
if (length(pkgpath) == 0L)
stop(gettextf("there is no package called '%s'", package),
domain = NA)
bindTranslations(package, pkgpath)
package.lib <- dirname(pkgpath)
package <- basename(pkgpath) # need the versioned name
if (! packageHasNamespace(package, package.lib)) {
hasNoNamespaceError <-
function (package, package.lib, call = NULL) {
class <- c("hasNoNamespaceError", "error", "condition")
msg <- gettextf("package '%s' does not have a name space",
package)
structure(list(message = msg, package = package,
package.lib = package.lib, call = call),
class = class)
}
stop(hasNoNamespaceError(package, package.lib))
}
## create namespace; arrange to unregister on error
## Can we rely on the existence of R-ng 'nsInfo.rds' and
## 'package.rds'?
## No, not during builds of standard packages
## stats4 depends on methods, but exports do not matter
## whilst it is being built on
nsInfoFilePath <- file.path(pkgpath, "Meta", "nsInfo.rds")
nsInfo <- if(file.exists(nsInfoFilePath)) .readRDS(nsInfoFilePath)
else parseNamespaceFile(package, package.lib, mustExist = FALSE)
pkgInfoFP <- file.path(pkgpath, "Meta", "package.rds")
if(file.exists(pkgInfoFP)) {
pkgInfo <- .readRDS(pkgInfoFP)
version <- pkgInfo$DESCRIPTION["Version"]
## we need to ensure that S4 dispatch is on now if the package
## will require it, or the exports will be incomplete.
dependsMethods <- "methods" %in% names(pkgInfo$Depends)
if(dependsMethods && pkgInfo$Built$R < "2.4.0")
stop("package was installed prior to 2.4.0 and must be re-installed")
if(dependsMethods) loadNamespace("methods")
} else {
version <- read.dcf(file.path(pkgpath, "DESCRIPTION"),
fields = "Version")
## stats4 depends on methods, but exports do not matter
## whilst it is being build on Unix
dependsMethods <- FALSE
}
ns <- makeNamespace(package, version = version, lib = package.lib)
on.exit(.Internal(unregisterNamespace(package)))
## process imports
for (i in nsInfo$imports) {
if (is.character(i))
namespaceImport(ns, loadNamespace(i, c(lib.loc, .libPaths())))
else
namespaceImportFrom(ns,
loadNamespace(i[[1L]],
c(lib.loc, .libPaths())),
i[[2L]])
}
for(imp in nsInfo$importClasses)
namespaceImportClasses(ns, loadNamespace(imp[[1L]],
c(lib.loc, .libPaths())),
imp[[2L]])
for(imp in nsInfo$importMethods)
namespaceImportMethods(ns, loadNamespace(imp[[1L]],
c(lib.loc, .libPaths())),
imp[[2L]])
## dynamic variable to allow/disable .Import and friends
"__NamespaceDeclarativeOnly__" <- declarativeOnly
## store info for loading name space for loadingNamespaceInfo to read
"__LoadingNamespaceInfo__" <- list(libname = package.lib,
pkgname = package)
env <- asNamespace(ns)
## save the package name in the environment
assign(".packageName", package, envir = env)
## load the code
codename <- strsplit(package, "_", fixed = TRUE)[[1L]][1L]
codeFile <- file.path(pkgpath, "R", codename)
if (file.exists(codeFile)) {
res <- try(sys.source(codeFile, env, keep.source = keep.source))
if(inherits(res, "try-error"))
stop(gettextf("unable to load R code in package '%s'", package),
call. = FALSE, domain = NA)
} else warning(gettextf("package '%s' contains no R code", package),
domain = NA)
## partial loading stops at this point
## -- used in preparing for lazy-loading
if (partial) return(ns)
## lazy-load any sysdata
dbbase <- file.path(pkgpath, "R", "sysdata")
if (file.exists(paste(dbbase, ".rdb", sep = ""))) lazyLoad(dbbase, env)
## register any S3 methods
registerS3methods(nsInfo$S3methods, package, env)
## load any dynamic libraries
dlls <- list()
dynLibs <- nsInfo$dynlibs
for (i in seq_along(dynLibs)) {
lib <- dynLibs[i]
dlls[[lib]] <- library.dynam(lib, package, package.lib)
assignNativeRoutines(dlls[[lib]], lib, env,
nsInfo$nativeRoutines[[lib]])
## If the DLL has a name as in useDynLib(alias = foo),
## then assign DLL reference to alias. Check if
## names() is NULL to handle case that the nsInfo.rds
## file was created before the names were added to the
## dynlibs vector.
if(!is.null(names(nsInfo$dynlibs))
&& names(nsInfo$dynlibs)[i] != "")
assign(names(nsInfo$dynlibs)[i], dlls[[lib]], envir = env)
setNamespaceInfo(env, "DLLs", dlls)
}
addNamespaceDynLibs(env, nsInfo$dynlibs)
## run the load hook
runHook(".onLoad", package, env, package.lib, package)
## process exports, seal, and clear on.exit action
exports <- nsInfo$exports
for (p in nsInfo$exportPatterns)
exports <- c(ls(env, pattern = p, all.names = TRUE), exports)
##
if(.isMethodsDispatchOn() && methods:::.hasS4MetaData(ns) &&
!identical(package, "methods") ) {
## cache generics, classes in this namespace (but not methods itself,
## which pre-cached at install time
methods:::cacheMetaData(ns, TRUE, ns)
## process class definition objects
expClasses <- nsInfo$exportClasses
##we take any pattern, but check to see if the matches are classes
pClasses <- character(0L)
aClasses <- methods:::getClasses(ns)
for (p in nsInfo$exportClassPatterns) {
pClasses <- c(aClasses[grep(p, aClasses)], pClasses)
}
pClasses <- unique(pClasses)
if( length(pClasses) ) {
good <- sapply(pClasses, methods:::isClass, where = ns)
if( !any(good) ) warning(gettextf("exportClassPattern specified but no matching classes in %s", package))
expClasses <- c(expClasses, pClasses[good])
}
if(length(expClasses)) {
missingClasses <-
!sapply(expClasses, methods:::isClass, where = ns)
if(any(missingClasses))
stop(gettextf("in '%s' classes for export not defined: %s",
package,
paste(expClasses[missingClasses],
collapse = ", ")),
domain = NA)
expClasses <- paste(methods:::classMetaName(""), expClasses,
sep = "")
}
## process methods metadata explicitly exported or
## implied by exporting the generic function.
allGenerics <- unique(c(methods:::.getGenerics(ns),
methods:::.getGenerics(parent.env(ns))))
expMethods <- nsInfo$exportMethods
expTables <- character()
expMLists <- character()
if(length(allGenerics)) {
expMethods <-
unique(c(expMethods,
exports[!is.na(match(exports, allGenerics))]))
missingMethods <- !(expMethods %in% allGenerics)
if(any(missingMethods))
stop(gettextf("in '%s' methods for export not found: %s",
package,
paste(expMethods[missingMethods],
collapse = ", ")),
domain = NA)
## Deprecated note: the mlistPattern objects are deprecated in 2.7.0
## and will disappear later. For now, deal with them if they exist
## but don't complain if they do not.
mlistPattern <- methods:::methodsPackageMetaName("M","")
allMethodLists <-
unique(c(methods:::.getGenerics(ns, mlistPattern),
methods:::.getGenerics(parent.env(ns),
mlistPattern)))
tPrefix <- methods:::.TableMetaPrefix()
allMethodTables <-
unique(c(methods:::.getGenerics(ns, tPrefix),
methods:::.getGenerics(parent.env(ns), tPrefix)))
needMethods <-
(exports %in% allGenerics) & !(exports %in% expMethods)
if(any(needMethods))
expMethods <- c(expMethods, exports[needMethods])
## Primitives must have their methods exported as long
## as a global table is used in the C code to dispatch them:
## The following keeps the exported files consistent with
## the internal table.
pm <- allGenerics[!(allGenerics %in% expMethods)]
if(length(pm)) {
prim <- logical(length(pm))
for(i in seq_along(prim)) {
f <- methods:::getFunction(pm[[i]], FALSE, FALSE, ns)
prim[[i]] <- is.primitive(f)
}
expMethods <- c(expMethods, pm[prim])
}
for(i in seq_along(expMethods)) {
mi <- expMethods[[i]]
if(!(mi %in% exports) &&
exists(mi, envir = ns, mode = "function",
inherits = FALSE))
exports <- c(exports, mi)
pattern <- paste(tPrefix, mi, ":", sep="")
ii <- grep(pattern, allMethodTables, fixed = TRUE)
if(length(ii)) {
if(length(ii) > 1L) {
warning("Multiple methods tables found for '",
mi, "'", call. = FALSE)
ii <- ii[1L]
}
expTables[[i]] <- allMethodTables[ii]
if(exists(allMethodLists[[ii]], envir = ns))
expMLists <- c(expMLists, allMethodLists[[ii]])
}
else { ## but not possible?
warning(gettextf("Failed to find metadata object for \"%s\"", mi))
}
}
}
else if(length(expMethods))
stop(gettextf("in '%s' methods specified for export, but none defined: %s",
package,
paste(expMethods, collapse = ", ")),
domain = NA)
exports <- c(exports, expClasses, expTables, expMLists)
}
namespaceExport(ns, exports)
sealNamespace(ns)
## run user hooks here
runUserHook(package, file.path(package.lib, package))
on.exit()
ns
}
}
loadingNamespaceInfo <- function() {
dynGet <- function(name, notFound = stop(name, " not found")) {
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
dynGet("__LoadingNamespaceInfo__", stop("not loading a name space"))
}
topenv <- function(envir = parent.frame(),
matchThisEnv = getOption("topLevelEnvironment")) {
while (! identical(envir, emptyenv())) {
nm <- attributes(envir)[["names", exact = TRUE]]
if ((is.character(nm) && length(grep("^package:" , nm))) ||
## matchThisEnv is used in sys.source
identical(envir, matchThisEnv) ||
identical(envir, .GlobalEnv) ||
identical(envir, baseenv()) ||
.Internal(isNamespaceEnv(envir)) ||
## packages except base and those with a separate namespace have .packageName
exists(".packageName", envir = envir, inherits = FALSE))
return(envir)
else envir <- parent.env(envir)
}
return(.GlobalEnv)
}
unloadNamespace <- function(ns)
{
## only used to run .onUnload
runHook <- function(hookname, env, ...) {
if (exists(hookname, envir = env, inherits = FALSE)) {
fun <- get(hookname, envir = env, inherits = FALSE)
res <- tryCatch(fun(...), error=identity)
if (inherits(res, "error")) {
stop(gettextf("%s failed in unloadNamespace(\"%s\"), details:\n call: %s\n message: %s",
hookname, nsname,
deparse(conditionCall(res))[1L],
conditionMessage(res)),
call. = FALSE, domain = NA)
}
}
}
ns <- asNamespace(ns, base.OK = FALSE)
nsname <- getNamespaceName(ns)
pos <- match(paste("package", nsname, sep = ":"), search())
if (! is.na(pos)) detach(pos = pos)
users <- getNamespaceUsers(ns)
if (length(users))
stop(gettextf("name space '%s' is still used by: %s",
getNamespaceName(ns),
paste(sQuote(users), collapse = ", ")),
domain = NA)
nspath <- getNamespaceInfo(ns, "path")
hook <- getHook(packageEvent(nsname, "onUnload")) # might be list()
for(fun in rev(hook)) try(fun(nsname, nspath))
try(runHook(".onUnload", ns, nspath))
.Internal(unregisterNamespace(nsname))
if(.isMethodsDispatchOn() && methods:::.hasS4MetaData(ns))
methods:::cacheMetaData(ns, FALSE, ns)
.Call("R_lazyLoadDBflush",
paste(nspath, "/R/", nsname, ".rdb", sep=""),
PACKAGE="base")
invisible()
}
.Import <- function(...) {
dynGet <- function(name, notFound = stop(name, " not found")) {
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
if (dynGet("__NamespaceDeclarativeOnly__", FALSE))
stop("imperative name space directives are disabled")
envir <- parent.frame()
names <- as.character(substitute(list(...)))[-1L]
for (n in names)
namespaceImportFrom(envir, n)
}
.ImportFrom <- function(name, ...) {
dynGet <- function(name, notFound = stop(name, " not found")) {
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
if (dynGet("__NamespaceDeclarativeOnly__", FALSE))
stop("imperative name space directives are disabled")
envir <- parent.frame()
name <- as.character(substitute(name))
names <- as.character(substitute(list(...)))[-1L]
namespaceImportFrom(envir, name, names)
}
.Export <- function(...) {
dynGet <- function(name, notFound = stop(name, " not found")) {
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
if (dynGet("__NamespaceDeclarativeOnly__", FALSE))
stop("imperative name space directives are disabled")
ns <- topenv(parent.frame(), NULL)
if (identical(ns, .BaseNamespaceEnv))
warning("all objects in base name space are currently exported.")
else if (! isNamespace(ns))
stop("can only export from a name space")
else {
names <- as.character(substitute(list(...)))[-1L]
namespaceExport(ns, names)
}
}
.S3method <- function(generic, class, method) {
dynGet <- function(name, notFound = stop(name, " not found")) {
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
if (dynGet("__NamespaceDeclarativeOnly__", FALSE))
stop("imperative name space directives are disabled")
generic <- as.character(substitute(generic))
class <- as.character(substitute(class))
if (missing(method)) method <- paste(generic, class, sep = ".")
registerS3method(generic, class, method, envir = parent.frame())
invisible(NULL)
}
isNamespace <- function(ns) .Internal(isNamespaceEnv(ns))
isBaseNamespace <- function(ns) identical(ns, .BaseNamespaceEnv)
getNamespaceInfo <- function(ns, which) {
ns <- asNamespace(ns, base.OK = FALSE)
info <- get(".__NAMESPACE__.", envir = ns, inherits = FALSE)
get(which, envir = info, inherits = FALSE)
}
setNamespaceInfo <- function(ns, which, val) {
ns <- asNamespace(ns, base.OK = FALSE)
info <- get(".__NAMESPACE__.", envir = ns, inherits = FALSE)
assign(which, val, envir = info)
}
asNamespace <- function(ns, base.OK = TRUE) {
if (is.character(ns) || is.name(ns))
ns <- getNamespace(ns)
if (! isNamespace(ns))
stop("not a name space")
else if (! base.OK && isBaseNamespace(ns))
stop("operation not allowed on base name space")
else ns
}
namespaceImport <- function(self, ...)
for (ns in list(...)) namespaceImportFrom(self, asNamespace(ns))
namespaceImportFrom <- function(self, ns, vars, generics, packages)
{
addImports <- function(ns, from, what) {
imp <- structure(list(what), names = getNamespaceName(from))
imports <- getNamespaceImports(ns)
setNamespaceInfo(ns, "imports", c(imports, imp))
}
namespaceIsSealed <- function(ns)
environmentIsLocked(ns)
makeImportExportNames <- function(spec) {
old <- as.character(spec)
new <- names(spec)
if (is.null(new)) new <- old
else new[new == ""] <- old[new == ""]
names(old) <- new
old
}
whichMethodMetaNames <- function(impvars) {
if(!.isMethodsDispatchOn())
return(numeric())
mm <- ".__T__"
seq_along(impvars)[substr(impvars, 1L, nchar(mm, type = "c")) == mm]
}
if (is.character(self))
self <- getNamespace(self)
ns <- asNamespace(ns)
nsname <- getNamespaceName(ns)
impvars <- if (missing(vars)) getNamespaceExports(ns) else vars
impvars <- makeImportExportNames(impvars)
impnames <- names(impvars)
if (anyDuplicated(impnames)) {
stop("duplicate import names ",
paste(impnames[duplicated(impnames)], collapse = ", "))
}
if (isNamespace(self) && isBaseNamespace(self)) {
impenv <- self
msg <- "replacing local value with import"
register <- FALSE
}
else if (isNamespace(self)) {
if (namespaceIsSealed(self))
stop("cannot import into a sealed name space")
impenv <- parent.env(self)
msg <- "replacing previous import"
register <- TRUE
}
else if (is.environment(self)) {
impenv <- self
msg <- "replacing local value with import"
register <- FALSE
}
else stop("invalid import target")
which <- whichMethodMetaNames(impvars)
if(length(which)) {
## If methods are already in impenv, merge and don't import
delete <- integer()
for(i in which) {
methodsTable <- .mergeImportMethods(impenv, ns, impvars[[i]])
if(is.null(methodsTable))
{} ## first encounter, just import it
else { ##
delete <- c(delete, i)
## eventually mlist objects will disappear, for now
## just don't import any duplicated names
mlname = sub("__T__", "__M__", impvars[[i]], fixed=TRUE)
ii = match(mlname, impvars, 0L)
if(ii > 0)
delete <- c(delete, ii)
if(!missing(generics)) {
genName <- generics[[i]]
if(i > length(generics) || !nzchar(genName))
{warning("got invalid index for importing ",mlname); next}
fdef <- methods:::getGeneric(genName,
where = impenv,
package = packages[[i]])
if(is.null(fdef))
warning(gettextf("Found methods to import for function \"%s\" but not the generic itself",
genName))
else
methods:::.updateMethodsInTable(fdef, ns, TRUE)
}
}
}
if(length(delete)) {
impvars <- impvars[-delete]
impnames <- impnames[-delete]
}
}
for (n in impnames)
if (exists(n, envir = impenv, inherits = FALSE)) {
if (.isMethodsDispatchOn() && methods:::isGeneric(n, ns)) {
## warn only if generic overwrites a function which
## it was not derived from
genNs <- methods:::slot(get(n, envir = ns), "package")
genImpenv <- environmentName(environment(get(n, envir = impenv)))
if (!identical(genNs, genImpenv) ||
## warning if generic overwrites another generic
methods:::isGeneric(n, impenv)) {}
else next
}
## this is always called from another function, so reporting call
## is unhelpful
warning(msg, " ", sQuote(n), " when loading ", sQuote(nsname),
call. = FALSE, domain = NA)
}
importIntoEnv(impenv, impnames, ns, impvars)
if (register)
addImports(self, ns, if (missing(vars)) TRUE else impvars)
}
namespaceImportClasses <- function(self, ns, vars) {
for(i in seq_along(vars))
vars[[i]] <- methods:::classMetaName(vars[[i]])
namespaceImportFrom(self, asNamespace(ns), vars)
}
namespaceImportMethods <- function(self, ns, vars) {
allVars <- character()
allFuns <- methods:::.getGenerics(ns)
packages <- attr(allFuns, "package")
tPrefix <- methods:::.TableMetaPrefix()
pkg <- methods:::getPackageName(ns)
allMethodTables <- methods:::.getGenerics(ns, tPrefix)
if(any(is.na(match(vars, allFuns))))
stop(gettextf("requested 'methods' objects not found in environment/package '%s': %s",
pkg,
paste(vars[is.na(match(vars, allFuns))],
collapse = ", ")), domain = NA)
for(i in seq_along(allFuns)) {
## import methods list objects if asked for
## or if the corresponding generic was imported
g <- allFuns[[i]]
if(exists(g, envir = self, inherits = FALSE) # already imported
|| g %in% vars) { # requested explicitly
tbl <- methods:::.TableMetaName(g, packages[[i]])
if(is.null(.mergeImportMethods(self, ns, tbl))) # a new methods table
allVars <- c(allVars, tbl) # import it;else, was merged
}
if(g %in% vars && !exists(g, envir = self, inherits = FALSE) &&
exists(g, envir = ns, inherits = FALSE) &&
methods:::is(get(g, envir = ns), "genericFunction"))
allVars <- c(allVars, g)
}
namespaceImportFrom(self, asNamespace(ns), allVars, allFuns, packages)
}
importIntoEnv <- function(impenv, impnames, expenv, expnames) {
exports <- getNamespaceInfo(expenv, "exports")
ex <- .Internal(ls(exports, TRUE))
if(!all(expnames %in% ex)) {
miss <- expnames[! expnames %in% ex]
stop(sprintf(ngettext(length(miss),
"object '%s' is not exported by 'namespace:%s'",
"objects '%s' are not exported by 'namespace:%s'"),
paste(sQuote(miss), collapse = ", "),
getNamespaceName(expenv)),
domain = NA)
}
expnames <- unlist(lapply(expnames, get, envir = exports, inherits = FALSE))
if (is.null(impnames)) impnames <- character(0L)
if (is.null(expnames)) expnames <- character(0L)
.Internal(importIntoEnv(impenv, impnames, expenv, expnames))
}
namespaceExport <- function(ns, vars) {
namespaceIsSealed <- function(ns)
environmentIsLocked(ns)
if (namespaceIsSealed(ns))
stop("cannot add to exports of a sealed name space")
ns <- asNamespace(ns, base.OK = FALSE)
if (length(vars)) {
addExports <- function(ns, new) {
exports <- getNamespaceInfo(ns, "exports")
expnames <- names(new)
intnames <- new
objs <- .Internal(ls(exports, TRUE))
ex <- expnames %in% objs
if(any(ex))
warning(sprintf(ngettext(sum(ex),
"previous export '%s' is being replaced",
"previous exports '%s' are being replaced"),
paste(sQuote(expnames[ex]), collapse = ", ")),
call. = FALSE, domain = NA)
for (i in seq_along(new))
assign(expnames[i], intnames[i], envir = exports)
}
makeImportExportNames <- function(spec) {
old <- as.character(spec)
new <- names(spec)
if (is.null(new)) new <- old
else new[new == ""] <- old[new == ""]
names(old) <- new
old
}
new <- makeImportExportNames(unique(vars))
## calling exists each time is too slow, so do two phases
undef <- new[! new %in% .Internal(ls(ns, TRUE))]
undef <- undef[! sapply(undef, exists, envir = ns)]
if (length(undef)) {
undef <- do.call("paste", as.list(c(undef, sep = ", ")))
stop("undefined exports: ", undef)
}
if(.isMethodsDispatchOn()) .mergeExportMethods(new, ns)
addExports(ns, new)
}
}
.mergeExportMethods <- function(new, ns) {
## if(!.isMethodsDispatchOn()) return(FALSE)
mm <- methods:::methodsPackageMetaName("M","")
newMethods <- new[substr(new, 1L, nchar(mm, type = "c")) == mm]
nsimports <- parent.env(ns)
for(what in newMethods) {
if(exists(what, envir = nsimports, inherits = FALSE)) {
m1 <- get(what, envir = nsimports)
m2 <- get(what, envir = ns)
assign(what, envir = ns, methods:::mergeMethods(m1, m2))
}
}
}
## NB this needs a decorated name, foo_ver, if appropriate
packageHasNamespace <- function(package, package.lib) {
namespaceFilePath <- function(package, package.lib)
file.path(package.lib, package, "NAMESPACE")
file.exists(namespaceFilePath(package, package.lib))
}
parseNamespaceFile <- function(package, package.lib, mustExist = TRUE)
{
namespaceFilePath <- function(package, package.lib)
file.path(package.lib, package, "NAMESPACE")
## These two functions are essentially local to the parsing of
## the namespace file and don't need to be made available to
## users. These manipulate the data from useDynLib() directives
## for the same DLL to determine how to map the symbols to R
## variables.
nativeRoutineMap <-
## Creates a new NativeRoutineMap.
function(useRegistration, symbolNames, fixes) {
proto <- list(useRegistration = FALSE,
symbolNames = character(0L))
class(proto) <- "NativeRoutineMap"
mergeNativeRoutineMaps(proto, useRegistration, symbolNames, fixes)
}
mergeNativeRoutineMaps <-
## Merges new settings into a NativeRoutineMap
function(map, useRegistration, symbolNames, fixes) {
if(!useRegistration)
names(symbolNames) <-
paste(fixes[1L], names(symbolNames), fixes[2L], sep = "")
else
map$registrationFixes <- fixes
map$useRegistration <- map$useRegistration || useRegistration
map$symbolNames <- c(map$symbolNames, symbolNames)
map
}
nsFile <- namespaceFilePath(package, package.lib)
descfile <- file.path(package.lib, package, "DESCRIPTION")
enc <- NA
if (file.exists(descfile)) {
dcf <- read.dcf(file = descfile)
if(NROW(dcf) >= 1) enc <- as.list(dcf[1, ])[["Encoding"]]
if(is.null(enc)) enc <- NA
}
if (file.exists(nsFile))
directives <- if (!is.na(enc) &&
! Sys.getlocale("LC_CTYPE") %in% c("C", "POSIX")) {
con <- file(nsFile, encoding=enc)
on.exit(close(con))
parse(con)
} else parse(nsFile)
else if (mustExist)
stop(gettextf("package '%s' has no NAMESPACE file", package),
domain = NA)
else directives <- NULL
exports <- character(0L)
exportPatterns <- character(0L)
exportClasses <- character(0L)
exportClassPatterns <- character(0L)
exportMethods <- character(0L)
imports <- list()
importMethods <- list()
importClasses <- list()
dynlibs <- character(0L)
S3methods <- matrix(NA_character_, 500L, 3L)
nativeRoutines <- list()
nS3 <- 0
parseDirective <- function(e) {
## trying to get more helpful error message:
asChar <- function(cc) {
r <- as.character(cc)
if(any(r == ""))
stop(gettextf("empty name in directive '%s' in NAMESPACE file",
as.character(e[[1L]])),
domain = NA)
r
}
switch(as.character(e[[1L]]),
"if" = if (eval(e[[2L]], .GlobalEnv))
parseDirective(e[[3L]])
else if (length(e) == 4L)
parseDirective(e[[4L]]),
"{" = for (ee in as.list(e[-1L])) parseDirective(ee),
"=", "<-" = {
parseDirective(e[[3L]])
if(as.character(e[[3L]][[1L]]) == "useDynLib")
names(dynlibs)[length(dynlibs)] <<- asChar(e[[2L]])
},
export = {
exp <- e[-1L]
exp <- structure(asChar(exp), names = names(exp))
exports <<- c(exports, exp)
},
exportPattern = {
pat <- asChar(e[-1L])
exportPatterns <<- c(pat, exportPatterns)
},
exportClassPattern = {
pat <- asChar(e[-1L])
exportClassPatterns <<- c(pat, exportClassPatterns)
},
exportClass = , exportClasses = {
exportClasses <<- c(asChar(e[-1L]), exportClasses)
},
exportMethods = {
exportMethods <<- c(asChar(e[-1L]), exportMethods)
},
import = imports <<- c(imports,as.list(asChar(e[-1L]))),
importFrom = {
imp <- e[-1L]
ivars <- imp[-1L]
inames <- names(ivars)
imp <- list(asChar(imp[1L]),
structure(asChar(ivars), names = inames))
imports <<- c(imports, list(imp))
},
importClassFrom = , importClassesFrom = {
imp <- asChar(e[-1L])
pkg <- imp[[1L]]
impClasses <- imp[-1L]
imp <- list(asChar(pkg), asChar(impClasses))
importClasses <<- c(importClasses, list(imp))
},
importMethodsFrom = {
imp <- asChar(e[-1L])
pkg <- imp[[1L]]
impMethods <- imp[-1L]
imp <- list(asChar(pkg), asChar(impMethods))
importMethods <<- c(importMethods, list(imp))
},
useDynLib = {
## This attempts to process as much of the
## information as possible when NAMESPACE is parsed
## rather than when it is loaded and creates
## NativeRoutineMap objects to handle the mapping
## of symbols to R variable names.
## The name is the second element after useDynLib
dyl <- as.character(e[2L])
## We ensure uniqueness at the end.
dynlibs <<-
structure(c(dynlibs, dyl),
names = c(names(dynlibs),
ifelse(!is.null(names(e)) &&
names(e)[2L] != "", names(e)[2L], "" )))
if (length(e) > 2L) {
## Author has specified some mappings for the symbols
symNames <- as.character(e[-c(1L, 2L)])
names(symNames) <- names(e[-c(1, 2)])
## If there are no names, then use the names of
## the symbols themselves.
if (length(names(symNames)) == 0L)
names(symNames) = symNames
else if (any(w <- names(symNames) == "")) {
names(symNames)[w] = symNames[w]
}
## For each DLL, we build up a list the (R
## variable name, symbol name) mappings. We do
## this in a NativeRoutineMap object and we
## merge potentially multiple useDynLib()
## directives for the same DLL into a single
## map. Then we have separate NativeRoutineMap
## for each different DLL. E.g. if we have
## useDynLib(foo, a, b, c) and useDynLib(bar,
## a, x, y) we would maintain and resolve them
## separately.
dup <- duplicated(names(symNames))
if (any(dup))
warning("duplicated symbol names ",
paste(names(symNames)[dup],
collapse = ", "),
" in useDynLib(", dyl, ")")
symNames <- symNames[!dup]
## Deal with any prefix/suffix pair.
fixes <- c("", "")
idx <- match(".fixes", names(symNames))
if(!is.na(idx)) {
## Take .fixes and treat it as a call,
## e.g. c("pre", "post") or a regular name
## as the prefix.
if(symNames[idx] != "") {
e <- parse(text = symNames[idx])[[1L]]
if(is.call(e))
val <- eval(e)
else
val <- as.character(e)
if(length(val))
fixes[seq_along(val)] <- val
}
symNames <- symNames[-idx]
}
## Deal with a .registration entry. It must be
## .registration = value and value will be coerced
## to a logical.
useRegistration <- FALSE
idx <- match(".registration", names(symNames))
if(!is.na(idx)) {
useRegistration <- as.logical(symNames[idx])
symNames <- symNames[-idx]
}
## Now merge into the NativeRoutineMap.
nativeRoutines[[ dyl ]] <<-
if(dyl %in% names(nativeRoutines))
mergeNativeRoutineMaps(nativeRoutines[[ dyl ]],
useRegistration,
symNames, fixes)
else
nativeRoutineMap(useRegistration, symNames,
fixes)
}
},
S3method = {
spec <- e[-1L]
if (length(spec) != 2L && length(spec) != 3L)
stop(gettextf("bad 'S3method' directive: %s",
deparse(e)),
call. = FALSE, domain = NA)
nS3 <<- nS3 + 1L
if(nS3 > 500L)
stop("too many 'S3method' directives", call. = FALSE)
S3methods[nS3, seq_along(spec)] <<- asChar(spec)
},
stop(gettextf("unknown namespace directive: %s", deparse(e)),
call. = FALSE, domain = NA)
)
}
for (e in directives)
parseDirective(e)
dynlibs <- unique(dynlibs)
list(imports = imports, exports = exports, exportPatterns = exportPatterns,
importClasses = importClasses, importMethods = importMethods,
exportClasses = exportClasses, exportMethods = exportMethods,
exportClassPatterns = exportClassPatterns,
dynlibs = dynlibs, nativeRoutines = nativeRoutines,
S3methods = S3methods[seq_len(nS3), ,drop = FALSE])
} ## end{parseNamespaceFile}
registerS3method <- function(genname, class, method, envir = parent.frame()) {
addNamespaceS3method <- function(ns, generic, class, method) {
regs <- getNamespaceInfo(ns, "S3methods")
regs <- rbind(regs, c(generic, class, method))
setNamespaceInfo(ns, "S3methods", regs)
}
groupGenerics <- c("Math", "Ops", "Summary", "Complex")
defenv <- if(genname %in% groupGenerics) .BaseNamespaceEnv
else {
genfun <- get(genname, envir = envir)
if(.isMethodsDispatchOn() && methods:::is(genfun, "genericFunction"))
genfun <- methods:::slot(genfun, "default")@methods$ANY
if (typeof(genfun) == "closure") environment(genfun)
else .BaseNamespaceEnv
}
if (! exists(".__S3MethodsTable__.", envir = defenv, inherits = FALSE))
assign(".__S3MethodsTable__.", new.env(hash = TRUE, parent = baseenv()),
envir = defenv)
table <- get(".__S3MethodsTable__.", envir = defenv, inherits = FALSE)
if (is.character(method)) {
assignWrapped <- function(x, method, home, envir) {
method <- method # force evaluation
home <- home # force evaluation
delayedAssign(x, get(method, envir = home), assign.env = envir)
}
if(!exists(method, envir = envir)) {
warning(gettextf("S3 method '%s' was declared in NAMESPACE but not found",
method), call. = FALSE)
} else {
assignWrapped(paste(genname, class, sep = "."), method, home = envir,
envir = table)
}
}
else if (is.function(method))
assign(paste(genname, class, sep = "."), method, envir = table)
else stop("bad method")
if (isNamespace(envir) && ! identical(envir, .BaseNamespaceEnv))
addNamespaceS3method(envir, genname, class, method)
}
registerS3methods <- function(info, package, env)
{
n <- NROW(info)
if(n == 0) return()
assignWrapped <- function(x, method, home, envir) {
method <- method # force evaluation
home <- home # force evaluation
delayedAssign(x, get(method, envir = home), assign.env = envir)
}
.registerS3method <- function(genname, class, method, nm, envir)
{
## S3 generics should either be imported explicitly or be in
## the base namespace, so we start the search at the imports
## environment, parent.env(envir), which is followed by the
## base namespace. (We have already looked in the namespace.)
## However, in case they have not been imported, we first
## look up where some commonly used generics are (including the
## group generics).
defenv <- if(!is.na(w <- .knownS3Generics[genname])) asNamespace(w)
else {
if(!exists(genname, envir = parent.env(envir)))
stop(gettextf("object '%s' not found whilst loading namespace '%s'",
genname, package), call. = FALSE, domain = NA)
genfun <- get(genname, envir = parent.env(envir))
if(.isMethodsDispatchOn() && methods:::is(genfun, "genericFunction")) {
genfun <- methods:::slot(genfun, "default")@methods$ANY
warning(gettextf("found an S4 version of '%s' so it has not been imported correctly",
genname), call. = FALSE, domain = NA)
}
if (typeof(genfun) == "closure") environment(genfun)
else .BaseNamespaceEnv
}
if (! exists(".__S3MethodsTable__.", envir = defenv, inherits = FALSE))
assign(".__S3MethodsTable__.", new.env(hash = TRUE, parent = baseenv()),
envir = defenv)
table <- get(".__S3MethodsTable__.", envir = defenv, inherits = FALSE)
assignWrapped(nm, method, home = envir, envir = table)
}
methname <- paste(info[,1], info[,2], sep = ".")
z <- is.na(info[,3])
info[z,3] <- methname[z]
Info <- cbind(info, methname)
loc <- .Internal(ls(env, TRUE))
notex <- !(info[,3] %in% loc)
if(any(notex))
warning(sprintf(ngettext(sum(notex),
"S3 method %s was declared in NAMESPACE but not found",
"S3 methods %s were declared in NAMESPACE but not found"),
paste(sQuote(info[notex, 3]), collapse = ", ")),
call. = FALSE, domain = NA)
Info <- Info[!notex, , drop = FALSE]
## Do local generics first (this could be load-ed if pre-computed).
## However, the local generic could be an S4 takeover of a non-local
## (or local) S3 generic. We can't just pass S4 generics on to
## .registerS3method as that only looks non-locally (for speed).
l2 <- localGeneric <- Info[,1] %in% loc
if(.isMethodsDispatchOn())
for(i in which(localGeneric)) {
genfun <- get(Info[i, 1], envir = env)
if(methods:::is(genfun, "genericFunction")) {
localGeneric[i] <- FALSE
registerS3method(Info[i, 1], Info[i, 2], Info[i, 3], env)
}
}
if(any(localGeneric)) {
lin <- Info[localGeneric, , drop = FALSE]
S3MethodsTable <-
get(".__S3MethodsTable__.", envir = env, inherits = FALSE)
## we needed to move this to C for speed.
## for(i in seq_len(nrow(lin)))
## assign(lin[i,4], get(lin[i,3], envir = env),
## envir = S3MethodsTable)
.Internal(importIntoEnv(S3MethodsTable, lin[,4], env, lin[,3]))
}
## now the rest
fin <- Info[!l2, , drop = FALSE]
for(i in seq_len(nrow(fin)))
.registerS3method(fin[i, 1], fin[i, 2], fin[i, 3], fin[i, 4], env)
setNamespaceInfo(env, "S3methods",
rbind(info, getNamespaceInfo(env, "S3methods")))
}
.mergeImportMethods <- function(impenv, expenv, metaname)
{
expMethods <- get(metaname, envir = expenv)
if(exists(metaname, envir = impenv, inherits = FALSE)) {
impMethods <- get(metaname, envir = impenv)
assign(metaname,
methods:::.mergeMethodsTable2(impMethods,
expMethods, expenv, metaname),
envir = impenv)
impMethods
} else NULL
}
|
//
// ArtistInfoVIew.swift
// Spotify Challenge
//
// Created by Daniel Azuaje on 9/12/22.
//
import UIKit
class ArtistInfoView: UIView {
lazy var artistNameLabel: UILabel = {
let label = UILabel()
label.font = .appBold(size: 24)
label.textColor = .white
label.numberOfLines = 1
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var genresLabel: UILabel = {
let label = UILabel()
label.font = .appMedium(size: 16)
label.text = "Genrea"
label.textColor = .white
label.numberOfLines = 1
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var genresValueLabel: UILabel = {
let label = UILabel()
label.font = .appRegular(size: 14)
label.textColor = .white
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var followersLabel: UILabel = {
let label = UILabel()
label.font = .appMedium(size: 16)
label.text = "Followers"
label.textColor = .white
label.numberOfLines = 1
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var followersValueLabel: UILabel = {
let label = UILabel()
label.font = .appRegular(size: 14)
label.textColor = .white
label.numberOfLines = 1
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: .zero)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
addSubview(artistNameLabel)
artistNameLabel.topToSuperView()
artistNameLabel.pinHorizontalEdges()
artistNameLabel.setHeight(35)
addSubview(genresLabel)
genresLabel.topTo(view: artistNameLabel, padding: 4)
genresLabel.pinHorizontalEdges()
genresLabel.setHeight(24)
addSubview(genresValueLabel)
genresValueLabel.topTo(view: genresLabel, padding: 0)
genresValueLabel.pinHorizontalEdges()
genresValueLabel.setHeight(20)
addSubview(followersLabel)
followersLabel.topTo(view: genresValueLabel, padding: 4)
followersLabel.pinHorizontalEdges()
followersLabel.setHeight(24)
addSubview(followersValueLabel)
followersValueLabel.topTo(view: followersLabel, padding: 0)
followersValueLabel.pinHorizontalEdges()
followersValueLabel.setHeight(20)
followersValueLabel.bottomToSuperView()
}
func setup(artist: Artist) {
artistNameLabel.text = artist.name
genresValueLabel.text = (artist.genres ?? []).joined(separator: ", ")
followersValueLabel.text = "\(artist.followers?.total ?? 0)"
}
}
|
/**
* SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com
* SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
*/
package com.liferay.journal.web.internal.display.context;
import com.liferay.dynamic.data.mapping.configuration.DDMWebConfiguration;
import com.liferay.dynamic.data.mapping.model.DDMStructure;
import com.liferay.dynamic.data.mapping.model.DDMTemplate;
import com.liferay.frontend.taglib.clay.servlet.taglib.display.context.SearchContainerManagementToolbarDisplayContext;
import com.liferay.frontend.taglib.clay.servlet.taglib.util.CreationMenu;
import com.liferay.frontend.taglib.clay.servlet.taglib.util.DropdownItem;
import com.liferay.frontend.taglib.clay.servlet.taglib.util.DropdownItemListBuilder;
import com.liferay.journal.constants.JournalPortletKeys;
import com.liferay.journal.model.JournalArticle;
import com.liferay.journal.web.internal.security.permission.resource.DDMTemplatePermission;
import com.liferay.petra.string.StringBundler;
import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Group;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.portlet.LiferayPortletRequest;
import com.liferay.portal.kernel.portlet.LiferayPortletResponse;
import com.liferay.portal.kernel.portlet.url.builder.PortletURLBuilder;
import com.liferay.portal.kernel.security.permission.ActionKeys;
import com.liferay.portal.kernel.template.TemplateConstants;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.staging.StagingGroupHelper;
import com.liferay.staging.StagingGroupHelperUtil;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/**
* @author Eudaldo Alonso
*/
public class JournalDDMTemplateManagementToolbarDisplayContext
extends SearchContainerManagementToolbarDisplayContext {
public JournalDDMTemplateManagementToolbarDisplayContext(
HttpServletRequest httpServletRequest,
LiferayPortletRequest liferayPortletRequest,
LiferayPortletResponse liferayPortletResponse,
JournalDDMTemplateDisplayContext journalDDMTemplateDisplayContext)
throws Exception {
super(
httpServletRequest, liferayPortletRequest, liferayPortletResponse,
journalDDMTemplateDisplayContext.getDDMTemplateSearchContainer());
_ddmWebConfiguration =
(DDMWebConfiguration)httpServletRequest.getAttribute(
DDMWebConfiguration.class.getName());
_journalDDMTemplateDisplayContext = journalDDMTemplateDisplayContext;
}
@Override
public List<DropdownItem> getActionDropdownItems() {
return DropdownItemListBuilder.add(
dropdownItem -> {
dropdownItem.putData("action", "deleteDDMTemplates");
dropdownItem.setIcon("trash");
dropdownItem.setLabel(
LanguageUtil.get(httpServletRequest, "delete"));
dropdownItem.setQuickAction(true);
}
).build();
}
public String getAvailableActions(DDMTemplate ddmTemplate)
throws PortalException {
ThemeDisplay themeDisplay =
(ThemeDisplay)httpServletRequest.getAttribute(
WebKeys.THEME_DISPLAY);
if (DDMTemplatePermission.contains(
themeDisplay.getPermissionChecker(), ddmTemplate,
ActionKeys.DELETE)) {
return "deleteDDMTemplates";
}
return StringPool.BLANK;
}
@Override
public String getClearResultsURL() {
return PortletURLBuilder.create(
getPortletURL()
).setKeywords(
StringPool.BLANK
).buildString();
}
@Override
public String getComponentId() {
return "ddmTemplateManagementToolbar";
}
@Override
public CreationMenu getCreationMenu() {
ThemeDisplay themeDisplay =
(ThemeDisplay)httpServletRequest.getAttribute(
WebKeys.THEME_DISPLAY);
return new CreationMenu() {
{
addPrimaryDropdownItem(
dropdownItem -> {
dropdownItem.setHref(
liferayPortletResponse.createRenderURL(), "mvcPath",
"/edit_ddm_template.jsp", "redirect",
themeDisplay.getURLCurrent(), "classPK",
_journalDDMTemplateDisplayContext.getClassPK());
dropdownItem.setLabel(
LanguageUtil.format(
httpServletRequest, "add-x",
StringBundler.concat(
LanguageUtil.get(
httpServletRequest,
TemplateConstants.LANG_TYPE_FTL +
"[stands-for]"),
StringPool.SPACE,
StringPool.OPEN_PARENTHESIS,
StringPool.PERIOD,
TemplateConstants.LANG_TYPE_FTL,
StringPool.CLOSE_PARENTHESIS),
false));
});
}
};
}
@Override
public String getSearchContainerId() {
return "ddmTemplates";
}
@Override
public Boolean isSelectable() {
ThemeDisplay themeDisplay =
(ThemeDisplay)httpServletRequest.getAttribute(
WebKeys.THEME_DISPLAY);
User user = themeDisplay.getUser();
return !user.isGuestUser();
}
@Override
public Boolean isShowCreationMenu() {
ThemeDisplay themeDisplay =
(ThemeDisplay)httpServletRequest.getAttribute(
WebKeys.THEME_DISPLAY);
Group group = themeDisplay.getScopeGroup();
StagingGroupHelper stagingGroupHelper =
StagingGroupHelperUtil.getStagingGroupHelper();
if ((stagingGroupHelper.isLocalLiveGroup(group) ||
stagingGroupHelper.isRemoteLiveGroup(group)) &&
stagingGroupHelper.isStagedPortlet(
group, JournalPortletKeys.JOURNAL)) {
return false;
}
try {
if (_ddmWebConfiguration.enableTemplateCreation() &&
DDMTemplatePermission.containsAddTemplatePermission(
themeDisplay.getPermissionChecker(),
themeDisplay.getScopeGroupId(),
PortalUtil.getClassNameId(DDMStructure.class),
PortalUtil.getClassNameId(JournalArticle.class))) {
return true;
}
}
catch (Exception exception) {
if (_log.isDebugEnabled()) {
_log.debug(exception);
}
}
return false;
}
@Override
protected String getDefaultDisplayStyle() {
return "icon";
}
@Override
protected String getDisplayStyle() {
return _journalDDMTemplateDisplayContext.getDisplayStyle();
}
@Override
protected String[] getDisplayViews() {
return new String[] {"list", "icon"};
}
@Override
protected String[] getOrderByKeys() {
return new String[] {"modified-date", "name", "id"};
}
private static final Log _log = LogFactoryUtil.getLog(
JournalDDMTemplateManagementToolbarDisplayContext.class);
private final DDMWebConfiguration _ddmWebConfiguration;
private final JournalDDMTemplateDisplayContext
_journalDDMTemplateDisplayContext;
}
|
#include "interpreter_debugPrinter.h"
// The border to display on the top screen.
const char topScreenBorderText[] = {
"--------------------------------"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"--------------------------------"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"| |"
"--------------------------------"
};
// Create a top screen screen console for text.
PrintConsole topScreenBorder, topScreenPC, topScreenMemory, topScreenRegisters;
/*
* Initializes the system for the debug printer.
*/
void initDebugPrinter()
{
// Initialize the top screen's border text console.
consoleInit(&topScreenBorder, 0, BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
// Initialize the top screen's program counter text console.
consoleInit(&topScreenPC, 1, BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
// Initialize the top screen's memory text console.
consoleInit(&topScreenMemory, 2, BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
// Initialize the top screen's registers text console.
consoleInit(&topScreenRegisters, 3, BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
// Set the border console's window position and size.
consoleSetWindow(&topScreenBorder, 0, 0, 32, 24);
// Set the program counter console's window position and size.
consoleSetWindow(&topScreenPC, 1, 1, 10, 2);
// Set the memory console's window position and size.
consoleSetWindow(&topScreenMemory, 1, 1, 32 - 2, 24 / 2 - 2);
// Set the registers console's window position and size.
consoleSetWindow(&topScreenRegisters, 1, 24 / 2 + 1, 32 - 2, 24 / 2 - 2);
}
/*
* Prints the border on the top screen of the Nintendo DS.
*/
void printTopScreenBorder()
{
// Select the top console.
consoleSelect(&topScreenBorder);
// Clear the text.
consoleClear();
// Print the border to the screen.
iprintf("\x1b[%d;%dH%s", 0, 0, topScreenBorderText);
}
/*
* Prints the memory, registers, and program counter
* for the interpreter.
*/
void printInterpreterSystemInfo()
{
// Select the top console's memory section.
consoleSelect(&topScreenMemory);
// Clear the console.
consoleClear();
// Print the Memory title.
iprintf("\x1b[%d;%dH%s", 0, 32 / 2 - 4, "Memory");
// Position the cursor to 0, 1.
iprintf("\x1b[%d;%dH", 2, 0);
// Create a foor loop variable.
int i = 0;
// Loop through all of the memory.
for(i = 0;i < MAX_MEM;i += 1)
{
// Check if 5 memory cells are displayed
if(i != 0 && i % 5 == 0)
{
// If so, print the next one on a new line.
iprintf("\n\nM%d:%d\t", i + 1, memory[i]);
}
else
{
// Otherwise, just print out the memory cell.
iprintf("M%d:%d\t", i, memory[i]);
}
}
// Select the top console's registers section.
consoleSelect(&topScreenRegisters);
// Clear the console.
consoleClear();
// Print the Registers title.
iprintf("\x1b[%d;%dH%s", 0, 32 / 2 - 6, "Registers");
// Position the cursor to 0, 1.
iprintf("\x1b[%d;%dH", 2, 0);
// Loop through all of the registers.
for(i = 0;i < MAX_REG;i += 1)
{
// Check if 5 registers are displayed
if(i != 0 && i % 5 == 0)
{
// If so, print the next one on a new line.
iprintf("\n\nR%d:%d\t", i + 1, registers[i]);
}
else
{
// Otherwise, just print out the register.
iprintf("R%d:%d\t", i, registers[i]);
}
}
// Check if 5 registers are displayed
if(i != 0 && i % 5 == 0)
{
// If so, print the accumulator on a new line.
iprintf("\n\nAC:%d\t", reg_ac);
}
else
{
// Otherwise, just print out the accumulator.
iprintf("AC:%d\t", reg_ac);
}
// Select the top console's program counter section.
consoleSelect(&topScreenPC);
// Clear the console.
consoleClear();
// Print the program counter.
iprintf("\x1b[%d;%dH%s%d", 0, 0, "PC: ", pc);
}
|
import java.awt.*;
public class Board {
// grid line width
public static final int GRID_WIDTH = 8;
// grid line half width
public static final int GRID_WIDTH_HALF = GRID_WIDTH / 2;
//2D array of ROWS-by-COLS Cell instances
public Cell [][] cells;
/** Constructor to create the game board */
public Board() {
// initialize the cells array using ROWS and COLS constants
this.cells = new Cell[GameMain.ROWS][GameMain.COLS];
for (int row = 0; row < GameMain.ROWS; ++row) {
for (int col = 0; col < GameMain.COLS; ++col) {
this.cells[row][col] = new Cell(row, col);
}
}
}
/** Return true if it is a draw (i.e., no more EMPTY cells) */
public boolean isDraw() {
// Check whether the game has ended in a draw.
// Note: Assume we have already checked for a win first
// Iterate each cell in cells
for (int row = 0; row < GameMain.ROWS; ++row) {
for (int col = 0; col < GameMain.COLS; ++col) {
// if this cell is blank then return false and exit
if (this.cells[row][col].content == Player.Empty) {
return false;
}
}
}
// If we have iterated each cell and it is filled in then the game is a draw
return true;
}
/** Return true if the current player "thePlayer" has won after making their move */
public boolean hasWon(Player thePlayer, int playerRow, int playerCol) {
// check if player has 3-in-that-row
if(this.cells[playerRow][0].content == thePlayer && this.cells[playerRow][1].content == thePlayer && this.cells[playerRow][2].content == thePlayer ) {
return true;
}
// check if player has 3-in-that-col
if(this.cells[0][playerCol].content == thePlayer && this.cells[1][playerCol].content == thePlayer && this.cells[2][playerCol].content == thePlayer ) {
return true;
}
// 3-in-the-diagonal
if( this.cells[0][0].content == thePlayer && this.cells[1][1].content == thePlayer && this.cells[2][2].content == thePlayer) {
return true;
}
// 3-in-the-other-diagonal
if( this.cells[0][2].content == thePlayer && this.cells[1][1].content == thePlayer && this.cells[2][0].content == thePlayer) {
return true;
}
//no winner, keep playing
return false;
}
/**
* Draws the grid (rows then columns) using constant sizes, then call on the
* Cells to paint themselves into the grid
*/
public void paint(Graphics g) {
//draw the grid
g.setColor(Color.gray);
for (int row = 1; row < GameMain.ROWS; ++row) {
g.fillRoundRect(0, GameMain.CELL_SIZE * row - GRID_WIDTH_HALF,
GameMain.CANVAS_WIDTH - 1, GRID_WIDTH,
GRID_WIDTH, GRID_WIDTH);
}
for (int col = 1; col < GameMain.COLS; ++col) {
g.fillRoundRect(GameMain.CELL_SIZE * col - GRID_WIDTH_HALF, 0,
GRID_WIDTH, GameMain.CANVAS_HEIGHT - 1,
GRID_WIDTH, GRID_WIDTH);
}
//Draw the cells
for (int row = 0; row < GameMain.ROWS; ++row) {
for (int col = 0; col < GameMain.COLS; ++col) {
cells[row][col].paint(g);
}
}
}
}
|
package com.groupfour.foodbox.service.user;
import com.groupfour.foodbox.domain.UserDTO;
import com.groupfour.foodbox.mapper.user.UserLoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;
@Service
public class UserLoginServiceImpl implements UserLoginService {
@Autowired
UserLoginMapper userLoginMapper;
@Autowired
JavaMailSender mailSender;
@Autowired
PasswordEncoder passwordEncoder;
//유저정보 가져오기(카카오로그인)
public UserDTO getUser(String user_id) {
// 익명클래스를 사용하면 가독성이 떨어져서 람다식으로 치환해서 사용한다.
// User findUser = userRepository.findByUsername(username).orElseGet(new Supplier<User>() {
// @Override
// public User get() {
// return new User();
// }
// });
// 검색결과가 없으면 빈 객체를 리턴한다.
UserDTO findUser = userLoginMapper.findByUserId(user_id).orElseGet(()->{
return new UserDTO();
});
return findUser;
}
// 로그인 하기
@Override
public boolean userLogin(UserDTO userDto, HttpServletRequest req) {
HttpSession session = req.getSession();
// 아이디와 일치하는 회원정보를 DTO에 담아서 가져옴
UserDTO userLoginDto = userLoginMapper.userLogin(userDto);
if(userLoginDto != null){ // 일치하는 아이디가 있는 경우
String inputPw= userDto.getUser_pw(); // 사용자가 입력한 비번
String dbPw = userLoginDto.getUser_pw(); // DB 비번
if(true ==passwordEncoder.matches(inputPw,dbPw)){ // 비번 일치
session.setAttribute("userLoginDto", userLoginDto);
System.out.println("로그인 성공");
return true;
}else{ // 비번 불일치
System.out.println("로그인 실패");
return false;
}
}
return false;
}
// 아이디 찾기
@Override
public String findId(String name, String email) {
String resultId= userLoginMapper.findId(name, email);
return resultId;
}
// 비밀번호 찾기
@Override
public int findPw(String uid, String uEmail) {
// 임시비밀번호
String tempPw = UUID.randomUUID().toString().substring(0,6);
MimeMessage mail = mailSender.createMimeMessage();
String mailContents = "<h3>임시 비밀번호 발급</h3></br>"
+"<h2>"+tempPw+"</h2>"
+"<p>로그인 후 마이페이지에서 비밀번호를 변경해주면 됩니다.</p>";
try {
mail.setSubject("푸드박스 [임시 비밀번호]", "utf-8");
mail.setText(mailContents, "utf-8", "html");
// 상대방 메일 셋팅
mail.addRecipient(Message.RecipientType.TO, new InternetAddress(uEmail));
mailSender.send(mail);
} catch (Exception e) {
e.printStackTrace();
}
tempPw = passwordEncoder.encode(tempPw);
int n = userLoginMapper.findPw(uid, uEmail, tempPw);
return n;
}
}
|
import axios from "axios";
import { useState } from "react";
import { Link } from "react-router-dom";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import Navbar from "../../components/navbar/Navbar";
import Topbar from "../../components/topbar/Topbar";
import Footer from "../../components/footer/Footer";
import { loginStart,loginSuccess,loginFailure } from "../../redux/userRedux";
import "./login.css";
const Login = () => {
// const user=useSelector(state=>state.user);
const dispatch=useDispatch();
const [credentials, setCredentials] = useState({
email: undefined,
password: undefined,
});
const [loginErr, setLoginErr] = useState(false);
// const { loading, error, dispatch } = useContext(AuthContext);
const navigate = useNavigate();
const handleChange = (e) => {
setCredentials((prev) => ({ ...prev, [e.target.id]: e.target.value }));
};
const handleClick = async (e) => {
e.preventDefault();
dispatch(loginStart());
try {
const res = await axios.post("http://localhost:8000/api/auth/login", credentials);
if (res.data === "User Not Found !!.." || res.data === "OOps ! Invalid Credentials...") {
dispatch(loginFailure());
setLoginErr(true);
navigate("/login");
} else {
dispatch(loginSuccess(res.data));
navigate("/");
console.log(res.data);
}
} catch (err) {
dispatch(loginFailure());
}
};
// console.log(user.currentUser);
return (
<>
<Topbar/>
<Navbar />
<div className="login-div">
<div className="loginContainer">
<input
type="email"
placeholder="username"
id="email"
onChange={handleChange}
className="loginInput"
/>
<input
type="password"
placeholder="password"
id="password"
onChange={handleChange}
className="loginInput"
/>
<button
// disabled={loading}
onClick={handleClick}
className="loginButton">
Login
</button>
{/* {loginErr && <span>loginErr</span>} */}
{loginErr ? <span style={{ color: "red" }}>Wrong Credentials !!...</span> : <span></span>}
<div>
<br></br>
<hr/>
<h5>Don't have an account ?.</h5>
<br/>
<Link to="/register">Register here !.</Link>
</div>
</div>
</div>
<Footer />
</>
);
};
export default Login;
|
/*
--- Directions
Create a stack data structure. The stack
should be a class with methods 'push', 'pop', and
'peek'. Adding an element to the stack should
store it until it is removed.
--- Examples
const s = new Stack();
s.push(1);
s.push(2);
s.pop(); // returns 2
s.pop(); // returns 1
*/
class Stack {
constructor() {
this.data = [];
}
push(value) {
this.data.push(value);
}
pop() {
return this.data.pop();
}
peek() {
return this.data[this.data.length - 1];
}
}
module.exports = Stack;
|
class QueueWithStacks {
constructor() {
this.in = [];
this.out = [];
}
enqueue(val) {
this.in.push(val);
}
dequeue() {
if (this.out.length === 0) {
while(this.in.length > 0) {
this.out.push(this.in.pop());
}
}
return this.out.pop();
}
peek() {
if (this.out.length === 0) {
while(this.in.length > 0) {
this.out.push(this.in.pop());
}
}
return this.out[this.out.length - 1];
}
empty() {
return this.in.length === 0 && this.out.length === 0;
}
}
const queue = new QueueWithStacks();
queue.enqueue(5);
queue.enqueue(10);
queue.enqueue(15);
queue.enqueue(20);
queue.enqueue(25);
console.log(queue);
console.log(queue.dequeue());
console.log(queue.peek());
|
package streamapi.Collectors;
import streamapi.Phone2;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MaxByMinBy {
public static void main(String[] args) {
Stream<Phone2> phoneStream = Stream.of(new Phone2("iPhone X", "Apple", 600),
new Phone2("Pixel 2", "Google", 500),
new Phone2("iPhone 8", "Apple", 450),
new Phone2("Galaxy S9", "Samsung", 440),
new Phone2("Galaxy S8", "Samsung", 340));
Map<String, Optional<Phone2>> phonesByCompany = phoneStream.collect(
Collectors.groupingBy(Phone2::getCompany,
Collectors.minBy(Comparator.comparing(Phone2::getPrice))));
for(Map.Entry<String, Optional<Phone2>> item : phonesByCompany.entrySet()){
System.out.println(item.getKey() + " - " + item.getValue().get().getName());
}
}
}
|
(function() {
var FILTER = _CMProxy.parameter.FILTER;
var SOURCE_CLASS_NAME = _CMProxy.parameter.SOURCE_CLASS_NAME;
Ext.define("CMDBuild.delegate.administration.common.dataview.CMFilterDataViewFormFieldsManager", {
extend: "CMDBuild.delegate.administration.common.basepanel.CMBaseFormFiledsManager",
mixins: {
delegable: "CMDBuild.core.CMDelegable"
},
constructor: function() {
this.mixins.delegable.constructor.call(this,
"CMDBuild.delegate.administration.common.dataview.CMFilterDataViewFormDelegate");
this.callParent(arguments);
},
/**
* @return {array} an array of Ext.component to use as form items
*/
build: function() {
var me = this;
var fields = this.callParent(arguments);
Ext.apply(this.description, {
translationsKeyType: "FilterView",
translationsKeyField: "Description"
});
this.classes = new CMDBuild.field.ErasableCombo({
fieldLabel: CMDBuild.Translation.targetClass,
labelWidth: CMDBuild.LABEL_WIDTH,
width: CMDBuild.ADM_BIG_FIELD_WIDTH,
name: SOURCE_CLASS_NAME,
valueField: 'name',
displayField: 'description',
editable: false,
store: _CMCache.getClassesAndProcessesAndDahboardsStore(),
queryMode: 'local',
listeners: {
select: function(combo, records, options) {
var className = null;
if (Ext.isArray(records)
&& records.length > 0) {
var record = records[0];
className = record.get(me.classes.valueField);
}
me.callDelegates("onFilterDataViewFormBuilderClassSelected", [me, className]);
}
}
});
this.filterChooser = new CMDBuild.view.common.field.CMFilterChooser({
fieldLabel: CMDBuild.Translation.filter,
labelWidth: CMDBuild.LABEL_WIDTH,
name: FILTER
});
fields.push(this.classes);
fields.push(this.filterChooser);
return fields;
},
setFilterChooserClassName: function(className) {
this.filterChooser.setClassName(className);
},
/**
*
* @param {Ext.data.Model} record
* the record to use to fill the field values
*/
// override
loadRecord: function(record) {
this.callParent(arguments);
var filterConfiguration = Ext.decode(record.get(FILTER));
var className = record.get(SOURCE_CLASS_NAME);
this.filterChooser.setFilter(new CMDBuild.model.CMFilterModel({
configuration: filterConfiguration,
entryType: className
}));
Ext.apply(this.description, {
translationsKeyName: record.get("name")
});
this.classes.setValue(className);
// the set value programmatic does not fire the select
// event, so call the delegates manually
this.callDelegates("onFilterDataViewFormBuilderClassSelected", [this, className]);
},
/**
* @return {object} values
* a key/value map with the values of the fields
*/
// override
getValues: function() {
var values = this.callParent(arguments);
values[SOURCE_CLASS_NAME] = this.classes.getValue();
var filter = this.filterChooser.getFilter();
if (filter) {
values[FILTER] = Ext.encode(filter.getConfiguration());
}
return values;
},
/**
* clear the values of his fields
*/
// override
reset: function() {
this.callParent(arguments);
this.classes.reset();
this.filterChooser.reset();
}
});
})();
|
import React from 'react'
import { Routes, Route } from 'react-router-dom'
import { Home } from './components/Home'
// import { About } from './components/About'
import { Navbar } from './components/Navbar'
import { NoMatch } from './components/NoMatch'
import { Users } from './components/Users'
import { UserDetails } from './components/UserDetails'
import { Admin } from './components/Admin'
import { AuthProvider } from './components/auth'
import { Login } from './components/Login'
import { Profile } from './components/Profile'
import { RequireAuth } from './components/RequireAuth'
import store from './store/index'
import {Provider} from 'react-redux'
const LazyAbout = React.lazy(() => import('./components/About'))
// localStorage.userName ? setUser(localStorage.userName) : setUser (user)
function App() {
return (
<Provider store={store}>
<AuthProvider>
<Navbar />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/login' element={<Login />} />
<Route
path='/profile'
element={
<RequireAuth>
<Profile />
</RequireAuth>
}
/>
<Route
path='about'
element={
<React.Suspense fallback='Loading...'>
<LazyAbout />
</React.Suspense>
}
/>
{/* <Route path='order-summary' element={<OrderSummary />} /> */}
{/* <Route path='products' element={<Products />}>
<Route index element={<FeaturedProducts />} />
<Route path='featured' element={<FeaturedProducts />} />
<Route path='new' element={<NewProducts />} />
</Route> */}
<Route path='users' element={<Users />}>
<Route path=':userId' element={<UserDetails />} />
<Route path='admin' element={<Admin />} />
</Route>
<Route path='*' element={<NoMatch />} />
</Routes>
</AuthProvider>
</Provider>
)
}
export default App
|
import type {ReactNode} from 'react';
import {useEffect, useState} from "react";
import {Roboto} from "next/font/google";
import Header from "@/layout/Header/Header";
import Footer from "@/layout/Footer/Footer";
import styles from './Main.module.scss'
import Image from "next/image";
import {icons} from "../../public/assets/icons/icons";
type IMainProps = {
meta: ReactNode
children: ReactNode
}
const roboto = Roboto({
weight: ['300', '400', '500', '700', '900'],
subsets: ['latin'],
})
const Main = ({meta, children}: IMainProps) => {
const [backToTopButton, setBackToTopButton] = useState(false);
useEffect(() => {
window.addEventListener('scroll', () => {
if (window.scrollY > 1000) {
setBackToTopButton(true)
} else {
setBackToTopButton(false)
}
});
return () => {
window.removeEventListener('scroll', () => {
if (window.scrollY > 1000) {
setBackToTopButton(true)
} else {
setBackToTopButton(false)
}
});
}
}, [backToTopButton])
const scrollUp = () => {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
})
}
return (
<div className={`${roboto.className}`}>
{meta}
<Header/>
<main>{children}</main>
<Footer/>
<button
onClick={scrollUp}
className={!backToTopButton ? styles.backToTopButton : `${styles.backToTopButton} ${styles.backToTopButtonActive}`}
>
<Image src={icons.toTop} alt='To Top'/>
</button>
</div>
)
}
export {Main}
|
/*************************************************************************************
* Copyright (C) 2013-2015, Cypress Semiconductor Corporation. All rights reserved.
*
* This software, including source code, documentation and related
* materials ( "Software" ), is owned by Cypress Semiconductor
* Corporation ( "Cypress" ) and is protected by and subject to worldwide
* patent protection (United States and foreign), United States copyright
* laws and international treaty provisions. Therefore, you may use this
* Software only as provided in the license agreement accompanying the
* software package from which you obtained this Software ( "EULA" ).
* If no EULA applies, Cypress hereby grants you a personal, nonexclusive,
* non-transferable license to copy, modify, and compile the
* Software source code solely for use in connection with Cypress's
* integrated circuit products. Any reproduction, modification, translation,
* compilation, or representation of this Software except as specified
* above is prohibited without the express written permission of Cypress.
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO
* WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING,
* BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. Cypress reserves the right to make
* changes to the Software without notice. Cypress does not assume any
* liability arising out of the application or use of the Software or any
* product or circuit described in the Software. Cypress does not
* authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ( "High Risk Product" ). By
* including Cypress's product in a High Risk Product, the manufacturer
* of such system or application assumes all risk of such use and in doing
* so agrees to indemnify Cypress against all liability.
*/
/******************************************************************************/
/** \file main.c
**
** This example demonstrates RTC mode of low power consumption mode. Every
** 5 second the MCU is wakeup from RTC mode and polling a LED for 1 second.
**
** History:
** - 2015-01-08 0.0.1 EZh First version for FM universal PDL.
**
******************************************************************************/
/******************************************************************************/
/* Include files */
/******************************************************************************/
#include "pdl_header.h"
/******************************************************************************/
/* Local pre-processor symbols/macros ('#define') */
/******************************************************************************/
#if !defined(GPIO1PIN_P3F_INIT)
#error P3F is not available in this MCU product, \
change to other GPIO pin! Then delete "me" !
#endif
#if (PDL_PERIPHERAL_RTC_AVAILABLE != PDL_ON)
#error This example only supports the products which has RTC!
#endif
#if ((SCM_CTL_Val & 0x08) != 0x08)
#error Enable sub clock in system_fmx.h before using this example!
#endif
/******************************************************************************/
/* Global variable definitions (declared in header file with 'extern') */
/******************************************************************************/
uint8_t u8TimerIrqtFlag = 0;
/******************************************************************************/
/* Local type definitions ('typedef') */
/******************************************************************************/
/******************************************************************************/
/* Local function prototypes ('static') */
/******************************************************************************/
/******************************************************************************/
/* Local variable definitions ('static') */
/******************************************************************************/
/******************************************************************************/
/* Function implementation - global ('extern') and local ('static') */
/******************************************************************************/
/**
******************************************************************************
** \brief Initializatio GPIO
**
******************************************************************************/
static void PortInit(void)
{
Gpio1pin_InitOut(GPIO1PIN_P3F, Gpio1pin_InitVal(1u));
}
/**
******************************************************************************
** \brief Set port for LED
**
******************************************************************************/
static void SetLed(boolean_t bLed)
{
if (0 == bLed)
{
Gpio1pin_Put(GPIO1PIN_P3F, 0);
}
else
{
Gpio1pin_Put(GPIO1PIN_P3F, 1);
}
}
/**
******************************************************************************
** \brief RTC Timer Interrupt callback function
**
******************************************************************************/
static void SampleRtcTimerCb(void)
{
// Set timer interruption flag
u8TimerIrqtFlag = TRUE;
}
/**
******************************************************************************
** \brief Configure and start RTC
******************************************************************************/
static void InitRtc(void)
{
stc_rtc_config_t stcRtcConfig;
stc_rtc_irq_en_t stcRtcEn;
stc_rtc_irq_cb_t stcRtcCb;
stc_rtc_time_t stcRtcTime;
stc_rtc_timer_t stcRtcTimer;
// Clear structures
PDL_ZERO_STRUCT(stcRtcConfig);
PDL_ZERO_STRUCT(stcRtcEn);
PDL_ZERO_STRUCT(stcRtcCb);
PDL_ZERO_STRUCT(stcRtcTime);
PDL_ZERO_STRUCT(stcRtcTimer);
// Time setting (23:59:00 5th of January 2015)
stcRtcTime.u8Second = 0; // Second : 00
stcRtcTime.u8Minute = 59; // Minutes : 59
stcRtcTime.u8Hour = 23; // Hour : 23
stcRtcTime.u8Day = 5; // Date : 5th
stcRtcTime.u8DayOfWeek = RtcMonday; // Week : monday
stcRtcTime.u8Month = RtcJanuary; // Month : January
stcRtcTime.u16Year = 2015; // Year : 2015
// Intialize RTC timer
stcRtcTimer.enMode = RtcTimerPeriod;
stcRtcTimer.u32TimerCycle = 5; // Generate interrupt every 5s
// Configure interrupt
stcRtcEn.bTimerIrq = TRUE;
stcRtcCb.pfnTimerIrqCb = SampleRtcTimerCb;
// Clear seconds interrupt flag
u8TimerIrqtFlag = FALSE;
// Initialize RTC configuration
stcRtcConfig.bEnSuboutDivider = FALSE;
stcRtcConfig.enRtccoSel = RtccoOutput1Hz;
#if (PDL_RTC_TYPE == PDL_RTC_WITHOUT_VBAT_TYPEA) || (PDL_RTC_TYPE == PDL_RTC_WITHOUT_VBAT_TYPEB)
stcRtcConfig.enClkSel = RtcUseSubClk;
stcRtcConfig.u32ClkPrescaler = __CLKSO; // sub clock
#endif
stcRtcConfig.pstcTimeDate = &stcRtcTime;
stcRtcConfig.pstcTimer = &stcRtcTimer;
stcRtcConfig.pstcIrqEn = &stcRtcEn;
stcRtcConfig.pstcIrqCb = &stcRtcCb;
stcRtcConfig.bTouchNvic = TRUE;
// Initialize the RTC
Rtc_Init(&RTC0, &stcRtcConfig);
// Start RTC
Rtc_EnableFunc(&RTC0, RtcCount);
// Enable timer
Rtc_EnableFunc(&RTC0, RtcTimer);
}
/**
******************************************************************************
** \brief Main function of project for FM family.
**
** \return int32_t return value, if needed
******************************************************************************/
int32_t main(void)
{
PortInit();
/* Turn off LED */
SetLed(0);
SetLed(1);
/* Configure and start RTC */
InitRtc();
while(1)
{
/* Enter RTC mode */
Lpm_GoToStandByMode(StbRtcMode, TRUE);
if(u8TimerIrqtFlag == TRUE) // wakeup here!, RTC interrupt flag is set in the callback function
{
u8TimerIrqtFlag = FALSE;
/* Turn on LED */
SetLed(0);
Rtc_ClrIrqFlag(&RTC0, RtcHalfSecondIrq);
while(Rtc_GetIrqFlag(&RTC0, RtcHalfSecondIrq) != TRUE); // Wait 0.5s
/* Turn off LED */
SetLed(1);
Rtc_ClrIrqFlag(&RTC0, RtcHalfSecondIrq);
while(Rtc_GetIrqFlag(&RTC0, RtcHalfSecondIrq) != TRUE); // Wait 0.5s
}
}
}
/******************************************************************************/
/* EOF (not truncated) */
/******************************************************************************/
|
package com.nnacres.assessment.service.impl;
import com.SphereEngine.Api.Exception.ClientException;
import com.SphereEngine.Api.Exception.ConnectionException;
import com.nnacres.assessment.dto.CodeResponseDTO;
import com.nnacres.assessment.dto.QuestionResponseDTO;
import com.nnacres.assessment.entity.Option;
import com.nnacres.assessment.entity.Question;
import com.nnacres.assessment.entity.QuestionResponse;
import com.nnacres.assessment.enums.QuestionType;
import com.nnacres.assessment.exception.GenericException;
import com.nnacres.assessment.repository.QuestionRepository;
import com.nnacres.assessment.repository.QuestionResponseRepository;
import com.nnacres.assessment.response.ResponseObject;
import com.nnacres.assessment.service.IQuestionResponseService;
import com.nnacres.assessment.service.SphereEngineCompilerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Service
@Slf4j
public class QuestionResponseServiceImpl implements IQuestionResponseService {
@Autowired
private QuestionResponseRepository questionResponseRepository;
@Autowired
private SphereEngineCompilerService sphereEngineCompilerService;
@Autowired
private QuestionRepository questionRepository;
@Override
@Transactional(rollbackFor = GenericException.class)
public List<QuestionResponseDTO> addQuestionResponse(final Long id, Set<QuestionResponseDTO> dtos) {
List<QuestionResponse> questionResponses = new ArrayList<>();
List<QuestionResponseDTO> responseDtos = new ArrayList<>();
Timestamp timestamp = Timestamp.from(Instant.now());
if (CollectionUtils.isNotEmpty(dtos)) {
dtos.parallelStream().forEach(dto->{
QuestionResponse questionResponse =
QuestionResponse.builder().contestId(dto.getContestId())
.questionId(dto.getQuestionId()).language(dto.getLanguageId())
.userId(dto.getUserId()).timeTaken(dto.getTimeTaken()).program(dto.getProgram())
.answerGiven(String.valueOf(dto.getAnswerGiven())).build();
if(QuestionType.CODING.equals(dto.getQuestionType())){
CodeResponseDTO codeResponseDTO =
CodeResponseDTO.builder().input("").languageId(dto.getLanguageId())
.questionId(dto.getQuestionId()).source(dto.getProgram()).build();
ResponseObject<List<Boolean>> responseObject = new ResponseObject<>();
try {
if (!sphereEngineCompilerService
.checkCompilationFailed(codeResponseDTO, responseObject)) {
List<Integer> marks = new ArrayList<>();
sphereEngineCompilerService
.executeTestCases(codeResponseDTO, new ArrayList<>(), marks);
log.error("marks : ", marks);
questionResponse.setMarks(marks.stream().mapToInt(i->i).sum());
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
Optional<Question> question = questionRepository.findById(dto.getQuestionId());
Set<Option> options = question.get().getOptions();
log.error("option selected : ", dto.getAnswerGiven());
boolean isCorrect = true;
for(Option option : options){
if(option.isCorrect() && !dto.getAnswerGiven().contains(option.getId())){
log.error("option : ", option);
isCorrect = false;
break;
}
}
if(isCorrect){
log.error("called isCorrect true");
questionResponse.setMarks(dto.getMarks());
}
else {
log.error("called isCorrect false");
questionResponse.setMarks(dto.getNegativeMarks());
}
}
questionResponse.setCreatedDate(timestamp);
questionResponse.setUpdatedDate(timestamp);
questionResponses.add(questionResponse);
});
List<QuestionResponse> responses = questionResponseRepository.saveAll(questionResponses);
if (CollectionUtils.isNotEmpty(responses)) {
for (QuestionResponse questionResponse : responses) {
QuestionResponseDTO dto = new QuestionResponseDTO();
responseDtos.add(dto.convertQuestionResponse(questionResponse));
}
}
}
return responseDtos;
}
}
|
package parser_test
import (
"fmt"
"testing"
"github.com/henningrck/monkey-interpreter/ast"
"github.com/henningrck/monkey-interpreter/lexer"
"github.com/henningrck/monkey-interpreter/parser"
"github.com/stretchr/testify/assert"
)
func TestLetStatements(t *testing.T) {
tests := []struct {
input string
expectedIdentifier string
expectedValue any
}{
{"let x = 5;", "x", 5},
{"let y = true;", "y", true},
{"let something = y;", "something", "y"},
}
for _, test := range tests {
l := lexer.New(test.input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
letStmt, ok := program.Statements[0].(*ast.LetStatement)
assert.True(t, ok)
assert.Equal(t, test.expectedIdentifier, letStmt.Name.Value)
checkLiteral(t, letStmt.Value, test.expectedValue)
}
}
func TestReturnStatements(t *testing.T) {
tests := []struct {
input string
expectedValue any
}{
{"return 5;", 5},
{"return 10;", 10},
{"return 993322;", 993322},
}
for _, test := range tests {
l := lexer.New(test.input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
retStmt, ok := program.Statements[0].(*ast.ReturnStatement)
assert.True(t, ok)
checkLiteral(t, retStmt.ReturnValue, test.expectedValue)
}
}
func TestIdentifierExpressions(t *testing.T) {
input := `something;`
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
assert.Equal(t, "something", expStmt.TokenLiteral())
checkLiteral(t, expStmt.Expression, "something")
}
func TestIntegerLiteralExpressions(t *testing.T) {
input := `5;`
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
assert.Equal(t, "5", expStmt.TokenLiteral())
checkLiteral(t, expStmt.Expression, 5)
}
func TestBooleanLiteralExpressions(t *testing.T) {
input := `true;`
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
assert.Equal(t, "true", expStmt.TokenLiteral())
checkLiteral(t, expStmt.Expression, true)
}
func TestFunctionLiteralExpressions(t *testing.T) {
input := `fn(x, y) { x + y; }`
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
function, ok := expStmt.Expression.(*ast.FunctionLiteral)
assert.True(t, ok)
assert.Len(t, function.Parameters, 2)
checkLiteral(t, function.Parameters[0], "x")
checkLiteral(t, function.Parameters[1], "y")
assert.Len(t, function.Body.Statements, 1)
bodyExpStmt, ok := function.Body.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
checkInfixExpression(t, bodyExpStmt.Expression, "x", "+", "y")
}
func TestFunctionLiteralParameters(t *testing.T) {
tests := []struct {
input string
expectedParams []string
}{
{input: "fn() {};", expectedParams: []string{}},
{input: "fn(x) {};", expectedParams: []string{"x"}},
{input: "fn(x, y) {};", expectedParams: []string{"x", "y"}},
{input: "fn(x, y, z) {};", expectedParams: []string{"x", "y", "z"}},
}
for _, test := range tests {
l := lexer.New(test.input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
funcLit, ok := expStmt.Expression.(*ast.FunctionLiteral)
assert.True(t, ok)
assert.Len(t, funcLit.Parameters, len(test.expectedParams))
for i, ident := range test.expectedParams {
checkLiteral(t, funcLit.Parameters[i], ident)
}
}
}
func TestPrefixExpressions(t *testing.T) {
tests := []struct {
input string
operator string
value any
}{
{"!5;", "!", 5},
{"-15;", "-", 15},
{"!true;", "!", true},
{"!false;", "!", false},
}
for _, test := range tests {
l := lexer.New(test.input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
prefixExp, ok := expStmt.Expression.(*ast.PrefixExpression)
assert.True(t, ok)
assert.Equal(t, test.operator, prefixExp.Operator)
checkLiteral(t, prefixExp.Right, test.value)
}
}
func TestInfixExpressions(t *testing.T) {
tests := []struct {
input string
leftValue any
operator string
rightValue any
}{
{"5 + 5;", 5, "+", 5},
{"5 - 5;", 5, "-", 5},
{"5 * 5;", 5, "*", 5},
{"5 / 5;", 5, "/", 5},
{"5 > 5;", 5, ">", 5},
{"5 < 5;", 5, "<", 5},
{"5 == 5;", 5, "==", 5},
{"5 != 5;", 5, "!=", 5},
{"true == true", true, "==", true},
{"true != false", true, "!=", false},
{"false == false", false, "==", false},
}
for _, test := range tests {
l := lexer.New(test.input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
checkInfixExpression(t, expStmt.Expression, test.leftValue, test.operator, test.rightValue)
}
}
func TestIfExpression(t *testing.T) {
input := `if (x < y) { x }`
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
ifExp, ok := expStmt.Expression.(*ast.IfExpression)
assert.True(t, ok)
checkInfixExpression(t, ifExp.Condition, "x", "<", "y")
assert.Len(t, ifExp.Consequence.Statements, 1)
assert.Nil(t, ifExp.Alternative)
consequence, ok := ifExp.Consequence.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
checkLiteral(t, consequence.Expression, "x")
}
func TestIfElseExpression(t *testing.T) {
input := `if (x < y) { x } else { y }`
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
ifExp, ok := expStmt.Expression.(*ast.IfExpression)
assert.True(t, ok)
checkInfixExpression(t, ifExp.Condition, "x", "<", "y")
assert.Len(t, ifExp.Consequence.Statements, 1)
assert.Len(t, ifExp.Alternative.Statements, 1)
consequence, ok := ifExp.Consequence.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
checkLiteral(t, consequence.Expression, "x")
alternative, ok := ifExp.Alternative.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
checkLiteral(t, alternative.Expression, "y")
}
func TestCallExpression(t *testing.T) {
input := "add(1, 2 * 3, 4 + 5);"
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Len(t, program.Statements, 1)
expStmt, ok := program.Statements[0].(*ast.ExpressionStatement)
assert.True(t, ok)
callExp, ok := expStmt.Expression.(*ast.CallExpression)
assert.True(t, ok)
checkLiteral(t, callExp.Function, "add")
assert.Len(t, callExp.Arguments, 3)
checkLiteral(t, callExp.Arguments[0], 1)
checkInfixExpression(t, callExp.Arguments[1], 2, "*", 3)
checkInfixExpression(t, callExp.Arguments[2], 4, "+", 5)
}
func TestOperatorPrecedenceParsing(t *testing.T) {
tests := []struct {
input string
expected string
}{
{
"-a * b",
"((-a) * b)",
},
{
"!-a",
"(!(-a))",
},
{
"a + b + c",
"((a + b) + c)",
},
{
"a + b - c",
"((a + b) - c)",
},
{
"a * b * c",
"((a * b) * c)",
},
{
"a * b / c",
"((a * b) / c)",
},
{
"a + b / c",
"(a + (b / c))",
},
{
"a + b * c + d / e - f",
"(((a + (b * c)) + (d / e)) - f)",
},
{
"3 + 4; -5 * 5",
"(3 + 4)((-5) * 5)",
},
{
"5 > 4 == 3 < 4",
"((5 > 4) == (3 < 4))",
},
{
"5 < 4 != 3 > 4",
"((5 < 4) != (3 > 4))",
},
{
"3 + 4 * 5 == 3 * 1 + 4 * 5",
"((3 + (4 * 5)) == ((3 * 1) + (4 * 5)))",
},
{
"true",
"true",
},
{
"false",
"false",
},
{
"3 > 5 == false",
"((3 > 5) == false)",
},
{
"3 < 5 == true",
"((3 < 5) == true)",
},
{
"1 + (2 + 3) + 4",
"((1 + (2 + 3)) + 4)",
},
{
"(5 + 5) * 2",
"((5 + 5) * 2)",
},
{
"2 / (5 + 5)",
"(2 / (5 + 5))",
},
{
"-(5 + 5)",
"(-(5 + 5))",
},
{
"!(true == true)",
"(!(true == true))",
},
{
"a + add(b * c) + d",
"((a + add((b * c))) + d)",
},
{
"add(a, b, 1, 2 * 3, 4 + 5, add(6, 7 * 8))",
"add(a, b, 1, (2 * 3), (4 + 5), add(6, (7 * 8)))",
},
{
"add(a + b + c * d / f + g)",
"add((((a + b) + ((c * d) / f)) + g))",
},
}
for _, test := range tests {
l := lexer.New(test.input)
p := parser.New(l)
program := p.ParseProgram()
checkParserErrors(t, p)
assert.Equal(t, test.expected, program.String())
}
}
func checkParserErrors(t *testing.T, p *parser.Parser) {
errors := p.Errors()
assert.Len(t, errors, 0)
}
func checkInfixExpression(t *testing.T, exp ast.Expression, leftValue any, operator string, rightValue any) {
infixExp, ok := exp.(*ast.InfixExpression)
assert.True(t, ok)
assert.Equal(t, operator, infixExp.Operator)
checkLiteral(t, infixExp.Left, leftValue)
checkLiteral(t, infixExp.Right, rightValue)
}
func checkLiteral(t *testing.T, exp ast.Expression, expected any) {
switch value := expected.(type) {
case string:
checkIdentifier(t, exp, value)
case int:
checkIntegerLiteral(t, exp, int64(value))
case int64:
checkIntegerLiteral(t, exp, value)
case bool:
checkBooleanLiteral(t, exp, value)
default:
t.Errorf("type of exp not handled, got %T", exp)
t.Fail()
}
}
func checkIdentifier(t *testing.T, exp ast.Expression, value string) {
ident, ok := exp.(*ast.Identifier)
assert.True(t, ok)
assert.Equal(t, value, ident.Value)
assert.Equal(t, value, ident.TokenLiteral())
}
func checkIntegerLiteral(t *testing.T, exp ast.Expression, value int64) {
lit, ok := exp.(*ast.IntegerLiteral)
assert.True(t, ok)
assert.Equal(t, value, lit.Value)
assert.Equal(t, fmt.Sprintf("%d", value), lit.TokenLiteral())
}
func checkBooleanLiteral(t *testing.T, exp ast.Expression, value bool) {
lit, ok := exp.(*ast.BooleanLiteral)
assert.True(t, ok)
assert.Equal(t, value, lit.Value)
assert.Equal(t, fmt.Sprintf("%t", value), lit.TokenLiteral())
}
|
package cc.ddrpa.playground.vikare;
import cc.ddrpa.playground.vikare.event.UserTaskCompletedEventListener;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* 展示全局事件监听的作用
* {@link UserTaskCompletedEventListener} 是一个全局事件监听器,
* 在 {@link cc.ddrpa.playground.vikare.BPMNEngineConfiguration} 中注册监听 TASK_COMPLETED 事件
*/
@SpringBootTest
@ActiveProfiles("mem")
public class ExecutionListenersTests {
private static final Logger logger = LoggerFactory.getLogger(ExecutionListenersTests.class);
private static final String PROCESS_DEFINITION_KEY = "execution_listeners";
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
@Test
void runningTest() {
runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY, Map.of("stage-start", "process start", "next_usergroup", "tom"));
int taskCounter = 1;
while (true) {
var taskList = taskService.createTaskQuery().taskCandidateGroupIn(List.of("tom", "jerry")).list();
if (taskList.size() == 0) {
break;
}
assertEquals(1, taskList.size());
var taskId = taskList.get(0).getId();
if (taskCounter % 2 == 0) {
// 有些任务不需要变量,看看会不会产生不同的事件
taskService.complete(taskId, "tom-" + taskCounter, Map.of("stage-task-" + taskCounter, UUID.randomUUID(), "next_usergroup", "jerry"));
} else {
taskService.complete(taskId, "jerry-" + taskCounter, Map.of("next_usergroup", "tom"));
}
taskCounter++;
}
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* arg_rang.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: luicasad <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/31 08:58:33 by luicasad #+# #+# */
/* Updated: 2024/01/17 10:04:57 by luicasad ### ########.fr */
/* */
/* ************************************************************************** */
#include "argpar.h"
#include "libft.h"
#include <limits.h>
/* ************************************************************************** */
/*.<* .*/
/*.@file arg_rang.c .*/
/*.@brief arg_range_int() check if arg fits in the integer range. .*/
/*. .*/
/*.@param[in] arg: the string to see if fits inside an integer. .*/
/*.@param[out] my_int: the value resulting from arg conversion. .*/
/*.@returns 1 if the argument is inside INT_MIN..INT_MAX, 0 otherwise. .*/
/*. .*/
/*.@details .*/
/*.To check, first converts arg to long with ft_atol() from ft_libft. .*/
/*. .*/
/*.@var long arg_num .*/
/*.Holds the value resulting form convert arg string int a number .*/
/*. .*/
/*.@author LMCD (Luis Miguel Casado Diaz) .*/
/*.>* .*/
/* ************************************************************************** */
int arg_range_int(char *arg, int *my_int)
{
long arg_num;
short l;
char c;
l = ft_strlen(arg);
c = arg[0];
if (((c == '+' || c == '-' ) && l > 11) || (c != '+' && c != '-' && l > 10))
return (0);
arg_num = ft_atol(arg);
if (INT_MIN <= arg_num && arg_num <= INT_MAX)
{
*my_int = (int)arg_num;
return (1);
}
else
return (0);
}
|
import * as XLSX from "xlsx";
import excel from "../../../../assets/excel.svg";
import { useRecoilValue, useRecoilState } from "recoil";
import {
excelState1,
excelState2,
excelState3,
excelStateI1,
excelStateI2,
excelStateI3,
excelDisabled,
} from "../../../../states/Excel";
import { useParams } from "react-router-dom";
import { useEffect } from "react";
function Excel(props) {
const filename =
props.state === "Nation" ? "국가별_데이터.xlsx" : "품목별_데이터.xlsx";
const data1 = useRecoilValue(excelState1);
const data2 = useRecoilValue(excelState2);
const data3 = useRecoilValue(excelState3);
const dataI1 = useRecoilValue(excelStateI1);
const dataI2 = useRecoilValue(excelStateI2);
const dataI3 = useRecoilValue(excelStateI3);
const [disable, setDisable] = useRecoilState(excelDisabled);
const params = useParams();
useEffect(() => {
setDisable(true);
}, [params]);
function convertData2ToTable(data1, data2) {
const table = [
["nation", data1.nationName],
["period", data1.period],
[],
[
"expdlrSum",
"impdlrSum",
"balpaymentsDlr",
"expwgtSum",
"impwgtSum",
"balpaymentsWgt",
],
[
data1.expdlrSum,
data1.impdlrSum,
data1.balpaymentsDlr,
data1.expwgtSum,
data1.impwgtSum,
data1.balpaymentsWgt,
],
];
// Add exportTop data to the table
table.push([], ["수출 top5"], ["item", "date", "expDlr"]);
const dates = Object.keys(data2.expdlrChange).filter(
(key) => key !== "changeRate"
);
Object.keys(data2.exportTop).forEach((key) => {
const topItem = data2.exportTop[key];
const expChange = topItem.exportChange;
const itemRow = [key];
const dateRow = [dates[0]];
const expDlrRow = [expChange[dates[0]]];
// iterate over the dates and push date and expDlr to the table except the first date
for (let i = 1; i < dates.length; i++) {
itemRow[i] = "";
dateRow[i] = dates[i];
expDlrRow[i] = expChange[dates[i]];
}
// push item, date, expDlr to the table
for (let i = 0; i < itemRow.length; i++) {
table.push([itemRow[i], dateRow[i], expDlrRow[i]]);
}
table.push(["expdlrSum", "", topItem.expdlrSum]);
});
// Add exportTop data to the table
table.push([], ["수입 top5"], ["item", "date", "impDlr"]);
Object.keys(data2.importTop).forEach((key) => {
const topItem = data2.importTop[key];
const impChange = topItem.importChange;
const itemRow = [key];
const dateRow = [dates[0]];
const impDlrRow = [impChange[dates[0]]];
// iterate over the dates and push date and impDlr to the table except the first date
for (let i = 1; i < dates.length; i++) {
itemRow[i] = "";
dateRow[i] = dates[i];
impDlrRow[i] = impChange[dates[i]];
}
// push item, date, impDlr to the table
for (let i = 0; i < itemRow.length; i++) {
table.push([itemRow[i], dateRow[i], impDlrRow[i]]);
}
table.push(["impdlrSum", "", topItem.impdlrSum]);
});
return table;
}
function convertDataI2ToTable(data1, data2) {
const table = [
["item", data1.itemName],
["period", data1.period],
[],
[
"expdlrSum",
"impdlrSum",
"balpaymentsDlr",
"expwgtSum",
"impwgtSum",
"balpaymentsWgt",
],
[
data1.expdlrSum,
data1.impdlrSum,
data1.balpaymentsDlr,
data1.expwgtSum,
data1.impwgtSum,
data1.balpaymentsWgt,
],
];
// Add exportTop data to the table
table.push([], ["수출 top5"], ["nation", "date", "expDlr"]);
const dates = Object.keys(data2.expdlrChange).filter(
(key) => key !== "changeRate"
);
Object.keys(data2.exportTop).forEach((key) => {
const topNation = data2.exportTop[key];
const expChange = topNation.exportChange;
const nationRow = [key];
const dateRow = [dates[0]];
const expDlrRow = [expChange[dates[0]]];
// iterate over the dates and push date and expDlr to the table except the first date
for (let i = 1; i < dates.length; i++) {
nationRow[i] = "";
dateRow[i] = dates[i];
expDlrRow[i] = expChange[dates[i]];
}
// push item, date, expDlr to the table
for (let i = 0; i < nationRow.length; i++) {
table.push([nationRow[i], dateRow[i], expDlrRow[i]]);
}
table.push(["expdlrSum", "", topNation.expdlrSum]);
});
// Add exportTop data to the table
table.push([], ["수입 top5"], ["Nation", "date", "impDlr"]);
Object.keys(data2.importTop).forEach((key) => {
const topNation = data2.importTop[key];
const impChange = topNation.importChange;
const nationRow = [key];
const dateRow = [dates[0]];
const impDlrRow = [impChange[dates[0]]];
// iterate over the dates and push date and impDlr to the table except the first date
for (let i = 1; i < dates.length; i++) {
nationRow[i] = "";
dateRow[i] = dates[i];
impDlrRow[i] = impChange[dates[i]];
}
// push item, date, impDlr to the table
for (let i = 0; i < nationRow.length; i++) {
table.push([nationRow[i], dateRow[i], impDlrRow[i]]);
}
table.push(["impdlrSum", "", topNation.impdlrSum]);
});
return table;
}
function convertData3ToTable(data) {
const table = [
["period", data.period],
[],
[
"Export Detail",
"ranking",
"nationName",
"expdlrSum",
"expdlrRatio",
"expwgtSum",
"expwgtRatio",
"hsCode",
"",
"Import Detail",
"ranking",
"nationName",
"expdlrSum",
"expdlrRatio",
"expwgtSum",
"expwgtRatio",
"hsCode",
],
];
// Add exportDetail data to the table
const exportDetailKeys = Object.keys(data.exportDetail);
for (let i = 0; i < exportDetailKeys.length; i++) {
const key = exportDetailKeys[i];
const detail = data.exportDetail[key];
// when table is undefined, creat new row
if (!table[i + 3]) {
table[i + 3] = [];
}
// add push
table[i + 3].push(
key,
detail.ranking,
detail.nationName,
detail.expdlrSum,
detail.expdlrRatio,
detail.expwgtSum,
detail.expwgtRatio,
detail.hsCode
);
}
// Add a blank column between the tables
for (let i = 3; i < table.length; i++) {
table[i].push("");
}
// Add a blank column between the tables
const importDetailKeys = Object.keys(data.importDetail);
for (let i = 0; i < importDetailKeys.length; i++) {
const key = importDetailKeys[i];
const detail = data.importDetail[key];
if (!table[i + 3]) {
table[i + 3] = [];
}
table[i + 3].push(
key,
detail.ranking,
detail.nationName,
detail.impdlrSum,
detail.impdlrRatio,
detail.impwgtSum,
detail.impwgtRatio,
detail.hsCode
);
}
return table;
}
const exportToExcel = () => {
const ws1 = XLSX.utils.aoa_to_sheet(convertData2ToTable(data1, data2));
const ws2 = XLSX.utils.aoa_to_sheet(convertData3ToTable(data3));
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws1, "수출입 비중 & top 5");
XLSX.utils.book_append_sheet(wb, ws2, "수출입 상세");
XLSX.writeFile(wb, filename);
};
const exportToExcelI = () => {
const wsI1 = XLSX.utils.aoa_to_sheet(convertDataI2ToTable(dataI1, dataI2));
const wsI2 = XLSX.utils.aoa_to_sheet(convertData3ToTable(dataI3));
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, wsI1, "수출입 비중 & top 5");
XLSX.utils.book_append_sheet(wb, wsI2, "수출입 상세");
XLSX.writeFile(wb, filename);
};
return props.state == "Nation" ? (
disable == true ? (
<button onClick={exportToExcel} disabled={disable}>
<img src={excel} className="w-10 h-10 grayscale" />
</button>
) : (
<button onClick={exportToExcel} disabled={disable}>
<img src={excel} className="w-10 h-10" />
</button>
)
) : disable == true ? (
<button onClick={exportToExcelI} disabled={disable}>
<img src={excel} className="w-10 h-10 grayscale" />
</button>
) : (
<button onClick={exportToExcelI} disabled={disable}>
<img src={excel} className="w-10 h-10" />
</button>
);
}
export default Excel;
|
/**
* Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
*
* Example 1:
*
* Input: 121
* Output: true
* Example 2:
*
* Input: -121
* Output: false
* Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
* Example 3:
*
* Input: 10
* Output: false
* Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
* Follow up:
*
* Coud you solve it without converting the integer to a string?
*/
public class IsPalindromeNum {
/**
* Reverse half of the digits
*
* Time: O(log_10 n)
* Space: O(1)
*/
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int rev = 0;
while (x > rev) {
rev = rev * 10 + (x % 10);
x /= 10;
}
return x == rev || x == rev / 10;
}
/**
* Use a stack to store all the digits
* and another to store half of them
* compare the two stacks
*
* Time: O(log_10 n)
* Space: O(log_10 n)
*/
public boolean isPalindromeII(int x) {
if (x < 0) {
return false;
}
Deque<Integer> stack1 = new ArrayDeque<>();
Deque<Integer> stack2 = new ArrayDeque<>();
int cnt = 0;
while (x != 0) {
stack1.push(x % 10);
x /= 10;
cnt++;
}
for (int i = 0; i < cnt / 2; i++){
stack2.push(stack1.pop());
}
if (cnt % 2 == 1 && !stack1.isEmpty()) {
stack1.pop();
}
while (!stack1.isEmpty() && !stack2.isEmpty()){
if (stack1.pop() != stack2.pop()) {
return false;
}
}
return true;
}
}
|
=head1 NAME
Badger::FAQ - Frequently asked questions about Badger
=head1 SYNOPSIS
$you->ask;
$we->answer
=head1 GENERAL QUESTIONS
=head2 What is Badger?
It's a collection of Perl modules designed to take away some of the tedium
involved in writing Perl modules, libraries and applications.
Badger started off as being all the generic bits of the Template Toolkit that
weren't directly related to template processing. Things like a common base
class, file handling modules, error handling, logging, and so on.
Now there are plenty of other fine modules on CPAN that do these kinds of
things, including some that were my own earlier attempts at extracting useful
functionality out of TT into generic modules (e.g. Class::Base,
Class::Singleton, App::Config, etc). So in that sense, there's nothing
particularly new or revolutionary about Badger - I've just taken a bunch of
modules I've written a dozen times before for various different projects,
cleaned then up, moved them into a new namespace of my own (that hopefully
no-one will ever accuse me of name-squatting in), made them work with each
other in a consistent way (i.e. without the mish-mash of different API styles
you get whenever you plug a random selection of CPAN modules together) and
released them for other people to use if they want to.
=head2 Why Should I Use Badger?
There is no Badger world order. I wrote Badger because it makes my life
easier. If it makes your life easier too then I'm happy for you, but it makes
no difference to me if you use it or not. I'm tired of having to justify the
existence of the software that I chose to give away for free. In other words,
what you see is what you get. Take it or leave it.
=head2 How is Badger similar to / different from Moose?
Badgers are smaller and can easily be recognised by their black fur and
distinctive white stripe running down their snout. Moose are larger and have
an impressive set of antlers. Both enjoy foraging in the forest for nuts and
berries.
Joking aside, they're completely different animals. Badger is in no way
intended to be a replacement or substitute for Moose or vice-versa. They were
developed entirely separately with different motivations and goals. That said,
they do have a lot in common.
I'll try and list some of the similarities and differences that
I'm aware of. Please bear in mind that I know Badger much better than I do
Moose so my knowledge may be incomplete or incorrect in places.
Some of the similarities:
=over
=item *
Both provide a more robust object layer on top of Perl 5
=item *
Both use metaprogramming to achieve those goals (although to
different degrees)
=item *
Both are named after cool animals
=back
Some of the differences:
=over
=item *
Moose sets out to implement the post-modern Perl 6 object model (or something
very close to it). It uses a lot of clever magic to make that happen.
In contrast Badger implements a more "regular" Perl 5 object model, albeit a a
thoroughly modern one. It's got some of the metaprogramming goodness that Perl
6 amd Moose have, but not all of it. The emphasis is on providing enough
metaprogramming to get the Badger job done, rather than providing a completely
extensible metaprogramming environment.
To borrow the ice-cream analogy, if Perl 5's object system is vanilla, then
Badger's is strawberry and Moose's is neapolitan with sprinkles and a
sparkler.
=item *
Moose is more framework, Badger is more toolkit.
One of the important principles with Badger is that you can use just one
module (say, L<Badger::Base>, L<Badger::Prototype> or L<Badger::Factory>) as a
regular Perl 5 OO module, without having to use any of the other modules.
L<Badger::Class> provides the metaprogramming side of things to make life easy
if you want it, but you can manage just fine without it.
On the other hand, Moose is all about metaprogramming. If you don't use the
metaprogramming wide of things then you're not really using Moose.
=item *
Moose is "just" an OO programming framework. It's a very impressive OO
framework that contains some really great ideas (some of which I've borrowed).
The fact that it just concerns itself with the OO framework side of things
should be considered a featured, not a weakness. It does one thing (well,
several things, all under the guess of one meta-thing) and does it extremely
well.
Badger provides a smaller and simpler set of generic OO programming tools as
part of a collection of generally useful modules for application authors (me
in particular). It contains the things that I need for TT, and the kind of
things that I find myself writing over and over again in pretty much every
Perl project I work on. So the Moose-like (and Spiffy-like) parts of Badger
are a means to an end, rather than the raison d'etre in themselves.
=item *
Badger attempts to bring some of the "Batteries Included" mentality of Python
to the Perl world. Perl already has some highly functional batteries included
with it (the File::* modules, for example) but they're all different shapes
and sizes. Part of the Badger philosophy is to provide a consistent interface
to some of these various different modules. Hence the L<Badger::Filesystem>
modules that try to paper over the cracks that can result from having "More
Than One Way To Do It".
=item *
Badger has no external dependencies. In the general case that's probably not
something to be proud of (reuse is good, right?) But in the case of TT (and
some other projects in the pipeline), having as few dependencies as possible
is really important. If you can't install it then you can't use it, and there
are quite a few TT users for whom installing something from CPAN is not an
option, either because their ISP won't allow it or they're incapable of using
a command line. (Mr T pities those fools, but we try to help them, not berate
them).
=back
So to sum up, Badger and Moose do some similar things but in different ways.
They both like to forage in the forest for nuts and berries. The Moose picks
them off the trees and the Badger gets them off the ground.
=head2 Is Badger Re-Inventing Wheels?
Yes and no. Some of the wheels that I've "re-invented" were my own wheels to
start with (e.g. L<Class::Base>, L<Class::Singleton> and L<Class::Facade>
which have been, or will soon be superceded by their Badger counterparts).
Bundling them all into one place makes them easier for me to maintain and
easier for the end user to find, download, install and use. It also means that
they can share other core Badger modules (like L<Badger::Exception> for error
handling, for example) without having to distribute all of those separately on
CPAN. Furthermore, the nature of CPAN is such that they would all end up in
various different namespaces giving no real clue to the end user that they all
make up part of a common toolkit.
So part of the Badger effort is about bundling up a bunch of modules that
I've written (some on CPAN, some not) into a common namespace where they
can play happily together. Apart from anything else, it means I only have
just I<one> CPAN distribution, test suite, set of documentation, web site,
bug tracker, subversion repository, etc., etc., to deal with instead of
I<many>. In that sense we're taking existing wheels, cleaning them up,
fixing any broken spokes and putting new tyres on. It's as much about
packaging and presentation as it is about functionality.
Having said that, there is some duplication between Badger modules and
existing CPAN modules that can do the same things just as well or even better.
In some cases that is an unavoidable consequence of the length of time that
Badger was in gestation. I've been developing the code base for TT3/Badger on
and off since 2001. Many of the fine CPAN modules that people take for granted
these days weren't around back then so I started by rolling my own. This code
then made its way into other projects and evolved over time to where it is
now. Having invested a lot of time in the code, test suite and documentation,
I know exactly where I am with it and I can be very productive using it.
So while it's not broken, I don't plan to fix it.
In other cases, the choice to re-invent a wheel was deliberate because the
existing wheels weren't a good fit for what I wanted or needed. For example,
the L<Path::Class> modules do a fantastic job of providing an OO interface to a
filesystem. I worship the ground that Ken Williams walks on for saving me the
torment of having to deal with all the different File::* modules directly.
Unfortunately the L<Path::Class> modules don't provide the level of
abstraction that is required for them to work with virtual filesystems (such
as I require for TT). Adapting them turned out to be a futile effort because
they're essentially just very simple and elegant wrappers around the various
File::* modules. I needed a similarly simple wrapper, but of a slightly
different kind. So I rolled my own, borrowing Ken's (and other people's) ideas
and/or bits of code wherever I could. That's the I<second> best kind of code
re-use - don't re-invent a wheel, just copy someone else's (just as long as
you've also got something new to add).
Another example is the L<Badger::Exporter> module. It does pretty much
exactly what the L<Exporter> module does, except that it works with class
inheritance and has some methods of convenience to make it more friendly
to use. I could have written it as a wrapper around Exporter (and that's
what I started doing) but in the end, it was easier to cut and paste the
dozen or so critical lines from Exporter and build the module how I wanted
from scratch instead of trying to cobble OO on top a procedural module and
confuse everyone (myself included) in the process.
So in summary, yeah, but no, but.
Badger doesn't really re-invent any wheels but adapts a few to fit into this
particular niche.
=head1 AUTHOR
Andy Wardley E<lt>[email protected]<gt>
=head1 COPYRIGHT
Copyright (C) 2008-2012 Andy Wardley. All Rights Reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=head1 SEE ALSO
L<http://badgerpower.com/>
=cut
|
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.hawkbit.repository.jpa.model;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Index;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder;
import org.eclipse.persistence.annotations.CascadeOnDelete;
import org.eclipse.persistence.descriptors.DescriptorEvent;
/**
* A {@link DistributionSetTag} is used to describe DistributionSet attributes
* and use them also for filtering the DistributionSet list.
*
*/
@Entity
@Table(name = "sp_distributionset_tag", indexes = {
@Index(name = "sp_idx_distribution_set_tag_prim", columnList = "tenant,id"),
@Index(name = "sp_idx_distribution_set_tag_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = {
"name", "tenant" }, name = "uk_ds_tag"))
public class JpaDistributionSetTag extends JpaTag implements DistributionSetTag, EventAwareEntity {
private static final long serialVersionUID = 1L;
@CascadeOnDelete
@ManyToMany(mappedBy = "tags", targetEntity = JpaDistributionSet.class, fetch = FetchType.LAZY)
private List<DistributionSet> assignedToDistributionSet;
/**
* Public constructor.
*
* @param name
* of the {@link DistributionSetTag}
* @param description
* of the {@link DistributionSetTag}
* @param colour
* of tag in UI
*/
public JpaDistributionSetTag(final String name, final String description, final String colour) {
super(name, description, colour);
}
/**
* Default constructor for JPA.
*/
public JpaDistributionSetTag() {
// Default constructor for JPA.
}
@Override
public void fireCreateEvent(final DescriptorEvent descriptorEvent) {
EventPublisherHolder.getInstance().getEventPublisher().publishEvent(
new DistributionSetTagCreatedEvent(this, EventPublisherHolder.getInstance().getApplicationId()));
}
@Override
public void fireUpdateEvent(final DescriptorEvent descriptorEvent) {
EventPublisherHolder.getInstance().getEventPublisher().publishEvent(
new DistributionSetTagUpdatedEvent(this, EventPublisherHolder.getInstance().getApplicationId()));
}
@Override
public void fireDeleteEvent(final DescriptorEvent descriptorEvent) {
EventPublisherHolder.getInstance().getEventPublisher().publishEvent(new DistributionSetTagDeletedEvent(
getTenant(), getId(), getClass(), EventPublisherHolder.getInstance().getApplicationId()));
}
}
|
import React, {useEffect, useState} from 'react';
import {Link} from 'react-router-dom';
import {styles} from '../styles';
import {navLinks} from '../constants';
import {logo, menu, close} from '../assets';
const Navbar = () => {
const [active, setActive] = useState('');
const [toggle, setToggle] = useState(false);
return (
<nav
className={`${styles.paddingX} w-full flex item-center py-5 fixed top-0 z-20 bg-primary`}>
<div className="w-full flex justify-between items-center max-w-7xl mx-auto">
<Link
to="/" className="flex items-center gap-2"
onClick ={()=>{
setActive("");
window.scrollTo(0,0)
}}>
<img src={logo} alt={logo} className="w-9 h-109 object-contain"/>
<p className="text-white text-[18px] font-bold cursor-pointer flex"> AviC <span className="sm:block hidden"> | MERN Stack Dev</span></p>
</Link>
<ul className="list-none hidden sm:flex flex-row gap-10">
{navLinks.map((links) =>
<li key={links.id} className={`${active === links.title ? "text-white":"text-secondary"} hover:text-white text-[18px] font-medium cursor-pointer`} onClick={()=> setActive(links.title)}><a href={`#${links.id}`}>{links.title}</a></li>)}
</ul>
<div className="sm:hidden flex flex-1 justify-end item-center">
<img src={toggle?close:menu} alt="menu" className="w-[28px] h-[28px] object-contain cursor-pointer" onClick ={() => setToggle(!toggle)}/>
<div className={`${!toggle?"hidden":"flex"} black-gradient p-6 absolute top-20 right-0 mx-4 my-2 min-w-[140px] rounded-xl z-10`}>
<ul className="list-none flex justify-end items-start flex-col gap-3">
{navLinks.map((links) =>
<li key={links.id} className={`${active === links.title ? "text-white":"text-secondary"} font-poppins font-medium cursor-pointer text-[16px]`} onClick={()=> {setToggle(!toggle);setActive(links.title);}}><a href={`#${links.id}`}>{links.title}</a></li>)}
</ul>
</div>
</div>
</div>
</nav>
)
}
export default Navbar
|
<template>
<v-app>
<v-main>
<ContentBlock :users="users" :filters="filters" @changeFilters="changeFilters"/>
</v-main>
<v-footer app v-bind="localAttrs">
<Footer/>
</v-footer>
</v-app>
</template>
<script>
import { mapGetters } from "vuex";
import ContentBlock from './components/ContentBlock';
import Footer from './components/Footer';
export default {
name: 'App',
components: {
ContentBlock,
Footer
},
computed: {
...mapGetters(['users', 'filters']),
localAttrs() {
const attrs = {};
attrs.absolute = true;
attrs.fixed = false;
return attrs;
},
},
created() {
this.$store.dispatch('fetchUsers');
},
methods: {
changeFilters(filters) {
this.$store.dispatch('changeFilters', filters);
}
}
};
</script>
|
import BaseService from "../../common/BaseService";
import CountryModel from "./CountryModel.model";
import { AddCountry } from "./dto/AddCountry.dto";
import { EditCountry } from "./dto/EditCountry.dto";
import * as mysql2 from "mysql2/promise";
export interface CountryAdapterOptions {}
export default class CountryService extends BaseService<
CountryModel,
CountryAdapterOptions
> {
tableName(): string {
return "country";
}
protected async adaptToModel(
data: any,
_options: CountryAdapterOptions
): Promise<CountryModel> {
const country = new CountryModel();
country.countryId = +data?.country_id;
country.countryName = data?.country_name;
return country;
}
public async add(data: AddCountry): Promise<CountryModel> {
return this.baseAdd(data, {});
}
public async editById(
countryId: number,
data: EditCountry
): Promise<CountryModel> {
return this.baseEditById(countryId, data, {});
}
public async deleteById(countryId: number) {
return this.baseDeleteById(countryId);
}
public async getByName(name: string): Promise<CountryModel | null> {
return new Promise((resolve, reject) => {
this.getAllByFieldNameAndValue("name", name, {})
.then((result) => {
if (result.length === 0) {
return resolve(null);
}
resolve(result[0]);
})
.catch((error) => {
reject(error?.message);
});
});
}
public async getAllBySearchString(
searchString: string
): Promise<CountryModel[]> {
return new Promise<CountryModel[]>((resolve, reject) => {
const sql: string =
"SELECT * FROM `country` WHERE `country_name` LIKE CONCAT('%', ?, '%');";
this.db
.execute(sql, [searchString])
.then(async ([rows]) => {
if (rows === undefined) {
return resolve([]);
}
const items: CountryModel[] = [];
for (const row of rows as mysql2.RowDataPacket[]) {
items.push(await this.adaptToModel(row, {}));
}
resolve(items);
})
.catch((error) => {
reject(error);
});
});
}
}
|
import React, { useState, useContext } from "react";
import { UserContext } from "../../store";
// Networking and event handling
import { Socket } from "socket.io-client";
import { DefaultEventsMap } from "socket.io/dist/typed-events";
import { Events } from "../../eventHandlers/Events";
// Routing
import { useNavigate } from "react-router-dom";
// Types
import { Card } from "../../types/card";
import { BasePlayer, Player } from "../../types/player";
// Styles
import "../../styles/playing-cards.css";
import "../../styles/rang.css";
// Components
import PlayerHandComponent from "./PlayerHandComponent";
import MessagesComponent from "./MessagesComponent";
import GameBoardComponent from "./GameBoardComponent";
import SelectRangComponent from "./SelectRangComponent";
interface GamePageProps {
socket: Socket<DefaultEventsMap, DefaultEventsMap>;
}
function Game({ socket }: GamePageProps) {
const navigate = useNavigate();
const { user_id, setUser_id } = useContext(UserContext);
// Sample starts
let testCard: Card = { rank: "7", suit_name: "spades", suit_symbol: "♠" };
let testCard2: Card = { rank: "8", suit_name: "spades", suit_symbol: "♠" };
let playerHand: Card[] = [testCard, testCard2];
let testMessages: Message[] = [
{ sender: "Esha", content: "Hello" },
{ sender: "Saood", content: "Hi" },
];
let testPlayers: BasePlayer[] = [
{ name: "test1", current_card: testCard, score: 0, is_turn: false },
{ name: "test2", current_card: testCard2, score: 0, is_turn: false },
{ name: "test3", current_card: testCard, score: 0, is_turn: false },
];
let testPlayer: Player = {
name: "testMe",
score: 0,
is_turn: false,
hand: playerHand,
user_id: user_id,
current_card: testCard,
};
const [players, setPlayers] = useState<BasePlayer[]>(testPlayers);
const [myPlayer, setMyPlayer] = useState<Player>(testPlayer);
const [playStarted, setPlayStarted] = useState<Boolean>(false);
const [choosesRang, setChoosesRang] = useState<Boolean>(false);
const [rang, setRang] = useState<String>("none");
React.useEffect(() => {
socket.on(Events.LOAD_STATE, (data: any) => {
console.log("Received: ");
console.log(data.data);
setMyPlayer(data.data.myPlayer);
setPlayers(data.data.players);
setPlayStarted(data.data.playStarted);
});
socket.on(Events.SELECT_RANG, (data: any) => {
setChoosesRang(true);
});
socket.emit(Events.GAME_STARTED, {
event: Events.GAME_STARTED,
data: {
playerId: user_id,
},
});
socket.on(Events.RANG_SELECTED, (data: any) => {
console.log("Received");
console.log(data.data);
setChoosesRang(false);
setRang(data.data.rang);
});
socket.on(Events.UPDATE_HAND, (data: any) => {
console.log("Received update hand");
console.log(data.data);
setMyPlayer(data.data.myPlayer);
});
socket.on("update-players", (data: any) => {
console.log("Received update players");
console.log(data.data);
setPlayers(data.data.players);
});
socket.on("round_winner", (data: any) => {
console.log("Received round winner");
console.log(data.data);
alert(`${data.data.winner} won the round!`);
});
socket.on("game_over", (data: any) => {
console.log("Received game winner");
console.log(data.data);
alert(`${data.data.winner} won the game!`);
});
return () => {
socket.off(Events.LOAD_STATE);
socket.off(Events.SELECT_RANG);
socket.off(Events.RANG_SELECTED);
socket.off(Events.UPDATE_HAND);
socket.off("update-players");
socket.off("round_winner");
};
}, [socket, user_id]);
return (
<div className="main-container playingCards">
<div className="game-container">
<div className="heading-container">
<h1>Rang</h1>
</div>
<GameBoardComponent player={myPlayer} players={players} />
{
(!playStarted) ?
(
choosesRang ?
<SelectRangComponent player={myPlayer} socket={socket} setPlayStarted={setPlayStarted} setRang={setRang}/> : <></>
) :
(
<h1>Rang: {rang}</h1>
)
}
</div>
<div className="messages-and-cards-container">
<MessagesComponent player={myPlayer} socket={socket} />
<PlayerHandComponent
player={myPlayer}
players={players}
setPlayer={setMyPlayer}
setPlayers={setPlayers}
socket={socket}
/>
</div>
</div>
);
}
export default Game;
|
//
// GameScene.swift
// PacMan
//
// Created by Andrii Moisol on 05.09.2021.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
private var pacman: PacMan!
private var gameField: SKShapeNode!
private var scoreLabel: SKLabelNode!
private var score: Int
private var ghosts: [Ghost] = []
private var timeLabel: SKLabelNode!
private var lastUpdateTime: TimeInterval = 0
private var dt: CGFloat = 0
let level: Level
let expectimax: Bool = false
var isGameOver = false
let startTime = Date()
init(size: CGSize, level: Level, score: Int = 0) {
self.level = Level(map: level.map, number: level.number, tileSize: level.tileSize)
self.score = score
super.init(size: size)
}
override func didMove(to view: SKView) {
pacman = PacMan(size: CGSize(width: 40, height: 40))
gameField = SKShapeNode(rectOf: CGSize(width: level.tileSize.width * CGFloat(level.map[0].count), height: level.tileSize.height * CGFloat(level.map.count)))
gameField.fillColor = .black
gameField.strokeColor = .clear
gameField.position = CGPoint(x: size.width / 2, y: size.height / 2)
addChild(gameField)
scoreLabel = SKLabelNode(text: "Score: \(0)")
scoreLabel.color = .white
scoreLabel.position = CGPoint(x: size.width - 70, y: size.height - 50)
scoreLabel.fontSize = 16
addChild(scoreLabel)
let levelLabel = SKLabelNode(text: "Level: \(level.number)")
levelLabel.color = .white
levelLabel.position = CGPoint(x: size.width - 70, y: size.height - 100)
levelLabel.fontSize = 14
addChild(levelLabel)
timeLabel = SKLabelNode(text: "\(0)")
timeLabel.color = .white
timeLabel.position = CGPoint(x: size.width - 70, y: size.height - 150)
timeLabel.fontSize = 13
addChild(timeLabel)
physicsWorld.contactDelegate = self
for (i, array) in level.map.reversed().enumerated() {
for (j, element) in array.enumerated() {
if element & CategoryBitMask.obstacleCategory != 0 {
let obstacle = Obstacle(size: level.tileSize)
obstacle.position = .init(x: CGFloat(j) * level.tileSize.width + level.tileSize.width / 2 - gameField.frame.width / 2, y: CGFloat(i) * level.tileSize.height + level.tileSize.height / 2 - gameField.frame.height / 2)
gameField.addChild(obstacle)
}
if element & CategoryBitMask.foodCategory != 0 {
let food = Food(radius: 3)
food.position = .init(x: CGFloat(j) * level.tileSize.width + level.tileSize.width / 2 - gameField.frame.width / 2, y: CGFloat(i) * level.tileSize.height + level.tileSize.height / 2 - gameField.frame.height / 2)
gameField.addChild(food)
}
if element & CategoryBitMask.pacmanCategory != 0 {
pacman.position = .init(x: CGFloat(j) * level.tileSize.width + level.tileSize.width / 2 - gameField.frame.width / 2, y: CGFloat(i) * level.tileSize.height + level.tileSize.height / 2 - gameField.frame.height / 2)
pacman.zPosition = 1
pacman.animate()
gameField.addChild(pacman)
}
if element & CategoryBitMask.blinkyCategory != 0 {
let ghost = Ghost(type: .blinky, size: level.tileSize)
ghost.position = .init(x: CGFloat(j) * level.tileSize.width + level.tileSize.width / 2 - gameField.frame.width / 2, y: CGFloat(i) * level.tileSize.height + level.tileSize.height / 2 - gameField.frame.height / 2)
gameField.addChild(ghost)
ghost.zPosition = 1
ghosts.append(ghost)
}
if element & CategoryBitMask.pinkyCategory != 0 {
let ghost = Ghost(type: .pinky, size: level.tileSize)
ghost.position = .init(x: CGFloat(j) * level.tileSize.width + level.tileSize.width / 2 - gameField.frame.width / 2, y: CGFloat(i) * level.tileSize.height + level.tileSize.height / 2 - gameField.frame.height / 2)
gameField.addChild(ghost)
ghost.zPosition = 1
ghosts.append(ghost)
}
if element & CategoryBitMask.inkyCategory != 0 {
let ghost = Ghost(type: .inky, size: level.tileSize)
ghost.position = .init(x: CGFloat(j) * level.tileSize.width + level.tileSize.width / 2 - gameField.frame.width / 2, y: CGFloat(i) * level.tileSize.height + level.tileSize.height / 2 - gameField.frame.height / 2)
gameField.addChild(ghost)
ghost.zPosition = 1
ghosts.append(ghost)
}
if element & CategoryBitMask.clydeCategory != 0 {
let ghost = Ghost(type: .clyde, size: level.tileSize)
ghost.position = .init(x: CGFloat(j) * level.tileSize.width + level.tileSize.width / 2 - gameField.frame.width / 2, y: CGFloat(i) * level.tileSize.height + level.tileSize.height / 2 - gameField.frame.height / 2)
gameField.addChild(ghost)
ghost.zPosition = 1
ghosts.append(ghost)
}
}
}
}
override func update(_ currentTime: TimeInterval) {
if lastUpdateTime > 0 {
dt = CGFloat(currentTime - lastUpdateTime)
} else {
dt = 0
}
lastUpdateTime = currentTime
let previousPosition = pacman.position
let oldJ = Int(((previousPosition.x + gameField.frame.width / 2 - level.tileSize.width / 2) / level.tileSize.width).rounded(.toNearestOrEven))
let oldI = Int(((previousPosition.y + gameField.frame.height / 2 - level.tileSize.height / 2) / level.tileSize.height).rounded(.toNearestOrEven))
ghosts.forEach { ghost in
if !ghost.hasActions() {
if ghost.type == .blinky {
ghost.moveRandom(level: level)
} else if ghost.type == .pinky {
ghost.moveAStar(level: level, to: Point(i: level.map.count - oldI - 1, j: oldJ))
}
}
}
if !pacman.hasActions() {
if let bestMove = PacMan.bestMove(map: level.map, expectimax: expectimax) {
pacman.move(level: level, move: bestMove)
}
}
checkWin()
}
override func keyDown(with event: NSEvent) {
switch event.keyCode {
case 0x00:
pacman.currentDirection = .left
pacman.run(SKAction.rotate(toAngle: .pi, duration: 0.2))
case 0x01:
pacman.currentDirection = .down
pacman.run(SKAction.rotate(toAngle: -.pi / 2, duration: 0.2))
case 0x0D:
pacman.currentDirection = .up
pacman.run(SKAction.rotate(toAngle: .pi / 2, duration: 0.2))
case 0x02:
pacman.currentDirection = .right
pacman.run(SKAction.rotate(toAngle: 0, duration: 0.2))
default:
break
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
let bodyA = contact.bodyA
let bodyB = contact.bodyB
if bodyA.node?.name == "pacman" && bodyB.node?.name == "food" {
(bodyA.node as! PacMan).eat(food: bodyB.node as! Food)
increaseScore(by: 10)
} else if bodyB.node?.name == "pacman" && bodyA.node?.name == "food" {
(bodyB.node as! PacMan).eat(food: bodyA.node as! Food)
increaseScore(by: 10)
}
if bodyA.node?.name == "pacman" && bodyB.node?.name == "ghost" {
gameOver()
} else if bodyA.node?.name == "ghost" && bodyB.node?.name == "pacman" {
gameOver()
}
}
private func increaseScore(by amount: Int) {
score += amount
scoreLabel.text = "Score: \(score)"
}
private func writeResultsToFile(win: Bool) {
let time = Date().timeIntervalSince(startTime)
let fileURL = URL(fileURLWithPath: "results.csv", isDirectory: false)
if !FileManager.default.fileExists(atPath: fileURL.path) {
FileManager.default.createFile(atPath: fileURL.path, contents: "win,time,score,algo\n".data(using: .utf8), attributes: nil)
}
guard let handle = FileHandle(forWritingAtPath: fileURL.path) else { return }
defer {
try! handle.close()
}
try! handle.seekToEnd()
try! handle.write(contentsOf: "\(win ? "win" : "lose"),\(time),\(score),\(self.expectimax ? "expectimax" : "minimax")\n".data(using: .utf8)!)
}
private func checkWin() {
if !level.map.contains(where: { $0.contains(where: { $0 & CategoryBitMask.foodCategory != 0 }) }) {
writeResultsToFile(win: true)
let nextLevel = Level.staticLevel
nextLevel.number += 1
let gameScene = GameScene(size: size, level: nextLevel, score: score)
gameScene.scaleMode = .aspectFill
view?.presentScene(gameScene, transition: .fade(withDuration: 0.5))
}
}
private func gameOver() {
guard !isGameOver else { return }
isGameOver = true
writeResultsToFile(win: false)
let highScore = UserDefaults.standard.integer(forKey: "highScore")
if score > highScore {
UserDefaults.standard.setValue(score, forKey: "highScore")
}
let scene = StartScene(size: size)
scene.scaleMode = .aspectFill
view?.presentScene(scene, transition: .fade(withDuration: 0.5))
}
}
|
---
title: "A closer look: Setting private members in the editor"
author: manio
popular: false
image: /images/blog/2023-09-21-closer-look-private-members/script-with-secrets.png
tags: ['.NET', 'Education']
---
Let's take a closer look at why currently you can't set private members of scripts and components in the Stride Editor and explore the options to change that in the future.
---
Table of Contents:
[[TOC]]
It has been an amazing week for Stride and our Discord is booming with new people who want to [learn more about the engine](https://www.stride3d.net/blog/embracing-open-source-stride-as-an-alternative-to-unity/) and maybe port some games from Unity. One of the questions that has been asked a few times was why we can't set private members on scripts in the editor. I thought it's a good opportunity to dive a little deeper into the technical reasons and engine architecture to explain the current limitation and explore the options to change it in the future.
## What is public and what is private
Let's run through a quick reminder. In C# members are annotated with [access modifiers](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers)
such as `public`, `protected` or `private`. The modifier describes the access objects of other classes will have when accessing the members. It allows us to control the API surface of an object by hiding away certain aspects of its state to allow the inner implementation to be changed without affecting other parts of code that would only interact with the publicly visible members.
_To understand it better read [this analogy](https://cseducators.stackexchange.com/a/1246)._
When designing systems we will often decide to make certain things public (maybe even use an interface to further describe the public API regardless of the class holding the methods) and keep most things private. This allows us to prevent accidental mistakes when another part of the systems makes changes to some delicate state.
However, with a more Data Oriented approach we can find ourselves creating classes which hold mainly data. In many Entity Component System implementations the components are just data bags that systems read and update. With this kind of approach there's rarely need for private members, although sometimes the `internal` visibility is used for data on a component that is exclusively managed by its default system.
Moreover, component's public properties are often not just modified at design time, but also at runtime. Think about the Transform component and how it's public properties are modified to move the entities around, or how changing the velocity on a Physics component affects how quickly the simulation will move it around on the next step.
## Design vs runtime access
We can talk about components in two contexts: setting the properties during level design in the editor and setting them at runtime while the game is running. We would generally expect in both cases that we can modify the properties of the component and they will be picked up by the processing system.
With the introduction of [Scripts](https://doc.stride3d.net/latest/en/manual/scripts/index.html), however, which are components containing logic, we get into a bit of a pickle. Yes, the script should be able to have private state and a public API for other components to interact with it. What if we want to restrict some data so that it can only be set once during initialization? Ideally the editor would not be constrained to modify the property during design, but once we hit the runtime it should be allowed to change.
## Editor runs your code directly
In Stride when you create a script in your project and open the project in the editor, the project will be compiled, the DLL loaded into memory of the editor, and when you add the script to an entity it will actually create a new instance of your script class. Same as at runtime.
It won't run the script Update method, but if you have any logic in your property getters and setters those will be invoked at design time. This can give you enormous flexibility. But it also means that however you want your script to behave at runtime when it comes to properties the same will be enforced at design time.
The editor uses reflection to access properties and fields on your script. It technically could modify private fields on the object instance it holds during design. But this needs to survive saving the project to disk.
## Serialization
Stride uses YAML for design time serialization of [Assets](https://doc.stride3d.net/latest/en/manual/game-studio/assets.html). The assets can have a different form from the actual Content they are compiled to by the AssetCompiler. This is used for example by Audio or Model assets which at design time just hold a reference to your media files, but once compiled actually hold the bits of your media in a format that's easy to consume by Stride's runtime.
For components and scripts rather than having a second class for each component and doing compilation from design to runtime representation, those classes are the same in both scenarios. This simplifies things but it means that serialization constraints need to be applied equally.
While YAML is very flexible and the serializer currently uses reflection to set the properties, the runtime serialization is done using a custom binary serializer system. When you compile your game project, after C# compiler has done its job, the build system runs the AssemblyProcessor over your code to generate efficient serializer classes that do not use reflection to access members on the objects they deserialize.
Access modifiers are enforced by the CLR, which means it's not possible to generate code that accesses private members of another class directly.
### What about constructors?
If we have a private field that we want to set once, why don't we use a constructor to accept a value for it? It's certainly an option and there are serialization systems which look at constructors to provide deserialization in this way. They may be a bit more complicated but it's possible to implement them.
However, in a generic environment that Stride provides it's a bit difficult. How would the editor create a new instance of your class if it requires data to be passed in the constructor? Will it provide `default` values, will it look for a private parameterless constructor?
### What about init properties?
C# 9 has introduced [`init`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/init) properties which are only allowed to be set at object construction. Reflection is able to bypass that of course, while at the CLR level a special marker `modreq` is placed on the property which asks the compiler to provide `modreq` marker on the callsite as well (see [thread](https://stackoverflow.com/a/64749884)). Compilers which don't know about init properties would still prevent you from assigning them. And the CLR is not actually enforcing anything here - only compiler - thus the generated serializers are still able to use those properties.
But in your code the constraint will be enforced and no runtime modification will occur after the object is initialized.
```csharp
public string MyProperty { get; init; }
```
### `UnsafeAccessor` in .NET 8
As we're trying to squeeze out more performance and improve the Stride codebase we're looking at rewriting the AssemblyProcessor from Mono.Cecil and manually emitting IL into a Roslyn C# source generator. This will also mean being restricted to whatever the compiler enforces, such as not setting init properties outside of object construction.
Luckily in .NET 8 there's a new performance hack which allows you to access private fields on other classes. You can read about it more in the [proposal](https://github.com/dotnet/runtime/issues/81741) and on the [performance blog](https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-8/#networking-primitives).
```csharp
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_myField")]
extern static ref string _myField(MyClass c);
```
## Summary
There might be some extra work needed to implement the changes to allow setting private members in the editor. At the moment using `init` properties is nice a middle ground.
While in my opinion designing clear public APIs for components in a data driven approach is the way and it doesn't need access to private members, there's many users who see value in being able to use private members to their advantage and it's on the editor and engine to provide flexibility of choice in how you structure your code.
Thank you for reading 📖, and happy coding 💻👩💻👨💻!
|
export interface Billboard {
id: string;
label: string;
imageUrl: string;
};
export interface Category {
id: string;
name: string;
billboard: Billboard;
};
export interface Product {
id: string;
category: Category;
name: string;
price: string;
isFeatured: boolean;
size: Size;
color: Color;
images: Image[];
};
export interface Size{
id: string;
name: string;
value: string;
};
export interface Color{
id: string;
name: string;
value: string;
};
export interface Image{
id: string;
url: string;
};
|
// An FPS counter in the console using tasks
#include "../example_base.hpp"
// For the task functionality:
#include <coresystem/task.hpp>
// For from::unique_ptr with delay deletion:
#include <memory/from_unique_ptr.hpp>
// For wait_for_system:
#include <dantelion2/system.hpp>
// Our new task must derive from CS::CSEzTask
// It's a task that accumulates frame time passed to it by ELDEN RING
struct count_frames_task : public from::CS::CSEzTask {
// Override the abstract execute method
// It will be called every frame
void eztask_execute(from::FD4::FD4TaskData* data) override {
// Add the current frame's delta time to the total time
time_passed += data->get_dt();
// Increment frame count
++frame_count;
}
// Custom free_task that is called from the overriden destructor
// Prints out all of the collected data
void free_task() override {
system("cls");
std::cout << "Framerate collection finished!\n";
std::cout << "Game time passed: " << time_passed << "\n";
std::cout << "Total frames counted: " << frame_count << std::endl;
}
// Call this class's free_task when the task is destroyed
// CS::CSEzTask does so too, but it calls the base free_task
~count_frames_task() override {
this->free_task();
}
// Member variables for persistent data:
double time_passed = 0.0;
long long frame_count = 0;
};
// We can further instrument frame counting to do something every second
// This task prints out data from a count_frames_task and calculates the framerate
// Derives from CS::CSEzTask through its parent class
struct print_fps_task : count_frames_task {
print_fps_task(count_frames_task& count_task) : count_task(count_task) {}
void eztask_execute(from::FD4::FD4TaskData* data) override {
// Call the base function to increment this task's time and frame count
count_frames_task::eztask_execute(data);
if (count_task.time_passed > 0.0f && this->time_passed >= 1.0f) {
double fps = static_cast<double>(count_task.frame_count)
/ count_task.time_passed;
// Clear console and print FPS:
system("cls");
std::cout << "Frames last second: " << this->frame_count << "\n";
std::cout << "Average FPS: " << fps << std::endl;
// Reset the counters of this task
this->time_passed = 0.0f;
this->frame_count = 0;
}
}
// The counter task to read from:
count_frames_task& count_task;
};
// Will be called from DllMain
void example_base() {
// Allocate console, enable manual flushing
con_allocate(true);
// Make two unique_ptr objects locally
// Once they go out of scope, the tasks will be freed
from::unique_ptr<count_frames_task> count_task =
from::make_unique<count_frames_task>();
from::unique_ptr<print_fps_task> print_task =
from::make_unique<print_fps_task>(*count_task);
// It's necessary to wait for the task system to be initialized
// before registering tasks. We can use wait_for_system
// with a timeout of 5000ms to ensure ELDEN RING has initialized it
if (!from::DLSY::wait_for_system(5'000)) {
std::cout << "wait_for_system timed out!" << std::endl;
return;
}
// Register the two tasks, which starts their execution
// count_task is set to execute on FrameBegin, the first task group
// print_task will execute on Flip, a much later task group
// This chronological relationship means print_task can
// access count_task's data in a thread safe manner
count_task->register_task(from::CS::CSTaskGroup::FrameBegin);
print_task->register_task(from::CS::CSTaskGroup::Flip);
// Wait and let the tasks run for 60s
Sleep(60'000);
// The tasks don't need to be explicitly freed,
// as the delay deleter of from::unique_ptr will free
// them instead when they go out of scope.
// count_task->free_task();
// print_task->free_task();
}
|
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
import '@testing-library/jest-dom/vitest';
import { fireEvent, render, screen } from '@testing-library/svelte';
import { beforeEach, expect, test, vi } from 'vitest';
import { type CombinedExtensionInfoUI } from '/@/stores/all-installed-extensions';
import { catalogExtensionInfos } from '/@/stores/catalog-extensions';
import { extensionInfos } from '/@/stores/extensions';
import type { CatalogExtension } from '../../../../main/src/plugin/extensions-catalog/extensions-catalog-api';
import ExtensionDetails from './ExtensionDetails.svelte';
beforeEach(() => {
vi.resetAllMocks();
});
async function waitRender(customProperties: object): Promise<void> {
const result = render(ExtensionDetails, { ...customProperties });
while (result.component.$$.ctx[0] === undefined) {
console.log(result.component.$$.ctx);
await new Promise(resolve => setTimeout(resolve, 100));
}
}
export const aFakeExtension: CatalogExtension = {
id: 'idAInstalled',
publisherName: 'FooPublisher',
shortDescription: 'this is short A',
publisherDisplayName: 'Foo Publisher',
extensionName: 'a-extension',
displayName: 'A Extension',
categories: [],
unlisted: false,
versions: [
{
version: '1.0.0A',
preview: false,
files: [
{
assetType: 'icon',
data: 'iconA',
},
],
ociUri: 'linkA',
lastUpdated: new Date(),
},
],
};
export const withSpacesFakeExtension: CatalogExtension = {
id: 'id A Installed',
publisherName: 'FooPublisher',
shortDescription: 'this is short A',
publisherDisplayName: 'Foo Publisher',
extensionName: 'a-extension',
displayName: 'A Extension',
categories: [],
unlisted: false,
versions: [
{
version: '1.0.0A',
preview: false,
files: [
{
assetType: 'icon',
data: 'iconA',
},
],
ociUri: 'linkA',
lastUpdated: new Date(),
},
],
};
const combined: CombinedExtensionInfoUI[] = [
{
id: 'idAInstalled',
displayName: 'A installed Extension',
name: 'A extension',
removable: true,
state: 'started',
},
{
id: 'idYInstalled',
displayName: 'Y installed Extension',
},
] as unknown[] as CombinedExtensionInfoUI[];
const combinedWithError: CombinedExtensionInfoUI[] = [
{
id: 'idAInstalled',
displayName: 'A failed installed Extension',
name: 'A extension',
removable: true,
state: 'failed',
error: {
message: 'custom error',
stack: 'custom stack',
},
},
] as unknown[] as CombinedExtensionInfoUI[];
test('Expect to have details page', async () => {
const extensionId = 'idAInstalled';
catalogExtensionInfos.set([aFakeExtension]);
extensionInfos.set(combined);
await waitRender({ extensionId });
const heading = screen.getByRole('heading', { name: 'A installed Extension extension' });
expect(heading).toBeInTheDocument();
const extensionActions = screen.getByRole('group', { name: 'Extension Actions' });
expect(extensionActions).toBeInTheDocument();
const extensionBadge = screen.getByRole('region', { name: 'Extension Badge' });
expect(extensionBadge).toBeInTheDocument();
// no tabs as not failing state
const readmeTab = screen.queryByRole('button', { name: 'Readme' });
expect(readmeTab).not.toBeInTheDocument();
const errorTab = screen.queryByRole('button', { name: 'Error' });
expect(errorTab).not.toBeInTheDocument();
});
test('Expect to have details page with error tab with failed state', async () => {
const extensionId = 'idAInstalled';
catalogExtensionInfos.set([aFakeExtension]);
extensionInfos.set(combinedWithError);
await waitRender({ extensionId });
// check that we have two tabs
const readmeTab = screen.getByRole('button', { name: 'Readme' });
expect(readmeTab).toBeInTheDocument();
// check that we have two tabs
const errorTab = screen.getByRole('button', { name: 'Error' });
expect(errorTab).toBeInTheDocument();
// click on the error tab
await fireEvent.click(errorTab);
// now check that the error is on the page
// should contain the error
const error = screen.getByText('Error: custom error');
expect(error).toBeInTheDocument();
});
test('Expect empty screen', async () => {
const extensionId = 'idUnknown';
catalogExtensionInfos.set([aFakeExtension]);
extensionInfos.set(combined);
await waitRender({ extensionId });
// should have the text "Extension not found"
const extensionNotFound = screen.getByText('Extension not found');
expect(extensionNotFound).toBeInTheDocument();
});
test('Expect to have details page with id with spaces', async () => {
const extensionId = 'id A Installed';
catalogExtensionInfos.set([withSpacesFakeExtension]);
extensionInfos.set(combined);
await waitRender({ extensionId });
const heading = screen.getByRole('heading', { name: 'A Extension extension' });
expect(heading).toBeInTheDocument();
});
|
import ReactTimeAgo from "react-time-ago";
import Avatar from "./Avatar";
import Link from "next/link";
import PostButtons from "./PostButtons";
export default function PostContent({
text, author, createdAt, _id,
likesCount,likedByMe, commentsCount,
big = false }) {
//console.log('this is the author: ' + author);
return (
<div>
{likedByMe? 1:0}
<div className="flex w-full">
<div>
{!!author?.image && (
<div className="cursor-pointer">
<Link href={'/'+author?.username}>
<Avatar src={author.image} />
</Link>
</div>
)}
</div>
<div className="pl-2 grow">
<div>
<Link href={'/' + author?.username}>
<span className="font-bold pr-1 cursor-pointer">{author.name}</span>
</Link>
{big && (<br />)}
<Link href={'/' + author?.username}>
<span className=" text-twitterLightGray cursor-pointer">@{author.username}</span>
</Link>
{createdAt && !big && (
<span className="pl-1 text-twitterLightGray">
<ReactTimeAgo
date={Date.parse(createdAt)}
timeStyle={'twitter'} />
</span>
)}
</div>
{!big && (
<div>
<Link href={'/' + author?.username + '/status/' + _id}>
<div className="w-full cursor-pointer">
{text}
</div>
</Link>
<PostButtons username={author?.username} id={_id} likesCount={likesCount} likedByMe={likedByMe} commentsCount={commentsCount}/>
</div>
)}
</div>
</div>
{big && (
<div className="mt-2">
<Link href={'/' + author?.username + '/status/' + _id}>
{text}
</Link>
{createdAt && (
<div className="text-twitterLightGray text-sm">
{(new Date(createdAt))
.toISOString()
.replace('T', ' ')
.slice(0, 16)
.split(' ')
.reverse()
.join(' ')
}
</div>
)}
<PostButtons username={author?.username} id={_id} likesCount={likesCount} likedByMe={likedByMe} commentsCount={commentsCount}/>
</div>
)}
</div>
);
}
|
public void testSelectProjectWithPaging() throws Exception {
// Test inserting and retrieving a couple pages worth of data
int pages = 3;
int pageSize = 10;
int insertCount = (pages * pageSize);
// Unique project characteristics for testing against
String projectTitle = "ProjectListAPITest Test Project insert " + insertCount + " records and select using paging";
String keywords = "Tracker:" + System.currentTimeMillis();
// Insert lots of projects for testing the paging
{
// Define the project
DataRecord record = new DataRecord();
record.setName("project");
record.setAction(DataRecord.INSERT);
record.setShareKey(true);
record.addField("title", projectTitle);
record.addField("shortDescription", "API Test Project short description");
record.addField("keywords", keywords);
record.addField("requestDate", new Date());
record.addField("enteredBy", USER_ID);
record.addField("modifiedBy", USER_ID);
record.addField("groupId", GROUP_ID);
// Insert it several times
for (int insertTracker = 0; insertTracker < insertCount; insertTracker++) {
api.save(record);
processTheTransactions(api, packetContext);
assertFalse("API reported a transaction error: " + api.getLastResponse(), api.hasError());
}
}
int recordCountProcessed = 0;
int currentOffset = 0;
for (int pageCount = 0; pageCount < pages; pageCount++) {
// Start at offset 0 and add the number per page
currentOffset = (pageCount * pageSize);
// Retrieve records by paging through the resultset
{
// Add Meta Info with fields required
ArrayList<String> meta = new ArrayList<String>();
meta.add("id");
meta.add("title");
meta.add("keywords");
api.setTransactionMeta(meta);
System.out.println("Checking offset: " + currentOffset);
DataRecord record = new DataRecord();
record.setName("projectList");
record.setAction(DataRecord.SELECT);
record.addField("keywords", keywords);
// NOTE: Sort takes the actual database fields (instead of bean properties) comma separated
record.setSort("project_id");
record.setOffset(currentOffset);
record.setItems(pageSize);
api.save(record);
processTheTransactions(api, packetContext);
assertFalse("API reported a transaction error: " + api.getLastResponse(), api.hasError());
assertTrue("Couldn't find inserted projects - " + api.getRecordCount(), api.getRecordCount() == record.getItems());
}
// Demonstrate using the raw DataRecord objects when the Project class is unavailable in the classpath
ArrayList<DataRecord> recordList = api.getRecords();
assertTrue(recordList.size() == pageSize);
for (DataRecord thisRecord : recordList) {
assertTrue("ProjectId is -1", thisRecord.getValueAsInt("id") > -1);
assertTrue(projectTitle.equals(thisRecord.getValue("title")));
assertTrue(keywords.equals(thisRecord.getValue("keywords")));
}
// Demonstrate converting the recordset to Project objects
ArrayList<Object> projectObjects = api.getRecords("com.concursive.connect.web.modules.profile.dao.Project");
assertTrue(projectObjects.size() == pageSize);
for (Object projectObject : projectObjects) {
Project partialProject = (Project) projectObject;
assertNotNull(partialProject);
assertTrue("ProjectId is -1", partialProject.getId() > -1);
assertTrue(projectTitle.equals(partialProject.getTitle()));
++recordCountProcessed;
}
}
// Cleanup any matching projects
ProjectList projects = new ProjectList();
projects.setKeywords(keywords);
projects.buildList(db);
assertEquals(insertCount, projects.size());
for (Project project : projects) {
project.delete(db, null);
}
// Make sure all the records were seen that were inserted
assertEquals(insertCount, recordCountProcessed);
}
|
// Primitive Data Types
// -Strings
const name = 'Akhil Jayan';
console.log(typeof name);
// -Numbers [includes everything int float ]
const age = 20;
console.log(typeof age);
// -Boolean
const hasKids = true;
console.log(typeof hasKids);
// -null
const car = null;
console.log(typeof car); // this will give us object which is a bug in JS.
// -undefined
let test;
console.log(typeof test);
// -Symbols
const sym = Symbol();
console.log(typeof sym);
// Reference Data Types - Objects
// -Arrays
const hobbies = ['movies','music'];
console.log(typeof hobbies);
// -Object Literals
const address = {
city: 'Delhi' ,
state: 'Delhi'
}
console.log(typeof address);
// -dates
const today = new Date();
console.log(today);
console.log(typeof today);
// -functions
// -Anything else
// JS is a dynamically typed value which means the data type is associated with the value not the variables. The same variable can hold multiple types without giving errors. We dont need to specify the types.
|
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import React, { useContext } from 'react'
import { ListGroup } from 'react-bootstrap'
import { Helmet } from 'react-helmet-async'
import { userContext } from '../App'
import JobOffer from '../components/JobOffer'
import Loader from '../components/Loader'
import Message from '../components/Message'
import { Offer } from '../types'
import { errorHandler } from '../utils/errorHandler'
type FetchedData = { offers: Offer[]; page: number; pages: number }
const FavouritesScreen = () => {
const { userInfo } = useContext(userContext)
const { isLoading, isError, error, data } = useQuery<any, Error, FetchedData>(
['listOffers'],
async () => {
const { data } = await axios.get('/api/offers/all')
return data
}
)
return (
<>
{isLoading ? (
<Loader />
) : isError ? (
<Message variant='danger'>{errorHandler(error)}</Message>
) : (
<>
<h2>Favourites</h2>
{isLoading ? (
<Loader />
) : isError ? (
<Message variant='danger'>{errorHandler(error)}</Message>
) : (
<>
<Helmet>
<title>Job finder - Saved job offers</title>
</Helmet>
{userInfo && userInfo.saved.length > 0 ? (
<ListGroup variant='flush'>
<ListGroup.Item className='p-0 p-lg-3'>
{data.offers
.filter((offer) => userInfo?.saved.includes(offer._id))
.map((offer) => (
<JobOffer key={offer._id} offer={offer} />
))}
</ListGroup.Item>
</ListGroup>
) : (
<Message className='my-3' variant='info'>
You don't have any favourites job offers yet.
</Message>
)}
</>
)}
</>
)}
</>
)
}
export default FavouritesScreen
|
//
// NSArray+CWAdditions.m
// SC68 Player
//
// Created by Fredrik Olsson on 2008-11-13.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "NSArray+CWAutoboxing.h"
@implementation NSArray (CWAutoboxing)
-(char)charValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number charValue];
}
return 0;
}
-(unsigned char)unsignedCharValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number unsignedCharValue];
}
return 0;
}
-(short)shortValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number shortValue];
}
return 0;
}
-(unsigned short)unsignedShortValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number unsignedShortValue];
}
return 0;
}
-(int)intValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number intValue];
}
return 0;
}
-(unsigned int)unsignedIntValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number unsignedIntValue];
}
return 0;
}
-(long)longValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number longValue];
}
return 0;
}
-(unsigned long)unsignedLongValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number unsignedLongValue];
}
return 0;
}
-(long long)longLongValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number longLongValue];
}
return 0;
}
-(unsigned long long)unsignedLongLongValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number unsignedLongLongValue];
}
return 0;
}
-(float)floatValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number floatValue];
}
return 0;
}
-(double)doubleValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number doubleValue];
}
return 0;
}
-(BOOL)boolValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number boolValue];
}
return NO;
}
-(NSInteger)integerValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number integerValue];
}
return 0;
}
-(NSUInteger)unsignedIntegerValueAtIndex:(NSUInteger)index;
{
NSNumber* number = [self objectAtIndex:index withExpectedClass:[NSNumber class]];
if (number) {
return [number unsignedIntegerValue];
}
return 0;
}
-(NSNumber*)numberValueAtIndex:(NSUInteger)index;
{
return [self objectAtIndex:index withExpectedClass:[NSNumber class]];
}
-(NSString*)stringValueAtIndex:(NSUInteger)index;
{
return [self objectAtIndex:index withExpectedClass:[NSString class]];
}
-(id)objectAtIndex:(NSUInteger)index withExpectedClass:(Class)aClass;
{
id<NSObject> anObject = (id<NSObject>)[self objectAtIndex:index];
if (anObject) {
if (![anObject isKindOfClass:aClass]) {
[NSException raise:NSInternalInconsistencyException format:@"Expected %@ instance, found %@", NSStringFromClass(aClass), NSStringFromClass([anObject class])];
}
}
return anObject;
}
@end
@implementation NSMutableArray (CWAutoboxing)
-(void)addChar:(char)value;
{
[self addObject:[NSNumber numberWithChar:value]];
}
-(void)addUnsignedChar:(unsigned char)value;
{
[self addObject:[NSNumber numberWithUnsignedChar:value]];
}
-(void)addShort:(short)value;
{
[self addObject:[NSNumber numberWithShort:value]];
}
-(void)addUnsignedShort:(unsigned short)value;
{
[self addObject:[NSNumber numberWithUnsignedShort:value]];
}
-(void)addInt:(int)value;
{
[self addObject:[NSNumber numberWithInt:value]];
}
-(void)addUnsignedInt:(unsigned int)value;
{
[self addObject:[NSNumber numberWithUnsignedInt:value]];
}
-(void)addLong:(long)value;
{
[self addObject:[NSNumber numberWithLong:value]];
}
-(void)addUnsignedLong:(unsigned long)value;
{
[self addObject:[NSNumber numberWithUnsignedLong:value]];
}
-(void)addLongLong:(long long)value;
{
[self addObject:[NSNumber numberWithLongLong:value]];
}
-(void)addUnsignedLongLong:(unsigned long long)value;
{
[self addObject:[NSNumber numberWithUnsignedLongLong:value]];
}
-(void)addFloat:(float)value;
{
[self addObject:[NSNumber numberWithFloat:value]];
}
-(void)addDouble:(double)value;
{
[self addObject:[NSNumber numberWithDouble:value]];
}
-(void)addBool:(BOOL)value;
{
[self addObject:[NSNumber numberWithBool:value]];
}
-(void)addInteger:(NSInteger)value;
{
[self addObject:[NSNumber numberWithInteger:value]];
}
-(void)addUnsignedInteger:(NSUInteger)value;
{
[self addObject:[NSNumber numberWithUnsignedInteger:value]];
}
-(void)insertChar:(char)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithChar:value] atIndex:index];
}
-(void)insertUnsignedChar:(unsigned char)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithUnsignedChar:value] atIndex:index];
}
-(void)insertShort:(short)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithShort:value] atIndex:index];
}
-(void)insertUnsignedShort:(unsigned short)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithUnsignedShort:value] atIndex:index];
}
-(void)insertInt:(int)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithInt:value] atIndex:index];
}
-(void)insertUnsignedInt:(unsigned int)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithUnsignedInt:value] atIndex:index];
}
-(void)insertLong:(long)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithLong:value] atIndex:index];
}
-(void)insertUnsignedLong:(unsigned long)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithUnsignedLong:value] atIndex:index];
}
-(void)insertLongLong:(long long)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithLongLong:value] atIndex:index];
}
-(void)insertUnsignedLongLong:(unsigned long long)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithUnsignedLongLong:value] atIndex:index];
}
-(void)insertFloat:(float)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithFloat:value] atIndex:index];
}
-(void)insertDouble:(double)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithDouble:value] atIndex:index];
}
-(void)insertBool:(BOOL)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithBool:value] atIndex:index];
}
-(void)insertInteger:(NSInteger)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithInteger:value] atIndex:index];
}
-(void)insertUnsignedInteger:(NSUInteger)value atIndex:(NSUInteger)index;
{
[self insertObject:[NSNumber numberWithUnsignedInteger:value] atIndex:index];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withChar:(char)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithChar:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withUnsignedChar:(unsigned char)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithUnsignedChar:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withShort:(short)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithShort:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withUnsignedShort:(unsigned short)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithUnsignedShort:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withInt:(int)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withUnsignedInt:(unsigned int)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithUnsignedInt:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withLong:(long)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithLong:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withUnsignedLong:(unsigned long)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithUnsignedLong:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withLongLong:(long long)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithLongLong:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withUnsignedLongLong:(unsigned long long)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithUnsignedLongLong:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withFloat:(float)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithFloat:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withDouble:(double)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithDouble:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withBool:(BOOL)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withInteger:(NSInteger)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithInteger:value]];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withUnsignedInteger:(NSUInteger)value;
{
[self replaceObjectAtIndex:index withObject:[NSNumber numberWithUnsignedInteger:value]];
}
@end
|
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
/*
uv: uv map
fun: function
output 1 to represent there this is in the range of the function, else output 0
*/
float plot_func(vec2 uv, float func) {
// blur amount is relative to the resolution
float blur = 2./u_resolution.y;
return smoothstep( func-blur, func, uv.y) -
smoothstep( func, func+blur, uv.y);
}
void main() {
// normalization
vec2 uv = gl_FragCoord.xy/u_resolution;
// extract the x and y variable
float x = uv.x;
float y = uv.y;
// try different functions!
float func = 1. - pow(abs(x), 0.5*6.*abs(sin(u_time)));
func = pow(cos(3.1415*x/2.0), 0.5*6.*abs(sin(u_time)));
func = 1.-pow(abs(sin(3.1415*x/2.)), 0.5*6.*abs(sin(u_time)));
func = pow(min(cos(3.1415*x/2.0), 1.-abs(x)),0.5*6.*abs(sin(u_time)));
func = 1. - pow(max(0.0, abs(x)*2.-1.), 0.5*6.*abs(sin(u_time)));
float c_func = plot_func(uv, func);
vec3 color_func = vec3(c_func) * vec3(1.0,0.0,0.0);
// Plot y changed base on x
vec3 color_bright = vec3(func);
// here we mix the color_bright and color_func
vec3 color = mix(color_bright, color_func, c_func);
gl_FragColor = vec4(color,1.0);
}
|
#!/usr/bin/python3
"""Module containing ``Square`` class inheriting from
``Rectangle`` class
"""
base_g = __import__('9-rectangle')
class Square(base_g.Rectangle):
"""Class definition"""
def __init__(self, size):
"""Initialize the square attributes"""
super().integer_validator("size", size)
super().__init__(size, size)
self.__size = size
def area(self):
"""Compute the area of the square"""
return self.__size ** 2
|
/*
https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/
Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor have cooperated with the director at least 3 times.
Example:
ActorDirector table:
+-------------+-------------+-------------+
| actor_id | director_id | timestamp |
+-------------+-------------+-------------+
| 1 | 1 | 0 |
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 2 | 3 |
| 1 | 2 | 4 |
| 2 | 1 | 5 |
| 2 | 1 | 6 |
+-------------+-------------+-------------+
Result table:
+-------------+-------------+
| actor_id | director_id |
+-------------+-------------+
| 1 | 1 |
+-------------+-------------+
The only pair is (1, 1) where they cooperated exactly 3 times.
*/
/*
A dummy Solution
SELECT actor_id, director_id
FROM (SELECT actor_id, director_id, count(DISTINCT(timestamp)) AS cnt
FROM ActorDirector
GROUP BY actor_id, director_id) AS cntTable
WHERE cnt >= 3
*/
SELECT actor_id, director_id
FROM ActorDirector
GROUP BY actor_id, director_id
HAVING COUNT(timestamp) >= 3; # Timestamp is Primary key, it is unique
|
package com.dogeby.reliccalculator.core.network.retrofit
import com.dogeby.reliccalculator.core.model.mihomo.Profile
import com.dogeby.reliccalculator.core.network.BuildConfig
import com.dogeby.reliccalculator.core.network.ProfileNetworkDataSource
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
private const val PROFILE_URL = BuildConfig.PROFILE_URL
@Singleton
class RetrofitProfileNetwork @Inject constructor(
networkJson: Json,
) : ProfileNetworkDataSource {
private val networkApi =
Retrofit.Builder()
.baseUrl(PROFILE_URL)
.addConverterFactory(
networkJson.asConverterFactory("application/json".toMediaType()),
)
.build()
.create(RetrofitProfileNetworkApi::class.java)
override suspend fun getProfile(
uid: String,
language: String,
): Result<Profile> {
return runCatching {
networkApi.getProfile(uid, language)
}
}
}
private interface RetrofitProfileNetworkApi {
@GET(value = "{uid}")
suspend fun getProfile(
@Path("uid") uid: String,
@Query("lang") language: String,
): Profile
}
|
import React, { useState } from "react";
import { Line } from "react-chartjs-2";
// import { de } from "date-fns/locale";
// import { format, parseISO } from "date-fns";
import "chartjs-adapter-date-fns";
import Datepicker, { type DateValueType } from "react-tailwindcss-datepicker";
import {
Chart as ChartJS,
LinearScale,
PointElement,
Tooltip,
Legend,
TimeScale,
type ChartOptions,
} from "chart.js";
ChartJS.register(LinearScale, PointElement, Tooltip, Legend, TimeScale);
const AreaChart: React.FC = () => {
const [value, setValue] = useState<DateValueType>({
startDate: new Date(),
endDate: new Date(),
});
// const handleValueChange = (newValue: React.SetStateAction<{ startDate: Date; endDate: Date; }>) => {
// console.log("newValue:", newValue);
// setValue(newValue);
// };
const handleValueChange = (
value: DateValueType,
) => {
if (value !== null && typeof value !== "undefined") {
setValue(value);
}
};
const data = {
datasets: [
{
label: "Africa",
data: [
{ x: "2023-12-07", y: 40 },
{ x: "2023-12-08", y: 55 },
{ x: "2023-12-09", y: 45 },
{ x: "2023-12-10", y: 75 },
{ x: "2023-12-11", y: 65 },
{ x: "2023-12-12", y: 55 },
{ x: "2023-12-13", y: 70 },
{ x: "2023-12-14", y: 60 },
{ x: "2023-12-15", y: 100 },
{ x: "2023-12-16", y: 98 },
{ x: "2023-12-17", y: 90 },
{ x: "2023-12-18", y: 120 },
{ x: "2023-12-19", y: 125 },
{ x: "2023-12-20", y: 140 },
{ x: "2023-12-21", y: 155 },
],
backgroundColor: "rgba(44, 154, 255, 0.8)",
borderWidth: 0,
pointRadius: 1,
fill: "start",
},
{
label: "Asia",
data: [
{ x: "2023-12-07", y: 70 },
{ x: "2023-12-08", y: 85 },
{ x: "2023-12-09", y: 75 },
{ x: "2023-12-10", y: 150 },
{ x: "2023-12-11", y: 100 },
{ x: "2023-12-12", y: 140 },
{ x: "2023-12-13", y: 110 },
{ x: "2023-12-14", y: 105 },
{ x: "2023-12-15", y: 160 },
{ x: "2023-12-16", y: 150 },
{ x: "2023-12-17", y: 125 },
{ x: "2023-12-18", y: 190 },
{ x: "2023-12-19", y: 200 },
{ x: "2023-12-20", y: 225 },
{ x: "2023-12-21", y: 275 },
],
backgroundColor: "#84D0FF",
borderWidth: 0,
pointRadius: 1,
fill: "start",
},
{
label: "Europe",
data: [
{ x: "2023-12-07", y: 240 },
{ x: "2023-12-08", y: 195 },
{ x: "2023-12-09", y: 160 },
{ x: "2023-12-10", y: 215 },
{ x: "2023-12-11", y: 185 },
{ x: "2023-12-12", y: 215 },
{ x: "2023-12-13", y: 185 },
{ x: "2023-12-14", y: 200 },
{ x: "2023-12-15", y: 250 },
{ x: "2023-12-16", y: 210 },
{ x: "2023-12-17", y: 195 },
{ x: "2023-12-18", y: 250 },
{ x: "2023-12-19", y: 235 },
{ x: "2023-12-20", y: 300 },
{ x: "2023-12-21", y: 315 },
],
backgroundColor: "#EDF1F4",
borderWidth: 0,
pointRadius: 1,
fill: "start",
},
],
};
const options: ChartOptions<"line"> = {
responsive: true,
maintainAspectRatio: false,
// adapters: {
// date: {
// locale: de,
// },
// },
scales: {
x: {
type: "time",
min: "2023-12-07",
max: "2023-12-21",
time: {
unit: "day",
// parser: (value: string) => {
// return parseISO(value);
// },
// tooltipFormat: "dd/MM",
// formatter: (time: number | Date) => {
// // Custom formatting using date-fns
// return format(time, "dd/MM");
// },
},
position: "bottom",
ticks: {
color: "#9196b2",
callback: (value) => {
// Custom label formatting using date-fns with "/" separator
const date = new Date(value);
const day = date.getDate().toString();
const month = (date.getMonth() + 1).toString();
return `${day}/${month}`;
},
},
grid: {
color: "#646880",
display: false,
},
// beginAtZero: true,
},
y: {
min: 0,
max: 400,
ticks: {
stepSize: 100,
color: "#9196b2",
},
grid: {
color: "#646880",
display: false,
},
beginAtZero: true,
},
},
plugins: {
legend: {
labels: {
color: "white",
boxWidth: 15,
boxHeight: 15,
usePointStyle: true,
pointStyle: "circle",
padding: 30,
},
position: "top",
align: "start",
},
},
};
return (
<div className={`w-full`}>
<div className={`flex items-center justify-between p-4`}>
<div className={``}>
<h1>Area Chart</h1>
</div>
<div className={` rounded-lg border-[1px] border-[#454960]`}>
<Datepicker
// placeholder={"My Placeholder"}
// separator={"<->"}
// startFrom={new Date("1999-01-01")}
asSingle={true}
useRange={false}
primaryColor={"blue"}
value={value}
onChange={handleValueChange}
// showShortcuts={true}
// showFooter={true}
// displayFormat={"DD/MM/YYYY"}
// readOnly={true}
// disabled={true}
// inputClassName="w-full rounded-md focus:ring-0 font-normal bg-green-100 dark:bg-green-900 dark:placeholder:text-green-100"
// containerClassName="relative mt-8"
// toggleClassName="absolute bg-red-300 rounded-r-lg text-white right-0 h-full px-3 text-gray-400 focus:outline-none disabled:opacity-40 disabled:cursor-not-allowed"
// popoverDirection="up"
/>
</div>
</div>
<div className="h-[70vh] w-full flex-col items-center justify-center rounded-lg">
<Line data={data} options={options} />
</div>
</div>
);
};
export default AreaChart;
|
from django.contrib.auth.forms import UserCreationForm
from .constants import ACCOUNT_TYPE,GENDER_TYPE
from django import forms
from django.contrib.auth.models import User
from .models import UserAddress,UserBankAccount
class UserRegistrationForm(UserCreationForm):
birth_date=forms.DateField(widget=forms.DateInput(attrs={'type':'date'}))
gender=forms.ChoiceField(choices=GENDER_TYPE)
account_type=forms.ChoiceField(choices=ACCOUNT_TYPE)
street_address=forms.CharField(max_length=100)
city=forms.CharField(max_length=50)
postal_code=forms.IntegerField()
country=forms.CharField(max_length=100)
class Meta:
model=User
fields=['username','email','first_name','last_name','account_type','birth_date','gender','street_address','city','postal_code','country','password1','password2']
def save(self,commit=True):
our_user=super().save(commit=False)
if commit==True:
our_user.save()
account_type=self.cleaned_data.get('account_type')
gender=self.cleaned_data.get('gender')
postal_code=self.cleaned_data.get('postal_code')
city=self.cleaned_data.get('city')
country=self.cleaned_data.get('country')
birth_date=self.cleaned_data.get('birth_date')
street_address=self.cleaned_data.get('street_address')
UserAddress.objects.create(
user=our_user,
street_address=street_address,
city=city,
postal_code=postal_code,
country=country,
)
UserBankAccount.objects.create(
user=our_user,
account_type=account_type,
gender=gender,
birth_date=birth_date,
account_no=100000+our_user.id
)
return our_user
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({
'class' : (
'form-control '
'bg-light '
'text-dark '
'border '
'border-secondary '
'rounded '
'py-3 px-4 '
'leading-tight '
'focus:outline-none '
'focus:bg-white focus:border-secondary'
)
})
class UserUpdateForm(forms.ModelForm):
birth_date = forms.DateField(widget=forms.DateInput(attrs={'type':'date'}))
gender = forms.ChoiceField(choices=GENDER_TYPE)
account_type = forms.ChoiceField(choices=ACCOUNT_TYPE)
street_address = forms.CharField(max_length=100)
city = forms.CharField(max_length= 100)
postal_code = forms.IntegerField()
country = forms.CharField(max_length=100)
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({
'class' : (
'form-control '
'bg-light '
'text-dark '
'border '
'border-secondary '
'rounded '
'py-3 px-4 '
'leading-tight '
'focus:outline-none '
'focus:bg-white focus:border-secondary'
)
})
# jodi user er account thake
if self.instance:
try:
user_account = self.instance.account
user_address = self.instance.address
except UserBankAccount.DoesNotExist:
user_account = None
user_address = None
if user_account:
self.fields['account_type'].initial = user_account.account_type
self.fields['gender'].initial = user_account.gender
self.fields['birth_date'].initial = user_account.birth_date
self.fields['street_address'].initial = user_address.street_address
self.fields['city'].initial = user_address.city
self.fields['postal_code'].initial = user_address.postal_code
self.fields['country'].initial = user_address.country
def save(self, commit=True):
user = super().save(commit=False)
if commit:
user.save()
user_account, created = UserBankAccount.objects.get_or_create(user=user) # jodi account thake taile seta jabe user_account ar jodi account na thake taile create hobe ar seta created er moddhe jabe
user_address, created = UserAddress.objects.get_or_create(user=user)
user_account.account_type = self.cleaned_data['account_type']
user_account.gender = self.cleaned_data['gender']
user_account.birth_date = self.cleaned_data['birth_date']
user_account.save()
user_address.street_address = self.cleaned_data['street_address']
user_address.city = self.cleaned_data['city']
user_address.postal_code = self.cleaned_data['postal_code']
user_address.country = self.cleaned_data['country']
user_address.save()
return user
|
import {useStore} from "vuex";
import {useRoute, useRouter} from "vue-router";
import {computed} from "vue";
import {getSearchParamsFromStore} from "../api/helpers";
import {SET_LAYOUT, SET_PAGINATE_PARAMS, SET_SORTING_PARAMS} from "../store/types";
export const useSubmitSearch = () => {
const store = useStore();
const route = useRoute();
const router = useRouter();
const submitSearch = () => {
store.dispatch('search/resetPaginateSortParams');
const params = doSearch();
updateUrlQueryParams(params, true);
}
const doSearch = () => {
const params = getSearchParamsFromStore({...store.state.search});
store.dispatch('search/search', params);
return params;
}
const handleLayout = layout => {
store.commit(`search/${SET_LAYOUT}`, layout);
let query = Object.assign({}, route.query);
query = {...query, layout};
router.replace({query});
}
const handlePerPage = perPage => {
store.commit(`search/${SET_PAGINATE_PARAMS}`, {page: 1, per_page: perPage});
const params = doSearch();
updateUrlQueryParams(params);
}
const handleSorting = sortObj => {
store.commit(`search/${SET_SORTING_PARAMS}`, {...sortObj});
store.commit(`search/${SET_PAGINATE_PARAMS}`, {page: 1, per_page: store.state.search.paginate_params.per_page});
const params = doSearch();
updateUrlQueryParams(params);
}
const handlePaginate = page => {
store.commit(`search/${SET_PAGINATE_PARAMS}`, {page, per_page: store.state.search.paginate_params.per_page});
const params = doSearch();
updateUrlQueryParams(params);
}
const updateUrlQueryParams = (params, reset = false) => {
let query = Object.assign({}, route.query);
if(reset) {
if(Object.entries(params).length) {
query = {...params};
router.replace({query});
} else {
router.replace({});
}
return;
}
if(Object.entries(params).length) {
query = {...query, ...params};
router.replace({query});
} else {
router.replace({});
}
}
const properties = computed(() => store.state.search.properties);
const loading = computed(() => store.state.search.loading);
const sortingParams = computed(() => store.state.search.sorting_params);
const paginateParams = computed(() => store.state.search.paginate_params);
const defaultLayout = computed(() => store.state.search.defaultLayout);
return {
submitSearch,
properties,
loading,
sortingParams,
paginateParams,
defaultLayout,
handleLayout,
handlePerPage,
handleSorting,
handlePaginate,
doSearch
}
}
|
# flake8: noqa
# yapf: disable
import argparse
import datetime
import json
import math
import os
import os.path as osp
import re
from collections import defaultdict
from datetime import datetime
from glob import glob
from itertools import product
import mmengine
import numpy as np
#import plotly.express as px
import pandas as pd
import tiktoken
from mmengine import ConfigDict
from sklearn.linear_model import LogisticRegression
from tabulate import tabulate
from tqdm import tqdm
from opencompass.partitioners.sub_naive import remove_duplicate_pairs
from opencompass.utils import dataset_abbr_from_cfg, model_abbr_from_cfg
from .utils import get_outdir
def compute_mle_elo(df, SCALE=400, BASE=10, INIT_RATING=1000):
models = pd.concat([df['model_a'], df['model_b']]).unique()
models = pd.Series(np.arange(len(models)), index=models)
# duplicate battles
df = pd.concat([df, df], ignore_index=True)
p = len(models.index)
n = df.shape[0]
X = np.zeros([n, p])
X[np.arange(n), models[df['model_a']]] = +math.log(BASE)
X[np.arange(n), models[df['model_b']]] = -math.log(BASE)
# one A win => two A win
Y = np.zeros(n)
Y[df['winner'] == 'model_a'] = 1.0
# one tie => one A win + one B win
# find tie + tie (both bad) index
tie_idx = (df['winner'] == 'tie') | (df['winner'] == 'tie (bothbad)')
tie_idx[len(tie_idx)//2:] = False
Y[tie_idx] = 1.0
lr = LogisticRegression(fit_intercept=False, penalty=None, tol=1e-8)
lr.fit(X,Y)
elo_scores = SCALE * lr.coef_[0] + INIT_RATING
# set anchor as gpt4-0314 = 1000
if 'gpt4-0314' in models.index:
elo_scores += 1000 - elo_scores[models['gpt4-0314']]
return pd.Series(elo_scores, index = models.index).sort_values(ascending=False)
def get_bootstrap_result(battles, func_compute_elo, num_round):
rows = []
for i in tqdm(range(num_round), desc='bootstrap'):
rows.append(func_compute_elo(battles.sample(frac=1.0, replace=True)))
df = pd.DataFrame(rows)
return df[df.median().sort_values(ascending=False).index]
def preety_print_two_ratings(ratings_1, ratings_2, column_names):
df = pd.DataFrame([
[n, ratings_1[n], ratings_2[n]] for n in ratings_1.keys()
], columns=['Model', column_names[0], column_names[1]]).sort_values(column_names[0], ascending=False).reset_index(drop=True)
df[column_names[0]] = (df[column_names[0]] + 0.5).astype(int)
df[column_names[1]] = (df[column_names[1]] + 0.5).astype(int)
df.index = df.index + 1
return df
def visualize_bootstrap_scores(df, title):
bars = pd.DataFrame(dict(
lower = df.quantile(.025),
rating = df.quantile(.5),
upper = df.quantile(.975))).reset_index(names='model').sort_values('rating', ascending=False)
bars['error_y'] = bars['upper'] - bars['rating']
bars['error_y_minus'] = bars['rating'] - bars['lower']
bars['rating_rounded'] = np.round(bars['rating'], 2)
fig = px.scatter(bars, x='model', y='rating', error_y='error_y',
error_y_minus='error_y_minus', text='rating_rounded',
title=title)
fig.update_layout(xaxis_title='Model', yaxis_title='Rating',
height=600)
return fig
def predict_win_rate(elo_ratings, SCALE=400, BASE=10, INIT_RATING=1000):
names = sorted(list(elo_ratings.keys()))
wins = defaultdict(lambda: defaultdict(lambda: 0))
for a in names:
for b in names:
ea = 1 / (1 + BASE ** ((elo_ratings[b] - elo_ratings[a]) / SCALE))
wins[a][b] = ea
wins[b][a] = 1 - ea
data = {
a: [wins[a][b] if a != b else np.NAN for b in names]
for a in names
}
df = pd.DataFrame(data, index=names)
df.index.name = 'model_a'
df.columns.name = 'model_b'
return df.T
def model_abbr_from_cfg_used_in_summarizer(model):
if model.get('summarizer_abbr', None):
return model['summarizer_abbr']
else:
return model_abbr_from_cfg(model)
def post_process_compass_arena(s):
if result := re.findall('\[\[([AB<>=]+)\]\]', s):
return result[0]
else:
return None
def get_win_rate_column(df, column, baseline='gpt4-0314'):
to_dict = df[['model', column]].set_index('model').to_dict()[column]
win_rate_table = predict_win_rate(to_dict)
return win_rate_table[baseline].fillna(0.5).apply(lambda x: round(x * 100, 2))
def get_battles_from_judgment(dataset, subdir_path, post_process, first_game_only=False, WEIGHT=3):
arena_hard_battles = pd.DataFrame()
print('Turning judgment results into battles...')
dataset_abbr = dataset_abbr_from_cfg(dataset)
filename = osp.join(subdir_path, dataset_abbr + '.json')
partial_filename = osp.join(subdir_path, dataset_abbr + '_0.json')
if osp.exists(osp.realpath(filename)):
result = mmengine.load(filename)
elif osp.exists(osp.realpath(partial_filename)):
filename = partial_filename
result = {}
i = 1
partial_dict_flag = 0
while osp.exists(osp.realpath(filename)):
res = mmengine.load(filename)
for k, v in res.items():
result[partial_dict_flag] = v
partial_dict_flag += 1
filename = osp.join(subdir_path,
dataset_abbr + '_' + str(i) + '.json')
i += 1
else:
result = {}
if len(result) == 0:
print('*' * 100)
print('There are no results for ' + filename + ' or ' +
partial_filename)
print('*' * 100)
assert len(result) > 0
judged_answers = []
references = []
for k, v in result.items():
output = {
'model_a': v['gold']['answer1'],
'model_b': v['gold']['answer2']}
processed_judge = post_process(v['prediction'])
if processed_judge is not None:
weight = 1
if processed_judge == 'A=B':
output['winner'] = 'tie'
elif processed_judge == 'A>B':
output['winner'] = 'model_a'
elif processed_judge == 'A>>B':
output['winner'] = 'model_a'
weight = WEIGHT
elif processed_judge == 'B>A':
output['winner'] = 'model_b'
elif processed_judge == 'B>>A':
output['winner'] = 'model_b'
weight = WEIGHT
else:
weight = 0
else:
weight = 0
if weight:
arena_hard_battles = pd.concat([arena_hard_battles, pd.DataFrame([output] * weight)])
arena_hard_battles.to_json(os.path.join(subdir_path,'arena_hard_battles.jsonl'), lines=True, orient='records')
return arena_hard_battles
class ArenaHardSummarizer:
"""Do the subjectivity analyze based on evaluation results.
Args:
config (ConfigDict): The configuration object of the evaluation task.
It's expected to be filled out at runtime.
"""
def __init__(self,
config: ConfigDict,
judge_type='general',
check_pos_bias=True,
summary_type='single') -> None:
self.tasks = []
self.cfg = config
self.base_models = self.cfg['eval']['partitioner']['base_models']
self.compare_models = self.cfg['eval']['partitioner']['compare_models']
self.judge_models = self.cfg.get('judge_models', None)
self.meta_judge_model = self.cfg.eval.partitioner.get('meta_judge_model', None)
self.judge_type = judge_type
assert self.judge_type in ['general']
self.judge_map = {'general': post_process_compass_arena}
self.judge_function = self.judge_map[self.judge_type]
self.check_pos_bias = check_pos_bias
self.summary_type = summary_type
def get_score(self, time_str):
output_dir, results_folder = get_outdir(self.cfg, time_str)
model_combinations = list(product(self.base_models, self.compare_models))
unique_combinations = remove_duplicate_pairs([combo for combo in model_combinations if combo[0] != combo[1]])
if self.meta_judge_model is not None:
self.judge_models.append(self.meta_judge_model)
scores = {}
for idx, judge_model_cfg in enumerate(self.judge_models):
judge_model = model_abbr_from_cfg(judge_model_cfg)
for dataset in self.cfg['datasets']:
dataset_abbr = dataset_abbr_from_cfg(dataset)
for model_pair in unique_combinations:
model1 = model_pair[0]['abbr']
model2 = model_pair[1]['abbr']
if idx == len(self.judge_models):
subdir = model1 + '_' + model2 + '_summarized-by--' + judge_model
else:
subdir = model1 + '_' + model2 + '_judged-by--' + judge_model
subdir_path = os.path.join(results_folder, subdir)
if not os.path.isdir(subdir_path):
print(subdir_path + ' is not exist! please check!')
continue
battles = get_battles_from_judgment(dataset, subdir_path, self.judge_function)
bootstrap_online_elo = compute_mle_elo(battles)
np.random.seed(42)
bootstrap_elo_lu = get_bootstrap_result(battles, compute_mle_elo, 100)
bootstrap_elo_lu.to_json(os.path.join(subdir_path,'bootstrapping_results.jsonl'), lines=True, orient='records')
stats = pd.DataFrame()
stats['results'] = None
stats['results'] = stats['results'].astype('object')
for i, model in enumerate(bootstrap_online_elo.index):
assert model in bootstrap_elo_lu.columns
stats.at[i, 'model'] = model
stats.at[i, 'score'] = bootstrap_online_elo[model]
stats.at[i, 'lower'] = np.percentile(bootstrap_elo_lu[model], 2.5)
stats.at[i, 'upper'] = np.percentile(bootstrap_elo_lu[model], 97.5)
if model == 'gpt4-0314':
stats.at[i, 'avg_tokens'] = 423
else:
with open(os.path.join(output_dir.split('summary')[0], 'predictions', model, dataset_abbr+'.json'), 'r') as f:
model_preds = json.load(f)
pred_length = 0
for k, v in model_preds.items():
pred_length += len(tiktoken.encoding_for_model('gpt-3.5-turbo').encode(v['prediction']))
pred_length /= len(model_preds)
stats.at[i, 'avg_tokens'] = pred_length
stats.at[i, 'results'] = bootstrap_elo_lu[model].tolist()
stats.sort_values(by='model', inplace=True)
stats['score'] = get_win_rate_column(stats, 'score', 'gpt4-0314').tolist()
stats['lower'] = get_win_rate_column(stats, 'lower', 'gpt4-0314').tolist()
stats['upper'] = get_win_rate_column(stats, 'upper', 'gpt4-0314').tolist()
decimal = 1
stats.sort_values(by='score', ascending=False, inplace=True)
for _, row in stats.iterrows():
interval = str((round(row['lower'] - row['score'], decimal), round(row['upper'] - row['score'], decimal)))
print(f"{row['model'] : <30} | score: {round(row['score'], decimal) : ^5} | 95% CI: {interval : ^12} | average #tokens: {int(row['avg_tokens'])}")
stats.to_json(os.path.join(output_dir,'arena_hard_leaderboard.json'), orient='records', indent=4)
def summarize(
self,
time_str: str = datetime.now().strftime('%Y%m%d_%H%M%S'),
):
"""Summarize the subjectivity analysis based on evaluation results.
Args:
time_str (str): Timestamp for file naming.
Returns:
pd.DataFrame: The summary results.
"""
self.get_score(time_str)
|
import mongoose ,{Schema} from "mongoose";
import bcrypt from "bcrypt";
const userSchema = new Schema(
{
username :{
type : String,
required : true,
unique : true,
lowercase : true,
index : true,
trim : true
},
email :{
type : String,
required : true,
unique : true,
lowercase : true,
trim : true
},
fullname :{
type :String,
required : true,
index : true,
trim : true
},
avatar :{
type :String,
required : true
},
coverImage :{
type :String,
},
watchHistory :[{
type : Schema.Types.ObjectId,
ref : "Video"
}],
password :{
type :String,
required :[true , 'Password is required']
},
refreshToken :{
type:String
}
},
{
timestamps : true
}
)
userSchema.pre("save", async function (next) {
if(!this.isModified("password")) return next()
this.password = await bcrypt.hash(this.password, 10)
next()
})
userSchema.methods.isPasswordCorrect = async function (password) {
return await bcrypt.compare(password , this.password)
}
userSchema.methods.generateAccessToken = function(){
return jwt.sign(
{
_id : this._id,
email : this.email,
username : this.username,
fullname : this.fullname
},
process.env.ACCESS_TOKEN_SECRET,
{
expiresIn : process.env.ACCESS_TOKEN_EXPIRY
}
)
}
userSchema.methods.generateRefreshToken = function(){
return jwt.sign(
{
_id : this._id,
},
process.env.REFRESH_TOKEN_SECRET,
{
expiresIn : process.env.REFRESH_TOKEN_EXPIRY
}
)}
export const User = mongoose.model("User",userSchema)
|
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="SignupViewModel"
type="com.kshitizbali.presto.viewmodels.SignupViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back4"
tools:context=".view.MainActivity">
<ImageView
android:id="@+id/ivRestImage"
android:layout_width="@dimen/iv_logo_dimen"
android:layout_height="@dimen/iv_logo_dimen"
android:background="#00070707"
android:contentDescription="@string/restaurant_image"
android:src="@drawable/my_logo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.airbnb.lottie.LottieAnimationView
android:id="@+id/animation_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="@dimen/lotti_image"
android:minHeight="@dimen/lotti_image"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivRestImage"
app:layout_constraintVertical_bias="0.0"
app:lottie_autoPlay="true"
app:lottie_loop="true"
app:lottie_rawRes="@raw/food_corousal" />
<TextView
android:id="@+id/tvLoyInfoTitle"
style="@style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:background="#45070707"
android:fontFamily="cursive"
android:text="@string/thanks_for_your_loyalty_now_its_out_turn"
android:textColor="#FFFFFF"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="@+id/animation_view"
app:layout_constraintStart_toStartOf="@+id/animation_view"
app:layout_constraintTop_toBottomOf="@+id/animation_view" />
<Button
android:id="@+id/btSignUp"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"
android:drawableStart="@drawable/ic_sign_24dp"
android:drawablePadding="@dimen/drawable_padding"
android:text="@string/sign_up"
android:textAllCaps="false"
app:layout_constraintEnd_toEndOf="@+id/tvLoyInfoTitle"
app:layout_constraintStart_toStartOf="@+id/tvLoyInfoTitle"
app:layout_constraintTop_toBottomOf="@+id/tvLoyInfoTitle" />
<androidx.constraintlayout.widget.Group
android:id="@+id/groupWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:animateLayoutChanges="true"
app:constraint_referenced_ids="animation_view,tvLoyInfoTitle,btSignUp" />
<androidx.constraintlayout.widget.Group
android:id="@+id/groupSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:animateLayoutChanges="true"
app:constraint_referenced_ids="tvSignUpTitle,cvSIgnUp" />
<TextView
android:id="@+id/tvSignUpTitle"
style="@style/TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:fontFamily="cursive"
android:text="@string/sign_up_it_s_free"
android:textColor="@android:color/white"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="@+id/ivRestImage"
app:layout_constraintStart_toStartOf="@+id/ivRestImage"
app:layout_constraintTop_toBottomOf="@+id/ivRestImage" />
<androidx.cardview.widget.CardView
android:id="@+id/cvSIgnUp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="32dp"
app:cardBackgroundColor="#F3FFFFFF"
app:cardCornerRadius="@dimen/card_corner_rad"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvSignUpTitle">
<!--<include
layout="@layout/layout_signup_module"
android:background="#00F0EDED" />-->
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00F0EDED"
android:orientation="vertical">
<ImageView
android:id="@+id/ivCancelSignup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:contentDescription="@string/cancel_signup"
android:src="@drawable/ic_cancel_24dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til_first_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.06"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="@+id/atvFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="@string/digits_name_all"
android:drawableStart="@drawable/ic_person_pin_circle_yellow_24dp"
android:drawablePadding="@dimen/drawable_padding"
android:hint="@string/first_name"
android:text="@={SignupViewModel.firstName}"
android:textColor="@android:color/darker_gray" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til_last_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="@+id/til_first_name"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/til_first_name"
app:layout_constraintTop_toBottomOf="@+id/til_first_name">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="@+id/atvLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="@string/digits_name_all"
android:drawableStart="@drawable/ic_person_pin_circle_yellow_24dp"
android:drawablePadding="@dimen/drawable_padding"
android:hint="@string/last_name"
android:text="@={SignupViewModel.lastName}"
android:textColor="@android:color/darker_gray" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til_email"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="@+id/til_last_name"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/til_last_name"
app:layout_constraintTop_toBottomOf="@+id/til_last_name">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="@+id/atvEmailId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="@string/digits_email_allow"
android:drawableStart="@drawable/ic_email_24dp"
android:drawablePadding="@dimen/drawable_padding"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:text="@={SignupViewModel.email}"
android:textColor="@android:color/darker_gray" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="@+id/til_email"
app:layout_constraintStart_toStartOf="@+id/til_email"
app:layout_constraintTop_toBottomOf="@+id/til_email">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="@+id/atvPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="@string/digits_phone_allow"
android:drawableStart="@drawable/ic_smartphone_24dp"
android:drawablePadding="@dimen/drawable_padding"
android:hint="@string/phone"
android:inputType="phone"
android:text="@={SignupViewModel.phone}"
android:textColor="@android:color/darker_gray" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/btSignUpFinal"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="16dp"
android:onClick="@{(v) -> SignupViewModel.onClick(v)}"
android:text="@string/sign_up"
android:drawableStart="@drawable/ic_sign_up_24dp"
android:drawablePadding="@dimen/drawable_padding"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/til_phone"
app:layout_constraintStart_toStartOf="@+id/til_phone"
app:layout_constraintTop_toBottomOf="@+id/til_phone" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:visibility="gone"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/btSignUpFinal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
|
<%--
Document : editLesson
Created on : May 31, 2023, 5:07:15 PM
Author : Yui
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<c:set var="courseId" value="${empty param.courseId ? -1 : param.courseId}"></c:set>
<c:set var="chapterId" value="${empty param.chapterId ? -1 : param.chapterId}"></c:set>
<c:set var="lessonNumber" value="${empty param.lessonNumber ? -1 : param.lessonNumber}"></c:set>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit Lesson</title>
<%@include file="/components/headCommon.jspf" %>
</head>
<body>
<div class="course-editor-frame">
<div class="course-editor-header">
<%@include file="/components/headerEditCourse.jspf" %>
</div>
<div id="course-editor-nav" class="course-editor-nav">
<%@include file="/components/editCourseNavbar.jspf" %>
</div>
<div class="course-editor-title-bar">
<button onclick="collapseEvent(this)" data-target="course-editor-nav"><i class="fa-solid fa-bars"></i></button>
<h1 class="editor-default-title">
Edit Lesson
</h1>
</div>
<main class="course-editor-main">
<form method="post">
<input type="hidden" name="courseId" value="${courseId}"/>
<input type="hidden" name="chapterId" value="${chapterId}"/>
<input type="hidden" name="lessonNumber" value="${lessonNumber}"/>
<div class="field-list">
<label for="lesson-name">Name</label>
<input type="text" id="lesson-name" name="lessonName" value="${lesson.name}" required/>
<label for="lesson-prev">Previous Lesson</label>
<select id="lesson-prev" name="lessonPrev" required>
<option value="0">None (First lesson in this chapter)</option>
<c:forEach var="item" items="${lessons}">
<option value="${item.lessonNumber}" ${prev.lessonNumber == item.lessonNumber ? "selected" : ""}>${item.lessonNumber}: ${item.name}</option>
</c:forEach>
</select>
<label for="lesson-vid">Video URL</label>
<input type="url" id="lesson-vid" name="lessonVid" value="${lesson.video}" required/>
<label for="lesson-desc">Description</label>
<textarea height="300px" id="lesson-desc" name="lessonDesc">${lesson.description}</textarea>
<p style="color: red; grid-column: 1 / span 2;">${status}</p>
</div>
<div class="action-container">
<input type="submit" name="action" value="Delete" class="btn-del"/>
<input type="submit" name="action" value="Save" class="btn-save"/>
</div>
</form>
</main>
</div>
<style>
body {
background: #F4F6FC;
}
.course-editor-main {
padding: 2rem;
}
</style>
<script src="/assets/js/base.js"></script>
</body>
</html>
|
import pickle
import os
import nltk
from nltk.corpus import stopwords
from nltk.stem.lancaster import LancasterStemmer
from nltk import everygrams
from string import punctuation as punctuation_list
from nltk.tokenize import word_tokenize
class PredictionService:
def __init__(self):
self.load_model()
self.load_nltk()
def get_sentiment(self, input_string):
words = self.extract_features(input_string)
words = self.bag_of_words(words)
return self.model.classify(words)
def load_model(self):
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(
BASE_DIR, "..", "trained_models", "sa_classifier.pickle"
)
try:
with open(MODEL_PATH, "rb") as file:
model = pickle.load(file)
self.model = model
except FileNotFoundError:
print(f"Model file not found: {MODEL_PATH}")
return None
except Exception as e:
print(f"Error loading model: {e}")
return None
def load_nltk(self):
nltk.download("punkt")
nltk.download("stopwords")
self.stopword_list = stopwords.words("english")
self.stemmer = LancasterStemmer()
def extract_features(self, input_string):
"""Extract features from the input string for sentiment analysis."""
# Tokenize words.
words = word_tokenize(input_string)
# Second pass, remove stop words and punctuation.
features = [
self.stemmer.stem(word)
for word in words
if self.stemmer.stem(word) not in self.stopword_list
and self.stemmer.stem(word) not in punctuation_list
]
# Third pass, generate n_grams
n_grams = everygrams(features, max_len=3)
return n_grams
def bag_of_words(self, words):
"""Create a bag of words from the input words."""
bag = {}
for word in words:
bag[word] = bag.get(word, 0) + 1
return bag
|
package com.test.singleton;
/**
* lazy loading
* 懒汉式
* 虽然达到了按需初始化的目的,但却带来了线程不安全的问题
* 多个线程访问getInstance(),会导致创建的实例不是同一个
*/
public class SingleTest02 {
private static SingleTest02 INSTANCE;
private SingleTest02(){}
public static SingleTest02 getInstance(){
if(INSTANCE == null){
try {//模拟使用
Thread.sleep(1);
}catch (Exception e){
e.printStackTrace();
}
INSTANCE = new SingleTest02();
}
return INSTANCE;
}
public static void main(String[] args){
for(int i=0;i<100;i++){
new Thread(()->{
System.out.println(SingleTest02.getInstance().hashCode());
}).start();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.