text
stringlengths 184
4.48M
|
---|
package test.task.library.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import test.task.library.service.UserDetailService;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailService userDetailService;
@Bean
public TokenBasedRememberMeServices rememberMeServices() {
return new TokenBasedRememberMeServices("remember-me-key", userDetailService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new StandardPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailService)
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/favicon.ico", "/resources/**", "/WEB-INF/**", "/registration").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(authenticationFilter())
.formLogin()
.loginPage("/login")
.permitAll()
.failureUrl("/login?error=1")
.loginProcessingUrl("/authenticate")
.and()
.logout()
.logoutUrl("/logout")
.permitAll()
.logoutSuccessUrl("/")
.and()
.rememberMe()
.rememberMeServices(rememberMeServices())
.key("remember-me-key")
.and()
.csrf().disable();
}
private UsernamePasswordAuthenticationFilter authenticationFilter() throws Exception {
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setUsernameParameter("email");
filter.setPasswordParameter("password");
filter.setFilterProcessesUrl("/auth");
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
} |
import { ethers } from "ethers";
const network = "testnet";
async function walletConnectFcn() {
// ETHERS PROVIDER
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
// SWITCH TO HEDERA TEST NETWORK
console.log(`- Switching network to the Hedera ${network}...🟠`);
let chainId;
if (network === "testnet") {
chainId = "0x128";
} else if (network === "previewnet") {
chainId = "0x129";
} else {
chainId = "0x127";
}
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [
{
chainName: `Hedera ${network}`,
chainId: chainId,
nativeCurrency: { name: "HBAR", symbol: "ℏℏ", decimals: 18 },
rpcUrls: [`https://${network}.hashio.io/api`],
blockExplorerUrls: [`https://hashscan.io/${network}/`],
},
],
});
console.log("- Switched ✅");
// CONNECT TO ACCOUNT
console.log("- Connecting wallet...🟠");
let selectedAccount;
await provider
.send("eth_requestAccounts", [])
.then((accounts) => {
selectedAccount = accounts[0];
console.log(`- Selected account: ${selectedAccount} ✅`);
})
.catch((connectError) => {
console.log(`- ${connectError.message.toString()}`);
return;
});
return [selectedAccount, provider, network];
}
export default walletConnectFcn; |
/**
* EasyBeeGo
* @author: Tinymeng <666@majiameng.com>
*/
package controllers
import (
"easybeego/app/constant"
"easybeego/app/dto"
"easybeego/app/models"
"easybeego/app/services"
"easybeego/utils"
"easybeego/utils/common"
"github.com/gookit/validate"
)
var Dept = new(DeptController)
type DeptController struct {
BaseController
}
func (ctl *DeptController) Index() {
ctl.Layout = "public/layout.html"
ctl.TplName = "dept/index.html"
}
func (ctl *DeptController) List() {
// 参数对象
var req dto.DeptPageReq
// 参数绑定
if err := ctl.ParseForm(&req); err != nil {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 调用获取列表函数
list, err := services.Dept.GetList(req)
if err != nil {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 返回结果集
ctl.JSON(common.JsonResult{
Code: 0,
Data: list,
Msg: "查询成功",
})
}
func (ctl *DeptController) Edit() {
id, _ := ctl.GetInt("id", 0)
if id > 0 {
// 编辑
info := &models.Dept{Id: id}
err := info.Get()
if err != nil {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 渲染模板
ctl.Data["info"] = info
}
// 渲染模板
ctl.Data["typeList"] = constant.DEPT_TYPE_LIST
ctl.Layout = "public/form.html"
ctl.TplName = "dept/edit.html"
}
func (ctl *DeptController) Add() {
// 参数对象
var req dto.DeptAddReq
// 参数绑定
if err := ctl.ParseForm(&req); err != nil {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 参数校验
v := validate.Struct(req)
if !v.Validate() {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: v.Errors.One(),
})
}
// 调用添加方法
rows, err := services.Dept.Add(req, utils.Uid(ctl.Ctx))
if err != nil || rows == 0 {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 添加成功
ctl.JSON(common.JsonResult{
Code: 0,
Msg: "添加成功",
})
}
func (ctl *DeptController) Update() {
// 参数对象
var req dto.DeptUpdateReq
// 参数绑定
if err := ctl.ParseForm(&req); err != nil {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 参数校验
v := validate.Struct(req)
if !v.Validate() {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: v.Errors.One(),
})
}
// 调用更新方法
rows, err := services.Dept.Update(req, utils.Uid(ctl.Ctx))
if err != nil || rows == 0 {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 更新成功
ctl.JSON(common.JsonResult{
Code: 0,
Msg: "更新成功",
})
}
func (ctl *DeptController) Delete() {
ids := ctl.GetString("id")
if ids == "" {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: "记录ID不能为空",
})
}
// 调用删除方法
rows, err := services.Dept.Delete(ids)
if err != nil || rows == 0 {
ctl.JSON(common.JsonResult{
Code: -1,
Msg: err.Error(),
})
}
// 删除成功
ctl.JSON(common.JsonResult{
Code: 0,
Msg: "删除成功",
})
} |
import "../../firebase.config.admin";
import slugify from "slugify";
import admin from "firebase-admin";
// Assuming admin is already initialized elsewhere if this file isn't the first entry
export const storage = admin.storage();
/**
* Deletes a file from the specified bucket
* @param bucketName The name of the bucket to delete the file from
* @param url The URL of the file to delete
*/
export const deleteFile = async (
bucketName: string,
url?: string,
): Promise<void> => {
const bucket = storage.bucket();
const parsedUrl = new URL(url ?? "");
let fileName = parsedUrl.pathname.substring(1).split("/").pop();
if (fileName) {
const fileRef = bucket.file(`${bucketName}/${fileName}`);
await fileRef.delete();
}
};
/**
* Uploads a file to the specified bucket
* @param file The file to upload
* @param bucketName The name of the bucket to upload the file to
* @returns The URL of the uploaded file
*/
export const uploadFile = async (
file: File,
bucketName: string,
): Promise<string> => {
return new Promise(async (resolve, reject) => {
// file to blob
const blob = new Blob([file], { type: file.type });
// blob to Buffer object
const buffer = Buffer.from(await blob.arrayBuffer());
const fileName = slugify(file.name, { lower: true });
const bucket = storage.bucket();
// Create a file reference
const fileRef = bucket.file(`${bucketName}/${fileName}`);
// Upload the file
try {
await fileRef.save(buffer); // Assuming 'file' is a Buffer
// After upload, generate a signed URL for public access (if the file should be publicly accessible)
const signedUrls = await fileRef.getSignedUrl({
action: "read",
expires: "03-09-2491", // Use an appropriate expiry date
});
resolve(signedUrls[0]); // Resolve with the URL
} catch (err) {
reject(err);
}
});
};
/**
* Downloads a file from the specified bucket
* @param bucketName The name of the bucket to download the file from
* @param url The URL of the file to download
* @returns The file as a Buffer
*/
export const downloadFile = async (
bucketName: string,
url: string,
): Promise<Buffer> => {
return new Promise(async (resolve, reject) => {
const parsedUrl = new URL(url);
const fileName = parsedUrl.pathname.substring(1).split("/").pop();
const bucket = storage.bucket();
const fileRef = bucket.file(`${bucketName}/${fileName}`);
try {
const [file] = await fileRef.download();
resolve(file);
} catch (err) {
reject(err);
}
});
};
/**
* Update a file in the specified bucket
* @param file The file to update
* @param bucketName The name of the bucket to update the file in
* @param url The URL of the file to update
* @returns The URL of the updated file
*/
export const updateFile = async (
file: File,
bucketName: string,
url: string,
): Promise<string> => {
return new Promise(async (resolve, reject) => {
const parsedUrl = new URL(url);
const fileName = parsedUrl.pathname.substring(1).split("/").pop();
const bucket = storage.bucket();
const fileRef = bucket.file(`${bucketName}/${fileName}`);
// file to blob
const blob = new Blob([file], { type: file.type });
// blob to Buffer object
const buffer = Buffer.from(await blob.arrayBuffer());
try {
await fileRef.save(buffer);
const signedUrls = await fileRef.getSignedUrl({
action: "read",
expires: "03-09-2491", // Use an appropriate expiry date
});
resolve(signedUrls[0]);
} catch (err) {
reject(err);
}
});
}; |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef mozilla_dom_RefMessageBodyService_h
#define mozilla_dom_RefMessageBodyService_h
#include <cstdint>
#include "js/TypeDecls.h"
#include "mozilla/Maybe.h"
#include "mozilla/Mutex.h"
#include "mozilla/StaticMutex.h"
#include "mozilla/UniquePtr.h"
#include "nsHashKeys.h"
#include "nsID.h"
#include "nsISupports.h"
#include "nsRefPtrHashtable.h"
namespace JS {
class CloneDataPolicy;
} // namespace JS
namespace mozilla {
class ErrorResult;
template <class T>
class OwningNonNull;
namespace dom {
class MessagePort;
template <typename T>
class Sequence;
namespace ipc {
class StructuredCloneData;
}
/**
* At the time a BroadcastChannel or MessagePort sends messages, we don't know
* which process is going to receive it. Because of this, we need to check if
* the message is able to cross the process boundary.
* If the message contains objects such as SharedArrayBuffers, WASM modules or
* ImageBitmaps, it can be delivered on the current process only.
* Instead of sending the whole message via IPC, we send a unique ID, while the
* message is kept alive by RefMessageBodyService, on the current process using
* a ref-counted RefMessageBody object.
* When the receiver obtains the message ID, it checks if the local
* RefMessageBodyService knows that ID. If yes, the sender and the receiver are
* on the same process and the delivery can be completed; if not, a
* messageerror event has to be dispatched instead.
*
* For MessagePort communication is 1-to-1 and because of this, the
* receiver takes ownership of the message (RefMessageBodyService::Steal()).
* If the receiver port is on a different process, RefMessageBodyService will
* return a nullptr and a messageerror event will be dispatched.
* For BroadcastChannel, the life-time of a message is a bit different than for
* MessagePort. It has a 1-to-many communication and we could have multiple
* receivers. Each one needs to deliver the message without taking full
* ownership of it.
* In order to support this feature, BroadcastChannel needs to call
* RefMessageBodyService::SetMaxCount() to inform how many ports are allowed to
* retrieve the current message, on the current process. Receivers on other
* processes are not kept in consideration because they will not be able to
* retrieve the message from RefMessageBodyService. When the last allowed
* port has called RefMessageBodyService::GetAndCount(), the message is
* released.
*/
class RefMessageBody final {
friend class RefMessageBodyService;
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(RefMessageBody)
RefMessageBody(const nsID& aPortID,
UniquePtr<ipc::StructuredCloneData>&& aCloneData);
const nsID& PortID() const { return mPortID; }
void Read(JSContext* aCx, JS::MutableHandle<JS::Value> aValue,
const JS::CloneDataPolicy& aCloneDataPolicy, ErrorResult& aRv);
// This method can be called only if the RefMessageBody is not supposed to be
// ref-counted (see mMaxCount).
bool TakeTransferredPortsAsSequence(
Sequence<OwningNonNull<mozilla::dom::MessagePort>>& aPorts);
private:
~RefMessageBody();
const nsID mPortID;
// In case the RefMessageBody is shared and refcounted (see mCount/mMaxCount),
// we must enforce that the reading does not happen simultaneously on
// different threads.
Mutex mMutex MOZ_UNANNOTATED;
UniquePtr<ipc::StructuredCloneData> mCloneData;
// When mCount reaches mMaxCount, this object is released by the service.
Maybe<uint32_t> mMaxCount;
uint32_t mCount;
};
class RefMessageBodyService final {
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(RefMessageBodyService)
static already_AddRefed<RefMessageBodyService> GetOrCreate();
void ForgetPort(const nsID& aPortID);
const nsID Register(already_AddRefed<RefMessageBody> aBody, ErrorResult& aRv);
already_AddRefed<RefMessageBody> Steal(const nsID& aID);
already_AddRefed<RefMessageBody> GetAndCount(const nsID& aID);
void SetMaxCount(const nsID& aID, uint32_t aMaxCount);
private:
explicit RefMessageBodyService(const StaticMutexAutoLock& aProofOfLock);
~RefMessageBodyService();
static RefMessageBodyService* GetOrCreateInternal(
const StaticMutexAutoLock& aProofOfLock);
nsRefPtrHashtable<nsIDHashKey, RefMessageBody> mMessages;
};
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_RefMessageBodyService_h |
package store
import (
"errors"
"golang.org/x/crypto/bcrypt"
)
// HashPassword will take a string and return a string copy of a bcrypt
// hashed password.
func HashPassword(plaintextPassword string) (string, error) {
hashedPassword, err := bcrypt.GenerateFromPassword(
[]byte(plaintextPassword),
bcrypt.DefaultCost,
)
if err != nil {
return "", err
}
return string(hashedPassword), nil
}
// Matches will return true if the provided plaintextPassword matches the
// hashedPassword.
func Matches(plaintextPassword, hashedPassword string) (bool, error) {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(plaintextPassword))
if err != nil {
switch {
case errors.Is(err, bcrypt.ErrMismatchedHashAndPassword):
return false, nil
default:
return false, err
}
}
return true, nil
} |
<template>
<v-list class="pa-0">
<v-subheader class="d-flex justify-space-between">
<div class="overline">Menu</div>
<Version />
</v-subheader>
<v-divider></v-divider>
<template v-for="(item, key) in items">
<v-list-group
v-if="hasChild(item)"
:key="key"
no-action
:to="item.path"
:value="computeGroupExpanded(item, $route)"
>
<template #prependIcon>
<v-tooltip bottom>
<template #activator="{ on, attrs }">
<NavIcon v-bind="attrs" v-on="on" :icon="item.icon" />
</template>
<span v-text="item.title" />
</v-tooltip>
</template>
<template #activator>
<v-list-item-content>
<v-list-item-title v-text="item.title" />
</v-list-item-content>
</template>
<nav-list-item v-for="child in item.children" v-show="!mini" :key="'c' + child.path" :item="child" />
</v-list-group>
<v-divider v-else-if="item.divider" :key="'ss' + key"></v-divider>
<nav-list-item v-else :key="'nav' + key" :item="item" />
</template>
</v-list>
</template>
<script>
import Version from '@/components/nav/Version';
import NavIcon from '@/components/nav/NavIcon';
import NavListItem from '@/components/nav/NavListItem';
export default {
components: {
Version,
NavIcon,
NavListItem
},
props: {
mini: Boolean,
items: {
type: Array,
default: () => []
}
},
methods: {
hasChild(item) {
return Array.isArray(item.children) && item.children.length > 0;
},
computeGroupExpanded(item, $route) {
return $route.matched.map(item => item.path).includes(item.path);
}
}
};
</script> |
import {inject, injectable} from 'inversify';
import {DocumentType, types} from '@typegoose/typegoose';
import {OfferServiceInterface} from './offer-service.interface.js';
import {Component} from '../../types/component.types.js';
import {LoggerInterface} from '../../common/logger/logger.interface.js';
import {OfferEntity} from './offer.entity.js';
import CreateOfferDto from './dto/create-offer.dto.js';
import UpdateOfferDto from './dto/update-offer.dto.js';
import {SortType} from '../../types/sort-type.enum.js';
import {DEFAULT_OFFER_COUNT} from './offer.constant.js';
@injectable()
export default class OfferService implements OfferServiceInterface {
constructor(
@inject(Component.LoggerInterface) private readonly logger: LoggerInterface,
@inject(Component.OfferModel) private readonly offerModel: types.ModelType<OfferEntity>
) {}
public async create(dto: CreateOfferDto): Promise<DocumentType<OfferEntity>> {
const result = await this.offerModel.create(dto);
this.logger.info(`New offer created: ${dto.name}`);
return result;
}
public async findByOfferId(offerId: string): Promise<DocumentType<OfferEntity> | null> {
return this.offerModel
.findById(offerId)
.populate(['userId'])
.exec();
}
public async find(): Promise<DocumentType<OfferEntity>[]> {
return this.offerModel
.aggregate([
{
$lookup: {
from: 'comments',
let: {offerId: '$_id'},
pipeline: [
{$match: {$expr: {$eq: ['$offerId', '$$offerId']}}},
{$project: {_id: 1}}
],
as: 'comments'
},
},
{
$addFields:
{id: {$toString: '$_id'}, commentsCount: {$size: '$comments'}}
},
{$unset: 'comments'},
{$limit: DEFAULT_OFFER_COUNT},
{$sort: {offerCount: SortType.Down}}
]).exec();
}
public async deleteById(offerId: string): Promise<DocumentType<OfferEntity> | null> {
return this.offerModel
.findByIdAndDelete(offerId)
.exec();
}
public async updateById(offerId: string, dto: UpdateOfferDto): Promise<DocumentType<OfferEntity> | null> {
return this.offerModel
.findByIdAndUpdate(offerId, dto, {new: true})
.populate(['userId'])
.exec();
}
public async exists(documentId: string): Promise<boolean> {
return (await this.offerModel
.exists({_id: documentId})) !== null;
}
public async incCommentCount(offerId: string): Promise<DocumentType<OfferEntity> | null> {
return this.offerModel
.findByIdAndUpdate(offerId, {
'$inc': {
commentCount: 1,
}
}).exec();
}
public async findNew(count: number): Promise<DocumentType<OfferEntity>[]> {
return this.offerModel
.find()
.sort({createdAt: SortType.Down})
.limit(count)
.populate(['userId'])
.exec();
}
public async findDiscussed(count: number): Promise<DocumentType<OfferEntity>[]> {
return this.offerModel
.find()
.sort({commentCount: SortType.Down})
.limit(count)
.populate(['userId'])
.exec();
}
public async findPremiums(): Promise<DocumentType<OfferEntity>[]> {
return this.offerModel
.find({isPremium: true})
.sort({createdAt: SortType.Down})
.populate(['userId'])
.exec();
}
public async calcRating(offerId: string, newRating: number): Promise<DocumentType<OfferEntity> | null> {
const oldOffer = await this.offerModel.findById(offerId).lean();
const oldRating = oldOffer?.rating;
return this.offerModel
.findByIdAndUpdate(offerId, {
'$set': {
rating: oldRating ? ((oldRating + newRating) / 2).toFixed(1) : newRating,
}
}).exec();
}
} |
#include "lists.h"
/**
* delete_dnodeint_at_index - deletes the node at index
* @head: double pointer
* @index: index of the node that should be deleted
* Return: 1 or -1
*/
int delete_dnodeint_at_index(dlistint_t **head, unsigned int index)
{
dlistint_t *current;
unsigned int i;
if (head == NULL || *head == NULL)
{
return (-1);
}
current = *head;
if (index == 0)
{
*head = current->next;
if (current->next != NULL)
{
current->next->prev = NULL;
}
free(current);
return (1);
}
for (i = 0; i < index; i++)
{
if (current == NULL)
{
return (-1);
}
current = current->next;
}
if (current == NULL)
{
return (-1);
}
current->prev->next = current->next;
if (current->next != NULL)
{
current->next->prev = current->prev;
}
free(current);
return (1);
} |
from django.contrib.auth import authenticate, login, logout
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import CustomUserSerializer, RegisterUserSerializer
from rest_framework import generics
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
class RegisterApiView(generics.CreateAPIView):
serializer_class = RegisterUserSerializer
class LoginView(APIView):
def post(self, request):
# Recuperamos las credenciales y autenticamos al usuario
email = request.data.get('email', None)
password = request.data.get('password', None)
user = authenticate(email=email, password=password)
# Si es correcto añadimos a la request la información de sesión
if user:
login(request, user)
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=status.HTTP_200_OK)
else:
return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
class LogoutView(APIView):
authentication_classes = [TokenAuthentication]
def post(self, request):
user = request.user
Token.objects.filter(user=user).delete()
logout(request)
return Response({'message': 'Successfully logged out'}, status=status.HTTP_200_OK)
class ProfileView(generics.RetrieveUpdateAPIView):
serializer_class = CustomUserSerializer
http_method_names = ['get', 'patch', 'options']
authentication_classes = [TokenAuthentication]
def get_object(self):
if self.request.user.is_authenticated:
return self.request.user |
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';
import Button from './Button';
const AlbumDetail = ({ album }) => {
const { title, artist, thumbnail_image, image, url } = album;
return (
<Card>
<CardSection>
<View style={styles.thumbnailContainerStyle}>
<Image
style={styles.thumbnailStyle}
source={{ uri: thumbnail_image }}
/>
</View>
<View style={styles.headerContentStyle}>
<Text style={styles.headerTextStyle}>{title}</Text>
<Text>{artist}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={styles.imageStyle}
source={{ uri: image }}
/>
</CardSection>
<CardSection>
<Button onPress={() => Linking.openURL(url)}>
Buy Now
</Button>
</CardSection>
</Card>
);
};
const styles = {
// for the header
headerContentStyle: {
flexDerection: 'column',
justifyContent: 'space-around'
},
headerTextStyle: {
fontSize: 18
},
// for the image
thumbnailStyle: {
height: 50,
width: 50
},
// for the image view
thumbnailContainerStyle: {
justifyContent: 'center',
alignItems: 'center',
marginLeft: 10,
marginRight: 10
},
// image in second CardSection
imageStyle: {
height: 300,
flex: 1,
width: null
}
}
export default AlbumDetail; |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { CoreSetup, Plugin } from '@kbn/core/public';
import { VisualizationsSetup } from '@kbn/visualizations-plugin/public';
import { Plugin as ExpressionsPlugin } from '@kbn/expressions-plugin/public';
import { SelfChangingEditor } from './self_changing_vis/self_changing_editor';
import { selfChangingVisFn, SelfChangingVisParams } from './self_changing_vis_fn';
import { selfChangingVisRenderer } from './self_changing_vis_renderer';
import { toExpressionAst } from './to_ast';
export interface SetupDependencies {
expressions: ReturnType<ExpressionsPlugin['setup']>;
visualizations: VisualizationsSetup;
}
export class CustomVisualizationsPublicPlugin
implements Plugin<CustomVisualizationsSetup, CustomVisualizationsStart>
{
public setup(core: CoreSetup, { expressions, visualizations }: SetupDependencies) {
/**
* Register an expression function with type "render" for your visualization
*/
expressions.registerFunction(selfChangingVisFn);
/**
* Register a renderer for your visualization
*/
expressions.registerRenderer(selfChangingVisRenderer);
/**
* Create the visualization type with definition
*/
visualizations.createBaseVisualization<SelfChangingVisParams>({
name: 'self_changing_vis',
title: 'Self Changing Vis',
icon: 'controlsHorizontal',
description:
'This visualization is able to change its own settings, that you could also set in the editor.',
visConfig: {
defaults: {
counter: 0,
},
},
editorConfig: {
optionTabs: [
{
name: 'options',
title: 'Options',
editor: SelfChangingEditor,
},
],
},
toExpressionAst,
});
}
public start() {}
public stop() {}
}
export type CustomVisualizationsSetup = ReturnType<CustomVisualizationsPublicPlugin['setup']>;
export type CustomVisualizationsStart = ReturnType<CustomVisualizationsPublicPlugin['start']>; |
<?php
namespace B0bm0rane\PhpLibrary\Db;
use Exception;
use PDO;
/**
* Connexion à la base de données (SINGLETON)
*/
class DbConnect
{
private static array $config;
/**
* Constructeur privé (la classe n'est pas instanciable)
*/
private function __construct() {}
/** @var PDO $instance l'instance PDO unique */
private static ?PDO $instance = null;
/**
* Récupère l'instance unique de PDO
* La crée si elle n'existe pas encore
* @return PDO l'instance de PDO
*/
public static function getInstance(): PDO
{
if(self::$instance === null) {
self::$instance = new PDO('mysql:host='.self::$config['db_host'].';port='.self::$config['db_port'].';dbname='.self::$config['db_name'].';charset=utf8', self::$config['db_user'], self::$config['db_password'], [
// self::$instance = new PDO('mysql:host=localhost;port=3306;dbname=db_cars;charset=utf8', 'root', '', [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
}
return self::$instance;
}
public static function setConfiguration(string $chemin_vers_le_fichier) : void
{
if(is_file($chemin_vers_le_fichier)){
self::$config = require $chemin_vers_le_fichier;
var_export(self::$config);
}
else{
throw new Exception("Erreur");
}
}
} |
"use client";
import { FC, useState } from "react";
import Button from "./Button";
import { addFriendValidator } from "@/lib/validations/add-friend";
import axios, { AxiosError } from "axios";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
interface AddFriendButtonProps {}
type FormData = z.infer<typeof addFriendValidator>;
const AddFriendButton: FC<AddFriendButtonProps> = ({}) => {
const [showSuccessState, setShowSuccessState] = useState<boolean>(false);
const { register, handleSubmit, setError, formState:{errors} } = useForm<FormData>({
resolver: zodResolver(addFriendValidator),
});
const addFriend = async (email: string) => {
try {
const validateEmail = addFriendValidator.parse({ email });
await axios.post("/api/friends/add", {
email: validateEmail,
});
setShowSuccessState(true);
} catch (error) {
if (error instanceof z.ZodError) {
setError('email', {
message: error.message
})
return;
}
if (error instanceof AxiosError) {
setError('email', {
message: error.response?.data
})
return;
}
setError('email', {message:"Something went wrong!"})
}
};
const onSubmit = (data: FormData) =>{
addFriend(data.email)
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="max-w-sm">
<label
htmlFor="email"
className="block text-sm font-medium leading-6 text-blue-950"
>
Add friend by Email
</label>
<div className="mt-2 flex gap-4">
<input
type="text"
className="block w-full rounded-md border-0 py-1.5 text-blue-900 shadow-sm ring-1 ring-inset ring-gray-400 placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-indigo-700 sm:text-sm sm:leading-6"
placeholder="you@exemple.com"
{...register("email")}
/>
<Button>Add</Button>
</div>
<p className="mt-1 text-red-700 ">
{errors.email?.message}
</p>
{showSuccessState ? (
<p className="mt-1 text-green-600">Friend request send</p>
) : null}
</form>
);
};
export default AddFriendButton; |
//
// ChatsView.swift
// ChatGPTClient
//
// Created by Artem Shishkin on 22.03.2023.
//
import SwiftUI
import Combine
struct ChatView: View {
@State private var messageText = ""
@State private var saveConversationAlert = false
@State private var conversationName = ""
@State private var settingPageSheet = false
@State private var keyboardHeight: CGFloat = 0
@ObservedObject var viewModel: ChatViewModel
init(viewModel: ChatViewModel) {
self.viewModel = viewModel
}
var body: some View {
VStack {
messageScrollView
CustomInputView(text: $messageText, viewModel: viewModel.customInputViewModel, action:
sendMessage)
}
.padding(.bottom)
.scrollDismissesKeyboard(.interactively)
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button(action: {
settingPageSheet = true
}, label: {
Image(systemName: "gear")
})
}
if viewModel.mode == .newOne {
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button(action: {
viewModel.resetConversation()
}, label: {
Image(systemName: "arrow.counterclockwise")
})
}
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button(action: {
self.saveConversationAlert = true
}, label: {
Image(systemName: "folder.fill.badge.plus")
})
}
}
}
.alert(Constants.Chat.alertTitle, isPresented: $saveConversationAlert, actions: ({
TextField(Constants.Chat.alerPlaceHolderTitle, text: $conversationName)
Button(Constants.saveText, action: saveConversation)
Button(Constants.cancelText, role: .cancel) { }
}), message: ({
Text(Constants.Chat.alertMessageText)
}))
.sheet(isPresented: $settingPageSheet, onDismiss: updateViewModel, content: {
ChatSettingSheet()
.presentationDetents([.height(300)])
.cornerRadius(10)
})
.onReceive(Publishers.keyboardHeight) { self.keyboardHeight = $0 }
}
private var messageScrollView: some View {
ScrollViewReader { reader in
ScrollView(.vertical) {
ZStack {
Color(.systemBackground)
LazyVStack(alignment: .leading, spacing: 12) {
ForEach(viewModel.messages) { message in
MessageView(viewModel: MessageViewModel(message))
}
}
}
}
.onChange(of: keyboardHeight) { id in
guard let id = viewModel.messages.last?.id else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
withAnimation() {
reader.scrollTo(id, anchor: .bottom)
}
}
}
.onChange(of: viewModel.messages.count) { id in
guard let id = viewModel.messages.last?.id else { return }
withAnimation() {
reader.scrollTo(id)
}
}
}
.onTapGesture {
self.hideKeyboard()
}
}
private func sendMessage() {
viewModel.sendMessage(messageText)
messageText = ""
}
private func saveConversation() {
viewModel.saveConversation(with: conversationName)
}
private func updateViewModel() {
viewModel.updateSettings()
}
} |
import json
import os
input_path = "./data/ACE05-E/sentence-level_test.json"
output_path = "./data/ACE05-E/ED_E_gold.json"
with open(input_path, 'r') as f:
lines = f.readlines()
EVENT_ID = 0
with open(output_path, 'w') as f:
for line in lines:
line = json.loads(line)
doc_id = line['doc_id']
sent_id = line['sent_id']
events = line['events']
words = line['words']
res = {
'id': f'{doc_id}-{sent_id}',
'words': words,
'events': events,
}
f.write(json.dumps(res)+'\n')
# Generating Prompts for Open Setting
open_input_path = output_path
open_prompt_path = './Prompt/ED_E_Open.json'
with open(open_input_path, 'r') as f:
lines = f.readlines()
output={}
for line in lines:
line = json.loads(line)
prompt = "Event Detection (ED) task definition:\n\
Given an input list of words, identify triggers in the list and categorize their event types. \
An event is something that happens. An event is a specific occurrence involving participants, \
and it can frequently be described as a change of state. A trigger is the main word that most \
clearly expresses the occurrence of an event.\n\n\
The output of ED task should be a list of dictionaries following json format. \
Each dictionary corresponds to a trigger and should consists of \"trigger\", \"word_index\", \
\"event_type\", \"confidence\", \"if_context_dependent\", \"reason\" and \"if_reasonable\" seven \
keys. The value of \"word_index\" key is an integer indicating the index (start from zero) of the \
\"trigger\" in the input list. The value of \"confidence\" key is an integer ranging from 0 to 100, \
indicating how confident you are that the \"trigger\" expresses the \"event_type\" event. The value \
of \"if_context_dependent\" key is either 0 (indicating the event semantic is primarily expressed \
by the trigger rather than contexts) or 1 (indicating the event semantic is primarily expressed by \
contexts rather than the trigger). The value of \"reason\" key is a string describing the reason \
why the \"trigger\" expresses the \"event_type\" event, and do not use any \" mark in this string. \
The value of \"if_reasonable\" key is either 0 (indicating the reason given in the \"reason\" field \
is not reasonable) or 1 (indicating the reason given in the \"reason\" field is reasonable). \
Note that your answer should only contain the json string and nothing else.\n\n\
Perform ED task for the following input list, and print the output:\n"
prompt += str(line['words'])
output[line['id']] = prompt
with open(open_prompt_path, 'w') as f:
json.dump(output, f, indent=4)
# Generating Prompts for Standard Setting
closed_input_path = output_path
closed_prompt_path = './Prompt/ED_E_Closed.json'
with open(closed_input_path, 'r') as f:
lines = f.readlines()
output={}
for line in lines:
line = json.loads(line)
prompt = "Event Detection (ED) task definition:\n\
Given an input list of words, identify all triggers in the list, and categorize each of \
them into the predefined set of event types. A trigger is the main word that most clearly \
expresses the occurrence of an event in the predefined set of event types.\n\n\
The predefined set of event types includes: [Life.Be-Born, Life.Marry, Life.Divorce, Life.Injure, \
Life.Die, Movement.Transport, Transaction.Transfer-Ownership, Transaction.Transfer-Money, \
Business.Start-Org, Business.Merge-Org, Business.Declare-Bankruptcy, Business.End-Org, \
Conflict.Attack, Conflict.Demonstrate, Contact.Meet, Contact.Phone-Write, Personnel.Start-Position\
, Personnel.End-Position, Personnel.Nominate, Personnel.Elect, Justice.Arrest-Jail, \
Justice.Release-Parole, Justice.Trial-Hearing, Justice.Charge-Indict, Justice.Sue, Justice.Convict\
, Justice.Sentence, Justice.Fine, Justice.Execute, Justice.Extradite, Justice.Acquit, \
Justice.Appeal, Justice.Pardon].\n\n\
The output of ED task should be a list of dictionaries following json format. \
Each dictionary corresponds to the occurrence of an event in the input list and should consists \
of \"trigger\", \"word_index\", \"event_type\", \"top3_event_type\", \"top5_event_type\", \
\"confidence\", \"if_context_dependent\", \"reason\" and \"if_reasonable\" nine keys. The value \
of \"word_index\" key is an integer indicating the index (start from zero) of the \"trigger\" in \
the input list. The value of \"confidence\" key is an integer ranging from 0 to 100, indicating \
how confident you are that the \"trigger\" expresses the \"event_type\" event. The value of \
\"if_context_dependent\" key is either 0 (indicating the event semantic is primarily expressed by \
the trigger rather than contexts) or 1 (indicating the event semantic is primarily expressed by \
contexts rather than the trigger). The value of \"reason\" key is a string describing the reason \
why the \"trigger\" expresses the \"event_type\", and do not use any \" mark in this string. The \
value of \"if_reasonable\" key is either 0 (indicating the reason given in the \"reason\" field is \
not reasonable) or 1 (indicating the reason given in the \"reason\" field is reasonable). \
Note that your answer should only contain the json string and nothing else.\n\n\
Perform ED task for the following input list, and print the output:\n"
prompt += str(line['words'])
output[line['id']] = prompt
with open(closed_prompt_path, 'w') as f:
json.dump(output, f, indent=4) |
package libs::QRHandler;
#
##
##########################################################################
# #
# Google Authenticator Automater #
# #
# Copyright (C) 2012 by Vamegh Hedayati #
# vamegh <AT> gmail.com #
# #
# Please see Copying for License Information #
# GNU/GPL v2 2010 #
##########################################################################
##
#
#################################################
# Integrity Checks
##
use strict;
use warnings;
#################################################
# External Modules
##
use GD::Barcode::QRcode;
use File::Path;
use File::Copy;
#################################################
# My Modules
##
##
use libs::LogHandle;
use libs::CMDHandle;
use libs::UserDetails;
#################################################
# Exporting variables out of module
##
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(&qrgen &qrimg_write $qrident $qrkey $qrcode_png);
use vars qw($qrident $qrkey $qrcode_png);
#################################################
# Variables Exported From Module - Definitions
##
$qrident='';
$qrkey='';
$qrcode_png='';
#################################################
# Local Internal Variables for this script
##
my $myname=":: module QRHandler";
sub qrgen {
my $subname="qrgen";
my $caller=$myname." :: ".$subname;
if ("@_" ne '') {
$qrident=shift(@_);
} if ("@_" ne '') {
$qrkey=shift(@_);
}
binmode(STDOUT);
$qrcode_png = GD::Barcode::QRcode->new("otpauth://totp/$qrident?secret=$qrkey",{ Ecc=> 'Q',Version=>9, ModuleSize => 5 })->plot->png;
&log_it("QR CODE PNG :: \n $qrcode_png \n","debug","3","$caller");
}
sub qrimg_write {
## This sub should not be called read as it writes the QRCODE pngs to file from the DB.
## but it does it by reading the db, terrible name still.
my $subname="sub qrimg_write";
my $caller=$myname." :: ".$subname;
my $qrimg_pwd='';
my $qrimg_file='';
### goog store is created by either the config file
### or via command line -G option, we only need to call it here,
### its actually exported from CMDHandle.
## auth_name is created and exported by UserDetails.pm
if ($auth_name eq 'root' or $sys_user eq 'root') {
$qrimg_pwd="$goog_store/users/$auth_name";
$qrimg_file="$qrimg_pwd/$auth_name.png";
} else {
$qrimg_pwd="$auth_dir/.gauth";
$qrimg_file="$qrimg_pwd/$auth_name.png";
}
&log_it("Creating directory $qrimg_pwd ".
"if it doesnt exist",
"debug","3", "$caller");
if ( ! -e "$qrimg_pwd") {
eval { mkpath("$qrimg_pwd" ,1, 0700) }
or &log_it("Unable to make path :: ".
"$qrimg_pwd :: $!",
"error","2","$caller");
}
if (!$goog_store or !$auth_dir) {
## The config location has not been specified or the user has no home path specified
&log_it("Not going to create image in :: $qrimg_pwd ".
"either the path :: $goog_store is empty ".
"or the users home path :: $auth_dir",
"debug","1", "$caller");
} else {
open IMAGE, ">$qrimg_file"
or &log_it("Error :: $!","error","1","$caller");
print IMAGE $qrcode_png;
close(IMAGE);
my $mode=0700; chmod $mode, "$qrimg_file"
or &log_it("Unable to change mode of file :: ".
"$qrimg_file :: $!",
"error","2","$caller");
}
}
END { } # Global Destructor
1;
#################################################
#
################################### EO PROGRAM #######################################################
#
################################ MODULE HELP / DOCUMENTATION SECTION #################################
##
# To access documentation please use perldoc AuthHandler.pm, This will provide
# the formatted help file for this specific module
##
#################################################
#
__END__
=head1 NAME
QRHandler.pm - Google Authenticator Automater : Gauth-run
=head1 SYNOPSIS
QRCode Generator, generates PNG images of the TOTP QRCode.
=head1 DESCRIPTION
This Module generates the QR Code for the TOTP generated by the google-authenticator program. It grabs the information gathered about the user and created by the google-authenticator program and calls GD::Barcode::QRcode to generate the qrcode for that users specific secret key. It outputs the resultant qrcode as a png image which is stored to later be processed by either DBCON or by the qrimg_write sub.
The data generated is stored in :
* $qrcode_png -- This is the actual QRCODE as a png image
The main function is qrgen and it requires the following input:
* $qrident -- This is the user identifier for the google-authenticator mobile app.
* $qrkey -- This is the users secret key.
the qrccode_png is then either handled by DBCON, which sends / stores the data to a db or by qrimg_write
which writes the image file directly to a png image file on disk, depending on if gauth has been called by root
or by another user, if user is not root the image is stored in the users home directory otherwise it is created
in the goog_store directory which is set in the configuration file.
=head1 AUTHOR
=over
=item Vamegh Hedayati <vamegh AT gmail DOT com>
=back
=head1 LICENSE
Copyright (C) 2012 Vamegh Hedayati <vamegh AT gmail DOT com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
Please refer to the COPYING file which is distributed with Automaton
for the full terms and conditions
=cut
#
#################################################
#
######################################### EOF ####################################################### |
import React from "react";
import "./rightbar.css";
import { Users } from "../../dummyData";
import Online from "../online/Online";
export default function Rightbar({profile}) {
const HomeRightbar=()=>{
return(
<>
<div className="birthdayContainer">
<img className="birthdayImg" src="/tools/gift.jpeg" />
<span className="birthdayText">
<b>Anime2</b> and <b>3 other friends</b> have a bithday today.
</span>
</div>
<img className="rightbarAd" src="/tools/post/3.jpg" />
<h4 className="rightbarTitle">Online Friends</h4>
<ul className="rightbarFriendList">
{Users.map(u=>(
<Online key={u.id} user={u}/>
))}
</ul>
</>
)
}
const ProfileRightbar=()=>{
return(
<>
<h4 className="rightbarTitle">User Information</h4>
<div className="rightbarInfo">
<div className="rightbarInfoItem">
<span className="rightbarInfoKey">City:</span>
<span className="rightbarInfoValue">TamilNadu</span>
</div>
<div className="rightbarInfoItem">
<span className="rightbarInfoKey">From:</span>
<span className="rightbarInfoValue">Chennai</span>
</div>
<div className="rightbarInfoItem">
<span className="rightbarInfoKey">Relationship:</span>
<span className="rightbarInfoValue">Single</span>
</div>
</div>
<h4 className="rightbarTitle">User friends</h4>
<div className="rightbarFollowings">
<div className="rightbarFollowing">
<img src="/tools/profile/pro1.jpg" className="rightbarFollowingImg"/>
<span className="rightbarFollwingName">John Carter</span>
</div>
<div className="rightbarFollowing">
<img src="/tools/profile/pro2.png" className="rightbarFollowingImg"/>
<span className="rightbarFollwingName">John Carter</span>
</div>
<div className="rightbarFollowing">
<img src="/tools/profile/pro3.jpg" className="rightbarFollowingImg"/>
<span className="rightbarFollwingName">John Carter</span>
</div>
<div className="rightbarFollowing">
<img src="/tools/profile/pro4.jpeg" className="rightbarFollowingImg"/>
<span className="rightbarFollwingName">John Carter</span>
</div>
<div className="rightbarFollowing">
<img src="/tools/profile/pro5.jpg" className="rightbarFollowingImg"/>
<span className="rightbarFollwingName">John Carter</span>
</div>
<div className="rightbarFollowing">
<img src="/tools/profile/pro6.jpg" className="rightbarFollowingImg"/>
<span className="rightbarFollwingName">John Carter</span>
</div>
</div>
</>
)
}
return (
<div className="rightbar">
<div className="rightbarWrapper">
{profile ?<ProfileRightbar/>:<HomeRightbar/>}
</div>
</div>
);
} |
package com.controller;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import org.springframework.beans.BeanUtils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.ContextLoader;
import javax.servlet.ServletContext;
import com.service.TokenService;
import com.utils.*;
import java.lang.reflect.InvocationTargetException;
import com.service.DictionaryService;
import org.apache.commons.lang3.StringUtils;
import com.annotation.IgnoreAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.*;
import com.entity.view.*;
import com.service.*;
import com.utils.PageUtils;
import com.utils.R;
import com.alibaba.fastjson.*;
/**
* 审核人员
* 后端接口
* @author
* @email
*/
@RestController
@Controller
@RequestMapping("/shenherenyuan")
public class ShenherenyuanController {
private static final Logger logger = LoggerFactory.getLogger(ShenherenyuanController.class);
@Autowired
private ShenherenyuanService shenherenyuanService;
@Autowired
private TokenService tokenService;
@Autowired
private DictionaryService dictionaryService;
//级联表service
@Autowired
private YonghuService yonghuService;
@Autowired
private YewurenyuanService yewurenyuanService;
/**
* 后端列表
*/
@RequestMapping("/page")
public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){
logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params));
String role = String.valueOf(request.getSession().getAttribute("role"));
if(false)
return R.error(511,"永不会进入");
else if("用户".equals(role))
params.put("yonghuId",request.getSession().getAttribute("userId"));
else if("审核人员".equals(role))
params.put("shenherenyuanId",request.getSession().getAttribute("userId"));
else if("业务人员".equals(role))
params.put("yewurenyuanId",request.getSession().getAttribute("userId"));
if(params.get("orderBy")==null || params.get("orderBy")==""){
params.put("orderBy","id");
}
PageUtils page = shenherenyuanService.queryPage(params);
//字典表数据转换
List<ShenherenyuanView> list =(List<ShenherenyuanView>)page.getList();
for(ShenherenyuanView c:list){
//修改对应字典表字段
dictionaryService.dictionaryConvert(c, request);
}
return R.ok().put("data", page);
}
/**
* 后端详情
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id, HttpServletRequest request){
logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id);
ShenherenyuanEntity shenherenyuan = shenherenyuanService.selectById(id);
if(shenherenyuan !=null){
//entity转view
ShenherenyuanView view = new ShenherenyuanView();
BeanUtils.copyProperties( shenherenyuan , view );//把实体数据重构到view中
//修改对应字典表字段
dictionaryService.dictionaryConvert(view, request);
return R.ok().put("data", view);
}else {
return R.error(511,"查不到数据");
}
}
/**
* 后端保存
*/
@RequestMapping("/save")
public R save(@RequestBody ShenherenyuanEntity shenherenyuan, HttpServletRequest request){
logger.debug("save方法:,,Controller:{},,shenherenyuan:{}",this.getClass().getName(),shenherenyuan.toString());
String role = String.valueOf(request.getSession().getAttribute("role"));
if(false)
return R.error(511,"永远不会进入");
Wrapper<ShenherenyuanEntity> queryWrapper = new EntityWrapper<ShenherenyuanEntity>()
.eq("username", shenherenyuan.getUsername())
.or()
.eq("shenherenyuan_phone", shenherenyuan.getShenherenyuanPhone())
.or()
.eq("shenherenyuan_id_number", shenherenyuan.getShenherenyuanIdNumber())
;
logger.info("sql语句:"+queryWrapper.getSqlSegment());
ShenherenyuanEntity shenherenyuanEntity = shenherenyuanService.selectOne(queryWrapper);
if(shenherenyuanEntity==null){
shenherenyuan.setCreateTime(new Date());
shenherenyuan.setPassword("123456");
shenherenyuanService.insert(shenherenyuan);
return R.ok();
}else {
return R.error(511,"账户或者审核人员手机号或者审核人员身份证号已经被使用");
}
}
/**
* 后端修改
*/
@RequestMapping("/update")
public R update(@RequestBody ShenherenyuanEntity shenherenyuan, HttpServletRequest request){
logger.debug("update方法:,,Controller:{},,shenherenyuan:{}",this.getClass().getName(),shenherenyuan.toString());
String role = String.valueOf(request.getSession().getAttribute("role"));
// if(false)
// return R.error(511,"永远不会进入");
//根据字段查询是否有相同数据
Wrapper<ShenherenyuanEntity> queryWrapper = new EntityWrapper<ShenherenyuanEntity>()
.notIn("id",shenherenyuan.getId())
.andNew()
.eq("username", shenherenyuan.getUsername())
.or()
.eq("shenherenyuan_phone", shenherenyuan.getShenherenyuanPhone())
.or()
.eq("shenherenyuan_id_number", shenherenyuan.getShenherenyuanIdNumber())
;
logger.info("sql语句:"+queryWrapper.getSqlSegment());
ShenherenyuanEntity shenherenyuanEntity = shenherenyuanService.selectOne(queryWrapper);
if("".equals(shenherenyuan.getShenherenyuanPhoto()) || "null".equals(shenherenyuan.getShenherenyuanPhoto())){
shenherenyuan.setShenherenyuanPhoto(null);
}
if(shenherenyuanEntity==null){
shenherenyuanService.updateById(shenherenyuan);//根据id更新
return R.ok();
}else {
return R.error(511,"账户或者审核人员手机号或者审核人员身份证号已经被使用");
}
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Integer[] ids){
logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString());
shenherenyuanService.deleteBatchIds(Arrays.asList(ids));
return R.ok();
}
/**
* 批量上传
*/
@RequestMapping("/batchInsert")
public R save( String fileName, HttpServletRequest request){
logger.debug("batchInsert方法:,,Controller:{},,fileName:{}",this.getClass().getName(),fileName);
Integer yonghuId = Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId")));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
List<ShenherenyuanEntity> shenherenyuanList = new ArrayList<>();//上传的东西
Map<String, List<String>> seachFields= new HashMap<>();//要查询的字段
Date date = new Date();
int lastIndexOf = fileName.lastIndexOf(".");
if(lastIndexOf == -1){
return R.error(511,"该文件没有后缀");
}else{
String suffix = fileName.substring(lastIndexOf);
if(!".xls".equals(suffix)){
return R.error(511,"只支持后缀为xls的excel文件");
}else{
URL resource = this.getClass().getClassLoader().getResource("../../upload/" + fileName);//获取文件路径
File file = new File(resource.getFile());
if(!file.exists()){
return R.error(511,"找不到上传文件,请联系管理员");
}else{
List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
dataList.remove(0);//删除第一行,因为第一行是提示
for(List<String> data:dataList){
//循环
ShenherenyuanEntity shenherenyuanEntity = new ShenherenyuanEntity();
// shenherenyuanEntity.setUsername(data.get(0)); //账户 要改的
// //shenherenyuanEntity.setPassword("123456");//密码
// shenherenyuanEntity.setShenherenyuanUuidNumber(data.get(0)); //审核人员工号 要改的
// shenherenyuanEntity.setShenherenyuanName(data.get(0)); //审核人员姓名 要改的
// shenherenyuanEntity.setShenherenyuanPhone(data.get(0)); //审核人员手机号 要改的
// shenherenyuanEntity.setShenherenyuanIdNumber(data.get(0)); //审核人员身份证号 要改的
// shenherenyuanEntity.setShenherenyuanPhoto("");//详情和图片
// shenherenyuanEntity.setSexTypes(Integer.valueOf(data.get(0))); //性别 要改的
// shenherenyuanEntity.setShenherenyuanEmail(data.get(0)); //电子邮箱 要改的
// shenherenyuanEntity.setCreateTime(date);//时间
shenherenyuanList.add(shenherenyuanEntity);
//把要查询是否重复的字段放入map中
//账户
if(seachFields.containsKey("username")){
List<String> username = seachFields.get("username");
username.add(data.get(0));//要改的
}else{
List<String> username = new ArrayList<>();
username.add(data.get(0));//要改的
seachFields.put("username",username);
}
//审核人员工号
if(seachFields.containsKey("shenherenyuanUuidNumber")){
List<String> shenherenyuanUuidNumber = seachFields.get("shenherenyuanUuidNumber");
shenherenyuanUuidNumber.add(data.get(0));//要改的
}else{
List<String> shenherenyuanUuidNumber = new ArrayList<>();
shenherenyuanUuidNumber.add(data.get(0));//要改的
seachFields.put("shenherenyuanUuidNumber",shenherenyuanUuidNumber);
}
//审核人员手机号
if(seachFields.containsKey("shenherenyuanPhone")){
List<String> shenherenyuanPhone = seachFields.get("shenherenyuanPhone");
shenherenyuanPhone.add(data.get(0));//要改的
}else{
List<String> shenherenyuanPhone = new ArrayList<>();
shenherenyuanPhone.add(data.get(0));//要改的
seachFields.put("shenherenyuanPhone",shenherenyuanPhone);
}
//审核人员身份证号
if(seachFields.containsKey("shenherenyuanIdNumber")){
List<String> shenherenyuanIdNumber = seachFields.get("shenherenyuanIdNumber");
shenherenyuanIdNumber.add(data.get(0));//要改的
}else{
List<String> shenherenyuanIdNumber = new ArrayList<>();
shenherenyuanIdNumber.add(data.get(0));//要改的
seachFields.put("shenherenyuanIdNumber",shenherenyuanIdNumber);
}
}
//查询是否重复
//账户
List<ShenherenyuanEntity> shenherenyuanEntities_username = shenherenyuanService.selectList(new EntityWrapper<ShenherenyuanEntity>().in("username", seachFields.get("username")));
if(shenherenyuanEntities_username.size() >0 ){
ArrayList<String> repeatFields = new ArrayList<>();
for(ShenherenyuanEntity s:shenherenyuanEntities_username){
repeatFields.add(s.getUsername());
}
return R.error(511,"数据库的该表中的 [账户] 字段已经存在 存在数据为:"+repeatFields.toString());
}
//审核人员工号
List<ShenherenyuanEntity> shenherenyuanEntities_shenherenyuanUuidNumber = shenherenyuanService.selectList(new EntityWrapper<ShenherenyuanEntity>().in("shenherenyuan_uuid_number", seachFields.get("shenherenyuanUuidNumber")));
if(shenherenyuanEntities_shenherenyuanUuidNumber.size() >0 ){
ArrayList<String> repeatFields = new ArrayList<>();
for(ShenherenyuanEntity s:shenherenyuanEntities_shenherenyuanUuidNumber){
repeatFields.add(s.getShenherenyuanUuidNumber());
}
return R.error(511,"数据库的该表中的 [审核人员工号] 字段已经存在 存在数据为:"+repeatFields.toString());
}
//审核人员手机号
List<ShenherenyuanEntity> shenherenyuanEntities_shenherenyuanPhone = shenherenyuanService.selectList(new EntityWrapper<ShenherenyuanEntity>().in("shenherenyuan_phone", seachFields.get("shenherenyuanPhone")));
if(shenherenyuanEntities_shenherenyuanPhone.size() >0 ){
ArrayList<String> repeatFields = new ArrayList<>();
for(ShenherenyuanEntity s:shenherenyuanEntities_shenherenyuanPhone){
repeatFields.add(s.getShenherenyuanPhone());
}
return R.error(511,"数据库的该表中的 [审核人员手机号] 字段已经存在 存在数据为:"+repeatFields.toString());
}
//审核人员身份证号
List<ShenherenyuanEntity> shenherenyuanEntities_shenherenyuanIdNumber = shenherenyuanService.selectList(new EntityWrapper<ShenherenyuanEntity>().in("shenherenyuan_id_number", seachFields.get("shenherenyuanIdNumber")));
if(shenherenyuanEntities_shenherenyuanIdNumber.size() >0 ){
ArrayList<String> repeatFields = new ArrayList<>();
for(ShenherenyuanEntity s:shenherenyuanEntities_shenherenyuanIdNumber){
repeatFields.add(s.getShenherenyuanIdNumber());
}
return R.error(511,"数据库的该表中的 [审核人员身份证号] 字段已经存在 存在数据为:"+repeatFields.toString());
}
shenherenyuanService.insertBatch(shenherenyuanList);
return R.ok();
}
}
}
}catch (Exception e){
e.printStackTrace();
return R.error(511,"批量插入数据异常,请联系管理员");
}
}
/**
* 登录
*/
@IgnoreAuth
@RequestMapping(value = "/login")
public R login(String username, String password, String captcha, HttpServletRequest request) {
ShenherenyuanEntity shenherenyuan = shenherenyuanService.selectOne(new EntityWrapper<ShenherenyuanEntity>().eq("username", username));
if(shenherenyuan==null || !shenherenyuan.getPassword().equals(password))
return R.error("账号或密码不正确");
// // 获取监听器中的字典表
// ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
// Map<String, Map<Integer, String>> dictionaryMap= (Map<String, Map<Integer, String>>) servletContext.getAttribute("dictionaryMap");
// Map<Integer, String> role_types = dictionaryMap.get("role_types");
// role_types.get(.getRoleTypes());
String token = tokenService.generateToken(shenherenyuan.getId(),username, "shenherenyuan", "审核人员");
R r = R.ok();
r.put("token", token);
r.put("role","审核人员");
r.put("username",shenherenyuan.getShenherenyuanName());
r.put("tableName","shenherenyuan");
r.put("userId",shenherenyuan.getId());
return r;
}
/**
* 注册
*/
@IgnoreAuth
@PostMapping(value = "/register")
public R register(@RequestBody ShenherenyuanEntity shenherenyuan){
// ValidatorUtils.validateEntity(user);
Wrapper<ShenherenyuanEntity> queryWrapper = new EntityWrapper<ShenherenyuanEntity>()
.eq("username", shenherenyuan.getUsername())
.or()
.eq("shenherenyuan_phone", shenherenyuan.getShenherenyuanPhone())
.or()
.eq("shenherenyuan_id_number", shenherenyuan.getShenherenyuanIdNumber())
;
ShenherenyuanEntity shenherenyuanEntity = shenherenyuanService.selectOne(queryWrapper);
if(shenherenyuanEntity != null)
return R.error("账户或者审核人员手机号或者审核人员身份证号已经被使用");
shenherenyuan.setCreateTime(new Date());
shenherenyuanService.insert(shenherenyuan);
return R.ok();
}
/**
* 重置密码
*/
@GetMapping(value = "/resetPassword")
public R resetPassword(Integer id){
ShenherenyuanEntity shenherenyuan = new ShenherenyuanEntity();
shenherenyuan.setPassword("123456");
shenherenyuan.setId(id);
shenherenyuanService.updateById(shenherenyuan);
return R.ok();
}
/**
* 忘记密码
*/
@IgnoreAuth
@RequestMapping(value = "/resetPass")
public R resetPass(String username, HttpServletRequest request) {
ShenherenyuanEntity shenherenyuan = shenherenyuanService.selectOne(new EntityWrapper<ShenherenyuanEntity>().eq("username", username));
if(shenherenyuan!=null){
shenherenyuan.setPassword("123456");
boolean b = shenherenyuanService.updateById(shenherenyuan);
if(!b){
return R.error();
}
}else{
return R.error("账号不存在");
}
return R.ok();
}
/**
* 获取用户的session用户信息
*/
@RequestMapping("/session")
public R getCurrShenherenyuan(HttpServletRequest request){
Integer id = (Integer)request.getSession().getAttribute("userId");
ShenherenyuanEntity shenherenyuan = shenherenyuanService.selectById(id);
if(shenherenyuan !=null){
//entity转view
ShenherenyuanView view = new ShenherenyuanView();
BeanUtils.copyProperties( shenherenyuan , view );//把实体数据重构到view中
//修改对应字典表字段
dictionaryService.dictionaryConvert(view, request);
return R.ok().put("data", view);
}else {
return R.error(511,"查不到数据");
}
}
/**
* 退出
*/
@GetMapping(value = "logout")
public R logout(HttpServletRequest request) {
request.getSession().invalidate();
return R.ok("退出成功");
}
} |
# RxJS 测试…我的可观察对象工作正常吗?
> 原文:<https://levelup.gitconnected.com/rxjs-testing-is-my-observable-working-correctly-9842bbe0a571>
## RxJS 中的单元测试,所有你需要知道的!

作者:FAM
今天的故事是关于测试的😈
在任何软件开发过程中,测试都是必须知道的。它保证了整个系统仍在工作,并且在开发新功能或修复 bug 时没有发生退化。
当然,如果我们对每个新实现的特性进行测试。否则,防止回归和系统错误的整个逻辑就行不通了。
可观测量是反应式编程中必须知道和使用的。使用新的框架和库,如 Angular、React 和 VueJS。这是在你的应用中处理数据的最干净、最恰当的方式。因此,知道如何测试可观察性也是需要的,这篇文章就是关于这个的!
> 如今编写单元测试是至关重要的
我们用一个物体来测试可观测性。如果你读过关于[可观察调度器](/rexjs-schedulers-the-observable-execution-orchestrators-60479ece23da?source=your_stories_page-------------------------------------),你可能会记得它是`TestScheduler`。用一句直白的话来说,这个物体就是:
> 我们同步测试异步代码的方式
如您所见,我们在链的末端进行测试,因此完全了解 RxJS 可观测量是至关重要的。因此,在阅读以下内容之前,一些必要的知识是必要的:
* 你需要知道的关于 RxJS 的全部知识和概念
[](/rxjs-like-youve-never-seen-it-b99467557a54) [## RxJS 像没见过一样!
### 关于 RxJS 你可能想了解或知道的一切!
levelup.gitconnected.com](/rxjs-like-youve-never-seen-it-b99467557a54)
* 单元测试(仅当`describe(...)`、`beforEach(..)`、`it(...)`不和你说话时)
[](/how-do-you-write-a-unit-test-case-what-you-must-know-before-starting-a-unit-test-in-angular-f1174f437cb6) [## 如何编写单元测试用例?在 Angular 中开始单元测试之前你必须知道的事情!
### 角度单位测试
levelup.gitconnected.com](/how-do-you-write-a-unit-test-case-what-you-must-know-before-starting-a-unit-test-in-angular-f1174f437cb6)
* 大理石图
[](https://famzil.medium.com/marble-diagram-testing-5009c74324db) [## 大理石图测试
### 什么是大理石图,它是如何工作的?
famzil.medium.com](https://famzil.medium.com/marble-diagram-testing-5009c74324db)
# 这家伙怎么能这么做?
* **通过虚拟化时间:**
如果您的可观察对象需要一个`T`时间来完成,那么`TestScheduler`将有效地使用它自己的内部定时器来测试异步代码。`TestCheduler`会提前时间。你不用等了。
* **一期 it**
不幸的是,使用这个家伙有一个限制。它只支持与`AsynchSechduler`一起工作的代码。(我在这篇[文章](/rexjs-schedulers-the-observable-execution-orchestrators-60479ece23da?source=your_stories_page-------------------------------------)里讲过这个调度器。如果这还不能说明问题,我建议您学习一下调度程序)。
* **优势**
这个家伙被 ***实例化,向它的构造函数传递一个函数*** ,你想用它来进行等式测试。这个信息的最大优点是它的*。它不会强迫你使用一个特定的测试框架。无论你想用什么(笑话,因果报应,笑话…),对于`TestScheduler`来说无所谓。*
* ***代码示例***
*实例化*
*通过使用带有`helpers`对象的`run()`方法编写您的测试。*
*被称为`helpers`(你可以随便叫它什么。这个对象的作用是帮助你测试。*
*`helpers`的另一种使用方式:*
*—如果您期望观察到`cold`或`hot`,那么您可以使用:*
*—其他助手也是如此……*
# *使用 Chai 的完整代码示例*
*仅供参考:你不需要使用柴。正如我之前告诉你的,你可以自由选择你的测试框架。*
* *对于测试套件,我们需要一个`***TestScheduler***`的实例*
* *在每次测试之前,我们实例化这个家伙*
* *每个测试将执行`*TestShcheduler*`对象的`***beforeEach(…)***`和`***run()***`方法。*
* *每个测试根据测试期望使用`***helpers***` (对于冷可观察的,我们使用`***helper.cold***($theColdObservable)***.toBe***(theExpectedProducedValues)`*
* *每个测试可以使用尽可能多的助手内置方法来测试预期值。*
* *测试使用了一个 ***弹球图,一个*** 字符串,包含表示虚拟时间内发生的事件的特殊语法。*
*就这样😛*
> *我今天的故事到此结束,希望你喜欢 it❤*
*如果你喜欢看我的文章… ♥️*
*[](https://famzil.medium.com/subscribe) [## 如果你喜欢看我的文章… ♥️
### 如果你喜欢读我的文章… ♥️,当我的文章发表时,欢迎你第一个得到通知…
famzil.medium.com](https://famzil.medium.com/subscribe)
> 谢谢你,❤
如果你有兴趣成为付费会员,你可以使用我的推荐链接。下次见
亲爱的读者,感谢你在我生命中的存在。
**让我们在** [**上取得联系**](https://medium.com/@famzil/)**[**Linkedin**](https://www.linkedin.com/in/fatima-amzil-9031ba95/)**[**脸书**](https://www.facebook.com/The-Front-End-World)**[**insta gram**](https://www.instagram.com/the_frontend_world/)**[**YouTube**](https://www.youtube.com/channel/UCaxr-f9r6P1u7Y7SKFHi12g)**或**[](https://twitter.com/FatimaAMZIL9)********
******参见我的关于网络要素和一般文化的电子书。******* |
package com.cybrarist.islamquiz.repositories
import androidx.annotation.WorkerThread
import com.cybrarist.islamquiz.database.games.Game
import com.cybrarist.islamquiz.database.games.GameDao
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GameRepository @Inject constructor (private val game_dao: GameDao) {
val all_games : Flow<List<Game>> = game_dao.all_games()
fun get_current_game(game_id: Int): Game {
return game_dao.get_the_current_game(game_id)
}
@WorkerThread
suspend fun upsert_game(game: Game){
game_dao.upsert(game)
}
@WorkerThread
suspend fun delete_game(game: Game){
game_dao.delete(game)
}
@WorkerThread
suspend fun update_game(game: Game){
game_dao.upsert(game = game)
}
} |
const express = require('express');
//import ApolloServer
const { ApolloServer} = require('apollo-server-express');
// const path = require('path');
//import our typeDefs and resolvers
const { typeDefs, resolvers} = require('./schemas');
const db = require('./connection');
const {authMiddleware} = require('./utils/auth');
const PORT = process.env.PORT || 3001;
const app = express();
const startServer = async () => {
//create a new Apollo server and pass in our schema data
const server = new ApolloServer({
typeDefs,
resolvers,
context: authMiddleware
});
//Start the Apollo server
await server.start();
//integrate our Apollo server with the Express application as middleware
server.applyMiddleware({ app });
// log where we can go to test our GQL API
console.log(`Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`);
};
//Initialize the Apollo server
startServer();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// // Serve up static assets
// if (process.env.NODE_ENV === 'production') {
// app.use(express.static(path.join(__dirname, '../client/build')));
// }
// app.get('*', (req, res) => {
// res.sendFile(path.join(__dirname, '../client/build/index.html'));
// });
db.once('open', () => {
app.listen(PORT, () => {
console.log(`API server running on port ${PORT}!`);
});
}); |
import { useState, useContext, useRef } from "react";
import { GlobalContext } from "../context/GlobalContext";
import ViewReport from "./ViewReport";
import {
Flex,
Text,
Button,
IconButton,
useColorModeValue,
Menu,
MenuButton,
MenuList,
MenuItem,
useDisclosure,
Tag,
TagLabel,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
CloseButton,
useToast,
Circle,
} from "@chakra-ui/react";
import {
SunIcon,
MoonIcon,
SmallCloseIcon,
SearchIcon,
AddIcon,
ViewIcon,
EditIcon,
DeleteIcon,
CopyIcon,
CloseIcon,
CheckIcon,
} from "@chakra-ui/icons";
import { BsPrinterFill } from "react-icons/bs";
import { useRouter } from "next/router";
import ReactToPrint from "react-to-print";
const Notifications = () => {
const { data, selected, setSelected, filteredReports } =
useContext(GlobalContext);
const modalBg = useColorModeValue("gray.50", "gray.900");
const sectionBg = useColorModeValue("gray.50", "gray.700");
const { isOpen, onOpen, onClose } = useDisclosure();
const [scrollBehavior, setScrollBehavior] = useState("inside");
const btnRef = useRef(null);
const toast = useToast();
const router = useRouter();
const componentRef = useRef();
const printHandler = () => {
// alert(
// "window.print(), where you can send to printer and save as PDF, Perhaps react-to-print package, where you can select graphics background. You cannot print in dark"
// );
return <button>Print</button>;
};
return (
<Flex w="full" flexDir="column">
{data.map((item, index) => (
<Flex
key={index}
h="36px"
_hover={{ bg: "gray.300" }}
w="full"
my={1}
p={3}
align="center"
onDoubleClick={() => setSelected(item._id)}
cursor="pointer"
>
{item.wellName}
</Flex>
))}
{selected &&
filteredReports.map((item, index) => (
<Modal
finalFocusRef={btnRef}
isOpen={selected}
scrollBehavior={scrollBehavior}
size="2xl"
key={index}
>
<ModalOverlay />
<ModalContent bg={modalBg}>
<ModalHeader p={3}>
<Flex w="full" justify="end">
<Flex>
<CloseButton size="sm" onClick={() => setSelected(null)} />
</Flex>
</Flex>
</ModalHeader>
<div className="overflow-x-auto overflow-y-auto scrollbar-hide">
<div>
{/* <ReactToPrint
trigger={() => <button>Print</button>}
content={() => componentRef.current}
/> */}
<ViewReport
_id={item._id}
ref={componentRef}
wellType={item.wellType}
wellName={item.wellName}
dateSubmitted={item.dateSubmitted}
submittedBy={item.submittedBy}
company={item.company}
field={item.field}
fluid={item.fluid}
environment={item.environment}
status={item.status}
completion={item.completion}
wellProfile={item.wellProfile}
spudDate={item.spudDate}
originalElevation={item.originalElevation}
units={item.units}
latitude={item.latitude}
longitude={item.longitude}
wellRemarks={item.wellRemarks}
jobDescription={item.jobDescription}
jobStartDate={item.jobStartDate}
jobStartTime={item.jobStartTime}
jobEndDate={item.jobEndDate}
jobEndTime={item.jobEndTime}
conveyance={item.conveyance}
operation={item.operation}
runs={item.runs}
jobRemarks={item.jobRemarks}
personnel={item.personnel}
equipment={item.equipment}
sequenceOfEvents={item.sequenceOfEvents}
pce={item.pce}
pceRunNumber={item.pceRunNumber}
nptHours={item.nptHours}
pceMinId={item.pceMinId}
pceTotalLength={item.pceTotalLength}
toolstring={item.toolstring}
toolstringRunNumber={item.toolstringRunNumber}
toolstringTotalLength={item.toolstringTotalLength}
toolstringTotalWeight={item.toolstringTotalWeight}
toolstringMaxOd={item.toolstringMaxOd}
attachments={item.attachments}
/>
</div>
</div>
<ModalFooter p={3} mt={6}>
<Flex w="full" justify="space-between">
<Flex>
<Button
onClick={() => alert("open edit form")}
size="sm"
leftIcon={<EditIcon />}
variant="outline"
colorScheme="blue"
w="80px"
mr={3}
>
Edit
</Button>
{/* This is a new button */}
<ReactToPrint
trigger={() => (
<Button
size="sm"
leftIcon={<BsPrinterFill />}
variant="outline"
colorScheme="blue"
>
Print
</Button>
)}
content={() => componentRef.current}
/>
{/* This is the old button */}
{/* <Button
onClick={printHandler}
size="sm"
leftIcon={<BsPrinterFill />}
variant="outline"
colorScheme="blue"
>
Print
</Button> */}
</Flex>
<Flex>
<Button
size="sm"
variant="outline"
colorScheme="green"
leftIcon={<CheckIcon />}
onClick={() => alert("set as Verified")}
>
Approve
</Button>
</Flex>
</Flex>
</ModalFooter>
</ModalContent>
</Modal>
))}
</Flex>
);
};
export default Notifications; |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2013-2016 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::functionObjects::turbulenceFields
Group
grpFieldFunctionObjects
Description
This function object stores turbulence fields on the mesh database for
further manipulation.
Fields are stored as copies of the original, with the prefix
"tubulenceModel:", e.g.:
\verbatim
turbulenceModel:R
\endverbatim
Example of function object specification:
\verbatim
turbulenceFields1
{
type turbulenceFields;
libs ("libfieldFunctionObjects.so");
...
fields
(
R
devRhoReff
);
}
\endverbatim
Usage
\table
Property | Description | Required | Default value
type | type name: processorField | yes |
fields | fields to store (see below) | yes |
\endtable
Where \c fields can include:
\plaintable
k | turbulence kinetic energy
epsilon | turbulence kinetic energy dissipation rate
omega | turbulence specific dissipation rate
nut | turbulence viscosity (incompressible)
nuEff | effective turbulence viscosity (incompressible)
mut | turbulence viscosity (compressible)
muEff | effective turbulence viscosity (compressible)
alphat | turbulence thermal diffusivity (compressible)
alphaEff | effective turbulence thermal diffusivity (compressible)
R | Reynolds stress tensor
devReff | Deviatoric part of the effective Reynolds stress
devRhoReff | Divergence of the Reynolds stress
\endplaintable
See also
Foam::functionObjects::fvMeshFunctionObject
Foam::functionObjects::timeControl
SourceFiles
tkeBudget.C
\*---------------------------------------------------------------------------*/
#ifndef functionObjects_tkeBudget_H
#define functionObjects_tkeBudget_H
#include "fvMeshFunctionObject.H"
#include "HashSet.H"
#include "NamedEnum.H"
#include "volFieldsFwd.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace functionObjects
{
/*---------------------------------------------------------------------------*\
Class turbulenceFields Declaration
\*---------------------------------------------------------------------------*/
//class turbulenceFields
class tkeBudget
:
public fvMeshFunctionObject
{
public:
enum incompressibleField
{
ifCk, // convection term
ifPk, // production term
ifTk, // turbulence transport
ifDk, // viscous diffusion
ifEpik, // viscous dissipation
ifPik // velocity-pressure gradient
};
static const NamedEnum<incompressibleField, 6> incompressibleFieldNames_;
protected:
// Protected data
//- Fields to load
wordHashSet fieldSet_;
// Reynolds number
scalar Re;
// Protected Member Functions
//- Process the tke field
template<class Type>
void processField
(
const word& fieldName,
const tmp<GeometricField<Type, fvPatchField, volMesh>>& tvalue
);
// return the convection term Ck
tmp<volScalarField> Ck() const;
// return the production term Pk
tmp<volScalarField> Pk() const;
// return the production term Tk
tmp<volScalarField> Tk() const;
// return the production term Dk
tmp<volScalarField> Dk() const;
// return the production term Dk
tmp<volScalarField> Epik() const;
// return the production term Dk
tmp<volScalarField> Pik() const;
private:
// private variables
// Private member functions
//- Disallow default bitwise copy construct
tkeBudget(const tkeBudget&);
//- Disallow default bitwise assignment
void operator=(const tkeBudget&);
public:
//- Runtime type information
TypeName("tkeBudget");
// Constructors
//- Construct from Time and dictionary
tkeBudget
(
const word& name,
const Time& runTime,
const dictionary& dict
);
//- Destructor
virtual ~tkeBudget();
// Member Functions
//- Read the controls
virtual bool read(const dictionary&);
//- Calculate turbulence fields
virtual bool execute();
//- Do nothing.
// The turbulence fields are registered and written automatically
virtual bool write();
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace functionObjects
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
#include "tkeBudgetTemplates.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* // |
import * as React from 'react';
import { Form, Input, Row, Col, Select, Divider, DatePicker } from 'antd';
import moment from 'moment';
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn';
// import CommonUtils from 'src/utils/commonUtils';
moment.locale('zh-cn');
const FormItem = Form.Item;
const { Option } = Select;
/** Props接口,定义需要用到的Porps类型 */
export interface IProps {
form: any;
editData?: any;
purchaseChannelChoices: any;
monetaryUnitChoices: any;
burstBillingChoices: any;
changeTypeChoices: any;
}
/** State接口,定义需要用到的State类型,constructor中的state应该和此定义的类型一致 */
export interface IState {
}
/**
*
*/
class AddEditContractModal extends React.PureComponent<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
// protocolSupportList: [],
};
}
render() {
const {
editData,
purchaseChannelChoices,
monetaryUnitChoices,
burstBillingChoices,
} = this.props;
const { getFieldDecorator } = this.props.form;
return (
<div>
<Form className="modal-form" layout="inline" labelCol={{ span: 10 }} wrapperCol={{ span: 14 }}>
<Divider orientation="left">基础信息</Divider>
<Row>
<Col span={12}>
<FormItem label="合同编号">
{getFieldDecorator('contract_num', {
initialValue: editData ? editData.contract_num : null,
rules: [
{ required: true, message: '请输入合同编号' }
],
})(
<Input />
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem label="商务实体">
{getFieldDecorator('business_entity', {
initialValue: editData ? editData.business_entity : null,
rules: [
{ required: true, message: '请输入商务实体' }
],
})(
<Input />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem label="采购渠道">
{getFieldDecorator('purchase_channel_id', {
initialValue: editData ? editData.purchase_channel_id : null,
rules: [
{ required: true, message: '请输入对端名称' }
],
})(
<Select
// style={{ width: 150 }}
>
{purchaseChannelChoices.map((type: any) => (
<Option value={type.value} key={type.value}>{type.label}</Option>
))}
</Select>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem label="服务起始">
{getFieldDecorator('start_date', {
initialValue: editData ? moment(editData.start_date, 'YYYY-MM-DD') : null,
rules: [
{ required: true, message: '请输入服务起始' }
],
})(
<DatePicker
locale={locale}
format="YYYY-MM-DD"
/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem label="服务结束">
{getFieldDecorator('end_date', {
initialValue: editData ? moment(editData.end_date, 'YYYY-MM-DD') : null,
rules: [
{ required: true, message: '请输入服务结束' }
],
})(
<DatePicker
locale={locale}
format="YYYY-MM-DD"
/>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem label="授权主体" >
{getFieldDecorator('authorized_subject', {
initialValue: editData ? editData.authorized_subject : null,
rules: [
{ required: true, message: '请输入授权主体' }
],
})(
<Input />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem label="续约提醒">
{getFieldDecorator('contract_remind', {
initialValue: editData ? editData.contract_remind : null,
rules: [
// { required: true, message: '请输入续约提醒' }
],
})(
<Input suffix="/天" />
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={24}>
<FormItem label="备注" labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
{getFieldDecorator('desc', {
initialValue: editData ? editData.desc : null,
rules: [
// { required: true, message: '请输入备注' }
],
})(
<Input />
)}
</FormItem>
</Col>
</Row>
<Divider orientation="left">费用信息</Divider>
<Row>
<Col span={12}>
<FormItem label="货币单位">
{getFieldDecorator('monetary_unit_id', {
initialValue: editData ? editData.monetary_unit_id : null,
rules: [
{ required: true, message: '请选择货币单位' }
],
})(
<Select
// style={{ width: 150 }}
>
{monetaryUnitChoices.map((type: any) => (
<Option value={type.value} key={type.value}>{type.label}</Option>
))}
</Select>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem label="突发计费">
{getFieldDecorator('burst_billing_id', {
initialValue: editData ? editData.burst_billing_id : null,
rules: [
{ required: true, message: '请选择突发计费' }
],
})(
<Select
// style={{ width: 150 }}
>
{burstBillingChoices.map((type: any) => (
<Option value={type.value} key={type.value}>{type.label}</Option>
))}
</Select>
)}
</FormItem>
</Col>
</Row>
<Row>
<Col span={12}>
<FormItem label="承诺月付">
{getFieldDecorator('committed_fee', {
initialValue: editData ? editData.committed_fee : null,
rules: [
{ required: true, message: '请输入承诺月付' }
],
})(
<Input />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem label="突发浮动">
{getFieldDecorator('burst_float', {
initialValue: editData ? editData.burst_float : null,
rules: [
{ required: true, message: '请输入突发浮动' }
],
})(
<Input />
)}
</FormItem>
</Col>
</Row>
</Form>
</div>
);
}
}
export default AddEditContractModal; |
<template>
<v-container grid-list-xs>
<v-layout row wrap>
<v-flex xs12>
<v-container grid-list-xs>
<v-layout row wrap justify-space-between>
<v-flex md3 xs12 mb-5>
<disc-table :datas="most" :answers="selectedMost" :key="refreshKey"></disc-table>
</v-flex>
<v-flex md3 xs12 mb-5>
<disc-table :datas="least" :answers="selectedLeast" :key="refreshKey"></disc-table>
</v-flex>
<v-flex md3 xs12>
<disc-table :datas="change" :answers="selectedChange" :key="refreshKey"></disc-table>
</v-flex>
</v-layout>
</v-container>
</v-flex>
</v-layout>
<v-layout row wrap>
<v-flex xs12>
<v-card>
<v-card-title primary-title>
<h1 class="headline">Set DISC Result</h1>
</v-card-title>
<v-card-text v-if="isLoaded">
<v-container grid-list-xs>
<v-layout row wrap>
<v-flex md6 xs12>
<v-autocomplete label="Behavior Style" :items="discCodes" v-model="discCode"></v-autocomplete>
</v-flex>
<v-flex md6 xs12>
<v-text-field name="discResult" label="Pattern Name" :value="discResult" readonly></v-text-field>
</v-flex>
</v-layout>
<v-layout row wrap>
<v-flex xs12 text-xs-right>
<v-btn
color="red darken-2 white--text"
@click="submit"
:disabled="isDisabledSubmit"
>Submit</v-btn>
</v-flex>
</v-layout>
<v-layout row wrap>
<v-dialog v-model="dialogSuccess" persistent max-width="500">
<v-card>
<v-card-title class="headline" color="red darken-2">Berhasil!</v-card-title>
<v-card-text>Hasil DISC telah berhasil diperbaharui!</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="green darken-1" flat @click="back">Close</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-layout>
</v-container>
</v-card-text>
<v-card-text v-else>Tidak ada data DISC!</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
import discTable from '@/components/Applicant/Result/Disc/DiscTable'
export default {
data () {
return {
most: {
type: 'most',
d: [21, 16, 15, '', '', 14, 13, '', 12, 11, 10, '', 9, '', 8, 7, 6, '', 5, 4, '', 3, '', '', 2, '', '', 1, '', 0, '', '', ''],
i: [19, 11, '', 9, 8, 7, '', '', '', 6, 5, '', '', '', 4, '', '', '', 3, '', '', 2, '', '', '', '', 1, '', '', '', '', 0, ''],
s: [20, '', 14, '', 12, '', 10, '', 9, '', 8, 7, '', '', 6, 5, '', 4, '', 3, '', '', '', 2, '', 1, '', '', 0, '', '', '', ''],
c: [17, 13, 11, 9, 8, 7, '', '', '', '', 6, '', 5, '', '', 4, '', '', '', 3, '', '', '', 2, '', '', 1, '', '', 0, '', '', '']
},
least: {
type: 'least',
d: [0, '', 1, '', '', '', '', 2, '', '', '', 3, '', 4, '', 5, 6, '', 7, 8, '', 9, 10, 11, '', 12, '', 13, 14, 15, 16, '', 20],
i: ['', 0, '', 1, '', '', '', '', 2, '', '', 3, '', '', '', 4, 5, '', '', '', 6, '', '', 7, '', 8, '', 9, '', 10, 11, 12, 19],
s: [0, 1, '', 2, '', '', '', '', 3, '', '', 4, '', 5, '', 6, '', '', 7, '', 8, '', 9, '', '', 10, '', 11, '', 12, 13, 16, 19],
c: [0, 1, '', '', 2, '', '', '', 3, '', '', 4, '', 5, '', 6, 7, '', 8, '', '', 9, '', 10, '', '', '', 11, 12, 13, '', 15, 17]
},
change: {
type: 'change',
d: [21, 18, 15, 14, 13, 12, 10, '', 9, 8, '', 7, '', 5, 3, 1, 0, -2, -3, -4, '', -6, -7, '', '', -10, '', -11, -12, '', -16, -20, ''],
i: [18, 10, 8, '', 7, 6, '', 5, 4, '', 3, '', '', 2, 1, 0, -1, '', '' - 2, -3, '', -4, -5, '', -6, '', '', -8, -9, -10, -18, ''],
s: [20, 15, 11, 10, 9, 8, 7, '', 5, 4, 3, '', 2, 1, 0, '', -1, -2, -3, -4, -5, '', -6, -7, '', -8, '', '', '', -10, '', -15, -18],
c: [17, 10, 6, 5, 4, '', '', 3, 2, '', 1, '', '', 0, -1, -2, -3, -4, '', '', '', -5, -6, -7, '', -8, '', '', -10, -13, -15, -19, -22]
},
selectedMost: {
d: 0,
i: 0,
s: 0,
c: 0
},
selectedLeast: {
d: 0,
i: 0,
s: 0,
c: 0
},
selectedChange: {
d: 0,
i: 0,
s: 0,
c: 0
},
refreshKey: 0,
discCodes: ["Pure D", "D equal I", "D equal I", "DS-SD", "DI", "DC", "DIC", "DIS", "Pure I", "IC", "ICS", "ID", "IDC", "IDS", "IS", "ISC", "ISD", "Pure S", "SC", "SCI", "SD", "SDC", "SI", "SIC", "Pure C", "CD", "CDS", "CI", "CIS", "CS", "CSI"],
discCode: "",
isLoaded: false,
dialogSuccess: false
}
},
computed: {
discResult () {
if (this.discCode == "Pure D") return "Establisher"
else if (this.discCode == "D equal I") return "Influencer"
else if (this.discCode == "DS-SD") return "Attainer"
else if (this.discCode == "DI") return "Concluder"
else if (this.discCode == "DC") return "Challenger"
else if (this.discCode == "DIC") return "Chancellor"
else if (this.discCode == "DIS") return "Director"
else if (this.discCode == "Pure I") return "Communicator"
else if (this.discCode == "IC") return "Assessor"
else if (this.discCode == "ICS") return "Governor"
else if (this.discCode == "ID") return "Persuader"
else if (this.discCode == "IDC") return "Leader"
else if (this.discCode == "IDS") return "Reformer"
else if (this.discCode == "IS") return "Advisor"
else if (this.discCode == "ISC") return "Governor"
else if (this.discCode == "ISD") return "Motivator"
else if (this.discCode == "Pure S") return "Specialist"
else if (this.discCode == "SC") return "Peacemaker"
else if (this.discCode == "SCI") return "Advocate"
else if (this.discCode == "SD") return "Attainer"
else if (this.discCode == "SDC") return "Inquirer"
else if (this.discCode == "SI") return "Advisor"
else if (this.discCode == "SIC") return "Advocate"
else if (this.discCode == "Pure C") return "Logical Thinker"
else if (this.discCode == "CD") return "Designer"
else if (this.discCode == "CDS") return "Contemplator"
else if (this.discCode == "CI") return "Assessor"
else if (this.discCode == "CIS") return "Mediator"
else if (this.discCode == "CS") return "Perfectionist"
else if (this.discCode == "CSI") return "Practitioner"
else return ""
},
isDisabledSubmit () {
return this.discResult ? false : true
}
},
methods: {
submit () {
const data = {
applicantId: this.$route.params.applicantId,
score: this.discCode,
remarks: this.discResult
}
const auth = {
headers: { Authorization: "Bearer " + localStorage.getItem("token") }
};
this.$store.dispatch('setLoading', true)
this.axios.post(process.env.VUE_APP_API_URL + "/exam/result/set/disc", data, auth)
.then(res => {
this.$store.dispatch('setLoading', false)
if (res.status == 200) {
this.dialogSuccess = true
}
})
},
back () {
this.$router.push({ name: 'applicants' })
}
},
components: {
discTable
},
created () {
const auth = {
headers: { Authorization: "Bearer " + localStorage.getItem("token") }
};
this.$store.dispatch('setLoading', true)
this.axios.get(process.env.VUE_APP_API_URL + "/exam/score/disc/" + this.$route.params.applicantId, auth)
.then(res => {
this.$store.dispatch('setLoading', false)
const ans = res.data.data
this.selectedMost.d = ans.scoreM_D
this.selectedMost.i = ans.scoreM_I
this.selectedMost.s = ans.scoreM_S
this.selectedMost.c = ans.scoreM_C
this.selectedLeast.d = ans.scoreL_D
this.selectedLeast.i = ans.scoreL_I
this.selectedLeast.s = ans.scoreL_S
this.selectedLeast.c = ans.scoreL_C
this.selectedChange.d = ans.scoreC_D
this.selectedChange.i = ans.scoreC_I
this.selectedChange.s = ans.scoreC_S
this.selectedChange.c = ans.scoreC_C
if (!ans.debug) {
this.isLoaded = true;
const auth = {
headers: { Authorization: "Bearer " + localStorage.getItem("token") }
};
this.$store.dispatch('setLoading', true)
this.axios.get(process.env.VUE_APP_API_URL + "/exam/result/get/" + this.$route.params.applicantId, auth)
.then(res => {
this.$store.dispatch('setLoading', false)
const examResult = res.data.data.examResult
examResult.forEach(el => {
if (el.examType.examTypeId == 1) this.discCode = el.score
});
})
}
this.refreshKey++;
})
}
}
</script> |
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCycleRequest;
use App\Http\Requests\UpdateCycleRequest;
use App\Models\Cycle;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
class CycleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$results = QueryBuilder::for(Cycle::class)
->allowedFilters(
AllowedFilter::partial('name'),
AllowedFilter::exact('status')
)
->paginate(request()->get('per_page', 15))
->appends(request()->query());
return response()->json($results);
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\StoreCycleRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StoreCycleRequest $request)
{
$result = Cycle::create($request->only([
'name',
'num_days',
'status',
'description',
]));
return response()->json($result);
}
/**
* Display the specified resource.
*
* @param \App\Models\Cycle $cycle
* @return \Illuminate\Http\Response
*/
public function show(Cycle $cycle)
{
return response()->json($cycle);
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\UpdateCycleRequest $request
* @param \App\Models\Cycle $cycle
* @return \Illuminate\Http\Response
*/
public function update(UpdateCycleRequest $request, Cycle $cycle)
{
$result = $cycle->update($request->only([
'name',
'num_days',
'status',
'description',
]));
return response()->json($result);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Cycle $cycle
* @return \Illuminate\Http\Response
*/
public function destroy(Cycle $cycle)
{
$cycle->delete();
return response()->json(null, 204);
}
} |
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";
const { AddonTestUtils } = ChromeUtils.import(
"resource://testing-common/AddonTestUtils.jsm"
);
const { AddonManager } = ChromeUtils.import(
"resource://gre/modules/AddonManager.jsm"
);
const { AboutNewTab } = ChromeUtils.import(
"resource:///modules/AboutNewTab.jsm"
);
// Lazy load to avoid having Services.appinfo cached first.
ChromeUtils.defineModuleGetter(
this,
"ExtensionParent",
"resource://gre/modules/ExtensionParent.jsm"
);
const { HomePage } = ChromeUtils.import("resource:///modules/HomePage.jsm");
AddonTestUtils.init(this);
// Allow for unsigned addons.
AddonTestUtils.overrideCertDB();
AddonTestUtils.createAppInfo(
"xpcshell@tests.mozilla.org",
"XPCShell",
"42",
"42"
);
add_task(async function test_settings_modules_not_loaded() {
await ExtensionParent.apiManager.lazyInit();
// Test that no settings modules are loaded.
let modules = Array.from(ExtensionParent.apiManager.settingsModules);
ok(modules.length, "we have settings modules");
for (let name of modules) {
ok(
!ExtensionParent.apiManager.getModule(name).loaded,
`${name} is not loaded`
);
}
});
add_task(async function test_settings_validated() {
let defaultNewTab = AboutNewTab.newTabURL;
equal(defaultNewTab, "about:newtab", "Newtab url is default.");
let defaultHomepageURL = HomePage.get();
equal(defaultHomepageURL, "about:home", "Home page url is default.");
let xpi = await AddonTestUtils.createTempWebExtensionFile({
manifest: {
version: "1.0",
applications: { gecko: { id: "test@mochi" } },
chrome_url_overrides: {
newtab: "/newtab",
},
chrome_settings_overrides: {
homepage: "https://example.com/",
},
},
});
let extension = ExtensionTestUtils.expectExtension("test@mochi");
let file = await AddonTestUtils.manuallyInstall(xpi);
await AddonTestUtils.promiseStartupManager();
await extension.awaitStartup();
equal(
HomePage.get(),
"https://example.com/",
"Home page url is extension controlled."
);
ok(
AboutNewTab.newTabURL.endsWith("/newtab"),
"newTabURL is extension controlled."
);
await AddonTestUtils.promiseShutdownManager();
// After shutdown, delete the xpi file.
Services.obs.notifyObservers(xpi, "flush-cache-entry");
try {
file.remove(true);
} catch (e) {
ok(false, e);
}
await AddonTestUtils.cleanupTempXPIs();
// Restart everything, the ExtensionAddonObserver should handle updating state.
let prefChanged = TestUtils.waitForPrefChange("browser.startup.homepage");
await AddonTestUtils.promiseStartupManager();
await prefChanged;
equal(HomePage.get(), defaultHomepageURL, "Home page url is default.");
equal(AboutNewTab.newTabURL, defaultNewTab, "newTabURL is reset to default.");
await AddonTestUtils.promiseShutdownManager();
});
add_task(async function test_settings_validated_safemode() {
let defaultNewTab = AboutNewTab.newTabURL;
equal(defaultNewTab, "about:newtab", "Newtab url is default.");
let defaultHomepageURL = HomePage.get();
equal(defaultHomepageURL, "about:home", "Home page url is default.");
function isDefaultSettings(postfix) {
equal(
HomePage.get(),
defaultHomepageURL,
`Home page url is default ${postfix}.`
);
equal(
AboutNewTab.newTabURL,
defaultNewTab,
`newTabURL is default ${postfix}.`
);
}
function isExtensionSettings(postfix) {
equal(
HomePage.get(),
"https://example.com/",
`Home page url is extension controlled ${postfix}.`
);
ok(
AboutNewTab.newTabURL.endsWith("/newtab"),
`newTabURL is extension controlled ${postfix}.`
);
}
async function switchSafeMode(inSafeMode) {
await AddonTestUtils.promiseShutdownManager();
AddonTestUtils.appInfo.inSafeMode = inSafeMode;
await AddonTestUtils.promiseStartupManager();
return AddonManager.getAddonByID("test@mochi");
}
let xpi = await AddonTestUtils.createTempWebExtensionFile({
manifest: {
version: "1.0",
applications: { gecko: { id: "test@mochi" } },
chrome_url_overrides: {
newtab: "/newtab",
},
chrome_settings_overrides: {
homepage: "https://example.com/",
},
},
});
let extension = ExtensionTestUtils.expectExtension("test@mochi");
await AddonTestUtils.manuallyInstall(xpi);
await AddonTestUtils.promiseStartupManager();
await extension.awaitStartup();
isExtensionSettings("on extension startup");
// Disable in safemode and verify settings are removed in normal mode.
let addon = await switchSafeMode(true);
await addon.disable();
addon = await switchSafeMode(false);
isDefaultSettings("after disabling addon during safemode");
// Enable in safemode and verify settings are back in normal mode.
addon = await switchSafeMode(true);
await addon.enable();
addon = await switchSafeMode(false);
isExtensionSettings("after enabling addon during safemode");
// Uninstall in safemode and verify settings are removed in normal mode.
addon = await switchSafeMode(true);
await addon.uninstall();
addon = await switchSafeMode(false);
isDefaultSettings("after uninstalling addon during safemode");
await AddonTestUtils.promiseShutdownManager();
await AddonTestUtils.cleanupTempXPIs();
});
// There are more settings modules than used in this test file, they should have been
// loaded during the test extensions uninstall. Ensure that all settings modules have
// been loaded.
add_task(async function test_settings_modules_loaded() {
// Test that all settings modules are loaded.
let modules = Array.from(ExtensionParent.apiManager.settingsModules);
ok(modules.length, "we have settings modules");
for (let name of modules) {
ok(ExtensionParent.apiManager.getModule(name).loaded, `${name} was loaded`);
}
}); |
import { AxiosError } from 'axios';
import { SellingPartnerApiAuthError } from './error';
import { axios } from './utils/axios';
export class AccessTokenFactory {
clientId;
clientSecret;
refreshToken;
scopes;
value;
expirationDate;
constructor(parameters) {
this.clientId = parameters.clientId;
this.clientSecret = parameters.clientSecret;
this.refreshToken = parameters.refreshToken;
this.scopes = parameters.scopes;
}
async get() {
if (!this.value || (this.expirationDate && Date.now() >= this.expirationDate.getTime())) {
const body = {
client_id: this.clientId,
client_secret: this.clientSecret,
...(this.refreshToken
? {
grant_type: 'refresh_token',
refresh_token: this.refreshToken,
}
: {
grant_type: 'client_credentials',
scope: this.scopes.join(' '),
}),
};
try {
const { data } = await axios.post('/o2/token', body);
const expiration = new Date();
expiration.setSeconds(expiration.getSeconds() + data.expires_in);
this.value = data;
this.expirationDate = expiration;
}
catch (error) {
if (error instanceof AxiosError) {
throw new SellingPartnerApiAuthError(error);
}
throw error;
}
}
return this.value.access_token;
}
} |
div.single-attachment(
[class.deprecated]="attachment.get('is_deprecated')",
*ngIf="attachment.get('id')",
)
.attachment-name
tg-attachment-link([attachment]="attachment", (preview)="preview.emit($event)")
tg-svg(svg-icon="icon-attachment")
span {{attachment.get('name')}}
.attachment-comments(*ngIf="!editable && attachment.get('description')")
span.deprecated-file(*ngIf="attachment.get('is_deprecated')") {{'ATTACHMENT.DEPRECATED' | translate}}
span {{attachment.get('description')}}
.attachment-size
span {{attachment.get('size') | sizeFormat}}
form.editable-attachment(
*ngIf="editable",
(ngSubmit)="updateAttachment()",
[formGroup]="attachmentForm"
)
.editable.editable-attachment-comment
// tg-auto-select,
input(
type="text",
name="description",
maxlength="140",
formControlName="description",
[placeholder]="'ATTACHMENT.DESCRIPTION' | translate"
)
.editable.editable-attachment-deprecated
input(
type="checkbox",
name="is-deprecated",
formControlName="isDeprecated",
id="attach-{{attachment.get('id')}}-is-deprecated"
)
label.is_deprecated(
for="attach-{{attachment.get('id')}}-is-deprecated",
translate="ATTACHMENT.DEPRECATED_FILE"
)
.attachment-settings
// tg-loading="attachment.get('loading')"
div
a.editable-settings.e2e-save(
[title]="'COMMON.SAVE' | translate",
(click)="updateAttachment($event, description.value, isDeprecated.value)"
)
tg-svg(svg-icon="icon-save")
div
a.editable-settings.e2e-cancel(
[title]="'COMMON.CANCEL' | translate",
(click)="editMode(false)"
)
tg-svg(svg-icon="icon-close")
// tg-check-permission="modify_{{vm.type}}"
.attachment-settings(*ngIf="!editable")
a.settings.e2e-edit(
[title]="'COMMON.EDIT' | translate",
(click)="editMode(true)"
)
tg-svg.drag(svg-icon="icon-edit")
a.settings.e2e-delete(
[title]="'COMMON.DELETE' | translate",
(click)="delete.emit(attachment.get('id'))"
)
tg-svg.drag(svg-icon="icon-trash")
a.settings([title]="'COMMON.DRAG' | translate")
tg-svg.drag(svg-icon="icon-drag") |
import fs from 'fs-extra';
import { exec, spawn, SpawnOptions } from 'child_process';
import path from 'path';
import { Driver, PackageManager } from './types';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import gradient from 'gradient-string';
import chalk from 'chalk';
export function intro(warn = false) {
console.log(gradient.fruit('\n\n🔥 Welcome to Twify!\n'));
console.log(
chalk.blue.bold('- A tool to help you setup your project with TailwindCSS.')
);
if (warn) {
console.log(
chalk.underline.yellow.bold(
`\n❯ It might reconfigure any existing setup you might have.\n❯ It is advised to be used in a new project.`
)
);
}
}
export function getVersion() {
const __dirname = dirname(fileURLToPath(import.meta.url));
const pkg = fs.readJsonSync(join(__dirname, '../package.json'));
return pkg.version;
}
export function detectFramework(): Driver | undefined {
const { dependencies = {}, devDependencies = {} } = fs.readJsonSync(
path.join(process.cwd(), 'package.json')
);
if (dependencies['next']) return 'NextJS';
if (dependencies['@remix-run/react']) return 'Remix';
if (dependencies['nuxt']) return 'Nuxt2';
if (dependencies['@angular/core']) return 'Angular';
if (dependencies['react-scripts']) return 'CreateReactApp';
if (dependencies['solid-js']) return 'Solid';
if (devDependencies['laravel-vite-plugin']) return 'LaravelVite';
if (devDependencies['@sveltejs/kit']) return 'SvelteKit';
if (devDependencies['nuxt']) return 'Nuxt3';
if (devDependencies['vite']) return 'Vite';
}
export function installerPrefix(manager?: PackageManager): string {
const npm = 'npm install --save-dev';
const yarn = 'yarn add --dev';
const pnpm = 'pnpm install --save-dev';
switch (manager) {
case 'npm':
return npm;
case 'yarn':
return yarn;
case 'pnpm':
return pnpm;
default:
return fs.existsSync(path.join(process.cwd(), 'yarn.lock')) ? yarn : npm;
}
}
export function runCommandSpawn(command: string, options: SpawnOptions = {}) {
return new Promise((resolve, reject) => {
const result = spawn(command, options);
result.on('close', async () => {
resolve(true);
});
result.on('error', (err) => {
reject(err);
});
});
}
export function runCommand(cmd: string) {
return new Promise((resolve, reject) => {
exec(cmd, { cwd: process.cwd() }, (err, stdout) => {
if (err) {
reject(err);
} else {
resolve(stdout);
}
});
});
} |
import * as React from "react";
import {
AppBar,
Card,
CardContent,
CardHeader,
Grid,
Link,
makeStyles,
Toolbar,
Typography,
} from "@material-ui/core";
import {Hrefs} from "lib/Hrefs";
const useStyles = makeStyles((theme) => ({
brand: {
marginRight: theme.spacing(4),
},
brandColor: {
color: theme.palette.common.white,
},
card: {
marginLeft: theme.spacing(4),
marginRight: theme.spacing(4),
},
cardHeader: {
textAlign: "center",
},
footerParagraph: {
textAlign: "center",
},
navLink: {
color: "white",
fontSize: "larger",
marginRight: theme.spacing(4),
textDecoration: "none",
},
}));
export const Layout: React.FunctionComponent<{
cardTitle?: React.ReactNode;
children: React.ReactNode;
className?: string;
}> = ({cardTitle, children}) => {
const classes = useStyles();
return (
<>
<Grid container direction="column" spacing={2}>
<Grid item>
<AppBar position="static">
<Toolbar>
<Typography variant="h6" className={classes.brand}>
<Link className={classes.brandColor} href={Hrefs.home}>
DressDiscover
</Link>
</Typography>
<Link className={classes.navLink} href={Hrefs.collections}>
Collections
</Link>
<Link className={classes.navLink} href={Hrefs.worksheet}>
Worksheet
</Link>
</Toolbar>
</AppBar>
</Grid>
<Grid item>
<Card className={classes.card}>
{cardTitle ? (
<CardHeader className={classes.cardHeader} title={cardTitle} />
) : null}
<CardContent>{children}</CardContent>
</Card>
</Grid>
<Grid item>
<footer>
<p className={classes.footerParagraph}>
<Link href={Hrefs.contact}>Contact</Link>
|
<Link href={Hrefs.gitHub}>GitHub</Link>
</p>
</footer>
</Grid>
</Grid>
</>
);
}; |
<template>
<div class="app-container">
<el-form label-width="120px">
<el-form-item label="Banner名称">
<el-input v-model="banner.title" />
</el-form-item>
<el-form-item label="Banner排序">
<el-input-number v-model="banner.sort" controls-position="right" :min="0" />
</el-form-item>
<!-- Banner轮播图 -->
<el-form-item label="Banner轮播图">
<!-- 头衔缩略图 -->
<pan-thumb :image="String(banner.imageUrl)" />
<!-- 文件上传按钮 -->
<el-button type="primary" icon="el-icon-upload" @click="imagecropperShow = true">更换Banner
</el-button>
<!--
v-show:是否显示上传组件
:key:类似于id,如果一个页面多个图片上传控件,可以做区分
:url:后台上传的url地址
@close:关闭上传组件
@crop-upload-success:上传成功后的回调
<input type="file" name="file"/>
-->
<image-cropper
v-show="imagecropperShow"
:width="1200"
:height="480"
:key="imagecropperKey"
:url="BASE_API + '/eduoss/fileoss'"
field="file"
@close="close"
@crop-upload-success="cropSuccess" />
</el-form-item>
<el-form-item>
<el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import banner from '@/api/cms/banner'
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
export default {
components: { ImageCropper, PanThumb },
data() {
return {
banner: {
title: '',
sort: 0,
imageUrl:'',
},
imagecropperShow: false,
imagecropperKey: 0, //上传组件key值
BASE_API: process.env.BASE_API, //获取dev.env.js里面地址
saveBtnDisabled: false,
}
},
created() {
this.init()
},
watch: { //监听
$route(to, from) {//路由变化的方式,路由发生变化,方法就会被执行
this.init()
}
},
methods: {
//关闭上传弹框的方法
close(){
this.imagecropperShow=false
//上传失败后,重新打开上传组件时初始化组件,否则显示上一次的上传结果
this.imagecropperKey=this.imagecropperKey+1
},
//上传成功的回调方法
cropSuccess(data){
this.imagecropperShow=false
//上传之后接口返回图片地址
this.banner.imageUrl=data.url
//上传失败后,重新打开上传组件时初始化组件,否则显示上一次的上传结果
this.imagecropperKey=this.imagecropperKey+1
},
init(){
//判断路径是否有id值, 有id值做修改
if (this.$route.params && this.$route.params.id) {
//从路径获取id值
const id = this.$route.params.id
//调用根据id查询的方法
this.getInfo(id)
} else { //路径没有id值 做添加
//清空表单
this.banner = {
}
}
},
//根据bannerid查询方法
getInfo(id) {
banner.getBanner(id)
.then(response => {
this.banner = response.data.banner
})
},
//添加banner
saveBanner(){
banner.addBanner(this.banner)
.then(response => { //添加成功
//提示信息
this.$message({
type: 'success',
message: '添加成功!'
});
//回到列表页面, 路由跳转
this.$router.push({ path: '/banner/list' })
})
},
//修改banner
updateBannerInfo(){
banner.updateBannerInfo(this.banner)
.then(response=>{
//提示信息
this.$message({
type: 'success',
message: '修改成功!'
});
//回到列表页面, 路由跳转
this.$router.push({ path: '/banner/list' })
})
},
saveOrUpdate(){
//判断是修改还是添加
//根据banner是否有id
if (!this.banner.id) {
//添加
this.saveBanner()
} else {
//修改
this.updateBannerInfo()
}
},
}
}
</script> |
import time
#!/usr/bin/env python
import cv2
import numpy as np
import json
from typing import List
from Models.MotorCommand import MotorCommand
import websocket
import threading
from simple_pid import PID
FRAME_W = 1920 // 3
FRAME_H = 1080 // 3
WEBSOCKET_SERVER_URL = "ws://192.168.50.10:8000/adam-2.7/off-board"
class WebSocketClient:
def __init__(self):
self.ws = None
self.is_connected = False
self.lock = threading.Lock()
def connect(self):
with self.lock:
if self.is_connected:
return
try:
self.ws = websocket.WebSocketApp(
WEBSOCKET_SERVER_URL,
on_open=self.on_open,
on_message=self.on_message,
on_close=self.on_close,
on_error=self.on_error,
)
self.is_connected = True
thread = threading.Thread(target=self.ws.run_forever)
thread.daemon = True
thread.start()
except Exception as e:
print("Failed to connect:", e)
def disconnect(self):
with self.lock:
if self.is_connected:
self.ws.close()
self.is_connected = False
def send_data(self, data):
with self.lock:
if self.is_connected:
data = json.dumps(data.__dict__, default=lambda x: x.__dict__)
self.ws.send(data)
def on_open(self, ws):
print("WebSocket connection opened.")
def on_message(self, ws, message):
# Handle any incoming messages from the WebSocket server, if needed.
pass
def on_close(self, ws, close_status_code, close_msg):
print("WebSocket connection closed:", close_status_code, close_msg)
self.is_connected = False
def on_error(self, ws, error):
print("WebSocket error:", error)
self.is_connected = False
class SerializableCommands:
motors: List[MotorCommand]
def __init__(self, motors: List[MotorCommand]) -> None:
self.motors = motors
# Generate a list of SerializableCommands objects
serializable_commands_list = []
def jsonCommandList(Head):
command_list = [MotorCommand("head", Head[0]),
MotorCommand("neck", Head[1])]
serializable_commands = SerializableCommands(command_list)
return (serializable_commands)
class DataGenerator:
def __init__(self):
self.frame_count = 0
def generate_data(self, HeadPercent):
serializable_commands = jsonCommandList(HeadPercent)
return serializable_commands
def frame_change_handler(HeadPercent):
# Update frame count in the data dictionary
data = data_generator.generate_data(HeadPercent)
# Send data to the WebSocket server
websocket_client.send_data(data)
# Create an instance of the WebSocketClient class
websocket_client = WebSocketClient()
data_generator = DataGenerator()
def sign(x):
return 1 if x > 0 else -1 if x < 0 else 0
def main():
PIDW = PID(0.05, 0.005, 0.0025)
PIDH = PID(0.07, 0.007, 0.0035)
PIDW.setpoint = 0.15
PIDH.setpoint = 0.15
PIDW.output_limits = (-50, 50)
PIDH.output_limits = (-50, 50)
PIDW.sample_time = 0.00001
PIDH.sample_time = 0.00001
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture("http://192.168.50.10:18000/stream/0.mjpeg")
#cap = cv2.VideoCapture(0)
no_move_zone_size = 5
pan_percent = 50 # Initial pan (left-right) position percentage
tilt_percent = 50 # Initial tilt (up-down) position percentage
HeadPercent = [pan_percent, tilt_percent]
frame_change_handler(HeadPercent)
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, (FRAME_W, FRAME_H))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
if len(faces) > 0:
(x, y, w, h) = faces[0]
center_face = (x + w // 2, y + h // 2)
center_image = (frame.shape[1] // 2, frame.shape[0] // 2)
cv2.line(frame, center_image, center_face, (0, 255, 255), 1)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)
distance_to_center = ((center_face[0] - center_image[0])**2 + (center_face[1] - center_image[1])**2)**0.5
cv2.rectangle(frame, (center_image[0] - no_move_zone_size, center_image[1] + no_move_zone_size),
(center_image[0] + no_move_zone_size, center_image[1] - no_move_zone_size), (0, 255, 255), 1)
if distance_to_center <= no_move_zone_size:
cv2.putText(frame, "No Move Zone", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
else:
# Get the centre of the face
x = x + (w / 2)
y = y + (h / 2)
# Correct relative to centre of image
turn_x = float(x - (FRAME_W / 2))
turn_y = float(y - (FRAME_H / 2))
# Convert to percentage offset
turn_x /= float(FRAME_W / 2)
turn_y /= float(FRAME_H / 2)
# Scale offset to degrees (that 2.5 value below acts like the Proportional factor in PID)
turn_x *= 100 # VFOV
turn_y *= 100 # HFOV
controlX = PIDW(turn_x)
controlY = PIDH(turn_y)
pan_percent -=controlX
tilt_percent += controlY
print("Pan percent:", pan_percent,"Tilt percent:", tilt_percent,"\f")
HeadPercent = [tilt_percent, pan_percent]
frame_change_handler(HeadPercent)
cv2.imshow('Face Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
websocket_client.connect()
main() |
from src.feature_engineering.exponential_smoothing_numba import ExponentialSmoother
from src.load_dataframe.data_loader import DataLoader
import numpy as np
import pandas as pd
from datetime import timedelta, datetime
from typing import Iterator, List
import time
from src.pipelines.pipeline_elements.filter import Filter
from src.pipelines.pipeline_elements.pipeline_element import PipelineElement
SMOOTH_COL_PREFIX = 'smooth_'
SMOOTH_COL_SIGMA2_PREFIX = 'smooth_sigma2_'
class FeatureEngineeringPipeline(PipelineElement):
def __init__(self, steps: List[PipelineElement] = None):
PipelineElement.__init__(self)
if steps is None:
self.steps = [Filter(lambda row: row['currency_pair'] == 'XBT/EUR'),
AddTimeAsFloat(),
#AddTimeFeatures(),
AddTimeDifference(),
#AddModulo(100),
#AddModulo(1000),
Smooth(nb_smoothers=2, nb_seconds_min=60 * 10, nb_seconds_max=60 * 60 * 24 * 30),
#AddDifferencesSmoothWithConversionRate()
]
else:
self.steps = steps
def __call__(self, iterator:Iterator[pd.Series]):
for step in self.steps:
iterator = step(iterator)
return iterator
def transform_dataframe(self, df:pd.DataFrame):
for step in self.steps:
df = step.transform_dataframe(df)
return df
class AddTimeAsFloat(PipelineElement):
def __call__(self, iterator:Iterator[pd.Series]):
PipelineElement.__init__(self)
for row in iterator:
row['time_as_float'] = self.convert_pandas_timestamp_to_float(row['time'])
yield row
def transform_dataframe(self, df:pd.DataFrame):
df['time_as_float'] = df['time'].map(self.convert_pandas_timestamp_to_float)
return df
def convert_pandas_timestamp_to_float(self, time:datetime):
return time.timestamp()
#return time.to_pydatetime().timestamp() # seconds
class AddTimeDifference(PipelineElement):
def __call__(self, iterator:Iterator[pd.Series]):
PipelineElement.__init__(self)
row = next(iterator)
previous_time = row['time']
for row in iterator:
row['time_difference'] = row['time'] - previous_time
previous_time = row['time']
yield row
def transform_dataframe(self, df:pd.DataFrame):
df = df.copy()
previous_time = df['time'].shift(1)
df['time_difference'] = df['time'] - previous_time
return df.iloc[1:].copy()
class Smooth(PipelineElement):
def __init__(self, nb_seconds_min=5, nb_seconds_max= 60 * 60 * 24 * 3, nb_smoothers=100):
PipelineElement.__init__(self)
self.smoother = ExponentialSmoother(
times_to_divide_by_e=np.exp(np.linspace(np.log(nb_seconds_min), np.log(nb_seconds_max), num=nb_smoothers)).astype(np.float32)
)
self.nanoseconds_in_one_second = 10.0**9
self.nb_smoothers = nb_smoothers
self.nb_seconds_max = nb_seconds_max
def transform_dataframe(self, df:pd.DataFrame):
df = df.copy()
df = df.reset_index(drop=True)
df_smooth = self.smooth(df)
df_no_burn_in = self.remove_burn_in_data(df_smooth)
return df_no_burn_in
def __call__(self, iterator:Iterator[pd.Series]):
t0 = None
for row in iterator:
if t0 is None:
t0 = row['time']
y = self.smoother.smooth_array(np.array([row['conversion_rate']], dtype=np.float32),
np.array([row['time_difference'].total_seconds()], dtype=np.float32))
if True or row['time'] - t0 > timedelta(seconds=self.nb_seconds_max):
for i in range(len(y[0])):
row[SMOOTH_COL_PREFIX + str(i)] = y[0][i]
yield row
else:
pass # way to remove burn in data
def smooth(self, df):
values = df['conversion_rate'].values.astype(np.float32)
time_difference = df['time_difference'].values.astype(np.float32) / self.nanoseconds_in_one_second
smoothed_values = self.smoother.smooth_array(values, time_difference)
smooth_conversion_rate = pd.DataFrame(data=smoothed_values, columns=[SMOOTH_COL_PREFIX + str(i) for i in range(self.nb_smoothers)])
return pd.merge(df, smooth_conversion_rate, left_index=True, right_index=True)
def remove_burn_in_data(self, df):
t0 = df.iloc[0]['time']
to_keep = df['time'] - t0 > timedelta(seconds=self.nb_seconds_max)
return df[to_keep]
class AddModulo:
def __init__(self, modulo):
assert isinstance(modulo, int)
PipelineElement.__init__(self)
self.modulo = modulo
def __call__(self, iterator:Iterator[pd.Series]):
for row in iterator:
row['modulo_' + str(self.modulo) + "_cos"] = np.cos(2 * np.pi * (row['conversion_rate'] % self.modulo) / self.modulo)
row['modulo_' + str(self.modulo) + "_sin"] = np.sin(2 * np.pi * (row['conversion_rate'] % self.modulo) / self.modulo)
yield row
def transform_dataframe(self, df):
df['modulo_' + str(self.modulo) + "_cos"] = np.cos(2 * np.pi * (df['conversion_rate'] % self.modulo) / self.modulo)
df['modulo_' + str(self.modulo) + "_sin"] = np.sin(2 * np.pi * (df['conversion_rate'] % self.modulo) / self.modulo)
return df
class AddDifferencesSmoothWithConversionRate:
def __call__(self, iterator:Iterator[pd.Series]):
column_names = []
for row in iterator:
if column_names == []:
column_names = [column for column in row.index if column[:len(SMOOTH_COL_PREFIX)] == SMOOTH_COL_PREFIX]
for column_name in column_names:
row['diff_' + column_name] = row['conversion_rate'] - row[column_name]
yield row
def transform_dataframe(self, df:pd.DataFrame):
column_names = [column for column in df.columns if column[:len(SMOOTH_COL_PREFIX)] == SMOOTH_COL_PREFIX]
for column_name in column_names:
df['diff_' + column_name] = df["conversion_rate"] - df[column_name]
return df
class AddTimeFeatures(PipelineElement):
def __init__(self):
self.functions = {
"time_feature_hour_cos": lambda time: np.cos(2 * np.pi * time.hour / 24),
"time_feature_hour_sin": lambda time: np.sin(2 * np.pi * time.hour / 24),
"time_feature_minute_cos": lambda time: np.cos(2 * np.pi * time.minute / 60),
"time_feature_minute_sin" : lambda time: np.sin(2 * np.pi * time.minute / 60),
"time_feature_weekday_cos" : lambda time: np.cos(2 * np.pi * time.isoweekday() / 7),
"time_feature_weekday_sin" : lambda time: np.sin(2 * np.pi * time.isoweekday() / 7)
}
def __call__(self, iterator:Iterator[pd.Series]):
for row in iterator:
time = row['time']
for feature_name, function in self.functions.items():
row[feature_name] = function(time)
yield row
def transform_dataframe(self, df:pd.DataFrame):
for feature_name, function in self.functions.items():
df[feature_name] = df['time'].map(function)
return df
if __name__ == "__main__":
dataframes = DataLoader().load().get_uninterrupted_datasets()
print(dataframes[0])
print(list(dataframes[0].columns)) |
import java.util.ArrayList;
public class SimpleCollection {
private String name;
private ArrayList<String> elements;
public SimpleCollection(String name) {
this.name = name;
this.elements = new ArrayList<>();
}
public void add(String element) {
this.elements.add(element);
}
public ArrayList<String> getElements() {
return this.elements;
}
@Override
public String toString() {
if (elements.isEmpty()) {
return "The collection " + name + " is empty.";
}
if (elements.size() == 1) {
return "The collection " + name + " has 1 element:" + '\n' + elements.get(0);
}
String message = "The collection " + name + " has " + elements.size() + " elements:" + '\n';
message = elements.stream().map((element) -> element + '\n').reduce(message, String::concat);
return message;
}
} |
import React from 'react';
import axios from 'axios';
import { useState } from 'react';
import { useEffect } from 'react';
function Trending() {
const [trending, setTrending] = useState([]);
const url = 'https://api.coingecko.com/api/v3/search/trending';
useEffect(() => {
axios.get(url).then(res => {
setTrending(res.data.coins);
// console.log(res.data);
});
}, []);
return (
<div className='font-roboto rounded-div py-8 text-primary'>
<h1 className='text-2xl font-bold py-4'>Trending Coins</h1>
<div className='grid md:grid-cols-2 lg:grid-cols-3 gap-4'>
{trending.map((coin, idx) => (
<div
key={idx}
className='rounded-div flex justify-between p-4 hover:scale-105 ease-in-out duration-300'
>
<div className='flex w-full items-center justify-between'>
<div className='flex'>
<img
className='mr-4 rounded-div'
src={coin.item.small}
alt='/'
/>
<div>
<p className='font-bold '>{coin.item.name}</p>
<p>{coin.item.symbol}</p>
</div>
</div>
<div className='flex items-center'>
<img
className='w-4 mr-2'
src='https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579'
alt='/'
/>
<p>{coin.item.price_btc.toFixed(7)}</p>
</div>
</div>
</div>
))}
</div>
</div>
);
}
export default Trending; |
package org.anime_game_servers.gi_lua.script_lib.handler.entites
import org.anime_game_servers.gi_lua.script_lib.GroupEventLuaContext
/**
* Handler for scriptlib functions used in GroupScripts related to Gadgets.
* These are only callable from a gadget controller context.
*/
interface GroupGadgetHandler<GroupEventContext : GroupEventLuaContext> {
/**
* Returns the state of a gadget based on the group id and config id
* @param context The context of the group event
* @param groupId group to search for the gadget in, 0 for the caller group.
* @param configId config id of the gadget in the group.
*/
fun GetGadgetStateByConfigId(context: GroupEventContext, groupId: Int, configId: Int): Int
/**
* Returns the hp in percent of a gadget based on the group id and config id
* @param context The context of the group event
* @param groupId group to search for the gadget entity in, 0 for the caller group.
* @param configId config id of the gadget in the group.
*/
fun GetGadgetHpPercent(context: GroupEventContext, groupId: Int, configId: Int): Int
/**
* Returns a float global value from the gadgets ability definitions.
* @param context The context of the group event
* @param groupId group to search for the gadget entity in, 0 for the caller group.
* @param configId config id of the gadget in the group.
* @param abilitySGVName name of the abilities svg value to get the float value from.
* */
fun GetGadgetAbilityFloatValue(
context: GroupEventContext,
groupId: Int,
configId: Int,
abilitySGVName: String
): Float
/**
* Retrieves and returns the gadget id of a gadget entity based on the entity id.
* @param context The context of the group event
* @param entityId The entity id of the gadget requested.
*/
fun GetGadgetIdByEntityId(context: GroupEventContext, entityId: Int): Int
/**
* Returns the config id of the gadget with the eid (gadget_eid)
* @param context The context of the group event
* @param gadgetEid The entity id of the gadget requested. Table with `gadget_eid` in lua.
*/
fun GetGadgetConfigId(context: GroupEventContext, gadgetEid: Int): Int
/**
* Change the state of a gadget in the defined group
* @param context The context of the group event
* @param groupId The group containing the target gadget or the caller group if 0
* @param configId config id of a gadget in the target group
* @param gadgetState target state for the gadget
*/
fun SetGroupGadgetStateByConfigId(context: GroupEventContext, groupId: Int, configId: Int, gadgetState: Int): Int
/**
* Change the state of a gadget in the current group
* @param context The context of the group event
* @param configId config id of a gadget in the current caller group
* @param gadgetState target state for the gadget
*/
fun SetGadgetStateByConfigId(context: GroupEventContext, configId: Int, gadgetState: Int): Int
/**
* Change the state of a gadget in the current group, based in the parametersTable
* @param context The context of the group event
* @param configId config id of a gadget in the current caller group
* @param gadgetState target state for the gadget
*/
fun ChangeGroupGadget(context: GroupEventContext, configId: Int, gadgetState: Int): Int
/**
* // TODO identify unknown parameters and exact behaviour
* Executes a lua function on a gadgets lua controller.
* This seems to be used in only the Crucible activity
* @param groupId group to find the gadget in
* @param gadgetCfgId cfg id of the gadget in the group to execute lua in
* @param activityType seems to be an activity type
* @param var4 TODO
* @param val5 TODO
*/
fun ExecuteGadgetLua(
context: GroupEventContext, groupId: Int, gadgetCfgId: Int,
activityType: Int, var4: Int, val5: Int
): Int
} |
#!/usr/bin/env Rscript
#################################################################
# #
# This script takes a tab-separated text file as #
# input, performs a survival test to give a p value, #
# produces a HR and a kaplan-meier style survival #
# curve grapgh (pdf) #
# Must have the following columns; #
# Days.OS = Days of overall survival #
# Treatment = Treatment given #
# Death_Binary = Death (1) or Censor (0) #
# Variant Summary = Unique variant descriptor #
# #
# Made for R v3.1.2 #
# #
#################################################################
##### Load the required packages #####
y <- c("survival", "tools", "survcomp", "plyr")
lapply(y, require, character.only = TRUE)
##### Take the file location from the command line argument #####
args <- commandArgs(trailingOnly = TRUE)
survival.file <- read.delim(args[1]) # Add the file to the command argument
##### Get the file name #####
filename <- basename(survival.file) # remove extension
region_header <- file_path_sans_ext(filename) # directory
dir <- dirname(survival.file)
##### Treatment into binary #####
treatment <- as.numeric(survival.file$Treatment)
survival.file["treatment_codes"] <- NA
survival.file$treatment_codes <- treatment
survival.file$treatment_codes[survival.file$treatment_codes == 1] <- 0
survival.file$treatment_codes[survival.file$treatment_codes == 2] <- 1
##### Split the input file by variant into list #####
spilt.by.variant <- split(survival.file, f = survival.file$Variant.Summary, drop=TRUE)
##### Assign first element in list to variable then remove it from list #####
write(paste("Variant", "p.value", "hazard.ratio", "Docetaxel Patients", "Docetaxel + Ganetespib Patients", sep = '\t'), file=file.out, append=FALSE)
for (i in 1:length(spilt.by.variant)){
if (length(spilt.by.variant[[i]]$Variant.Summary)>10) {
pdf(file.path(dir, paste(spilt.by.variant[[i]]$Variant.Summary, "pdf", sep = ".")))
plot(survfit(Surv(spilt.by.variant[[i]]$Days.OS, spilt.by.variant[[i]]$Death_Binary == 1) ~ spilt.by.variant[[i]]$treatment_codes),
main = spilt.by.variant[[i]]$Variant.Summary[1],
col.main = "black", xlab = "Time in days",
ylab = "Overall Survival Proportion",
col.lab= "blue", cex.lab = 0.9, mark = "+",
col = c(2, 4), lty = 2:3)
legend(300, 1.0, c("Docetaxel 75 mg/m2", "Ganetespib 150 mg/m2 in combination with Docetaxel 75 mg/m2"), cex = 0.6, lty = 2:3, col = c(2, 4))
dev.off()
sd <- survdiff(Surv(spilt.by.variant[[i]]$Days.OS) ~ spilt.by.variant[[i]]$treatment_codes, rho = 1) # Peto & Peto modification of the Gehan-Wilcoxon test
p.val <- 1 - pchisq(sd$chisq, length(sd$n) - 1) # Work out the p-value from the log rank test
my.hz <- hazard.ratio(x = spilt.by.variant[[i]]$treatment_codes, surv.time = spilt.by.variant[[i]]$Days.OS, surv.event = spilt.by.variant[[i]]$Death_Binary) # Hazard Ratio
treatment.coxph <- coxph(Surv(spilt.by.variant[[i]]$Days.OS, spilt.by.variant[[i]]$Death_Binary == 1) ~ spilt.by.variant[[i]]$treatment_codes, method = "efron")
fit1 <- coxph(Surv(spilt.by.variant[[i]]$Days.OS,spilt.by.variant[[i]]$Death_Binary) ~ spilt.by.variant[[i]]$treatment_codes)
output <- paste(spilt.by.variant[[i]]$Variant.Summary[1], p.val, my.hz$hazard.ratio, sum(spilt.by.variant[[i]]$Treatment=="Docetaxel"), sum(spilt.by.variant[[i]]$Treatment=="Ganetespib + Docetaxel"), sep = '\t')
my.outfile <- "logrank.txt"
file.out <- file.path("~/Desktop/output", my.outfile)
write(output, file=file.out, append=TRUE)
}
} |
import { async } from 'citation-js'
import React from 'react'
import { useQuery } from 'react-query'
import axios from 'axios';
import { Chart } from 'primereact/chart';
import PieChartData from '../Analytics/PieChartData';
import LineChart from '../Analytics/LineChart';
function Analytics() {
var department = [];
var total = [];
var deptcolor = [];
const query = useQuery('all', async () => {
const data = await axios.get(`/api/AllAccountsSchoolYearstaff`);
return data;
}, {
})
if (query.isLoading) {
return <h4>Loading</h4>
}
for (let index = 0; index < query.data.data.details.length; index++) {
const element = query.data.data.details[index].department_code;
const countdata = query.data.data.details[index].total;
const colorcode = query.data.data.details[index].color;
department.push(element);
total.push(countdata);
deptcolor.push(colorcode);
}
const basicData = {
labels: department,
datasets: [
{
label: 'Department Account',
backgroundColor: deptcolor,
data: total,
},
]
};
const getLightTheme = () => {
let basicOptions = {
maintainAspectRatio: false,
aspectRatio: .8,
plugins: {
legend: {
labels: {
color: 'white'
}
}
},
scales: {
x: {
ticks: {
color: '#d4d4d4'
},
grid: {
color: 'transparent'
}
},
y: {
ticks: {
color: '#d4d4d4'
},
grid: {
color: 'transparent'
}
}
}
};
return {
basicOptions,
}
}
const { basicOptions } = getLightTheme();
return (
<div>
<div className="container">
<div className="row justify-content-space align-items-center">
<div className="col-lg-12">
<LineChart />
</div>
<div className="col-lg-6">
<PieChartData />
</div>
<div className="col-lg-6">
<Chart type="bar" data={basicData} options={basicOptions} />
</div>
</div>
</div>
</div>
)
}
export default Analytics |
import { Injectable } from '@angular/core';
import { BehaviorSubject, debounceTime, Subject } from 'rxjs';
import { Character, SlormancerCharacterUpdaterService, valueOrDefault, valueOrNull } from 'slormancer-api';
import { environment } from '../../../../environments/environment';
import { Build } from '../model/build';
import { BuildPreview } from '../model/build-preview';
import { Layer } from '../model/layer';
import { BuildRetrocompatibilityService } from './build-retrocompatibility.service';
import { JsonConverterService } from './json-converter.service';
@Injectable({ providedIn: 'root' })
export class BuildStorageService {
private readonly MAX_LAYERS = 10;
private readonly BUILDS_STORAGE_KEY = 'builds';
private readonly CURRENT_BUILD_STORAGE_KEY = 'current-build';
private readonly CURRENT_LAYER_STORAGE_KEY = 'current-layer';
private builds: Array<BuildPreview> = [];
private build: Build | null = null;
private layer: Layer | null = null;
public readonly buildChanged = new BehaviorSubject<Build | null>(null);
public readonly layerChanged = new BehaviorSubject<Layer | null>(null);
public readonly saveTrigger = new Subject<void>();
constructor(private jsonConverterService: JsonConverterService,
private buildRetrocompatibilityService: BuildRetrocompatibilityService,
private slormancerCharacterUpdaterService: SlormancerCharacterUpdaterService) {
this.reload();
this.oldFormatTransition();
this.saveTrigger
.pipe(debounceTime(500))
.subscribe(() => this.saveToStorage());
}
private getCurrentLayerIndex(): number {
const storageData = localStorage.getItem(this.CURRENT_LAYER_STORAGE_KEY);
const index = storageData === null ? 0 : parseInt(storageData, 10);
return Number.isNaN(index) ? 0 : index;
}
private oldFormatTransition() {
const oldKey = 'slorm-planner-build';
const oldData = localStorage.getItem(oldKey);
if (oldData !== null && this.builds.length === 0) {
const build = this.jsonConverterService.jsonToBuild(JSON.parse(oldData))
this.addBuild(build);
localStorage.removeItem(oldKey);
this.saveToStorage();
}
}
private reload() {
this.builds = [];
this.build = null;
this.layer = null;
try {
const buildsData = localStorage.getItem(this.BUILDS_STORAGE_KEY);
const buildData = localStorage.getItem(this.CURRENT_BUILD_STORAGE_KEY);
const layerIndex = this.getCurrentLayerIndex();
if (buildsData !== null) {
this.builds = JSON.parse(buildsData);
}
if (buildData !== null) {
const buildContentData = localStorage.getItem(buildData);
if (buildContentData !== null) {
this.build = this.jsonConverterService.jsonToBuild(JSON.parse(buildContentData));
this.buildRetrocompatibilityService.updateToLatestVersion(this.build);
}
}
if (this.build !== null) {
let layer = valueOrDefault(this.build.layers[layerIndex], this.build.layers[0]);
if (layer !== undefined) {
this.layer = layer;
}
for (const layer of this.build.layers) {
this.slormancerCharacterUpdaterService.updateCharacter(layer.character, this.build.configuration);
}
}
} catch (e) {
console.error('Failed to reload build : ', e);
}
this.buildChanged.next(this.build);
this.layerChanged.next(this.layer);
}
private saveToStorage() {
localStorage.setItem(this.BUILDS_STORAGE_KEY, JSON.stringify(this.builds));
const currentKey = localStorage.getItem(this.CURRENT_BUILD_STORAGE_KEY);
if (currentKey !== null && this.build !== null) {
localStorage.setItem(currentKey, JSON.stringify(this.jsonConverterService.buildToJson(this.build)));
let layerIndex = 0;
if (this.layer !== null) {
layerIndex = this.build.layers.indexOf(this.layer);
}
localStorage.setItem(this.CURRENT_LAYER_STORAGE_KEY, layerIndex < 0 ? '0' : layerIndex.toString());
}
}
public saveBuild() {
if (this.build !== null) {
// TODO bouger update
for (const layer of this.build.layers) {
this.slormancerCharacterUpdaterService.updateCharacter(layer.character, this.build.configuration);
}
const buildPreview = this.getBuildPreview();
if (buildPreview !== null) {
buildPreview.name = this.build.name;
}
if (this.build !== null) {
let layerIndex = this.getCurrentLayerIndex();
const currentLayerIndex = this.layer === null ? -1 : this.build.layers.indexOf(this.layer);
layerIndex = currentLayerIndex !== -1 ? currentLayerIndex : Math.min(layerIndex, this.build.layers.length - 1);
this.layer = valueOrNull(this.build.layers[layerIndex]);
}
this.saveTrigger.next();
this.buildChanged.next(this.build);
this.layerChanged.next(this.layer);
}
}
public saveLayer() {
if (this.build !== null && this.layer !== null) {
// TODO bouger update
this.slormancerCharacterUpdaterService.updateCharacter(this.layer.character, this.build.configuration);
this.saveTrigger.next();
}
}
public loadBuild(preview: BuildPreview) {
localStorage.setItem(this.CURRENT_BUILD_STORAGE_KEY, preview.storageKey);
localStorage.setItem(this.CURRENT_LAYER_STORAGE_KEY, '0');
this.reload();
}
public deleteBuild() {
const currentKey = localStorage.getItem(this.CURRENT_BUILD_STORAGE_KEY);
if (currentKey !== null) {
const index = this.builds.findIndex(preview => preview.storageKey === currentKey);
if (index !== -1) {
this.builds.splice(index, 1);
localStorage.removeItem(currentKey)
localStorage.removeItem(this.CURRENT_BUILD_STORAGE_KEY)
this.saveToStorage();
const newIndex = Math.min(index, this.builds.length - 1);
const preview = this.builds[newIndex];
if (preview) {
this.loadBuild(preview);
} else {
this.reload();
}
}
}
}
public loadLayer(layer: Layer) {
if (this.build !== null) {
const layerIndex = this.build.layers.indexOf(layer);
if (layerIndex !== -1) {
this.layer = layer;
this.saveBuild();
}
}
}
public addBuild(build: Build) {
if (build !== null) {
this.buildRetrocompatibilityService.updateToLatestVersion(build);
}
const preview: BuildPreview = {
heroClass: build.heroClass,
name: build.name,
storageKey: 'build-' + new Date().getTime(),
version: environment.version
}
this.builds.push(preview);
this.build = build;
this.layer = valueOrDefault(build.layers[0], null);
localStorage.setItem(this.CURRENT_BUILD_STORAGE_KEY, preview.storageKey);
this.saveBuild();
}
public getBuilds(): Array<BuildPreview> {
return this.builds;
}
public getBuild(): Build | null {
return this.build;
}
public getBuildPreview(): BuildPreview | null {
const currentKey = localStorage.getItem(this.CURRENT_BUILD_STORAGE_KEY);
return valueOrNull(this.builds.find(preview => preview.storageKey === currentKey));
}
public getLayer(): Layer | null {
return this.layer;
}
public hasRoomForAnotherLayer(character: Character | null = null): boolean {
return this.build === null
|| (this.build.layers.length < this.MAX_LAYERS
&& (character === null || this.build.heroClass === character.heroClass));
}
} |
import 'dart:io';
import 'package:corelate/features/breathwork/four_7_8/four_7_8.dart';
import 'package:health/health.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../../services/provider.dart';
import '../../../models/breathwork_model.dart';
import '../../../models/breathwork_type.dart';
import '../../today/today.dart';
import '../wim_hof/wim_hof.dart';
import 'breathwork_setup_view_model.dart';
part 'breathwork_setup.g.dart';
@riverpod
class BreathworkSetup extends _$BreathworkSetup {
@override
BreathworkSetupViewModel build() =>
BreathworkSetupViewModel(BreathworkModel(date: DateTime.now()));
void setType(BreathworkType type) {
final is478 = type == BreathworkType.four78;
final rounds = is478 ? 4 : 3;
final breathsPerRound = is478 ? 0 : 30;
final breathwork = state.breathwork.copyWith(
type: type,
rounds: rounds,
breathsPerRound: breathsPerRound,
holdSecondsPerRound: is478 ? null : [],
);
state = state.copyWith(breathwork: breathwork);
}
void setRounds(int rounds) {
final breathwork = state.breathwork.copyWith(rounds: rounds);
state = state.copyWith(breathwork: breathwork);
}
void setBreathsPerRound(int breathsPerRound) {
final breathwork =
state.breathwork.copyWith(breathsPerRound: breathsPerRound);
state = state.copyWith(breathwork: breathwork);
}
void resetDate() {
final breathwork = state.breathwork.copyWith(date: DateTime.now());
state = state.copyWith(breathwork: breathwork);
}
void setRating(double rating) {
final breathwork = state.breathwork.copyWith(rating: rating);
state = state.copyWith(breathwork: breathwork);
}
void save() {
BreathworkModel breathwork;
if (state.breathwork.type == BreathworkType.four78) {
// TODO: Save 4-7-8 session
final four78 = ref.watch(four78Provider);
breathwork = state.breathwork.copyWith(
rounds: four78.currentRound,
);
} else {
final wimHof = ref.watch(wimHofProvider);
final rounds = wimHof.holdSeconds.length;
breathwork = state.breathwork.copyWith(
holdSecondsPerRound: wimHof.holdSeconds,
rounds: rounds,
);
}
state = state.copyWith(breathwork: breathwork);
ref.read(databaseProvider.future).then((db) async {
await db.saveBreathwork(breathwork);
ref.read(todayProvider.notifier).loadTodaysActivities();
});
if (Platform.isIOS) {
int elapsed;
if (breathwork.type == BreathworkType.four78) {
final four78 = ref.watch(four78Provider);
elapsed = four78.currentRound * 14;
} else {
final wimHof = ref.watch(wimHofProvider);
var holdsElapsed = 0;
for (final hold in wimHof.holdSeconds) {
holdsElapsed += hold;
}
final countsElapsed =
breathwork.rounds * (breathwork.breathsPerRound * 1.5 * 2.0);
final inhalesElapsed = breathwork.rounds * 15;
elapsed = countsElapsed.toInt() + holdsElapsed + inhalesElapsed;
}
ref.read(healthProvider.future).then((health) async {
await health.writeHealthData(
elapsed.toDouble(),
HealthDataType.MINDFULNESS,
state.breathwork.date,
state.breathwork.date.add(Duration(seconds: elapsed)),
);
});
}
}
} |
<h1 align="center">:rocket: Mongoose Paranoid Plugin :rocket:</h1>
<div align="center">
<sub>Built with ❤︎ by
<a href="https://github.com/euqen">Eugene Shilin</a> and
<a href="https://github.com/euqen/mongoose-paranoid-plugin/graphs/contributors">
contributors
</a>
</div>
<br />
This plugin allows to apply soft deletion of mongo db documents. It's simple, lightweight and easy to use. Inspired by Sequelize.
## Philosophy
All existing soft deletion plugins don't allow to disable quering by non-deleted documents. They all require to use their own-implemented methods. Sometimes you need to get all documents including deleted, sometimes you need to retrieve only non-deleted. All existing plugins provide their own separate methods to do this. It's not flexible, you need to call different methods depending on situations you faced with. Introducing soft deletion plugin, it's hide all deleted documents by default, but you are able to find all documents including deleted in several ways. See usage section
## Installation
Install using npm
```
npm install mongoose-paranoid-plugin
```
## Usage
### Enable plugin
```
const mongoose = require('mongoose');
const mongooseParanoidPlugin = require('mongoose-paranoid-plugin');
mongoose.plugin(mongooseParanoidPlugin, { field: 'deleted_at' })
```
Options:
- field: String. Column name which is used to store timestamp of deletion. Default value is 'deletedAt'
### Using in schemas
By default this plugin won't override any methods. To enable soft deletion of your document's you need to pass `paranoid` option into your model options.
```
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
firstName: { type: String },
lastName: { type: String }
}, {
paranoid: true,
});
const User = meta.model('users', schema);
```
This will enable soft deletion of your documents. All deleted models will be marked with `deletedAt` field by default and will not be retrieved by built-in mongoose methods. If you need to include deleted documents you need pass an attribute `{ paranoid: false }` to query options.
```
return User.find(query, {}, { paranoid: false });
```
### Soft deletion behavior
The behavior of remove method is also very explicit. If you enabled soft deletion in your schema, `remove` method will mark the document with deletedAt field. Otherwise the document will be completely removed. You can also use `paranoid` method before removing to enable/disable soft deletion.
## Copyright
Copyright (c) 2017 Eugene Shilin See LICENSE for further details. |
import React from 'react';
export const Icon: React.FC<{
width?: string;
height?: string;
viewBox?: string;
className?: string;
fill?: string;
stroke?: string;
d: string;
}> = ({
width = '24',
height = '24',
viewBox = '0 0 24',
className,
stroke = 'currentColor',
fill = 'none',
d,
}) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill={fill}
viewBox={viewBox}
strokeWidth="2"
width={width}
height={height}
className={className}
stroke={stroke}
>
<path strokeLinecap="round" strokeLinejoin="round" d={d} />
</svg>
);
}; |
import { useEffect, useState } from 'react'
import Box from '@mui/material/Box'
import Divider from '@mui/material/Divider'
import { Region, Family, SpeciesResult } from 'types/Birdism'
import { getAllRegions, getAllFamilies, getSpecies } from 'services'
import SearchResult from 'components/SearchResult'
import SearchErrors from 'components/SearchErrors'
import SearchForm from 'components/SearchForm'
export default function MainSearch() {
const [allRegions, setAllRegions] = useState<Region[]>([])
const [allFamilies, setAllFamilies] = useState<Family[]>([])
const [region, setRegion] = useState<Region | null>(null)
const [family, setFamily] = useState<Family | null>(null)
const [results, setResults] = useState<SpeciesResult[]>([])
const [noResults, setNoResults] = useState<boolean>(false)
const [searching, setSearching] = useState<boolean>(false)
const [searchErrs, setSearchErrs] = useState<string | null>(null)
useEffect(() => {
// fetch regions
getAllRegions().then(setAllRegions)
// fetch families
getAllFamilies().then(setAllFamilies)
}, []);
const runSearch = async () => {
setSearchErrs(null)
if (family === null || region === null) {
setSearchErrs('Please select a region and a family.')
return
}
setSearching(true)
const payload = {
family: family.scientific_name,
region: region.region_code,
}
try {
const data = await getSpecies(payload)
setSearching(false)
setNoResults(false)
setResults(data.result)
if (data.result && !data.result.length) {
setNoResults(true)
return
}
}
catch (err: any) {
console.error('search images error', err)
setSearchErrs(err)
}
finally {
setSearching(false)
}
}
return (
<Box>
<SearchForm
allFamilies={allFamilies}
allRegions={allRegions}
selectedFamily={family}
setSelectedFamily={setFamily}
selectedRegion={region}
setSelectedRegion={setRegion}
searchAction={runSearch}
searching={searching}
/>
<Divider />
<SearchErrors errors={searchErrs} />
<SearchResult results={results} noResults={noResults} />
</Box>
)
} |
import "./globals.css";
import NextTopLoader from "nextjs-toploader";
import Footer from "@/components/shared/Footer";
import Navbar from "@/components/shared/Navbar";
import Contact from "@/components/shared/Contact";
export async function generateMetadata() {
const res = await fetch(process.env.BASE_URL + "SiteMeta/home");
const jsonData = await res.json();
return {
title: jsonData[0].title,
description: jsonData[0].description,
keywords: jsonData[0].keywords,
};
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<NextTopLoader color="#269669" height={4} speed={200} />
<Navbar />
<main>{children}</main>
<Contact />
<Footer />
</body>
</html>
);
} |
import { useReducer } from 'react';
import './style.scss';
// type CounterAction = {
// type: 'INCREMENT' | 'DECREMENT' | 'SET';
// payload?: number;
// };
type BasicCounterAction = {
type: 'INCREMENT' | 'DECREMENT';
};
type ResetCounterAction = {
type: 'SET';
payload: number;
};
type BetterCounterAction = BasicCounterAction | ResetCounterAction;
type CounterState = {
value: number;
};
const reducer = (state: CounterState, action: BetterCounterAction) => {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + 1 };
case 'DECREMENT':
return { value: state.value - 1 };
case 'SET':
// return { value: action.payload || 0 };
return { value: action.payload };
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, { value: 0 });
const increment = () => dispatch({ type: 'INCREMENT' });
const decrement = () => dispatch({ type: 'DECREMENT' });
const reset = () => dispatch({ type: 'SET', payload: 0 });
return (
<main className='Counter'>
<h1>Days Since Last Incident</h1>
<p className='count'>{state.value}</p>
<section className='controls'>
<button onClick={increment}>Increment</button>
<button onClick={reset}>Reset</button>
<button onClick={decrement}>Decrement</button>
</section>
</main>
);
};
const Application = () => <Counter />;
export default Application; |
import axios from "../../utility/axios";
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom';
import './questionDetail.css'
import AnswerQuestion from '../../components/AnswerQuestion/AnswerQuestion';
import Answer from '../../components/answers/Answers';
import { useStateValue } from "../../utility/stateprovider";
import moment from 'moment';
const SingleQuestion = () => {
let params = useParams();
const [{ user }, dispatch] = useStateValue();
const [question, setQuestion] = useState([]);
const [answers, setAnswers] = useState([]);
const navigate = useNavigate();
useEffect(() => {
if (!user) {
navigate('/login');
}
// console.log(user);
}, [user, navigate])
const answersByQuestionId = async () => {
try {
const answersRes = await axios.get(
`/api/answers/:${params.id}`
);
setAnswers(answersRes.data.data);
console.log(answersRes.data.data)
} catch (err) {
console.error("Problem:", err);
}
};
useEffect(() => {
// async function fetchData() {
// try {
// const response = await axios.get(`/api/questions/:${params.id}`);
// setQuestion(response.data.data);
// console.log(response.data.data);
// } catch (err) {
// alert(err);
// console.log("problem", err);
// }
// answersByQuestionId();
// }
async function fetchData() {
try {
const response = await axios.get(`/api/questions/${params.id}`); // Remove the ":" before `${params.id}`
setQuestion(response.data.data);
// console.log(response.data.data);
// Call answersByQuestionId with the fetched data, assuming it takes a single argument
answersByQuestionId(response.data.data);
} catch (err) {
alert(err.message); // Use err.message to display the error message
console.error("Problem:", err);
}
}
// fetchData();
// }, [params.id]);
fetchData();
}, [params.id]);
// console.log(answers);
return (
<div className="container">
<h2>Question</h2>
{/* <p>{question?.question_id}</p> */}
<h4>{question?.question}</h4>
<h5>{question?.category}</h5>
<h5>{question?.question_description}</h5>
<p>{moment(question?.inserted_datetime).format("HH:mm:ss MM/DD/YYYY")}</p>
<hr />
<hr />
<div>{answers.length > 0 && <h3>Answer From The Community</h3>}</div>
{answers && answers?.map((answer) => (
<Answer key={answer?.answer_id} answer={answer?.answer} userName={answer.user_name} profile={answer.image_url} answered_date={ answer.answered_date} />
))}
<AnswerQuestion questionId={question?.question_id}/>
<hr />
</div>
)
}
export default SingleQuestion
// import axios from "../../utility/axios";
// import React, { useEffect, useState } from 'react';
// import { useNavigate, useParams } from 'react-router-dom';
// import './questionDetail.css';
// import AnswerQuestion from '../../components/AnswerQuestion/AnswerQuestion';
// import Answer from '../../components/answers/Answers';
// import { useStateValue } from "../../utility/stateprovider";
// import moment from 'moment';
// const SingleQuestion = () => {
// const params = useParams();
// const [{ user }, dispatch] = useStateValue();
// const [question, setQuestion] = useState({});
// const [answers, setAnswers] = useState([]);
// const navigate = useNavigate();
// useEffect(() => {
// if (!user) {
// navigate('/login');
// }
// }, [user, navigate]);
// useEffect(() => {
// async function fetchData() {
// try {
// const response = await axios.get(`/api/questions/${params.id}`);
// setQuestion(response.data.data);
// console.log(response.data.data);
// } catch (err) {
// console.error("problem", err);
// }
// answersByQuestionId();
// }
// fetchData();
// }, [params.id]);
// const answersByQuestionId = async () => {
// try {
// const answersRes = await axios.get(`/api/answers/${params.id}`);
// setAnswers(answersRes.data.data);
// } catch (err) {
// console.error("problem", err);
// }
// };
// return (
// <div className="container">
// <h2>Question</h2>
// <p>{question?.question_id}</p>
// <h4>{question?.question}</h4>
// <h5>{question?.category}</h5>
// <h5>{question?.question_description}</h5>
// <p>{moment(question?.inserted_datetime).format("HH:mm:ss MM/DD/YYYY")}</p>
// <hr />
// <div>{answers.length > 0 && <h3>Answer From The Community</h3>}</div>
// {answers && answers?.map((answer) => (
// <Answer
// key={answer?.answer_id}
// answer={answer?.answer}
// userName={answer.user_name}
// profile={answer.image_url}
// answered_date={answer.answered_date}
// />
// ))}
// <AnswerQuestion questionId={question?.question_id}/>
// <hr />
// </div>
// );
// };
// export default SingleQuestion; |
/**
* request 网络请求工具
* 更详细的 api 文档: https://github.com/umijs/umi-request
*/
import { extend } from 'umi-request';
import { message } from 'antd';
import { ResponseData } from '@/utils/request';
const codeMessage = {
200: '服务器成功返回请求的数据。',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)。',
204: '删除数据成功。',
400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
401: '用户没有权限(令牌、用户名、密码错误)。',
403: '用户得到授权,但是访问是被禁止的。',
404: '请求页面不存在',
405: '服务器禁止了使用当前 HTTP 方法的请求',
406: '请求的格式不可得。',
410: '请求的资源被永久删除,且不会再得到的。',
422: '当创建一个对象时,发生一个验证错误。',
500: '服务器发生错误,请检查服务器。',
502: '网关错误。',
503: '服务不可用,服务器暂时过载或维护。',
504: '网关超时。',
};
/**
* 异常处理程序
*/
const errorHandler = (error: { response: Response }): Response => {
const { response } = error;
if (response && response.status) {
const { status, statusText, url } = response;
const codeMsg = status ? codeMessage[status] : '';
message.error(`http 请求错误 ${status}: ${statusText}. ${url}. ${codeMsg}`);
} else if (!response) {
message.error(`未知错误, 服务器没有响应.`);
}
return response;
};
/**
* 配置request请求时的默认参数
*/
const request = extend({
errorHandler, // 默认错误处理
// credentials: 'include', // 默认请求是否带上cookie
});
request.interceptors.request.use((url, options) => {
const headers = { ...options.headers, 'Content-Type': 'application/json' };
return {
url,
options: { ...options, headers },
};
});
// response interceptor, chagne response
request.interceptors.response.use(async (response) => {
const respData: ResponseData<Object> = await response.clone().json();
const { code, message: msg, success } = respData;
if (!success) {
message.error(`code: ${code}, ${msg}, ${response.url}`);
}
return response;
});
export default request; |
<div class="row justify-content-sm-center">
<div class="col-12">
<div class="card border-0 shadow">
<form [formGroup]="form" autocomplete="off">
<div class="card-header border-0">
<h5 class="card-title mb-0 py-2">{{ title }}</h5>
</div>
<div class="card-body">
<div class="form-group">
<label for="name">Nombre</label>
<input
type="text"
class="form-control"
id="name"
maxlength="150"
placeholder="Nombre"
formControlName="name">
<ng-container *ngIf="isInvalid('name')">
<small class="form-text text-danger">
El nombre es requerido
</small>
</ng-container>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<label for="slug">Slug</label>
<input
type="text"
class="form-control"
id="slug"
maxlength="180"
placeholder="Nombre"
formControlName="slug">
<ng-container *ngIf="isInvalid('slug')">
<small class="form-text text-danger">
El slug es requerido
</small>
</ng-container>
</div>
<div class="form-group col-md-4">
<label for="code">Código</label>
<input
type="text"
class="form-control"
id="code"
maxlength="60"
placeholder="Código"
formControlName="code">
</div>
</div>
<div class="form-group">
<label for="excerpt">Descripción corta</label>
<textarea
rows="3"
class="form-control"
id="excerpt"
maxlength="250"
placeholder="Descripción corta"
formControlName="excerpt"
></textarea>
<ng-container *ngIf="isInvalid('excerpt')">
<small class="form-text text-danger">
La descripción corta es requerida
</small>
</ng-container>
</div>
<div class="form-group">
<label for="excerpt">Descripción detallada</label>
<ckeditor
[editor]="Editor"
data="<p>Hello, world!</p>"
formControlName="description"
></ckeditor>
<ng-container *ngIf="isInvalid('description')">
<small class="form-text text-danger">
La descripción es requerida
</small>
</ng-container>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="brandId">Marca</label>
<select
id="brandId"
class="form-control"
formControlName="brandId"
>
<option selected> Seleccione... </option>
<option>...</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="measureId">Unidad de medida</label>
<select
id="measureId"
class="form-control"
formControlName="measureId"
>
<option selected> Seleccione... </option>
<option>...</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="packingId">Unidad de empaque</label>
<select
id="packingId"
class="form-control"
formControlName="packingId"
>
<option selected> Seleccione... </option>
<option>...</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="taxId">Tarifa de impuesto</label>
<select
id="taxId"
class="form-control"
formControlName="taxId"
>
<option selected> Seleccione... </option>
<option>...</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="minStock">Stock mínimo</label>
<input
type="number"
class="form-control text-right"
id="minStock"
min="0"
placeholder="Stock mínimo"
formControlName="minStock">
</div>
<div class="form-group col-md-4">
<label for="maxStock">Stock máximo</label>
<input
type="number"
class="form-control text-right"
id="maxStock"
min="0"
placeholder="Stock máximo"
formControlName="maxStock">
</div>
<div class="form-group col-md-4">
<label for="balance">Saldo inicial</label>
<input
type="number"
class="form-control text-right"
id="balance"
min="0"
placeholder="Saldo inicial"
formControlName="balance">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="cost">Costo de compra</label>
<input
type="number"
class="form-control text-right"
id="cost"
min="0"
placeholder="Costo"
formControlName="cost">
</div>
<div class="form-group col-md-4">
<label for="price">Precio de venta</label>
<input
type="number"
class="form-control text-right"
id="price"
min="0"
placeholder="Precio de venta"
formControlName="price">
</div>
<div class="form-group col-md-4">
<label for="sale">Precio de oferta</label>
<input
type="number"
class="form-control text-right"
id="sale"
min="0"
placeholder="Saldo inicial"
formControlName="sale">
</div>
</div>
<div class="form-group">
<div class="custom-control custom-switch">
<input
type="checkbox"
class="custom-control-input"
id="onSale"
formControlName="onSale">
<label class="custom-control-label" for="onSale">
Producto en promoción
</label>
</div>
</div>
<div class="form-group">
<ng-multiselect-dropdown
name="categories"
[placeholder]="'Seleccione...'"
[settings]="dropdownSettings"
[data]="dropdownList"
formControlName="categories"
>
</ng-multiselect-dropdown>
</div>
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="disabled" formControlName="status">
<label class="custom-control-label" for="disabled">
Activo
</label>
</div>
</div>
</div>
<div class="card-footer border-0 text-right">
<a
[routerLink]="['/admin/parametros/marcas']"
class="btn btn-warning shadow-none mr-2">
Regresar
</a>
<button
type="submit"
class="btn shadow-none"
[ngClass]="{'btn-success': id, 'btn-primary': !id}"
[disabled]="form.invalid"
(click)="save()">
Guardar
</button>
</div>
</form>
{{ form.value | json }}
</div>
</div>
</div> |
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Image, TouchableOpacity } from 'react-native';
import DropDownPicker from 'react-native-dropdown-picker';
import { IconButton } from 'react-native-paper';
import axios from 'axios';
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
// Fetch the random data from the API endpoint
axios.get('<API_ENDPOINT>')
.then((response) => {
setData(response.data);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
}, []);
const handleEdit = (item) => {
// Send the edit data back to the API endpoint
axios.put(`<API_ENDPOINT>/${item.id}`, { title: `${item.title} (edited)` })
.then(() => {
console.log('Item edited successfully');
})
.catch((error) => {
console.error('Error editing item:', error);
});
};
const handleDelete = (item) => {
// Send the delete request to the API endpoint
axios.delete(`<API_ENDPOINT>/${item.id}`)
.then(() => {
console.log('Item deleted successfully');
// Remove the deleted item from the local data state
setData(data.filter((i) => i.id !== item.id));
})
.catch((error) => {
console.error('Error deleting item:', error);
});
};
const renderListItem = ({ item }) => (
<View style={{ flexDirection: 'row', alignItems: 'center', padding: 16 }}>
<Image source={{ uri: item.image }} style={{ width: 50, height: 50, marginRight: 16 }} />
<Text style={{ flex: 1 }}>{item.title}</Text>
<DropDownPicker
items={[
{ label: 'Edit', value: 'edit' },
{ label: 'Delete', value: 'delete' }
]}
defaultValue={null}
containerStyle={{ width: 120, height: 40, marginRight: 16 }}
onChangeItem={(selectedItem) => {
if (selectedItem.value === 'edit') {
handleEdit(item);
} else if (selectedItem.value === 'delete') {
handleDelete(item);
}
}}
/>
</View>
);
return (
<View style={{ flex: 1 }}>
<FlatList
data={data}
keyExtractor={(item) => item.id.toString()}
renderItem={renderListItem}
/>
</View>
);
};
export default App; |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Reports\Block\Adminhtml\Shopcart\Abandoned;
use Magento\Quote\Model\Quote;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\View\LayoutInterface;
/**
* Test class for \Magento\Reports\Block\Adminhtml\Shopcart\Abandoned\Grid
*
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Sales/_files/quote.php
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
class GridTest extends \Magento\Reports\Block\Adminhtml\Shopcart\GridTestAbstract
{
/**
* @return void
*/
public function testGridContent(): void
{
/** @var LayoutInterface $layout */
$layout = Bootstrap::getObjectManager()->get(LayoutInterface::class);
/** @var Grid $grid */
$grid = $layout->createBlock(Grid::class);
$grid->getRequest()->setParams(['filter' => base64_encode(urlencode('email=customer@example.com'))]);
$result = $grid->getPreparedCollection();
$this->assertCount(1, $result->getItems());
/** @var Quote $quote */
$quote = $result->getFirstItem();
$this->assertEquals('customer@example.com', $quote->getCustomerEmail());
$this->assertEquals(10.00, $quote->getSubtotal());
}
/**
* @return void
*/
public function testPageSizeIsSetToNullWhenExportCsvFile(): void
{
/** @var LayoutInterface $layout */
$layout = Bootstrap::getObjectManager()->get(LayoutInterface::class);
/** @var Grid $grid */
$grid = $layout->createBlock(Grid::class);
$grid->getCsvFile();
$this->assertNull($grid->getCollection()->getPageSize());
}
} |
<?php
namespace App\Services;
use App\Enums\StatusId;
use App\Repositories\RoleRepository;
use App\Repositories\StatusRepository;
use App\Repositories\UserRepository;
use App\Validators\LoginValidator;
use Carbon\Carbon;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Ramsey\Uuid\Uuid;
class LoginService
{
/**
* @var UserRepository userRepository
*/
private UserRepository $userRepository;
/**
* @var RoleRepository roleRepository
*/
private RoleRepository $roleRepository;
/**
* @var StatusRepository statusRepository
*/
private StatusRepository $statusRepository;
/**
* @var ResponseService service
*/
private ResponseService $service;
/**
* __construct
*
* @param UserRepository userRepository
* @param RoleRepository roleRepository
* @param StatusRepository statusRepository
* @param ResponseService service
*
* @return void
*/
public function __construct(
UserRepository $userRepository,
RoleRepository $roleRepository,
StatusRepository $statusRepository,
ResponseService $service
) {
$this->userRepository = $userRepository;
$this->statusRepository = $statusRepository;
$this->roleRepository = $roleRepository;
$this->service = $service;
}
/**
* login
*
* @param array data
*
* @return array
*/
public function login(array $data) : array
{
$validator = Validator::make($data, LoginValidator::$rules);
if ($validator->fails()) {
return $this->service->response(
null,
$validator->errors()->toArray(),
Response::HTTP_NOT_ACCEPTABLE
);
} else {
return $this->auth($data);
}
}
/**
* auth
*
* @param array data
*
* @return array
*/
private function auth(array $data) : array
{
$user = $this->userRepository->findByEmail($data['email']);
if ($user == null) {
return $this->service->response(null, null, Response::HTTP_UNAUTHORIZED);
} elseif (!$user->is_confirmed) {
return $this->service->response(
null,
['error' => 'auth.not_confirmed',],
Response::HTTP_UNAUTHORIZED
);
} elseif ($user->login_attemps >= env('LOGIN_ATTEMPS')) {
$data = $user->toArray();
$data['status_id'] = StatusId::INACTIVE;
$user = $this->userRepository->update($data);
return $this->service->response(
null,
['error' => 'auth.login_attemps',],
Response::HTTP_UNAUTHORIZED
);
} elseif (
$user->last_password_changed->diffInDays(Carbon::now()) > env('PASSWORD_EXPIRE ')
) {
$data = $user->toArray();
$data['status_id'] = StatusId::INACTIVE;
$user = $this->userRepository->update($data);
return $this->service->response(
null,
['error' => 'auth.password_expired',],
Response::HTTP_UNAUTHORIZED
);
} elseif ($user->status_id === StatusId::INACTIVE) {
return $this->service->response(
null,
['error' => 'auth.account_inactive',],
Response::HTTP_UNAUTHORIZED
);
} elseif (!Hash::check($data['password'], $user->password)) {
return $this->service->response(null, null, Response::HTTP_UNAUTHORIZED);
} else {
$this->userRepository->updateLoginAttemps(
[
'id' => $user->id,
'login_attemps' => 0,
'date' => Carbon::now()
]
);
$currentUser = $this->userRepository->updateToken([
'id' => $user->id,
'uuid' => Uuid::uuid4(),
'expired_token' => Carbon::now()->addMinutes(15),
'updated_at' => Carbon::now(),
]);
return $this->service->response([
'user' => $currentUser,
'role' => $this->roleRepository->findById($currentUser->role_id),
'status' => $this->statusRepository->findById($currentUser->status_id),
], null, Response::HTTP_OK);
}
}
} |
# Assignment 3 – Network analysis
The portfolio for __Language Analytics S22__ consists of 5 projects (4 class assignments and 1 self-assigned project). This is the __third assignment__ in the portfolio.
## 1. Contribution
The initial assignment was made partly in collaboration with others from the course, but the final code is my own. I made several adjustments to the code since I first handed it in. I found inspiration from this [blog post](https://towardsdatascience.com/customizing-networkx-graphs-f80b4e69bedf) to make the `NetworkX` plots more readable.
## 2. Assignment description by Ross
### Main task
In this assignment, you are going to write a ```.py``` script which can be used for network analysis. As we saw last week, pretty much anything can be formalised as a network. We're not going to focus on creating the edgelists for this project; instead, the goal is to have a script that would work the same way on _any_ input data, as long as the input format is correct.
So, as test data, I recommend that you use the files in the folder called ```network_data```. However, the final script should be able to be resused and work on any undirected, weighted edgelist with the same column names.
Your script should do the following:
- If the user enters a _single filename_ as an argument on the command line:
- Load that edgelist
- Perform network analysis using ```networkx```
- Save a simple visualisation
- Save a CSV which shows the following for every node:
- name; degree; betweenness centrality; eigenvector_centrality
- If the user enters a _directory name_ as an argument on the command line:
- Do all of the above steps for every edgelist in the directory
- Save a separate visualisation and CSV for each file
### Bonus task
- ```networkx``` offers a range of different plotting algorithms. Select a few of these and allow the user to decide between different options.
## 3. Methods
### Main task
The [network_analysis.py](https://github.com/agnesbn/LANG_assignment3/blob/main/src/network_analysis.py) script loads and reads an edgelist CSV, creates and saves network plots using `NetworkX`, and finally computes three different types of centrality metrics for the nodes (degree centrality, eigenvector centrality, and shortest-path betweenness centrality) and saves the results in a CSV. The user can choose whether to do this for a single edgelist or for all the edgelists in a directory.
### Bonus task
Adding a number of arguments with `argparse.ArgumentParser()` allows for the user to define a number of parameters for plotting the network, such as the colour of the nodes and their outline, the colour and width of the edges, the size and shape of the nodes, font size and weight, and the distance between the nodes. I also added an argument for the user to decide what centrality metric the output CSV should be sorted by.
## 4. Usage
### Install packages
Before running the script, you have to install the relevant packages. To do this, run the following from the command line:
```
sudo apt update
pip install --upgrade pip
pip install pandas numpy networkx
```
### Get the data
- The data should be provided to the examiner by Ross.
- Place the data folder in the `in` folder so that the path is `in/network_data`.
### Main and bonus task
Make sure your current directory is the ´LANG_assignment3` folder. Then from the command line, run:
```
python src/network_analysis.py (--filename <FILENAME> --directory_name <DIRECTORY NAME>)
(--sort_csv_by <CENTRALITY METRIC>) (--node_color <NODE COLOUR> --edgecolors <NODE OUTLINE COLOUR>
--edge_color <EDGE COLOUR> --node_shape <NODE SHAPE> --node_size <NODE SIZE> --width <EDGE WIDTH>
--font_size <FONT SIZE> --font_weight <FONT WEIGHT> --node_distance <NODE DISTANCE>)
```
__Data loading arguments__: Only put in one of these arguments!
- `<FILENAME>`: The name of the CSV file, you want to work with, e.g. `1H4.csv`.
- `<DIRECTORY NAME>`: The name of the directory of edgelists, you want to work with, e.g. `network_data`.
__Data saving arguement__:
- `<CENTRALITY METRIC>`: The centrality metric you wish for the output CSV to be sorted by. Put in `degree_centrality`, `eigenvector_centrality`, or `betweenness_centrality`. The default is `degree_centrality`.
__Network plotting arguments__:
- `<NODE COLOUR>`: The colour of the nodes in the network plot. The default is `orange`.
- `<NODE OUTLINE COLOUR>`: The colour of the outline of the nodes in the network plot. The default is `saddlebrown`.
- `<EDGE COLOUR>`: The colour of the edges (i.e. lines between nodes) in the network plot. The default is `dimgrey`.
- For other colour names, see this [documentation](https://matplotlib.org/stable/gallery/color/named_colors.html).
- `<NODE SHAPE>`: The shape of the nodes. The default is `$\u2B2C$` which is a horisontal ellipse.
- For different possibilities for node shapes, see the [documentation](https://matplotlib.org/stable/api/markers_api.html#module-matplotlib.markers) for matplotlib.markers.
- `<NODE SIZE>`: The size of the nodes. The default is `2700`.
- `<EDGE WIDTH>`: The line width of the edges. The default is `1`.
- `<FONT SIZE>`: The font size of the node labels. The default is `8`.
- `<FONT WEIGHT>`: The font weight of the node labels. The default is `heavy`.
- For different font weights, see this [documentation](https://matplotlib.org/stable/tutorials/text/text_props.html).
- `<NODE DISTANCE>`: The distance between nodes. The default is `0.9`.
## 5. Discussion of results
The final plots can be seen here. Making the `NetworkX` networks readable took some adjustment. Though this is the most readable I could make them, they are still not perfect. There are a few node labels that go outside of the nodes, and some nodes overlap. To avoid stacking and overlapping of the nodes, I set the node distance rather high (0.9), which also blurs the "clusteredness" of the network. But, the user can continue to make small adjustments to the plots by putting in different network plotting arguments to see if it is possible to make the plots more readable. And in any case, the current plots are much more readable now than in my [initial assignment](https://github.com/agnesbn/assignments-cds-lang/blob/main/assignment3/out/network_1H6.png).
 |
:---------------------------------------:|:---------------------------------------:
 | 
 | 
 | 
 |  |
/*
* Copyright (C) 2011-2013 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/kernel.h>
#include <drm/drm_mode.h>
#include <drm/drm_print.h>
#include <drm/drm_rect.h>
/**
* drm_rect_intersect - intersect two rectangles
* @r1: first rectangle
* @r2: second rectangle
*
* Calculate the intersection of rectangles @r1 and @r2.
* @r1 will be overwritten with the intersection.
*
* RETURNS:
* %true if rectangle @r1 is still visible after the operation,
* %false otherwise.
*/
bool drm_rect_intersect(struct drm_rect *r1, const struct drm_rect *r2)
{
r1->x1 = max(r1->x1, r2->x1);
r1->y1 = max(r1->y1, r2->y1);
r1->x2 = min(r1->x2, r2->x2);
r1->y2 = min(r1->y2, r2->y2);
return drm_rect_visible(r1);
}
EXPORT_SYMBOL(drm_rect_intersect);
static u32 clip_scaled(int src, int dst, int *clip)
{
u64 tmp;
if (dst == 0)
return 0;
/* Only clip what we have. Keeps the result bounded. */
*clip = min(*clip, dst);
tmp = mul_u32_u32(src, dst - *clip);
/*
* Round toward 1.0 when clipping so that we don't accidentally
* change upscaling to downscaling or vice versa.
*/
if (src < (dst << 16))
return DIV_ROUND_UP_ULL(tmp, dst);
else
return DIV_ROUND_DOWN_ULL(tmp, dst);
}
/**
* drm_rect_clip_scaled - perform a scaled clip operation
* @src: source window rectangle
* @dst: destination window rectangle
* @clip: clip rectangle
*
* Clip rectangle @dst by rectangle @clip. Clip rectangle @src by the
* the corresponding amounts, retaining the vertical and horizontal scaling
* factors from @src to @dst.
*
* RETURNS:
*
* %true if rectangle @dst is still visible after being clipped,
* %false otherwise.
*/
bool drm_rect_clip_scaled(struct drm_rect *src, struct drm_rect *dst,
const struct drm_rect *clip)
{
int diff;
diff = clip->x1 - dst->x1;
if (diff > 0) {
u32 new_src_w = clip_scaled(drm_rect_width(src),
drm_rect_width(dst), &diff);
src->x1 = src->x2 - new_src_w;
dst->x1 += diff;
}
diff = clip->y1 - dst->y1;
if (diff > 0) {
u32 new_src_h = clip_scaled(drm_rect_height(src),
drm_rect_height(dst), &diff);
src->y1 = src->y2 - new_src_h;
dst->y1 += diff;
}
diff = dst->x2 - clip->x2;
if (diff > 0) {
u32 new_src_w = clip_scaled(drm_rect_width(src),
drm_rect_width(dst), &diff);
src->x2 = src->x1 + new_src_w;
dst->x2 -= diff;
}
diff = dst->y2 - clip->y2;
if (diff > 0) {
u32 new_src_h = clip_scaled(drm_rect_height(src),
drm_rect_height(dst), &diff);
src->y2 = src->y1 + new_src_h;
dst->y2 -= diff;
}
return drm_rect_visible(dst);
}
EXPORT_SYMBOL(drm_rect_clip_scaled);
static int drm_calc_scale(int src, int dst)
{
int scale = 0;
if (WARN_ON(src < 0 || dst < 0))
return -EINVAL;
if (dst == 0)
return 0;
if (src > (dst << 16))
return DIV_ROUND_UP(src, dst);
else
scale = src / dst;
return scale;
}
/**
* drm_rect_calc_hscale - calculate the horizontal scaling factor
* @src: source window rectangle
* @dst: destination window rectangle
* @min_hscale: minimum allowed horizontal scaling factor
* @max_hscale: maximum allowed horizontal scaling factor
*
* Calculate the horizontal scaling factor as
* (@src width) / (@dst width).
*
* If the scale is below 1 << 16, round down. If the scale is above
* 1 << 16, round up. This will calculate the scale with the most
* pessimistic limit calculation.
*
* RETURNS:
* The horizontal scaling factor, or errno of out of limits.
*/
int drm_rect_calc_hscale(const struct drm_rect *src,
const struct drm_rect *dst,
int min_hscale, int max_hscale)
{
int src_w = drm_rect_width(src);
int dst_w = drm_rect_width(dst);
int hscale = drm_calc_scale(src_w, dst_w);
if (hscale < 0 || dst_w == 0)
return hscale;
if (hscale < min_hscale || hscale > max_hscale)
return -ERANGE;
return hscale;
}
EXPORT_SYMBOL(drm_rect_calc_hscale);
/**
* drm_rect_calc_vscale - calculate the vertical scaling factor
* @src: source window rectangle
* @dst: destination window rectangle
* @min_vscale: minimum allowed vertical scaling factor
* @max_vscale: maximum allowed vertical scaling factor
*
* Calculate the vertical scaling factor as
* (@src height) / (@dst height).
*
* If the scale is below 1 << 16, round down. If the scale is above
* 1 << 16, round up. This will calculate the scale with the most
* pessimistic limit calculation.
*
* RETURNS:
* The vertical scaling factor, or errno of out of limits.
*/
int drm_rect_calc_vscale(const struct drm_rect *src,
const struct drm_rect *dst,
int min_vscale, int max_vscale)
{
int src_h = drm_rect_height(src);
int dst_h = drm_rect_height(dst);
int vscale = drm_calc_scale(src_h, dst_h);
if (vscale < 0 || dst_h == 0)
return vscale;
if (vscale < min_vscale || vscale > max_vscale)
return -ERANGE;
return vscale;
}
EXPORT_SYMBOL(drm_rect_calc_vscale);
/**
* drm_rect_debug_print - print the rectangle information
* @prefix: prefix string
* @r: rectangle to print
* @fixed_point: rectangle is in 16.16 fixed point format
*/
void drm_rect_debug_print(const char *prefix, const struct drm_rect *r, bool fixed_point)
{
if (fixed_point)
DRM_DEBUG_KMS("%s" DRM_RECT_FP_FMT "\n", prefix, DRM_RECT_FP_ARG(r));
else
DRM_DEBUG_KMS("%s" DRM_RECT_FMT "\n", prefix, DRM_RECT_ARG(r));
}
EXPORT_SYMBOL(drm_rect_debug_print);
/**
* drm_rect_rotate - Rotate the rectangle
* @r: rectangle to be rotated
* @width: Width of the coordinate space
* @height: Height of the coordinate space
* @rotation: Transformation to be applied
*
* Apply @rotation to the coordinates of rectangle @r.
*
* @width and @height combined with @rotation define
* the location of the new origin.
*
* @width correcsponds to the horizontal and @height
* to the vertical axis of the untransformed coordinate
* space.
*/
void drm_rect_rotate(struct drm_rect *r,
int width, int height,
unsigned int rotation)
{
struct drm_rect tmp;
if (rotation & (DRM_MODE_REFLECT_X | DRM_MODE_REFLECT_Y)) {
tmp = *r;
if (rotation & DRM_MODE_REFLECT_X) {
r->x1 = width - tmp.x2;
r->x2 = width - tmp.x1;
}
if (rotation & DRM_MODE_REFLECT_Y) {
r->y1 = height - tmp.y2;
r->y2 = height - tmp.y1;
}
}
switch (rotation & DRM_MODE_ROTATE_MASK) {
case DRM_MODE_ROTATE_0:
break;
case DRM_MODE_ROTATE_90:
tmp = *r;
r->x1 = tmp.y1;
r->x2 = tmp.y2;
r->y1 = width - tmp.x2;
r->y2 = width - tmp.x1;
break;
case DRM_MODE_ROTATE_180:
tmp = *r;
r->x1 = width - tmp.x2;
r->x2 = width - tmp.x1;
r->y1 = height - tmp.y2;
r->y2 = height - tmp.y1;
break;
case DRM_MODE_ROTATE_270:
tmp = *r;
r->x1 = height - tmp.y2;
r->x2 = height - tmp.y1;
r->y1 = tmp.x1;
r->y2 = tmp.x2;
break;
default:
break;
}
}
EXPORT_SYMBOL(drm_rect_rotate);
/**
* drm_rect_rotate_inv - Inverse rotate the rectangle
* @r: rectangle to be rotated
* @width: Width of the coordinate space
* @height: Height of the coordinate space
* @rotation: Transformation whose inverse is to be applied
*
* Apply the inverse of @rotation to the coordinates
* of rectangle @r.
*
* @width and @height combined with @rotation define
* the location of the new origin.
*
* @width correcsponds to the horizontal and @height
* to the vertical axis of the original untransformed
* coordinate space, so that you never have to flip
* them when doing a rotatation and its inverse.
* That is, if you do ::
*
* drm_rect_rotate(&r, width, height, rotation);
* drm_rect_rotate_inv(&r, width, height, rotation);
*
* you will always get back the original rectangle.
*/
void drm_rect_rotate_inv(struct drm_rect *r,
int width, int height,
unsigned int rotation)
{
struct drm_rect tmp;
switch (rotation & DRM_MODE_ROTATE_MASK) {
case DRM_MODE_ROTATE_0:
break;
case DRM_MODE_ROTATE_90:
tmp = *r;
r->x1 = width - tmp.y2;
r->x2 = width - tmp.y1;
r->y1 = tmp.x1;
r->y2 = tmp.x2;
break;
case DRM_MODE_ROTATE_180:
tmp = *r;
r->x1 = width - tmp.x2;
r->x2 = width - tmp.x1;
r->y1 = height - tmp.y2;
r->y2 = height - tmp.y1;
break;
case DRM_MODE_ROTATE_270:
tmp = *r;
r->x1 = tmp.y1;
r->x2 = tmp.y2;
r->y1 = height - tmp.x2;
r->y2 = height - tmp.x1;
break;
default:
break;
}
if (rotation & (DRM_MODE_REFLECT_X | DRM_MODE_REFLECT_Y)) {
tmp = *r;
if (rotation & DRM_MODE_REFLECT_X) {
r->x1 = width - tmp.x2;
r->x2 = width - tmp.x1;
}
if (rotation & DRM_MODE_REFLECT_Y) {
r->y1 = height - tmp.y2;
r->y2 = height - tmp.y1;
}
}
}
EXPORT_SYMBOL(drm_rect_rotate_inv); |
import React, { useState, useEffect } from "react";
import { Wrapper } from "./home.styles";
import { Link } from "react-router-dom";
import axiosInstance from "../../axios";
import { Table } from 'reactstrap';
import Moment from 'moment';
import MyImage from "../image/image";
const Home = ({ userEmail, }) => {
const [mounted, setMounted] = useState(false);
const [dataBooks, setDataBooks] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(false);
if (!mounted) {
axiosInstance.get('books/').then((res) => {
setIsAuthenticated(true);
setDataBooks(res.data);
}).catch((error) => {
if (error.response?.status === 401) {
console.log(error.response);
}
console.log(error.response);
});
}
useEffect(() => {
setMounted(true)
}, [])
return (
<Wrapper>
<div className="imageContainer">
<MyImage src={"/book.png"} alt={"Book Image"} width={180} />
</div>
<div>
<h2>Książki w bibliotece</h2>
</div>
{dataBooks.length === 0 ? <h3>Aktualnie nie posiadamy żadnej ksiązki w naszej bibliotece</h3> :
<Table responsive>
<thead>
<tr>
<th>
Tytuł
</th>
<th>
Autor
</th>
<th>
Dodane
</th>
<th>
Status
</th>
<th>
Akcje
</th>
</tr>
</thead>
<tbody>
{dataBooks.map(book =>
<tr key={book.id}>
<td>{book.title}</td>
<td>{book.author}</td>
<td>{Moment(book.add_date).format('DD-MM-YYYY')}</td>
<td>{book.status === 0 ? <MyImage src={"/tick-mark-icon.png"} alt={"Book Image"} width={20} /> :
<MyImage src={"/incorrect-icon.png"} alt={"Book Image"} width={20} />}
</td>
<td>{book.borrowed_by === null ? <Link to="/borrow" className="borrow-link" state={{ values: book }}>Wypożycz</Link> : book.borrowed_by === userEmail ? <Link to="/return" state={{ values: book }}>Oddaj</Link> : null}</td>
</tr>)}
</tbody>
</Table>
}
</Wrapper>
)
}
export default Home; |
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map } from 'rxjs/operators';
//** Declaring the api url that will provide data for the client app */
const apiUrl = 'https://frightened-pink-onesies.cyclic.app/';
@Injectable({
providedIn: 'root'
})
export class FetchApiDataService {
// Inject the HttpClient module to the constructor params
// This will provide HttpClient to the entire class, making it available via this.http
constructor(private http: HttpClient) {
}
/**
* Makes an API call to the user registration endpoint.
* @service POST to apiUrl endpoint for register a new user
* @param {any} userDetails
* @returns new user object in json format
* @function userRegistration
*/
public userRegistration(userDetails: any): Observable<any> {
console.log(userDetails);
return this.http.post(apiUrl + 'users', userDetails).pipe(
catchError(this.handleError)
);
}
/**
* Extracts the response data from a non-typed response.
* @param res - The response from the server.
* @returns The response body or empty object.
*/
private extractResponseData(res: any): any {
const body = res;
return body || { };
}
/**
* Handles an error in the API call.
* @param error - The error that occurred.
* @returns An error message.
*/
private handleError(error: HttpErrorResponse): any {
if (error.error instanceof ErrorEvent) {
console.error('Some error occurred:', error.error.message);
} else {
console.error(
`Error Status code ${error.status}, ` +
`Error body is: ${error.error}`);
}
return throwError(
'Something bad happened; please try again later.');
}
/**
* User login
* @service POST to apiUrl endpoint to login user
* @param {any} userDetails
* @returns new user object in json format
* @function userLogin
*/
public userLogin(userDetails: any): Observable<any> {
console.log(userDetails);
return this.http.post(apiUrl + 'login', userDetails).pipe(
catchError(this.handleError)
);
}
/**
* Get One Movie
* @service GET to apiUrl endpoint to get movie by title
* @param {string} Title
* @returns array of movie object in json format
* @function GetOneMovie
*/
getOneMovie(Title: string): Observable<any> {
const token = localStorage.getItem('token');
return this.http
.get(`${apiUrl}movies/${Title}`,
{headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Get Director
* @service GET to apiUrl endpoint for Director information
* @param {String} directorName
* @returns director object in json format
* @function getDirector
*/
getDirector(directorName: string): Observable<any> {
const token = localStorage.getItem('token');
return this.http.get(apiUrl + 'movies' + 'directorName', {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Get Genre
* @service GET to apiUrl endpoint for genre information
* @param {string} genreName
* @returns genre object in json format
* @function getGenre
*/
getGenre(genreName: string): Observable<any> {
const token = localStorage.getItem('token');
return this.http.get(apiUrl + 'movies' + 'genreName', {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Get User.
* @service GET to apiUrl endpoint for a user
* @returns user object in json format
* @function getUser
*/
getUser(): Observable<any> {
const username = localStorage.getItem('user');
const token = localStorage.getItem('token');
return this.http
.get(`${apiUrl}users/${username}`, {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Get favourite movies for a user
* @service GET to apiUrl endpoint for users favourite movies
* @returns array of users favourite movies object in json format
* @function getFavouriteMovie
*/
getFavouriteMovie(): Observable<any> {
const token = localStorage.getItem('token');
return this.http.get(apiUrl + 'user' + "username" + "movies" + 'MovieID', {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Add movie to favourite movies
* @service POST to apiUrl endpoint for adding favourite movie
* @param {string} MovieID
* @returns user object in json format
* @function addMovietoFavourite
*/
addMovietoFavourite(MovieID: string): Observable<any> {
const username = localStorage.getItem('user');
const token = localStorage.getItem('token');
return this.http
.post(
`${apiUrl}users/${username}/movies/${MovieID}`,
{ FavouriteMovie: MovieID },
{headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Edit a user details
* @service PUT to apiUrl endpoint to update users information
* @returns user object in json format
* @function updateUser
*/
updateUser(updatedUser: any): Observable<any> {
const username = localStorage.getItem('user');
const token = localStorage.getItem('token');
return this.http
.put(`${apiUrl}users/${username}`, updatedUser, {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Delete user
* @service DELETE to apiUrl endpoint for deleting a users profile
* @returns a message
* @function deleteUser
*/
deleteUser(): Observable<any> {
const token = localStorage.getItem('token');
const username = localStorage.getItem('user');
return this.http
.delete(`${apiUrl}users/${username}`, {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Delete a movie from the favourites movie
* @service DELETE to apiUrl endpoint to remove favourite movies
* @returns user object
* @function deleteFavouriteMovie
*/
deleteFavouriteMovie(MovieID: string): Observable<any> {
const username = localStorage.getItem('user');
const token = localStorage.getItem('token');
return this.http
.delete(`${apiUrl}users/${username}/movies/${MovieID}`, {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
/**
* Get all Movies
* @service GET to apiUrl endpoint to get all movies
* @returns an array of all movies in json format
* @function getAllMovies
*/
getAllMovies(): Observable<any> {
const token = localStorage.getItem('token');
return this.http.get(apiUrl + 'movies', {headers: new HttpHeaders(
{
Authorization: 'Bearer ' + token,
})}).pipe(
map(this.extractResponseData),
catchError(this.handleError)
);
}
} |
/**
* CS 2003 - Lab 1
* Code to find the maximum integer in a given file
* NOTE:
* there are bugs including those causing compilation errors and
* resulting in runtime logical problems
*
* @author Kasey Mills
* @version 1
* @since 08-30-2017
*/
import java.util.Scanner;
import java.util.Vector;
import java.io.File;
import java.io.IOException;
public class Lab1a
{
/**stores the data retrived from the file */
Vector <Integer> intVector;
/** variable used to compute the run-time */
long startTime, endTime, totalTime;
/** Constructor: computes the running time and call readFile
* method
*/
public Lab1a()
{
startTime = System.currentTimeMillis();
readFile();
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
System.out.println("total time taken: " + totalTime + " milliseconds");
}
/* Method description here */
public void readFile()
{
try
{
File inputFile = new File("src/lab1a.dat");
Scanner input = new Scanner(inputFile);
intVector = new Vector<Integer>();
int max = 0;
int elt = input.nextInt(); //initializing elt to the first value of the File
int count=0;
// store all elements in a vector
while (input.hasNextInt()) //Returns boolean value to tell if it has next value
{
count++;
intVector.addElement(elt);
elt = input.nextInt(); //Gets the next integer from the file at the bottom so its not overwritten
}
// print on the terminal each elements of intVector
System.out.printf("There are %d integers in the input file:\n", count);
for (int value: intVector)
System.out.printf("%d ",value);
System.out.println();
// Find the max
for(int i=0;i<intVector.size();i++)
{
int value=intVector.get(i);
if(value > max) //* If value is greater than max
max = value;
}
//output results
System.out.printf("The maximum integer in the input file is %d\n",max);
input.close();
}
catch (IOException e)
{
System.err.println("IOException in reading input file!!!" + e.getMessage().toString());
}
} //end readFile()
/** main : creates an Object Lab1a */
public static void main(String args[])
{
Lab1a lab = new Lab1a();
}
//end main
} //end class Lab1a |
import React, { useContext } from "react";
import Modal from "../Modal/Modal";
import Board from "../Board/Board";
import PieceMenu from "../PieceMenu/PieceMenu";
import GameContext from "../../context/GameContext";
import useModal from "../../hooks/useModal";
import useBoardLogic from "../../hooks/useBoardLogic";
const Game = () => {
const {
initialBoard,
board,
setBoard,
kingCoordinate,
setKingCoordinate,
setMultipleSelectedCell,
} = useContext(GameContext);
const { transformAttackToQueen, handleSolveBoard, handleResetBoard } =
useBoardLogic({
initialBoard,
board,
setBoard,
setKingCoordinate,
setMultipleSelectedCell,
});
const { isShowModal: isShowAboutModal, toggleModal: toggleAboutModal } =
useModal();
const solveBoard = () => {
if (kingCoordinate === null) {
alert("No king placed");
return;
}
transformAttackToQueen(board);
const result = handleSolveBoard(board, [
kingCoordinate.row,
kingCoordinate.col,
]);
setBoard(result);
};
if (isShowAboutModal) return <Modal toggleModal={toggleAboutModal} />;
return (
<>
<PieceMenu />
<section className='md:w-[500px] min-h-screen mx-auto h-full w-full text-gray-400 p-3 md:p-0 flex flex-col'>
<header className='mt-5 text-xl'>
<div className='text-white font-medium'>
Queen That Can Attack The King
</div>
</header>
<section className='mt-5'>
<Board />
</section>
<section className='mt-5'>
<div>
You can choose multiple positions by clicking on the board, and then
choose the piece you want to place by{" "}
<span className='bg-gray-700 text-xs rounded py-[3px] px-[5px] text-white'>
Right click
</span>{" "}
or{" "}
<span className='bg-gray-700 text-xs rounded py-[3px] px-[5px] text-white'>
Ctrl + Click
</span>{" "}
Have fun customizing your chessboard!
</div>
<div className='flex mt-5 gap-x-3'>
<button
className='rounded-md px-4 py-2 bg-slate-600 font-medium hover:bg-opacity-80 duration-200'
onClick={solveBoard}>
Solve Board
</button>
<button
className='rounded-md px-4 py-2 bg-slate-600 font-medium hover:bg-opacity-80 duration-200'
onClick={handleResetBoard}>
Reset Board
</button>
<button
className='rounded-md px-4 py-2 bg-black-checker font-medium hover:bg-opacity-80 text-white duration-200 ml-auto'
onClick={toggleAboutModal}>
About project
</button>
</div>
</section>
<footer className='mt-auto border-t border-gray-600 text-center text-sm py-4'>
Crafted with passion by{" "}
<a
className='text-gray-200 underline'
rel='noreferrer'
target='_blank'
href='https://github.com/cehaaa'>
Christian
</a>{" "}
Check the GitHub{" "}
<a
className='text-gray-200 underline'
rel='noreferrer'
target='_blank'
href='https://github.com/cehaaa/queen-attack-the-king'>
here.
</a>{" "}
</footer>
</section>
</>
);
};
export default Game; |
.. _hw3:
Problem Set 3
.. _distance:
Distance
----------------
Write a function called s1() that prompts the user to enter two points on the Cartesian plane with different coordinates and calculates the slope between the two points and the distance between the two points. The formulas for both of these quantities are as follows between points (x1,y1) and (x2,y2):
.. math::
slope = \frac{y_{2}-y_{1}}{x_{2}-x_{1}}
dist = \sqrt{(y_{2}-y_{1})^2 + (x_{2}-x_{1})^2}
For example, if you have two points: (1,1) and (2,2), the slope and distance between the two points should be 1 and 1.4.
When you call s1(), the output should be like this:
.. image:: s1.gif
:width: 750
Universal Gravitation
----------------
The force of gravity, or gravitational force, pulls objects with mass toward each other. We often think about the force of gravity from Earth. This force is what keeps your body on the ground. But any object with mass exerts a gravitational force on all other objects with mass.
The gravitational force between two objects is larger when the masses of the objects are larger. That’s why you can feel the gravitational force between you and Earth, but the force between you and objects with smaller masses is too weak to feel.
The gravitational force between two objects also depends on the distance between their centers. The further objects are from one another, the weaker the force is.
The equation for gravitation force thus takes the form:
.. math::
F = G\frac{m1m2}{r^2}
where
* F: gravitational force acting between two objects(in Newton)
* m1 and m2: the masses of the objects(in kg)
* r: the distance between the centers of their masses(in m)
G is the gravitational constant, which is :math:`6.67*10^{-11}`
Write a function called s2() that prompts the user to enter the masses of two objects(for example, two stars), and the distance between them. Then it should calculate the gravitational force. When you call s2(), the output should be like this:
.. image:: s2.gif
:width: 750
.. _solve equation:
Solve Equation
----------------
Write a function called solve() to solve quadratic equation: :math:`ax^2+bx+c=0`
When you call solve(), the output should be like this:
.. image:: solve.gif
:width: 750
Lottery
-------
Most lotteries allow users to choose some balls painted in different numbers, out of the box. If the user choose all the balls correctly, then he/she wins the lottery.
Write a method gamble() to calculate a person’s chance of winning a lottery. For example, if the user needs to choose 1 ball out of 6, then the chance of winning should be 0.1666.
The number of possible choices of balls is :math:`\frac{n!}{(n-k)! * k!}`, when the user is choosing k balls out of n. When you call gamble(), the output should be look like this:
.. image:: gamble.gif
:width: 750
提交:
-----------
replit链接:https://replit.com/team/SCLS-CS2023/HW5
每个函数至少需要测试(调用)两次。 |
@set('isPaginated', Array.isArray(data?.rows) && data.currentPage)
@set('rows', isPaginated ? data.rows : data)
@set('alignments', {
left: 'text-left',
center: 'text-center',
right: 'text-right'
})
<div class="flex flex-col mb-3">
<div class="overflow-x-auto sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
<div class="align-middle inline-block min-w-full shadow overflow-hidden sm:rounded-lg border-b border-gray-200">
<table class="min-w-full">
@if ($slots.thead || columns?.length)
<thead>
<tr>
@if (columns?.length)
@each(column in columns)
<th {{{ column.width && `style="width: ${column.width}"` }}} class="
px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-800 uppercase tracking-wider
{{ alignments[align ?? 'left'] }}
{{ column.className }}
">
{{ column.name }}
</th>
@endeach
@else
{{{ await $slots.thead() }}}
@endif
</tr>
</thead>
@endif
<tbody class="bg-white">
@if (rows?.length)
@each(row in rows)
<tr>
@if (columns?.length)
@each(column in columns)
<td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
{{{ await $slots.tableData({ row, column }) }}}
</td>
@endeach
@elseif ($slots.row)
{{{ await $slots.row() }}}
@endif
</tr>
@endeach
@elseif ($slots.tbody)
{{{ await $slots.tbody() }}}
@else
<tr>
<td colspan="{{ columns.length ? columns.length : 1 }}" class="text-center">
@!component('components/empty', {
title: 'No Posts',
subtitle: 'Get started by creating your first post',
cta: 'Create Post',
href: route('studio.posts.create')
})
</td>
</tr>
@endif
</tbody>
</table>
</div>
</div>
</div>
@if (isPaginated)
@!pagination({ data, className: '-mt-3 border-none bg-gray-50 rounded-b-lg border border-t-0 border-gray-200' })
@endif |
<?php
/**
* The header for our theme.
*
* This is the template that displays all of the <head> section and everything up until <div id="content">
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package Fooding
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="site">
<!-- begin .header-mobile-menu -->
<nav class="st-menu st-effect-1" id="menu-3">
<div class="btn-close-home">
<button class="close-button" id="closemenu"></button>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" class="home-button"><i class="fa fa-home"></i></a>
</div>
<?php wp_nav_menu( array('theme_location' => 'primary','echo' => true,'items_wrap' => '<ul>%3$s</ul>')); ?>
<?php get_search_form( $echo = true ); ?>
</nav>
<!-- end .header-mobile-menu -->
<div class="site-pusher">
<a class="skip-link screen-reader-text" href="#main"><?php esc_html_e( 'Skip to content', 'fooding' ); ?></a>
<header id="masthead" class="site-header" role="banner" data-parallax="scroll" data-image-src="<?php header_image() ; ?>">
<div class="site-header-wrap">
<div class="container">
<button class="top-mobile-menu-button mobile-menu-button" data-effect="st-effect-1" type="button"><i class="fa fa-bars"></i></button>
<div class="site-branding">
<?php if ( has_custom_logo() ) : ?>
<div class="site-logo">
<?php fooding_the_custom_logo(); ?>
</div>
<?php endif; ?>
<?php
if ( is_front_page() && is_home() ) : ?>
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<?php else : ?>
<p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p>
<?php
endif;
$description = get_bloginfo( 'description', 'display' );
if ( $description || is_customize_preview() ) : ?>
<p class="site-description"><?php echo $description; /* WPCS: xss ok. */ ?></p>
<?php
endif; ?>
</div><!-- .site-branding -->
</div>
<nav id="site-navigation" class="main-navigation" role="navigation">
<div class="container">
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu' ) ); ?>
</div>
</nav><!-- #site-navigation -->
</div> <!-- .site-header-wrap -->
</header><!-- #masthead -->
<div id="content" class="site-content"> |
import numpy as np
from typing import Tuple, TypeVar, Optional, List, Tuple
from copy import deepcopy
"""
Geometry functions.
"""
Point = TypeVar("Point", Tuple, List)
Line = TypeVar("Line", List[Tuple], List[List])
Circle = TypeVar("Circle", Tuple, List) # x, y ,radius
class Polygon:
"""
Convex Polygon, anticlockwise vertexes/lines.
"""
def __init__(self, vertexes: List[Point]):
# anticlockwise_vertexes_sort(vertexes)
self.vertexes: List[Point] = anticlockwise_vertexes_sort(vertexes)
self.lines: List[Line] = vertexes_to_lines(self.vertexes)
self.norms: List[Point] = lines_to_norm(self.lines)
self.center: Point = tuple(np.mean(np.array(self.vertexes), axis=0))
@property
def ndarray(self):
return np.array(self.vertexes).T
def __eq__(self, other: object) -> bool:
if type(other).__name__ == "Polygon":
if len(self.vertexes) != len(other.vertexes):
return False
array1 = np.array(self.vertexes)
array2 = np.array(other.vertexes)
if np.max(abs(array1 - array2)) > 1e-2:
return False
return True
else:
raise TypeError("Unsupported operand type for ==")
def __repr__(self) -> str:
return "polygon vertexes: " + str(self.vertexes)
class PolygonContainer:
def __init__(self) -> None:
self.polygon_list = []
self.N = 0
self.iter_index = 0
def __len__(self):
return len(self.polygon_list)
def __getitem__(self, index):
if index > self.N:
raise IndexError("Index out range.")
return self.polygon_list[index]
def __setitem__(self, index, value: Polygon):
if index > self.N:
raise IndexError("Index out range.")
if not type(value).__name__ == "Polygon":
raise TypeError("Unsupported operand type for []")
self.polygon_list[index] = value
def __add__(self, other: Polygon) -> bool:
if type(other).__name__ == "Polygon":
if other in self.polygon_list:
pass
else:
self.polygon_list += [other]
return PolygonContainer(self.polygon_list)
else:
raise TypeError("Unsupported operand type for +")
def __iadd__(self, other: Polygon) -> bool:
if type(other).__name__ == "Polygon":
if other in self.polygon_list:
pass
else:
self.polygon_list += [other]
self.N += 1
return self
else:
raise TypeError("Unsupported operand type for +=")
def __sub__(self, other):
if type(other).__name__ == "Polygon":
if other in self.polygon_list:
self.polygon_list.remove(other)
else:
pass
return PolygonContainer(self.polygon_list)
else:
raise TypeError("Unsupported operand type for -")
def __isub__(self, other):
if type(other).__name__ == "Polygon":
if other in self.polygon_list:
self.polygon_list.remove(other)
self.N -= 1
else:
pass
return self
else:
raise TypeError("Unsupported operand type for -=")
def __iter__(self):
self.iter_index = 0
return self
def __next__(self):
last_index = self.iter_index
if last_index >= len(self.polygon_list):
raise StopIteration
else:
self.iter_index += 1
return self.polygon_list[last_index]
def ndarray_to_vertexlist(vertexs_array: np.ndarray):
"""
vertexs_array: 2 * n, n * 2
"""
nx, n = vertexs_array.shape
if nx != 2 and n == 2:
tmp = nx
nx = n
n = tmp
vertexs_array = vertexs_array.T
elif nx == 2 and n != 2:
pass
else:
raise ValueError("Check numpy array shape!")
vertexlist = []
for i in range(n):
vertexlist += [(vertexs_array[0, i], vertexs_array[1, i])]
return vertexlist
def move_vertexes_array(
vertexs_array: np.ndarray, rot_angle: float, offset: np.ndarray
):
"""
### move vertexs, coord is fixed, change points.
rot_angle [rad].
"""
nv, n = vertexs_array.shape
no, n = offset.shape
if nv != 2 or no != 2:
raise ValueError("Check numpy array shape! 2 * n")
rot = np.array(
[
[np.cos(rot_angle), -np.sin(rot_angle)],
[np.sin(rot_angle), np.cos(rot_angle)],
]
)
offset = np.array(offset).reshape((2, 1))
return rot @ vertexs_array + offset
def change_vertexes_array_coord(
vertexs_array: np.ndarray, rot_angle: float, offset: np.ndarray
):
"""
### change vertexs coord, point is fixed, change coord.
---
rot_angle [rad]. rotate current coord to target coord
offset [m]. trans current coord to target coord
"""
nv, n = vertexs_array.shape
no, n = offset.shape
if nv != 2 or no != 2:
raise ValueError("Check numpy array shape! 2 * n")
rot = np.array(
[
[np.cos(rot_angle), np.sin(rot_angle)],
[-np.sin(rot_angle), np.cos(rot_angle)],
]
)
return rot @ (vertexs_array - offset)
def to_left(line: Line, point: Point):
"""
### 2D To left test.
l: line [(x1, y1), (x2, y2)]
p: point (x1, y1)
"""
vec1 = np.array(line[1]) - np.array(line[0])
vec2 = np.array(point) - np.array(line[0])
return np.cross(vec1, vec2) > 0
# def anticlockwise_vertexes_sort(vertexes: List[Point]):
# """
# ### anticlockwise sort.
# """
# vertexes_array = np.array(vertexes).T # 2 * N
# center_x, center_y = np.mean(vertexes_array, axis=1)
# n = len(vertexes)
# for i in range(n):
# for j in range(n - i - 1):
# line = [(center_x, center_y), (vertexes[j][0], vertexes[j][1])]
# point = (vertexes[j + 1][0], vertexes[j + 1][1])
# if not to_left(line, point):
# temp = vertexes[j]
# vertexes[j] = vertexes[j + 1]
# vertexes[j + 1] = temp
# sorted_vertexes = vertexes
# return sorted_vertexes
def get_bottom_point(vertexes: List[Point]):
min_index = 0
n = len(vertexes)
for i in range(n):
if vertexes[i][1] < vertexes[min_index][1] or (
vertexes[i][1] == vertexes[min_index][1]
and vertexes[i][0] < vertexes[min_index][0]
):
min_index = i
return min_index
def pointset_to_convex_hull(vertexes_list: List[Point]):
N = len(vertexes_list)
sorted_vertexes = anticlockwise_vertexes_sort(vertexes_list)
if N < 3:
raise ValueError("point too small.")
if N == 3:
return sorted_vertexes
from scipy.spatial import ConvexHull
hull = ConvexHull(np.array(sorted_vertexes))
hull_array = hull.points[hull.vertices, :].T
return ndarray_to_vertexlist(hull_array)
def anticlockwise_vertexes_sort(vertexes: List[Point]):
"""
### anticlockwise sort.
"""
vertexes_array = np.array(vertexes).T
center_x, center_y = np.mean(vertexes_array, axis=1)
point_with_angle = []
n = len(vertexes)
for i in range(n):
atan2 = np.arctan2(vertexes[i][1] - center_y, vertexes[i][0] - center_x)
if atan2 < 0:
atan2 += 2 * np.pi
point_with_angle += [(vertexes[i], atan2)]
for i in range(n):
for j in range(n - i - 1):
if point_with_angle[j][1] > point_with_angle[j + 1][1]:
temp = point_with_angle[j]
point_with_angle[j] = point_with_angle[j + 1]
point_with_angle[j + 1] = temp
sorted_vertexes = [vertex for vertex, _ in point_with_angle]
return sorted_vertexes
def line_intersect_line(l1: Line, l2: Line):
"""
### Line interset line test.
point: (x, y)
l1: [point, point]
l2: [point, point]
"""
if to_left(l2, l1[0]) ^ to_left(l2, l1[1]): # 异或, 一个在左边,一个在右边
if to_left(l1, l2[0]) ^ to_left(l1, l2[1]):
return True
return False
def point_in_circle(point: Point, circle: Circle):
"""
### Point in circle test.
circle: (x, y, r)
point: (x, y)
"""
if np.hypot(point[0] - circle[0], point[1] - circle[1]) < circle[2]:
return True
return False
def line_intersect_circle(line: Line, circle):
"""
### Line intersect circle test.
circle: (x, y, r)
line: [p1, p2]
"""
if point_in_circle(line[0], circle) or point_in_circle(line[1], circle):
return True
oa = np.array([circle[0] - line[0][0], circle[1] - line[0][1]])
ob = np.array([circle[0] - line[1][0], circle[1] - line[1][1]])
ao = -oa
bo = -ob
ab = np.array([line[0][0] - line[1][0], line[0][1] - line[1][1]])
ba = -ab
d = abs(np.cross(ab, ob) / np.linalg.norm(ab))
if d <= circle[2]:
if np.dot(ao, ab) > 0 and np.dot(bo, ba) > 0:
return True
def vertexes_to_lines(vertexes: List[Point]):
"""
### From anticlockwise vertexes get anticlockwise lines.
"""
lines = []
newvertexes = deepcopy(vertexes)
newvertexes.append(newvertexes[0])
for i in range(len(newvertexes) - 1):
lines.append((newvertexes[i], newvertexes[i + 1]))
return lines
def lines_to_norm(lines: List[Line]):
"""
### Return every norm vector without normlize.
"""
norms = []
for line in lines:
vec = np.array(line[0]) - np.array(line[1])
norms.append((vec[1], -vec[0])) # (y,-x) in the left
return norms
def vertexes_to_norm(vertexes: List[Point]):
lines = vertexes_to_lines(vertexes)
return lines_to_norm(lines)
def get_polygon_area(polygon: Polygon):
def getS(a, b, c):
"""
Get triangle area.
"""
return abs(
((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) * 0.5
)
total_area = 0
for i in range(1, len(polygon.vertexes) - 1):
total_area += getS(
polygon.vertexes[0], polygon.vertexes[i], polygon.vertexes[i + 1]
)
return total_area
def polygon_intersect_polygon(polygon1: Polygon, polygon2: Polygon):
def dotProduct(nor, points: list):
res = []
for p in points:
res.append(nor[0] * p[0] + nor[1] * p[1])
return (min(res), max(res))
sep_axis = polygon1.norms + polygon2.norms
for sep in sep_axis:
res1 = dotProduct(sep, polygon1.vertexes)
res2 = dotProduct(sep, polygon2.vertexes)
if res1[1] < res2[0] or res1[0] > res2[1]:
return False
else:
continue
return True
def polygon_intersect_line(polygon: Polygon, line: Line):
"""
### Line intersect this polygon ?
line: [p1(x,y), p2]
"""
for l in polygon.lines:
if line_intersect_line(line, l):
return True
return False
# def point_in_polygon(point: Point, polygon: Polygon):
# """
# ### Point in polygon ?
# Point: (x, y)
# """
# for l in polygon.lines:
# if not to_left(l, point):
# return False
# return True
def point_in_polygon(point: Point, polygon: Polygon):
"""
### Point in polygon ?
Point: (x, y)
"""
px, py = point
polygon_array = np.array(polygon.vertexes)
xmin, ymin = np.min(polygon_array, axis=0)
xmax, ymax = np.max(polygon_array, axis=0)
if px > xmax or px < xmin or py > ymax or py < ymin:
return False
N = len(polygon.vertexes)
is_in = False
for i, corner in enumerate(polygon.vertexes):
next_i = i + 1 if i + 1 < N else 0
x1, y1 = corner
x2, y2 = polygon.vertexes[next_i]
if (x1 == px and y1 == py) or (x2 == px and y2 == py): # if point is on vertex
is_in = True
break
if min(y1, y2) < py <= max(y1, y2): # find horizontal edges of polygon
x = x1 + (py - y1) * (x2 - x1) / (y2 - y1)
if x == px: # if point is on edge
is_in = True
break
elif x > px: # if point is on left-side of line
is_in = not is_in
if py == y1 and py == y2:
if min(x1, x2) < px < max(x1, x2):
is_in = True
break
return is_in
def polygon_in_polygon(lhs_polygon: Polygon, rhs_polygon: Polygon):
"""
### Polygon in polygon ?
"""
for vertex in lhs_polygon.vertexes:
if not point_in_polygon(rhs_polygon, vertex):
return False
return True
def point_distance_line(point: Point, line: Line):
"""
### Point distance linesegment.
"""
A, B = line[0], line[1]
vec_AB = np.array(B) - np.array(A)
vec_AP = np.array(point) - np.array(A)
t = (vec_AB @ vec_AP) / (vec_AB @ vec_AB)
if t >= 1:
Dx = B[0]
Dy = B[1]
elif t > 0:
Dx = A[0] + vec_AB[0] * t
Dy = A[1] + vec_AB[1] * t
else:
Dx = A[0]
Dy = A[1]
vec_PD = [Dx - point[0], Dy - point[1]]
return np.sqrt(vec_PD[0] * vec_PD[0] + vec_PD[1] * vec_PD[1])
def line_distance_line(line1: Line, line2: Line):
a = line1[0]
b = line1[1]
c = line2[0]
d = line2[1]
dist_a_to_cd = point_distance_line(a, line2)
dist_b_to_cd = point_distance_line(b, line2)
dist_c_to_ab = point_distance_line(c, line1)
dist_d_to_ab = point_distance_line(d, line1)
return min(dist_a_to_cd, dist_b_to_cd, dist_c_to_ab, dist_d_to_ab)
def line_line_angle(line1: Line, line2: Line):
line_vec1 = np.array([line1[1][0] - line1[0][0], line1[1][1] - line1[0][1]])
line_vec2 = np.array([line2[1][0] - line2[0][0], line2[1][1] - line2[0][1]])
theta_1 = np.arctan2(line_vec1[1], line_vec1[0])
theta_2 = np.arctan2(line_vec2[1], line_vec2[0])
if theta_1 * theta_2 >= 0:
insideAngle = abs(theta_1 - theta_2)
else:
insideAngle = abs(theta_1) + abs(theta_2)
if insideAngle > np.pi:
insideAngle = 2 * np.pi - insideAngle
return insideAngle
def point_distance_polygon(point: Point, polygon: Polygon):
"""
### Point distance polygon
"""
dis_list = []
for line in polygon.lines:
dis = point_distance_line(point, line)
dis_list += [dis]
return min(dis_list)
def get_polygon_halfspaces(polygon: Polygon):
"""
Return A, b, the polygon can represent A@[x,y] <= b
[x,y] in polygon.
"""
N = len(polygon.lines)
A_ret = np.zeros((N, 2))
b_ret = np.zeros((N, 1))
for i in range(N):
v1, v2 = polygon.lines[i][1], polygon.lines[i][0]
ab = np.zeros((2, 1))
if abs(v1[0] - v2[0]) < 1e-10:
if v2[1] < v1[1]:
Atmp = np.array([1, 0])
btmp = v1[0]
else:
Atmp = np.array([-1, 0])
btmp = -v1[0]
elif abs(v1[1] - v2[1]) < 1e-10:
if v1[0] < v2[0]:
Atmp = np.array([0, 1])
btmp = v1[1]
else:
Atmp = np.array([0, -1])
btmp = -v1[1]
else:
temp1 = np.array([[v1[0], 1], [v2[0], 1]])
temp2 = np.array([[v1[1]], [v2[1]]])
ab = np.linalg.inv(temp1) @ temp2
a = ab[0, 0]
b = ab[1, 0]
if v1[0] < v2[0]:
Atmp = np.array([-a, 1])
btmp = b
else:
Atmp = np.array([a, -1])
btmp = -b
A_ret[i, :] = Atmp
b_ret[i, :] = btmp
return A_ret, b_ret
def test_scale_halfspaces():
import random
shape_points = [(random.randint(0, 10), random.randint(0, 10)) for i in range(3)]
polygon = Polygon(shape_points)
A, b = get_polygon_halfspaces(polygon)
def test_halfspaces():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
shape_points = [(random.randint(0, 10), random.randint(0, 10)) for i in range(3)]
polygon = Polygon(shape_points)
A, b = get_polygon_halfspaces(polygon)
for _ in range(100):
point = (random.randint(0, 10), random.randint(0, 10))
point_array = np.array([point])
flag1 = point_in_polygon(polygon, point)
flag2 = np.all(A @ point_array.T < b)
plt.cla()
plt_utils.plot_polygon(polygon)
plt.plot(point[0], point[1], "ro")
plt.draw()
plt.pause(0.1)
if flag1 == flag2:
print(f"\033[032m[test halfspaces pass, {flag1}]\033[0m")
else:
print(f"\033[031m[test halfspaces fail, {flag1}]\033[0m")
def test_single_area():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
shape_point = [(9.75, 3.0), (7.25, 3.0), (7.25, 9.0), (9.75, 9.0)]
vehicle_point = (9.4555, 5.60)
obstacle_polygon = Polygon(shape_point)
area = get_polygon_area(obstacle_polygon)
plt_utils.plot_polygon(obstacle_polygon)
plt.plot(vehicle_point[0], vehicle_point[1], "ro")
plt.draw()
plt.pause(0.1)
total_area = 0
for l in obstacle_polygon.lines:
a, b, c = l[0], l[1], vehicle_point
total_area += (
np.fabs((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) * 0.5
)
print(f"\033[032m[in polygon , {area,total_area}]\033[0m")
plt.show()
def test_area():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
for i in range(100):
shape_points = [
(random.randint(0, 10), random.randint(0, 10)) for i in range(4)
]
convexhull_points = pointset_to_convex_hull(shape_points)
convex_polygon = Polygon(convexhull_points)
plt_utils.plot_polygon(convex_polygon)
plt.draw()
area = get_polygon_area(convex_polygon)
point = (random.randint(0, 10), random.randint(0, 10))
plt.plot(point[0], point[1], "ro")
plt.draw()
plt.pause(0.5)
total_area = 0
for l in convex_polygon.lines:
a, b, c = l[0], l[1], point
# total_area += (
# np.fabs(
# c[0] * a[1]+ a[0] * b[1]+ b[0] * c[1]- c[0] * b[1]- a[0] * c[1]- b[0] * a[1]
# )
# * 0.5
# )
total_area += (
np.fabs((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))
* 0.5
)
if point_in_polygon(convex_polygon, point):
if abs(total_area - area) < 1e-3:
print(f"\033[032m[in polygon , test pass, {area==total_area}]\033[0m")
else:
print(f"\033[031m[in polygon , test fail, {area,total_area}]\033[0m")
else:
if abs(total_area - area) < -1e-3:
print(f"\033[031m[out polygon , test fail, {area,total_area}]\033[0m")
else:
print(f"\033[032m[out polygon , test pass, {total_area>=area}]\033[0m")
plt.pause(0.1)
plt.cla()
def test_convex_hull():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
for i in range(50):
shape_points = [
(random.randint(0, 10), random.randint(0, 10)) for i in range(7)
]
plt.cla()
plt_utils.plot_polygon(Polygon(shape_points))
plt.pause(0.1)
plt.draw()
convexhull_points = pointset_to_convex_hull(shape_points)
plt_utils.plot_polygon(Polygon(convexhull_points))
plt.pause(0.5)
plt.draw()
def test_polygon_eq():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
for i in range(50):
shape_points = [
(random.randint(0, 10), random.randint(0, 10)) for i in range(7)
]
p1 = Polygon(shape_points)
# shape_points = [
# (random.randint(0, 10), random.randint(0, 10)) for i in range(7)
# ]
p2 = Polygon(shape_points)
if p1 == p2:
print("p1 == p2")
print(f"\033[032m[polygon_eq, test pass, {p1!=p2}]\033[0m")
def test_polygon_eq_list():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
for i in range(5):
shape_points = [
(random.randint(0, 10), random.randint(0, 10)) for i in range(7)
]
plist = [Polygon(shape_points)]
p = Polygon(shape_points)
if p in plist:
print(f"\033[032m[polygon_eq, test pass, {p}]\033[0m")
def test_polygon_container():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
polygon_container1 = PolygonContainer()
for i in range(5):
shape_points = [
(random.randint(0, 10), random.randint(0, 10)) for i in range(7)
]
polygon_container1 += Polygon(shape_points)
for polygon in polygon_container1:
print(polygon)
print(polygon_container1.iter_index)
print(len(polygon_container1))
for polygon in polygon_container1:
print(polygon)
def test_point_polygon():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
plt.figure()
for i in range(50):
shape_points = [
(random.randint(0, 10), random.randint(0, 10)) for i in range(5)
]
point = (random.randint(0, 10), random.randint(0, 10))
polygon = Polygon(shape_points)
plt.cla()
plt_utils.plot_polygon(polygon)
plt.plot(point[0], point[1], "ro")
plt.pause(0.5)
plt.draw()
if point_in_polygon(point, polygon):
distance = point_distance_polygon(point, polygon)
print(f"point in polygon . min distance is {distance}")
plt.pause(1)
def test_point_polygon1():
import random
import matplotlib.pyplot as plt
import CarlaAutoParking.utils.plt_utils as plt_utils
shape_points = [(0, 10), (0, 7), (5, 1)]
shape_points = [(0, 5), (3, 3), (8, 6), (1, 9), (3, 1)]
point = (0, 9)
point = (2, 6)
polygon = Polygon(shape_points)
plt.cla()
plt_utils.plot_polygon(polygon)
plt.plot(point[0], point[1], "ro")
plt.draw()
plt.pause(0.1)
# pointset_to_convex_hull()
import time
start = time.time_ns()
for _ in range(10000):
point_in_polygon(point, polygon)
print(f"point in polygon time is {time.time_ns() - start:5d}")
# print(f"is in{point_in_polygon(point, polygon)}")
# print(f"distance {point_distance_polygon(point, polygon)}")
if __name__ == "__main__":
test_point_polygon() |
using DSharpPlus.Entities;
using DSharpPlus.SlashCommands;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Principal;
using System.Threading.Tasks;
using UPBot.UPBot_Code;
using UPBot.UPBot_Code.DataClasses;
namespace UPBot {
/// <summary>
/// Цeather command, allows users to get information about the weather in their city
/// Made with help of weatherapi.com
/// Information can be false from time to time, but it works.
/// Author: J0nathan550
/// </summary>
public class Weather : ApplicationCommandModule {
[SlashCommand("weather", "Get weather information from any city")]
public async Task WeatherCommand(InteractionContext ctx, [Option("city", "Weather about the city")] string city = null) {
try {
if (string.IsNullOrWhiteSpace(Configs.WeatherAPIKey)) {
Utils.Log($"Weather API Key is not defined", null);
await ctx.CreateResponseAsync(Utils.GenerateErrorAnswer(ctx.Guild.Name, "Weather", "Weather API Key is not specified"));
return;
}
if (city == null) {
DiscordEmbedBuilder discordEmbed = new DiscordEmbedBuilder() {
Title = "Error!",
Description = "Looks like you typed a wrong city, or you typed nothing.",
Color = DiscordColor.Red
};
await ctx.CreateResponseAsync(discordEmbed.Build());
return;
}
Utils.Log($"Weather executed by {ctx.User} command: Trying to get information from city: {city}", null);
using HttpClient response = new();
string json;
try {
json = response.GetStringAsync($"https://api.weatherapi.com/v1/forecast.json?key={Configs.WeatherAPIKey}&q={city}&days=3&aqi=yes&alerts=yes").Result;
} catch (Exception ex) {
await ctx.CreateResponseAsync($"Double check if the city _{city}_ is correct.");
return;
}
WeatherData data = JsonConvert.DeserializeObject<WeatherData>(json);
if (data == null) {
DiscordEmbedBuilder discordEmbed = new() {
Title = "Error!",
Description = "There was a problem in getting weather information, try again.",
Color = DiscordColor.Red
};
await ctx.CreateResponseAsync(discordEmbed.Build());
return;
}
DiscordColor orangeColor = new DiscordColor("#fc7f03");
DiscordEmbedBuilder discordEmbedBuilder = new() {
Title = $"Weather information - {city}",
Timestamp = DateTime.Parse(data.current.LastUpdated),
Color = orangeColor,
Footer = new DiscordEmbedBuilder.EmbedFooter() {
Text = "Last weather update: ",
IconUrl = "https://media.discordapp.net/attachments/1137667651326447726/1137668268426002452/cloudy.png"
},
Thumbnail = new DiscordEmbedBuilder.EmbedThumbnail() {
Url = $"https:{data.current.Condition.Icon}"
},
};
discordEmbedBuilder.AddField(":cityscape: City", $"{data.location.Name}", true);
discordEmbedBuilder.AddField(":map: Region", $"{(string.IsNullOrWhiteSpace(data.location.Region) ? data.location.Name : data.location.Region)}", true);
discordEmbedBuilder.AddField(":globe_with_meridians: Country", $"{(string.IsNullOrWhiteSpace(data.location.Country) ? data.location.Name : data.location.Country)}", true);
discordEmbedBuilder.AddField(":map: Coordinates", $"ϕ{data.location.Lat} λ{data.location.Lon}", true);
discordEmbedBuilder.AddField($":timer: Timezone", $"{(string.IsNullOrWhiteSpace(data.location.TzId) ? "__undefined__" : data.location.TzId)}", true);
discordEmbedBuilder.AddField(":clock1:Time", $"{data.location.Localtime}", true);
discordEmbedBuilder.AddField(":thermometer: Temperature", $"{data.current.TempC}°C/{data.current.TempF}°F", true);
discordEmbedBuilder.AddField(":thermometer: Feels like", $"{data.current.FeelslikeC}°C/{data.current.FeelslikeF}°F", true);
discordEmbedBuilder.AddField(":sunny: Condition", $"{(string.IsNullOrWhiteSpace(data.current.Condition.Text) ? "__undefined__" : data.current.Condition.Text)}", true);
discordEmbedBuilder.AddField(":leaves: Wind speed", $"{data.current.WindKph}Kph/{data.current.WindMph}Mph", true);
discordEmbedBuilder.AddField(":triangular_ruler: Wind angle", $"{data.current.WindDegree}°", true);
discordEmbedBuilder.AddField(":straight_ruler: Wind dir", $"{(string.IsNullOrWhiteSpace(data.current.WindDir) ? "__undefined__" : data.current.WindDir)}", true);
discordEmbedBuilder.AddField(":cloud: Clouds", $"{data.current.Cloud}", true);
discordEmbedBuilder.AddField(":droplet: Precip", $"{data.current.PrecipMm}mm/{data.current.PrecipIn}in", true);
discordEmbedBuilder.AddField(":cloud_rain: Humidity", $"{data.current.Humidity}%", true);
discordEmbedBuilder.AddField(":beach_umbrella: UVs", $"{data.current.Uv}", true);
discordEmbedBuilder.AddField(":compression: Pressure", $"{data.current.PressureMb}Mb/{data.current.PressureIn}In", true);
discordEmbedBuilder.AddField(":railway_track: Visibility", $"{data.current.VisKm}Km/{data.current.VisMiles}M", true);
List<string> convertedForecastStrings = new();
for (int i = 0; i < data.forecast.Forecastday.Count; i++) {
convertedForecastStrings.Add(
$"Condition: {data.forecast.Forecastday[i].Day.Condition.Text} :sunny:\n" +
$"Max: {data.forecast.Forecastday[i].Day.MaxtempC}C/{data.forecast.Forecastday[i].Day.MaxtempF}F\n" +
$"Min: {data.forecast.Forecastday[i].Day.MintempC}C/{data.forecast.Forecastday[i].Day.MintempF}F\n" +
$"Avg.: {data.forecast.Forecastday[i].Day.AvgtempC}C/{data.forecast.Forecastday[i].Day.AvgtempF}F\n" +
$"Will it rain?: {(data.forecast.Forecastday[i].Day.DailyWillItRain == 1 ? "Yes :cloud_rain:" : "No :sunny:")} \n" +
$"Chance of rain: {data.forecast.Forecastday[i].Day.DailyChanceOfRain}%\n" +
$"Avg. Humidity: {data.forecast.Forecastday[i].Day.Avghumidity}\n" +
$"Precip: {data.forecast.Forecastday[i].Day.TotalprecipMm}mm/{data.forecast.Forecastday[i].Day.TotalprecipIn}in\n" +
$"Will it snow?: {(data.forecast.Forecastday[i].Day.DailyWillItSnow == 1 ? "Yes :cloud_snow:" : "No :sunny:")}\n" +
$"Chance of snow: {data.forecast.Forecastday[i].Day.DailyChanceOfSnow}%\n" +
$"Total snow: {data.forecast.Forecastday[i].Day.TotalsnowCm}\n" +
$"Ultraviolet index: {data.forecast.Forecastday[i].Day.Uv} :beach_umbrella:");
discordEmbedBuilder.AddField($"Date: {data.forecast.Forecastday[i].Date}", convertedForecastStrings[i], true);
}
discordEmbedBuilder.AddField("Astronomic Info",
$"Sunrise will be: {data.forecast.Forecastday[0].Astro.Sunrise} :sunrise:\n" +
$"Sunset will be: {data.forecast.Forecastday[0].Astro.Sunset} :city_sunset:\n" +
$"Moonrise will be: {data.forecast.Forecastday[0].Astro.Moonrise} :full_moon:\n" +
$"Moonset will be: {data.forecast.Forecastday[0].Astro.Moonset} :crescent_moon: \n" +
$"Moon phase: {data.forecast.Forecastday[0].Astro.MoonPhase} :full_moon:\n" +
$"Moon illumination: {data.forecast.Forecastday[0].Astro.MoonIllumination} :bulb:\n" +
$"Is moon up?: {(data.forecast.Forecastday[0].Astro.IsMoonUp == 1 ? "Yes" : "No")} :full_moon:\n" +
$"Is sun up?: {(data.forecast.Forecastday[0].Astro.IsSunUp == 1 ? "Yes" : "No")} :sunny:", false);
await ctx.CreateResponseAsync(discordEmbedBuilder.Build());
} catch (Exception ex) {
Utils.Log($"Weather error command:\nMessage: {ex.Message}\nStacktrace:{ex.StackTrace}", null);
DiscordEmbedBuilder discordEmbed = new DiscordEmbedBuilder() {
Title = "Error!",
Description = $"There was a fatal error in executing weather command.\nMessage: {ex.Message}\nStacktrace: {ex.StackTrace}",
Color = DiscordColor.Red
};
await ctx.CreateResponseAsync(discordEmbed.Build());
}
}
}
} |
package com.karrar.marvelheroes.data.marvelResponse
import com.google.gson.annotations.SerializedName
data class MovieResponse(
@SerializedName("id")
val id: Int?,
@SerializedName("title")
val title: String?,
@SerializedName("release_date")
val releaseDate: String?,
@SerializedName("cover_url")
val coverUrl: String?,
@SerializedName("trailer_url")
val trailerUrl: String?,
@SerializedName("overview")
val overview: String?,
@SerializedName("box_office")
val boxOffice: String?,
@SerializedName("chronology")
val chronology: Int?,
@SerializedName("directed_by")
val directedBy: String?,
@SerializedName("duration")
val duration: Int?,
@SerializedName("imdb_id")
val imdbId: String?,
@SerializedName("phase")
val phase: Int?,
@SerializedName("post_credit_scenes")
val postCreditScenes: Int?,
@SerializedName("saga")
val saga: String?,
@SerializedName("related_movies")
val relatedMovies: List<MovieResponse?>
) |
/**
* Initiates canvas scrolling if current cursor point is close to a border.
* Cancelled when current point moves back inside the scrolling borders
* or cancelled manually.
*
* Default options :
* scrollThresholdIn: [ 20, 20, 20, 20 ],
* scrollThresholdOut: [ 0, 0, 0, 0 ],
* scrollRepeatTimeout: 15,
* scrollStep: 10
*
* Threshold order:
* [ left, top, right, bottom ]
*
*/
export default class AutoScroll {
static $inject: string[];
/**
* @param config
* @param eventBus
* @param canvas
*/
constructor(config: any, eventBus: EventBus, canvas: Canvas);
/**
* Starts scrolling loop.
* Point is given in global scale in canvas container box plane.
*
* @param point
*/
startScroll(point: Point): void;
/**
* Stops scrolling loop.
*/
stopScroll(): void;
/**
* Overrides defaults options.
*
* @param options
*/
setOptions(options: any): void;
}
type Point = import('../../util/Types').Point;
type EventBus = import('../../core/EventBus').default;
type Canvas = import('../../core/Canvas').default; |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Homepage</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- link to an bootstrap library -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- link to an icon library -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.7.2/font/bootstrap-icons.min.css" rel="stylesheet">
<!-- Inter font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inter">
<!-- scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- links for css -->
<link rel="stylesheet" href="../components/css/navbar.css">
<link rel="stylesheet" href="../components/css/base.css">
<link rel="stylesheet" href="../components/css/footer.css">
<link rel="stylesheet" href="../components/css/subnavbar.css">
<link rel="stylesheet" href="../../css/hompage.css">
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-custom shadow fixed-top">
<div class="container-fluid">
<a class="navbar-brand logo-custom" href="../pages/homepage.html">LOGO</a>
<form class="d-flex">
<input class="form-control me-2 border-dark" type="search" placeholder="Search" aria-label="Search">
</form>
<div class="d-flex">
<a href="../pages/registration.html" class="me-3 fs-3 text-black"><i class="bi bi-person"></i></a>
<a href="../pages/cart.html" class="me-3 fs-3 text-black"><i class="bi bi-cart"></i></a>
</div>
</div>
</nav>
<div class="page-wrapper">
<!-- Subnavbar -->
<nav class="navbar navbar-expand-lg subnavbar-custom shadow">
<div class="container-fluid ">
<div class="collapse navbar-collapse " id="navbarNav">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link text-white" href="../pages/tovary.html">PLAYSTATION</a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="../pages/tovary.html">NINTENDO</a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="../pages/tovary.html">PC</a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="../pages/tovary.html">XBOX</a>
</li>
</ul>
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link text-white" href="../pages/contacts.html">CONTACTS</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container mt-5">
<h2 class="text-new mb-4">NEW RELEASES</h2>
<div id="carouselIndicators" class="carousel slide bg-secondary rounded mx-auto w-85" data-bs-ride="carousel" style="height: 273px">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button>
</div>
<div class="carousel-inner rounded" style="width: 1192; height: 273px; background-color: #ABABAB">
<div class="carousel-item active">
<img src="..." class="d-block center w-100" alt="...">
</div>
<div class="carousel-item">
<img src="..." class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="..." class="d-block w-100" alt="...">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselIndicators" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselIndicators" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</div>
<div class="container mt-5">
<h2 class="text-new mb-4">CATALOGUE</h2>
<div class="row justify-content-around">
<div class="col-lg-3 col-md-4 col-sm-5 col-6">
<a href="productpage.html">
<div class="card card-product">
<img src="..." class="card-img-top" alt="Product 1">
<div class="card-body">
<h5 class="card-title">Product 1</h5>
<span class="text-av">Available</span>
<span class="card-text">$10.00</span>
</div>
</div>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-5 col-6">
<a href="productpage.html">
<div class="card card-product">
<img src="..." class="card-img-top" alt="Product 2">
<div class="card-body">
<h5 class="card-title">Product 2</h5>
<span class="text-av">Available</span>
<span class="card-text">$10.00</span>
</div>
</div>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-5 col-6">
<a href="productpage.html">
<div class="card card-product">
<img src="..." class="card-img-top" alt="Product 3">
<div class="card-body">
<h5 class="card-title">Product 3</h5>
<span class="text-av">Available</span>
<span class="card-text">$10.00</span>
</div>
</div>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-5 col-6">
<a href="productpage.html">
<div class="card card-product">
<img src="..." class="card-img-top" alt="Product 4">
<div class="card-body">
<h5 class="card-title">Product 4</h5>
<span class="text-av">Available</span>
<span class="card-text">$10.00</span>
</div>
</div>
</a>
</div>
<div class="col-lg-3 col-md-4 col-sm-5 col-6">
<a href="productpage.html">
<div class="card card-product">
<img src="..." class="card-img-top" alt="Product 5">
<div class="card-body">
<h5 class="card-title">Product 5</h5>
<span class="text-av">Available</span>
<span class="card-text">$10.00</span>
</div>
</div>
</a>
</div>
</div>
</div>
<!-- Footer -->
<footer class="py-3 footer-custom">
<div class="container-fluid text-center">
<span class="text-muted">WTECH 2022/23</span>
<br>
<span class="text-muted">Patrik Hitka, Maria Fedosenya, Samuel Švenk</span>
</div>
</footer>
</div>
</body>
</html> |
#include <bits/stdc++.h>
using namespace std;
class TrieNode{
public:
char data;
TrieNode* children[26]; // 26 alphabets
bool isTerminal;
TrieNode(char data){
this->data = data;
for(int i=0;i<26;i++){
children[i] = NULL;
}
isTerminal = false;
}
};
class Trie{
public:
TrieNode* root;
Trie(){
root = new TrieNode('\0');
}
void insertUtil(TrieNode* root, string word){
//base
if(word.size() == 0){
root->isTerminal = true;
return;
}
int index = word[0] - 'a';
TrieNode* child;
//present
if(root->children[index] != NULL){
child = root->children[index];
}
//not present
else{
child = new TrieNode(word[0]);
root->children[index] = child;
}
//recursive call
insertUtil(child, word.substr(1));
}
void insertVoid(string word){
insertUtil(root, word);
}
void searchUtil(TrieNode* root, string word){
//base
if(word.size() == 0){
if(root->isTerminal){
cout<<"Word is present"<<endl;
}
else{
cout<<"Word is not present"<<endl;
}
return;
}
int index = word[0] - 'a';
TrieNode* child;
//present
if(root->children[index] != NULL){
child = root->children[index];
}
//not present
else{
cout<<"Word is not present"<<endl;
return;
}
//recursive call
searchUtil(child, word.substr(1));
} // O(length of word)
void search(string word){
return searchUtil(root, word);
}
};
int main(){
Trie *t = new Trie();
t->insertVoid("hello");
t->search("hello");
t->search("hell");
return 0;
} |
@extends('layouts.auth')
@section('content')
<div class="container mx-auto px-5 md:px-0">
<div class="flex flex-col w-full sm:w-2/3 md:w-2/3 lg:w-1/2 xl:w-1/2 bg-white rounded-2xl p-12 my-36 mx-auto">
<a href="/" class="text-center mb-14">
<h1 class="text-accentCyan font-semibold font-poppins" style="font-size: 27px">How<span
class="text-accentOrange">iday.</span>
</h1>
</a>
<h1 class="text-left text-accentDarkGray font-poppins text-base sm:text-2xl font-medium mb-4 sm:mb-7 ">
Create an Account Now!</h1>
<form action="{{ route('register') }}" method="POST">
@csrf
@error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
<input type="text" placeholder="Name"
class="rounded-2xl border border-gray-200 text-accentBlack form-input px-4 sm:px-6 py-3 sm:py-5 bg-white focus:outline-none font-poppins font-normal w-full focus:ring-2 focus:ring-accentCyan sm:mb-11 mb-5 @error('name') is-invalid @enderror"
id="name" type="text" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
@error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
<input type="text" placeholder="Username"
class="rounded-2xl border border-gray-200 text-accentBlack form-input px-4 sm:px-6 py-3 sm:py-5 bg-white focus:outline-none font-poppins font-normal w-full focus:ring-2 focus:ring-accentCyan sm:mb-11 mb-5 @error('username') is-invalid @enderror"
id="username" type="text" name="username" value="{{ old('username') }}" required
autocomplete="username" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
<input type="email" placeholder="Email Address"
class="rounded-2xl border border-gray-200 text-accentBlack form-input px-4 sm:px-6 py-3 sm:py-5 bg-white focus:outline-none font-poppins font-normal w-full focus:ring-2 focus:ring-accentCyan sm:mb-11 mb-5 @error('email') is-invalid @enderror"
id="email" name="email" value="{{ old('email') }}" required autocomplete="email">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
<input type="password" placeholder="Password (8-20 Characters)"
class="rounded-2xl border border-gray-200 text-accentBlack form-input px-4 sm:px-6 py-3 sm:py-5 bg-white focus:outline-none font-poppins font-normal w-full focus:ring-2 focus:ring-accentCyan sm:mb-11 mb-5 @error('password') is-invalid @enderror"
id="password" name="password" required autocomplete="new-password">
<input type="password" placeholder="Confirm Password"
class="rounded-2xl border border-gray-200 text-accentBlack form-input px-4 sm:px-6 py-3 sm:py-5 bg-white focus:outline-none font-poppins font-normal w-full focus:ring-2 focus:ring-accentCyan sm:mb-4 mb-3"
id="password-confirm" name="password_confirmation" required autocomplete="new-password">
<div class="flex flex-row items-center mb-11">
<input type="checkbox" required class="form-checkbox mr-2 rounded-full">
<p class="font-poppins font-medium text-base text-left text-accentDarkGray">By signing up, i agree to
Howiday Terms of Services</p>
</div>
<div class="text-center mb-11">
<button type="submit"
class="text-white bg-accentCyan hover:bg-accentCyanHover py-3 px-20 rounded-md text-center lg:text-left transition duration-300 font-medium inline-block cursor-pointer focus:outline-none focus:ring-1 focus:ring-blue-500"
style="box-shadow: 0px 8px 15px 0px #3BBABE;
">Continue
</button>
</div>
</form>
<p class="text-sm sm:text-base font-poppins font-medium text-accentDarkGray text-center">Already have an
account?
<a href="{{ route('login') }}">
<span class="text-accentOrange hover:underline">Sign In
</span>
</a>
</p>
</div>
</div>
@endsection |
import { defineStore } from 'pinia'
import { DateTime } from 'luxon';
import _ from "lodash";
export const useStore = defineStore('store', {
state: () => ({
currentSelectSearch:null,
schemas: [],
notifications:[],
user: null
}),
actions: {
setSchemas(schemas){
this.schemas = schemas
},
setCurrentSelectSearch(id){
if(id === this.currentSelectSearch)
this.currentSelectSearch = null;
else
this.currentSelectSearch = id;
},
addNotify(notify){
notify.id = DateTime.now().toMillis();
this.notifications.push(notify);
},
removeNotify(id){
this.notifications = useFilter(this.notifications, (notify) => notify.id !== id);
},
setUser(data){
this.user = data;
}
},
getters: {
getSchemas(state){
return state.schemas;
},
getSchemasBySelectSearch(state){
if(!isNil(state.currentSelectSearch)){
const key = state.currentSelectSearch.split("-")[1];
for (const index in state.schemas) {
let name = _.get(state.schemas[index], 'name');
let type = _.get(state.schemas[index], 'type');
if(name === key)
{
return {
nameCfg: index,
type
};
}
}
}
return null;
},
getNotifications(state){
return state.notifications;
},
getUser(state){
return state.user;
}
},
}) |
/*
* dedupv1 - iSCSI based Deduplication System for Linux
*
* (C) 2008 Dirk Meister
* (C) 2009 - 2011, Dirk Meister, Paderborn Center for Parallel Computing
* (C) 2012 Dirk Meister, Johannes Gutenberg University Mainz
*
* This file is part of dedupv1.
*
* dedupv1 is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* dedupv1 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with dedupv1. If not, see http://www.gnu.org/licenses/.
*/
#ifndef GROUP_MONITOR_H__
#define GROUP_MONITOR_H__
#include <core/dedup.h>
#include "default_monitor.h"
#include "dedupv1d.h"
#include "dedupv1d_group.h"
#include <list>
#include <string>
namespace dedupv1d {
namespace monitor {
/**
* The group monitor reports informations about the currently
* configured group to the user.
*
* \ingroup monitor
*/
class GroupMonitorAdapter : public MonitorAdapter {
friend class GroupMonitorAdapterRequest;
private:
/**
* Reference to the dedupv1d daemon
*/
dedupv1d::Dedupv1d* ds;
public:
/**
* Constructor.
*
* @param ds
* @return
*/
explicit GroupMonitorAdapter(dedupv1d::Dedupv1d* ds);
/**
* Destructor.
* @return
*/
virtual ~GroupMonitorAdapter();
/**
* Creates a new group monitor request.
* @return
*/
virtual MonitorAdapterRequest* OpenRequest();
};
/**
* A group adapter request.
*
* \ingroup monitor
*/
class GroupMonitorAdapterRequest : public MonitorAdapterRequest {
private:
/**
* pointer to the parent monitor
*/
GroupMonitorAdapter* adapter;
/**
* list of options pairs.
*/
std::list< std::pair<std::string, std::string> > options;
/**
* key of the operation.
*/
std::string operation;
/**
* writes informations about a group in a JSON
* format.
*
* @param group
* @return
*/
std::string WriteGroup(const Dedupv1dGroup& group);
public:
/**
* Constructor.
* @param adapter
* @return
*/
explicit GroupMonitorAdapterRequest(GroupMonitorAdapter* adapter);
/**
* Destructor.
* @return
*/
virtual ~GroupMonitorAdapterRequest();
virtual std::string Monitor();
virtual bool ParseParam(const std::string& key, const std::string& value);
};
}
}
#endif /* GROUP_MONITOR_H_ */ |
const express = require("express")
const router = express.Router()
const User = require("../models/User.js")
const { body, validationResult } = require("express-validator")
var bcrypt = require("bcryptjs")
var jwt = require("jsonwebtoken")
router.post("/createuser", [
body("name", "Enter a valid name").isLength({ min: 3 }),
body("email", "Enter a valid email").isEmail(),
body("password", `Password must be atleast 5 characters`).isLength({ min: 5 })
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
let user = await User.findOne({ email: req.body.email })
if (user) {
return res.status(400).json({ error: "Sorry a user with this email already exist" })
}
const salt = await bcrypt.genSalt(10)
const secPass= await bcrypt.hash(req.body.password,salt)
const authToken = jwt.sign(req.body, process.env.JWT_Secret)
user = await User.create({
name: req.body.name,
password: secPass,
email: req.body.email,
userVerification : authToken
})
const data = {
user: {
id: user.id
}
}
const authtoken = jwt.sign(data, process.env.JWT_SECRET);
res.json({ authtoken })
}
catch (error) {
console.error(error.message)
res.status(500).send("Internal Servor Error")
}
})
module.exports = router |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="description" content="多彩炫酷环形时钟效果">
<meta name="description" content="">
<meta name="keywords" content="web前端,css,jQuery,javascript,demo页面">
<meta name="author" content="">
<title>多彩炫酷环形时钟效果</title>
<link rel="stylesheet" href="css/demo.css" type="text/css">
<link rel="stylesheet" href="css/clock.css" type="text/css">
</head>
<body>
<div id="main">
<h1>多彩炫酷环形时钟效果实例页面</h1>
<div id="body" class="light">
<div id="content" class="show">
<div class="demo">
<div id="fancyClock">
<div class="orange clock">
<div class="display" id="hours">17</div>
<div class="front left"></div>
<div class="rotate left" id="orangeRotateLeft" style="display: block; transform: rotate(180deg); -webkit-transform: rotate(180deg);">
<div class="bg left"></div>
</div>
<div class="rotate right" id="orangeRotateRight" style="display: block; transform: rotate(75deg); -webkit-transform: rotate(75deg);">
<div class="bg right"></div>
</div>
</div>
<div class="blue clock">
<div class="display" id="minuts">01</div>
<div class="front left"></div>
<div class="rotate left" id="blueRotateLeft" style="display: block; transform: rotate(6deg); -webkit-transform: rotate(6deg);">
<div class="bg left"></div>
</div>
<div class="rotate right" id="blueRotateRight" style="display: none;">
<div class="bg right"></div>
</div>
</div>
<div class="green clock">
<div class="display" id="seconds">56</div>
<div class="front left"></div>
<div class="rotate left" id="greenRotateLeft" style="display: block; transform: rotate(180deg); -webkit-transform: rotate(180deg);">
<div class="bg left"></div>
</div>
<div class="rotate right" id="greenRotateRight" style="display: block; transform: rotate(156deg); -webkit-transform: rotate(156deg);">
<div class="bg right"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</script><script type="text/javascript" async="" src="js/ga.js"></script>
<script type="text/javascript">
(function(){
var $ = function(id){
return document.getElementById(id);
};
var o = {
hour: $("hours"), //小时数值对象
minu: $("minuts"), //分钟数值对象
sec: $("seconds"), //秒钟数值对象
orgl: $("orangeRotateLeft"), //黄色旋转左半区
orgr: $("orangeRotateRight"), //黄色旋转右半区
bluel: $("blueRotateLeft"), //蓝色旋转左半区
bluer: $("blueRotateRight"), //蓝色旋转右半区
greenl: $("greenRotateLeft"), //绿色旋转左半区
greenr: $("greenRotateRight") //绿色旋转右半区
};
var f = {
css: function(o,key){
return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];
},
zero: function(n, top){
n = parseInt(n, 10), top = top || "00";
if(n > 0){
if(n <= 9){
n = "0" + n;
}
return String(n);
}else{
return top.toString();
}
},
angle: function(v, total){
var scale = v / total, offsetx = 0, offsety = 0, an;
var angle = scale * 360; //当前角度值
//IE矩阵角度值计算
var m11 = Math.cos(Math.PI*2 / 360 * angle)
var m21 = Math.sin(Math.PI*2 / 360 * angle);
if(angle > 90){
an = angle - 90;
}else{
an = angle;
}
offsety = offsetx = (200 - 200 * Math.sqrt(2) * Math.cos(Math.PI / 180 * Math.abs(an - 45))) / 2 ;
return {
trans: "rotate("+angle+"deg)",
ie: "progid:DXImageTransform.Microsoft.Matrix(M11="+m11+",M12=-"+m21+",M21="+m21+",M22="+m11+",SizingMethod='auto expand',FilterType='nearest neighbor')",
offset: {
x: offsetx,
y: offsety
}
};
},
cartoon: function(l, r, v, part){
var total = part * 2, angleV, anglePart;
if(v <= part && v > 0){
angleV = f.angle(v, total);
l.style.display = "block";
l.style.filter = angleV.ie;
l.style.MozTransform = l.style.WebkitTransform = l.style.transform = angleV.trans;
r.style.display = "none";
//ie 旋转非居中旋转的修复
if(document.all){
l.style.left = angleV.offset.x + "px";
l.style.top = angleV.offset.y + "px";
}
}else{
v = Math.abs(v - part);
angleV = f.angle(v, total);
anglePart = f.angle(part, total);
l.style.display = "block";
l.style.filter = anglePart.ie;
l.style.MozTransform = l.style.WebkitTransform = l.style.transform = anglePart.trans;
r.style.display = "block";
r.style.filter = angleV.ie;
r.style.MozTransform = r.style.WebkitTransform = r.style.transform = angleV.trans;
if(document.all){
r.style.left = angleV.offset.x + "px";
r.style.top = angleV.offset.x + "px";
}
}
},
ui: function(){
var mytime = new Date();
var h = mytime.getHours(), m = mytime.getMinutes(), s = mytime.getSeconds();
o.hour.innerHTML = f.zero(h);
o.minu.innerHTML = f.zero(m, 60);
o.sec.innerHTML = f.zero(s, 60);
f.cartoon(o.orgl, o.orgr, h, 12);
f.cartoon(o.bluel, o.bluer, m, 30);
f.cartoon(o.greenl, o.greenr, s, 30);
setTimeout(f.ui, 1000);
}
};
f.ui();
})();
</script>
</body></html> |
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';
import 'package:shopapp/Providers/category_prov.dart';
import '../Widgets/Favourate_Widgets.dart';
class FavoritesScreen extends StatefulWidget {
const FavoritesScreen({super.key});
@override
State<FavoritesScreen> createState() => _FavoritesScreenState();
}
class _FavoritesScreenState extends State<FavoritesScreen> {
@override
void initState() {
super.initState();
Provider.of<CategoriesProv>(context, listen: false).getcategories();
}
@override
Widget build(BuildContext context) {
return Consumer<CategoriesProv>(
builder: (BuildContext context, value,child) {
return SafeArea(
child: Container(
width: double.infinity,
height: double.infinity,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
itemCount: value.list_categories.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight(
crossAxisCount: 2,
height: 215,
crossAxisSpacing: 8,
mainAxisSpacing: 4),
itemBuilder: (BuildContext context, int index) {
// log('$index');
return FavoriteItem(
imageURL: value.list_categories[index].image_url,
itemName: value.list_categories[index].cate_name,
itemStoreName:
value.list_categories[index].cate_name,
onTapAddToCart: () async {
print('onTapAddToCart: ${value.list_categories[index].id}');
},
onTapShowDetails: () {
print('onTapShowDetails: ${value.list_categories[index].id}');
},
);
},
),
),
),
);
},
);
}
}
// custom Sliver Grid Delegate
class SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight
extends SliverGridDelegate {
/// Creates a delegate that makes grid layouts with a fixed number of tiles in
/// the cross axis.
///
/// All of the arguments must not be null. The `mainAxisSpacing` and
/// `crossAxisSpacing` arguments must not be negative. The `crossAxisCount`
/// and `childAspectRatio` arguments must be greater than zero.
const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight({
required this.crossAxisCount,
this.mainAxisSpacing = 0.0,
this.crossAxisSpacing = 0.0,
this.height = 56.0,
}) : assert(crossAxisCount > 0,),
assert(mainAxisSpacing >= 0),
assert(crossAxisSpacing >= 0),
assert(height > 0);
/// The number of children in the cross axis.
final int crossAxisCount;
/// The number of logical pixels between each child along the main axis.
final double mainAxisSpacing;
/// The number of logical pixels between each child along the cross axis.
final double crossAxisSpacing;
/// The height of the crossAxis.
final double height;
bool _debugAssertIsValid() {
assert(crossAxisCount > 0);
assert(mainAxisSpacing >= 0.0);
assert(crossAxisSpacing >= 0.0);
assert(height > 0.0);
return true;
}
@override
SliverGridLayout getLayout(SliverConstraints constraints) {
assert(_debugAssertIsValid());
final double usableCrossAxisExtent =
constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1);
final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;
final double childMainAxisExtent = height;
return SliverGridRegularTileLayout(
crossAxisCount: crossAxisCount,
mainAxisStride: childMainAxisExtent + mainAxisSpacing,
crossAxisStride: childCrossAxisExtent + crossAxisSpacing,
childMainAxisExtent: childMainAxisExtent,
childCrossAxisExtent: childCrossAxisExtent,
reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
);
}
@override
bool shouldRelayout(
SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight oldDelegate) {
return oldDelegate.crossAxisCount != crossAxisCount ||
oldDelegate.mainAxisSpacing != mainAxisSpacing ||
oldDelegate.crossAxisSpacing != crossAxisSpacing ||
oldDelegate.height != height;
}
} |
export class Slug {
public value: string;
private constructor(value: string) {
this.value = value;
}
static create(value: string) {
return new Slug(value);
}
// Receives a string and returns a Slug instance
// Example: "Hello World " => "hello-world"
static createFromText(text: string) {
const slugText = text
.normalize("NFKD")
.toLocaleLowerCase()
.trim()
.replace(/\s+/g, "-")
.replace(/[^\w-]+/g, "")
.replace(/_/g, "-")
.replace(/--+/g, "-")
.replace(/-$/g, "");
return new Slug(slugText);
}
} |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using DafnyCore.Verifier;
using Microsoft.Boogie;
using Microsoft.Dafny.ProofObligationDescription;
using VC;
namespace Microsoft.Dafny;
public record VerificationTaskResult(IVerificationTask Task, VerificationRunResult Result);
public class ProofDependencyWarnings {
public static void ReportSuspiciousDependencies(DafnyOptions options, IEnumerable<VerificationTaskResult> parts,
ErrorReporter reporter, ProofDependencyManager manager) {
foreach (var resultsForScope in parts.GroupBy(p => p.Task.ScopeId)) {
WarnAboutSuspiciousDependenciesForImplementation(options,
reporter,
manager,
resultsForScope.Key,
resultsForScope.Select(p => p.Result).ToList());
}
}
public static void WarnAboutSuspiciousDependencies(DafnyOptions dafnyOptions, ErrorReporter reporter, ProofDependencyManager depManager) {
var verificationResults = (dafnyOptions.Printer as DafnyConsolePrinter).VerificationResults.ToList();
var orderedResults =
verificationResults.OrderBy(vr =>
(vr.Implementation.Tok.filename, vr.Implementation.Tok.line, vr.Implementation.Tok.col));
foreach (var (implementation, result) in orderedResults) {
if (result.Outcome != VcOutcome.Correct) {
continue;
}
Warn(dafnyOptions, reporter, depManager, implementation.Name, result.VCResults.SelectMany(r => r.CoveredElements));
}
}
public static void WarnAboutSuspiciousDependenciesForImplementation(DafnyOptions dafnyOptions, ErrorReporter reporter,
ProofDependencyManager depManager, string name,
IReadOnlyList<VerificationRunResult> results) {
if (results.Any(r => r.Outcome != SolverOutcome.Valid)) {
return;
}
var coveredElements = results.SelectMany(r => r.CoveredElements);
Warn(dafnyOptions, reporter, depManager, name, coveredElements);
}
private static void Warn(DafnyOptions dafnyOptions, ErrorReporter reporter, ProofDependencyManager depManager,
string scopeName, IEnumerable<TrackedNodeComponent> coveredElements) {
var potentialDependencies = depManager.GetPotentialDependenciesForDefinition(scopeName);
var usedDependencies =
coveredElements
.Select(depManager.GetFullIdDependency)
.OrderBy(dep => dep.Range)
.ThenBy(dep => dep.Description);
var unusedDependencies =
potentialDependencies
.Except(usedDependencies)
.OrderBy(dep => dep.Range)
.ThenBy(dep => dep.Description).ToList();
foreach (var unusedDependency in unusedDependencies) {
if (dafnyOptions.Get(CommonOptionBag.WarnContradictoryAssumptions)) {
if (unusedDependency is ProofObligationDependency obligation) {
if (ShouldWarnVacuous(dafnyOptions, scopeName, obligation)) {
var message = $"proved using contradictory assumptions: {obligation.Description}";
if (obligation.ProofObligation is AssertStatementDescription) {
message += ". (Use the `{:contradiction}` attribute on the `assert` statement to silence.)";
}
reporter.Warning(MessageSource.Verifier, "", obligation.Range, message);
}
}
if (unusedDependency is EnsuresDependency ensures) {
if (ShouldWarnVacuous(dafnyOptions, scopeName, ensures)) {
reporter.Warning(MessageSource.Verifier, "", ensures.Range,
$"ensures clause proved using contradictory assumptions");
}
}
}
if (dafnyOptions.Get(CommonOptionBag.WarnRedundantAssumptions)) {
if (unusedDependency is RequiresDependency requires) {
reporter.Warning(MessageSource.Verifier, "", requires.Range, $"unnecessary requires clause");
}
if (unusedDependency is AssumptionDependency assumption) {
if (ShouldWarnUnused(assumption)) {
reporter.Warning(MessageSource.Verifier, "", assumption.Range,
$"unnecessary (or partly unnecessary) {assumption.Description}");
}
}
}
}
}
/// <summary>
/// Some proof obligations that don't show up in the dependency list
/// are innocuous. Either they come about because of internal Dafny
/// design choices that the programmer has no control over, or they
/// just aren't meaningful in context. This method identifies cases
/// where it doesn't make sense to issue a warning. Many of these
/// cases should perhaps be eliminated by changing the translator
/// to not generate vacuous proof goals, but that may be a difficult
/// change to make.
/// </summary>
/// <param name="dep">the dependency to examine</param>
/// <returns>false to skip warning about the absence of this
/// dependency, true otherwise</returns>
private static bool ShouldWarnVacuous(DafnyOptions options, string verboseName, ProofDependency dep) {
if (dep is ProofObligationDependency poDep) {
// Dafny generates some assertions about definite assignment whose
// proofs are always vacuous. Since these aren't written by Dafny
// programmers, it's safe to just skip them all.
if (poDep.ProofObligation is DefiniteAssignment) {
return false;
}
// Some proof obligations occur in a context that the Dafny programmer
// doesn't have control of, so warning about vacuity isn't helpful.
if (poDep.ProofObligation.ProvedOutsideUserCode) {
return false;
}
// Don't warn about `assert false` being proved vacuously. If it's proved,
// it must be vacuous, but it's also probably an attempt to prove that a
// given branch is unreachable (often, but not always, in ghost code).
var assertedExpr = poDep.ProofObligation.GetAssertedExpr(options);
if (assertedExpr is not null &&
Expression.IsBoolLiteral(assertedExpr, out var lit) &&
lit == false) {
return false;
}
if (poDep.ProofObligation is AssertStatementDescription { IsIntentionalContradiction: true }) {
return false;
}
}
// Ensures clauses are often proven vacuously during well-formedness checks.
// There's unfortunately no way to identify these checks once Dafny has
// been translated to Boogie other than looking at the name. This is a significant
// limitation, because it means that function ensures clauses that are satisfied
// only vacuously won't be reported. It would great if we could change the Boogie
// encoding so that these unreachable-by-construction checks don't exist.
if (verboseName.Contains("well-formedness") && dep is EnsuresDependency) {
return false;
}
return true;
}
/// <summary>
/// Some assumptions that don't show up in the dependency list
/// are innocuous. In particular, `assume true` is often used
/// as a place to attach attributes such as `{:split_here}`.
/// Don't warn about such assumptions. Also don't warn about
/// assumptions that aren't explicit (coming from `assume` or
/// `assert` statements), for now, because they are difficult
/// for the user to control.
/// </summary>
/// <param name="dep">the dependency to examine</param>
/// <returns>false to skip warning about the absence of this
/// dependency, true otherwise</returns>
private static bool ShouldWarnUnused(ProofDependency dep) {
if (dep is AssumptionDependency assumeDep) {
if (assumeDep.Expr is not null &&
Expression.IsBoolLiteral(assumeDep.Expr, out var lit) &&
lit) {
return false;
}
return assumeDep.WarnWhenUnused;
}
return true;
}
} |
//Array Methods
/*xxxx - Manipulating Array with push()
- You can append data to the end of an array with the push function
*/
var listOfItems = ["onion, sugar, milk"];
listOfItems.push(["milk, beverage"]);
//console.log(listOfItems);
var myItems = ["Books", "Pen", "Ipod"];
myItems.push(["Laptop", "Charger", "Stand"]);
//console.log(myItems);
var multiArray = [["Glory", 23], ["Lukas", 39]];
multiArray.push(["Evelyn", 20]);
//console.log(multiArray);
/*xxxx - Manipulating Array with pop()
- You can remove an item from an array with the pop() function
*/
var mySerialNumber = [1, 2, 3, 4, 5, 6];
mySerialNumber.pop()//This will remove the last element
//console.log(mySerialNumber);
var removeArray = [["Victor", "Ada"], ["Gloria"]]
removeArray.pop();
//console.log(removeArray);
/*xxxx - Manipulating Array with shift()
- The shift function is very similar to the pop() function except
that it removes the first element instead of the last element.
*/
var mySerialNumber2 = [1, 2, 3, 4, 5, 6];
mySerialNumber2.shift();
//console.log(mySerialNumber2);
var removeArray2 = [["Victor", "Ada"], ["Gloria"]];
removeArray2.shift();
//console.log(removeArray2);
/*xxxx - Manipulating Array with unshift()
- The shift function is similar to the push() function except
that it the push() function adds an element to the end of the array,
unshift() adds an element to the beginning of the array.
*/
var addArray = ["Sarah", "Ann", "Simeon"];
addArray.unshift(["Gloria"]);
//console.log(addArray);
var addArray2 = [["Victor", "Ada"], ["Gloria"]];
addArray2.unshift(["David"]);
//console.log(addArray2); |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username')->unique();
$table->string('name');
$table->string('email')->unique();
$table->string('document')->unique();
$table->string('phone')->nullable();
$table->string('avatar')->nullable();
$table->ipAddress('ip')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->timestamp('last_login_at')->nullable();
$table->string('password');
$table->date('birth_date')->nullable();
$table->string('pix_key')->nullable();
$table->string('pix_key_type')->nullable();
$table->string('ref_code')->unique();
$table->decimal('affiliate_percent_revenue_share', 14, 0)->default(60);
$table->decimal('affiliate_percent_revenue_share_sub', 14, 0)->default(10);
$table->decimal('affiliate_cpa', 14, 0)->default(2000);
$table->decimal('affiliate_cpa_sub', 14, 0)->default(200);
$table->decimal('affiliate_min_deposit_cpa', 14, 0)->default(2000);
$table->foreignId('affiliate_id')->nullable()->constrained('users');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
}; |
import React from 'react';
import Swal from 'sweetalert2';
import './Logout.css';
import { useTranslation } from 'react-i18next';
const Logout = ({ setIsAuthenticated }) => {
const { t } = useTranslation();
const handleLogout = () => {
Swal.fire({
icon: 'question',
title: t('logout.confirm_title'),
text: t('logout.confirm_text'),
showCancelButton: true,
confirmButtonText: t('logout.confirm_button'),
}).then(result => {
if (result.value) {
Swal.fire({
timer: 1500,
showConfirmButton: false,
willOpen: () => {
Swal.showLoading();
},
willClose: () => {
localStorage.setItem('is_authenticated', false);
setIsAuthenticated(false);
},
});
}
});
};
return (
<button
style={{ marginLeft: '12px' }}
className="muted-button"
onClick={handleLogout}
>
{t('logout.button_text')}
</button>
);
};
export default Logout; |
import { NavLink as RouterNavLink } from "react-router-dom";
import {
Container,
Dropdown,
Navbar,
Nav,
NavDropdown,
NavItem,
} from "react-bootstrap";
import {
AuthenticatedTemplate,
UnauthenticatedTemplate,
} from "@azure/msal-react";
import "./NavBar.css";
import { AppUser, useAppContext } from "./AppContext";
interface UserAvatarProps {
user: AppUser;
}
function UserAvatar(props: UserAvatarProps) {
// If a user avatar is available, return an img tag with the pic
return (
<img
src={props.user.avatar || "profil.jpg"}
alt="user"
className="rounded-circle align-self-center mr-2 "
style={{ width: "42px", border: "2px solid white" }}
></img>
);
}
export default function NavBar() {
const app = useAppContext();
const user = app.user || { displayName: "", email: "" };
return (
<Navbar bg="success" variant="dark" expand="md" fixed="top">
<Container>
<Navbar.Brand href="/">All Users</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse>
<Nav className="me-auto" navbar>
<AuthenticatedTemplate>
<NavItem>
<RouterNavLink to="/Search" className="nav-link">
Search
</RouterNavLink>
</NavItem>
</AuthenticatedTemplate>
<AuthenticatedTemplate>
<NavItem>
<RouterNavLink to="/Assignedplans" className="nav-link">
My info
</RouterNavLink>
</NavItem>
</AuthenticatedTemplate>
<AuthenticatedTemplate>
<NavItem>
<RouterNavLink to="/Organization" className="nav-link">
Organization
</RouterNavLink>
</NavItem>
</AuthenticatedTemplate>
<AuthenticatedTemplate>
<NavItem className="me-auto" id="logo">
<img src="micro.png" alt="..." height="38"></img>
</NavItem>
</AuthenticatedTemplate>
</Nav>
{/*
<Nav className="ms-auto align-items-center " navbar>
<AuthenticatedTemplate>
<NavItem className="logo">
<img src="micro.png" alt="..." height="38"></img></NavItem>
</AuthenticatedTemplate>
</Nav>*/}
<Nav className="ms-auto align-items-center" navbar>
<AuthenticatedTemplate>
<NavDropdown
title={<UserAvatar user={user} />}
id="user-dropdown"
align="end"
>
<h5 className="dropdown-item-text mb-0">{user.displayName}</h5>
<Dropdown.Divider />
<Dropdown.Item onClick={app.signOut!}>Sign Out</Dropdown.Item>
</NavDropdown>
</AuthenticatedTemplate>
<UnauthenticatedTemplate>
<NavItem>
<Nav.Link onClick={app.signIn!}>Sign In</Nav.Link>
</NavItem>
</UnauthenticatedTemplate>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
} |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hh_express/app/setup.dart';
import 'package:hh_express/models/delivery_info/deliery_info_model.dart';
import 'package:hh_express/models/pagination/pagination_model.dart';
import 'package:hh_express/models/products/product_model.dart';
import 'package:hh_express/models/property/values/property_value_model.dart';
import 'package:hh_express/repositories/products/product_repo.dart';
import 'package:hh_express/settings/consts.dart';
import 'package:hh_express/settings/enums.dart';
part 'home_state.dart';
class HomeBloc extends Cubit<HomeState> {
HomeBloc()
: super(HomeState(
state: ProductAPIState.init,
));
final _repo = getIt<ProductRepo>();
double lastPosition = 0;
List<PropertyValue> _filters = List.empty();
Future<void> init({bool forUpdate = false}) async {
if (state.state != ProductAPIState.init &&
state.state != ProductAPIState.error &&
!forUpdate) {
return;
}
emit(
HomeState(
deliveryInfo: state.deliveryInfo,
state: ProductAPIState.loading,
),
);
final data = await _repo.getProducts(
slugs: List.empty(),
properties: _filters.map((e) => e.id).toList(),
page: 0,
);
DeliveryInfoModel? deliveryInfo;
if (state.deliveryInfo == null) {
deliveryInfo = await _repo.getDeliveryInfo();
} else {
deliveryInfo = state.deliveryInfo;
}
if (data != null && deliveryInfo != null) {
return emit(
HomeState(
state: ProductAPIState.success,
pagination: data[APIKeys.pagination],
prods: List.from(data[APIKeys.products]),
deliveryInfo: deliveryInfo,
),
);
}
return emit(HomeState(
deliveryInfo: state.deliveryInfo, state: ProductAPIState.error));
}
Future<void> loadMore() async {
emit(
HomeState(
deliveryInfo: state.deliveryInfo,
state: ProductAPIState.loadingMore,
pagination: state.pagination,
prods: List.from(
state.prods ?? List.empty(),
),
),
);
final data = await _repo.getProducts(
slugs: List.empty(),
properties: List.empty(),
page: state.pagination!.currentPage + 1,
);
if (data != null) {
return emit(
HomeState(
deliveryInfo: state.deliveryInfo,
state: ProductAPIState.success,
pagination: data[APIKeys.pagination],
prods: List.from(state.prods ?? List.empty())
..addAll(data[APIKeys.products]),
),
);
}
return emit(
HomeState(
deliveryInfo: state.deliveryInfo,
state: ProductAPIState.loadingMoreError,
pagination: state.pagination,
prods: List.from(state.prods ?? List.empty()),
),
);
}
void filter(List<PropertyValue> props) {
_filters = List.from(props);
lastPosition = 0;
init(forUpdate: true);
}
} |
import { useEffect, useState } from 'react'
import { getRequestURL } from '../../rest/utils'
import { Button, FormControl, InputLabel, MenuItem, Select, TextField } from '@mui/material'
import getFormattedAnswer from './ConverterUtils'
const Converter = () => {
const [currencyList, setCurrencyList] = useState(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
// I added this piece of state to hold the results of the conversion request.
const [conversionAnswer, setConversionAnswer] = useState(null)
console.log(loading, error)
useEffect(() => {
const queryParams = {
type: 'fiat'
}
setLoading(true)
fetch(getRequestURL('currencies', queryParams))
.then((response) => {
return response.json()
})
.then((data) => {
const formattedList = Object.keys(data).map((key) => data[key])
formattedList.sort((a,b) => {
if(a.name > b.name) {
return 1
} else if(b.name > a.name) {
return -1
} else return 0
})
setLoading(false)
setCurrencyList(formattedList)
})
.catch(err => {
setError(err)
console.error(err)
})
}, [])
const handleSubmit = (event) => {
// onsubmit calls the passed function (handleSubmit in this case)
event.preventDefault();
/*
Step 1) Code for handling form data goes here, you should be able to extract the data from the event
Remember, the name attribute on the `input` and `select`s are the corresponding names for the data in the form data.
*/
const data = new FormData(event.target);
const base = data.get("base");
const amount = data.get("amount");
const destination = data.get("destination");
/*
Step 2) After getting data together, set queryParams based on the currencybeacon docs and use fetch with the appropriate endpoint
in order to get the conversion data.
*/
const queryParams = {
from: base,
amount: amount,
to: destination
}
setLoading(true)
fetch(getRequestURL('convert', queryParams))
.then((response) => {
return response.json()
})
.then((data) => {
setLoading(false)
setConversionAnswer(data)
})
.catch(err => {
setError(err)
console.error(err)
})
}
/*
Step 3) Call setConversionAnswer with the results to set the answer in the component's state.
*/
return (
<div className="converter-wrapper">
<h1>Currency Converter</h1>
<div className="form-wrapper">
{/* a form's `onsubmit` attribute expects a function */}
<form name="converterData" onSubmit={handleSubmit}>
<FormControl fullWidth>
<TextField type="number" placeholder='Amount' name="amount" />
</FormControl>
<FormControl fullWidth>
<InputLabel id='base'>Base</InputLabel>
<Select labelId='base' name="base" label='Base'>
{
currencyList?.map((currency) => (
<MenuItem key={currency.short_code} value={currency.short_code}>{currency.name}</MenuItem>
))
}
</Select>
</FormControl>
<span>To</span>
<FormControl fullWidth>
<InputLabel id='destination'>Destination</InputLabel>
<Select labelId='destination' name="destination" label='Destination'>
{
currencyList?.map((currency) => (
<MenuItem key={currency.short_code} value={currency.short_code}>{currency.name}</MenuItem>
))
}
</Select>
</FormControl>
<Button type="submit">Convert</Button>
</form>
{
conversionAnswer != null
?
<div className='results-wrapper'>
<span> {getFormattedAnswer(conversionAnswer,currencyList)} </span>
</div>
: null
}
</div>
</div>
)
}
export default Converter |
import 'package:flutter/material.dart';
import 'package:prateekthakur/pages/homepage.dart';
void main(List<String> args) {
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Prateek Thakur',
theme: ThemeData(
colorScheme: ColorScheme(
brightness: Brightness.light,
primary: Colors.yellow.shade800,
onPrimary: Colors.black,
secondary: Colors.grey.shade200,
onSecondary: Colors.black,
error: Colors.red.shade300,
onError: Colors.black,
background: Colors.white,
onBackground: Colors.black,
surface: Colors.white,
onSurface: Colors.black),
appBarTheme: const AppBarTheme(
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
titleTextStyle: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20),
foregroundColor: Colors.black),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.yellow.shade700)),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.transparent,
foregroundColor: Colors.yellow.shade800,
side: BorderSide(color: Colors.yellow.shade800, width: 2),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.zero),
padding: const EdgeInsets.symmetric(
vertical: 24, horizontal: 32))),
expansionTileTheme: ExpansionTileThemeData(
childrenPadding: const EdgeInsets.all(16),
iconColor: Colors.yellow.shade800,
textColor: Colors.yellow.shade800,
collapsedTextColor: Colors.black,
collapsedIconColor: Colors.black,
backgroundColor: Colors.grey.shade200,
collapsedBackgroundColor: Colors.transparent,
expandedAlignment: Alignment.topLeft,
collapsedShape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16))),
listTileTheme: const ListTileThemeData(
titleTextStyle: TextStyle(
fontSize: 16, color: Colors.black, fontWeight: FontWeight.bold),
subtitleTextStyle: TextStyle(
fontSize: 14,
),
),
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: Colors.yellow.shade800,
foregroundColor: Colors.white,
enableFeedback: true)),
darkTheme: ThemeData(
colorScheme: ColorScheme(
brightness: Brightness.light,
primary: Colors.yellow.shade800,
onPrimary: Colors.white,
secondary: Colors.grey.shade900,
onSecondary: Colors.white,
error: Colors.red.shade300,
onError: Colors.black,
background: Colors.white,
onBackground: Colors.black,
surface: Colors.white,
onSurface: Colors.black),
textTheme: Typography.whiteCupertino,
appBarTheme: const AppBarTheme(
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
titleTextStyle: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20),
foregroundColor: Colors.white),
canvasColor: Colors.black,
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.yellow.shade700)),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
backgroundColor: Colors.transparent,
foregroundColor: Colors.yellow.shade800,
side: BorderSide(color: Colors.yellow.shade800, width: 2),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.zero),
padding: const EdgeInsets.symmetric(
vertical: 24, horizontal: 32))),
expansionTileTheme: ExpansionTileThemeData(
childrenPadding: const EdgeInsets.all(16),
iconColor: Colors.yellow.shade800,
textColor: Colors.yellow.shade800,
collapsedTextColor: Colors.white,
collapsedIconColor: Colors.white,
backgroundColor: Colors.grey.shade900,
collapsedBackgroundColor: Colors.transparent,
expandedAlignment: Alignment.topLeft,
collapsedShape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16))),
listTileTheme: const ListTileThemeData(
iconColor: Colors.white,
titleTextStyle: TextStyle(
fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
subtitleTextStyle: TextStyle(
fontSize: 14,
),
),
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(backgroundColor: Colors.white)),
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: Colors.yellow.shade800,
foregroundColor: Colors.white,
enableFeedback: true)),
home: const HomePage(),
);
}
} |
<template lang="pug">
.curso-main-container.pb-3
BannerInterno
.container.tarjeta.tarjeta--blanca.p-4.p-md-5.mb-5
.titulo-principal.color-acento-contenido
.titulo-principal__numero
span 2
h1 Herramientas para creación de interfaz de usuario
.bloque-texto-g.color-acento-botones.inv01.p-3.p-sm-4.p-md-5.mb-4
.bloque-texto-g__img(
:style="{'background-image': `url(${require('@/assets/curso/tema2/img01.svg')})`}"
)(data-aos="fade-right")
.bloque-texto-g__texto.p-4(data-aos="fade-left")
p.mb-0 Conocer las herramientas y los diferentes tipos de sistemas que favorecen el diseño de interfaces gráficas de usuario es fundamental para los profesionales dedicados al desarrollo web en todo su conjunto, desde el inicio de la toma de requerimientos hasta la implementación de la aplicación.<br><br>Estas herramientas las utiliza, no solo el desarrollador web completo llamado #[em fullstack], sino también el diseñador conocido como #[em front-end], ya sea para el diseño de la aplicación, de una página web o de cualquier otro producto digital.
.BGIMG04.p-md-5.mb-4
.row.justify-content-end.align-items-center.mb-4
.col-lg-3.col-6.mb-lg-0.mb-4(data-aos="fade-right")
img(src="@/assets/curso/tema2/img02.svg")
.col-lg-8(data-aos="fade-left")
.cajon-b.color-acento-botones.p-3.mb-4
p.mb-0 Es indispensable, siempre que se vaya a hacer un diseño, contar con algunos recursos fundamentales para ese trabajo. En primera medida se debe revisar y seleccionar la herramienta adecuada para trabajar el diseño de las interfaces, realizando así una propuesta inicial o un prototipo para que el cliente pueda revisar si este primer acercamiento es acorde con lo que necesita y si se deben hacer ajustes dentro de la respectiva retroalimentación.
p.mb-0 Hasta hace unos años la herramienta predilecta para este proceso de diseño era #[em Photoshop], la cual era muy utilizada por ilustradores, diseñadores, desarrolladores y todos los roles con incidencia en contenidos o productos digitales. Pero ahora, como en los proyectos lo más común es que se tenga que diseñar para tres productos o plataformas: escritorio, web y móvil, se debe revisar qué herramienta da esa funcionalidad y facilidad.
p A continuación, se mencionan algunas herramientas que permiten hacer este trabajo de una manera más eficiente y sencilla. Es indispensable, siempre que se vaya a hacer un diseño, contar con algunos recursos fundamentales para ese trabajo. En primera medida se debe revisar y seleccionar la herramienta que se utilizará para el diseño de las interfaces.
.row.justify-content-end.mb-4
.col-lg-8.order-lg-1.order-2(data-aos="fade-right")
AcordionA(tipo="a" clase-tarjeta="BGR01")
.row(titulo="BALSAMIQ")
p Es una herramienta que se debe registrar para comenzar su uso, permite crear interfaces gráficas de usuario basadas en el #[em wireframing] y tiene un estilo visual de dibujo a mano alzada. Este #[em software] diseñado para la creación o bosquejo de interfaces tiene una variedad de elementos que se pueden utilizar: menús, barras de navegación, elementos de estado, etc. Además, tiene la funcionalidad de arrastrar y soltar para ir creando el diseño.
p.mb-0 Después de terminar el diseño de las interfaces se pueden exportar a JPG o PDF para su posterior comunicación. Una ventaja de esta herramienta es que su trabajo es multiplataforma, es decir, se puede trabajar desde cualquier sistema operativo y permite el trabajo colaborativo con otros integrantes de su equipo. Habría que decir también que en su versión gratuita se puede trabajar desde la nube.
.row(titulo="MOCKINGBIRD")
p Esta es una herramienta que no requiere de ninguna instalación en la máquina y no se necesita tener tantos conocimientos o experiencia, por eso es ideal para usuarios nuevos o con poca experiencia que necesiten crear #[em mockups], ofreciendo alrededor de 90 componentes de trabajo. Una característica importante de esta herramienta, que permite el prototipado de interfaces, es que los diseños que se realicen se pueden compartir; cabe señalar que cuenta con diseños interactivos que permiten testear la usabilidad desde el rol de usuario o cliente para tener un #[em feedback] más acertado.
p.mb-0 El sistema tiene una versión gratuita que se puede utilizar, pero tiene capacidades limitadas como la de crear proyectos debido a que solo permite 3, y la función de exportar y guardar solo está en la versión licenciada.
.row(titulo="INVISION")
p Es una herramienta de prototipado con funcionalidades sobresalientes en el mercado, ideal para especialistas del diseño web. Una ventaja diferenciadora con las otras herramientas es que es fácil de usar, intuitiva, no solo para el diseñador sino para todo el equipo de proyecto. También permite la colaboración compartiendo el proyecto y permitiendo su retroalimentación en tiempo real.
p Esta herramienta cuenta con muchos beneficios que la distinguen, algunos de ellos son:
ul.lista-ul--color.ms-4
li
<i class="fas fa-circle" style="color:#EF3C79; font-size: x-small"></i>
| Su diseño y visualización simula una web real.
li
<i class="fas fa-circle" style="color:#EF3C79; font-size: x-small"></i>
| Mejora el proceso de retroalimentación con el cliente.
li
<i class="fas fa-circle" style="color:#EF3C79; font-size: x-small"></i>
| Se puede hacer seguimiento y retroalimentación en tiempo real.
li
<i class="fas fa-circle" style="color:#EF3C79; font-size: x-small"></i>
| Se puede usar en plataformas móviles.
li
<i class="fas fa-circle" style="color:#EF3C79; font-size: x-small"></i>
| Tiene historial de versiones o contenido.
.col-lg-4.col-8.order-lg-2.order-1.mb-lg-0.mb-4(data-aos="fade-left")
img(src="@/assets/curso/tema2/img03.svg")
.BGIMG05.p-md-5.p-4(data-aos="zoom-in")
p Estas son algunas categorías adicionales de herramientas, para la creación de interfaces gráficas:
ImagenInfografica.color-acento-contenido.mb-5
template(v-slot:imagen)
figure
img(src='@/assets/curso/tema2/img04.svg')
.tarjeta.color-acento-contenido.p-3(x="20.2%" y="43%" numero="+")
.h5.mb-2 Balsamiq
p.mb-0 Popular en el mercado por ser fácil de usar y permite desarrollar los #[em wireframes] del proyecto directamente en el navegador.
.tarjeta.color-acento-contenido.p-3(x="20.2%" y="52.8%" numero="+")
.h5.mb-2 Mockupstogo
p.mb-0 Biblioteca con elementos visuales de Android y otros sistemas operativos para implementarla en Balsamiq.
.tarjeta.color-acento-contenido.p-3(x="20.2%" y="62%" numero="+")
.h5.mb-2 Moqups
p.mb-0 Herramienta que se puede buscar y trabajar vía web y permite desarrollar prototipos de interfaces gráficas de forma rápida; esto gracias a que es intuitiva y cuenta con más de 300 elementos visuales para construir la interfaz. Tiene una versión gratuita, pero solo permite gestionar 2 proyectos y con limitaciones en las funcionalidades de la herramienta.
.tarjeta.color-acento-contenido.p-3(x="20.2%" y="72.8%" numero="+")
.h5.mb-2 MockFlow
p.mb-0 Herramienta web donde se puede diseñar la estructura de una página o aplicación web, la característica principal es que permite añadir enlaces para ir de una página a otra y evaluar así la navegabilidad de la aplicación.
.tarjeta.color-acento-contenido.p-3(x="20.2%" y="82.7%" numero="+")
.h5.mb-2 iPlotz
p.mb-0 Herramienta que crea prototipos con navegación y permite el trabajo colaborativo.
.tarjeta.color-acento-contenido.p-3(x="78.5%" y="9.6%" numero="+")
.h5.mb-2 Axure
p.mb-0 Es una herramienta muy usada en la ejecución de proyectos profesionales, se pueden crear prototipos de aplicaciones web o móviles con un nivel de detalle muy amplio. Tiene una comunidad muy activa donde se generan tutoriales y ayudas.
.tarjeta.color-acento-contenido.p-3(x="78.5%" y="19.2%" numero="+")
.h5.mb-2 Justinmind
p.mb-0 Es una empresa que ofrece su herramienta llamada Prototyper, un programa potente con el cual se pueden elaborar prototipos de alto impacto y finos para aplicaciones móviles y web.
.tarjeta.color-acento-contenido.p-3(x="78.5%" y="29.3%" numero="+")
.h5.mb-2 Invision
p.mb-0 Herramienta para crear diseños o interfaces para #[em apps] móviles y web, permite también agregarles navegación.
.tarjeta.color-acento-contenido.p-3(x="81.3%" y="62%" numero="+")
.h5.mb-2 Fluid UI
p.mb-0 Tiene dentro de su herramienta más de 2000 #[em widgets] que se pueden utilizar para la construcción de prototipos para aplicaciones en IOS, Android o Windows Phone.
.tarjeta.color-acento-contenido.p-3(x="81.3%" y="71.75%" numero="+")
.h5.mb-2 Proto.io
p.mb-0 Herramienta también para crear prototipos móviles, pero con la característica de poder crear algunas funcionalidades habituales como tocar, arrastrar, pellizcar y otras más. Ofrece una versión plenamente funcional, pero de prueba y su licencia dura 15 días.
.tarjeta.color-acento-contenido.p-3(x="81.3%" y="81.75%" numero="+")
.h5.mb-2 Concept.ly
p.mb-0 Esta herramienta da la posibilidad de subir nuestros bocetos y añadirles zonas interactivas para crear interacción o agregar navegación.
.tarjeta.color-acento-contenido.p-3(x="81.3%" y="90.7%" numero="+")
.h5.mb-2 Appery.io
p.mb-0 No solo permite crear prototipos sino también desarrollar la aplicación entera, trabaja con Phonegap para hacerlas híbridas.
</template>
<script>
export default {
name: 'Tema2',
data: () => ({
// variables de vue
}),
mounted() {
this.$nextTick(() => {
this.$aosRefresh()
})
},
updated() {
this.$aosRefresh()
},
}
</script>
<style lang="sass"></style> |
import { ImageBackground, StyleSheet, Text, View, TouchableOpacity, Image, FlatList, RefreshControl, ToastAndroid, ScrollView } from 'react-native'
import React, { useEffect, useState, useCallback } from 'react'
import { DATABASE } from '../../FirebaseConfig';
import { get, ref, remove, set } from "@firebase/database";
import Loading from 'react-native-loading-spinner-overlay';
import IconAnt from 'react-native-vector-icons/AntDesign'
import Ionicon from 'react-native-vector-icons/Ionicons'
import IconMC from 'react-native-vector-icons/MaterialCommunityIcons'
const Favourite_Screen = () => {
const [Favorite, setFavorite] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [refreshing, setrefreshing] = useState(false);
const dataFavorite = ref(DATABASE, 'Favorite');
const getData = async () => {
try {
const favoriteSnapshot = await get(dataFavorite);
if (favoriteSnapshot.exists()) {
const favoriteData = favoriteSnapshot.val();
setFavorite(Object.values(favoriteData));
setIsLoading(false);
} else {
setIsLoading(false);
}
} catch (error) {
console.log('ERROR: ', error);
setIsLoading(false);
}
}
const onRefresh = useCallback(() => {
setrefreshing(true);
setTimeout(() => {
getData();
setrefreshing(false);
}, 2000);
}, []);
const handleDeleteItem = async (item) => {
try {
const itemRef = ref(DATABASE, `Favorite/${item.favId}`);
await remove(itemRef);
console.log(itemRef);
setFavorite((prevState) => prevState.filter((favItem) => favItem.favId !== item.favId));
ToastAndroid.show('Đã xoá khỏi yêu thích', ToastAndroid.SHORT);
} catch (error) {
console.error('Error deleting favorite:', error);
}
};
useEffect(() => {
getData();
}, []);
const ItemFavorite = ({ item }) => (
<View style={{ height: 575, width: '100%', borderRadius: 20, marginBottom: 10, backgroundColor: '#262B33' }}>
<ImageBackground source={{ uri: item.image_fav }} style={{ flex: 3, borderTopLeftRadius: 20, borderTopRightRadius: 20, }}>
<View style={{ flex: 2, borderRadius: 20, }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', padding: 30, marginTop: 10 }}>
<View>
</View>
<TouchableOpacity style={{ width: 40, height: 40, justifyContent: 'center', alignItems: 'center', backgroundColor: '#21262E', borderRadius: 10 }}
onPress={() => handleDeleteItem(item)}>
<IconAnt name='heart' size={22} color={'#DC3535'} />
</TouchableOpacity>
</View>
</View>
<View style={{
flex: 1,
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
backgroundColor: '#00000080',
padding: 20
}}>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }}>
<View style={{ flexDirection: 'column' }}>
<Text style={{ color: '#fff', fontSize: 20, fontWeight: '600' }}> {item.nameFav} </Text>
<Text style={{ color: '#AEAEAE', fontSize: 12, marginTop: 5 }}> {item.description} </Text>
</View>
<View style={{ flexDirection: 'row', width: 100, justifyContent: 'space-between' }}>
<TouchableOpacity style={{ backgroundColor: '#141921', width: 45, height: 45, borderRadius: 10, justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../../assets/icons/icon_cf_bean.png')} />
</TouchableOpacity>
<TouchableOpacity style={{ backgroundColor: '#141921', width: 45, height: 45, borderRadius: 10, justifyContent: 'center', alignItems: 'center' }}>
<IconMC name='water' size={40} color={'#D17842'} />
</TouchableOpacity>
</View>
</View>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
<View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
<IconAnt name='star' size={24} color={'#D17842'}/>
<Text style={{ color: '#FFFFFF', fontWeight: 600, fontSize: 16 }}> {item.rate} </Text>
</View>
<TouchableOpacity style={{ width: 100, height: 45, backgroundColor: '#141921', borderRadius: 10, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ color: '#AEAEAE', fontSize: 10, fontWeight: 500 }}>Medium Roasted</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
<View style={{ flex: 1, }}>
<View style={{ flex: 1, padding: 20, }}>
<Text style={{ color: '#AEAEAE', fontWeight: 600, fontSize: 14, }}>Description</Text>
<Text style={{ color: '#fff', fontWeight: 400, fontSize: 14, marginTop: 10 }}> {item.description} </Text>
</View>
</View>
</View>
)
return (
<View style={{ flex: 1, backgroundColor: '#0C0F14', }}>
<View style={{ flex: 1, padding: 20 }}>
<Text style={{
fontWeight: 'bold',
color: '#fff',
fontSize: 20,
marginTop: 20,
textAlign: 'center',
height: 30
}}>Favorite</Text>
<ScrollView
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
/>
}>
{isLoading ? <Loading visible={true} /> : null}
{
Favorite.length == 0 ?
<Text style={{ flex: 1, textAlign: 'center', color: '#52555a', fontWeight: '600', fontSize: 16, marginTop: 280 }}>Yêu thích của bạn đang trống</Text>
:
<View style={{ marginTop: 20 }}>
<FlatList
data={Favorite}
renderItem={({ item }) => {
return <ItemFavorite item={item} />
}}
showsVerticalScrollIndicator={false}
keyExtractor={(item) => item.favId}
/>
</View>
}
</ScrollView>
</View>
</View>
)
}
export default Favourite_Screen |
---
title: "Lab 2: Sharing Your Work"
format: html
editor: visual
---
## Lab Introduction
This document accompanies the Lab 2 description on our course website.
## Lab Tasks
1. Link your computer to your Github account following the instructions in our lab guide.
2. Create a Quarto Pub account following the instructions in our lab guide.
3. Modify this Quarto document to create an HTML document that describes the following:
a. How has a particular neighborhood or place shaped your life? What contributions did it make?
b. What makes a neighborhood good or bad? How can we reliably describe the differences that matter between neighborhoods?
c. What do you think the goal(s) of neighborhood analysis should be? What types of stories are you interested in telling?
Your response does not need to be extensive - this is both an opportunity to reflect as well as an opportunity to practice your Quarto document creation and formatting skills.
Publish your short reflection using Quarto Pub. Remember that this document is published on the internet and is accessible to anyone with the URL). Include the URL to your Quarto Pub site below - we want to hear your thoughts!
4. After you have published this document via Quarto Pub, add the URL to your Quarto Pub to the beginning of the Quarto document and then commit and push the document to Github (this will be in the Lab 2 repository which you initially pulled to your local computer).
5. In a folder separate from the one in which you completed the work on your first lab, pull the Lab 1 template from Github, add your modified lab 1 files, and then commit and push your completed lab 1 files to the Lab 1 assignment area on Github.
## Deliverables
1. Lab 1 repository pushed to your Lab 1 Github repository
2. Lab 2 repository pushed to your Lab 2 Github repository
3. Quarto Pub site with URL shared in your Lab 1 Quarto Markdown document that is pushed to your Lab 2 Github repository.
That's it! We're looking forward to seeing what you come up with! |
import { useDispatch } from 'react-redux';
import { FormBtn, FormLabel, FormRegistration } from './Registration.styled';
import { fetchAddNewUser } from 'redux/fetches';
import { addNewUser } from 'redux/Slices/UsersSlice';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
export const RegistrationPage = () => {
const dispatch = useDispatch();
const handleSubmit = e => {
e.preventDefault();
const { login, email, password } = e.target.elements;
const newUser = fetchAddNewUser({
name: login.value,
email: email.value,
password: password.value,
});
newUser.then(response => {
if (response === 400) {
toast.error(
`Такі користувач або пошта вже існують, введіть інші дані`,
{
position: 'top-left',
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: 'colored',
}
);
return;
}
dispatch(addNewUser(response.data));
});
};
return (
<FormRegistration onSubmit={handleSubmit}>
<FormLabel>
<p>Name</p>
<input type="text" name="login" placeholder="Login" />
</FormLabel>
<FormLabel>
<p>E-mail</p>
<input type="email" name="email" placeholder="Email" />
</FormLabel>
<FormLabel>
<p>Password</p>
<input type="password" name="password" placeholder="Password" />
</FormLabel>
<FormBtn type="submit">SIGNUP</FormBtn>
<ToastContainer />
</FormRegistration>
);
}; |
import { PrismaClient } from "@prisma/client";
import { authTokenMiddleware } from "../../../../public/utils/authTokenMiddleware";
const prisma = new PrismaClient();
export default async (req, res) => {
if (req.method === "PUT") {
authTokenMiddleware(req, res, async () => {
const { id } = req.query;
const { title, author, publisher, year, pages } = req.body;
try {
const book = await prisma.book.update({
where: { id: Number(id) },
data: {
title,
author,
publisher,
year: parseInt(year),
pages: parseInt(pages),
},
});
res.status(200).json({ book });
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
} else if (req.method === "DELETE") {
authTokenMiddleware(req, res, async () => {
const { id } = req.query;
try {
const book = await prisma.book.delete({
where: { id: Number(id) },
});
res.json({ message: "Delete Success", data: book });
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
} else if (req.method === "GET") {
try {
const { id } = req.query;
const book = await prisma.book.findUnique({
where: { id: Number(id) },
});
if (book) {
res.status(200).json({ book });
} else {
res.status(404).json({ message: "Book not found" });
}
} catch (e) {
console.log(e);
res.status(500).json({ message: "Something went wrong" });
}
} else {
res.status(405).json({ error: "Method not allowed" });
}
}; |
<?php
namespace App\Livewire\Pages\Rawmaterial\Components\Receive;
use App\Models\MaterialReport;
use App\Models\MaterialTnx;
use App\Models\RawMaterial;
use App\Models\ReceiveMaterial;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\On;
use Livewire\Attributes\Rule;
use Livewire\Features\SupportFileUploads\WithFileUploads;
use LivewireUI\Modal\ModalComponent;
class ReceiveForm extends ModalComponent
{
use WithFileUploads;
public $action = 'add';
public $id;
#[Rule('required')]
public $quantity;
#[Rule('required')]
public $date;
public $invoice;
public $new_invoice;
#[Rule('required', as: 'Material')]
public $raw_material_id;
protected $listeners = [
'update_receive_material' => 'editReceiveMaterial'
];
#[On('set_raw_material_id')]
public function setRawMaterialId($id)
{
$this->raw_material_id = $id;
}
public function addReceiveMaterial()
{
$this->validate();
$this->validate([
'invoice' => 'required|mimes:pdf'
]);
// save in material tnx table
$tnx = new MaterialTnx;
$tnx->date = $this->date;
$tnx->quantity = $this->quantity;
$tnx->action = 'in';
$tnx->raw_material_id = $this->raw_material_id;
$tnx->user_id = auth()->user()->id;
$tnx->save();
$receive_material = new ReceiveMaterial;
$receive_material->date = $this->date;
$receive_material->quantity = $this->quantity;
$receive_material->raw_material_id = $this->raw_material_id;
$receive_material->material_tnx_id = $tnx->id;
$receive_material->user_id = auth()->user()->id;
$fileNameToSave = null;
if ($this->invoice != null) {
$this->file = (object)$this->invoice;
try {
$file = $this->file->getClientOriginalName();
$extension = $this->file->getClientOriginalExtension();
$fileName = pathinfo($file, PATHINFO_FILENAME) . "-" . date('Ymd-His') . "." . $extension;
$this->file->storeAs('rawmaterial/invoices', $fileName, 'public');
$fileNameToSave = '/storage/rawmaterial/invoices/' . $fileName;
} catch (\Throwable $e) {
}
}
$receive_material->invoice = $fileNameToSave;
$receive_material->save();
// create report
$report = new MaterialReport;
$report->received = $this->quantity;
$report->raw_material_id = $this->raw_material_id;
$report->material_tnx_id = $tnx->id;
$report->user_id = auth()->user()->id;
$report->save();
$this->resetForm();
$this->dispatch('receive_material_saved');
$this->closeModal();
$this->dispatch('show_success', 'Record saved successfully!');
}
public function editReceiveMaterial($id)
{
$this->action = 'update';
$qs = ReceiveMaterial::find($id);
$this->id = $id;
$this->quantity = $qs->quantity;
$this->date = $qs->date;
$this->invoice = $qs->invoice;
$this->raw_material_id = $qs->raw_material_id;
$this->dispatch('update_raw_material_id_field', $qs->raw_material_id);
}
public function updateReceiveMaterial()
{
$this->validate();
if ($this->new_invoice) {
$this->validate([
'new_invoice' => 'required|mimes:pdf'
]);
}
$qs = ReceiveMaterial::find($this->id);
$qs->quantity = $this->quantity;
$qs->date = $this->date;
$qs->raw_material_id = $this->raw_material_id;
$tnx = MaterialTnx::find($qs->material_tnx_id);
if ($tnx) {
$tnx->date = $this->date;
$tnx->quantity = $this->quantity;
$tnx->action = 'in';
$tnx->raw_material_id = $this->raw_material_id;
$tnx->save();
} else { // if it is not there, create it
$tnx = new MaterialTnx;
$tnx->date = $this->date;
$tnx->quantity = $this->quantity;
$tnx->action = 'in';
$tnx->raw_material_id = $this->raw_material_id;
$tnx->user_id = auth()->user()->id;
$tnx->save();
}
// check if new invoice is added and replace the previous invoice
if ($this->new_invoice) {
$fileNameToSave = null;
$this->file = (object)$this->new_invoice;
try {
$file = $this->file->getClientOriginalName();
$extension = $this->file->getClientOriginalExtension();
$fileName = pathinfo($file, PATHINFO_FILENAME) . "-" . date('Ymd-His') . "." . $extension;
$invoice = $qs->invoice;
if ($invoice) {
$imgname = str_replace(substr($invoice, 0, 9), '', $invoice);
$check = Storage::disk('public')->exists($imgname);
if ($check) {
Storage::disk('public')->delete($imgname);
}
}
$this->file->storeAs('rawmaterial/invoices', $fileName, 'public');
$fileNameToSave = '/storage/rawmaterial/invoices/' . $fileName;
} catch (\Throwable $e) {
}
$qs->invoice = $fileNameToSave;
}
$qs->material_tnx_id = $tnx->id;
$qs->save();
// update report
$report = MaterialReport::where('material_tnx_id', $tnx->id)->first();
if($report) {
$report->received = $this->quantity;
$report->raw_material_id = $this->raw_material_id;
$report->material_tnx_id = $tnx->id;
$report->save();
}
$this->resetForm();
$this->dispatch('receive_material_saved');
$this->closeModal();
$this->dispatch('show_success', 'ReceiveMaterial updated successfully!');
}
public function mount($id = null)
{
if ($id) {
$this->editReceiveMaterial($id);
}
$this->dispatch('initialize_scripts');
}
public function resetForm()
{
$this->dispatch('reset_raw_material_id');
$this->reset();
}
public function render()
{
$materials = RawMaterial::all();
return view('livewire.pages.rawmaterial.components.receive.receive-form', compact('materials'));
}
} |
import React, { useState } from "react";
import styled from "styled-components";
import { TouchableWithoutFeedback, Keyboard } from "react-native";
import AuthButton from "../../components/AuthButton";
import AuthInput from "../../components/AuthInput";
import useInput from "../../hooks/useInput";
import { Alert } from "react-native";
import { useMutation } from "react-apollo-hooks";
import { CREATE_ACCOUNT } from "./AuthQueries";
import * as Facebook from "expo-facebook";
import * as Google from "expo-google-app-auth";
// import "../../env"
const View = styled.View`
justify-content: center;
align-items: center;
flex: 1;
`;
const FBContainer = styled.View`
margin-top: 25px;
padding-top: 25px;
border-top-width: 1px;
border-color: ${props => props.theme.lightGreyColor};
border-style: solid;
`;
const GoogleContainer = styled.View`
margin-top: 20px;
`;
export default ({ navigation }) => {
const fNameInput = useInput("");
const lNameInput = useInput("");
const emailInput = useInput(navigation.getParam("email", ""));
const usernameInput = useInput("");
const [loading, setLoading] = useState(false);
const [createAccountMutation] = useMutation(CREATE_ACCOUNT, {
variables: {
username: usernameInput.value,
email: emailInput.value,
firstName: fNameInput.value,
lastName: lNameInput.value
}
});
const handleSingup = async () => {
const { value: email } = emailInput;
const { value: fName } = fNameInput;
const { value: lName } = lNameInput;
const { value: username } = usernameInput;
const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!emailRegex.test(email)) {
return Alert.alert("Email형식에 맞게 작성하여 주세요.");
}
if (fName === "") {
return Alert.alert("이름을 작성하여 주세요.");
}
if (username === "") {
return Alert.alert("유효하지 않은 사용자이름입니다.");
}
try {
setLoading(true);
const {
data: { createAccount }
} = await createAccountMutation();
if (createAccount) {
Alert.alert("계정이 생성되었습니다.", "로그인 해주세요!");
navigation.navigate("Login", { email });
}
} catch (e) {
console.log(e);
Alert.alert("이미 사용인 Email 혹은 Username 입니다.");
} finally {
setLoading(false);
}
};
const fbLogin = async () => {
try {
setLoading(true);
await Facebook.initializeAsync("452173045455901");
const { type, token } = await Facebook.logInWithReadPermissionsAsync({
permissions: ["public_profile", "email"]
});
if (type === "success") {
// Get the user's name using Facebook's Graph API
const response = await fetch(
`https://graph.facebook.com/me?access_token=${token}&fields=id,last_name,first_name,email`
);
const data = await response.json();
console.log(data);
const { email, first_name, last_name } = await response.json();
updateFormData(email, first_name, last_name);
setLoading(false);
} else {
// type === 'cancel'
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
};
const googleLogin = async () => {
try {
const IOS_GOOGLE_ID =
"730928440948-b7kcr3q6qumje5j2m9ba373oh519hlts.apps.googleusercontent.com";
const AOS_GOOGLE_ID =
"730928440948-vesv34iu0vpfq97hq0jeon7e3t7t2pii.apps.googleusercontent.com";
setLoading(true);
const result = await Google.logInAsync({
iosClientId: IOS_GOOGLE_ID,
androidClientId: AOS_GOOGLE_ID,
scopes: ["profile", "email"]
});
if (result.type === "success") {
const user = await fetch("https://www.googleapis.com/userinfo/v2/me", {
headers: { Authorization: `Bearer ${result.accessToken}` }
});
const { email, family_name, given_name } = await user.json();
updateFormData(email, given_name, family_name);
} else {
return { cancelled: true };
}
} catch (e) {
console.log(e);
} finally {
setLoading(false);
}
};
const updateFormData = (email, firstName, lastName) => {
emailInput.setValue(email);
fNameInput.setValue(firstName);
lNameInput.setValue(lastName);
const [username] = email.split("@");
usernameInput.setValue(username);
};
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View>
<AuthInput
{...fNameInput}
placeholder="First name"
autoCapitalize="words"
returnKeyType="next"
/>
<AuthInput
{...lNameInput}
placeholder="Last name"
autoCapitalize="words"
returnKeyType="next"
/>
<AuthInput
{...emailInput}
placeholder="Email"
keyboardType="email-address"
returnKeyType="next"
autoCorrect={false}
/>
<AuthInput
{...usernameInput}
placeholder="Username"
returnKeyType="send"
autoCorrect={false}
/>
<AuthButton loading={loading} onPress={handleSingup} text="Sign up" />
<FBContainer>
<AuthButton
bgColor={"#2D4DA7"}
loading={false}
onPress={fbLogin}
text="Connect Facebook"
/>
</FBContainer>
<GoogleContainer>
<AuthButton
bgColor={"#EE1922"}
loading={false}
onPress={googleLogin}
text="Connect Google"
/>
</GoogleContainer>
</View>
</TouchableWithoutFeedback>
);
}; |
import { Component, OnInit } from '@angular/core';
import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog';
import { NgxSpinnerService } from 'ngx-spinner';
import { FamiliaService } from '../../services/familia.service';
import { EmpresaService } from '../../../shared/services/empresa.service';
import { Familia } from '../../entity/familia';
import { SubFamilia1 } from '../../entity/sub-familia1';
import { SubFamilia2 } from '../../entity/sub-familia2';
import { SubFamilia3 } from '../../entity/sub-familia3';
import { SubFamilia4 } from '../../entity/sub-familia4';
import { TipoConsumo } from '../../entity/tipo-consumo';
import { SubFamilia1Service } from '../../services/sub-familia1.service';
import { SubFamilia2Service } from '../../services/sub-familia2.service';
import { SubFamilia3Service } from '../../services/sub-familia3.service';
import { SubFamilia4Service } from '../../services/sub-familia4.service';
import { TipoConsumoService } from '../../services/tipo-consumo.service';
import { SeleccionarFamiliaDto } from '../../dto/seleccionar-familia-dto';
import swal from 'sweetalert2';
@Component({
selector: 'app-find-jerarquia',
templateUrl: './find-jerarquia.component.html',
styleUrls: ['./find-jerarquia.component.css']
})
export class FindJerarquiaComponent implements OnInit {
public descripcion: string = '';
public clasicas!: number;
public premiums!: number;
public tipoConsumoList: TipoConsumo[] = [];
public familiaList: Familia[] = [];
public subFamilia1List: SubFamilia1[] = [];
public subFamilia2List: SubFamilia2[] = [];
public subFamilia3List: SubFamilia3[] = [];
public subFamilia4List: SubFamilia4[] = [];
public tipoConsumo!: TipoConsumo;
public familia!: Familia;
public subFamilia1!: SubFamilia1;
public subFamilia2!: SubFamilia2;
public subFamilia3!: SubFamilia3;
public subFamilia4!: SubFamilia4;
private seleccionarFamiliaDto: SeleccionarFamiliaDto = new SeleccionarFamiliaDto();
public editarDescripcion: boolean = true;
constructor(private spinner: NgxSpinnerService,
private tipoConsumoService: TipoConsumoService,
private familiaService: FamiliaService,
private subFamilia1Service: SubFamilia1Service,
private subFamilia2Service: SubFamilia2Service,
private subFamilia3Service: SubFamilia3Service,
private subFamilia4Service: SubFamilia4Service,
public empresaService: EmpresaService,
public ref: DynamicDialogRef,
public config: DynamicDialogConfig) { }
ngOnInit(): void {
this.editarDescripcion = this.config.data.editarDescripcion;
this.descripcion = this.config.data.descripcion;
this.clasicas = this.config.data.clasica;
this.premiums = this.config.data.premium;
this.spinner.show();
this.tipoConsumoService.getAll().subscribe(
tipoConsumoList => {
this.tipoConsumoList = tipoConsumoList
this.familiaService.getAll().subscribe(
familiaList => {
this.familiaList = familiaList;
this.spinner.hide();
},
_err=> {
this.spinner.hide();
swal.fire('Error', 'Problemas al obtener las familias', 'error');
}
);
},
_err => {
this.spinner.hide();
swal.fire('Error', 'Problemas al obtener los tipos de consumo', 'error');
}
);
}
public aceptar(): void {
if (!this.descripcion && this.editarDescripcion) {
swal.fire({title:'Alerta!', html: 'Debe ingresar la descripción del producto', icon: 'warning', target: 'id', backdrop: 'false'});
return;
}
if (this.descripcion.trim().length < 5 && this.editarDescripcion) {
swal.fire({title:'Alerta!', html: 'Debe ingresar la descripción del producto', icon: 'warning', target: 'id', backdrop: 'false'});
return;
}
if (!this.tipoConsumo) {
swal.fire({title:'Alerta!', html: 'Debe seleccionar un tipo de consumo', icon: 'warning', target: 'id', backdrop: 'false'});
return;
}
if (!this.familia) {
swal.fire({title:'Alerta!', html: 'Debe seleccionar una familia', icon: 'warning', target: 'id', backdrop: 'false'});
return;
}
this.seleccionarFamiliaDto.descripcion = this.descripcion;
this.seleccionarFamiliaDto.tipoConsumo = this.tipoConsumo;
this.seleccionarFamiliaDto.familia = this.familia;
this.seleccionarFamiliaDto.subFamilia1 = this.subFamilia1;
this.seleccionarFamiliaDto.subFamilia2 = this.subFamilia2;
this.seleccionarFamiliaDto.subFamilia3 = this.subFamilia3;
this.seleccionarFamiliaDto.subFamilia4 = this.subFamilia4;
this.seleccionarFamiliaDto.clasica = this.clasicas;
this.seleccionarFamiliaDto.premium = this.premiums;
this.ref.close(this.seleccionarFamiliaDto);
}
public cancelar(): void {
this.ref.close();
}
public changeFamilia(): void {
this.subFamilia1 = new SubFamilia1();
this.subFamilia2 = new SubFamilia2();
this.subFamilia3 = new SubFamilia3();
this.subFamilia4 = new SubFamilia4();
if (!this.familia) {
return;
}
this.spinner.show();
this.subFamilia1Service.getAllPorPadre(this.familia.id).subscribe(
subfamilia => {
this.subFamilia1List = subfamilia;
this.spinner.hide();
},
_err => {
this.spinner.hide();
swal.fire('Error', 'Problemas al obtener las sub familias 1', 'error');
}
);
}
public changeSubFamilia1(): void {
this.subFamilia2 = new SubFamilia2();
this.subFamilia3 = new SubFamilia3();
this.subFamilia4 = new SubFamilia4();
if (!this.subFamilia1) {
return;
}
this.spinner.show();
this.subFamilia2Service.getAllPorPadre(this.subFamilia1.id).subscribe(
subfamilia => {
this.subFamilia2List = subfamilia;
this.spinner.hide();
},
_err => {
this.spinner.hide();
swal.fire('Error', 'Problemas al obtener las sub familias 2', 'error');
}
);
}
public changeSubFamilia2(): void {
this.subFamilia3 = new SubFamilia3();
this.subFamilia4 = new SubFamilia4();
if (!this.subFamilia2) {
return;
}
this.spinner.show();
this.subFamilia3Service.getAllPorPadre(this.subFamilia2.id).subscribe(
subfamilia => {
this.subFamilia3List = subfamilia;
this.spinner.hide();
},
_err => {
this.spinner.hide();
swal.fire('Error', 'Problemas al obtener las sub familias 3', 'error');
}
);
}
public changeSubFamilia3(): void {
this.subFamilia4 = new SubFamilia4();
if (!this.subFamilia3) {
return;
}
this.spinner.show();
this.subFamilia4Service.getAllPorPadre(this.subFamilia3.id).subscribe(
subfamilia => {
this.subFamilia4List = subfamilia;
this.spinner.hide();
},
_err => {
this.spinner.hide();
swal.fire('Error', 'Problemas al obtener las sub familias 4', 'error');
}
);
}
} |
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { FormComponent } from './form/form.component';
import { AngularFirestoreModule } from '@angular/fire/firestore';
//import { environment } from '../environments/environment';
//import { AngularFireModule } from '@angular/fire';
@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
CounterComponent,
FetchDataComponent,
FormComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: 'form', component: FormComponent },
]),
BrowserAnimationsModule,
MatInputModule,
MatButtonModule,
MatSelectModule,
MatChipsModule,
MatCheckboxModule,
//AngularFirestoreModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { } |
package mx.edu.utez.saem.controller.doctor;
import lombok.AllArgsConstructor;
import mx.edu.utez.saem.config.ApiResponse;
import mx.edu.utez.saem.controller.doctor.dto.DoctorDto;
import mx.edu.utez.saem.controller.doctor.dto.ChangeDocPasswordDto;
import mx.edu.utez.saem.service.doctor.DoctorService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/saem/doctor")
@CrossOrigin(origins = {"*"})
@AllArgsConstructor
public class DoctorController {
private final DoctorService service;
@PostMapping("/save")
public ResponseEntity<ApiResponse> registrar(@RequestBody DoctorDto dto) {
return service.save(dto.toEntity());
}
@PutMapping("/update")
public ResponseEntity<ApiResponse> actualizar(@RequestBody DoctorDto dto){
return service.update(dto.toEntity());
}
@DeleteMapping("/delete/{card}")
public ResponseEntity<ApiResponse> eliminar(@PathVariable String card) {
return service.delete(card);
}
@GetMapping("/findAll")
public ResponseEntity<ApiResponse> verTodos(){
return service.getAll();
}
@GetMapping("/findOne/{card}")
public ResponseEntity<ApiResponse> verUno(@PathVariable String card){
return service.getOne(card);
}
@GetMapping("/findOneCard/{curp}")
public ResponseEntity<ApiResponse> verUnoCurp(@PathVariable String curp){
return service.getOneCurp(curp);
}
@PostMapping("/changePassword")
public ResponseEntity<ApiResponse> changePassword(@RequestBody ChangeDocPasswordDto changePasswordDto) {
return service.changeDoctorPassword(
changePasswordDto.getCard(),
changePasswordDto.getOldPassword(),
changePasswordDto.getNewPassword());
}
} |
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode',
'application.extensions.recaptcha.EReCaptchaValidator',
'privateKey'=>'6LdqHN4SAAAAAM7O87xaMwzODtym8uV7r8qX0YXB'),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array('name' => Yii::t('app', 'Name' ),
'email' => Yii::t('app', 'E-mail' ),
'subject' => Yii::t('app', 'Subject' ),
'body' => Yii::t('app', 'Message body' ),
'verifyCode' => Yii::t('app', 'Verification Code'),);
}
} |
#ifndef ANDROID_SPEECH_PARSER_BASE_H
#define ANDROID_SPEECH_PARSER_BASE_H
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "SpeechParserType.h"
namespace android {
/*
* class
*/
class SpeechParserBase {
public:
virtual ~SpeechParserBase() {}
/**
* get instance's pointer
*/
static SpeechParserBase *getInstance();
/**
* @brief Parsing param file to get parameters into pOutBuf
*
* @param speechParserAttribute: the attribute for parser
* @param pOutBuf: the output buffer
* @param sizeByteOutBuf: the size byte of output buffer
*
* @return int
*/
virtual int getParamBuffer(SpeechParserAttribute speechParserAttribute, SpeechDataBufType *outBuf) = 0;
/**
* @brief set keyString string to library
*
* @param keyString the "key=value" string
* @param sizeKeyString the size byte of string
*
* @return int
*/
virtual int setKeyValuePair(const SpeechStringBufType *keyValuePair) = 0;
/**
* @brief get keyString string from library
*
* @param keyString there is only "key" when input,
and then library need rewrite "key=value" to keyString
* @param sizeKeyString the size byte of string
*
* @return int
*/
virtual int getKeyValuePair(SpeechStringBufType *keyValuePair) = 0;
/**
* @brief update phone call status from driver
*
* @param callOn: the phone call status: true(On), false(Off)
*
* @return int
*/
virtual int updatePhoneCallStatus(bool callOn) = 0;
bool mCallOn;
protected:
SpeechParserAttribute mSpeechParserAttribute;
SpeechParserBase() {
mCallOn = false;
mSpeechParserAttribute.inputDevice = AUDIO_DEVICE_IN_BUILTIN_MIC;
mSpeechParserAttribute.outputDevice = AUDIO_DEVICE_OUT_EARPIECE;
mSpeechParserAttribute.idxVolume = 3;
mSpeechParserAttribute.driverScenario = SPEECH_SCENARIO_SPEECH_ON;
mSpeechParserAttribute.ttyMode = AUD_TTY_OFF;
mSpeechParserAttribute.speechFeatureOn = 0;
mParamBuf = NULL;
mParamBufSize = 0;
}
void *mParamBuf;
uint16_t mParamBufSize;
private:
/**
* singleton pattern
*/
static SpeechParserBase *uniqueSpeechParser;
};
} // end namespace android
#endif // end of ANDROID_SPEECH_PARSER_BASE_H |
{% capture configScreen %}
1921=>visible,
1920=>widescreen,
1480=>desktop,
1200=>laptop,
992=>notebook,
768=>tablet,
576=>landscape,
481=>portrait,
361=>mobile,
1=>mobile-small
{% endcapture %}
{% capture configSwiper %}
auto-Height,
autoplay,
centered-Slides,
direction,
navigation,
pagination,
effect,
loop,
grid,
space-Between,
slides-Per-View,
slides-Per-Group,
speed,
{% endcapture %}
{% assign gridSlider = '' %}
{% if settings['use-slider'] == true %}
{% assign gridSlider = 'data-watch-Slides-Progress="true" data-watch-Slides-Visibility="true"' %}
{% assign configSwiper = configSwiper | strip_newlines | replace: ' ', '' | split: ',' %}
{% for opt in configSwiper %}
{% assign value = settings[opt] %}
{% if opt == 'navigation' and value == true %}
{% assign value = "{'nextEl': '.swiper-button-next', 'prevEl': '.swiper-button-prev'}" %}
{% endif %}
{% if opt == 'pagination' and value == true %}
{% assign value = "{'el': '.swiper-pagination', 'clickable': 'true'}" %}
{% endif %}
{% if opt == 'grid' and settings.rows > 1 %}
{% assign value = settings.rows | prepend: "{'fill': 'row', 'rows': " | append: '}' %}
{% endif %}
{% if opt == 'slides-Per-View' %}
{% assign value = settings.mobile %}
{% endif %}
{% if value != blank or value == true or value == false %}
{% capture gridSlider %}{{gridSlider}} data-{{opt}}="{{value}}"{% endcapture %}
{% endif %}
{% endfor %}
{% else %}
{% capture gridSlider %}data-space-Between="{{settings['space-Between']}}"{% endcapture %}
{% endif %}
{% assign configScreen = configScreen | strip_newlines | replace: ' ', '' | split: ',' %}
{% assign breakpoints = '{' %}
{% assign col = '1' %}
{% for cfg in configScreen %}
{% assign size = cfg | split: '=>' | first | strip %}
{% assign name = cfg | split: '=>' | last | strip %}
{% if forloop.last == true %}
{% capture breakpoints %}{{breakpoints}} '1':{'slidesPerView':{{ col }} } }{% endcapture %}
{% else %}
{% if settings[name] != blank %}
{% assign col = settings[name] %}
{% capture breakpoints %}{{breakpoints}} '{{size}}':{'slidesPerView':{{col}} },{% endcapture %}
{% endif %}
{% endif %}
{% endfor %}
{% capture gridSlider %} data-wrapper='#shopify-section-{{section.id}}' {{gridSlider}} data-breakpoints="{{breakpoints}}" {% endcapture %}
{% assign grid-slider = gridSlider %}
{% comment %}
Use in section:
{% include 'grid-slider', settings:section.settings %}
Use in block in section:
{% include 'grid-slider', settings:block.settings %}
Use in html:
<grid-slider {{gridSlider}}>
<div class="swiper iSwiper">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image1.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image2.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image3.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image4.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image5.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image6.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image7.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image8.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image9.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image10.jpg"/></div>
<div class="swiper-slide"><img src="https://www.starplugins.com/sites/starplugins/images/jetzoom/large/image11.jpg"/></div>
</div>
</div>
</grid-slider>
{% endcomment %}
{% comment %}
Add to settings_schema:
{
"type": "header",
"content": "---- Collection GridSlider ----",
"info": "Refer to the attribute values [here](https://swiperjs.com/swiper-api)"
},
{
"type": "checkbox",
"id": "use-slider",
"label": "Use slider?",
"default": true
},
{
"type": "range",
"id": "visible",
"label": "Columns in Visible",
"info": "Item(s) in screen ( Size >= 1920 )",
"min": 1,
"max": 8,
"step": 1,
"default": 5
},
{
"type": "range",
"id": "widescreen",
"label": "Columns in Widescreen",
"info": "Item(s) in screen ( 1480 <= Size < 1920 )",
"min": 1,
"max": 8,
"step": 1,
"default": 4
},
{
"type": "range",
"id": "desktop",
"label": "Columns in Desktop",
"info": "Item(s) in screen ( 1200 <= Size < 1480 )",
"min": 1,
"max": 8,
"step": 1,
"default": 4
},
{
"type": "range",
"id": "laptop",
"label": "Columns in Laptop",
"info": "Item(s) in screen ( 992 <= Size < 1200 )",
"min": 1,
"max": 8,
"step": 1,
"default": 4
},
{
"type": "range",
"id": "notebook",
"label": "Columns in Notebook",
"info": "Item(s) in screen ( 768 <= Size < 992 )",
"min": 1,
"max": 8,
"step": 1,
"default": 3
},
{
"type": "range",
"id": "tablet",
"label": "Columns in Tablet",
"info": "Item(s) in screen ( 576 <= Size < 768 )",
"min": 1,
"max": 8,
"step": 1,
"unit": "pds",
"default": 3
},
{
"type": "range",
"id": "landscape",
"label": "Columns in Landscape",
"info": "Item(s) in screen ( 480 <= Size < 576 )",
"min": 1,
"max": 6,
"step": 1,
"default": 2
},
{
"type": "range",
"id": "portrait",
"label": "Columns in Portrait",
"info": "Item(s) in screen ( 360 < Size < 480 )",
"min": 1,
"max": 6,
"step": 1,
"default": 2
},
{
"type": "range",
"id": "mobile",
"label": "Columns in Mobile",
"info": "Item(s) in screen ( Size < = 360 )",
"min": 1,
"max": 4,
"step": 1,
"default": 1
},
{
"type": "range",
"id": "slides-Per-Group",
"label": "Slide Per Group",
"info": "The number of items slide to scroll",
"min": 1,
"max": 8,
"step": 1,
"default": 1
},
{
"type": "range",
"id": "rows",
"label": "Rows Slider",
"min": 1,
"max": 3,
"step": 1,
"default": 1
},
{
"type": "checkbox",
"id": "autoplay",
"label": "Autoplay",
"default": true
},
{
"type": "text",
"id": "speed",
"label": "Speed",
"default": "300",
"info": "Duration of transition between slides (in ms)"
},
{
"type": "text",
"id": "autoplay_delay",
"label": "Auto Play delay",
"default": "3000",
"info": "Delay between transitions (in ms)"
},
{
"type": "checkbox",
"id": "navigation",
"label": "Navigation",
"info": "Arrows next,prev",
"default": true
},
{
"type": "select",
"id": "effect",
"label": "effect",
"options": [
{
"value": "coverflow",
"label": "Coverflow"
},
{
"value": "creative",
"label": "Creative"
},
{
"value": "cube",
"label": "Cube"
},
{
"value": "fade",
"label": "Fade"
},
{
"value": "flip",
"label": "Flip"
},
{
"value": "slide",
"label": "Slide"
}
],
"default": "slide"
},
{
"type": "checkbox",
"id": "centered-Slides",
"label": "centered Slides",
"default": false
},
{
"type": "checkbox",
"id": "auto-Height",
"label": "Auto Height",
"default": false
},
{
"type": "checkbox",
"id": "pagination",
"label": "Pagination",
"default": false
},
{
"type": "checkbox",
"id": "loop",
"label": "Loop",
"default": false
},
{
"type": "range",
"id": "space-Between",
"label": "Space Between",
"info": "Distance between slides in px.",
"min": 0,
"max": 15,
"step": 0.5,
"unit": "px",
"default": 10
},
{
"type": "select",
"id": "direction",
"label": "Direction",
"options": [
{
"value": "horizontal",
"label": "Horizontal"
},
{
"value": "vertical",
"label": "Vertical"
}
],
"default": "horizontal"
},
{% endcomment %} |
<%@page import="java.util.ArrayList"%>
<%@ page import="com.jai.*" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>MyFacebook</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<style>
.fakeimg {
height: 200px;
background: #aaa;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<!-- Brand/logo -->
<a class="navbar-brand" href="#">MyFacebook</a>
<!-- Links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 2</a>
</li>
<li class="nav-item">
<a class="nav-link " href="#">Link 3</a>
</li>
<li class="nav-item">
<a class="nav-link " href="#">Link 3</a>
</li>
</ul>
<div style="float: right;margin-left:auto;margin-right:0">
<form class="form-inline" action="Welcome.jsp" >
<input class="form-control mr-sm-4" type="text" name="txt_name" placeholder="Search">
<input class="btn btn-success" type="submit" value="Search">
</form>
</div>
<%
DBHandler db=new DBHandler();
%>
</nav>
<%
if(request.getParameter("txt_name")!=null && request.getParameter("txt_name").length()!=0)
{
ArrayList<User> users=db.getUser(request.getParameter("txt_name"));
if(users!=null && users.size()!=0)
{
%><div class="container-fluid">
<table class="table table-striped" style="font-size:20px;">
<tbody>
<%
for(User u:users)
{
%> <tr >
<td> <%=u.getName()%></td>
<td><%=u.getEmail()%></td>
<td><a class="btn btn-dark" role="button" href="SendRequest?email=<%=u.getEmail()%>">Send Request</a></td>
</tr>
<%
}
%>
</tbody>
</table>
</div>
<%
}
}
%>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3">
<table class="table table-dark table-hover">
<thead>
<tr>
<th> <h3>Friends</h3> </th>
</tr>
</thead>
<tbody>
<%
ArrayList<User> friends=db.getFriends(session.getAttribute("emailid").toString());
for(User u:friends)
{
%>
<tr >
<td style="font-size:20px"><a style="color:white" href="ViewProfile.jsp?email=<%=u.getEmail()%>"><%=u.getName() %></a></td>
</tr>
<%
}
%>
</tbody>
</table>
</div>
<div class="col-sm-6">
<h3>Whats on your mind <%=db.getName(session.getAttribute("emailid").toString()) %>?</h3>
<form action="SavePost">
<textarea rows="5" cols="90" name="txt_post"></textarea>
<br>
<input type="file" class="form-control-file border" name="image">
<input class="btn btn-dark" role="button" type="submit" value="Upload">
</form>
<%
DBHandler dba=new DBHandler();
ArrayList<Wpost> posts=dba.getPosts(session.getAttribute("emailid").toString());
for(Wpost w:posts)
{ String name=dba.getName(w.getSender());
%>
<div class="container p-3 my-3 border">
<span >
<h5><%=name %></h5>
<font size="2"><%=w.getDop() %></font>
<%if(w.getImg()!=null)
{ %>
<span>
<%=w.getImg() %>
</span>
<%
}
%>
<p class="container p-3 my-3 border">
<%=w.getPost() %>
<p>
</span>
</div>
<%
}
%>
</div>
<div class="col-sm-3">
<table class="table table-dark table-hover">
<thead>
<tr>
<th> <h3>Requests</h3> </th>
</tr>
</thead>
<tbody>
<%
DBHandler dbh=new DBHandler();
ArrayList<User> requests=dbh.getRequest(session.getAttribute("emailid").toString());
for(User u:requests)
{
%>
<tr ><td style="font-size:20px;"> <%=u.getName() %></td>
<td> <a class="btn btn-light" role="button" href="Accept?fid=<%=u.getEmail().split(":")[0]%>">Accept</a></td>
</tr>
<%
}
%>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html> |
const mongoose = require("mongoose");
const listingSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
regularPrice: {
type: Number,
required: true,
},
discountPrice: {
type: Number,
},
bathrooms: {
type: Number,
required: true,
},
bedrooms: {
type: Number,
required: true,
},
furnished: {
type: Boolean,
required: true,
},
parking: {
type: Boolean,
required: true,
},
type: {
type: String,
required: true,
},
offer: {
type: Boolean,
required: true,
},
imageUrls: [
{
url: {
type: String,
required: true,
},
fileName: {
type: String,
required: true,
},
},
],
userRef: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "user",
},
},
{
timestamps: true,
}
);
const listingModel = mongoose.model("listing", listingSchema);
module.exports = listingModel; |
import React, { useState, useRef, useEffect } from "react";
import { FaBars, FaTwitter } from "react-icons/fa";
import { links, social } from "./data";
import logo from "./logo.svg";
const Navbar = () => {
const [showLink, setShowLink] = useState(false);
const linksContainerRef = useRef(null);
const linksRef = useRef(null);
useEffect(() => {
const linksHeight = linksRef.current.getBoundingClientRect().height;
if (showLink) {
linksContainerRef.current.style.height = `${linksHeight}px`;
} else {
linksContainerRef.current.style.height = 0;
}
}, [showLink]);
return (
<nav>
<div className="nav-center">
<div className="nav-header">
<img src={logo} alt="logo" />
<button className="nav-toggle" onClick={() => setShowLink(!showLink)}>
<FaBars />
</button>
</div>
<div className="links-container" ref={linksContainerRef}>
<ul ref={linksRef} className="links">
{links.map((link) => {
return (
<li key={link.id}>
<a href="#">{link.text}</a>
</li>
);
})}
</ul>
</div>
<ul className="social-icons">
{social.map((item) => {
return (
<li key={item.id}>
<a href={item.url}>{item.icon}</a>
</li>
);
})}
</ul>
</div>
</nav>
);
};
export default Navbar; |
package br.com.felipe.validajwt.adapter.mapper;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import br.com.felipe.validajwt.adapter.controller.data.ErrorList;
import br.com.felipe.validajwt.adapter.controller.exception.ValidateJwtHttpException;
import br.com.felipe.validajwt.adapter.controller.mapper.JwtValidationMapper;
import br.com.felipe.validajwt.application.model.ValidateJwtInput;
import br.com.felipe.validajwt.application.model.enumerator.RoleEnum;
public class JwtValidationMapperTest {
@Test
public void testToDomain_ValidAuthorization_NoExceptionThrown() {
// Arrange
String authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJSb2xlIjoiTWVtYmVyIiwiU2VlZCI6IjEyMzQ1NiIsIk5hbWUiOiJKb2huIn0";
// Act & Assert
assertDoesNotThrow(() -> JwtValidationMapper.toDomain(authorization));
}
@Test
public void testToDomain_NullAuthorization_ExceptionThrown() {
// Arrange
String authorization = null;
// Act & Assert
ValidateJwtHttpException exception = assertThrows(ValidateJwtHttpException.class, () -> JwtValidationMapper.toDomain(authorization));
assertEquals(ValidateJwtHttpException.AUTHORIZATION_IS_NULL, exception);
}
@Test
public void testToDomain_BlankAuthorization_ExceptionThrown() {
// Arrange
String authorization = "";
// Act & Assert
ValidateJwtHttpException exception = assertThrows(ValidateJwtHttpException.class, () -> JwtValidationMapper.toDomain(authorization));
assertEquals(ValidateJwtHttpException.AUTHORIZATION_IS_BLANK, exception);
}
@Test
public void testToDomain_InvalidAuthorizationLength_ExceptionThrown() {
// Arrange
String authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
// Act & Assert
ValidateJwtHttpException exception = assertThrows(ValidateJwtHttpException.class, () -> JwtValidationMapper.toDomain(authorization));
assertEquals(ValidateJwtHttpException.AUTHORIZATION_LENGTH_ERROR, exception);
}
@Test
public void testToDomain_DecodeBase64Error_ExceptionThrown() {
// Arrange
String authorization = "invalid_token.invalid_token";
// Act & Assert
ValidateJwtHttpException exception = assertThrows(ValidateJwtHttpException.class, () -> JwtValidationMapper.toDomain(authorization));
assertEquals(ValidateJwtHttpException.DECODE_BASE_64_ERROR, exception);
}
@Test
public void testToDomain_ParseObjectError_ExceptionThrown() {
// Arrange
String authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.ZmtsZGpnbGtqc2tsZ2pzZA";
// Act & Assert
ValidateJwtHttpException exception = assertThrows(ValidateJwtHttpException.class, () -> JwtValidationMapper.toDomain(authorization));
assertEquals(ValidateJwtHttpException.PARSE_OBJECT_ERROR, exception);
}
@Test
public void testToDomain_ContainsClaimsError_ExceptionThrown() {
// Arrange
String authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoiU2VhZCIsInNlZWQiOiIxMjM0NTYiLCJuYW1lIjoiSm9obiJ9";
// Act & Assert
ValidateJwtHttpException exception = assertThrows(ValidateJwtHttpException.class, () -> JwtValidationMapper.toDomain(authorization));
assertTrue(exception.getErrors().contains(ErrorList.CONTAINS_CLAIMS));
}
@Test
public void testToDomain_ClaimsFormatError_ExceptionThrown() {
// Arrange
String authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJSb2xlIjpbIjEyMzQ1NiJdLCJTZWVkIjoiMTIzNDU2IiwiTmFtZSI6IkpvaG4ifQ";
// Act & Assert
ValidateJwtHttpException exception = assertThrows(ValidateJwtHttpException.class, () -> JwtValidationMapper.toDomain(authorization));
assertTrue(exception.getErrors().contains(ErrorList.CLAIMS_FORMAT_INCORRECT));
}
@Test
public void testToDomain_ValidInput_CorrectOutput() throws ValidateJwtHttpException {
// Arrange
String authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJSb2xlIjoiTWVtYmVyIiwiU2VlZCI6IjEyMzQ1NiIsIk5hbWUiOiJKb2huIn0";
Map<String, Object> claims = new HashMap<>();
claims.put("Role", "admin");
claims.put("Seed", "123456");
claims.put("Name", "John");
// Act
ValidateJwtInput input = JwtValidationMapper.toDomain(authorization);
// Assert
assertEquals(RoleEnum.MEMBER, input.getRole());
assertEquals(new BigDecimal("123456"), input.getSeed());
assertEquals("John", input.getName());
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.