text
stringlengths 184
4.48M
|
---|
import * as core from "@actions/core";
import * as github from "@actions/github";
import * as fs from "fs";
import { components } from "@octokit/openapi-types";
import { GitHub } from "@actions/github/lib/utils";
export type Octokit = InstanceType<typeof GitHub>;
export type Review = components["schemas"]["pull-request-review"];
export type Reviews = Review[];
export type Reviewer = {
username: string;
name: string;
};
export type Reviewers = Reviewer[];
export type Cache = { [key: string]: string };
export function getApprovedReviews(reviews: Reviews): Reviews {
const latestReviews = reviews
.reverse()
.filter((review) => review.state.toLowerCase() !== "commented")
.filter((review, index, array) => {
// https://dev.to/kannndev/filter-an-array-for-unique-values-in-javascript-1ion
return array.findIndex((x) => review.user?.id === x.user?.id) === index;
});
return latestReviews.filter((review) => review.state.toLowerCase() === "approved");
}
export async function getReviewers(
octokit: Octokit,
reviews: Reviews,
cache: Cache
): Promise<Reviewers> {
const reviewers: Reviewers = [];
for (const review of reviews) {
if (!review.user) {
continue;
}
reviewers.push(await getReviewer(octokit, review.user.login, cache));
}
return reviewers;
}
export async function getReviewer(
octokit: Octokit,
username: string,
cache: Cache
): Promise<Reviewer> {
const reviewer = { username } as Reviewer;
if (username in cache) {
reviewer.name = cache[username];
} else {
core.info(`API call to get ${username} name`);
const { data: user } = await octokit.rest.users.getByUsername({ username: username });
if (user) {
reviewer.name = user.name || "";
cache[username] = reviewer.name;
}
}
return reviewer;
}
export function readCache(path = "./cache.json"): Cache {
try {
const data = fs.readFileSync(path, "utf8");
return JSON.parse(data) as Cache;
} catch (err) {
console.log(`Error reading file: ${err}`);
}
return {} as Cache;
}
export function updateCache(cache: Cache, path = "./cache.json"): void {
try {
fs.writeFileSync(path, JSON.stringify(cache), "utf8");
} catch (err) {
console.log(`Error writing file: ${err}`);
}
}
export function getBodyWithApprovedBy(pullBody: string | null, reviewers: Reviewers): string {
pullBody = pullBody || "";
const approveByIndex = pullBody.search(/Approved-by/);
let approvedByBody = "";
for (const reviewer of reviewers) {
approvedByBody += `\nApproved-by: ${reviewer.username}`;
if (reviewer.name) {
approvedByBody += ` (${reviewer.name})`;
}
}
// body with "Approved-by" already set
if (approveByIndex > -1) {
pullBody = pullBody.replace(/\nApproved-by:.*/s, approvedByBody);
}
// body without "Approved-by"
if (approvedByBody.length > 0 && approveByIndex === -1) {
pullBody += `\n${approvedByBody}`;
}
return pullBody;
}
export async function run(): Promise<void> {
const token = core.getInput("GITHUB_TOKEN", { required: true });
if (!token) {
throw new Error("No GITHUB_TOKEN found in input");
}
const octokit = github.getOctokit(token);
const context = github.context;
if (!context.payload.pull_request) {
throw new Error("No pull request found in payload");
}
const { data: pull } = await octokit.rest.pulls.get({
...context.repo,
pull_number: context.payload.pull_request.number,
});
const { data: reviews } = await octokit.rest.pulls.listReviews({
...context.repo,
pull_number: context.payload.pull_request.number,
per_page: 100,
});
const approvedReviews = getApprovedReviews(reviews);
const cache: Cache = readCache();
const reviewers = await getReviewers(octokit, approvedReviews, cache);
updateCache(cache);
const body = getBodyWithApprovedBy(pull.body, reviewers);
if (body !== pull.body) {
await octokit.rest.pulls.update({
...context.repo,
pull_number: context.payload.pull_request.number,
body: body,
});
}
}
|
#include<Servo.h> //servo motor kütüphanesini ekle
#define led 6 //6 nolu pine led ismini ver
#define alarm 7
#define yagmur A0
Servo motor;
int su_miktari ; //int tipinde su_miktari adında bir değişken oluştur
int uyari = 0 ; //int tipinde uyari adında bir değişken oluştur ve başlangıç olarak 0 yükle
void setup() {
pinMode(3,OUTPUT); // 3 nolu pini çıkış olarak ayarla
pinMode(led,OUTPUT);
pinMode(alarm,OUTPUT);
pinMode(yagmur,INPUT); // yagmur isimli pini giriş olarak ayarla
motor.attach(9);
Serial.begin(9600); // haberleşmeyi 9600 bps hızında başlat
}
void loop() {
int isik = analogRead(A5); // int tipinde isik adinda bir değişken oluşturup a5 pinini analog olarak okuyoruz
Serial.println(isik); // seri port ekranına isik yaz bir alt satıra geç
delay(50); // bu komutları 50ms de bir tekrarla
su_miktari = analogRead(yagmur); // yagmur adlı değişkeni analog olarak oku ve su miktarina eşitle
delay(200);
Serial.print("su miktarı"); // seri port ekranına su miktarı yaz
Serial.println(su_miktari);
if(su_miktari < 450){ // eğer su miktarı 450 den küçükse
digitalWrite(led,HIGH); // led'i yak
digitalWrite(alarm,HIGH); // alarmı çalıştır
delay(500); // komutu 500ms saniyede bir tekrarla
uyari = uyari + 1;
}
if(uyari = 3){ // eğer uyari 3 e eşitlnirse
digitalWrite(led,LOW); // led isimle pine 0v gönder
digitalWrite(alarm,LOW);
motor.write(180); // motoru 180 derece çevir
uyari = 0; //uyarı yı 0 a eşitle
}
else{
uyari = 0; // uyarıyı 0 a eşitle
motor.write(0); // motoru 0 dereceye getir
}
if(isik > 250){ // isik 250 den büyükse
digitalWrite(3,LOW); // 3 nolu pin 0 volt gönder
}
if(isik < 150){ // eğer isik 150 den küçükse
digitalWrite(3,HIGH); // 3 nolu pine +5 volt gönder
}
}
|
from rest_framework import serializers
from django.conf import settings
from core._shared.serializers.list_meta_response_serializer import ListMetaResponseSerializer
from core.cast_member.domain import CastMemberType
class EnumField(serializers.ChoiceField):
# TODO: find a better way to serialize enums
def __init__(self, enum, **kwargs):
self.enum = enum
kwargs['choices'] = [(e.name, e.value) for e in enum]
super(EnumField, self).__init__(**kwargs)
def to_representation(self, obj):
if type(obj) == str:
return obj
else:
return obj.name
def to_internal_value(self, data):
try:
return self.enum[data]
except KeyError:
self.fail('invalid_choice', input=data)
class CastMemberSerializer(serializers.Serializer):
id = serializers.UUIDField()
name = serializers.CharField()
cast_member_type = EnumField(enum=CastMemberType)
class ListCastMembersRequestSerializer(serializers.Serializer):
page = serializers.IntegerField(default=1)
page_size = serializers.IntegerField(default=settings.DEFAULT_PAGE_SIZE)
class ListCastMembersResponseSerializer(serializers.Serializer):
data = CastMemberSerializer(many=True)
meta = ListMetaResponseSerializer()
class GetCastMemberRequestSerializer(serializers.Serializer):
cast_member_id = serializers.UUIDField()
class GetCastMemberResponseSerializer(serializers.Serializer):
data = CastMemberSerializer(source="cast_member")
class CreateCastMemberRequestSerializer(serializers.Serializer):
name = serializers.CharField()
cast_member_type = EnumField(enum=CastMemberType)
class CreateCastMemberResponseSerializer(serializers.Serializer):
id = serializers.UUIDField()
class UpdateCastMemberRequestSerializer(serializers.Serializer):
cast_member_id = serializers.UUIDField()
name = serializers.CharField(required=True)
cast_member_type = EnumField(enum=CastMemberType)
class UpdateCastMemberResponseSerializer(serializers.Serializer):
pass
class PartialUpdateCastMemberRequestSerializer(serializers.Serializer):
cast_member_id = serializers.UUIDField()
name = serializers.CharField(required=False)
cast_member_type = EnumField(enum=CastMemberType, required=False)
class PartialUpdateCastMemberResponseSerializer(serializers.Serializer):
pass
class DeleteCastMemberRequestSerializer(serializers.Serializer):
cast_member_id = serializers.UUIDField()
|
import {IsNumber, IsString, IsUUID} from "class-validator";
import {ApiProperty} from "@nestjs/swagger";
export class UserDto {
@ApiProperty({
type: 'uuid',
description: 'User id',
})
@IsUUID()
public id: string;
@ApiProperty({
type: 'string',
description: 'User telegram username',
})
@IsString()
public tg_name: string;
@ApiProperty({
type: 'number',
description: 'User role code',
})
@IsNumber()
public role_code: number;
}
|
//
// ContentView.swift
// WordScramble
//
// Created by Kamil Krzych on 16/06/2021.
//
import SwiftUI
struct ContentView: View {
@State private var usedWords = [String]()
@State private var rootWord = ""
@State private var newWord = ""
@State private var errorTitle = ""
@State private var errorMessage = ""
@State private var showingError = false
var body: some View {
NavigationView {
VStack {
Section {
TextField("Enter your word", text: $newWord, onCommit: addNewWord)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.autocapitalization(.none)
Button(action: startGame, label: {
Text("Draw new word")
.foregroundColor(.black)
.padding()
.background(Color.accentColor)
.cornerRadius(8)
})
}
List(usedWords, id: \.self){
Image(systemName: "\($0.count).circle")
Text($0)
}
}
.navigationBarTitle(rootWord)
.alert(isPresented: $showingError) {
Alert(title: Text(errorTitle), message: Text(errorMessage), dismissButton: .default(Text("OK")))
}
}
}
func addNewWord() {
// lowercase and trim the word, to make sure we don't add duplicate words with case differences
let answer = newWord.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
// exit if the remaining string is empty
guard answer.count > 0 else {
return
}
guard isOriginal(word: answer) else {
wordError(title: "Word used already", message: "Be more original")
return
}
guard isPossible(word: answer) else {
wordError(title: "Word not recognized", message: "You know that you can't just make them up, right?")
return
}
guard isReal(word: answer) else {
if (answer.count <= 3) {
wordError(title: "Word not possible", message: "Word cannot be shorter or even 3 letters.")
return
} else{
wordError(title: "Word not possible", message: "That is not a real word")
return
}
}
usedWords.insert(answer, at: 0)
newWord = ""
}
func startGame() {
// Find the URL for start.txt in our app bundle
if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") {
// Load start.txt into a string
if let startWords = try? String(contentsOf: startWordsURL) {
// Split the string up into an array of strings, splitting on line breaks
let allWords = startWords.components(separatedBy: "\n")
// Pick one random word, or use "silkworm" as a sensible default
rootWord = allWords.randomElement() ?? "silkworm"
// If we are here, everything has worked, so we can exit
return
}
}
// If we are here, then there was a problem - trigger a crash and report an error
fatalError("Could not load string.txt from bundle.")
}
func isOriginal(word: String) -> Bool {
!usedWords.contains(word)
}
func isPossible(word: String) -> Bool {
var tempWord = rootWord
for letter in word {
if let pos = tempWord.firstIndex(of: letter) {
tempWord.remove(at: pos)
} else {
return false
}
}
return true
}
func isReal(word: String) -> Bool {
let checker = UITextChecker()
let range = NSRange(location: 0, length: word.utf16.count)
let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
if (word.count <= 3) {
return false
} else {
return misspelledRange.location == NSNotFound
}
}
func wordError(title: String, message: String) {
errorTitle = title
errorMessage = message
showingError = true
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rbroque <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/01/28 04:34:09 by rbroque #+# #+# */
/* Updated: 2023/01/28 14:31:54 by rbroque ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_PRINTF_H
# define FT_PRINTF_H
# include <stdarg.h>
# include "libft.h"
# ifndef BUFFER_SIZE
# define BUFFER_SIZE 10
# endif
# define EMPTY_STRING ""
# define NULL_DEF "(null)"
# define NIL_DEF "(nil)"
# define SPACE_PAT " "
# define END_CHAR '\0'
# define PLUS_SIGN "+"
# define MINUS_SIGN "-"
# define WIDTH_UNIT " 0"
# define HEX "0123456789abcdef"
# define DEC "0123456789"
# define PREFIX_HEX "0x"
# define OPTION_CHAR "%"
# define PRECISION_CHAR "."
# define OPTIONS "cs%diuxXp"
# define NBOF_OPTIONS 9
# define UNSET_PRECISION -1
# define FLAGS " +#-0"
# define NBOF_FLAGS 4
# define NO_FLAG 0x01
# define SPACE_FLAG 0x02
# define PLUS_FLAG 0x04
# define PREFIX_FLAG 0x08
# define MINUS_FLAG 0x10
# define ZERO_FLAG 0x20
# define NO_TYPE 0x0000
# define CHAR_TYPE 0x0007
# define PERCENTAGE_TYPE 0x0004
# define CHARACTER_TYPE 0x0001
# define NB_TYPE 0x01F8
# define SIGNED_TYPE 0x0018
# define UNSIGNED_TYPE 0x01E0
# define HEX_TYPE 0x01C0
# define LOW_TYPE 0x0040
# define UP_TYPE 0x0080
# define ADDRESS_TYPE 0x0100
enum e_state
{
E_STANDARD,
E_MOD,
E_WIDTH,
E_PRECISION,
E_CONV,
E_END,
};
typedef uint16_t t_type;
typedef uint8_t t_flag;
typedef struct s_arg
{
va_list aptr;
size_t size;
t_type type;
t_flag flags;
size_t width;
ssize_t precision;
} t_arg;
typedef struct s_output
{
char buffer[BUFFER_SIZE + 1];
size_t index;
size_t total_size;
char *final_str;
} t_output;
typedef struct s_machine
{
const char *input;
t_output *output;
t_arg *arg;
int fd;
enum e_state state;
} t_machine;
// ft_getprintf
char *ft_getprintf(const char *str, ...);
// ft_vdprintf
int ft_vdprintf(int fd, const char *str, va_list aptr);
// ft_dprintf
int ft_dprintf(int fd, const char *str, ...);
// ft_printf
int ft_printf(const char *str, ...);
// machine_struct
t_arg *init_arg(t_type type, va_list aptr);
t_machine *init_machine(const char *str, va_list aptr, int fd);
void free_machine(t_machine *machine);
//states_utils
char *fill_unknown(t_machine *machine);
void fill_invalid_precision(t_machine *machine);
// converters
size_t apply_converter(t_machine *machine);
char *character(t_arg *arg);
char *string(t_arg *arg);
char *percentage(t_arg *arg);
char *integer_d(int nb);
char *integer_i(int nb);
char *u_integer(unsigned long nb);
char *low_hex(unsigned int nb);
char *up_hex(unsigned int nb);
char *address(void *address);
// states
size_t conv_state(t_machine *machine);
size_t mod_state(t_machine *machine);
size_t width_state(t_machine *machine);
size_t precision_state(t_machine *machine);
size_t standard_state(t_machine *machine);
// converters/type
void add_sign(int nb, char **output, t_arg *arg);
void add_beginning(int nb, char **output, t_arg *arg);
char *char_type(t_arg *arg);
char *nb_type(t_arg *arg);
char *signed_type(t_arg *arg);
char *unsigned_type(t_arg *arg);
char *hex_type(t_arg *arg, unsigned long nb);
// flags
void remove_flag(t_flag *flags, t_flag removing_flag);
void add_flag(t_flag *flags, t_flag removing_flag);
size_t get_index_from_type(t_type type, t_type mask);
void get_flag(t_flag *flags, const ssize_t flag_index);
// precision
char *get_precision(ssize_t precision, char *string);
size_t get_precision_size(const char *input, const t_arg *arg);
// get_size
void get_widthsize(t_machine *machine, ssize_t option_index);
// tocase_str
char *toupper_str(char *str);
char *tolower_str(char *str);
// itoa_base
size_t get_nbsize(unsigned long nb, const size_t len_base);
char *itoa_base(const unsigned long nb, const char *base);
// utils
size_t reduce_size(size_t width, size_t size);
ssize_t get_index(const char *str, const char c);
char *to_string(const char c);
// strings
size_t ft_strlen_sec(const char *str);
char *strset(int c, size_t n);
char *ft_strndup(const char *str, const size_t size);
char *add_str(char *s1, const char *s2, const size_t n);
char *add_strn(char *s1, const size_t n1,
const char *s2, const size_t n2);
// cpy_data
size_t get_output_size(const char *string, const t_arg *arg);
void cpy_data(t_output *output, void *data, size_t n);
void cpy_to_buffer(t_machine *machine, char *string);
void add_width(char **output, t_arg *arg);
void prefix_add(char *prefix, char **string);
#endif
|
//--------------------------------------------------------------------------------------
// File: Shadersasd.fx
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License (MIT).
//--------------------------------------------------------------------------------------
#define NUM_LIGHTS (1)
#define NEAR_PLANE (0.01f)
#define FAR_PLANE (1000.0f)
//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
TextureCube environmentMapTexture : register(t0);
Texture2D txDiffuse : register(t1);
SamplerState sampLinear : register(s0);
//--------------------------------------------------------------------------------------
// Constant Buffer Variables
//--------------------------------------------------------------------------------------
/*C+C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C
Cbuffer: cbChangeOnCameraMovement
Summary: Constant buffer used for view transformation
C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C-C*/
cbuffer cbChangeOnCameraMovement : register(b0)
{
matrix View;
float4 CameraPosition;
};
/*C+C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C
Cbuffer: cbChangeOnResize
Summary: Constant buffer used for projection transformation
C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C-C*/
cbuffer cbChangeOnResize : register(b1)
{
matrix Projection;
};
/*C+C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C
Cbuffer: cbChangesEveryFrame
Summary: Constant buffer used for world transformation
C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C-C*/
cbuffer cbChangesEveryFrame : register(b2)
{
matrix World;
float4 OutputColor;
bool HasNormalMap;
};
struct PointLight
{
float4 Position;
float4 Color;
matrix View;
matrix Projection;
float4 AttenuationDistance;
};
cbuffer cbLights : register(b3)
{
PointLight aPointLight[NUM_LIGHTS];
};
//--------------------------------------------------------------------------------------
/*C+C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C
Struct: VS_INPUT
Summary: Used as the input to the vertex shader
C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C-C*/
struct VS_INPUT
{
float4 Position : POSITION;
float2 TexCoord : TEXCOORD0;
float3 Normal : NORMAL;
float3 Tangent : TANGENT;
float3 Bitangent : BITANGENT;
row_major matrix mTransform : INSTANCE_TRANSFORM;
};
/*C+C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C
Struct: PS_INPUT
Summary: Used as the input to the pixel shader, output of the
vertex shader
C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C-C*/
struct PS_INPUT
{
float4 Position : SV_POSITION;
float2 TexCoord : TEXCOORD0;
float3 Normal : NORMAL;
float3 WorldPosition : WORLDPOS;
float3 Tangent : TANGENT;
float3 Bitangent : BITANGENT;
float4 LightViewPosition : TEXCOORD1;
float3 Reflection : REFLECTION;
};
//--------------------------------------------------------------------------------------
// Vertex Shader
//--------------------------------------------------------------------------------------
PS_INPUT VSEnvironmentMap(VS_INPUT input)
{
PS_INPUT output = (PS_INPUT)0;
output.Position = input.Position;
output.Position = mul(output.Position, World);
output.Position = mul(output.Position, View);
output.Position = mul(output.Position, Projection);
output.Normal = mul(float4(input.Normal, 0.0f), World).xyz;
output.TexCoord = input.TexCoord;
output.WorldPosition = mul(input.Position, World).xyz;
if (HasNormalMap)
{
output.Tangent = normalize(mul(float4(input.Tangent, 0.0f), World).xyz);
output.Bitangent = normalize(mul(float4(input.Bitangent, 0.0f), World).xyz);
}
output.Reflection = reflect(normalize(output.WorldPosition - CameraPosition.xyz), normalize(mul(float4(input.Normal, 0.0f), World).xyz));
return output;
}
//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PSEnvironmentMap(PS_INPUT input) : SV_Target
{
float4 albedo = txDiffuse.Sample(sampLinear, input.TexCoord);
float3 environmentMapColor = environmentMapTexture.Sample(sampLinear, input.Reflection).rgb;
/* shading */
// ambient light
float3 ambient = float3(0.1f, 0.1f, 0.1f) * albedo.rgb;
for (uint i = 0u; i < NUM_LIGHTS; ++i)
{
ambient += float3(0.1f, 0.1f, 0.1f) * aPointLight[i].Color.xyz;
}
// diffuse light
float3 diffuse = float3(0.0f, 0.0f, 0.0f);
float3 lightDirection = float3(0.0f, 0.0f, 0.0f);
for (uint j = 0; j < NUM_LIGHTS; ++j)
{
lightDirection = normalize(aPointLight[j].Position.xyz - input.WorldPosition);
diffuse += saturate(dot(input.Normal, lightDirection)) * aPointLight[j].Color;
}
// specular light
float3 specular = float3(0.0f, 0.0f, 0.0f);
float3 viewDirection = normalize(CameraPosition.xyz - input.WorldPosition);
for (uint k = 0; k < NUM_LIGHTS; ++k)
{
float3 lightDirection = normalize(aPointLight[k].Position.xyz - input.WorldPosition);
float3 reflectDirection = reflect(-lightDirection, input.Normal);
specular += pow(saturate(dot(reflectDirection, viewDirection)), 40.0f)
* aPointLight[k].Color; // color of the light
}
return float4(saturate(ambient + diffuse + specular + environmentMapColor * 0.5f), albedo.a);
}
|
<script lang="ts">
import { computed, defineComponent, ref } from 'vue';
import { useManifest } from '~/composables';
import { ConfigurationTableColumn } from '~/types';
export default defineComponent({
props: {
component: {
type: String,
required: true
}
},
setup(props) {
const componentName = computed(() => props.component);
const { manifest } = useManifest(componentName);
const componentEvents = computed(() => manifest.value?.events || []);
const columns = ref<ConfigurationTableColumn[]>([
{ label: 'Event', key: 'name', type: 'code' },
{ label: '', key: 'description' }
]);
return {
componentEvents,
columns
};
}
});
</script>
<template>
<ConfigurationTable :rows="componentEvents" :columns="columns" />
</template>
|
package it.polimi.db2.project.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
@Entity
@Table(name = "user", schema = "db2")
@NamedQueries({ @NamedQuery(name = "User.findAllInsolvent", query = "SELECT u FROM User u WHERE u.insolvent=true"),
@NamedQuery(name = "User.checkCredentials", query = "SELECT r FROM User r WHERE r.email = ?1 and r.password = ?2"),
@NamedQuery(name = "User.findById", query="SELECT u FROM User u WHERE u.idUser = ?1")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int idUser;
//bi-directional many-to-one association to Order
@OneToMany(mappedBy="user", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true )
private List<Order> orders;
//bi-directional many-to-one association to Order
@OneToOne(mappedBy="user")
private Alert alert;
private String Name;
private String password;
private String Surname;
private String email;
private String role;
private Boolean insolvent;
private String username;
public User() {
}
public int getId() {
return this.idUser;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
public void setId(int id) {
this.idUser = id;
}
public String getName() {
return this.Name;
}
public void setName(String name) {
this.Name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSurname() {
return this.Surname;
}
public void setSurname(String surname) {
this.Surname = surname;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
public Boolean getInsolvent() {
return this.insolvent;
}
public void setInsolvent(Boolean insolvent) {
this.insolvent = insolvent;
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public void addOrder(Order o) {
getOrders().add(o);
o.setUser(this);
}
public void removeOrder(Order o) {
getOrders().remove(o);
o.setUser(null);
}
public Alert getAlert() {
return this.alert;
}
public void setAlert(Alert alert) {
this.alert = alert;
}
}
|
package org.academiadecodigo.felinux.gtfo.characters.enemies;
import org.academiadecodigo.felinux.gtfo.field.Field;
import org.academiadecodigo.simplegraphics.graphics.Color;
import org.academiadecodigo.simplegraphics.graphics.Rectangle;
import org.academiadecodigo.simplegraphics.graphics.Text;
import org.academiadecodigo.simplegraphics.pictures.Picture;
public class CopCar extends Enemy {
private boolean forward;
private boolean turning;
private final float MAX_SPEED = 4.5f;
private final float ACCEL = 1.5f;
private float cSpeed;
private int turningCounter;
public CopCar(int posX, int posY, String spriteName) {
super(EnemyAreaType.COP_CAR, posX, posY, spriteName, 10);
}
@Override
public Picture getEnemy() {
return super.getEnemy();
}
/**
* Traces the route for the policeCar
* And makes the movement
*/
@Override
public void move() {
if (turning) {
cSpeed = 1;
if (turningCounter > 4) {
turningCounter = 0;
turning = false;
if (forward) {
forward = false;
return;
}
forward = true;
return;
}
turnCar();
return;
}
//if it is not turning it gains speed
//and moves accordingly
if (cSpeed < MAX_SPEED) {
cSpeed += ACCEL;
}
//direction that the car is moving and the movement
if (!forward) {
if (getEnemy().getX() < Field.width - 50) {
getEnemy().translate(cSpeed, 0);
getArea().getBoundArea().translate(cSpeed, 0);
return;
}
turning = true;
return;
}
//other direction
if (getEnemy().getX() > Field.PADDING_X + 50) {
getEnemy().translate(-cSpeed, 0);
getArea().getBoundArea().translate(-cSpeed, 0);
return;
}
turning = true;
}
//handles turning
private void turnCar() {
turningCounter++;
if (forward) {
getEnemy().translate(0, cSpeed);
getArea().getBoundArea().translate(0, cSpeed);
return;
}
getEnemy().translate(0, -cSpeed);
getArea().getBoundArea().translate(0, -cSpeed);
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas width="570" height="570" id="my_Canvas"></canvas>
</body>
<script>
var canvas = document.getElementById("my_Canvas");
var gl = canvas.getContext("webgl");
var vertexSource = "attribute vec4 aVertexPosition;attribute vec4 aVertexColor;varying lowp vec4 vColor;" +
"void main(){gl_Position=aVertexPosition;vColor = aVertexColor;}";
var fragmentSource = "varying lowp vec4 vColor;void main(){gl_FragColor=vColor;}";
var shaderProgram = initShaderProgram(gl, vertexSource, fragmentSource);
//顶点数据
var vertices = [-0.2, 0,
0, -0.5, -0.4, -0.5,
0.4, 0,
0, -0.5,
0.4, -0.5,
];
//索引数据
var indices = [0, 1, 2, 2, 0, 3];
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
var Index_Buffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
//获取属性的位置
var aVertexPosition = gl.getAttribLocation(shaderProgram, 'aVertexPosition');
//分配缓冲对象的属性变量
//参数1它指定一个属性变量的存储位置。根据这个方案,必须通过由getAttribLocation()方法返回的值
//参数2代表每个顶点需要几个向量(几维);参数3代表数据类型;参数4是一个布尔值。如果为真,非浮动数据被归一化到[0,1]。否则,它被归一化到[-1,1]。;
//参数5指定不同顶点数据元素之间的字节数,或默认为零步幅;
//参数6它指定在缓冲器对象,以指示数据从顶点的哪个存储字节偏移(字节)。如果数据是从开始(beginning)存储的,偏移量(offset)为0。
gl.vertexAttribPointer(aVertexPosition, 2, gl.FLOAT, false, 0, 0);
//激活顶点着色器属性来访问缓冲对象的顶点着色器
gl.enableVertexAttribArray(aVertexPosition);
var colors = [
1.0, 1.0, 1.0, 1.0, // 白色
1.0, 0.0, 0.0, 1.0, // 红色
0.0, 1.0, 0.0, 1.0, // 绿色
0.0, 0.0, 1.0, 1.0 // 蓝色
];
squareVerticesColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
gl.vertexAttribPointer(vertexColorAttribute, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vertexColorAttribute);
var red = 210;
var green = 138;
var blue = 138;
// 清除指定<画布>的颜色为此颜色
gl.clearColor(red / 255, green / 255, blue / 255, 1.0);
// 清空 <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
//使用数组之间绘制。参数1绘制类型;参数2指定第几个元素开始;参数3使用几个点
//gl.drawArrays(gl.TRIANGLE_STRIP, 0, 6);
//使用索引进行绘制。参数1绘制类型;参数2绘制数量;参数3数据类型;参数4第几个开始
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
//创建着色器程序
function initShaderProgram(gl, vsSource, fsSource) {
var vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if(!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
console.log("error:" + gl.getProgramInfoLog())
return null;
}
gl.useProgram(shaderProgram);
return shaderProgram;
}
//创建着色器
function loadShader(gl, type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.log("error:" + gl.getShaderInfoLog(shader));
gl.deleteShader(shader)
return null;
}
return shader;
}
</script>
</html>
|
<template>
<q-page class="bg-brown-1">
<div class="q-pa-md">
<q-card class="q-pa-md">
<q-breadcrumbs separator="---" class="text-brown" active-color="black">
<q-breadcrumbs-el label="Main Menu" icon="widgets" />
<q-breadcrumbs-el label="Penjualan" icon="storefront" />
</q-breadcrumbs>
</q-card>
<div class="row q-mt-md">
<div class="row q-gutter-md col-12">
<q-card class="col-lg-3 col-md-4 col-sm-6" flat bordered>
<q-card-section horizontal>
<q-card-section class="col-4 flex flex-center">
<lottie style="width: 80px" :options="defaultOptions" />
</q-card-section>
<q-card-section class="q-pt-xs">
<div class="text-h6 q-mt-sm" style="font-size: 14px">
Data Penjualan
</div>
<div class="text-caption text-grey" style="font-size: 11px">
jumlah penjualan usaha kopi.
</div>
<div class="row items-center">
<q-icon name="credit_score" />
<div
class="text-h6 q-ml-sm text-blue-13"
style="font-size: 12px"
>
<vue3-autocounter
ref="counter"
:startAmount="0"
:endAmount="Number(dataPenjualan)"
:duration="3"
:autoinit="true"
/>
</div>
</div>
</q-card-section>
</q-card-section>
</q-card>
</div>
<div class="row col-12 q-mt-md">
<q-card class="col-md-12 col-xs-12" flat bordered>
<q-table
:rows="rows"
:columns="columns"
row-key="name"
:filter="filter"
:pagination="pagination"
>
<template v-slot:top>
<div class="col">
<div class="text-weight-bold">PENJUALAN</div>
<div>Daftar semua penjualan pada saat ini</div>
</div>
<q-space />
<q-btn
@click="openDialog(false, null)"
icon="library_add"
label="Tambah Data"
color="blue-7"
>
</q-btn>
<q-btn
flat
color="primary"
icon="search"
@click="visibles = !visibles"
size="md"
class="q-mr-sm"
/>
<q-slide-transition>
<div v-show="visibles">
<q-input
outlined
debounce="300"
placeholder="Pencarian"
style="width: 200px"
color="primary"
v-model="filter"
dense
/>
</div>
</q-slide-transition>
</template>
<template v-slot:body="props">
<q-tr :props="props">
<q-td key="tanggal" :props="props">
{{
new Date(props.row.tanggal).toLocaleDateString("id", {
year: "numeric",
month: "long",
day: "numeric",
})
}}
</q-td>
<q-td key="namaProduk" :props="props">
{{ props.row.namaProduk }}
</q-td>
<q-td key="keterangan" :props="props">
{{ props.row.keterangan }}
</q-td>
<q-td key="harga" :props="props">
Rp. {{ props.row.harga }}
</q-td>
<q-td key="jumlah" :props="props">
{{ props.row.jumlah }}
</q-td>
<q-td key="total" :props="props">
Rp {{ props.row.total }}
</q-td>
<q-td key="action" :props="props">
<div class="justify-center q-gutter-x-xs">
<q-btn
flat
color="blue-8"
size="md"
class="q-px-xs"
icon="edit"
@click="openDialog(true, props.row)"
></q-btn>
<q-btn
flat
color="red"
size="md"
@click="hapusData(props.row._id)"
class="q-px-xs"
icon="delete"
></q-btn>
</div>
</q-td>
</q-tr>
</template>
</q-table>
</q-card>
</div>
<q-dialog v-model="dialog">
<q-card
class="my-card"
flat
bordered
style="width: 600px; max-width: 70vw"
>
<q-item>
<q-item-section avatar>
<q-avatar>
<q-icon name="storefront" size="30px" color="brown" />
</q-avatar>
</q-item-section>
<q-item-section>
<q-item-label class="text-weight-bold text-uppercase">
Input /Edit Penjualan
</q-item-label>
<q-item-label caption>
Input atau edit data penjualan
</q-item-label>
</q-item-section>
<q-item-section class="col-1">
<q-btn
flat
dense
icon="close"
class="float-right"
color="grey-8"
v-close-popup
></q-btn>
</q-item-section>
</q-item>
<q-separator />
<q-form @submit="onSubmit()" @reset="onReset()">
<q-card-section horizontal>
<q-card-section class="q-gutter-md fit">
<q-input
dense
type="date"
v-model="tanggal"
outlined
label="Tanggal"
/>
<q-input
dense
v-model="namaProduk"
outlined
label="Nama Produk "
/>
<q-input
dense
v-model="keterangan"
outlined
label="keterangan"
/>
</q-card-section>
<q-separator vertical />
<q-card-section class="q-gutter-md fit">
<q-input
dense
type="number"
v-model="harga"
outlined
label="Harga"
/>
<q-input
dense
type="number"
v-model="jumlah"
outlined
label="Jumlah"
/>
</q-card-section>
</q-card-section>
<q-separator />
<q-card-actions>
<q-btn flat type="submit" label="Simpan" color="primary" />
<q-btn flat type="reset" label="Reset" color="grey" />
</q-card-actions>
</q-form>
</q-card>
</q-dialog>
</div>
</div>
</q-page>
</template>
<script>
import Vue3autocounter from "vue3-autocounter";
import Lottie from "./../../components/Lottie.vue";
import * as animationData from "./../../../public/images/lottie/pengeluaran.json";
const columns = [
{
name: "tanggal",
label: "Tanggal",
field: "tanggal",
align: "left",
},
{
name: "namaProduk",
label: "Nama Produk",
field: "namaProduk",
align: "left",
},
{
name: "keterangan",
label: "Keterangan",
field: "keterangan",
align: "left",
},
{
name: "harga",
label: "Harga",
field: "harga",
align: "left",
},
{
name: "jumlah",
label: "Jumlah",
field: "jumlah",
align: "left",
},
{
name: "total",
label: "Total",
field: "total",
align: "left",
},
{
name: "action",
label: "Action",
field: "action",
align: "center",
},
];
const rows = [];
export default {
name: "PenjualanPage",
components: {
"vue3-autocounter": Vue3autocounter,
Lottie: Lottie,
},
data() {
return {
defaultOptions: { animationData: animationData.default },
animationSpeed: 2,
columns,
rows,
filter: "",
pagination: {
rowsPerPage: 10,
},
visibles: false,
editMode: false,
dialog: false,
dataPenjualan: null,
tanggal: null,
namaProduk: null,
harga: null,
jumlah: null,
keterangan: null,
idActive: null,
};
},
created() {
this.getData();
},
methods: {
openDialog(editMode, data) {
this.editMode = editMode;
if (editMode) {
this.tanggal = data.tanggal;
this.namaProduk = data.namaProduk;
this.harga = data.harga;
this.jumlah = data.jumlah;
this.total = data.total;
this.keterangan = data.keterangan;
this.idActive = data._id;
} else {
this.tanggal = null;
this.namaProduk = null;
this.harga = null;
this.jumlah = null;
this.total = null;
this.keterangan = null;
this.idActive = null;
}
this.dialog = true;
},
resetDialog() {
this.editMode = false;
this.dialog = false;
},
onReset() {
this.tanggal = null;
this.namaProduk = null;
this.harga = null;
this.jumlah = null;
this.total = null;
this.keterangan = null;
},
onSubmit() {
if (this.editMode) {
this.$axios
.put(`penjualan/edit/${this.idActive}`, {
tanggal: this.tanggal,
namaProduk: this.namaProduk,
harga: this.harga,
jumlah: this.jumlah,
total: this.total,
keterangan: this.keterangan,
})
.then((res) => {
if ((res.data.sukses = true)) {
this.$successNotif(res.data.pesan, "positive");
}
this.getData();
this.resetDialog();
this.onReset();
});
} else {
this.$axios
.post("penjualan/add", {
tanggal: this.tanggal,
namaProduk: this.namaProduk,
harga: this.harga,
jumlah: this.jumlah,
total: this.total,
keterangan: this.keterangan,
})
.then((res) => {
if (res.data.sukses) {
this.$successNotif(res.data.pesan, "positive");
}
this.dialog = false;
this.getData();
});
}
},
getData() {
this.$axios.get("penjualan/getAll").then((res) => {
if (res.data.sukses) {
this.rows = res.data.data;
}
});
},
hapusData(_id) {
this.$q
.dialog({
title: "Konfirmasi",
message: "Apakah anda yakin ingin menghapus data ini?",
cancel: true,
persistent: true,
})
.onOk(() => {
this.$axios.delete(`penjualan/delete/${_id}`).then((res) => {
if (res.data.sukses) {
this.$successNotif(res.data.pesan, "positive");
}
this.getData();
});
});
},
},
computed: {
total() {
return this.harga * this.jumlah;
},
},
};
</script>
|
//
// PetitionDetailContract.swift
// AI-Image-Demo
//
// Created by Aitor Zubizarreta on 2023-03-20.
//
import UIKit
import Combine
// MARK: - View
/// View Output (Presenter -> View)
protocol PresenterToViewPetitionDetailProtocol {
var presenter: ViewToPresenterPetitionDetailProtocol? { get set }
func onGetPetitionSuccess()
func onGetPetitionFailure(errorDescription: String)
}
// MARK: - Presenter
/// View Input (View -> Presenter)
protocol ViewToPresenterPetitionDetailProtocol {
var view: PresenterToViewPetitionDetailProtocol? { get set }
var interactor: PresenterToInteractorPetitionDetailProtocol? { get set }
var router: PresenterToRouterPetitionDetailProtocol? { get set }
var petitionId: String { get set }
init(petitionId: String)
func viewDidLoad()
func petitionImagesData() -> [Data]
func petitionErrorDescription() -> String
func petitionDescription() -> String
}
/// Interactor Input (Interactor -> Presenter)
protocol InteractorToPresenterPetitionDetailProtocol {
func retrievePetitionSuccess()
func retrievePetitionFailure(errorDescription: String)
}
// MARK: - Interactor
/// Interactor Output (Presenter -> Interactor)
protocol PresenterToInteractorPetitionDetailProtocol {
var presenter: InteractorToPresenterPetitionDetailProtocol? { get set }
var realmManager: InteractorToRealmManagerPetitionDetailProtocol? { get set }
func getPetition(with id: String)
func getPetitionImagesData() -> [Data]
func getPetitionErrorDescription() -> String
func getPetitionDescription() -> String
}
// MARK: - Router
/// Router Output (Presenter -> Router)
protocol PresenterToRouterPetitionDetailProtocol {
static func createModule(with petitionId: String) -> UIViewController
}
// MARK: - Realm Manager
/// RealmManager Output (Interactor -> Realm Manager)
protocol InteractorToRealmManagerPetitionDetailProtocol {
var petition: PassthroughSubject<Petition, Error> { get set }
func getPetition(with id: String)
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using java = biz.ritter.javapi;
namespace biz.ritter.javapi.lang.reflect{
/**
* This class represents a field. Information about the field can be accessed,
* and the field's value can be accessed dynamically.
*/
public sealed class Field : AccessibleObject, Member {
private String name;
/*
* This class must be implemented by the VM vendor.
*/
/**
* Prevent this class from being instantiated
*/
private Field(){
//do nothing
}
internal Field (String name){
this.name = name;
}
/*
* Returns the field's signature in non-printable form. This is called
* (only) from IO native code and needed for deriving the serialVersionUID
* of the class
*
* @return the field's signature.
*/
//native String getSignature();
/**
* Indicates whether or not this field is synthetic.
*
* @return {@code true} if this field is synthetic, {@code false} otherwise
*/
public bool isSynthetic() {
return false;
}
/**
* Returns the string representation of this field, including the field's
* generic type.
*
* @return the string representation of this field
* @since 1.5
*/
public String toGenericString() {
return null;
}
/**
* Indicates whether or not this field is an enumeration constant.
*
* @return {@code true} if this field is an enumeration constant, {@code
* false} otherwise
* @since 1.5
*/
public bool isEnumConstant() {
return false;
}
/**
* Returns the generic type of this field.
*
* @return the generic type
* @throws GenericSignatureFormatError
* if the generic field signature is invalid
* @throws TypeNotPresentException
* if the generic type points to a missing type
* @throws MalformedParameterizedTypeException
* if the generic type points to a type that cannot be
* instantiated for some reason
* @since 1.5
*/
public Type getGenericType() {
return null;
}
/**
* Indicates whether or not the specified {@code object} is equal to this
* field. To be equal, the specified object must be an instance of
* {@code Field} with the same declaring class, type and name as this field.
*
* @param object
* the object to compare
* @return {@code true} if the specified object is equal to this method,
* {@code false} otherwise
* @see #hashCode
*/
public override bool Equals(Object objectJ) {
return false;
}
/**
* Returns the value of the field in the specified object. This reproduces
* the effect of {@code object.fieldName}
* <p/>
* If the type of this field is a primitive type, the field value is
* automatically wrapped.
* <p/>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is null, a NullPointerException is thrown. If
* the object is not an instance of the declaring class of the method, an
* IllegalArgumentException is thrown.
* <p/>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value, possibly wrapped
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public Object get(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
return resultObj;
}
/**
* Returns the value of the field in the specified object as a {@code
* boolean}. This reproduces the effect of {@code object.fieldName}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public bool getBoolean(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is Boolean) return ((Boolean)resultObj);
if (resultObj is java.lang.Boolean)
return (((java.lang.Boolean)resultObj).booleanValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "boolean");
}
/**
* Returns the value of the field in the specified object as a {@code byte}.
* This reproduces the effect of {@code object.fieldName}
* <p/>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p/>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public byte getByte(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is Byte) return ((Byte)resultObj);
if (resultObj is java.lang.Byte)
return (((java.lang.Byte)resultObj).byteValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "byte");
}
/**
* Returns the value of the field in the specified object as a {@code char}.
* This reproduces the effect of {@code object.fieldName}
* <p/>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p/>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public char getChar(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is Char) return ((Char)resultObj);
if (resultObj is java.lang.Character)
return (((java.lang.Character)resultObj).charValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "char");
}
/**
* Returns the class that declares this field.
*
* @return the declaring class
*/
public java.lang.Class getDeclaringClass() {
return null;
}
/**
* Returns the value of the field in the specified object as a {@code
* double}. This reproduces the effect of {@code object.fieldName}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public double getDouble(Object objectJ){
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is Double) return ((Double)resultObj);
if (resultObj is java.lang.Double)
return (((java.lang.Double)resultObj).doubleValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "double");
}
/**
* Returns the value of the field in the specified object as a {@code float}.
* This reproduces the effect of {@code object.fieldName}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public float getFloat(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is Float) return ((Float)resultObj);
if (resultObj is java.lang.Float)
return (((java.lang.Float)resultObj).floatValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "float");
}
/**
* Returns the value of the field in the specified object as an {@code int}.
* This reproduces the effect of {@code object.fieldName}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public int getInt(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is int) return ((int)resultObj);
if (resultObj is java.lang.Integer)
return (((java.lang.Character)resultObj).charValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "int");
}
/**
* Returns the value of the field in the specified object as a {@code long}.
* This reproduces the effect of {@code object.fieldName}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public long getLong(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is long) return ((long)resultObj);
if (resultObj is java.lang.Long)
return (((java.lang.Long)resultObj).longValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "long");
}
/**
* Returns the modifiers for this field. The {@link Modifier} class should
* be used to decode the result.
*
* @return the modifiers for this field
* @see Modifier
*/
public int getModifiers(){
throw new UnsupportedOperationException ("Not yet implemented");
}
/**
* Returns the name of this field.
*
* @return the name of this field
*/
public String getName() {
return this.name;
}
/**
* Returns the value of the field in the specified object as a {@code short}
* . This reproduces the effect of {@code object.fieldName}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
*
* @param object
* the object to access
* @return the field value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public short getShort(Object objectJ) {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
Object resultObj = f.GetValue (objectJ);
if (resultObj is short) return ((short)resultObj);
if (resultObj is java.lang.Short)
return (((java.lang.Short)resultObj).shortValue());
throw new IllegalArgumentException ("Attempt to get int field " + objectJ.getClass().getName()+"."+this.getName() + " with illegal data type conversion to " + "short");
}
/**
* Return the {@link Class} associated with the type of this field.
*
* @return the type of this field
*/
public java.lang.Class getType() {
return null;
}
/**
* Returns an integer hash code for this field. Objects which are equal
* return the same value for this method.
* <p>
* The hash code for a Field is the exclusive-or combination of the hash
* code of the field's name and the hash code of the name of its declaring
* class.
*
* @return the hash code for this field
* @see #equals
*/
public override int GetHashCode() {
return 0;
}
/**
* Sets the value of the field in the specified object to the value. This
* reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the field type is a primitive type, the value is automatically
* unwrapped. If the unwrap fails, an IllegalArgumentException is thrown. If
* the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void set(Object objectJ, Object value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Sets the value of the field in the specified object to the {@code
* boolean} value. This reproduces the effect of {@code object.fieldName =
* value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setBoolean(Object objectJ, bool value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Sets the value of the field in the specified object to the {@code byte}
* value. This reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setByte(Object objectJ, byte value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Sets the value of the field in the specified object to the {@code char}
* value. This reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setChar(Object objectJ, char value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Sets the value of the field in the specified object to the {@code double}
* value. This reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setDouble(Object objectJ, double value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Sets the value of the field in the specified object to the {@code float}
* value. This reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setFloat(Object objectJ, float value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Set the value of the field in the specified object to the {@code int}
* value. This reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setInt(Object objectJ, int value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Sets the value of the field in the specified object to the {@code long}
* value. This reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setLong(Object objectJ, long value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Sets the value of the field in the specified object to the {@code short}
* value. This reproduces the effect of {@code object.fieldName = value}
* <p>
* If this field is static, the object argument is ignored.
* Otherwise, if the object is {@code null}, a NullPointerException is
* thrown. If the object is not an instance of the declaring class of the
* method, an IllegalArgumentException is thrown.
* <p>
* If this Field object is enforcing access control (see AccessibleObject)
* and this field is not accessible from the current context, an
* IllegalAccessException is thrown.
* <p>
* If the value cannot be converted to the field type via a widening
* conversion, an IllegalArgumentException is thrown.
*
* @param object
* the object to access
* @param value
* the new value
* @throws NullPointerException
* if the object is {@code null} and the field is non-static
* @throws IllegalArgumentException
* if the object is not compatible with the declaring class
* @throws IllegalAccessException
* if this field is not accessible
*/
public void setShort(Object objectJ, short value){
try {
Type type = objectJ.GetType ();
System.Reflection.FieldInfo f = type.GetField (this.name);
f.SetValue(objectJ,value);
}
catch (ArgumentException ae) {
throw new IllegalArgumentException(ae.getMessage());
}
}
/**
* Returns a string containing a concise, human-readable description of this
* field.
* <p>
* The format of the string is:
* <ol>
* <li>modifiers (if any)
* <li>type
* <li>declaring class name
* <li>'.'
* <li>field name
* </ol>
* <p>
* For example: {@code public static java.io.InputStream
* java.lang.System.in}
*
* @return a printable representation for this field
*/
public override String ToString() {
return null;
}
}
}
|
<?php
/**
* Plugin recommandations.
*
* @package Positor
* @subpackage TGM-Plugin-Activation
* @author Thomas Griffin, Gary Jones, Juliette Reinders Folmer
* @license http://opensource.org/licenses/gpl-2.0.php GPL v2 or later
* @link https://github.com/TGMPA/TGM-Plugin-Activation
* @see http://tgmpluginactivation.com/configuration/ for detailed documentation.
*/
/**
* Include the TGM_Plugin_Activation class.
*
* Depending on your implementation, you may want to change the include call:
*
* Parent Theme:
* require_once get_template_directory() . '/path/to/class-tgm-plugin-activation.php';
*
* Child Theme:
* require_once get_stylesheet_directory() . '/path/to/class-tgm-plugin-activation.php';
*
* Plugin:
* require_once dirname( __FILE__ ) . '/path/to/class-tgm-plugin-activation.php';
*/
require_once get_template_directory() . '/inc/tgm-plugin-activation.php';
add_action( 'tgmpa_register', 'positor_register_required_plugins' );
/**
* Register the required plugins for this theme.
*/
function positor_register_required_plugins() {
/*
* Array of plugin arrays. Required keys are name and slug.
* If the source is NOT from the .org repo, then source is also required.
*/
$plugins = array(
// This is an example of how to include a plugin from the WordPress Plugin Repository.
array(
'name' => 'Meta Box',
'slug' => 'meta-box',
'required' => false,
),
);
/*
* Array of configuration settings. Amend each line as needed.
*
* TGMPA will start providing localized text strings soon. If you already have translations of our standard
* strings available, please help us make TGMPA even better by giving us access to these translations or by
* sending in a pull-request with .po file(s) with the translations.
*
* Only uncomment the strings in the config array if you want to customize the strings.
*/
$config = array(
'id' => 'positor', // Unique ID for hashing notices for multiple instances of TGMPA.
'default_path' => '', // Default absolute path to bundled plugins.
'menu' => 'tgmpa-install-plugins', // Menu slug.
'has_notices' => true, // Show admin notices or not.
'dismissable' => true, // If false, a user cannot dismiss the nag message.
'dismiss_msg' => '', // If 'dismissable' is false, this message will be output at top of nag.
'is_automatic' => true, // Automatically activate plugins after installation or not.
'message' => '', // Message to output right before the plugins table.
'strings' => array(
'page_title' => __( 'Install Required Plugins', 'positor' ),
'menu_title' => __( 'Install Plugins', 'positor' ),
/* translators: %s: plugin name. */
'installing' => __( 'Installing Plugin: %s', 'positor' ),
/* translators: %s: plugin name. */
'updating' => __( 'Updating Plugin: %s', 'positor' ),
'oops' => __( 'Something went wrong with the plugin API.', 'positor' ),
/*
'notice_can_install_required' => _n_noop(
/* translators: 1: plugin name(s). * /
'This theme requires the following plugin: %1$s.',
'This theme requires the following plugins: %1$s.',
'positor'
),
'notice_can_install_recommended' => _n_noop(
/* translators: 1: plugin name(s). * /
'This theme recommends the following plugin: %1$s.',
'This theme recommends the following plugins: %1$s.',
'positor'
),
'notice_ask_to_update' => _n_noop(
/* translators: 1: plugin name(s). * /
'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.',
'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.',
'positor'
),
'notice_ask_to_update_maybe' => _n_noop(
/* translators: 1: plugin name(s). * /
'There is an update available for: %1$s.',
'There are updates available for the following plugins: %1$s.',
'positor'
),
'notice_can_activate_required' => _n_noop(
/* translators: 1: plugin name(s). * /
'The following required plugin is currently inactive: %1$s.',
'The following required plugins are currently inactive: %1$s.',
'positor'
),
'notice_can_activate_recommended' => _n_noop(
/* translators: 1: plugin name(s). * /
'The following recommended plugin is currently inactive: %1$s.',
'The following recommended plugins are currently inactive: %1$s.',
'positor'
),
'install_link' => _n_noop(
'Begin installing plugin',
'Begin installing plugins',
'positor'
),
'update_link' => _n_noop(
'Begin updating plugin',
'Begin updating plugins',
'positor'
),
'activate_link' => _n_noop(
'Begin activating plugin',
'Begin activating plugins',
'positor'
),
'return' => __( 'Return to Required Plugins Installer', 'positor' ),
'plugin_activated' => __( 'Plugin activated successfully.', 'positor' ),
'activated_successfully' => __( 'The following plugin was activated successfully:', 'positor' ),
/* translators: 1: plugin name. * /
'plugin_already_active' => __( 'No action taken. Plugin %1$s was already active.', 'positor' ),
/* translators: 1: plugin name. * /
'plugin_needs_higher_version' => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'positor' ),
/* translators: 1: dashboard link. * /
'complete' => __( 'All plugins installed and activated successfully. %1$s', 'positor' ),
'dismiss' => __( 'Dismiss this notice', 'positor' ),
'notice_cannot_install_activate' => __( 'There are one or more required or recommended plugins to install, update or activate.', 'positor' ),
'contact_admin' => __( 'Please contact the administrator of this site for help.', 'positor' ),
'nag_type' => '', // Determines admin notice type - can only be one of the typical WP notice classes, such as 'updated', 'update-nag', 'notice-warning', 'notice-info' or 'error'. Some of which may not work as expected in older WP versions.
*/
),
);
tgmpa( $plugins, $config );
}
|
<template lang="pug">
main.container(role="main" v-if="dataLoaded")
div#contact.container.contact-form
h1(id='content') Contact Me
if error
p #{ error }
span(v-html="formHTML")
</template>
<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import ContactService from './../../services/ContactService';
import animateLogo from './../../ts/animateLogo';
@Component
export default class Contact extends Vue {
data = [];
dataLoaded = false;
error = '';
formHTML = '';
async created(): Promise<void> {
try {
this.data = await ContactService.getContact();
this.$store.commit('setRecords', this.data);
// @ts-ignore
this.formHTML = this.getForm(this.data.data);
this.dataLoaded = true;
animateLogo('logo-image', '');
} catch (err) {
this.error = err.message;
}
}
mounted(): void {
animateLogo('logo-image', 'spin');
this.updateMeta();
}
updateMeta(): void {
const titleEl = document.querySelector('head title');
if (titleEl) {
titleEl.textContent = 'Contact Me | Chris Corchado';
}
const descEl = document.querySelector("[name='description']");
if (descEl) {
descEl.remove();
}
const desc = document.createElement('meta');
desc.setAttribute('name', 'description');
desc.setAttribute('content', 'Contact me if you have any question or comments');
document.getElementsByTagName('head')[0].appendChild(desc);
}
updated(): void {
const emailField = document.getElementById('edit-mail');
if (emailField) {
emailField.focus();
}
}
getForm(data: unknown): string {
// @ts-ignore
let form = data.substr(
// @ts-ignore
data.indexOf('<form class='),
// @ts-ignore
data.indexOf('</form>')
);
form = form.substr(0, form.indexOf('</form>') + 8);
form = form.replace('Your email address', 'Email');
// get the contact form JavaScript
const scriptString =
'<script type="application/json" data-drupal-selector="drupal-settings-json">';
// @ts-ignore
let script = data.substr(
// @ts-ignore
data.indexOf(scriptString),
// @ts-ignore
data.indexOf('><\/script>')
);
script = script.substr(0, script.indexOf('<\/script>') + 9);
return `${form} ${script}`;
}
}
</script>
<style lang="scss">
@import './../../scss/pages/contact.scss';
</style>
|
import { createSlice } from "@reduxjs/toolkit";
interface IFilters {
sort: string;
numberGames: number;
}
const filterSlice = createSlice({
name: "filters",
initialState: {
sort: "Saldo de gols (melhor)",
numberGames: 5,
},
reducers: {
setSort: (state: IFilters, action) => {
state.sort = action.payload;
},
setGamesNumber: (state: IFilters, action) => {
state.numberGames = action.payload;
},
},
});
export const { setSort, setGamesNumber } = filterSlice.actions;
export const filtersReducer = filterSlice.reducer;
|
//`timescale 1ns/10ps
module sram #(parameter ADDR_WIDTH = 32 ,
parameter DATA_WIDTH = 16 ,
parameter MEM_INIT_FILE = "" )
(
//---------------------------------------------------------------
//
input wire [ADDR_WIDTH-1:0 ] write_address ,
input wire [DATA_WIDTH-1:0 ] write_data ,
input wire [ADDR_WIDTH-1:0 ] read_address ,
output reg [DATA_WIDTH-1:0 ] read_data ,
input wire write_enable ,
input clk
);
//--------------------------------------------------------
// Associative memory
bit [DATA_WIDTH-1 :0 ] mem [longint] ;
//--------------------------------------------------------
// RAW and X condition
reg [ADDR_WIDTH-1:0 ] last_write_addr;
reg last_write_en;
integer block = 0;
//--------------------------------------------------------
// Read
always @(posedge clk)
begin
read_data = 'hx;
if((write_enable === 1'bx) | (write_enable === 1'bz))
read_data = 'hx;
else if ( ^read_address === 1'bx || ( (last_write_addr) == (read_address) && last_write_en == 1'b1) )
read_data = 'hx;
else if(mem.exists(read_address))
begin
read_data = mem [read_address];
end
else
read_data = 'hx;
end
//--------------------------------------------------------
// Write
always @(posedge clk)
begin
last_write_addr = write_address;
last_write_en = write_enable;
if (write_enable)
begin
mem [write_address] = write_data;
end else if((write_enable === 1'bx) | (write_enable === 1'bz))
mem.delete();
end
//--------------------------------------------------------
//--------------------------------------------------------
//Loading inputs and weights to sram
string entry ;
int fileDesc ;
bit [ADDR_WIDTH-1 :0 ] memory_address ;
bit [DATA_WIDTH-1 :0 ] memory_data ;
int temp;
function void loadMem(input string memFile);
mem.delete();
$display("INFO: Reading memory file: %s",memFile);
if (memFile != "")
$readmemh(memFile,mem);
block = 1;
endfunction
function void clearMem();
mem.delete();
endfunction
function void loadInitFile(input string memFile);
if (memFile != "")
begin
fileDesc = $fopen (memFile, "r");
if (fileDesc == 0)
begin
$display("ERROR::readmem file error : %s ", memFile);
$finish;
end
//$display("INFO::%m::readmem : %s ", memFile);
while (!$feof(fileDesc))
begin
void'($fgets(entry, fileDesc));
void'($sscanf(entry, "@%x %h", memory_address, memory_data));
mem[memory_address] = memory_data ;
//$display("INFO::%m::readmem file contents : %s : Addr:%h, Data:%h, MEM:%h", memFile, memory_address, memory_data,mem[memory_address]);
end
$fclose(fileDesc);
end
endfunction
endmodule
|
<?php
namespace App\Exports;
use App\Http\Resources\LaboursResource;
use App\Models\Company\Labour;
use App\Models\Company\Unit;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
class MyDataExport implements FromCollection, WithHeadings, ShouldAutoSize
{
public function collection()
{
$labours = Labour::with('units')->get();
$collection = LaboursResource::collection($labours);
return collect($collection);
}
public function headings(): array
{
return [
'#',
'Name',
'Category',
'Unit',
];
}
public function styles(Worksheet $sheet)
{
return [
1 => ['font' => ['bold' => true], 'freeze' => true],
];
}
}
|
# Be pessimistic or optimistic
**Pessimistic lock**: the idea is that before I want to touch this system resource (not have to be database records), it could be a file or network port, ***I want to assume that everyone else who uses this resource will affect my work***. so I want to lock them to prevent others from making changes.
**Optimistic lock** is another way wrong, which means ***I am okay to share the resource with other processes who need it***, as long as not affecting my job, ***when conflict happens we can resolve it on the spot***.
# Shared or Exclusive
I was also confused by the word “**shared lock**”, if it is shared, why lock? so just remember that `Shared` is for reading => I allow another process to read this resource.
**Exclusive lock** is easy to understand: I am using it, locking it, and no one should be able to access (read or write) it.
# Range Locks
Range locks are best described by illustrating all the possible lock levels.
1. ***Serialized Database Access*** — *Making the database run queries one by one — terrible concurrency, the highest level of consistency, though.*
2. ***Table Lock*** — *lock the table for your transaction with slightly better concurrency, but concurrent table writes are still slowed.*
3. ***Row Lock*** — *Locks the row you are working on even better than table locks, but if multiple transactions need this row, they will need to wait.*
***Range locks*** are between the last two levels of locks; *they lock the range of values captured by the transaction and don't allow inserts or updates within the range captured by the transaction.*
# Isolation Levels
The SQL standard defines 4 standard isolation levels these can and should be configured globally (insidious things can happen if we can't reliably reason about isolation levels).
![[Pasted image 20230605134755.png]]
#### READ UNCOMMITTED
The _READ UNCOMMITTED_ isolation level doesn't maintain any transaction locking and can see uncommitted data as it happens, leading to dirty reads. The stuff of nightmares... in some systems.
##### Dirty reads
*A dirty read occurs when you perform a read, and another transaction updates the same row but doesn't commit the work, you perform another read, and you can access the uncommitted (dirty) value, which isn't a durable state change and is inconsistent with the state of the database.*
![[Pasted image 20230605134357.png]]
#### READ COMMITTED
Each read creates its own consistent (committed) snapshot of time. ==*As a result, this isolation mode is susceptible to phantom reads if we execute multiple reads within the same transaction.*==
1. Read only committed data
2. Lock VISIBLE recored when update:
1. the record exist in the DB
2. the record matched the “where” condition
Example:
We have rows with ids 1, 2, 4 in the `table`
```SQL
select * from the table where id>2
```
visible record is 4 (3 is not included because it doesn't exist in the database) => susceptible for *Phantom reads* because it doesn’t lock the “Gaps” between records (including the last record to infinity)
##### **Phantom reads**
*Phantom reads are another committed read phenomena, which occurs when you are most commonly dealing with aggregates. For example, you ask for the number of customers in a specific transaction. Between the two subsequent reads, another customer signs up or deletes their account (committed), which results in you getting two different values if your database doesn't support range locks for these transactions.*
![[Pasted image 20230605134544.png]]
#### REPEATABLE READ
This isolation level ensures consistent reads within the transaction established by the first read.
1. Read only committed data
2. Lock “Whatever records matched where condition” which could affect this transaction
It does have the minor data inconsistency while its locked to specific view of the database; ***keeping transactions short-lived as possible here is beneficial.***
##### Non-repeatable reads
*Non-repeatable reads occur if you cannot get a consistent view of the data between two subsequent reads during your transaction. In specific modes, concurrent database modification is possible, and there can be scenarios where the value you just read can be modified, resulting in a non-repeatable read.*
![[Pasted image 20230605134218.png]]
#### SERIALIZABLE
This operating mode can be the most restrictive and consistent since it allows only one query to be run at a time.
*==All types of reading phenomena are no longer possible since the database runs the queries one by one, transitioning from one stable state to the next.==* There is more nuance here, but more or less accurate.
_It is essential to note in this mode to have some retry mechanism since queries can fail due to concurrency issues._
Newer distributed databases take advantage of this isolation level for consistency guarantees. [CockroachDB](https://www.cockroachlabs.com/?ref=architecturenotes.co) is an example of such a database. Worth a look.
|
import type { Validator, BasicType } from '../../_utils';
import type { PropType, ExtractPropTypes } from 'vue';
import type { VmSize, VmIcon, HandleChange } from '../../_interface';
export declare const Props: {
/** 绑定值 */
readonly modelValue: {
readonly required: true;
readonly type: BooleanConstructor;
readonly default: () => boolean;
readonly validator?: Validator | undefined;
};
/**
* 尺寸
*
* @values large middle small mini
* @default null
*/
readonly size: BasicType<PropType<VmSize>, VmSize | null>;
/** 是否禁用 */
readonly disabled: BasicType<BooleanConstructor, boolean>;
/** 自定义 icon */
readonly icon: BasicType<PropType<VmIcon>, null>;
/** 关闭时的颜色 */
readonly closeColor: BasicType<PropType<string>, string | null>;
/** 打开时的颜色 */
readonly activeColor: BasicType<PropType<string>, string | null>;
/** 自定义打开时的文案 */
readonly activeText: BasicType<PropType<string>, string | null>;
/** 自定义关闭时的文案 */
readonly closeText: BasicType<PropType<string>, string | null>;
/** 是否为方形的 */
readonly square: BasicType<BooleanConstructor, boolean>;
/** 自定义 icon size */
readonly iconSize: BasicType<PropType<string | number>, string | number | null>;
/** 绑定值发生改变时触发的回调 */
readonly onChange: BasicType<PropType<HandleChange>, null>;
};
/** switch 组件 props 类型 */
export type SwitchProps = ExtractPropTypes<typeof Props>;
|
import { useEffect, useCallback } from 'react';
import { signIn as signInApi, signUp as signUpApi } from 'api';
import AsyncStorage from '@react-native-community/async-storage';
import { User, SignInPayload, SignUpPayload } from 'types';
import { useAuthDispatch, useAuthState } from './useAuthContext';
const storageUser = 'user';
export const useInitialAuth = () => {
const dispatch = useAuthDispatch();
const { isLoggedIn } = useAuthState();
const getUserInfo = useCallback(async () => {
try {
const storageInfo = await AsyncStorage.getItem(storageUser);
if (!storageInfo) return;
const userInfo: User = JSON.parse(storageInfo);
if (userInfo && userInfo.token) {
dispatch({ type: 'signIn', payload: userInfo });
}
} catch (e) {
throw new Error(e);
}
}, []);
useEffect(() => {
getUserInfo();
}, [getUserInfo]);
return isLoggedIn;
};
export const useAuth = () => {
const dispatch = useAuthDispatch();
const setUserInfo = useCallback(async userInfo => {
try {
await AsyncStorage.setItem(storageUser, JSON.stringify(userInfo));
} catch (e) {
throw new Error(e);
}
}, []);
const removeUserInfo = useCallback(async () => {
try {
await AsyncStorage.removeItem(storageUser);
} catch (e) {
throw new Error(e);
}
}, []);
const signIn = async (val: SignInPayload) => {
try {
const userInfo = await signInApi(dispatch, val);
if (userInfo) {
setUserInfo(userInfo);
}
} catch (e) {
throw new Error(e);
}
};
const signUp = async (val: SignUpPayload) => {
try {
const userInfo = await signUpApi(dispatch, val);
if (userInfo) {
setUserInfo(userInfo);
}
} catch (e) {
throw new Error(e);
}
};
const signOut = () => {
removeUserInfo();
dispatch({ type: 'signOut' });
};
return {
signIn,
signUp,
signOut,
};
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forms</title>
</head>
<body>
<h2>This is html forms tutorial</h2>
<form action="backend.php">
<label for="name"> Name</label>
<div>
<input type="text" name="myName" id="name">
<!-- The input statement is inline
statement of div -->
<!-- div is a block element it takes the block
(the next element has to go in next line) -->
</div>
<br><!-- for space in between the lines -->
<hr>
<div>
Role: <input type="text" name="myrole">
</div>
<br>
<div>
Email: <input type="email" name="myEmail">
</div>
<br>
<div>
Date: <input type="date" name="Mydate">
</div>
<br>
<div>
Bonus: <input type="number" name="MyBonus">
</div>
<br>
<div>
<label for="Myeligibility"> Are you eligible:</label>
<input type="checkbox" name="" id="Myeligibility"selected >
</div>
<br>
<div>
Gender: Male <input type="radio" name="myGender">
Female <input type="radio" name="myGender">
other <input type="radio" name="myGender">
<!-- We can take only one option because we
called it by the same "name(myGender)" -->
</div>
<br>
<div>
Write about yourself: <br> <textarea name="myText" cols="30" rows="10"></textarea>
</div>
<!-- alt + arrow keys to shift block of lines -->
<br>
<div>
<label for="car">Car</label>
<select name="myCar" id="car">
<option value="ind" >Indica</option>
<option value="Kwd" selected>Kwid</option>
</select>
</div>
<br>
<div>
<input type="submit" Value="Submit Now">
<input type="Reset" Value="Reset Now">
</div>
</form>
</body>
</html>
|
import React, { useState, useEffect } from 'react'
import { Button, Table, Space, Tag, Modal, Form, Input, message } from 'antd'
import './admin.less'
import {
reqGetAllLabels,
reqGetIssues,
reqGetRepoInfo,
reqUpdateIssue
} from '../../api'
import config from '../../config/config'
const { ColumnGroup, Column } = Table
const { CheckableTag } = Tag
const layout = {
labelCol: { span: 5 },
wrapperCol: { span: 16 }
}
export default function AdminPost() {
const [pagination, setPagination] = useState({
// 当前页数
current: 1,
pageSize: config.post.page_size,
total: 0,
onChange: function (value) {
this.current = value
// 页数发生变化即更新数据
getIssueList(this.current)
}
})
// 修改对话框
const [isModalVisible, setIsModalVisible] = useState(false)
// 表格数据
const [data, setData] = useState([])
// 当前issue的nunber
const [number, setNumber] = useState(0)
const [form] = Form.useForm()
// 标签
const [tags, setTags] = useState([])
// 选择的标签
const [selectedTags, setSelectedTags] = useState([])
// 获取仓库基本信息
const getRepoInfo = async () => {
const result = await reqGetRepoInfo()
const total = result.open_issues_count
const obj = { ...pagination }
obj.total = total
setPagination(obj)
}
// 获取issue列表
const getIssueList = async (page) => {
const result = await reqGetIssues(page)
if (result.length > 0) {
setNumber(result[0].number)
}
result.forEach((item) => {
item.key = item.id
})
setData(result)
}
// 获取所有labels
const getLabels = async () => {
const labels = await reqGetAllLabels()
if (labels) {
setTags(labels)
}
}
const showModal = (text, record) => {
setNumber(text.number)
form.setFieldsValue({
title: text.title,
body: text.body
})
const newLabels = []
text.labels.forEach((item) => {
newLabels.push(item.name)
})
setSelectedTags(newLabels)
setIsModalVisible(true)
}
const handleOk = () => {
// setIsModalVisible(false)
form.validateFields().then(async (result) => {
console.log(selectedTags)
const updateObj = await reqUpdateIssue(
number,
result.title,
result.body,
selectedTags
)
if (updateObj.title === result.title) {
message.success('更新成功')
setIsModalVisible(false)
} else {
message.error('更新失败')
}
})
}
// 选择标签事件
const handleSelected = (item, check) => {
// const tags = [...selectedTags]
const nextSelectedTags = check
? [...selectedTags, item.name]
: selectedTags.filter((t) => t !== item.name)
setSelectedTags(nextSelectedTags)
console.log(selectedTags)
}
const handleCancel = () => {
form.resetFields()
setIsModalVisible(false)
}
const onFinish = () => {
console.log(1)
}
useEffect(() => {
getRepoInfo()
getIssueList(1)
getLabels()
}, [])
return (
<div className='admin-container'>
<Table dataSource={data} pagination={pagination}>
<Column title='标题' dataIndex='title' key='id' />
<Column title='时间' dataIndex='updated_at' key='id' />
<Column
title='Action'
key='action'
render={(item) => (
<Space size='middle'>
<a
onClick={() => {
showModal(item)
}}
>
编辑
</a>
<a>删除</a>
</Space>
)}
/>
</Table>
<Modal
title='Basic Modal'
visible={isModalVisible}
onOk={handleOk}
onCancel={handleCancel}
>
<Form {...layout} form={form} name='control-hooks' onFinish={onFinish}>
<Form.Item name='title' label='标题' rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name='body' label='内容' rules={[{ required: true }]}>
<Input.TextArea />
</Form.Item>
<Form.Item label='标签'>
{tags.map((item) => {
return (
<CheckableTag
key={item.id}
checked={selectedTags.indexOf(item.name) > -1}
onChange={(checked) => handleSelected(item, checked)}
>
{item.name}
</CheckableTag>
)
})}
</Form.Item>
</Form>
</Modal>
</div>
)
}
|
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";
import { ChartData } from "react-native-chart-kit/dist/HelperTypes";
import DigiLineChart from "@Components/Charts/LineChart";
import { formatTimeAgo } from "@DigiUtils/helperFunctions";
import OutfitBox from "@Components/Box/OutfitBox";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { RootStackParamList } from "@Routes/Navigator.interface";
import { getDatabase } from "@Database/database";
import { getOutfits } from "@Database/outfits";
import { useGet } from "@Hooks/useGet";
import { ScrollContainer } from "@DigiUtils/ScrollContainer";
import { Ionicons } from "@expo/vector-icons";
import { deleteItem, getWardrobeItemById, setItemAsFavorite, updateItem, updateWearDetails } from "@Database/item";
import DateTimePickerInput from "@Components/Inputs/DateTimePickerInput";
import { useContext, useLayoutEffect, useRef, useState } from "react";
import EditableDetail from "@Components/Detail/EditableDetail";
import Input from "@Components/Inputs/Input";
import ImageContainer from "@Components/Box/ImageContainer";
import { Item } from "@Classes/Item";
import DigiButton from "@Components/Button/DigiButton";
import { deleteAlert } from "@DigiUtils/alertHelper";
import SnackbarContext from "@Context/SnackbarContext";
import DetailImage from "@Components/Image/DetailImage";
import { StatisticData, useGetItemStatistic } from "@Hooks/useGetItemStatistic";
import Skeleton from "@Components/Skeleton/Skeleton";
type ItemDetailsProps = NativeStackScreenProps<RootStackParamList, "ItemDetails">;
export default function ItemDetails({ route, navigation }: ItemDetailsProps) {
const routeItem = route.params.item;
const db = getDatabase();
const snack = useContext(SnackbarContext);
const { data: savedOutfits, isLoading, error, refetch } = useGet(getOutfits(db));
const { data, isLoading: loadingItem, error: itemError, refetch: refetchItem } = useGet(getWardrobeItemById(db, routeItem.uuid));
const { data: chartData } = useGetItemStatistic(routeItem.uuid);
const item = useRef<Item>(data ? data : routeItem).current;
const [editMode, setEditMode] = useState<boolean>(false);
const [selectedChartData, setSelectedChartData] = useState<keyof StatisticData>("month");
useLayoutEffect(() => {
navigation.setOptions({
headerRight: ({ tintColor }: any) => (
<TouchableOpacity onPress={() => handleEdit(true)}>
<Ionicons name="ios-create-outline" size={24} color={tintColor} />
</TouchableOpacity>
),
});
}, [navigation]);
const handleEdit = (edit: boolean) => {
if (edit) {
setEditMode(true);
navigation.setOptions({
headerRight: ({ tintColor }: any) => (
<TouchableOpacity onPress={() => handleSaveUpdatedItem(item)}>
<Ionicons name="ios-checkmark-circle-outline" size={32} color={tintColor} />
</TouchableOpacity>
),
});
} else {
setEditMode(false);
navigation.setOptions({
headerRight: ({ tintColor }: any) => (
<TouchableOpacity onPress={() => handleEdit(true)}>
<Ionicons name="ios-create-outline" size={24} color={tintColor} />
</TouchableOpacity>
),
});
}
};
const handleSaveUpdatedItem = (currItem: Item) => {
handleEdit(false);
updateItem(db, currItem);
};
const handleFavoritePress = async () => {
item.toggleFavorite();
await setItemAsFavorite(db, item);
refetch();
};
const handleUpdateWears = async (date?: Date) => {
if (!date) return;
item.updateWearDetails(date);
await updateWearDetails(db, item, date);
refetch();
};
const handleDeleteItem = async () => {
if (!snack) return;
deleteItem(db, item.uuid)
.then(() => {
snack.setMessage(`${item.name} was deleted.`);
snack.setIsOpen(true);
})
.catch((e) => console.log(e))
.finally(() => navigation.goBack());
};
const renderSavedOutfits = () => {
const filteredOutfits = savedOutfits
?.filter((outfit) => outfit.getAllItems().some((i) => item.uuid === i.uuid))
.map((o) => <OutfitBox key={o.uuid} label={o.name} outfitImage={o.imageURL} itemImages={o.getItemImagePreviews()} outfit={o} />);
return (
<View style={{ marginHorizontal: 8 }}>
<Text style={{ fontSize: 24, marginLeft: 16 }}>Saved Outfits ({filteredOutfits?.length ?? 0})</Text>
<View style={{ alignItems: "center", marginTop: 16 }}>
{filteredOutfits && filteredOutfits.length ? (
<View style={{ alignItems: "center", gap: 8 }}>{filteredOutfits}</View>
) : (
<Text>No Outfits.</Text>
)}
</View>
</View>
);
};
if (error || itemError)
return (
<View>
<Text>Error</Text>
</View>
);
return (
<ScrollContainer isLoading={isLoading} refetch={refetchItem}>
{editMode ? (
<ImageContainer defaultImage={item.getImage()} setImageCallback={(uri) => item.setImage(uri)} />
) : (
<DetailImage image={item.getImage()} />
)}
<View style={styles.content}>
<View style={styles.description}>
<View style={styles.descriptionInner}>
{editMode ? (
<Input
defaultValue={item.name}
onChange={(value) => {
if (value) item.name = value;
}}
/>
) : (
<Text style={{ fontSize: 24 }}>{item.name}</Text>
)}
<TouchableOpacity onPress={handleFavoritePress} style={{ paddingLeft: 16 }}>
<Ionicons name={item.isFavorite() ? "heart" : "heart-outline"} size={28} color={item.isFavorite() ? "red" : "black"} />
</TouchableOpacity>
</View>
<View style={styles.descriptionInner}>
<Text>{item.wears} times worn.</Text>
<Text>Last worn: {formatTimeAgo(item.lastWorn)}</Text>
</View>
</View>
<View style={styles.description}>
<DateTimePickerInput text="I wore this" onChange={handleUpdateWears} />
</View>
<View style={styles.details}>
{item.getConstructorKeys().map((i) => (
<EditableDetail
edit={i.editable ? editMode : false}
key={i.key}
label={i.label}
detail={{
...i.detailProps,
isColor: i.inputType === "multi-select-color",
value: i.isDate
? typeof i.value === "string"
? new Date(i.value).toLocaleDateString("de", {
day: "numeric",
month: "long",
year: "numeric",
})
: i.value
: i.value,
}}
detailInput={{
inputProps: { onChange: i.setter, textInputProps: { keyboardType: i.keyboardType } },
type: i.inputType,
defaultValue: i.value,
}}
/>
))}
</View>
<View
style={{
width: "100%",
}}
>
<Text style={{ fontSize: 24, marginLeft: 16 }}>Statistic</Text>
<View style={{ flexDirection: "row", width: "100%", gap: 8, paddingLeft: 16, marginTop: 16 }}>
<DigiButton
title="30 Days"
variant="outline"
selected={selectedChartData === "month"}
onPress={() => setSelectedChartData("month")}
/>
<DigiButton
title="1 Year"
variant="outline"
selected={selectedChartData === "year"}
onPress={() => setSelectedChartData("year")}
/>
<DigiButton
title="Overall"
variant="outline"
selected={selectedChartData === "overall"}
onPress={() => setSelectedChartData("overall")}
/>
</View>
{chartData ? <DigiLineChart chartData={chartData[selectedChartData]} /> : <Skeleton />}
</View>
{renderSavedOutfits()}
<View style={{ flex: 1, height: 80, width: "100%", marginTop: 32 }}>
<DigiButton title={`Delete ${item.name}`} variant="text" onPress={() => deleteAlert("Item", item.name, handleDeleteItem)} />
</View>
</View>
</ScrollContainer>
);
}
const styles = StyleSheet.create({
content: {
backgroundColor: "white",
marginTop: -32,
marginBottom: 32,
height: "100%",
paddingTop: 8,
gap: 16,
elevation: 3,
borderTopLeftRadius: 32,
borderTopRightRadius: 32,
},
description: {
paddingHorizontal: 24,
marginVertical: 16,
},
descriptionInner: {
flexDirection: "row",
justifyContent: "space-between",
paddingTop: 8,
},
details: {
flexDirection: "column",
padding: 8,
},
});
|
// import { useState } from "react";
import { useContext } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import styles from "./Home.module.scss";
import QuizContext from "@/context/quizContext";
const Home = () => {
const levels = ["easy", "medium", "hard"];
const { limit, setLimit, difficulty, setDifficulty, startQuiz } =
useContext(QuizContext);
const handleLimitChange = (e) => {
setLimit(e.target.value);
};
const handledifficulty = (level) => () => {
setDifficulty(level);
};
return (
<div className={styles.main}>
<h1>Welcome to the Quiz App</h1>
<label htmlFor="difficulty">
Please Select the level (default is easy) :
</label>
<div className={styles.difficulty} id="difficulty">
{levels.map((level) => (
<Button
key={level}
variant={difficulty === level ? "primary" : "secondary"}
onClick={handledifficulty(level)}
>
{level}
</Button>
))}
</div>
<div className={styles.limit}>
<label htmlFor="limit">Total no of questions?</label>
<Input
type="number"
id="limit"
value={limit}
onChange={handleLimitChange}
/>
</div>
<Button variant="secondary" onClick={startQuiz}>
Start Quiz
</Button>
</div>
);
};
export default Home;
|
!-----------------------------------------------------------------------------!
! CP2K: A general program to perform molecular dynamics simulations !
! Copyright (C) 2000 - 2011 CP2K developers group !
!-----------------------------------------------------------------------------!
! *****************************************************************************
!> \par History
!> Subroutine input_torsions changed (DG) 05-Dec-2000
!> Output formats changed (DG) 05-Dec-2000
!> JGH (26-01-2002) : force field parameters stored in tables, not in
!> matrices. Input changed to have parameters labeled by the position
!> and not atom pairs (triples etc)
!> Teo (11.2005) : Moved all information on force field pair_potential to
!> a much lighter memory structure
!> Teo 09.2006 : Splitted all routines force_field I/O in a separate file
!> 10.2008 Teodoro Laino [tlaino] : splitted from force_fields_input in order
!> to collect in a unique module only the functions to read external FF
!> \author CJM
! *****************************************************************************
MODULE force_fields_ext
USE cp_output_handling, ONLY: cp_print_key_finished_output,&
cp_print_key_unit_nr
USE cp_para_types, ONLY: cp_para_env_type
USE cp_parser_methods, ONLY: parser_get_next_line,&
parser_get_object,&
parser_search_string,&
parser_test_next_token
USE cp_parser_types, ONLY: cp_parser_type,&
parser_create,&
parser_release
USE cp_units, ONLY: cp_unit_to_cp2k
USE f77_blas
USE force_field_types, ONLY: amber_info_type,&
charmm_info_type,&
force_field_type,&
gromos_info_type
USE input_constants, ONLY: do_ff_g96
USE input_section_types, ONLY: section_vals_type
USE kinds, ONLY: default_string_length,&
dp
USE memory_utilities, ONLY: reallocate
USE particle_types, ONLY: particle_type
USE string_utilities, ONLY: uppercase
USE timings, ONLY: timeset,&
timestop
USE topology_amber, ONLY: rdparm_amber_8
#include "cp_common_uses.h"
IMPLICIT NONE
CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'force_fields_ext'
PRIVATE
PUBLIC :: read_force_field_charmm,&
read_force_field_amber,&
read_force_field_gromos
CONTAINS
! *****************************************************************************
!> \brief Reads the GROMOS force_field
!> \author ikuo
! *****************************************************************************
SUBROUTINE read_force_field_gromos ( ff_type , para_env, mm_section, error )
TYPE(force_field_type), INTENT(INOUT) :: ff_type
TYPE(cp_para_env_type), POINTER :: para_env
TYPE(section_vals_type), POINTER :: mm_section
TYPE(cp_error_type), INTENT(inout) :: error
CHARACTER(len=*), PARAMETER :: routineN = 'read_force_field_gromos', &
routineP = moduleN//':'//routineN
REAL(KIND=dp), PARAMETER :: ekt = 2.5_dp
CHARACTER(LEN=default_string_length) :: label
CHARACTER(LEN=default_string_length), &
DIMENSION(21) :: avail_section
CHARACTER(LEN=default_string_length), &
POINTER :: namearray(:)
INTEGER :: handle, iatom, icon, itemp, &
itype, iw, jatom, ncon, &
ntype, offset, stat
LOGICAL :: failure, found
REAL(KIND=dp) :: cosphi0, cost2, csq, sdet
TYPE(cp_logger_type), POINTER :: logger
TYPE(cp_parser_type), POINTER :: parser
TYPE(gromos_info_type), POINTER :: gro_info
CALL timeset(routineN,handle)
failure = .FALSE.
NULLIFY(logger,parser)
logger => cp_error_get_logger(error)
iw = cp_print_key_unit_nr(logger,mm_section,"PRINT%FF_INFO",&
extension=".mmLog",error=error)
avail_section( 1) = "TITLE"
avail_section( 2) = "TOPPHYSCON"
avail_section( 3) = "TOPVERSION"
avail_section( 4) = "ATOMTYPENAME"
avail_section( 5) = "RESNAME"
avail_section( 6) = "SOLUTEATOM"
avail_section( 7) = "BONDTYPE"
avail_section( 8) = "BONDH"
avail_section( 9) = "BOND"
avail_section(10) = "BONDANGLETYPE"
avail_section(11) = "BONDANGLEH"
avail_section(12) = "BONDANGLE"
avail_section(13) = "IMPDIHEDRALTYPE"
avail_section(14) = "IMPDIHEDRALH"
avail_section(15) = "IMPDIHEDRAL"
avail_section(16) = "DIHEDRALTYPE"
avail_section(17) = "DIHEDRALH"
avail_section(18) = "DIHEDRAL"
avail_section(19) = "LJPARAMETERS"
avail_section(20) = "SOLVENTATOM"
avail_section(21) = "SOLVENTCONSTR"
gro_info => ff_type%gro_info
gro_info%ff_gromos_type = ff_type%ff_type
NULLIFY(namearray)
! ATOMTYPENAME SECTION
IF(iw>0) WRITE(iw,'(T2,A)') 'GTOP_INFO| Parsing the ATOMTYPENAME section'
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(avail_section(4))
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF(found) THEN
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,ntype,error=error)
CALL reallocate(namearray,1,ntype)
DO itype=1,ntype
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,namearray(itype),lower_to_upper=.TRUE.,error=error)
IF(iw>0) WRITE(iw,*) "GTOP_INFO| ",TRIM(namearray(itype))
END DO
END IF
CALL parser_release(parser,error=error)
! SOLVENTCONSTR SECTION
IF(iw>0) WRITE(iw,'(T2,A)') 'GROMOS_FF| Parsing the SOLVENTATOM section'
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(avail_section(21))
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF(found) THEN
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,ncon,error=error)
CALL reallocate(gro_info%solvent_k,1,ncon)
CALL reallocate(gro_info%solvent_r0,1,ncon)
DO icon=1,ncon
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,itemp,error=error)
CALL parser_get_object(parser,itemp,error=error)
CALL parser_get_object(parser,gro_info%solvent_r0(icon),error=error)
gro_info%solvent_k(icon)=0.0_dp
END DO
END IF
CALL parser_release(parser,error=error)
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
! BONDTYPE SECTION
IF(iw>0) WRITE(iw,'(T2,A)') 'GROMOS_FF| Parsing the BONDTYPE section'
label = TRIM(avail_section(7))
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF(found) THEN
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,ntype,error=error)
CALL reallocate(gro_info%bond_k,1,ntype)
CALL reallocate(gro_info%bond_r0,1,ntype)
DO itype=1,ntype
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,gro_info%bond_k(itype),error=error)
CALL parser_get_object(parser,gro_info%bond_r0(itype),error=error)
IF(ff_type%ff_type==do_ff_g96) THEN
gro_info%bond_k(itype) = cp_unit_to_cp2k(gro_info%bond_k(itype),"kjmol*nm^-4",error=error)
ELSE ! Assume its G87
gro_info%bond_k(itype) = (2.0_dp) * gro_info%bond_k(itype) * gro_info%bond_r0(itype)**2
gro_info%bond_k(itype) = cp_unit_to_cp2k(gro_info%bond_k(itype),"kjmol*nm^-2",error=error)
END IF
gro_info%bond_r0(itype)= cp_unit_to_cp2k(gro_info%bond_r0(itype),"nm",error=error)
IF(iw>0) WRITE(iw,*) "GROMOS_FF| PUT BONDTYPE INFO HERE!!!!"
END DO
END IF
! BONDANGLETYPE SECTION
IF(iw>0) WRITE(iw,'(T2,A)') 'GROMOS_FF| Parsing the BONDANGLETYPE section'
label = TRIM(avail_section(10))
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF(found) THEN
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,ntype,error=error)
CALL reallocate(gro_info%bend_k,1,ntype)
CALL reallocate(gro_info%bend_theta0,1,ntype)
DO itype=1,ntype
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,gro_info%bend_k(itype),error=error)
CALL parser_get_object(parser,gro_info%bend_theta0(itype),error=error)
gro_info%bend_theta0(itype) = cp_unit_to_cp2k(gro_info%bend_theta0(itype),"deg",error=error)
IF(ff_type%ff_type==do_ff_g96) THEN
gro_info%bend_theta0(itype) = COS(gro_info%bend_theta0(itype))
ELSE ! Assume its G87
cost2 = COS(gro_info%bend_theta0(itype))*COS(gro_info%bend_theta0(itype))
sdet = cost2*cost2 - (2.0_dp*cost2-1.0_dp)*(1.0_dp-ekt/gro_info%bend_k(itype))
csq = (cost2-SQRT(sdet))/(2.0_dp*cost2-1.0_dp)
gro_info%bend_k(itype) = ekt/ACOS(csq)**2
END IF
gro_info%bend_k(itype) = cp_unit_to_cp2k(gro_info%bend_k(itype),"kjmol",error=error)
IF(iw>0) WRITE(iw,*) "GROMOS_FF| PUT BONDANGLETYPE INFO HERE!!!!"
END DO
END IF
! IMPDIHEDRALTYPE SECTION
IF(iw>0) WRITE(iw,'(T2,A)') 'GROMOS_FF| Parsing the IMPDIHEDRALTYPE section'
label = TRIM(avail_section(13))
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF(found) THEN
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,ntype,error=error)
CALL reallocate(gro_info%impr_k,1,ntype)
CALL reallocate(gro_info%impr_phi0,1,ntype)
DO itype=1,ntype
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,gro_info%impr_k(itype),error=error)
CALL parser_get_object(parser,gro_info%impr_phi0(itype),error=error)
gro_info%impr_phi0(itype) = cp_unit_to_cp2k(gro_info%impr_phi0(itype),"deg",error=error)
gro_info%impr_k(itype) = cp_unit_to_cp2k(gro_info%impr_k(itype),"kjmol*deg^-2",error=error)
IF(iw>0) WRITE(iw,*) "GROMOS_FF| PUT IMPDIHEDRALTYPE INFO HERE!!!!"
END DO
END IF
! DIHEDRALTYPE SECTION
IF(iw>0) WRITE(iw,'(T2,A)') 'GROMOS_FF| Parsing the DIHEDRALTYPE section'
label = TRIM(avail_section(16))
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF(found) THEN
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,ntype,error=error)
CALL reallocate(gro_info%torsion_k,1,ntype)
CALL reallocate(gro_info%torsion_m,1,ntype)
CALL reallocate(gro_info%torsion_phi0,1,ntype)
DO itype=1,ntype
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,gro_info%torsion_k(itype),error=error)
CALL parser_get_object(parser,cosphi0,error=error)
CALL parser_get_object(parser,gro_info%torsion_m(itype),error=error)
gro_info%torsion_phi0(itype) = ACOS(cosphi0)
gro_info%torsion_k(itype) = cp_unit_to_cp2k(gro_info%torsion_k(itype),"kjmol",error=error)
IF(iw>0) WRITE(iw,*) "GROMOS_FF| PUT DIHEDRALTYPE INFO HERE!!!!"
END DO
END IF
CALL parser_release(parser,error=error)
! LJPARAMETERS SECTION
IF(iw>0) WRITE(iw,'(T2,A)') 'GROMOS_FF| Parsing the LJPARAMETERS section'
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(avail_section(19))
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF(found) THEN
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,ntype,error=error)
offset = 0
IF(ASSOCIATED(gro_info%nonbond_a)) offset = SIZE(gro_info%nonbond_a)
ntype=SIZE(namearray)
CALL reallocate(gro_info%nonbond_a,1,ntype)
CALL reallocate(gro_info%nonbond_a_14,1,ntype)
CALL reallocate(gro_info%nonbond_c6,1,ntype,1,ntype)
CALL reallocate(gro_info%nonbond_c12,1,ntype,1,ntype)
CALL reallocate(gro_info%nonbond_c6_14,1,ntype,1,ntype)
CALL reallocate(gro_info%nonbond_c12_14,1,ntype,1,ntype)
gro_info%nonbond_c12 = 0._dp
gro_info%nonbond_c6 = 0._dp
gro_info%nonbond_c12_14 = 0._dp
gro_info%nonbond_c6_14 = 0._dp
DO itype=1,ntype*(ntype+1)/2
CALL parser_get_next_line(parser,1,error=error)
CALL parser_get_object(parser,iatom,error=error)
CALL parser_get_object(parser,jatom,error=error)
IF(iatom==jatom) THEN
gro_info%nonbond_a(iatom) = namearray(iatom)
gro_info%nonbond_a_14(iatom) = namearray(iatom)
END IF
CALL parser_get_object(parser,gro_info%nonbond_c12(iatom,jatom),error=error)
CALL parser_get_object(parser,gro_info%nonbond_c6(iatom,jatom),error=error)
CALL parser_get_object(parser,gro_info%nonbond_c12_14(iatom,jatom),error=error)
CALL parser_get_object(parser,gro_info%nonbond_c6_14(iatom,jatom),error=error)
gro_info%nonbond_c6(iatom,jatom) = cp_unit_to_cp2k(gro_info%nonbond_c6(iatom,jatom),"kjmol*nm^6",error=error)
gro_info%nonbond_c12(iatom,jatom) = cp_unit_to_cp2k(gro_info%nonbond_c12(iatom,jatom),"kjmol*nm^12",error=error)
gro_info%nonbond_c6_14(iatom,jatom) = cp_unit_to_cp2k(gro_info%nonbond_c6_14(iatom,jatom),"kjmol*nm^6",error=error)
gro_info%nonbond_c12_14(iatom,jatom) = cp_unit_to_cp2k(gro_info%nonbond_c12_14(iatom,jatom),"kjmol*nm^12",error=error)
gro_info%nonbond_c6_14(jatom,iatom)= gro_info%nonbond_c6_14(iatom,jatom)
gro_info%nonbond_c12_14(jatom,iatom)= gro_info%nonbond_c12_14(iatom,jatom)
gro_info%nonbond_c6(jatom,iatom)= gro_info%nonbond_c6(iatom,jatom)
gro_info%nonbond_c12(jatom,iatom)= gro_info%nonbond_c12(iatom,jatom)
IF(iw>0) WRITE(iw,*) "GROMOS_FF| PUT LJPARAMETERS INFO HERE!!!!"
END DO
END IF
CALL parser_release(parser,error=error)
CALL cp_print_key_finished_output(iw,logger,mm_section,&
"PRINT%FF_INFO",error=error)
CALL timestop(handle)
DEALLOCATE(namearray,STAT=stat)
CPPostcondition(stat==0,cp_failure_level,routineP,error,failure)
END SUBROUTINE read_force_field_gromos
! *****************************************************************************
!> \brief Reads the charmm force_field
!> \author ikuo
! *****************************************************************************
SUBROUTINE read_force_field_charmm ( ff_type, para_env, mm_section, error )
TYPE(force_field_type), INTENT(INOUT) :: ff_type
TYPE(cp_para_env_type), POINTER :: para_env
TYPE(section_vals_type), POINTER :: mm_section
TYPE(cp_error_type), INTENT(inout) :: error
CHARACTER(len=*), PARAMETER :: routineN = 'read_force_field_charmm', &
routineP = moduleN//':'//routineN
CHARACTER(LEN=default_string_length) :: label, string, string2, &
string3, string4
CHARACTER(LEN=default_string_length), &
DIMENSION(1) :: bond_section
CHARACTER(LEN=default_string_length), &
DIMENSION(19) :: avail_section
CHARACTER(LEN=default_string_length), &
DIMENSION(2) :: angl_section, impr_section, &
nbon_section, thet_section
INTEGER :: dummy, handle, ilab, iw, &
nbend, nbond, nimpr, &
nnonbond, nonfo, ntorsion, nub
LOGICAL :: failure, found
TYPE(charmm_info_type), POINTER :: chm_info
TYPE(cp_logger_type), POINTER :: logger
TYPE(cp_parser_type), POINTER :: parser
CALL timeset(routineN,handle)
failure = .FALSE.
NULLIFY(logger,parser)
logger => cp_error_get_logger(error)
iw = cp_print_key_unit_nr(logger,mm_section,"PRINT%FF_INFO",&
extension=".mmLog",error=error)
avail_section(1) = "BOND" ; bond_section(1) = avail_section(1)
avail_section(11)= "BONDS"
avail_section(2) = "ANGL" ; angl_section(1) = avail_section(2)
avail_section(3) = "THETA" ; angl_section(2) = avail_section(3)
avail_section(12)= "THETAS"
avail_section(13)= "ANGLE"
avail_section(14)= "ANGLES"
avail_section(4) = "DIHEDRAL" ; thet_section(1) = avail_section(4)
avail_section(15)= "DIHEDRALS"
avail_section(5) = "PHI" ; thet_section(2) = avail_section(5)
avail_section(6) = "IMPROPER" ; impr_section(1) = avail_section(6)
avail_section(7) = "IMPH" ; impr_section(2) = avail_section(7)
avail_section(16)= "IMPHI"
avail_section(8) = "NONBONDED"; nbon_section(1) = avail_section(8)
avail_section(9) = "NBOND" ; nbon_section(2) = avail_section(9)
avail_section(10)= "HBOND"
avail_section(17)= "NBFIX"
avail_section(18)= "CMAP"
avail_section(19)= "END"
chm_info => ff_type%chm_info
!-----------------------------------------------------------------------------
!-----------------------------------------------------------------------------
! 1. Read in all the Bonds info from the param file here
! Vbond = Kb(b-b0)^2
! UNITS for Kb: [(kcal/mol)/(A^2)] to [Eh/(AU^2)]
!-----------------------------------------------------------------------------
nbond = 0
DO ilab = 1, SIZE(bond_section)
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(bond_section(ilab))
DO
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF (found) THEN
CALL parser_get_object(parser,string,error=error)
IF (INDEX(string,TRIM(label)) /= 1) CYCLE
CALL charmm_get_next_line(parser,1,error=error)
DO
CALL parser_get_object(parser,string,error=error)
CALL uppercase ( string )
IF(ANY(string == avail_section)) EXIT
CALL parser_get_object(parser,string2,error=error)
CALL uppercase ( string2 )
nbond = nbond + 1
CALL reallocate(chm_info%bond_a,1,nbond)
CALL reallocate(chm_info%bond_b,1,nbond)
CALL reallocate(chm_info%bond_k,1,nbond)
CALL reallocate(chm_info%bond_r0,1,nbond)
chm_info%bond_a(nbond) = string
chm_info%bond_b(nbond) = string2
CALL parser_get_object(parser,chm_info%bond_k(nbond),error=error)
CALL parser_get_object(parser,chm_info%bond_r0(nbond),error=error)
IF(iw>0) WRITE(iw,*) " CHM BOND ",nbond,&
TRIM(chm_info%bond_a(nbond))," ",&
TRIM(chm_info%bond_b(nbond))," ",&
chm_info%bond_k(nbond),&
chm_info%bond_r0(nbond)
! Do some units conversion into internal atomic units
chm_info%bond_r0(nbond) = cp_unit_to_cp2k(chm_info%bond_r0(nbond),"angstrom",error=error)
chm_info%bond_k(nbond) = cp_unit_to_cp2k(chm_info%bond_k(nbond),"kcalmol*angstrom^-2",error=error)
CALL charmm_get_next_line(parser,1,error=error)
END DO
ELSE
EXIT
END IF
END DO
CALL parser_release(parser,error=error)
END DO
!-----------------------------------------------------------------------------
!-----------------------------------------------------------------------------
! 2. Read in all the Bends and UB info from the param file here
! Vangle = Ktheta(theta-theta0)^2
! UNITS for Ktheta: [(kcal/mol)/(rad^2)] to [Eh/(rad^2)]
! FACTOR of "2" rolled into Ktheta
! Vub = Kub(S-S0)^2
! UNITS for Kub: [(kcal/mol)/(A^2)] to [Eh/(AU^2)]
!-----------------------------------------------------------------------------
nbend = 0
nub = 0
DO ilab = 1, SIZE(angl_section)
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(angl_section(ilab))
DO
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF (found) THEN
CALL parser_get_object(parser,string,error=error)
IF (INDEX(string,TRIM(label)) /= 1) CYCLE
CALL charmm_get_next_line(parser,1,error=error)
DO
CALL parser_get_object(parser,string,error=error)
CALL uppercase ( string )
IF(ANY(string == avail_section)) EXIT
CALL parser_get_object(parser,string2,error=error)
CALL parser_get_object(parser,string3,error=error)
CALL uppercase ( string2 )
CALL uppercase ( string3 )
nbend = nbend + 1
CALL reallocate(chm_info%bend_a,1,nbend)
CALL reallocate(chm_info%bend_b,1,nbend)
CALL reallocate(chm_info%bend_c,1,nbend)
CALL reallocate(chm_info%bend_k,1,nbend)
CALL reallocate(chm_info%bend_theta0,1,nbend)
chm_info%bend_a(nbend) = string
chm_info%bend_b(nbend) = string2
chm_info%bend_c(nbend) = string3
CALL parser_get_object(parser,chm_info%bend_k(nbend),error=error)
CALL parser_get_object(parser,chm_info%bend_theta0(nbend),error=error)
IF(iw>0) WRITE(iw,*) " CHM BEND ",nbend,&
TRIM(chm_info%bend_a(nbend))," ",&
TRIM(chm_info%bend_b(nbend))," ",&
TRIM(chm_info%bend_c(nbend))," ",&
chm_info%bend_k(nbend),&
chm_info%bend_theta0(nbend)
! Do some units conversion into internal atomic units
chm_info%bend_theta0(nbend) = cp_unit_to_cp2k(chm_info%bend_theta0(nbend),"deg",error=error)
chm_info%bend_k(nbend) = cp_unit_to_cp2k(chm_info%bend_k(nbend),"kcalmol*rad^-2",error=error)
IF (parser_test_next_token(parser,error=error) == "FLT") THEN
nub = nub + 1
CALL reallocate(chm_info%ub_a,1,nub)
CALL reallocate(chm_info%ub_b,1,nub)
CALL reallocate(chm_info%ub_c,1,nub)
CALL reallocate(chm_info%ub_k,1,nub)
CALL reallocate(chm_info%ub_r0,1,nub)
chm_info%ub_a(nub) = string
chm_info%ub_b(nub) = string2
chm_info%ub_c(nub) = string3
CALL parser_get_object(parser,chm_info%ub_k(nub),error=error)
CALL parser_get_object(parser,chm_info%ub_r0(nub),error=error)
IF(iw>0) WRITE(iw,*) " CHM UB ",nub,&
TRIM(chm_info%ub_a(nub))," ",&
TRIM(chm_info%ub_b(nub))," ",&
TRIM(chm_info%ub_c(nub))," ",&
chm_info%ub_k(nub),&
chm_info%ub_r0(nub)
! Do some units conversion into internal atomic units
chm_info%ub_r0(nub) = cp_unit_to_cp2k(chm_info%ub_r0(nub),"angstrom",error=error)
chm_info%ub_k(nub) = cp_unit_to_cp2k(chm_info%ub_k(nub),"kcalmol*angstrom^-2",error=error)
END IF
CALL charmm_get_next_line(parser,1,error=error)
END DO
ELSE
EXIT
END IF
END DO
CALL parser_release(parser,error=error)
END DO
!-----------------------------------------------------------------------------
!-----------------------------------------------------------------------------
! 3. Read in all the Dihedrals info from the param file here
! Vtorsion = Kphi(1+COS(n(phi)-delta))
! UNITS for Kphi: [(kcal/mol)] to [Eh]
!-----------------------------------------------------------------------------
ntorsion = 0
DO ilab = 1, SIZE(thet_section)
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(thet_section(ilab))
DO
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF (found) THEN
CALL parser_get_object(parser,string,error=error)
IF (INDEX(string,TRIM(label)) /= 1) CYCLE
CALL charmm_get_next_line(parser,1,error=error)
DO
CALL parser_get_object(parser,string,error=error)
CALL uppercase ( string )
IF(ANY(string == avail_section)) EXIT
CALL parser_get_object(parser,string2,error=error)
CALL parser_get_object(parser,string3,error=error)
CALL parser_get_object(parser,string4,error=error)
CALL uppercase ( string2 )
CALL uppercase ( string3 )
CALL uppercase ( string4 )
ntorsion = ntorsion + 1
CALL reallocate(chm_info%torsion_a,1,ntorsion)
CALL reallocate(chm_info%torsion_b,1,ntorsion)
CALL reallocate(chm_info%torsion_c,1,ntorsion)
CALL reallocate(chm_info%torsion_d,1,ntorsion)
CALL reallocate(chm_info%torsion_k,1,ntorsion)
CALL reallocate(chm_info%torsion_m,1,ntorsion)
CALL reallocate(chm_info%torsion_phi0,1,ntorsion)
chm_info%torsion_a(ntorsion) = string
chm_info%torsion_b(ntorsion) = string2
chm_info%torsion_c(ntorsion) = string3
chm_info%torsion_d(ntorsion) = string4
CALL parser_get_object(parser,chm_info%torsion_k(ntorsion),error=error)
CALL parser_get_object(parser,chm_info%torsion_m(ntorsion),error=error)
CALL parser_get_object(parser,chm_info%torsion_phi0(ntorsion),error=error)
IF(iw>0) WRITE(iw,*) " CHM TORSION ",ntorsion,&
TRIM(chm_info%torsion_a(ntorsion))," ",&
TRIM(chm_info%torsion_b(ntorsion))," ",&
TRIM(chm_info%torsion_c(ntorsion))," ",&
TRIM(chm_info%torsion_d(ntorsion))," ",&
chm_info%torsion_k(ntorsion),&
chm_info%torsion_m(ntorsion),&
chm_info%torsion_phi0(ntorsion)
! Do some units conversion into internal atomic units
chm_info%torsion_phi0(ntorsion) = cp_unit_to_cp2k(chm_info%torsion_phi0(ntorsion),&
"deg",error=error)
chm_info%torsion_k(ntorsion) = cp_unit_to_cp2k(chm_info%torsion_k(ntorsion),"kcalmol",&
error=error)
CALL charmm_get_next_line(parser,1,error=error)
END DO
ELSE
EXIT
END IF
END DO
CALL parser_release(parser,error=error)
END DO
!-----------------------------------------------------------------------------
!-----------------------------------------------------------------------------
! 4. Read in all the Improper info from the param file here
! Vimpr = Kpsi(psi-psi0)^2
! UNITS for Kpsi: [(kcal/mol)/(rad^2)] to [Eh/(rad^2)]
!-----------------------------------------------------------------------------
nimpr = 0
DO ilab = 1, SIZE(impr_section)
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(impr_section(ilab))
DO
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF (found) THEN
CALL parser_get_object(parser,string,error=error)
IF (INDEX(string,TRIM(label)) /= 1) CYCLE
CALL charmm_get_next_line(parser,1,error=error)
DO
CALL parser_get_object(parser,string,error=error)
CALL uppercase ( string )
IF(ANY(string == avail_section)) EXIT
CALL parser_get_object(parser,string2,error=error)
CALL parser_get_object(parser,string3,error=error)
CALL parser_get_object(parser,string4,error=error)
CALL uppercase ( string2 )
CALL uppercase ( string3 )
CALL uppercase ( string4 )
nimpr = nimpr + 1
CALL reallocate(chm_info%impr_a,1,nimpr)
CALL reallocate(chm_info%impr_b,1,nimpr)
CALL reallocate(chm_info%impr_c,1,nimpr)
CALL reallocate(chm_info%impr_d,1,nimpr)
CALL reallocate(chm_info%impr_k,1,nimpr)
CALL reallocate(chm_info%impr_phi0,1,nimpr)
chm_info%impr_a(nimpr) = string
chm_info%impr_b(nimpr) = string2
chm_info%impr_c(nimpr) = string3
chm_info%impr_d(nimpr) = string4
CALL parser_get_object(parser,chm_info%impr_k(nimpr),error=error)
CALL parser_get_object(parser,dummy,error=error)
CALL parser_get_object(parser,chm_info%impr_phi0(nimpr),error=error)
IF(iw>0) WRITE(iw,*) " CHM IMPROPERS ",nimpr,&
TRIM(chm_info%impr_a(nimpr))," ",&
TRIM(chm_info%impr_b(nimpr))," ",&
TRIM(chm_info%impr_c(nimpr))," ",&
TRIM(chm_info%impr_d(nimpr))," ",&
chm_info%impr_k(nimpr),&
chm_info%impr_phi0(nimpr)
! Do some units conversion into internal atomic units
chm_info%impr_phi0(nimpr) = cp_unit_to_cp2k(chm_info%impr_phi0(nimpr),"deg",error=error)
chm_info%impr_k(nimpr) = cp_unit_to_cp2k(chm_info%impr_k(nimpr),"kcalmol",error=error)
CALL charmm_get_next_line(parser,1,error=error)
END DO
ELSE
EXIT
END IF
END DO
CALL parser_release(parser,error=error)
END DO
!-----------------------------------------------------------------------------
!-----------------------------------------------------------------------------
! 5. Read in all the Nonbonded info from the param file here
!-----------------------------------------------------------------------------
nnonbond = 0
nonfo = 0
DO ilab = 1, SIZE(nbon_section)
CALL parser_create(parser,ff_type%ff_file_name,para_env=para_env,error=error)
label = TRIM(nbon_section(ilab))
DO
CALL parser_search_string(parser,label,.TRUE.,found,begin_line=.TRUE.,error=error)
IF (found) THEN
CALL parser_get_object(parser,string,error=error)
IF (INDEX(string,TRIM(label)) /= 1) CYCLE
CALL charmm_get_next_line(parser,1,error=error)
DO
CALL parser_get_object(parser,string,error=error)
CALL uppercase ( string )
IF(ANY(string == avail_section)) EXIT
nnonbond = nnonbond + 1
CALL reallocate(chm_info%nonbond_a,1,nnonbond)
CALL reallocate(chm_info%nonbond_eps,1,nnonbond)
CALL reallocate(chm_info%nonbond_rmin2,1,nnonbond)
chm_info%nonbond_a(nnonbond) = string
CALL parser_get_object(parser,chm_info%nonbond_eps(nnonbond),error=error)
CALL parser_get_object(parser,chm_info%nonbond_eps(nnonbond),error=error)
CALL parser_get_object(parser,chm_info%nonbond_rmin2(nnonbond),error=error)
IF(iw>0) WRITE(iw,*) " CHM NONBOND ",nnonbond,&
TRIM(chm_info%nonbond_a(nnonbond))," ",&
chm_info%nonbond_eps(nnonbond),&
chm_info%nonbond_rmin2(nnonbond)
chm_info%nonbond_rmin2(nnonbond) = cp_unit_to_cp2k(chm_info%nonbond_rmin2(nnonbond),&
"angstrom", error=error)
chm_info%nonbond_eps(nnonbond) = cp_unit_to_cp2k(chm_info%nonbond_eps(nnonbond),&
"kcalmol",error=error)
IF (parser_test_next_token(parser,error=error) == "FLT") THEN
nonfo = nonfo + 1
CALL reallocate(chm_info%nonbond_a_14,1,nonfo)
CALL reallocate(chm_info%nonbond_eps_14,1,nonfo)
CALL reallocate(chm_info%nonbond_rmin2_14,1,nonfo)
chm_info%nonbond_a_14(nonfo) = chm_info%nonbond_a(nnonbond)
CALL parser_get_object(parser,chm_info%nonbond_eps_14(nonfo),error=error)
CALL parser_get_object(parser,chm_info%nonbond_eps_14(nonfo),error=error)
CALL parser_get_object(parser,chm_info%nonbond_rmin2_14(nonfo),error=error)
IF(iw>0) WRITE(iw,*) " CHM ONFO ",nonfo,&
TRIM(chm_info%nonbond_a_14(nonfo))," ",&
chm_info%nonbond_eps_14(nonfo),&
chm_info%nonbond_rmin2_14(nonfo)
chm_info%nonbond_rmin2_14(nonfo) = cp_unit_to_cp2k(chm_info%nonbond_rmin2_14(nonfo),&
"angstrom",error=error)
chm_info%nonbond_eps_14(nonfo) = cp_unit_to_cp2k(chm_info%nonbond_eps_14(nonfo),&
"kcalmol",error=error)
END IF
CALL charmm_get_next_line(parser,1,error=error)
END DO
ELSE
EXIT
END IF
END DO
CALL parser_release(parser,error=error)
END DO
CALL cp_print_key_finished_output(iw,logger,mm_section,&
"PRINT%FF_INFO",error=error)
CALL timestop(handle)
END SUBROUTINE read_force_field_charmm
! *****************************************************************************
!> \brief Reads the AMBER force_field
!> \author Teodoro Laino [tlaino, teodoro.laino-AT-gmail.com] - 11.2008
! *****************************************************************************
SUBROUTINE read_force_field_amber ( ff_type, para_env, mm_section, particle_set, error )
TYPE(force_field_type), INTENT(INOUT) :: ff_type
TYPE(cp_para_env_type), POINTER :: para_env
TYPE(section_vals_type), POINTER :: mm_section
TYPE(particle_type), DIMENSION(:), &
POINTER :: particle_set
TYPE(cp_error_type), INTENT(inout) :: error
CHARACTER(len=*), PARAMETER :: routineN = 'read_force_field_amber', &
routineP = moduleN//':'//routineN
INTEGER :: handle, i, iw
LOGICAL :: failure
TYPE(amber_info_type), POINTER :: amb_info
TYPE(cp_logger_type), POINTER :: logger
CALL timeset(routineN,handle)
failure = .FALSE.
NULLIFY(logger)
logger => cp_error_get_logger(error)
iw = cp_print_key_unit_nr(logger,mm_section,"PRINT%FF_INFO",&
extension=".mmLog",error=error)
amb_info => ff_type%amb_info
! Read the Amber topology file to gather the forcefield information
CALL rdparm_amber_8(ff_type%ff_file_name, iw, para_env, do_connectivity=.FALSE.,&
do_forcefield=.TRUE., particle_set=particle_set, amb_info=amb_info, error=error)
!-----------------------------------------------------------------------------
! 1. Converts all the Bonds info from the param file here
! Vbond = Kb(b-b0)^2
! UNITS for Kb: [(kcal/mol)/(A^2)] to [Eh/(AU^2)]
!-----------------------------------------------------------------------------
DO i = 1, SIZE(amb_info%bond_a)
IF(iw>0) WRITE(iw,*) " AMB BOND ",i,&
TRIM(amb_info%bond_a(i))," ",&
TRIM(amb_info%bond_b(i))," ",&
amb_info%bond_k(i),&
amb_info%bond_r0(i)
! Do some units conversion into internal atomic units
amb_info%bond_r0(i) = cp_unit_to_cp2k(amb_info%bond_r0(i),"angstrom",error=error)
amb_info%bond_k(i) = cp_unit_to_cp2k(amb_info%bond_k(i),"kcalmol*angstrom^-2",error=error)
END DO
!-----------------------------------------------------------------------------
! 2. Converts all the Bends info from the param file here
! Vangle = Ktheta(theta-theta0)^2
! UNITS for Ktheta: [(kcal/mol)/(rad^2)] to [Eh/(rad^2)]
! FACTOR of "2" rolled into Ktheta
! Vub = Kub(S-S0)^2
! UNITS for Kub: [(kcal/mol)/(A^2)] to [Eh/(AU^2)]
!-----------------------------------------------------------------------------
DO i = 1, SIZE(amb_info%bend_a)
IF(iw>0) WRITE(iw,*) " AMB BEND ",i,&
TRIM(amb_info%bend_a(i))," ",&
TRIM(amb_info%bend_b(i))," ",&
TRIM(amb_info%bend_c(i))," ",&
amb_info%bend_k(i),&
amb_info%bend_theta0(i)
! Do some units conversion into internal atomic units
amb_info%bend_theta0(i) = cp_unit_to_cp2k(amb_info%bend_theta0(i),"rad",error=error)
amb_info%bend_k(i) = cp_unit_to_cp2k(amb_info%bend_k(i),"kcalmol*rad^-2",error=error)
END DO
!-----------------------------------------------------------------------------
! 3. Converts all the Dihedrals info from the param file here
! Vtorsion = Kphi(1+COS(n(phi)-delta))
! UNITS for Kphi: [(kcal/mol)] to [Eh]
!-----------------------------------------------------------------------------
DO i = 1, SIZE(amb_info%torsion_a)
IF(iw>0) WRITE(iw,*) " AMB TORSION ",i,&
TRIM(amb_info%torsion_a(i))," ",&
TRIM(amb_info%torsion_b(i))," ",&
TRIM(amb_info%torsion_c(i))," ",&
TRIM(amb_info%torsion_d(i))," ",&
amb_info%torsion_k(i),&
amb_info%torsion_m(i),&
amb_info%torsion_phi0(i)
! Do some units conversion into internal atomic units
amb_info%torsion_phi0(i) = cp_unit_to_cp2k(amb_info%torsion_phi0(i),"rad",error=error)
amb_info%torsion_k(i) = cp_unit_to_cp2k(amb_info%torsion_k(i),"kcalmol",error=error)
END DO
!-----------------------------------------------------------------------------
! 4. Converts all the Nonbonded info from the param file here
!-----------------------------------------------------------------------------
DO i = 1, SIZE(amb_info%nonbond_eps)
IF(iw>0) WRITE(iw,*) " AMB NONBOND ",i,&
TRIM(amb_info%nonbond_a(i))," ",&
amb_info%nonbond_eps(i),&
amb_info%nonbond_rmin2(i)
! Do some units conversion into internal atomic units
amb_info%nonbond_rmin2(i) = cp_unit_to_cp2k(amb_info%nonbond_rmin2(i),"angstrom", error=error)
amb_info%nonbond_eps(i) = cp_unit_to_cp2k(amb_info%nonbond_eps(i),"kcalmol",error=error)
END DO
CALL cp_print_key_finished_output(iw,logger,mm_section,"PRINT%FF_INFO",error=error)
CALL timestop(handle)
END SUBROUTINE read_force_field_amber
! *****************************************************************************
!> \brief This function is simply a wrap to the parser_get_next_line..
!> Comments: This routine would not be necessary if the continuation
!> char for CHARMM would not be the "-".. How can you choose this
!> character in a file of numbers as a continuation char????
!> This sounds simply crazy....
!> \author Teodoro Laino - Zurich University - 06.2007
! *****************************************************************************
SUBROUTINE charmm_get_next_line(parser, nline, error)
TYPE(cp_parser_type), POINTER :: parser
INTEGER, INTENT(IN) :: nline
TYPE(cp_error_type), INTENT(inout) :: error
CHARACTER(len=*), PARAMETER :: routineN = 'charmm_get_next_line', &
routineP = moduleN//':'//routineN
CHARACTER(LEN=1), PARAMETER :: continuation_char = "-"
INTEGER :: i, len_line
DO i = 1, nline
len_line = LEN_TRIM(parser%input_line)
DO WHILE (parser%input_line(len_line:len_line)==continuation_char)
CALL parser_get_next_line(parser,1,error=error)
len_line = LEN_TRIM(parser%input_line)
END DO
CALL parser_get_next_line(parser,1,error=error)
END DO
END SUBROUTINE charmm_get_next_line
END MODULE force_fields_ext
|
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const User = require('../client/src/components/models/User');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mongoose.connect('mongodb+srv://hemantsuteri:[email protected]/?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// app.get("/api", (req, res) => {
// res.json({ message: "Hello from server!" });
// });
// Login API
app.post('/api/login', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ message: 'Email and password are required' });
}
try {
const user = await User.findOne({ email, password });
if (user) {
res.status(200).json({ message: 'Login successful' });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
} catch (error) {
res.status(500).json({ message: 'Internal server error' });
}
});
// Signup API
app.post('/api/register', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ message: 'Email and password are required' });
}
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
res.status(409).json({ message: 'User already exists' });
} else {
await User.create({ email, password });
res.status(201).json({ message: 'Registration successful' });
}
} catch (error) {
res.status(500).json({ message: 'Internal server error' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
// const express = require('express');
// const mongoose = require('mongoose');
// const bodyParser = require('body-parser');
// const User = require('./models/User');
// const app = express();
// const PORT = process.env.PORT || 5000;
// app.use(bodyParser.json());
// // Connect to MongoDB Atlas
// mongoose.connect('mongodb+srv://hemantsuteri:[email protected]/?retryWrites=true&w=majority', {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// });
// const db = mongoose.connection;
// db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// db.once('open', () => {
// console.log('Connected to MongoDB Atlas');
// });
// // Authentication Routes
// app.post('/api/login', async (req, res) => {
// const { email, password } = req.body;
// try {
// const user = await User.findOne({ email, password });
// if (user) {
// res.status(200).json({ message: 'Login successful' });
// } else {
// res.status(401).json({ message: 'Invalid credentials' });
// }
// } catch (error) {
// console.error(error);
// res.status(500).json({ message: 'Internal server error' });
// }
// });
// app.post('/api/register', async (req, res) => {
// const { email, password } = req.body;
// try {
// const existingUser = await User.findOne({ email });
// if (existingUser) {
// res.status(400).json({ message: 'User already exists' });
// } else {
// const newUser = new User({ email, password });
// await newUser.save();
// res.status(201).json({ message: 'Registration successful' });
// }
// } catch (error) {
// console.error(error);
// res.status(500).json({ message: 'Internal server error' });
// }
// });
// app.listen(PORT, () => {
// console.log(`Server is running on port ${PORT}`);
// });
|
<template>
<div class="file-view">
<component :is="component" :content="content" :path="path" ref="fileRef" />
</div>
</template>
<script setup lang="ts">
import { ref, watch, computed, markRaw, onMounted } from 'vue'
import type { Component } from 'vue'
import { invoke } from '@tauri-apps/api/tauri'
import mdEditor from '../components/editors/mdEditor.vue'
import luluEditor from '../components/editors/luluEditor.vue'
import { BusEvent } from '../types/BusEvent'
import { FileStore } from '../stores/FileStore.ts'
import { emit, listen } from '@tauri-apps/api/event'
const content = ref<string>('')
const path = ref<string>('')
const extension = computed(() => {
return path.value.split('.').at(-1)
})
const readFile = async (pathValue: string) => {
return await invoke('read_file', {
path: pathValue
})
}
const component = ref<Component | null>(null)
watch(extension, newV => {
newV === 'md' ? (component.value = markRaw(mdEditor)) : (component.value = markRaw(luluEditor))
})
const fileStore = FileStore()
onMounted(async () => {
content.value = (await readFile(fileStore.filePath)) as string
path.value = fileStore.filePath
})
listen(BusEvent.SwitchFilePath, async data => {
const newPath = data.payload as string
content.value = (await readFile(newPath)) as string
path.value = newPath
})
const fileRef = ref<InstanceType<typeof mdEditor> | InstanceType<typeof luluEditor> | null>(null)
listen(BusEvent.SaveFile, async () => {
await fileRef.value!.saveFile()
await emit(BusEvent.SaveCompleted)
})
</script>
<style lang="less" scoped>
.file-view {
height: 100%;
display: flex;
}
</style>
|
#!/usr/bin/env python3
"""
filtered_logger module
"""
import re
from typing import List
import logging
import mysql.connector
from os import environ
PII_FIELDS = ("name", "email", "phone", "ssn", "password")
class RedactingFormatter(logging.Formatter):
""" Redacting Formatter class
"""
REDACTION = "***"
FORMAT = "[HOLBERTON] %(name)s %(levelname)s %(asctime)-15s: %(message)s"
SEPARATOR = ";"
def __init__(self, fields: List[str]):
"""
Initialization.
"""
super(RedactingFormatter, self).__init__(self.FORMAT)
self.fields = fields
def format(self, record: logging.LogRecord) -> str:
"""
Filter values in incoming log records.
"""
log_message = super().format(record)
return filter_datum(
self.fields, self.REDACTION, log_message, self.SEPARATOR)
def filter_datum(fields: List[str], redaction: str,
message: str, separator: str) -> str:
"""
Obfuscate specified fields in the log message using regex.
Arguments:
fields: A list of strings repr all fields to obfuscate.
redaction: A string repr by what the field will be obfuscated.
message: A string representing the log line.
separator: A string repr the separator.
Returns:
The log message with specified fields obfuscated.
"""
return re.sub(
r'(\b(?:{}))[^{};]+'.format("|".join(fields), re.escape(
separator)), r'\1=' + redaction, message, flags=re.MULTILINE)
def get_logger() -> logging.Logger:
"""
Create and configure the 'user_data' logger.
"""
logger = logging.getLogger("user_data")
logger.setLevel(logging.INFO)
stream_handler = logging.StreamHandler()
formatter = RedactingFormatter(fields=list(PII_FIELDS))
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.propagate = False
return logger
def get_db() -> mysql.connector.connection.MySQLConnection:
"""
Returns A MySQLConnection by obtaining credentials from
environment variables
"""
username = environ.get("PERSONAL_DATA_DB_USERNAME", "root")
password = environ.get("PERSONAL_DATA_DB_PASSWORD", "")
host = environ.get("PERSONAL_DATA_DB_HOST", "localhost")
db_name = environ.get("PERSONAL_DATA_DB_NAME")
conn_obj = mysql.connector.connection.MySQLConnection(user=username,
password=password,
host=host,
database=db_name)
return conn_obj
def main() -> None:
"""
Main function to obtain a database connection,
retrieve all rows in the users table,
and display each row under a filtered format.
"""
db = get_db()
cursor = db.cursor()
try:
cursor.execute("SELECT * FROM users;")
field_names = [i[0] for i in cursor.description]
logger = get_logger()
for row in cursor:
formatted_row = ""
for value, field_name in zip(row, field_names):
if field_name in PII_FIELDS:
formatted_row += '{}={}; '.format(
field_name, logger.handlers[0].formatter.REDACTION)
else:
formatted_row += '{}={}; '.format(field_name, str(value))
logger.info(formatted_row.strip())
except mysql.connector.Error as err:
logger.error(f"Error accessing the database: {err}")
finally:
cursor.close()
db.close()
if __name__ == "__main__":
main()
|
// Foolowing on from the example
// DrawSingleShape_CodeExample in week 1 of this unit.
// This example can draw multiple shapes
// Each shape is now contained in a DrawnShape object
// It uses a "DrawingList" to contain all the DrawnShape instances
// as the user creates them
float[][] edge_matrix = { { 0, -2, 0 },
{ -2, 8, -2 },
{ 0, -2, 0 } };
float[][] blur_matrix = { {0.1, 0.1, 0.1 },
{0.1, 0.1, 0.1 },
{0.1, 0.1, 0.1 } };
float[][] sharpen_matrix = { { 0, -1, 0 },
{-1, 5, -1 },
{ 0, -1, 0 } };
float[][] gaussianblur_matrix = { { 0.000, 0.000, 0.001, 0.001, 0.001, 0.000, 0.000},
{ 0.000, 0.002, 0.012, 0.020, 0.012, 0.002, 0.000},
{ 0.001, 0.012, 0.068, 0.109, 0.068, 0.012, 0.001},
{ 0.001, 0.020, 0.109, 0.172, 0.109, 0.020, 0.001},
{ 0.001, 0.012, 0.068, 0.109, 0.068, 0.012, 0.001},
{ 0.000, 0.002, 0.012, 0.020, 0.012, 0.002, 0.000},
{ 0.000, 0.000, 0.001, 0.001, 0.001, 0.000, 0.000}
};
PImage myImage;
PImage outputImage;
PImage canvasToSave;
SimpleUI myUI;
DrawingList drawingList;
String toolMode = "";
void setup() {
size(900,750);
myUI = new SimpleUI();
drawingList = new DrawingList();
ButtonBaseClass rectButton = myUI.addRadioButton("rect", 5, 50, "group1");
myUI.addRadioButton("ellipse", 5, 80, "group1");
myUI.addRadioButton("line", 5, 110, "group1");
myUI.addRadioButton("circle", 5, 140, "group1");
rectButton.selected = true;
toolMode = rectButton.UILabel;
// add a new tool .. the select tool
myUI.addRadioButton("select", 5, 180, "group1");
myUI.addToggleButton("show fill", 5, 250).setSelected(true);
myUI.addToggleButton("show line", 5, 280);
myUI.addRadioButton("Use sliders", 5, 320, "colour setting choice").setSelected(true);
// add sliders
myUI.addSlider("Red", 5, 350);
myUI.addSlider("Green", 5, 380);
myUI.addSlider("Blue", 5, 410);
myUI.addRadioButton("Use text boxes", 5, 450, "colour setting choice");
// add text input boxes
myUI.addTextInputBox("R", 5, 480, "0");
myUI.addTextInputBox("G", 5, 510, "0");
myUI.addTextInputBox("B", 5, 540, "0");
myUI.addLabel("Stroke Weight",5,600,"");
myUI.addTextInputBox("S", 5, 630, "0");
myUI.addPlainButton("openFile", 620,5);
myUI.addPlainButton("saveFile", 690,5);
String[] items = { "brighten", "darken", "contrast", "negative","greyscale","edges","blur","sharpen","gaussianblur"};
myUI.addMenu("Effect", 100, 5, items );
myUI.addPlainButton("undo", 200,5);
myUI.addCanvas(130,60,730,660);
}
void draw() {
background(255);
if( myImage != null ){
checkSize(myImage);
image(myImage,130,60);
//outputImage = myImage.copy();
if(outputImage != null){
image(outputImage, 130, 60);
}
//outputImage = myImage.copy();
}
drawingList.drawMe();
myUI.update();
}
void checkSize(PImage image){
if((image.width>590) || (image.height>590)){
image.width=590;
image.height=590;
}
}
void conv_filter(PImage myImage,float[][] matrix){
checkSize(myImage);
for(int y = 0; y < myImage.width; y++){
for(int x = 0; x < myImage.height; x++){
color c = convolution(x, y, matrix, 3, myImage);
outputImage.set(x,y,c);
}
}
}
void handleUIEvent(UIEventData eventData){
if( eventData.eventIsFromWidget("openFile")) {
myUI.openFileLoadDialog("open an image");
}
if(eventData.eventIsFromWidget("fileLoadDialog")){
myImage=loadImage(eventData.fileSelection);
checkSize(myImage);
//image(myImage,110,10);
outputImage = myImage.copy();
checkSize(outputImage);
//outputImage.width=590;
//outputImage.height=560;
}
if(eventData.eventIsFromWidget("saveFile")){
myUI.openFileSaveDialog("save an image");
}
//this catches the file save information when the file save dialogue's "save" button is hit
if(eventData.eventIsFromWidget("fileSaveDialog")){
canvasToSave= get(131,61,729,659);
canvasToSave.save(eventData.fileSelection);
}
if( eventData.eventIsFromWidget("brighten")){
int[] lut = makeLUT("brighten", 1.5, 0.0);
outputImage = applyPointProcessing(lut, myImage);
}
if( eventData.eventIsFromWidget("darken")){
int[] lut = makeLUT("brighten", 0.5, 0.0);
outputImage = applyPointProcessing(lut, myImage);
}
if(myImage!=null){
if( eventData.eventIsFromWidget("contrast")){
int[] lut = makeLUT("sigmoid", 0.0, 0.0);
outputImage = applyPointProcessing(lut, myImage);
}
if( eventData.eventIsFromWidget("negative")){
int[] lut = makeLUT("negative", 0.0, 0.0);
outputImage = applyPointProcessing(lut, myImage);
}
if( eventData.eventIsFromWidget("greyscale")){
checkSize(myImage);
for (int y = 0; y < myImage.height; y++) {
for (int x = 0; x < myImage.width; x++) {
color c = myImage.get(x,y);
int r = (int)red(c);
int g = (int)green(c);
int b = (int)blue(c);
int grey = (int)(r+g+b)/3;
outputImage.set(x,y, color(grey,grey,grey));
}
}
}
if( eventData.eventIsFromWidget("edges")){
conv_filter(myImage,edge_matrix);
}
if( eventData.eventIsFromWidget("blur")){
conv_filter(myImage,blur_matrix);
}
if( eventData.eventIsFromWidget("sharpen")){
conv_filter(myImage,sharpen_matrix);
}
if( eventData.eventIsFromWidget("gaussianblur")){
checkSize(myImage);
for(int y = 0; y < myImage.width; y++){
for(int x = 0; x < myImage.height; x++){
color c = convolution(x, y, gaussianblur_matrix, 7, myImage);
outputImage.set(x,y,c);
}
}
}
if( eventData.eventIsFromWidget("undo")){
outputImage = myImage.copy();
checkSize(outputImage);
}
}
// if from a tool-mode button, the just set the current tool mode string
if(eventData.uiComponentType == "RadioButton"){
toolMode = eventData.uiLabel;
return;
}
// only canvas events below here! First get the mouse point
if(eventData.eventIsFromWidget("canvas")==false) return;
PVector p = new PVector(eventData.mousex, eventData.mousey);
// this next line catches all the tool shape-drawing modes
// so that drawing events are sent to the display list class only if the current tool
// is a shape drawing tool
if( toolMode.equals("rect") ||
toolMode.equals("ellipse") || toolMode.equals("circle") ||
toolMode.equals("line")) {
drawingList.handleMouseDrawEvent(toolMode,eventData.mouseEventType, p);
return;
}
// if the current tool is "select" then do this
if( toolMode.equals("select") ) {
drawingList.trySelect(eventData.mouseEventType, p);
}
}
int[] makeLUT(String functionName, float param1, float param2){
int[] lut = new int[256];
for(int n = 0; n < 256; n++) {
float p = n/255.0f; // p ranges between 0...1
float val = getValueFromFunction( p, functionName, param1, param2);
lut[n] = (int)(val*255);
}
return lut;
}
float getValueFromFunction(float inputVal, String functionName, float param1, float param2){
if(functionName.equals("brighten")){
return simpleScale(inputVal, param1);
}
if(functionName.equals("step")){
return step(inputVal, (int)param1);
}
if(functionName.equals("negative")){
return invert(inputVal);
}
if(functionName.equals("sigmoid")){
return sigmoidCurve(inputVal);
}
// should only get here is the functionName is undefined
return 0;
}
PImage applyPointProcessing(int[] LUT, PImage inputImage){
PImage outputImage = createImage(inputImage.width,inputImage.height,RGB);
checkSize(inputImage);
for (int y = 0; y < inputImage.height; y++) {
for (int x = 0; x < inputImage.width; x++) {
color c = inputImage.get(x,y);
int r = (int)red(c);
int g = (int)green(c);
int b = (int)blue(c);
int lutR = LUT[r];
int lutG = LUT[g];
int lutB = LUT[b];
outputImage.set(x,y, color(lutR,lutG,lutB));
}
}
return outputImage;
}
color convolution(int Xcen, int Ycen, float[][] matrix, int matrixsize, PImage myImage)
{
checkSize(myImage);
float rtotal = 0.0;
float gtotal = 0.0;
float btotal = 0.0;
int offset = matrixsize / 2;
// this is where we sample every pixel around the centre pixel
// according to the sample-matrix size
for (int i = 0; i < matrixsize; i++){
for (int j= 0; j < matrixsize; j++){
//
// work out which pixel are we testing
int xloc = Xcen+i-offset;
int yloc = Ycen+j-offset;
// Make sure we haven't walked off our image
if( xloc < 0 || xloc >= myImage.width) continue;
if( yloc < 0 || yloc >= myImage.height) continue;
// Calculate the convolution
color col = myImage.get(xloc,yloc);
rtotal += (red(col) * matrix[i][j]);
gtotal += (green(col) * matrix[i][j]);
btotal += (blue(col) * matrix[i][j]);
}
}
// Make sure RGB is within range
rtotal = constrain(rtotal, 0, 255);
gtotal = constrain(gtotal, 0, 255);
btotal = constrain(btotal, 0, 255);
// Return the resulting color
return color(rtotal, gtotal, btotal);
}
void keyPressed(){
if(key == BACKSPACE){
drawingList.deleteSelected();
}
}
|
import React, { useEffect } from 'react';
import { CssBaseline, Hidden, Drawer, Container } from '@material-ui/core';
import { useTheme } from '@material-ui/core/styles';
import { useState } from 'react';
import { useStyles } from './static/style';
import SideDrawer from './components/SideDrawer';
import MobileHeader from './components/MobileHeader';
import { useHistory, useLocation } from 'react-router';
import { isFullScreen, isNotPublicAndFullScreen, isPublic } from './tools/handler';
import { useMutation, useQuery } from 'react-apollo';
import { GET_USER, UPDATE_LOCAL_IS_ADMIN, UPDATE_LOCAL_IS_SPECIAL_TYPE } from '../configs/queries';
import { ADMIN_TYPE, NORMAL_USER_TYPE } from '../configs/variables';
export default function Root(props) {
const { pathname } = useLocation();
const history = useHistory();
const { window } = props;
const classes = useStyles();
const theme = useTheme();
const [mobileOpen, setMobileOpen] = useState(false);
const [user, setUser] = useState(null);
const { data, loading, error } = useQuery(GET_USER);
const [updateLocalIsSpecialType] = useMutation(UPDATE_LOCAL_IS_SPECIAL_TYPE);
const [updateLocalIsAdmin] = useMutation(UPDATE_LOCAL_IS_ADMIN);
useEffect(() => {
if (data) {
const user = data.getUser;
setUser(data.getUser);
if (user.type === ADMIN_TYPE) {
updateLocalIsAdmin().catch(() => {});
}
if (user.type !== NORMAL_USER_TYPE) {
updateLocalIsSpecialType().catch(() => {});
}
}
if (error) {
if (!isPublic(pathname)) history.push('/needsign');
}
}, [data, error, history, pathname, updateLocalIsAdmin, updateLocalIsSpecialType]);
const handleDrawerToggle = () => {
setMobileOpen(!mobileOpen);
};
const container = window !== undefined ? () => window().document.body : undefined;
return (
<>
{!loading &&
(isPublic(pathname) ? (
isFullScreen(pathname) ? (
<>{props.children}</>
) : (
<Container maxWidth="sm">{props.children}</Container>
)
) : (
user && (
<div className={classes.root}>
<CssBaseline />
<Hidden smUp implementation="css">
<MobileHeader
mobileOpen={mobileOpen}
setMobileOpen={setMobileOpen}
/>
</Hidden>
<nav className={classes.drawer} aria-label="menu">
<Hidden smUp implementation="css">
<Drawer
container={container}
variant="temporary"
anchor={theme.direction === 'rtl' ? 'right' : 'left'}
open={mobileOpen}
onClose={handleDrawerToggle}
classes={{
paper: classes.drawerPaper,
}}
ModalProps={{
keepMounted: true,
}}
>
<SideDrawer user={user} />
</Drawer>
</Hidden>
<Hidden xsDown implementation="css">
<Drawer
classes={{
paper: classes.drawerPaper,
}}
variant="permanent"
open
>
<SideDrawer user={user} />
</Drawer>
</Hidden>
</nav>
<main
className={
isNotPublicAndFullScreen(pathname)
? classes.fullScreen
: classes.content
}
>
<Hidden smUp implementation="css">
<div className={classes.toolbar} />
</Hidden>
{props.children}
</main>
</div>
)
))}
</>
);
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace AwfulGarbageMod.Items.Armor
{
// The AutoloadEquip attribute automatically attaches an equip texture to this item.
// Providing the EquipType.Body value here will result in TML expecting X_Arms.png, X_Body.png and X_FemaleBody.png sprite-sheet files to be placed next to the item's main texture.
[AutoloadEquip(EquipType.Body)]
public class AerogelBreastplate : ModItem
{
public override void SetStaticDefaults() {
base.SetStaticDefaults();
// DisplayName.SetDefault("Aerogel Breastplate");
// Tooltip.SetDefault("Increases ranged damage by 12% while in the air");
}
public override void SetDefaults() {
Item.width = 18; // Width of the item
Item.height = 18; // Height of the item
Item.value = Item.sellPrice(gold: 1); // How many coins the item is worth
Item.rare = ItemRarityID.Green; // The rarity of the item
Item.defense = 5; // The amount of defense the item will give when equipped
}
public override void UpdateEquip(Player player) {
if (player.velocity.Y != 0)
{
player.GetDamage(DamageClass.Ranged) += 0.12f;
}
}
// Please see Content/ExampleRecipes.cs for a detailed explanation of recipe creation.
public override void AddRecipes()
{
Recipe recipe = CreateRecipe();
recipe.AddIngredient(ItemID.Cloud, 25);
recipe.AddIngredient(ItemID.GoldBar, 6);
recipe.AddIngredient(ItemID.Gel, 18);
recipe.AddTile(TileID.Anvils);
recipe.Register();
Recipe recipe4 = CreateRecipe();
recipe4.AddIngredient(ItemID.Cloud, 25);
recipe4.AddIngredient(ItemID.Gel, 18);
recipe4.AddIngredient(ItemID.PlatinumBar, 6);
recipe4.AddTile(TileID.Anvils);
recipe4.Register();
}
}
}
|
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Button, Input, Table } from 'antd';
import { useEffect, useState } from 'react';
import TransactionDetail from './TransactionDetail';
import { useGetListTransaction } from '../../../hooks/api';
import { numberFormatter } from '../../../utils/formatter';
const baseColumns = [
{
title: 'Id',
dataIndex: 'id',
sorter: true,
width: 50,
},
{
title: 'Mã đơn hàng',
dataIndex: 'code',
sorter: true,
},
{
title: 'Ngày hoàn tất',
dataIndex: 'completedAt',
sorter: true,
},
{
title: 'Ngày thanh toán',
dataIndex: 'paidAt',
sorter: true,
},
{
title: 'Phương thức thanh toán',
dataIndex: 'paymentMethod',
sorter: true,
},
{
title: 'Tổng tiền',
dataIndex: 'totalPay',
sorter: true,
},
{
title: 'Thao tác',
dataIndex: 'action',
},
];
function transformData(dt, setIsDetailOpen) {
return dt?.map((item) => {
return {
key: item?.id,
id: item?.id,
code: item?.orderCode,
createdAt: new Date(item?.createdAt)?.toLocaleString(),
paidAt: item?.paidAt && new Date(item?.paidAt)?.toLocaleString(),
completedAt: item?.completedAt && new Date(item?.completedAt)?.toLocaleString(),
paymentMethod: item?.paymentMethod,
totalPay: numberFormatter(item?.totalPay),
action: (
<div className="action-btn flex gap-3">
<Button
className="text-blue-500 border border-blue-500"
onClick={() => setIsDetailOpen({ id: item?.id, isOpen: true })}
>
<FontAwesomeIcon icon={faSearch} />
</Button>
</div>
),
};
});
}
function Data({ params, setParams }) {
const [isDetailOpen, setIsDetailOpen] = useState({
id: 0,
isOpen: false,
});
const { data, isLoading } = useGetListTransaction(params);
const [tableParams, setTableParams] = useState({
pagination: {
current: params.page,
pageSize: params.size,
total: data?.data?.totalItems,
},
});
const [tdata, setTData] = useState([]);
useEffect(() => {
if (isLoading || !data) return;
let dt = transformData(data?.data?.items, setIsDetailOpen);
setTData(dt);
setTableParams({
...tableParams,
pagination: {
...tableParams.pagination,
total: data?.data?.totalItems,
},
});
}, [isLoading, data]);
const onSearch = (value) => {
setParams({
...params,
search: value,
});
};
const handleTableChange = (pagination, filters, sorter) => {
setTableParams({
...tableParams,
pagination,
...sorter,
});
setParams({
...params,
page: pagination.current,
size: pagination.pageSize,
columnName: !sorter.column ? 'id' : sorter.field,
isSortAscending: sorter.order === 'ascend' || !sorter.order ? true : false,
});
};
return (
<div>
<div className="search-container p-4 bg-white mb-3 flex items-center rounded-lg">
<Input.Search
className="xl:w-1/4 md:w-1/2"
allowClear
enterButton
placeholder="Nhập từ khoá tìm kiếm"
onSearch={onSearch}
/>
</div>
<Table
loading={isLoading}
scroll={{
x: 'max-content',
}}
columns={baseColumns}
dataSource={tdata}
pagination={{ ...tableParams.pagination, showSizeChanger: true }}
onChange={handleTableChange}
/>
{isDetailOpen.id !== 0 && (
<TransactionDetail isDetailOpen={isDetailOpen} setIsDetailOpen={setIsDetailOpen} />
)}
</div>
);
}
export default Data;
|
import emailService from "../services/EmailService/email.service";
import prisma from "../prisma";
export async function createOrGetUser({
email,
facebookId,
googleId,
}: {
email: string;
facebookId?: string;
googleId?: string;
}) {
const olderUser = await prisma.user.findUnique({ where: { email } });
if (
olderUser?.facebookId &&
facebookId &&
olderUser.facebookId !== facebookId
) {
// something weird is going on, maybe best to error to be on the safe side
throw new Error(
"User trying to log in with a different facebook account attached to the same email"
);
}
if (olderUser?.googleId && googleId && olderUser.googleId !== googleId) {
// something weird is going on, maybe best to error to be on the safe side
throw new Error(
"User trying to log in with a different google account attached to the same email"
);
}
const newerUser = await prisma.user.upsert({
create: {
email,
...(facebookId && { facebookId }),
...(googleId && { googleId }),
verifiedEmail: true,
},
update: {
verifiedEmail: true,
...(!olderUser?.facebookId && facebookId && { facebookId }),
...(!olderUser?.googleId && googleId && { googleId }),
},
where: {
email,
},
});
// the user can join the app in two ways:
// 1. they go to the website and sign up
// 2. they get an invite to an group/coll from someone (when invited,
// their User object is also created). that invite just
// links them to the group/coll . then the user signs up like in case 1.
// In both cases they end up here where we can send their welcome mail
// (note that they also end up here when simply signing in)
if (olderUser?.verifiedEmail !== newerUser.verifiedEmail) {
// if true then it's a new user
await emailService.welcomeEmail({ newUser: newerUser });
}
return newerUser;
}
|
import { useState, useEffect } from "react";
import { FaSearch } from "react-icons/fa";
import { Link } from "react-router-dom";
import { couponApi } from "../../../../service/coupon.service";
import { toast } from "react-toastify";
const Coupons = () => {
const [coupons, setCoupons] = useState([]);
const [searchKeyword, setSearchKeyword] = useState("");
const filteredCoupons = coupons.filter((coupon) => {
return coupon.code.toLowerCase().includes(searchKeyword.toLowerCase());
});
useEffect(() => {
const fetchData = async () => {
try {
const response = await couponApi.getCoupon();
setCoupons(response.data);
} catch (error) {
console.error("Error fetching coupons:", error);
}
};
fetchData();
}, []);
const handleHide = async (couponId) => {
const confirmHide = window.confirm(
"Are you sure you want to hide this coupon?"
);
if (confirmHide) {
try {
await couponApi.removeCoupon(couponId);
const updatedcoupons = coupons.filter(
(coupon) => coupon._id !== couponId
);
setCoupons(updatedcoupons);
toast.success("Hide coupon Successfully!!!");
} catch (error) {
console.error("Error hiding coupon:", error);
}
}
};
const handleSearch = (event) => {
setSearchKeyword(event.target.value);
};
return (
<>
<div className="flex flex-col md:flex-row justify-between items-center mt-5">
<div className="relative rounded-2xl border w-full md:w-[600px] h-[50px] text-base text-primeColor flex items-center gap-2 justify-between px-6 mb-4 md:mb-0">
<input
className="flex-1 h-full outline-none placeholder:text-[#C4C4C4] placeholder:text-[14px]"
type="text"
placeholder="Search your coupon here"
value={searchKeyword}
onChange={handleSearch}
/>
<FaSearch className="w-5 h-5 hover:cursor-pointer" />
</div>
<div className="flex items-center">
{" "}
<div className="ml-auto">
<Link to={"/admin/add-coupon"}>
<button
type="button"
className="w-50 p-2 bg-green-500 text-white rounded mr-20"
>
Add New Coupon
</button>
</Link>
</div>
</div>
</div>
<hr className="h-px my-8 bg-gray-200 border-0 dark:bg-gray-700"></hr>
<div className="relative overflow-x-auto shadow-md sm:rounded-lg">
<table className="w-full text-sm text-left rtl:text-center text-gray-500 dark:text-gray-400">
<thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr>
<th scope="col" className="px-6 py-3">
Coupon code
</th>
<th scope="col" className="px-6 py-3">
Description
</th>
<th scope="col" className="px-6 py-3">
ValidFrom
</th>
<th scope="col" className="px-6 py-3">
ValidUntil
</th>
<th scope="col" className="px-6 py-3">
Discount
</th>
{/* <th scope="col" className="px-6 py-3">
Status
</th> */}
<th scope="col" className="px-6 py-3">
<span className="">Action</span>
</th>
</tr>
</thead>
<tbody>
{filteredCoupons.map((coupon) => (
<tr
key={coupon._id}
className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
>
<th
scope="row"
className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white"
>
{coupon.code}
</th>
<td className="px-6 py-4">{coupon.description}</td>
<td className="px-6 py-4">
{new Date(coupon.validFrom).toLocaleDateString("en-US")}
</td>
<td className="px-6 py-4">
{new Date(coupon.validUntil).toLocaleDateString("en-US")}
</td>
<td className="px-6 py-4">{coupon.discountPercent * 100}%</td>
<td className="px-2 py-2">
<Link to={`/admin/edit-coupon/${coupon._id}`}>
<button className="font-medium text-blue-600 dark:text-blue-500">
Edit
</button>
</Link>
<button
onClick={() => handleHide(coupon._id)}
className="font-medium text-red-600 dark:text-blue-500 ml-3"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<hr className="h-px my-8 bg-gray-200 border-0 dark:bg-gray-700"></hr>
<nav
aria-label="Page navigation example "
className="flex items-center justify-center mt-4"
>
<ul className="flex space-x-2 md:space-x-4 text-base h-10">
<li>
<a
href="#"
className="flex items-center justify-center px-4 h-10 ms-0 leading-tight text-gray-500 bg-white border border-e-0 border-gray-300 rounded-s-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
>
Previous
</a>
</li>
<li>
<a
href="#"
className="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
>
1
</a>
</li>
<li>
<a
href="#"
className="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
>
2
</a>
</li>
<li>
<a
href="#"
aria-current="page"
className="flex items-center justify-center px-4 h-10 text-blue-600 border border-gray-300 bg-blue-50 hover:bg-blue-100 hover:text-blue-700 dark:border-gray-700 dark:bg-gray-700 dark:text-white"
>
3
</a>
</li>
<li>
<a
href="#"
className="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
>
4
</a>
</li>
<li>
<a
href="#"
className="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
>
5
</a>
</li>
<li>
<a
href="#"
className="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 rounded-e-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
>
Next
</a>
</li>
</ul>
</nav>
</>
);
};
export default Coupons;
|
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime
// inf2one returns a signed 1 if f is an infinity and a signed 0 otherwise.
// The sign of the result is the sign of f.
func inf2one(f float64) float64 {
g := 0.0
if isInf(f) {
g = 1.0
}
return copysign(g, f)
}
func complex128div(n complex128, m complex128) complex128 {
var e, f float64 // complex(e, f) = n/m
// Algorithm for robust complex division as described in
// Robert L. Smith: Algorithm 116: Complex division. Commun. ACM 5(8): 435 (1962).
if abs(real(m)) >= abs(imag(m)) {
ratio := imag(m) / real(m)
denom := real(m) + ratio*imag(m)
e = (real(n) + imag(n)*ratio) / denom
f = (imag(n) - real(n)*ratio) / denom
} else {
ratio := real(m) / imag(m)
denom := imag(m) + ratio*real(m)
e = (real(n)*ratio + imag(n)) / denom
f = (imag(n)*ratio - real(n)) / denom
}
if isNaN(e) && isNaN(f) {
// Correct final result to infinities and zeros if applicable.
// Matches C99: ISO/IEC 9899:1999 - G.5.1 Multiplicative operators.
a, b := real(n), imag(n)
c, d := real(m), imag(m)
switch {
case m == 0 && (!isNaN(a) || !isNaN(b)):
e = copysign(inf, c) * a
f = copysign(inf, c) * b
case (isInf(a) || isInf(b)) && isFinite(c) && isFinite(d):
a = inf2one(a)
b = inf2one(b)
e = inf * (a*c + b*d)
f = inf * (b*c - a*d)
case (isInf(c) || isInf(d)) && isFinite(a) && isFinite(b):
c = inf2one(c)
d = inf2one(d)
e = 0 * (a*c + b*d)
f = 0 * (b*c - a*d)
}
}
return complex(e, f)
}
|
---
title: "Cuadro de diálogo de configuración de tema (heredado) | Documentos de Microsoft"
ms.custom:
ms.date: 11/04/2016
ms.reviewer:
ms.suite:
ms.tgt_pltfrm:
ms.topic: reference
f1_keywords: System.Workflow.ComponentModel.Design.ThemeConfigurationDialog.UI
helpviewer_keywords:
- themes, configuring
- Theme Configuration dialog box
ms.assetid: 9e6d182a-c4d9-4e71-b2b9-02f675fc2b29
caps.latest.revision: "6"
author: ErikRe
ms.author: erikre
manager: erikre
ms.workload: multiple
ms.openlocfilehash: fad771da4643c68b3be08f778ca2db3b8e09c703
ms.sourcegitcommit: 32f1a690fc445f9586d53698fc82c7debd784eeb
ms.translationtype: MT
ms.contentlocale: es-ES
ms.lasthandoff: 12/22/2017
---
# <a name="theme-configuration-dialog-box-legacy"></a>Configuración de tema (Cuadro de diálogo) (Heredado)
Este tema se describe cómo utilizar el **configuración de tema** cuadro de diálogo heredado [!INCLUDE[wfd1](../workflow-designer/includes/wfd1_md.md)]. Use el [!INCLUDE[wfd2](../workflow-designer/includes/wfd2_md.md)] heredado cuando deba tener como destino [!INCLUDE[netfx35_long](../workflow-designer/includes/netfx35_long_md.md)] o [!INCLUDE[vstecwinfx](../workflow-designer/includes/vstecwinfx_md.md)].
Un tema define los colores de fondo y de primer plano, estilos, iconos y otros elementos visuales de un flujo de trabajo. Puede guardar los temas para volverlos a usar en otros flujos de trabajo.
Crear y modificar temas utilizando el **configuración de tema** cuadro de diálogo. Para abrir el cuadro de diálogo, seleccione **crear nuevo tema** en el **flujo de trabajo** menú o menú contextual del flujo de trabajo superficie de diseño y seleccione **crear nuevo tema**.
La tabla siguiente describen los elementos de interfaz de usuario de la **configuración de tema** cuadro de diálogo.
|Elemento de la interfaz de usuario|Descripción|
|----------------|-----------------|
|**Nombre del tema:**|El nombre que identifica el tema en el [temas, Diseñador de flujo de trabajo, cuadro de diálogo de opciones (heredado)](../workflow-designer/themes-workflow-designer-options-dialog-box-legacy.md). Para los temas nuevos se genera un nombre que se puede cambiar.|
|**Ubicación del tema:**|Nombre y ruta de acceso del archivo del tema. Para los nuevos temas se genera un nombre de archivo que se puede cambiar, basado en el nombre del tema generado. Si cambia el nombre del tema generado, puede que desee cambiar el nombre de archivo para que coincida con el nombre del tema.|
|**...**|Haga clic para seleccionar la ubicación para guardar el archivo de tema de flujo de trabajo, que utiliza la extensión de nombre de archivo .wtm. La ruta de acceso seleccionada se verá en el **ubicación del tema** cuadro de texto.|
|**Seleccione Diseñador y Configure propiedades:**|En el panel izquierdo se muestra una vista de árbol de las actividades para las que se puede personalizar el tema. Seleccione una actividad en la vista de árbol y se mostrarán las propiedades del tema para la actividad en el panel de propiedades, situado a la derecha del panel de vista del árbol. Haga clic en una propiedad para cambiar su valor.|
|**Vista previa**|Haga clic para mostrar una ventana con una vista previa de los efectos de los cambios realizados en la propiedad.|
## <a name="see-also"></a>Vea también
[Cuadro de diálogo de opciones de temas, Diseñador de flujo de trabajo (heredado)](../workflow-designer/themes-workflow-designer-options-dialog-box-legacy.md)
[Ayuda de la interfaz de usuario del diseñador heredado para Windows Workflow Foundation](../workflow-designer/legacy-designer-for-windows-workflow-foundation-ui-help.md)
|
$(document).ready(function() {
// Tax calculation function
function calculateTax(income, age) {
const exemptedIncome = 800000;
let taxableIncome = income - exemptedIncome;
let tax = 0;
if (taxableIncome <= 0) {
return 0;
}
if (age < 40) {
tax = taxableIncome * 0.3;
} else if (age >= 40 && age < 60) {
tax = taxableIncome * 0.4;
} else {
tax = taxableIncome * 0.1;
}
return tax;
}
// Form validation and submission
$('#taxForm').submit(function(e) {
e.preventDefault();
clearErrors();
const grossIncome = parseFloat($('#grossIncome').val().replace(/,/g, '')) || 0;
const extraIncome = parseFloat($('#extraIncome').val().replace(/,/g, '')) || 0;
const deductions = parseFloat($('#deductions').val().replace(/,/g, '')) || 0;
const ageGroup = $('#ageGroup').val();
let errors = false;
if (isNaN(grossIncome) || grossIncome < 0) {
showError('#grossIncomeError', 'Please enter a valid positive number');
errors = true;
}
if (isNaN(extraIncome) || extraIncome < 0) {
showError('#extraIncomeError', 'Please enter a valid positive number');
errors = true;
}
if (isNaN(deductions) || deductions < 0) {
showError('#deductionsError', 'Please enter a valid positive number');
errors = true;
}
if (ageGroup === '') {
showError('#ageGroupError', 'Age group is required');
errors = true;
}
if (!errors) {
const income = grossIncome + extraIncome - deductions;
let age;
switch (ageGroup) {
case '<40':
age = 30;
break;
case '>=40&<60':
age = 50;
break;
case '>=60':
age = 65;
break;
}
const tax = calculateTax(income, age);
const overall = income-tax;
$('#taxResult').text(`Your overall income will be ${overall.toFixed(2)}`);
$('#taxModal').modal('show');
}
});
// Clear error icons and tooltips
function clearErrors() {
$('.error-icon').text('').tooltip('dispose');
}
// Show error icon and tooltip
function showError(selector, message) {
$(selector)
.text('!')
.attr('data-toggle', 'tooltip')
.attr('title', message)
.tooltip('show')
.addClass('error-icon');
}
// Enable tooltips
$(function() {
$('[data-toggle="tooltip"]').tooltip();
});
});
|
import { z } from 'zod';
export const UserProfileSchema = z.object({
firstName: z.string().min(3, 'First Name is required').max(50, 'First Name must be between 2 and 50 characters'),
lastName: z.string().min(3, 'Last Name is required').max(50, 'Last Name must be between 2 and 50 characters'),
username: z.string().min(3, 'Username must be at least 3 characters long'),
email: z.string().email('Invalid email address').min(1, 'Email is required'),
password: z.string().min(8, 'Current Password is required'),
newPassword: z
.string()
.optional()
.refine((value) => {
if (!value) return true;
return value.length >= 8;
}, 'New Password must be at least 8 characters long')
.refine((value) => {
if (!value) return true;
return /(?=.*\d)(?=.*[A-Z])(?=.*[A-Z])(?=.*\W)/.test(value);
}, 'New Password must contain at least one number, one uppercase letter, and one special character'),
avatar: z.instanceof(File).optional(),
});
export type UserProfileFormValues = z.infer<typeof UserProfileSchema>;
|
import UIKit
import UnsplashPhotoPicker
class MainCoordinator: AbstractCoordinator {
// MARK: - Properties
var navigationController: UINavigationController
var coordinators: [AbstractCoordinator] = []
private let constants: Constants = Constants.shared
// MARK: - Init
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
// MARK: - Start
func start() {
assemble()
}
// MARK: - Private Functions
private func assemble() {
let mainViewModel = MainViewModel(mainService: MainService.shared, photoService: PhotoService.shared)
let mainView = MainViewController()
mainView.viewModel = mainViewModel
mainViewModel.setRandomPhotos()
mainViewModel.nextRoute = { route in
switch route {
case .unsplashPhotoPicker(let query):
let configuration = UnsplashPhotoPickerConfiguration(
accessKey: self.constants.accessKey,
secretKey: self.constants.secretKey,
query: query,
allowsMultipleSelection: true
)
let unsplashPhotoPicker = UnsplashPhotoPicker(configuration: configuration)
unsplashPhotoPicker.photoPickerDelegate = mainView
self.navigationController.present(unsplashPhotoPicker, animated: true)
case .detailScreen(let photo):
let detailViewModel = DetailViewModel(detailService: DetailService.shared, photoService: PhotoService.shared)
let detailView = DetailViewController()
detailView.viewModel = detailViewModel
detailView.isMainScreen = true
detailView.photo = photo
detailViewModel.getDetailInfo(photo: photo)
detailViewModel.dismissDetailViewControllerToMain = { [weak self] in
self?.navigationController.popViewController(animated: true)
}
self.navigationController.show(detailView, sender: self)
}
}
navigationController.show(mainView, sender: self)
}
}
|
import { expect, test } from "vitest";
import { generateTypeOverrideFromDocumentation } from "./generateTypeOverrideFromDocumentation";
test("finds a type override", () => {
const docString =
"this is some property \n here is the type override @kyselyType('admin' | 'member') ";
expect(generateTypeOverrideFromDocumentation(docString)).toEqual(
"'admin' | 'member'"
);
});
test("supports parentheses in type", () => {
const docString =
"this is some property \n here is the type override @kyselyType(('admin' | 'member')) ";
expect(generateTypeOverrideFromDocumentation(docString)).toEqual(
"('admin' | 'member')"
);
});
test("reacts correctly to unbalanced parens", () => {
const docString =
"this is some property \n here is the type override @kyselyType(('admin' | 'member') ";
expect(generateTypeOverrideFromDocumentation(docString)).toEqual(null);
});
test("reacts correctly to extra parens", () => {
const docString =
"this is some property \n here is the type override @kyselyType(('admin' | 'member'))) ";
expect(generateTypeOverrideFromDocumentation(docString)).toEqual(
"('admin' | 'member')"
);
});
test("finds type following incomplete one", () => {
const docString =
"this is some property \n here is the type @kyselyType( override @kyselyType('admin' | 'member') ";
expect(generateTypeOverrideFromDocumentation(docString)).toEqual(
"'admin' | 'member'"
);
});
test("doesn't do anything in case of no type", () => {
const docString = "this is some property with no override";
expect(generateTypeOverrideFromDocumentation(docString)).toEqual(null);
});
test("bails when we have an at sign and no match", () => {
const docString = "hit me up at [email protected]";
expect(generateTypeOverrideFromDocumentation(docString)).toEqual(null);
});
|
using System;
using System.Globalization;
using Jint.Native.Function;
using Jint.Native.Object;
using Jint.Runtime;
using Jint.Runtime.Interop;
namespace Jint.Native.Date
{
public sealed class DateConstructor : FunctionInstance, IConstructor
{
internal static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public DateConstructor(Engine engine) : base(engine, null, null, false)
{
}
public static DateConstructor CreateDateConstructor(Engine engine)
{
var obj = new DateConstructor(engine);
obj.Extensible = true;
// The value of the [[Prototype]] internal property of the Date constructor is the Function prototype object
obj.Prototype = engine.Function.PrototypeObject;
obj.PrototypeObject = DatePrototype.CreatePrototypeObject(engine, obj);
obj.FastAddProperty("length", 7, false, false, false);
// The initial value of Date.prototype is the Date prototype object
obj.FastAddProperty("prototype", obj.PrototypeObject, false, false, false);
return obj;
}
public void Configure()
{
FastAddProperty("parse", new ClrFunctionInstance(Engine, Parse, 1), true, false, true);
FastAddProperty("UTC", new ClrFunctionInstance(Engine, Utc, 7), true, false, true);
FastAddProperty("now", new ClrFunctionInstance(Engine, Now, 0), true, false, true);
}
private JsValue Parse(JsValue thisObj, JsValue[] arguments)
{
DateTime result;
var date = TypeConverter.ToString(arguments.At(0));
if (!DateTime.TryParseExact(date, new[]
{
"yyyy/MM/ddTH:m:s.fff",
"yyyy/MM/dd",
"yyyy/MM",
"yyyy-MM-ddTH:m:s.fff",
"yyyy-MM-dd",
"yyyy-MM",
"yyyy",
"THH:m:s.fff",
"TH:mm:sm",
"THH:mm",
"THH"
}, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out result))
{
if (!DateTime.TryParseExact(date, new[]
{
"yyyy/MM/ddTH:m:s.fffK",
"yyyy/MM/ddK",
"yyyy/MMK",
"yyyy-MM-ddTH:m:s.fffK",
"yyyy-MM-ddK",
"yyyy-MMK",
"yyyyK",
"THH:m:s.fffK",
"TH:mm:smK",
"THH:mmK",
"THHK"
}, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result))
{
if (!DateTime.TryParse(date, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal,out result))
{
throw new JavaScriptException(Engine.SyntaxError, "Invalid date");
}
}
}
return Construct(result);
}
private JsValue Utc(JsValue thisObj, JsValue[] arguments)
{
var local = (DateInstance) Construct(arguments);
return local.PrimitiveValue;
}
private JsValue Now(JsValue thisObj, JsValue[] arguments)
{
return (DateTime.UtcNow - Epoch).TotalMilliseconds;
}
public override JsValue Call(JsValue thisObject, JsValue[] arguments)
{
return PrototypeObject.ToString(Construct(Arguments.Empty), Arguments.Empty);
}
/// <summary>
/// http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3
/// </summary>
/// <param name="arguments"></param>
/// <returns></returns>
public ObjectInstance Construct(JsValue[] arguments)
{
if (arguments.Length == 0)
{
return Construct(DateTime.Now);
}
else if (arguments.Length == 1)
{
var v = TypeConverter.ToPrimitive(arguments[0]);
if (v.IsString())
{
return Parse(Undefined.Instance, Arguments.From(v)).AsObject();
}
return Construct(DatePrototype.TimeClip(TypeConverter.ToNumber(v)));
}
else
{
var y = TypeConverter.ToNumber(arguments[0]);
var m = (int)TypeConverter.ToInteger(arguments[1]);
var dt = arguments.Length > 2 ? (int)TypeConverter.ToInteger(arguments[2]) : 1;
var h = arguments.Length > 3 ? (int)TypeConverter.ToInteger(arguments[3]) : 0;
var min = arguments.Length > 4 ? (int)TypeConverter.ToInteger(arguments[4]) : 0;
var s = arguments.Length > 5 ? (int)TypeConverter.ToInteger(arguments[5]) : 0;
var milli = arguments.Length > 6 ? (int)TypeConverter.ToInteger(arguments[6]) : 0;
for (int i = 2; i < arguments.Length; i++)
{
if (double.IsNaN(TypeConverter.ToNumber(arguments[i])))
{
return Construct(double.NaN);
}
}
if ((!double.IsNaN(y)) && (0 <= TypeConverter.ToInteger(y)) && (TypeConverter.ToInteger(y) <= 99))
{
y += 1900;
}
var finalDate = DatePrototype.MakeDate(DatePrototype.MakeDay(y, m, dt),
DatePrototype.MakeTime(h, min, s, milli));
return Construct(DatePrototype.TimeClip(DatePrototype.Utc(finalDate)));
}
}
public DatePrototype PrototypeObject { get; private set; }
public DateInstance Construct(DateTimeOffset value)
{
return Construct(value.UtcDateTime);
}
public DateInstance Construct(DateTime value)
{
var instance = new DateInstance(Engine)
{
Prototype = PrototypeObject,
PrimitiveValue = FromDateTime(value),
Extensible = true
};
return instance;
}
public DateInstance Construct(double time)
{
var instance = new DateInstance(Engine)
{
Prototype = PrototypeObject,
PrimitiveValue = TimeClip(time),
Extensible = true
};
return instance;
}
public static double TimeClip(double time)
{
if (double.IsInfinity(time) || double.IsNaN(time))
{
return double.NaN;
}
if (System.Math.Abs(time) > 8640000000000000)
{
return double.NaN;
}
return TypeConverter.ToInteger(time);
}
public static double FromDateTime(DateTime dt)
{
return System.Math.Floor((dt.ToUniversalTime() - Epoch).TotalMilliseconds);
}
}
}
|
package main
import (
"bytes"
"fmt"
"io"
"net"
"net/http"
"testing"
"time"
"github.com/awoodbeck/gnp/ch09/handlers"
)
func TestSimpleHTTPServer(t *testing.T) {
// http 서버 객체 생성
srv := &http.Server{
// 서버 주소 및 포트
Addr: "127.0.0.1:8081",
// 입출력 핸들러 함수 및 대기 제한시간 2분이 지나면
// 3번째 인수로 넣은 에러 메세지를 바디로 하여 503 에러 리턴
Handler: http.TimeoutHandler(
handlers.DefaultHandler(), 2*time.Minute, ""),
// 작업이 없는 동안 대기시간 5분
IdleTimeout: 5 * time.Minute,
// 서버로 보내는 요청헤더를 읽는데 1분 제한
// 서버에 느리게 데이터를 보내 서버 연결을 점유하는 slowloris 공격 방지
ReadHeaderTimeout: time.Minute,
}
// tcp 서버 리스너 생성
l, err := net.Listen("tcp", srv.Addr)
if err != nil {
t.Fatal(err)
}
// 고루틴 생성
go func() {
// 객체와 리스너를 바탕으로 실제 http 서버 시작
err := srv.Serve(l)
if err != http.ErrServerClosed {
t.Error(err)
}
}()
// 테스트 해볼 케이스들
testCases := []struct {
method string
body io.Reader
code int
response string
}{
//
{http.MethodGet, nil, http.StatusOK, "Hello, friend!"},
{http.MethodPost, bytes.NewBufferString("<world>"), http.StatusOK, "Hello, <world>!"},
{http.MethodHead, nil, http.StatusMethodNotAllowed, ""},
}
// http 클라이언트 생성
client := new(http.Client)
// "http://서버 아이피/"로 연결할 경로 변수 생성
path := fmt.Sprintf("http://%s/", srv.Addr)
for i, c := range testCases {
// 테스트 케이스의 메서드로 서버 아이피로 바디와 함께 요청 생성
r, err := http.NewRequest(c.method, path, c.body)
if err != nil {
t.Errorf("%d: %v", i, err)
// 요청 중에 에러가 있어도 다음 케이스 실행
continue
}
// 위에서 만든 요청을 가지고
// 테스트 서버에 실제로 요청을 날린 뒤
// 응답을 받아 resp 변수에 저장
resp, err := client.Do(r)
if err != nil {
t.Errorf("%d: %v", i, err)
continue
}
// 상태코드가 테스트 케이스의 것과 다르면
if resp.StatusCode != c.code {
// 에러 뿌리기
t.Errorf("%d: unexpected status code: %q", i, resp.Status)
}
// 응답 바디를 모두 읽은 뒤
// 변수 b에 저장하고
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("%d: %v", i, err)
continue
}
// 바디 닫기
_ = resp.Body.Close()
// 테스트 케이스의 응답과 실제 응답이 다르면
if c.response != string(b) {
// 에러 뿌리기
t.Errorf("%d: expected %q; actual %q", i, c.response, b)
}
}
// 테스트가 모두 끝났으니 서버 닫기
if err := srv.Close(); err != nil {
// 서버 닫기 실패 시 테스트 실패
t.Fatal(err)
}
}
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { CourseType } from 'src/interfaces/course.interface';
import { applyInstructor } from './instructor.action';
import { InstructorIntialStateType } from './instructor.interface';
const initialState: InstructorIntialStateType = {
isLoading: false,
error: null,
courses: [],
course: null,
};
export const instructorSlice = createSlice({
name: 'instructor',
initialState,
reducers: {
clearInstructorError: state => {
state.error = null;
},
instructorAllCourses: (state, action: PayloadAction<CourseType[]>) => {
state.courses = action.payload;
},
instructorDetailedCourse: (state, action: PayloadAction<CourseType>) => {
state.course = action.payload;
},
},
extraReducers: builder => {
builder
.addCase(applyInstructor.pending, state => {
state.isLoading = true;
state.error = null;
})
.addCase(applyInstructor.fulfilled, state => {
state.isLoading = false;
state.error = null;
})
.addCase(applyInstructor.rejected, (state, { payload }) => {
state.isLoading = false;
state.error = payload;
});
},
});
export const instructorReducer = instructorSlice.reducer;
export const instructorSliceAction = instructorSlice.actions;
|
import React from 'react'
interface props {
Icon: any;
title: string;
selected?: boolean;
}
export default function HeaderOption({ Icon, title, selected }: props) {
return (
<div
className={`flex items-center space-x-1
border-b-4 border-transparent
hover:text-blue-500 hover:border-blue-500
pb-3 cursor-pointer
${selected && 'text-blue-500 border-blue-500'}`}>
<Icon className='h-4' />
<p className='hidden sm:inline-flex'>{title}</p>
</div>
)
}
|
from asyncore import write
import email
from .models import User
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
username = serializers.CharField()
email = serializers.CharField()
birthdate = serializers.DateField()
first_name = serializers.CharField()
last_name = serializers.CharField()
bio = serializers.CharField(allow_null=True, allow_blank=True, default=None)
password = serializers.CharField(write_only=True)
is_critic = serializers.BooleanField(allow_null=True, default=False)
updated_at = serializers.DateTimeField(read_only=True)
is_superuser = serializers.BooleanField(read_only=True, default=False)
def validate_username(self, value: int):
if User.objects.filter(username=value).exists():
raise serializers.ValidationError('username already exists')
return value
def validate_email(self, value: int):
if User.objects.filter(email=value).exists():
raise serializers.ValidationError('email already exists')
return value
def create(self, validated_data):
user = User.objects.create(**validated_data)
user.set_password(user.password)
user.save()
return user
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(write_only=True)
password = serializers.CharField(write_only=True)
|
function data = elbeat(data)
% Identify beats from EKG data and calculate running average of BPM
%
% The input "data" is a structure generated by running an Edulogger experiment,
% consisting of the following fields:
% Time: The time (s) since the start of the experiment of each sample.
% (double)
% Concern: Whether or not each sample took more than twice the specified
% sample rate to retrieve (logical)
% EKG: Raw electrodermal data from a GSR edulogger (double)
% An additional field for each kind of Edulogger used, containing the
% measurements taken at each point in data.Time.
%
% The output "data" is the same structure which was inputted, with two
% fields added:
% BeatApex: Indicating whether or not the datapoint was the apex of a heartbeat (logical)
% BPM: A running average of beats per minute
if ~isfield(data, 'EKG') % If data does not have a column called "EKG"...
error("Data does not contain EKG data") % Deliver an error
end
sps = elsps(data); % From data, estimate sps which was used
tonic = smooth([data.EKG], sps, 'moving'); % Use a moving smooth method with a span of 1 second to extract tonic signal
phasic = [data.EKG]' - tonic; % Subtract tonic signal from raw data to get phasic signal
beats = islocalmax(abs(phasic), 'FlatSelection', 'center', 'MinSeparation', round(sps/2)); % Identify apex point of each beat (local peaks within 0.5s range)
beatdiffs = diff([ 0 data(beats).Time ]); % Get matrix of time difference between each beat
bpm = 60./smooth(beatdiffs); % Smooth and convert to beats per minute
for n = 1:length(data) % For each data point...
data(n).BeatApex = beats(n); % Store whether or not it was the apex point of a beat
[~, i] = min(abs( n - find(beats) )); % Find index of closest peak
data(n).BPM = bpm(i); % Store BPM for closest beat
end
|
"""
Week 7: Make grids of IGRF
"""
import datetime
import numpy as np
import xarray as xr
import verde as vd
import pygmt
import igrf
def igrf_grid(region, spacing, height, date):
"""
Make a grid of Bx, By, Bz at a uniform height.
"""
longitude, latitude = vd.grid_coordinates(region, spacing=spacing, meshgrid=False)
shape = (latitude.size, longitude.size)
be = np.zeros(shape)
bn = np.zeros(shape)
bu = np.zeros(shape)
for i, lat in enumerate(latitude):
for j, lon in enumerate(longitude):
be_point, bn_point, bu_point = igrf.igrf(lon, lat, height, date)
be[i, j] = be_point
bn[i, j] = bn_point
bu[i, j] = bu_point
dims = ("latitude", "longitude")
grid = xr.Dataset(
{
"be": (dims, be),
"bn": (dims, bn),
"bu": (dims, bu),
},
coords={"longitude": longitude, "latitude": latitude},
)
return grid
if __name__ == "__main__":
grid = igrf_grid((0, 360, -90, 90), spacing=3, height=1000, date=datetime.datetime.today())
print(grid)
grid["amplitude"] = np.sqrt(grid.be**2 + grid.bn**2 + grid.bu**2)
fig = pygmt.Figure()
fig.grdimage(grid.amplitude, projection="W0/20c", cmap="viridis", frame=True)
fig.colorbar()
fig.coast(shorelines=True)
fig.show()
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <set>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
#define LOG_TAG "SwappyTestMain"
#include <jni.h>
#include "../../samples/common/include/Log.h"
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestCase;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;
namespace {
static JNIEnv* s_env = 0;
static jobject s_context = 0;
// Record the output of googletest tests
class GTestRecorder : public EmptyTestEventListener {
std::set<std::string> tests_started;
std::set<std::string> tests_completed;
std::set<std::string> tests_failed;
std::vector<std::string> success_invocations; // Only from SUCCESS macros
std::vector<std::string>
failed_invocations; // From any failed EXPECT or ASSERT
bool overall_success;
std::string current_test;
private:
// Called before any test activity starts.
void OnTestProgramStart(const UnitTest& /* unit_test */) override {
overall_success = false;
}
// Called after all test activities have ended.
void OnTestProgramEnd(const UnitTest& unit_test) override {
overall_success = unit_test.Passed();
}
// Called before a test starts.
void OnTestStart(const TestInfo& test_info) override {
current_test =
std::string(test_info.test_case_name()) + "." + test_info.name();
tests_started.insert(current_test);
ALOGI("TestStarted: %s", current_test.c_str());
}
// Called after a failed assertion or a SUCCEED() invocation.
void OnTestPartResult(const TestPartResult& test_part_result) override {
std::stringstream record;
record << current_test << " " << test_part_result.file_name() << ":"
<< test_part_result.line_number() << '\n'
<< test_part_result.summary() << '\n';
if (test_part_result.failed()) {
failed_invocations.push_back(record.str());
tests_failed.insert(current_test);
ALOGI("TestFailed: %s\n%s", current_test.c_str(),
record.str().c_str());
} else {
success_invocations.push_back(record.str());
}
}
// Called after a test ends.
void OnTestEnd(const TestInfo& test_info) override {
tests_completed.insert(std::string(test_info.test_case_name()) + "." +
test_info.name());
}
public:
std::string GetResult() const {
std::stringstream result;
result << "TESTS " << (overall_success ? "SUCCEEDED" : "FAILED")
<< '\n';
result << "\nTests that ran to completion:\n";
for (auto s : tests_completed) {
result << s << '\n';
}
std::set<std::string> not_completed;
std::set_difference(tests_started.begin(), tests_started.end(),
tests_completed.begin(), tests_completed.end(),
std::inserter(not_completed, not_completed.end()));
if (not_completed.size() > 0) {
result << "\nTests that started but failed to complete:\n";
for (auto s : not_completed) {
result << s << '\n';
}
}
if (!tests_failed.empty()) {
result << "\nFailed tests:\n";
for (auto s : tests_failed) result << s << '\n';
}
if (!success_invocations.empty()) {
result << "\nExplicitly recorded successes:\n";
for (auto s : success_invocations) result << s << '\n';
}
if (!failed_invocations.empty()) {
result << "\nFailure details:\n";
for (auto s : failed_invocations) result << s << '\n';
}
return result.str();
}
std::string Summary() const {
std::stringstream str;
str << "Running:\n" << current_test << '\n';
str << "\nCompleted:\n";
for (auto& i : tests_completed) {
str << i << '\n';
}
str << "\nFailed:\n";
for (auto& i : failed_invocations) {
str << i << '\n';
}
return str.str();
}
}; // class GTestRecorder
} // namespace
static std::shared_ptr<GTestRecorder> s_recorder;
extern "C" size_t test_summary(char* result, size_t len) {
if (s_recorder.get()) {
auto s = s_recorder->Summary();
auto sz = std::min(len, s.size());
strncpy(result, s.c_str(), sz);
return sz;
} else
return 0;
}
extern "C" int shared_main(int argc, char* argv[], JNIEnv* env, jobject context,
std::string& messages) {
::testing::InitGoogleTest(&argc, argv);
// Set up Java env
s_env = env;
s_context = context;
// Set up result recorder
UnitTest& unit_test = *UnitTest::GetInstance();
TestEventListeners& listeners = unit_test.listeners();
delete listeners.Release(listeners.default_result_printer());
s_recorder = std::make_shared<GTestRecorder>();
listeners.Append(s_recorder.get());
// Run tests
int result = RUN_ALL_TESTS();
messages = s_recorder->GetResult();
return result;
}
|
<?php
//
// Description
// This method will update a message in the database.
//
// Arguments
// ---------
// api_key:
// auth_token:
// tnid: The ID of the tenant the message is attached to.
//
// Returns
// -------
// <rsp stat='ok' />
//
function ciniki_fatt_messageUpdate(&$ciniki) {
//
// Find all the required and optional arguments
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'prepareArgs');
$rc = ciniki_core_prepareArgs($ciniki, 'no', array(
'tnid'=>array('required'=>'yes', 'blank'=>'no', 'name'=>'Tenant'),
'message_id'=>array('required'=>'yes', 'blank'=>'no', 'name'=>'Location'),
'object'=>array('required'=>'no', 'blank'=>'no', 'name'=>'Object'),
'object_id'=>array('required'=>'no', 'blank'=>'no', 'name'=>'Object ID'),
'status'=>array('required'=>'no', 'blank'=>'no', 'validlist'=>array('0', '10', '20'), 'name'=>'Status'),
'days'=>array('required'=>'no', 'blank'=>'yes', 'name'=>'Days'),
'subject'=>array('required'=>'no', 'blank'=>'yes', 'name'=>'Subject'),
'message'=>array('required'=>'no', 'blank'=>'yes', 'name'=>'Message'),
'parent_subject'=>array('required'=>'no', 'blank'=>'yes', 'name'=>'Parent Subject'),
'parent_message'=>array('required'=>'no', 'blank'=>'yes', 'name'=>'Parent Message'),
));
if( $rc['stat'] != 'ok' ) {
return $rc;
}
$args = $rc['args'];
//
// Make sure this module is activated, and
// check permission to run this function for this tenant
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'fatt', 'private', 'checkAccess');
$rc = ciniki_fatt_checkAccess($ciniki, $args['tnid'], 'ciniki.fatt.messageUpdate');
if( $rc['stat'] != 'ok' ) {
return $rc;
}
//
// Start transaction
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbTransactionStart');
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbTransactionRollback');
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbTransactionCommit');
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbAddModuleHistory');
$rc = ciniki_core_dbTransactionStart($ciniki, 'ciniki.fatt');
if( $rc['stat'] != 'ok' ) {
return $rc;
}
//
// Update the message in the database
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'objectUpdate');
$rc = ciniki_core_objectUpdate($ciniki, $args['tnid'], 'ciniki.fatt.message', $args['message_id'], $args, 0x04);
if( $rc['stat'] != 'ok' ) {
ciniki_core_dbTransactionRollback($ciniki, 'ciniki.fatt');
return $rc;
}
//
// Commit the transaction
//
$rc = ciniki_core_dbTransactionCommit($ciniki, 'ciniki.fatt');
if( $rc['stat'] != 'ok' ) {
return $rc;
}
//
// Update the last_change date in the tenant modules
// Ignore the result, as we don't want to stop user updates if this fails.
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'tenants', 'private', 'updateModuleChangeDate');
ciniki_tenants_updateModuleChangeDate($ciniki, $args['tnid'], 'ciniki', 'fatt');
return array('stat'=>'ok');
}
?>
|
import 'package:flutter/material.dart';
import 'package:task_hyd/models/task_model.dart';
import 'package:task_hyd/repos/task_repos.dart';
import 'package:velocity_x/velocity_x.dart';
class HomeBody extends StatelessWidget {
// final TaskModel? taskModel;
const HomeBody({
super.key,
// required this.taskModel,
});
@override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
FutureBuilder<List<TaskModel>>(
future: techs(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
final tasks = snapshot.data!;
return ListView.separated(
separatorBuilder: (context, index) => 12.heightBox,
shrinkWrap: true,
primary: false,
itemCount: tasks.length,
itemBuilder: (context, index) {
return ListTile(
tileColor: Colors.grey[200],
title: Text('ID: ${tasks[index].id}'),
subtitle: Text('Column 1: ${tasks[index].column1}'),
);
},
);
}
},
),
],
).p12(),
),
);
}
}
|
import Image from "next/image";
import { FaStar, FaCodeBranch, FaEye } from "react-icons/fa";
const fetchRepo = async (name) => {
const response = await fetch(
`https://api.github.com/repos/dazzlerabhi30800/${name}`,
{
next: { revalidate: 60 },
}
);
const repo = await response.json();
return repo;
};
const CurrentRepo = async ({ name }) => {
const repo = await fetchRepo(name);
return (
<div>
<h1>{repo.name}</h1>
<p style={{ margin: "5px 0" }}>Repo name :- {repo.full_name}</p>
<span style={{ display: "block", margin: "8px 0" }}>
Full Name :- {repo.owner.login}
</span>
<div className="details--container">
<Image
unoptimized
style={{ borderRadius: "10px", margin: "8px 0" }}
src={repo.owner.avatar_url}
width={50}
height={50}
alt={repo.name}
/>
<div className="details--list">
<span>
<FaStar /> {repo.stargazers_count}
</span>
<span>
<FaCodeBranch /> {repo.forks_count}
</span>
<span>
<FaEye /> {repo.watchers_count}
</span>
</div>
</div>
</div>
);
};
export default CurrentRepo;
|
package biz.belcorp.salesforce.modules.developmentpath.core.data.repository.salesconsultant.dto.co
import biz.belcorp.salesforce.core.constants.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import biz.belcorp.salesforce.core.utils.JsonUtil.JsonEncodedDefault
@Serializable
class TopSalesCoParams(
@SerialName(KEY_COUNTRY)
var country: String = Constant.EMPTY_STRING,
@SerialName(KEY_CAMPAIGN)
var campaigns: List<String> = emptyList(),
@SerialName(KEY_CONSULTANT_CODE)
var consultantCode: String = Constant.EMPTY_STRING,
@SerialName(KEY_REGION)
var region: String = Constant.EMPTY_STRING,
@SerialName(KEY_ZONE)
var zone: String = Constant.EMPTY_STRING,
@SerialName(KEY_SECTION)
var section: String = Constant.EMPTY_STRING
) {
fun toJson(): String {
return JsonEncodedDefault.encodeToString(serializer(), this)
}
}
|
//
// EpisodeDetailViewModel.swift
// RickAndMortyAPI
//
// Created by Tuğrul Özpehlivan on 24.02.2023.
//
import Foundation
protocol EpisodeDetailViewModelInterface {
var view: EpisodeDetailViewInterface? { get set }
func viewDidLoad()
func getCharacters()
}
final class EpisodeDetailViewModel {
weak var view: EpisodeDetailViewInterface?
var characters = [Character]()
}
extension EpisodeDetailViewModel: EpisodeDetailViewModelInterface {
func viewDidLoad() {
getCharacters()
view?.episodeDetailViewConfigure()
view?.episodeInfoCardConfigure()
view?.episodeCharactersLabelConfigure()
view?.collectionViewConfigure()
}
func getCharacters() {
guard let list = view?.episode?.characters else { return }
var strings = ""
for x in list {
strings += "\(x.dropFirst(42)),"
}
if strings != "" {
strings.removeLast()
}
print(strings)
APIManager.shared.getMultipleCharacters(query: strings) { [weak self] result in
DispatchQueue.main.async {
switch result {
case .success(let model):
self?.characters.removeAll()
self?.characters = model
self?.view?.reloadCollectionView()
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
}
|
import styled from "styled-components";
import { darken } from "polished";
import Link from "next/link";
import Image from "next/image";
import {
Flex,
FlexBetween,
FlexCenter,
FlexColumn,
FlexStart,
} from "../styles";
import { Text } from "../text";
import { PrimaryButton } from "../button";
import { InfoIcon } from "../icons";
import media from "../theme/media";
import { GradientAvatar } from "../identicon";
const Wrapper = styled(FlexCenter)`
position: relative;
min-height: calc(100vh - 7rem);
padding-top: 2rem;
`;
const HeroBackdrop = styled(Flex)<{ bg?: string }>`
position: absolute;
width: 100%;
height: 100%;
background: ${({ theme, bg }) =>
`${theme.bg100} url(${bg}) center center/cover no-repeat border-box border-box fixed`};
filter: blur(0.4rem);
opacity: 0.2;
mask: linear-gradient(white, transparent);
z-index: -1;
`;
const Row = styled(Flex)`
flex-wrap: wrap;
margin-right: auto;
margin-left: auto;
& > div:nth-child(2) {
align-items: flex-end;
}
${media.tabletL`
flex-direction: column;
align-items: center;
& > div {
max-width: 100%;
align-items: center;
margin-top: 2rem;
text-align: center;
}
& > div:nth-child(2) {
align-items: center;
}
`};
`;
const Column = styled(FlexColumn)`
width: 100%;
max-width: calc(50% - 0.5rem);
padding: 0rem 2rem;
justify-content: center;
`;
const Title = styled(Text)`
font-size: 3rem;
color: ${({ theme }) => theme.text300};
font-weight: 600;
text-align: left;
line-height: 1.2;
${media.tabletL`
text-align: center;
`};
`;
const SubTitle = styled(Text)`
font-size: 1.5rem;
margin-top: 1.5rem;
text-align: left;
${media.tabletL`
text-align: center;
`};
`;
const ButtonGroup = styled(FlexStart)`
margin-top: 2rem;
& > button:first-child {
margin-right: 1rem;
}
`;
const ExploreButton = styled(PrimaryButton)`
width: 10rem;
font-weight: 600;
margin-right: 1rem;
`;
const CreateButton = styled(ExploreButton)`
background-color: transparent;
border-color: ${({ theme }) => theme.bg700};
:hover {
background-color: ${({ theme }) => theme.bg700};
}
`;
const FeaturedCard = styled(FlexColumn)`
position: relative;
width: 100%;
height: 100%;
max-width: 34rem;
border-radius: 1rem;
overflow: hidden;
`;
const FeaturedImage = styled(FlexColumn)`
position: relative;
width: 100%;
min-height: 26rem;
height: 100%;
background-color: ${({ theme }) => theme.bg100};
`;
const FeaturedProfile = styled(Flex)`
padding: 1rem;
background-color: ${({ theme }) => theme.bg100};
z-index: 2;
`;
const ProfileDetails = styled(FlexColumn)`
margin-left: 0.5rem;
`;
const ProfileImage = styled(Image)`
border-radius: 50%;
border: 0.5rem solid ${({ theme }) => theme.primary100};
`;
const StyledLink = styled.a`
font-size: 0.875rem;
font-weight: 600;
color: ${({ theme }) => theme.text300};
text-decoration: none;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
transition: color 0.3s ease-in-out;
:hover {
color: ${({ theme }) => darken(0.2, theme.text300)};
}
`;
const ProfileLink = styled(StyledLink)`
color: ${({ theme }) => theme.primary100};
:hover {
color: ${({ theme }) => darken(0.2, theme.primary100)};
}
`;
export const HomeHero = () => {
return (
<Wrapper>
<Row>
<Column>
<Title>Discover, collect, and sell extraordinary NFTs</Title>
<SubTitle>
CassavaLand is the best platform to create, showcase and market NFTs
across multiple blockchains.
</SubTitle>
<ButtonGroup>
<Link href="/collections">
<ExploreButton>Explore</ExploreButton>
</Link>
<Link href="/create">
<CreateButton>Create</CreateButton>
</Link>
</ButtonGroup>
</Column>
<Column>
<FeaturedCard>
<FeaturedImage>
<Link
href="/assets/1287/0x2aa213d093cb0c0f7d3a5aceaf3bcff3c1d8f6a0/1"
passHref
>
<StyledLink>
<Image src="/gorilla.jpg" layout="fill" objectFit="cover" />
</StyledLink>
</Link>
</FeaturedImage>
<FeaturedProfile>
<Link href="/cassavaboy" passHref>
<StyledLink style={{ overflow: "unset" }}>
{/* <ProfileImage
width={48}
height={48}
src="/gorilla.jpg"
alt="featured"
/> */}
<GradientAvatar
seed="0x51685d226F643814EC3081593f0753CC8b2C38D1"
size={48}
/>
</StyledLink>
</Link>
<FlexBetween full>
<ProfileDetails>
<Link
href="/assets/1287/0x2aa213d093cb0c0f7d3a5aceaf3bcff3c1d8f6a0/1"
passHref
>
<StyledLink>Gorilla#38</StyledLink>
</Link>
<Link href="/cassavaboy" passHref>
<ProfileLink>The hankees</ProfileLink>
</Link>
</ProfileDetails>
<InfoIcon size={24} />
</FlexBetween>
</FeaturedProfile>
</FeaturedCard>
</Column>
</Row>
<HeroBackdrop bg="/gorilla.jpg" />
</Wrapper>
);
};
|
package com.javalex.ex;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FormEx
*/
@WebServlet("/FormEx")
public class FormEx extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public FormEx() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.setCharacterEncoding("EUC-KR");
String name = request.getParameter("name");
String id = request.getParameter("id");
String pw = request.getParameter("pw");
String hobbys[] = request.getParameterValues("hobby");
String major = request.getParameter("major");
String protocol = request.getParameter("protocol");
request.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
writer.println("<html><head></head><body>");
writer.println("이름: "+name+"<br>");
writer.println("아이디: "+id+"<br>");
writer.println("비밀번호: "+pw+"<br>");
writer.println("취미: " + Arrays.toString(hobbys)+"<br>");
writer.println("전공: "+major+"<br>");
writer.println("프로토콜"+protocol);
writer.println("</body></html>");
writer.close();
}
}
|
---
import alien from "/images/symbols/alien.svg";
import "../styles/global.css";
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/icons/Icon.jpg" type="image/svg+xml" />
<title>Fin du jeu</title>
</head>
<body>
<div class="container">
<object type="image/svg+xml" data="" id="random-svg"></object>
<h1 id="end-game-message">Fin du jeu</h1>
<h2 id="end-game-info">
<!-- Les informations de fin de jeu seront ajoutées ici -->
<span>Résultat:</span>
</h2>
<div class="button-flex">
<button id="restart-button">Réessayer</button>
<button id="account-button">Mon Profil</button>
</div>
</div>
<script>
// Array contenant les chemins vers les SVG
const svgs = [
"/images/symbols/alien.svg",
"/images/symbols/goal.svg",
"/images/symbols/grave.svg",
"/images/symbols/robot.svg",
"/images/symbols/ovni.svg",
"/images/symbols/hand.svg",
"/images/symbols/story/battery.svg",
"/images/symbols/story/walle.svg",
"/images/symbols/story/neutral.svg",
];
// Fonction pour choisir aléatoirement un SVG
function choisirSVGAléatoire() {
const index = Math.floor(Math.random() * svgs.length);
return svgs[index];
}
document.addEventListener("DOMContentLoaded", () => {
const svgPath = choisirSVGAléatoire();
const svgElement = document.getElementById("random-svg");
svgElement.data = svgPath;
svgElement.onload = function () {
const svgDoc = svgElement.contentDocument;
if (svgDoc && svgDoc.documentElement) {
const paths = svgDoc.querySelectorAll("path");
paths.forEach((path) => {
path.style.fill = "#a23322";
});
}
};
});
// Array contenant les propositions
const propositions = [
"Oups, mieux vaut recommencer.",
"C'était un flop total.",
"Un échec retentissant.",
"Catastrophe totale, désolé!",
"Raté de justesse!",
"Pas de chance cette fois-ci.",
"Fiasco complet, vraiment désolé.",
"Un dénouement bien décevant.",
"Rideau sur cette débâcle.",
"Tout ça pour ça?",
"Quel gâchis total!",
"Vous avez réussi à atteindre de nouveaux sommets de médiocrité.",
"Si l'échec était une œuvre d'art, ce serait vous.",
"Je pensais avoir tout vu, puis vous êtes arrivé.",
"C'était comme regarder un train dérailler en slow motion.",
"Vous avez l'art de tout gâcher, félicitations!",
"Même un singe ivre aurait fait mieux.",
"Je suis sûr qu'un hamster aurait pris de meilleures décisions.",
"Je ne sais pas si je dois rire ou pleurer de votre performance.",
"Est-ce que c'était votre stratégie pour impressionner les escargots?",
];
// Fonction pour choisir aléatoirement une proposition
function choisirPropositionAleatoire() {
const index = Math.floor(Math.random() * propositions.length);
return propositions[index];
}
// Mettre la proposition aléatoire dans le h1
document.getElementById("end-game-message").textContent =
choisirPropositionAleatoire();
document.addEventListener("DOMContentLoaded", () => {
const partieId = localStorage.getItem("choixFinalId"); // Utiliser le nom correct de la clé
console.log(partieId);
fetch(`http://localhost:4000/api/fin-jeu/${partieId}`) // Utiliser partieId au lieu de choixId
.then((response) => response.json())
.then((data) => {
const endGameInfo = document.getElementById("end-game-info");
endGameInfo.textContent = `"${data.partie_texte}"`;
})
.catch((error) =>
console.error(
"Erreur lors de la récupération des données de fin de jeu :",
error
)
);
const restartButton = document.getElementById("restart-button");
restartButton.addEventListener("click", () => {
window.location.href = "/game"; // Rediriger vers la page de jeu pour recommencer
});
const accountButton = document.getElementById("account-button");
accountButton.addEventListener("click", () => {
window.location.href = "/utilisateur"; // Rediriger vers la page de l'utilsiateur
});
});
</script>
</body>
</html>
<style scoped>
@import url("https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap");
body {
background: #181930;
color: #ffffff;
background-image: url("/images/noise.webp");
}
#random-svg {
fill: #a23322;
width: 550px;
height: 550px;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding-top: 6%;
}
.button-flex {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 40px;
}
#end-game-message {
font-size: 3rem;
font-weight: bold;
font-family: var(--font-sego);
margin-top: 1%;
}
#end-game-info {
color: rgba(250, 235, 215, 0.8);
font-size: 1.7rem;
font-family: var(--font-sego);
margin-bottom: 1%;
}
button {
background-color: transparent;
color: white;
border: none;
font-weight: bold;
font-family: "Bebas Neue", sans-serif;
padding: 12px 25px; /* Ajustez selon vos besoins */
cursor: pointer;
outline: none; /* Supprime la bordure de focus */
font-size: 1.5em; /* Double la taille du texte */
transition: all 0.15s ease-in-out;
}
button:nth-child(1) {
background-color: #b53926;
}
button:nth-child(2) {
border: 3px solid #4c4946;
background-color: #1b1b1b;
color: #e4dad1;
background-image: url("/images/noise.webp");
}
/* Style de survol */
button:nth-child(1):hover {
background-color: #a23322;
color: white; /* Couleur du texte au survol */
}
button:nth-child(2):hover {
background-color: #4c4946;
color: white; /* Couleur du texte au survol */
}
@media (min-width: 1400px) {
#random-svg {
width: 350px;
height: 350px;
padding-bottom: 10px;
}
#end-game-message {
font-size: 2.5rem;
width: 60vw;
text-align: center;
line-height: 1.1;
}
#end-game-info {
font-size: 1.7rem;
width: 60vw;
text-align: center;
}
}
</style>
|
# Write-Ahead Log
Write-ahead log written in TypeScript
## Installation
```shell
npm install write-ahead-log
```
## Performance
| Operation | # of Operations | Duration (in seconds) | Throughput (ops/ms) |
| --------- | --------------- | --------------------- | ------------------- |
| Write | 1 000 000 | 2582.32 | 387 |
| Read | 1 000 000 | 5498.57 | 182 |
## Usage
```typescript
import { WriteAheadLogReader, WriteAheadLogWriter } from 'write-ahead-log';
// Write-ahead log writer
const writeAheadLogWriter: WriteAheadLogWriter = new WriteAheadLogWriter(
'data',
'log-001.data',
);
await writeAheadLogWriter.open();
await writeAheadLogWriter.write({
key: 'hello',
value: 'world',
});
await writeAheadLogWriter.close();
// Write-ahead log reader
const writeAheadLogReader: WriteAheadLogReader = new WriteAheadLogReader(
'data',
'log-001.data',
);
const logEntries = await writeAheadLogReader.read();
```
## Contribute
Thank you for your interest in contributing to [Project Name]! We welcome contributions from everyone, whether it's through submitting bug reports, suggesting improvements, adding documentation, or contributing code. Here's how you can contribute:
### Reporting Bugs
If you find a bug in the project:
1. Use the GitHub Issues page to search for existing issues related to your problem.
2. If the issue is new, click the "New Issue" button and fill out the form with as much detail as possible.
3. Provide a clear and descriptive title as well as a detailed description of the issue. Include any relevant code samples or error messages.
### Suggesting Enhancements
Have an idea for an improvement or new feature? We'd love to hear it! Please:
1. Check the GitHub Issues page to see if someone else has already suggested the same enhancement.
2. If it's a new idea, open a new issue, choosing the "Feature Request" template if available.
3. Provide a succinct title and detailed description of your proposed enhancement. Explain why you believe it would be beneficial to the project.
### Pull Requests
Ready to contribute code or documentation? Follow these steps:
1. Fork the repository on GitHub.
2. Clone your fork to your local machine.
3. Create a new branch for your contribution (`git checkout -b feature/AmazingFeature`).
4. Make your changes in the new branch.
5. Commit your changes, ensuring your commit messages are concise and descriptive.
6. Push the branch to your fork (`git push origin feature/AmazingFeature`).
7. Open a pull request from your fork to the main project. Include a clear title and description of your changes.
8. Wait for feedback or approval from the project maintainers.
### Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project, you agree to abide by its terms.
We're excited to welcome you to our community and look forward to your contributions!
|
package com.mprog.hangman;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import java.lang.reflect.Array;
/**
* This class draws the gamescreen on every move.
*/
public class HangmanDraw extends View {
Canvas canvas;
Bitmap background;
Bitmap gallow;
Display display;
int width;
int height;
//Fix for bigger screens
int scrMlt = 1;
Paint paint = new Paint();
HangmanDraw(Context context) {
super(context);
background = (Bitmap) BitmapFactory.decodeResource(getResources(), R.drawable.background_gamescreen);
paint.setStrokeWidth(8);
paint.setColor(Color.BLACK);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
if (width >= 720) {
scrMlt = 2;
}
}
@Override
public void onDraw(Canvas canvas) {
this.canvas = canvas;
drawBackground();
drawGallow();
drawWord();
drawScore();
drawLives();
drawGuessed();
}
private void drawBackground() {
canvas.drawBitmap(background, 0, 0, null);
}
/**
* Draw the correct gallow image. Calculate the best hangman image, and then search the ID from the resource
*/
private void drawGallow() {
double steps = (((double)config.DRAW_GALLOW_STEPS)/Hangman.settings.get_tries()) * (Hangman.settings.get_tries() - Hangman.getLives());
int nr;
if (steps < 12) nr = (int)Math.round(steps);
else if (steps >= 13) nr = 13;
else nr = 12;
String HANGMAN = "hangman" + nr;
int resID = this.getResources().getIdentifier(HANGMAN, "drawable", "com.mprog.hangman");
gallow = (Bitmap) BitmapFactory.decodeResource(getResources(), resID);
canvas.drawBitmap(gallow, 0, (45 * scrMlt), null);
}
private void drawWord() {
String[] word = Hangman.getWord();
/**
* Center the word and make sure it fits on the screen.
*/
int y = 36 * scrMlt;
int xIncrease = (width-(20 * scrMlt))/(Array.getLength(word));
if (xIncrease > 100) {
xIncrease = 100;
}
int x = (width - (Array.getLength(word) * xIncrease))/2;
paint.setTextSize(35 * scrMlt);
/**
* Print each letter of the word, the empty slots are being filled with a underscore
*/
for (String letter : word) {
if (letter == null) {
canvas.drawText("_", x, y, paint);
} else {
canvas.drawText("" + letter, x, y, paint);
}
x += xIncrease;
}
}
/**
* Draw the current score
*/
private void drawScore() {
paint.setTextSize(18 * scrMlt);
int startX = (int)gallow.getWidth()/4;
int startY = gallow.getHeight() + (30 * scrMlt);
canvas.drawText("Score: " + Hangman.getScore(), startX, startY, paint);
}
/**
* Draw the remaining lives
*/
private void drawLives() {
paint.setTextSize(18 * scrMlt);
int startX = (int)gallow.getWidth()/5 + (140 * scrMlt);
int startY = gallow.getHeight() + (30 * scrMlt);
canvas.drawText("Lives: " + Hangman.getLives(), startX, startY, paint);
}
/**
* Draw all the already guessed letters
*/
private void drawGuessed() {
int x = 2 * scrMlt;
int y = 60 * scrMlt;
paint.setTextSize(14 * scrMlt);
for(String letter : Hangman.getGuessed()) {
if (letter != null) {
canvas.drawText(" " + letter, x, y, paint);
x += (16 * scrMlt);
if (x > (40 * scrMlt)) {
x = (2 * scrMlt);
y += (20 * scrMlt);
}
}
}
}
}
|
# VirtualBoxへのUbuntu Serverのインストール
[Install Ubuntu Server (Ubuntu公式サイト)](https://ubuntu.com/tutorials/install-ubuntu-server)
[VirtualBox](https://www.virtualbox.org)の仮想マシンにUbuntu Serverをインストールする手順を説明します。
## Ubuntu Serverのインストールメディアの準備
[ここ](https://ubuntu.com/download/server)からUbuntu Serverのインストールディスクイメージファイルをダウンロードする。
`ubuntu-22.04.2-live-server-amd64.iso`という1.84GBのISOファイルがダウンロードされる。(令和5年6月16日現在)
*実機にインストールする場合はこのISOファイルをUSBメモリスティックなどに書き込み、そのUSBメモリスティックからPCを起動してインストールを行いますがこの文書では説明しません。*
## VirtualBoxのインストール
[このページ](https://www.linuxcapable.com/install-virtualbox-on-ubuntu-linux/)を参考にしてVirtualBoxをインストールする。(Ubuntuの場合)
他のLinuxディストリビューションやWindowsやMacOSを使用する場合は同様の説明を探してインストールする。
## VirtualBoxの起動
VirtualBoxを起動するとこのような画面が表示される。(初めてVirtualBoxをインストールした場合は左側の「ツール」の下欄は空白)

## 新規仮想マシンの作成
「新規」ボタンを押して「仮想マシンの作成」画面を開く。

「仮想マシンの作成」画面で「名前(仮想マシンの名前)」、「フォルダー(仮想マシンを保存する場所)」、「ISO Image(Ubuntu ServerのISOファイル)」を入力する。
この例では仮想マシンの名前は「UbuntuServer」、仮想マシンの保存場所は自分のホームディレクトリ内の「VirtualBox VMs」、ISO ImageにはダウンロードしてUbuntu ServerのISOファイルを指定している。

「Skip Unattended Installation」のチェックボックをチェックして「次へ」ボタンを押して「Hardware」の設定画面に移動する。
*ここをチェックしないと設定が終わったらすぐに自動的にインストールが始まってしまう。*
「Hardware」の設定画面では仮想マシンで使用するメインメモリー量とプロセッサー数を設定する。
この例ではメインメモリーに2048MB、プロセッサー数に1を設定している。
*サーバーOSの場合は2048MB (2GB)程度のメモリーがあれば十分に動く。学習環境ではプロセッサー数は1か2で十分*

「Enable EFI」をチェックせずに「次へ」ボタンを押し「Virtual Hard Disk」画面に移動する。

「Create a Virual Hard Disk Now」を選択し、「Disk Size」を適当な値に設定する。デフォルトで25GBでも十分。(用途による)
設定ができたら「次へ」ボタンを押し「概要」画面で設定内容を確認し問題がなければ「完了」ボタンを押す。設定間違いがあれば「戻る」ボタンを押して設定値を変更する。

これで新たな仮想マシンがVirtual Boxに追加された。

## 仮想マシンのネットワーク設定
新規仮想マシンが作られたときのネットワーク設定は「NAT」を使うものになっている。この状態で起動した仮想マシンはホストマシン(作業中のPC)とは別のネットワークになり、仮想マシンとホストマシンの間の通信はできない状態である。
サーバーは単体で使用することは稀で通常は他のマシンからネットワーク接続して使うことになるので、ホストマシンのネットワークと同一のネットワークに仮想マシンが接続されるように設定する。
新たに作成した仮想マシン「UbuntuServer」を選択した状態で「設定」ボタンを押し「ネットワーク」設定画面に移動する。

ここでネットワークアダプターの「割り当て」を「ブリッジアダプター」に変更する。
ネットワークアダプターの「名前」は何もしなければその時点で有効なものが選択されているはず。作業しているPCに有線LANとWiFiのインターフェースがあればどちらも選ぶことができる。

ネットワークの設定ができたら「OK」ボタンを押して設定画面を終了する。
## 仮想マシンの起動
「起動」ボタンを押して仮想マシンを起動する。Ubuntu ServerのISOファイル(インストールディスク)からUbuntu Serverが起動する。

「Try or Install Ubuntu Server」を選択してエンターキーを押すとインストールが始まる。

## インストール
インストール画面の各画面について簡単に説明する。
### 言語選択

サーバー上で直接日本語を使うことはないので通常は「English」を選ぶ。
### キーボード設定

### インストールタイプの選択

### ネットワーク設定

### プロキシー設定

### Ubuntuアーカイブ設定

### ストレージ設定



### プロフィール設定


### SSH設定

### インストール開始

### インストール終了

### 再起動


## インストール後の設定
### Ubuntu Server にログインする

### DHCPネットワークの問題への対処
Ubuntu ServerのネットワークをDHCPに設定した場合、ネットワークアクセス時にネームサーバーを参照しない(バグか?)。
その対策。
テキストエディターで`/etc/netplan/00-installer-config.yaml`を編集する。
```
$ sudo vim /etc/netplan/00-installer-config.yaml
```
編集内容
```
# This is the network config written by 'subiquity'
network:
ethernets:
enp0s3: # 使用しているネットワークインターフェースによってenp0s3ではない場合がある
dhcp4: true
# ここから追記
nameservers:
addresses: [8.8.8.8,192.168.0.1] # ネットワーク環境によって変わる
routes:
- to: default
via: 192.168.0.1 # ネットワーク環境によって変わる
# ここまで追記
version: 2
```
保存したらnetplanコマンドで変更を反映する。
```
$ sudo netplan apply
```
### ソフトウェアリポジトリの更新とソフトウェアの更新
```
$ sudo apt update && sudo apt upgrade -y
```
### mDNSのインストール
別のマシンからIPアドレス (192.168.x.xのような形式)でアクセスするのではなく、ホスト名を使ってアクセスするためにAvahiをインストールする。
```
sudo apt install avahi-daemon -y
```
Avahiの起動と自動起動設定
```
sudo systemctl start avahi-daemon
sudo systemctl enable avahi-daemon
```
これで(この文章の例の場合)
```
$ ssh ubuntuserver.local
```
とすることで別のマシンからこのサーバーにアクセスできる。
ここまで出来たら以降の作業はすべて別のマシンからsshを使って行う。
|
This code implements the SHA256 hashing algorithm specified in FIPS180-4.
It also implements a NIST approved Hash_DRBG Random Number Generator based on SHA256,
which includes the Continuous Random Number Generator Test specified in FIP140-2.
It also implements a Random Number Generator for generating 256-bit OTPMK values,
with check bits already inserted.
NOTE: There has been a change to the API.
There are six routines that can be used to generate random data.
get_rand_bits() and get_rand_bytes() return purely random data,
useful for any purpose. The first parameter is a pointer to the array of data,
while the second parameter is the length.
otpmk_get_rand_bits_256() and otpmk_get_rand_256() return data formatted
as an OTPMK 256-bit secret (as a proper hamming code word).
The first paramter is a pointer to the array of random data, while a second parameter
(with_f) specifies whether to fix four bits at all 1s. This is helpful during development,
when there is no OTPMK programmed into fuses, but the chip requires a valid codeword,
or it will not go secure. Simply program those four bits, and this routing will then
generate an OTPMK value that can be programmed over top of that.
drvr_b_get_rand_bits_64() and drvr_b_get_rand_64() return data formatted
as a response value for the 64-bit debug challenge/response feature.
Again, a second parameter (with_1e) specifies whether or not to fix four bits to 1.
int otpmk_get_rand_bits_256() returns the OTPMK as an array of 256 unsigned bytes,
with each byte containing either 0 or 1.
int otpmk_get_rand_256() returns the OTPMK as an array of 32 unsigned words,
in big endian format. It really does not matter whether the array is treated as
big endian or little endian, it will work either way.
int get_rand_bits() returns an array of unsigned bytes, with each byte
containing either 0 or 1.
int get_rand_bytes() returns an array of unsigned words, in big endian format.
It really does not matter whether the array is treated as big endian or little endian,
it is just random data.
These routine are all that is required.
The first call to any routine will check if a TPM is available and/or required to be used;
it will open /dev/random as its source of entropy;
it will perform a CAVP (NIST Cryptographic Algorithm Validation Program) self-test to
verify the correct operation of the code (both for the SHA256 and Hash_DRBG implementations);
it will instantiate the Hash_DRBG; and set the reseed interval depending on whether there
is a TPM present and useable or not.
Each call will cause a reseed, if needed.
The main() program is simply a small test program, and is not needed.
It is an example only.
The Makefile is set up to build a shared library, stored in shared_lib/libhash_drbg.so.
The main program is then linked with the shared library.
The shared library, and the main program, can be compiled with either GCC or G++.
Note that either GCC or G++ must be used to compile all of the files.
Do not try to mix compilers, as this will not work.
The code compiles cleanly with -Wall -pedantic, except for the large strings that
are used in sha256LongMsg.c. C90 specifies only that strings can be at least 509 characters.
To prevent a GCC warning about strings that may be too long, -Wno-overlength-strings
has been added to the compile flags.
There are several Makefile parameters that can be set, for production or test use.
If these are not set in the Makefile, they will default to the strictest values.
TPM_REQUIRED:
0 - The TPM is not required, but will be used if available
1 - The TPM is required, and no OTPMK values will be generated if one is not
This should be set during production runs.
SEVERITY:
0 - An error will cause a non-zero return code.
1 - An error will cause an error message to be printed, and the program will exit immediately.
VERBOSITY:
0 - Do not print any messages (unless the SEVERITY is 1).
1 - Print error messages.
2 - Print informational messages
PRED_RES:
Prediction Resistance causes a reseed of the Hash_DRBG before every request for random data.
Note that if a TPM is present, the Hash_DRBG will reseed after every few requests,
therefore PRED_RES is not normally ever required, (other than for testing purposes).
0 - No Prediction Resistance is required when generating the OTPMK values.
1 - Prediction Resistance is required, even if a TPM is not present.
Source Files:
entropy.c - Open /dev/random and read entropy; test if a TPM is available for use
hash_drbg.c - Implement the SHA256 Hash_DRBG as specified in SP800-90A
hash_drbg_cavp_data.c - CAVP test data for the Hash_DRBG
hash_drbg_selftest.c - CAVP test code for the Hash_DRBG
main.c - An example main() program
otpmk.c - Generate and format OTPMK values
sha256.c - Implement the SHA256 algorithm as specified in FIPS180-4
sha256_cavp_selftest.c - CAVP test code for SHA256
sha256LongMsg_data.c - CAVP Long Message SHA256 test data
sha256Monte_data.c - CAVP Monte Carlo SHA256 test data
sha256ShortMsg_data.c - CAVP Short Message SHA256 test data
Include Files:
entropy.h
hash_drbg.h
otpmk.h
sha256.h
|
/*
Copyright (c) 2024 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package hcp
import (
"fmt"
"net/http"
"strings"
"github.com/terraform-redhat/terraform-provider-rhcs/build"
. "github.com/onsi/ginkgo/v2/dsl/core" // nolint
. "github.com/onsi/gomega" // nolint
. "github.com/onsi/gomega/ghttp" // nolint
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
. "github.com/openshift-online/ocm-sdk-go/testing" // nolint
)
const (
propKey = "prop_key"
propValue = "prop_value"
cluster123Route = "/api/clusters_mgmt/v1/clusters/123"
)
var _ = Describe("HCP Cluster", func() {
// cmv1 doesn't have a marshaling option for page
versionListPage := `
{
"kind": "VersionList",
"page": 1,
"size": 2,
"total": 2,
"items": [
{
"kind": "Version",
"id": "openshift-v4.14.0",
"href": "/api/clusters_mgmt/v1/versions/openshift-v4.14.0",
"raw_id": "4.14.0"
},
{
"kind": "Version",
"id": "openshift-v4.14.1",
"href": "/api/clusters_mgmt/v1/versions/openshift-v4.14.1",
"raw_id": "4.14.1"
}
]
}`
v4140Builder := cmv1.NewVersion().ChannelGroup("stable").
Enabled(true).
ROSAEnabled(true).
HostedControlPlaneEnabled(true).
ID("openshift-v4.14.0").
RawID("v4.14.0").
AvailableUpgrades("4.14.1")
v4141Spec, err := cmv1.NewVersion().ChannelGroup("stable").
Enabled(true).
ROSAEnabled(true).
HostedControlPlaneEnabled(true).
ID("openshift-v4.14.1").
RawID("v4.14.1").Build()
b := new(strings.Builder)
err = cmv1.MarshalVersion(v4141Spec, b)
Expect(err).ToNot(HaveOccurred())
v4141Info := b.String()
const emptyControlPlaneUpgradePolicies = `
{
"page": 1,
"size": 0,
"total": 0,
"items": []
}`
Expect(err).NotTo(HaveOccurred())
baseSpecBuilder := cmv1.NewCluster().
ID("123").
ExternalID("123").
Name("my-cluster").
AWS(cmv1.NewAWS().
AccountID("123").
BillingAccountID("123").
SubnetIDs("id1", "id2", "id3")).
State(cmv1.ClusterStateReady).
Region(cmv1.NewCloudRegion().ID("us-west-1")).
MultiAZ(true).
Hypershift(cmv1.NewHypershift().Enabled(true)).
API(cmv1.NewClusterAPI().URL("https://my-api.example.com")).
Console(cmv1.NewClusterConsole().URL("https://my-console.example.com")).
Properties(map[string]string{
"rosa_tf_version": build.Version,
"rosa_tf_commit": build.Commit,
}).
Nodes(cmv1.NewClusterNodes().
Compute(3).AvailabilityZones("us-west-1a").
ComputeMachineType(cmv1.NewMachineType().ID("r5.xlarge")),
).
Network(cmv1.NewNetwork().
MachineCIDR("10.0.0.0/16").
ServiceCIDR("172.30.0.0/16").
PodCIDR("10.128.0.0/14").
HostPrefix(23)).
Version(v4140Builder).
DNS(cmv1.NewDNS().BaseDomain("mycluster-api.example.com"))
spec, err := baseSpecBuilder.Build()
Expect(err).ToNot(HaveOccurred())
b = new(strings.Builder)
err = cmv1.MarshalCluster(spec, b)
Expect(err).ToNot(HaveOccurred())
template := b.String()
Context("Create/Update/Delete", func() {
baseSpecBuilder.AdditionalTrustBundle("REDACTED")
specWithTrustBundle, err := baseSpecBuilder.Build()
Expect(err).ToNot(HaveOccurred())
b = new(strings.Builder)
err = cmv1.MarshalCluster(specWithTrustBundle, b)
Expect(err).ToNot(HaveOccurred())
templateWithTrustBundle := b.String()
Context("Availability zones", func() {
It("invalid az for region", func() {
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
availability_zones = ["us-east-1a"]
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
}`)
Expect(terraform.Apply()).NotTo(BeZero())
})
})
Context("Version", func() {
It("version with unsupported prefix error", func() {
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "openshift-v4.14.1"
}`)
Expect(terraform.Apply()).NotTo(BeZero())
})
})
Context("Test channel groups", func() {
It("doesn't append the channel group when on the default channel", func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.version.id`, "openshift-v4.14.1"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "replace",
"path": "/version/id",
"value": "openshift-v4.14.1"
}]`),
))
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("appends the channel group when on a non-default channel", func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithPatchedJSON(http.StatusOK, versionListPage, `[
{
"op": "add",
"path": "/items/-",
"value": {
"kind": "Version",
"id": "openshift-v4.50.0-fast",
"href": "/api/clusters_mgmt/v1/versions/openshift-v4.50.0-fast",
"raw_id": "4.50.0",
"channel_group": "fast"
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.version.id`, "openshift-v4.50.0-fast"),
VerifyJQ(`.version.channel_group`, "fast"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "replace",
"path": "/version/id",
"value": "openshift-v4.50.0-fast"
},
{
"op": "add",
"path": "/version/channel_group",
"value": "fast"
}]`),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
channel_group = "fast"
version = "4.50.0"
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("returns an error when the version is not found in the channel group", func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithPatchedJSON(http.StatusOK, versionListPage, `[
{
"op": "add",
"path": "/items/-",
"value": {
"kind": "Version",
"id": "openshift-v4.50.0-fast",
"href": "/api/clusters_mgmt/v1/versions/openshift-v4.50.0-fast",
"raw_id": "4.50.0",
"channel_group": "fast"
}
}]`),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
channel_group = "fast"
version = "4.99.99"
}`)
Expect(terraform.Apply()).NotTo(BeZero())
})
})
Context("Test wait attribute", func() {
It("Create cluster and wait till it will be in error state", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/state",
"value": "error"
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
wait_for_create_complete = true
}`)
Expect(terraform.Apply()).ToNot(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.state", "error"))
})
It("Create cluster and wait till it will be in ready state", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/state",
"value": "ready"
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
wait_for_create_complete = true
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.state", "ready"))
})
})
It("Create cluster and wait til std compute nodes are up", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/state",
"value": "ready"
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/status",
"value": {
"current_compute": 3
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
wait_for_create_complete = true
wait_for_std_compute_nodes_complete = true
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.state", "ready"))
})
Context("Create cluster and wait until std compute nodes are up", func() {
BeforeEach(func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/state",
"value": "ready"
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/status",
"value": {
"current_compute": 3
}
}]`),
),
)
})
When("not waiting for creating alongside", func() {
It("fails - wait_for_create_complete = false", func() {
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
wait_for_create_complete = false
wait_for_std_compute_nodes_complete = true
}`)
Expect(terraform.Apply()).ToNot(BeZero())
})
It("fails - wait_for_create_complete = nil", func() {
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
wait_for_std_compute_nodes_complete = true
}`)
Expect(terraform.Apply()).ToNot(BeZero())
})
})
When("waiting for creating alongside", func() {
It("succeeds", func() {
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
wait_for_create_complete = true
wait_for_std_compute_nodes_complete = true
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.state", "ready"))
})
})
})
It("Creates basic cluster", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.current_version", "4.14.0"))
})
Context("Creates cluster with etcd encryption", func() {
BeforeEach(func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
},
"etcd_encryption": {
"kms_key_arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-78dcc31c5865498cbe98ad5ab9769a04"
}
}
},
{
"op": "add",
"path": "/etcd_encryption",
"value": true
}]`),
),
)
})
When("Required together etcd_encryption and etcd_kms_key_arn", func() {
It("fails when no etcd_kms_key_arn", func() {
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
etcd_encryption = true
}`)
Expect(terraform.Apply()).ToNot(BeZero())
})
It("fails when no etcd_encryption", func() {
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
etcd_kms_key_arn = "kms"
}`)
Expect(terraform.Apply()).ToNot(BeZero())
})
})
It("Creates cluster with etcd encryption", func() {
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
etcd_encryption = true
etcd_kms_key_arn = "arn:aws:kms:us-west-2:111122223333:key/mrk-78dcc31c5865498cbe98ad5ab9769a04"
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.current_version", "4.14.0"))
})
})
It("Creates basic cluster returned empty az list", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusCreated, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "replace",
"path": "/nodes",
"value": {
"compute": 3,
"compute_machine_type": {
"id": "r5.xlarge"
}
}
}
]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.current_version", "4.14.0"))
})
It("Creates basic cluster - and reconcile on a 404", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.current_version", "4.14.0"))
Expect(resource).To(MatchJQ(".attributes.id", "123")) // cluster has id 123
// Prepare the server for reconcile
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithJSON(http.StatusNotFound, "{}"),
),
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "replace",
"path": "/id",
"value": "1234"
},
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
resource = terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.current_version", "4.14.0"))
Expect(resource).To(MatchJQ(".attributes.id", "1234")) // reconciled cluster has id of 1234
})
It("Creates basic cluster with properties", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.properties.`+propKey, propValue),
RespondWithPatchedJSON(http.StatusCreated, template, fmt.Sprintf(`[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"%s": "%s"
}
}]`, propKey, propValue)),
),
)
// Run the apply command:
terraform.Source(fmt.Sprintf(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
properties = {
%s = "%s"
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`, propKey, propValue))
Expect(terraform.Apply()).To(BeZero())
})
It("Creates basic cluster with properties and update them", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.properties.`+propKey, propValue),
RespondWithPatchedJSON(http.StatusCreated, template, fmt.Sprintf(`[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit":"%s",
"rosa_tf_version":"%s",
"%s": "%s"
}
}]`, build.Commit, build.Version, propKey, propValue)),
),
)
// Run the apply command:
terraform.Source(fmt.Sprintf(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
properties = {
%s = "%s"
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`, propKey, propValue))
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_commit`, build.Commit))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_version`, build.Version))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.`+propKey, propValue))
Expect(resource).To(MatchJQ(`.attributes.properties.`+propKey, propValue))
// Prepare server for update
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, fmt.Sprintf(`[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit":"%s",
"rosa_tf_version":"%s",
"%s": "%s"
}
}]`, build.Commit, build.Version, propKey, propValue)),
),
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
VerifyJQ(`.properties.`+propKey, propValue+"_1"),
RespondWithPatchedJSON(http.StatusOK, template, fmt.Sprintf(`[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit":"%s",
"rosa_tf_version":"%s",
"%s": "%s"
}
}]`, build.Commit, build.Version, propKey, propValue+"_1")),
),
)
// Run the apply command:
terraform.Source(fmt.Sprintf(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
properties = {
%s = "%s"
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`, propKey, propValue+"_1"))
Expect(terraform.Apply()).To(BeZero())
resource = terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_commit`, build.Commit))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_version`, build.Version))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.`+propKey, propValue+"_1"))
Expect(resource).To(MatchJQ(`.attributes.properties.`+propKey, propValue+"_1"))
})
It("Creates basic cluster with properties and delete them", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.properties.`+propKey, propValue),
RespondWithPatchedJSON(http.StatusCreated, template, fmt.Sprintf(`[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit":"%s",
"rosa_tf_version":"%s",
"%s": "%s"
}
}]`, build.Commit, build.Version, propKey, propValue)),
),
)
// Run the apply command:
terraform.Source(fmt.Sprintf(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
properties = {
%s = "%s"
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`, propKey, propValue))
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_commit`, build.Commit))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_version`, build.Version))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.`+propKey, propValue))
Expect(resource).To(MatchJQ(`.attributes.properties.`+propKey, propValue))
Expect(resource).To(MatchJQ(`.attributes.properties| keys | length`, 1))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties| keys | length`, 3))
// Prepare server for update
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, fmt.Sprintf(`[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit":"%s",
"rosa_tf_version":"%s",
"%s": "%s"
}
}]`, build.Commit, build.Version, propKey, propValue)),
),
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
VerifyJQ(`.properties.`+propKey, nil),
RespondWithPatchedJSON(http.StatusOK, template, fmt.Sprintf(`[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit":"%s",
"rosa_tf_version":"%s"
}
}]`, build.Commit, build.Version)),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
properties = {
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
resource = terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_commit`, build.Commit))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties.rosa_tf_version`, build.Version))
Expect(resource).To(MatchJQ(`.attributes.properties | keys | length`, 0))
Expect(resource).To(MatchJQ(`.attributes.ocm_properties | keys | length`, 2))
})
It("Should fail cluster creation when trying to override reserved properties", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
properties = {
rosa_tf_version = "bob"
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).ToNot(BeZero())
})
It("Should fail cluster creation when cluster name length is more than 15", func() {
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster-234567"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
properties = {
cluster_name = "too_long"
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).ToNot(BeZero())
})
Context("Test destroy cluster", func() {
BeforeEach(func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.aws.sts.instance_iam_roles.worker_role_arn`, ""),
VerifyJQ(`.aws.sts.operator_role_prefix`, "test"),
VerifyJQ(`.aws.sts.role_arn`, ""),
VerifyJQ(`.aws.sts.support_role_arn`, ""),
VerifyJQ(`.aws.account_id`, "123"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithJSON(http.StatusOK, template),
),
CombineHandlers(
VerifyRequest(http.MethodDelete, cluster123Route),
RespondWithJSON(http.StatusOK, template),
),
)
})
It("Disable waiting in destroy resource", func() {
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
disable_waiting_in_destroy = true
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
// it should return a warning so exit code will be "0":
Expect(terraform.Apply()).To(BeZero())
Expect(terraform.Destroy()).To(BeZero())
})
It("Wait in destroy resource but use the default timeout", func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithJSON(http.StatusNotFound, template),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
// it should return a warning so exit code will be "0":
Expect(terraform.Apply()).To(BeZero())
Expect(terraform.Destroy()).To(BeZero())
})
It("Wait in destroy resource and set timeout to a negative value", func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithJSON(http.StatusNotFound, template),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
destroy_timeout = -1
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
// it should return a warning so exit code will be "0":
Expect(terraform.Apply()).To(BeZero())
Expect(terraform.Destroy()).To(BeZero())
})
It("Wait in destroy resource and set timeout to a positive value", func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithJSON(http.StatusNotFound, template),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
destroy_timeout = 10
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
// it should return a warning so exit code will be "0":
Expect(terraform.Apply()).To(BeZero())
Expect(terraform.Destroy()).To(BeZero())
})
})
Context("Test Proxy", func() {
It("Creates cluster with http proxy and update it", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.proxy.http_proxy`, "http://proxy.com"),
VerifyJQ(`.proxy.https_proxy`, "https://proxy.com"),
VerifyJQ(`.additional_trust_bundle`, "123"),
RespondWithPatchedJSON(http.StatusOK, templateWithTrustBundle, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/proxy",
"value": {
"http_proxy" : "http://proxy.com",
"https_proxy" : "https://proxy.com"
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
proxy = {
http_proxy = "http://proxy.com",
https_proxy = "https://proxy.com",
additional_trust_bundle = "123",
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
// apply for update the proxy's attributes
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/proxy",
"value": {
"http_proxy" : "http://proxy.com",
"https_proxy" : "https://proxy.com"
}
},
{
"op": "add",
"path": "/",
"value": {
"additional_trust_bundle" : "REDACTED"
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
VerifyJQ(`.proxy.https_proxy`, "https://proxy2.com"),
VerifyJQ(`.proxy.no_proxy`, "test"),
VerifyJQ(`.additional_trust_bundle`, "123"),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/proxy",
"value": {
"https_proxy" : "https://proxy2.com",
"no_proxy" : "test"
}
},
{
"op": "add",
"path": "/",
"value": {
"additional_trust_bundle" : "REDACTED"
}
}]`),
),
)
// update the attribute "proxy"
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
proxy = {
https_proxy = "https://proxy2.com",
no_proxy = "test"
additional_trust_bundle = "123",
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(`.attributes.proxy.https_proxy`, "https://proxy2.com"))
Expect(resource).To(MatchJQ(`.attributes.proxy.no_proxy`, "test"))
Expect(resource).To(MatchJQ(`.attributes.proxy.additional_trust_bundle`, "123"))
})
It("Creates cluster without http proxy and update trust bundle - should successes", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
// apply for update the proxy's attributes
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
VerifyJQ(`.additional_trust_bundle`, "123"),
RespondWithPatchedJSON(http.StatusCreated, templateWithTrustBundle, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// update the attribute "proxy"
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
proxy = {
additional_trust_bundle = "123",
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
})
})
It("Except to fail on proxy validators", func() {
// Expected at least one of the following: http-proxy, https-proxy, additional-trust-bundle
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
proxy = {}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).NotTo(BeZero())
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.additional_trust_bundle`, "123"),
RespondWithPatchedJSON(http.StatusOK, templateWithTrustBundle, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts": {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles": {
"worker_role_arn": ""
},
"operator_role_prefix": "test"
}
}
}]`),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
proxy = {
additional_trust_bundle = "123",
}
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("Creates private cluster with aws subnet ids & private link", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.aws.subnet_ids.[0]`, "id1"),
VerifyJQ(`.aws.private_link`, true),
VerifyJQ(`.nodes.availability_zones.[0]`, "us-west-1a"),
VerifyJQ(`.api.listening`, "internal"),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"private_link": true,
"subnet_ids": ["id1", "id2", "id3"],
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/api",
"value": {
"listening": "internal"
}
},
{
"op": "replace",
"path": "/nodes",
"value": {
"availability_zones": [
"us-west-1a"
],
"compute_machine_type": {
"id": "r5.xlarge"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
availability_zones = ["us-west-1a"]
private = true
aws_subnet_ids = [
"id1", "id2", "id3"
]
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("Creates cluster when private link is false", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.aws.private_link`, false),
VerifyJQ(`.api.listening`, "external"),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"private_link": false,
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
private = false
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("Creates rosa sts cluster with OIDC Configuration ID", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
VerifyJQ(`.aws.sts.role_arn`, ""),
VerifyJQ(`.aws.sts.support_role_arn`, ""),
VerifyJQ(`.aws.sts.instance_iam_roles.worker_role_arn`, ""),
VerifyJQ(`.aws.sts.operator_role_prefix`, "terraform-operator"),
VerifyJQ(`.aws.sts.oidc_config.id`, "aaa"),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"oidc_config": {
"id": "aaa",
"secret_arn": "aaa",
"issuer_url": "https://127.0.0.1",
"reusable": true,
"managed": false
},
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "terraform-operator"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = ""
},
"operator_role_prefix" : "terraform-operator",
"oidc_config_id" = "aaa"
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("Fails to create cluster with incompatible account role's version and fail", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
VerifyJQ(`.name`, "my-cluster"),
VerifyJQ(`.cloud_provider.id`, "aws"),
VerifyJQ(`.region.id`, "us-west-1"),
VerifyJQ(`.product.id`, "rosa"),
RespondWithPatchedJSON(http.StatusCreated, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "arn:aws:iam::765374464689:role/terr-account-Installer-Role",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
version = "openshift-v4.12"
sts = {
operator_role_prefix = "test"
role_arn = "arn:aws:iam::765374464689:role/terr-account-Installer-Role",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
}`)
// expect to get an error
Expect(terraform.Apply()).ToNot(BeZero())
})
})
Context("Upgrade", func() {
BeforeEach(func() {
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions"),
RespondWithJSON(http.StatusOK, versionListPage),
),
CombineHandlers(
VerifyRequest(http.MethodPost, "/api/clusters_mgmt/v1/clusters"),
RespondWithPatchedJSON(http.StatusCreated, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = "",
support_role_arn = "",
instance_iam_roles = {
worker_role_arn = "",
},
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.0"
}`)
Expect(terraform.Apply()).To(BeZero())
// Verify initial cluster version
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.current_version", "4.14.0"))
})
It("Upgrades Cluster", func() {
server.AppendHandlers(
// Refresh cluster state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions/openshift-v4.14.1"),
RespondWithJSON(http.StatusOK, v4141Info),
),
// Look for existing upgrade policies
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies"),
RespondWithJSON(http.StatusOK, emptyControlPlaneUpgradePolicies),
),
// Look for gate agreements by posting an upgrade policy w/ dryRun
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/control_plane/upgrade_policies", "dryRun=true"),
VerifyJQ(".version", "4.14.1"),
RespondWithJSON(http.StatusBadRequest, `{
"kind": "Error",
"id": "400",
"href": "/api/clusters_mgmt/v1/errors/400",
"code": "CLUSTERS-MGMT-400",
"reason": "There are missing version gate agreements for this cluster. See details.",
"details": [
{
"kind": "VersionGate",
"id": "999",
"href": "/api/clusters_mgmt/v1/version_gates/596326fb-d1ea-11ed-9f29-0a580a8312f9",
"version_raw_id_prefix": "4.14",
"label": "api.openshift.com/gate-sts",
"value": "4.14",
"warning_message": "STS roles must be updated blah blah blah",
"description": "OpenShift STS clusters include new required cloud provider permissions in OpenShift 4.YY.",
"documentation_url": "https://access.redhat.com/solutions/0000000",
"sts_only": true,
"creation_timestamp": "2023-04-03T06:39:57.057613Z"
}
],
"operation_id": "8f2d2946-c4ef-4c2f-877b-c19eb17dc918"
}`),
),
// Send acks for all gate agreements
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/gate_agreements"),
VerifyJQ(".version_gate.id", "999"),
RespondWithJSON(http.StatusCreated, `{
"kind": "VersionGateAgreement",
"id": "888",
"href": "/api/clusters_mgmt/v1/clusters/24g9q8jhdhv66fi41jfiuup5lsvu61fi/gate_agreements/d2e8d371-1033-11ee-9f05-0a580a820bdb",
"version_gate": {
"kind": "VersionGate",
"id": "999",
"href": "/api/clusters_mgmt/v1/version_gates/596326fb-d1ea-11ed-9f29-0a580a8312f9",
"version_raw_id_prefix": "4.14",
"label": "api.openshift.com/gate-sts",
"value": "4.14",
"warning_message": "STS blah blah blah",
"description": "OpenShift STS clusters include new required cloud provider permissions in OpenShift 4.YY.",
"documentation_url": "https://access.redhat.com/solutions/0000000",
"sts_only": true,
"creation_timestamp": "2023-04-03T06:39:57.057613Z"
},
"creation_timestamp": "2023-06-21T13:02:06.291443Z"
}`),
),
// Create an upgrade policy
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/control_plane/upgrade_policies"),
VerifyJQ(".version", "4.14.1"),
RespondWithJSON(http.StatusCreated, `
{
"id": "123",
"schedule_type": "manual",
"upgrade_type": "OSD",
"version": "4.14.1",
"next_run": "2023-06-09T20:59:00Z",
"cluster_id": "123",
"enable_minor_version_upgrades": true
}`),
),
// Patch the cluster (w/ no changes)
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
RespondWithPatchedJSON(http.StatusCreated, template, `
[
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
)
// Perform upgrade w/ auto-ack of sts-only gate agreements
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("Does nothing if upgrade is in progress to a different version than the desired", func() {
server.AppendHandlers(
// Refresh cluster state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions/openshift-v4.14.1"),
RespondWithJSON(http.StatusOK, v4141Info),
),
// Look for existing upgrade policies
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies"),
RespondWithJSON(http.StatusOK, `{
"page": 1,
"size": 1,
"total": 1,
"items": [
{
"id": "456",
"schedule_type": "manual",
"upgrade_type": "ControlPlane",
"version": "4.14.0",
"next_run": "2023-06-09T20:59:00Z",
"cluster_id": "123",
"enable_minor_version_upgrades": true
}
]
}`),
),
// Check it's state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies/456"),
RespondWithJSON(http.StatusOK, `
{
"id": "456",
"state": {
"description": "Upgrade in progress",
"value": "started"
}
}`),
),
)
// Perform try the upgrade
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
}`)
// Will fail due to upgrade in progress
Expect(terraform.Apply()).NotTo(BeZero())
})
It("Cancels and upgrade for the wrong version & schedules new", func() {
server.AppendHandlers(
// Refresh cluster state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions/openshift-v4.14.1"),
RespondWithJSON(http.StatusOK, v4141Info),
),
// Look for existing upgrade policies
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies"),
RespondWithJSON(http.StatusOK, `{
"kind": "UpgradePolicyState",
"page": 1,
"size": 0,
"total": 0,
"items": [
{
"id": "456",
"schedule_type": "manual",
"upgrade_type": "ControlPlane",
"version": "4.14.0",
"next_run": "2023-06-09T20:59:00Z",
"cluster_id": "123",
"enable_minor_version_upgrades": true
}
]
}`),
),
// Check it's state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies/456"),
RespondWithJSON(http.StatusOK, `{
"id": "456",
"state": {
"description": "",
"value": "scheduled"
}
}`),
),
// Delete existing upgrade policy
CombineHandlers(
VerifyRequest(http.MethodDelete, cluster123Route+"/control_plane/upgrade_policies/456"),
RespondWithJSON(http.StatusOK, "{}"),
),
// Look for gate agreements by posting an upgrade policy w/ dryRun (no gates necessary)
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/control_plane/upgrade_policies", "dryRun=true"),
VerifyJQ(".version", "4.14.1"),
RespondWithJSON(http.StatusNoContent, ""),
),
// Create an upgrade policy
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/control_plane/upgrade_policies"),
VerifyJQ(".version", "4.14.1"),
RespondWithJSON(http.StatusCreated, `{
"id": "123",
"schedule_type": "manual",
"upgrade_type": "ControlPlane",
"version": "4.14.1",
"next_run": "2023-06-09T20:59:00Z",
"cluster_id": "123",
"enable_minor_version_upgrades": true
}`),
),
// Patch the cluster (w/ no changes)
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
RespondWithJSON(http.StatusOK, template),
),
)
// Perform try the upgrade
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("Cancels upgrade if version=current_version", func() {
server.AppendHandlers(
// Refresh cluster state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithJSON(http.StatusOK, template),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies"),
RespondWithJSON(http.StatusOK, `{
"kind": "UpgradePolicyState",
"page": 1,
"size": 0,
"total": 0,
"items": [
{
"id": "456",
"schedule_type": "manual",
"upgrade_type": "ControlPlane",
"version": "4.14.1",
"next_run": "2023-06-09T20:59:00Z",
"cluster_id": "123",
"enable_minor_version_upgrades": true
}
]
}`),
),
// Check it's state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies/456"),
RespondWithJSON(http.StatusOK, `{
"id": "456",
"state": {
"description": "",
"value": "scheduled"
}
}`),
),
// Delete existing upgrade policy
CombineHandlers(
VerifyRequest(http.MethodDelete, cluster123Route+"/control_plane/upgrade_policies/456"),
RespondWithJSON(http.StatusOK, "{}"),
),
// Patch the cluster (w/ no changes)
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
RespondWithJSON(http.StatusOK, template),
),
)
// Set version to match current cluster version
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.0"
}`)
Expect(terraform.Apply()).To(BeZero())
})
It("is an error to request a version older than current", func() {
server.AppendHandlers(
// Refresh cluster state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template,
`[
{
"op": "replace",
"path": "/version/id",
"value": "openshift-v4.14.2"
}]`),
),
)
// Set version to before current cluster version, but after version from create
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
}`)
Expect(terraform.Apply()).NotTo(BeZero())
})
It("older than current is allowed as long as not changed", func() {
server.AppendHandlers(
// Refresh cluster state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template,
`[
{
"op": "replace",
"path": "/version/id",
"value": "openshift-v4.14.1"
}]`),
),
// Patch the cluster (w/ no changes)
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
RespondWithJSON(http.StatusOK, template),
),
)
// Set version to before current cluster version, but matching what was
// used during creation (i.e. in state file)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.0"
}`)
Expect(terraform.Apply()).To(BeZero())
})
Context("Un-acked gates", func() {
BeforeEach(func() {
server.AppendHandlers(
// Refresh cluster state
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `
[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/properties",
"value": {
"rosa_tf_commit": "",
"rosa_tf_version": ""
}
}
]`),
),
CombineHandlers(
VerifyRequest(http.MethodGet, "/api/clusters_mgmt/v1/versions/openshift-v4.14.1"),
RespondWithJSON(http.StatusOK, v4141Info),
),
// Look for existing upgrade policies
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route+"/control_plane/upgrade_policies"),
RespondWithJSON(http.StatusOK, emptyControlPlaneUpgradePolicies),
),
// Look for gate agreements by posting an upgrade policy w/ dryRun
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/control_plane/upgrade_policies", "dryRun=true"),
VerifyJQ(".version", "4.14.1"),
RespondWithJSON(http.StatusBadRequest, `{
"kind": "Error",
"id": "400",
"href": "/api/clusters_mgmt/v1/errors/400",
"code": "CLUSTERS-MGMT-400",
"reason": "There are missing version gate agreements for this cluster. See details.",
"details": [
{
"id": "999",
"version_raw_id_prefix": "4.14",
"label": "api.openshift.com/ackme",
"value": "4.14",
"warning_message": "user gotta ack",
"description": "deprecations... blah blah blah",
"documentation_url": "https://access.redhat.com/solutions/0000000",
"sts_only": false,
"creation_timestamp": "2023-04-03T06:39:57.057613Z"
}
],
"operation_id": "8f2d2946-c4ef-4c2f-877b-c19eb17dc918"
}`),
),
)
})
It("Fails upgrade for un-acked gates", func() {
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
}`)
Expect(terraform.Apply()).NotTo(BeZero())
})
It("Fails upgrade if wrong version is acked", func() {
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
upgrade_acknowledgements_for = "1.1"
}`)
Expect(terraform.Apply()).NotTo(BeZero())
})
It("It acks gates if correct ack is provided", func() {
server.AppendHandlers(
// Send acks for all gate agreements
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/gate_agreements"),
VerifyJQ(".version_gate.id", "999"),
RespondWithJSON(http.StatusCreated, `{
"kind": "VersionGateAgreement",
"id": "888",
"href": "/api/clusters_mgmt/v1/clusters/24g9q8jhdhv66fi41jfiuup5lsvu61fi/gate_agreements/d2e8d371-1033-11ee-9f05-0a580a820bdb",
"version_gate": {
"id": "999",
"version_raw_id_prefix": "4.14",
"label": "api.openshift.com/gate-sts",
"value": "4.14",
"warning_message": "blah blah blah",
"description": "whatever",
"documentation_url": "https://access.redhat.com/solutions/0000000",
"sts_only": false,
"creation_timestamp": "2023-04-03T06:39:57.057613Z"
},
"creation_timestamp": "2023-06-21T13:02:06.291443Z"
}`),
),
// Create an upgrade policy
CombineHandlers(
VerifyRequest(http.MethodPost, cluster123Route+"/control_plane/upgrade_policies"),
VerifyJQ(".version", "4.14.1"),
RespondWithJSON(http.StatusCreated, `
{
"kind": "UpgradePolicy",
"id": "123",
"href": "/api/clusters_mgmt/v1/clusters/123/upgrade_policies/123",
"schedule_type": "manual",
"upgrade_type": "ControlPlane",
"version": "4.14.1",
"next_run": "2023-06-09T20:59:00Z",
"cluster_id": "123",
"enable_minor_version_upgrades": true
}`),
),
// Patch the cluster (w/ no changes)
CombineHandlers(
VerifyRequest(http.MethodPatch, cluster123Route),
RespondWithJSON(http.StatusCreated, template),
),
)
terraform.Source(`
resource "rhcs_cluster_rosa_hcp" "my_cluster" {
name = "my-cluster"
cloud_region = "us-west-1"
aws_account_id = "123"
aws_billing_account_id = "123"
sts = {
operator_role_prefix = "test"
role_arn = ""
support_role_arn = ""
instance_iam_roles = {
worker_role_arn = ""
}
}
aws_subnet_ids = [
"id1", "id2", "id3"
]
version = "4.14.1"
upgrade_acknowledgements_for = "4.14"
}`)
Expect(terraform.Apply()).To(BeZero())
})
})
})
Context("Import", func() {
It("can import a cluster", func() {
// Prepare the server:
server.AppendHandlers(
CombineHandlers(
VerifyRequest(http.MethodGet, cluster123Route),
RespondWithPatchedJSON(http.StatusOK, template, `[
{
"op": "add",
"path": "/aws",
"value": {
"sts" : {
"oidc_endpoint_url": "https://127.0.0.1",
"thumbprint": "111111",
"role_arn": "",
"support_role_arn": "",
"instance_iam_roles" : {
"master_role_arn" : "",
"worker_role_arn" : ""
},
"operator_role_prefix" : "test"
}
}
},
{
"op": "add",
"path": "/nodes",
"value": {
"availability_zones": [
"us-west-1a",
"us-west-1b",
"us-west-1c"
],
"compute": 3,
"compute_machine_type": {
"id": "r5.xlarge"
}
}
}]`),
),
)
// Run the apply command:
terraform.Source(`resource "rhcs_cluster_rosa_hcp" "my_cluster" {}`)
Expect(terraform.Import("rhcs_cluster_rosa_hcp.my_cluster", "123")).To(BeZero())
resource := terraform.Resource("rhcs_cluster_rosa_hcp", "my_cluster")
Expect(resource).To(MatchJQ(".attributes.current_version", "4.14.0"))
})
})
})
|
import React from "react";
import { Box, Badge, Button } from "@chakra-ui/react";
import Image from "next/image";
import Link from "next/link";
import {
Center,
useColorModeValue,
Heading,
Text,
Stack,
} from "@chakra-ui/react";
function Product({ _id, image, name, price, category }) {
return (
<Center py={12} m={3}>
<Link href={`/shop/${_id}`}>
<Box
role={"group"}
p={6}
maxW={"330px"}
w={"full"}
bg={useColorModeValue("white", "gray.800")}
boxShadow={"2xl"}
rounded={"lg"}
pos={"relative"}
zIndex={1}
>
<Box
rounded={"lg"}
mt={-12}
pos={"relative"}
height={"230px"}
_after={{
transition: "all .3s ease",
content: '""',
w: "full",
h: "full",
pos: "absolute",
top: 5,
left: 0,
backgroundImage: `url(${image})`,
filter: "blur(15px)",
zIndex: -1,
}}
_groupHover={{
_after: {
filter: "blur(20px)",
},
}}
>
<Image
rounded={"lg"}
height={230}
width={282}
objectFit={"cover"}
src={image}
alt="product image"
/>
</Box>
<Stack pt={10} align={"center"}>
<Text
color={"gray.500"}
fontSize={"sm"}
textTransform={"uppercase"}
>
<Badge borderRadius="full" px="2" colorScheme="teal">
{category}
</Badge>{" "}
</Text>
<Heading fontSize={"2xl"} fontFamily={"body"} fontWeight={500}>
{name}
</Heading>
<Stack direction={"row"} align={"center"}>
<Text fontWeight={800} fontSize={"xl"}>
{price}€
</Text>
{/* <Text textDecoration={'line-through'} color={'gray.600'}>
$199
</Text> */}
</Stack>
</Stack>
</Box>
</Link>
</Center>
);
}
export default Product;
|
import React,{Component} from 'react';
import { StyleSheet, Text, View,Dimensions } from 'react-native';
import MapView from 'react-native-maps';
const{width,height}=Dimensions.get('window')
export default class App extends Component {
constructor(){
super()
this.state={
region:{
latitude:null,
longitude:null,
latitudeDelta:null,
longitudeDelta:null
}
}
}
calcDelta(lat,lon,accuracy){
const oneDegreeOfLongidInMeters=111.32;
const circunference=(40075 / 360)
const latDelta= accuracy *(1 / (Math.cos(lat)* circunference))
const lonDelta = (accuracy / oneDegreeOfLongidInMeters)
this.setState({
region: {
latitude:lat,
longitude:lon,
latitudeDelta:latDelta,
longitudeDelta:lonDelta
}
})
}
componentDidMount(){
navigator.geolocation.getCurrentPosition(
(position)=>{
const lat=position.coords.latitude
const lon=position.coords.longitude
const accuracy=position.coords.accuracy
this.calcDelta(lat,lon,accuracy)
}
)
}
Marker(){
return{
latitude:this.state.region.latitude,
longitude:this.state.region.longitude,
}
}
render(){
console.log('App.js latitude: '+this.state.region.latitude+' longitude: '+this.state.region.longitude)
return (
<View style={styles.container}>
{this.state.region.latitude ? <MapView
style={styles.map}
initialRegion={this.state.region}
>
<MapView.Marker
coordinate={this.Marker()}
title="Aqui estoy"
description="home"
/>
</MapView>: null }
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
map:{
flex:1,
width:width,
}
});
import React,{useEffect,useState} from 'react';
import axios from 'axios';
import {Table, TableContainer, TableHead, TableCell, TableBody, TableRow} from '@material-ui/core';
const Url='http://192.168.10.128:3030/donadores';
const Donadores=()=>{
const [data, setData] = useState([]);
const peticionGet=async()=>{
await axios.get(Url)
.then(response=>{
setData(response.data);
console.log(response.data)
})
}
useEffect(()=>{
async function fetchData(){
await peticionGet();
}
fetchData();
},[])
return (
<div className="text-center">
<TableContainer>
<Table>
<TableHead>
<TableRow>
<TableCell>Nombre</TableCell>
<TableCell>Latitud</TableCell>
<TableCell>Longitud</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map(dato=>(
<TableRow key={dato.id}>
<TableCell>{dato.name}</TableCell>
<TableCell>{dato.latitud}</TableCell>
<TableCell>{dato.longitud}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</div>
);
}
export default Donadores
|
import { Request, Response } from "express";
import { handleErrorResponse, handleHttpError } from "../utils/error.handle";
import { PermissionService } from "../services/permissions.service";
export class PermissionController {
static async findAll(req: Request, res: Response) {
try {
const data = await PermissionService.getPermissions();
res.status(200).send({ data });
} catch (e) {
handleHttpError(res, "Error al obtener la lista de permisos");
}
}
static async findOne({ params }: Request, res: Response) {
try {
const { id } = params;
const data = await PermissionService.getPermission(id);
if (!data) return handleErrorResponse(res, "Permiso no encontrado", 404);
return res.status(200).send({ data });
} catch (e) {
handleHttpError(res, "Error al obtener el permiso");
}
}
static async create({ body }: Request, res: Response) {
try {
const data = await PermissionService.createPermission(body);
res.status(201).send({ data });
} catch (e) {
handleHttpError(res, "Error al crear el permiso");
}
}
static async update({ params, body }: Request, res: Response) {
try {
const { id } = params;
const data = await PermissionService.updatePermission(id, body);
if (!data) return handleErrorResponse(res, "Permiso no encontrado", 404);
res.status(200).send({ data });
} catch (e) {
handleHttpError(res, "Error al actualizar el permiso");
}
}
static async remove({ params }: Request, res: Response) {
try {
const { id } = params;
const data = await PermissionService.deletePermission(id);
if (!data) return handleErrorResponse(res, "Permiso no encontrado", 404);
res.status(200).send({ data });
} catch (e) {
handleHttpError(res, "Error al eliminar el permiso");
}
}
}
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/cart.dart';
class CartItem extends StatelessWidget {
final String id;
final String productId;
final double price;
final int qunatity;
final String title;
CartItem(
this.id,
this.productId,
this.price,
this.qunatity,
this.title,
);
@override
Widget build(BuildContext context) {
return Dismissible(
key: ValueKey(id),
background: Container(
color: Theme.of(context).errorColor,
child: Icon(
Icons.delete,
color: Colors.white,
size: 40,
),
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 20),
margin: EdgeInsets.symmetric(horizontal: 15, vertical: 4),
),
direction: DismissDirection.endToStart,
confirmDismiss: (direction) {
return showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('Are you sure'),
content: Text("Do you want remove the item from the cart?"),
actions: <Widget>[
FlatButton(onPressed: () {
Navigator.of(ctx).pop(false);
}, child: Text("No")),
FlatButton(onPressed: () {
Navigator.of(ctx).pop(true);
}, child: Text("Yes")),
],
),
);
},
onDismissed: (direction) {
Provider.of<Cart>(context, listen: false).removeItem(productId);
},
child: Card(
margin: EdgeInsets.symmetric(horizontal: 15, vertical: 4),
child: Padding(
padding: EdgeInsets.all(8),
child: ListTile(
leading: CircleAvatar(
child: FittedBox(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Text('\$${price}'),
)),
),
title: Text(title),
subtitle: Text('Total: \$${(price * qunatity)} '),
trailing: Text('$qunatity x'),
),
),
),
);
}
}
|
export enum ActionTypes {
SET_FILES,
SET_IS_LOADING
}
export interface SetFiles {
type: typeof ActionTypes.SET_FILES;
payload: File[];
}
export interface SetIsLoading {
type: typeof ActionTypes.SET_IS_LOADING;
payload: boolean;
}
export interface State {
files: File[];
isLoading: boolean;
}
export type Action = SetFiles | SetIsLoading;
export type Dispatch = (action: Action) => void;
|
"""Sensor implementaion routines"""
import logging
from typing import Callable
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.components import sensor
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import UnitOfEnergy, UnitOfVolume
from homeassistant.core import (
HomeAssistant,
HomeAssistantError,
ServiceCall,
ServiceResponse,
SupportsResponse,
callback,
)
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import entity_platform
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo, EntityCategory
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import PescDataUpdateCoordinator, const, pesc_api, pesc_client
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable
):
"""Set up the platform from config entry."""
_LOGGER.debug("Setup %s (%s)", entry.title, entry.data[const.CONF_USERNAME])
coordinator: PescDataUpdateCoordinator = hass.data[const.DOMAIN][entry.entry_id]
diag = entry.options.get(const.CONF_DIAGNOSTIC_SENSORS, False)
async_add_entities(
PescMeterSensor(coordinator, m, diag) for m in coordinator.api.meters
)
if entry.options.get(const.CONF_RATES_SENSORS, True):
async_add_entities(
PescRateSensor(coordinator, m) for m in coordinator.api.meters
)
service_schema = {
vol.Required(const.CONF_VALUE): vol.All(
vol.Coerce(int),
vol.Range(min=1),
),
vol.Optional("throws"): vol.All(
vol.Coerce(bool),
vol.DefaultTo(True),
),
}
platform = entity_platform.async_get_current_platform()
async def async_execute_update_valaue(service_call: ServiceCall) -> ServiceResponse:
# device_id: service_call.data.get(homeassistant.const.ATTR_DEVICE_ID)
entities = await platform.async_extract_from_service(service_call)
if len(entities) != 1:
raise HomeAssistantError("Only one entity should be selected")
entity = entities[0]
if not isinstance(entity, _PescMeterSensor):
raise HomeAssistantError("PescMeterSensor entity should be selected")
return await entity.async_update_value(
service_call.data[const.CONF_VALUE],
service_call.return_response,
)
hass.services.async_register(
const.DOMAIN,
const.SERVICE_UPDATE_VALUE,
async_execute_update_valaue,
cv.make_entity_service_schema(service_schema),
SupportsResponse.OPTIONAL,
)
class _PescBaseSensor(
CoordinatorEntity[PescDataUpdateCoordinator], sensor.SensorEntity
):
def __init__(
self,
coordinator: PescDataUpdateCoordinator,
account_id: int,
unique_id: str,
name: str,
model: str,
):
super().__init__(coordinator)
entry = coordinator.config_entry
_LOGGER.debug("Initialize %s for %s", self.__class__.__name__, entry.title)
self._attr_unique_id = unique_id
self._attr_device_info = DeviceInfo(
configuration_url=pesc_client.PescClient.BASE_URL,
# connections={},
entry_type=DeviceEntryType.SERVICE,
identifiers={(const.DOMAIN, entry.entry_id, account_id)},
manufacturer=self.coordinator.api.profile_name,
model=model,
name=name,
# sw_version="",
# hw_version="",
)
self.entity_id = f"sensor.{self._attr_unique_id}"
@property
def api(self) -> pesc_api.PescApi:
return self.coordinator.api
class _PescMeterSensor(_PescBaseSensor):
def __init__(
self,
coordinator: PescDataUpdateCoordinator,
meter: pesc_api.MeterInd,
id_suffix: str = "",
):
super().__init__(
coordinator,
meter.account.id,
f"{const.DOMAIN}_{meter.id}{id_suffix}",
meter.account.name,
meter.account.tenancy,
)
self.meter = meter
self._update_state_attributes()
async def async_update_value(
self, value: int, return_response: bool = True
) -> ServiceResponse:
"""nothing to do with RO value"""
def _update_state_attributes(self):
pass
@callback
def _handle_coordinator_update(self) -> None:
"""Handle data update."""
ind = self.api.find_ind(self.meter.id)
if ind is not None:
self.meter = ind
_LOGGER.debug("[%s] New indication %s", self.entity_id, self.meter)
self._update_state_attributes()
else:
_LOGGER.warning(
"[%s] Indication %s not found", self.entity_id, self.meter.id
)
super()._handle_coordinator_update()
@property
def assumed_state(self) -> bool:
return not self.coordinator.last_update_success
@property
def available(self) -> bool:
return True
class PescMeterSensor(_PescMeterSensor):
_attr_state_class = sensor.SensorStateClass.TOTAL_INCREASING
_attr_has_entity_name = True
_attr_supported_features = 0
_attr_translation_key = "meter"
def __init__(
self,
coordinator: PescDataUpdateCoordinator,
meter: pesc_api.MeterInd,
diag: bool = False,
):
super().__init__(coordinator, meter)
if diag:
self._attr_entity_category = EntityCategory.DIAGNOSTIC
def _update_state_attributes(self):
if not self.meter.auto:
self._attr_supported_features = const.PescEntityFeature.MANUAL
subservice = self.api.subservice(self.meter.meter.subservice_id)
utility = "" if subservice is None else subservice["utility"]
if utility == pesc_client.SubserviceUtility.ELECTRICITY:
self._attr_device_class = sensor.SensorDeviceClass.ENERGY
self._attr_native_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR
elif utility == pesc_client.SubserviceUtility.GAS:
self._attr_device_class = sensor.SensorDeviceClass.GAS
self._attr_native_unit_of_measurement = UnitOfVolume.CUBIC_METERS
elif utility == pesc_client.SubserviceUtility.WATER:
self._attr_device_class = sensor.SensorDeviceClass.WATER
self._attr_native_unit_of_measurement = UnitOfVolume.CUBIC_METERS
# TODO implement HEATING device_class and unit_of_measurement
# elif utility == pesc_client.SubserviceUtility.HEATING:
else:
self._attr_native_unit_of_measurement = self.meter.unit
self._attr_name = self.meter.name
self._attr_extra_state_attributes = {
"type": self.meter.account.type,
"date": self.meter.date.isoformat(),
"name": self.meter.name,
"scale_id": self.meter.scale_id,
"meter_id": self.meter.meter.id,
"serial": self.meter.meter.serial,
"account_id": str(self.meter.account.id),
"tenancy": self.meter.account.tenancy,
"address": self.meter.account.address,
}
if subservice is not None:
self._attr_extra_state_attributes["subservice_id"] = subservice["id"]
self._attr_extra_state_attributes["subservice_name"] = subservice["name"]
self._attr_extra_state_attributes["subservice_type"] = subservice["type"]
self._attr_extra_state_attributes["subservice_utility"] = subservice[
"utility"
]
tariff = self.api.tariff(self.meter)
if tariff is not None:
if tariff.name is not None:
self._attr_extra_state_attributes["tariff_kind"] = tariff.kind
rate = tariff.rate(self.meter.scale_id)
if rate is not None:
self._attr_extra_state_attributes["tariff_rate"] = rate
@property
def native_value(self) -> int:
"""Return the value of the sensor."""
return self.meter.value
def __str__(self):
return f"{self.meter.value}"
async def async_update_value(
self, value: int, return_response: bool = True
) -> ServiceResponse:
_LOGGER.debug('[%s]: Updating "%s" to %d', self.entity_id, self.name, value)
if self.meter.auto:
msg = "Показания передаются в автоматическом режиме"
if not return_response:
raise HomeAssistantError(msg)
return {"code": -2, "message": msg}
if value < self.state:
msg = f"Новое значение {value} меньше предыдущего {int(self.meter.value)}"
if not return_response:
raise HomeAssistantError(msg)
return {"code": -3, "message": msg}
res = await self.relogin_and_update_(value, return_response, False)
await self.async_update()
return res
async def relogin_and_update_(
self, value: int, return_response: bool, do_relogin: bool
) -> ServiceResponse:
try:
if do_relogin:
await self.coordinator.relogin()
payload = await self.api.async_update_value(self.meter, value)
_LOGGER.debug('[%s] Update "%s" success', self.entity_id, self.name)
return {
"code": 0,
"message": "Операция выполнена успешно",
"payload": payload,
}
except pesc_client.ClientAuthError as err:
if not do_relogin:
await self.relogin_and_update_(value, return_response, True)
return None
if not return_response:
raise ConfigEntryAuthFailed from err
return {"code": err.code, "message": err.message}
except pesc_client.ClientError as err:
if not return_response:
raise HomeAssistantError(f"Ошибка вызова API: {err}") from err
return {"code": err.code, "message": err.message}
class PescRateSensor(_PescMeterSensor):
_attr_entity_category = EntityCategory.DIAGNOSTIC
_attr_has_entity_name = True
_attr_translation_key = "meter"
_attr_icon = "mdi:currency-rub"
def __init__(
self,
coordinator: PescDataUpdateCoordinator,
meter: pesc_api.MeterInd,
):
super().__init__(coordinator, meter, "_rate")
subservice = self.api.subservice(self.meter.meter.subservice_id)
utility = "" if subservice is None else subservice["utility"]
if utility == pesc_client.SubserviceUtility.ELECTRICITY:
self._attr_native_unit_of_measurement = (
f"{const.CURRENCY_RUB}/{UnitOfEnergy.KILO_WATT_HOUR}"
)
elif utility == pesc_client.SubserviceUtility.GAS:
self._attr_native_unit_of_measurement = (
f"{const.CURRENCY_RUB}/{UnitOfVolume.CUBIC_METERS}"
)
elif utility == pesc_client.SubserviceUtility.WATER:
self._attr_native_unit_of_measurement = (
f"{const.CURRENCY_RUB}/{UnitOfVolume.CUBIC_METERS}"
)
# TODO implement HEATING device_class and unit_of_measurement
# elif utility == pesc_client.SubserviceUtility.HEATING:
else:
self._attr_native_unit_of_measurement = (
f"{const.CURRENCY_RUB}/{self.meter.unit}"
)
def _update_state_attributes(self):
self._attr_name = f"Тариф {self.meter.name}"
tariff = self.coordinator.api.tariff(self.meter)
if tariff is not None:
self._attr_extra_state_attributes = {
"tariff_kind": tariff.kind,
}
@property
def native_value(self) -> float | None:
"""Return the value of the sensor."""
tariff = self.coordinator.api.tariff(self.meter)
if tariff is None:
return None
return tariff.rate(self.meter.scale_id)
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.queryable.queries;
import com.android.queryable.Queryable;
import java.util.Collection;
import java.util.List;
/** Query for a {@link java.util.List}. */
public interface ListQuery<E extends Queryable, F, G extends Query<F>> extends Query<List<F>> {
static ListQuery<ListQuery<?, ?, ?>, ?, ?> list() {
return new ListQueryHelper<>();
}
IntegerQuery<E> size();
/**
* Used to query whether a list contains certain objects.
*/
E contains(G... objects);
/**
* Used to query whether a list contains certain objects.
*
* <p>There are no bounds on the type for this method and therefore to find matches objects are
* compared using {@link Object#equals} If you are not checking for equality use
* {@link #contains(Query[])}.
*/
E contains(F... objects);
/**
* Used to query whether a list does not contain certain objects.
*/
E doesNotContain(G... objects);
/**
* Used to query whether a list does not contain certain objects.
*
* <p>There are no bounds on the type for this method and therefore to find matches objects are
* compared using {@link Object#equals}. If you are not checking for equality use
* {@link #contains(Query[])}.
*/
E doesNotContain(F... objects);
/**
* Used to query whether a list contains all of the elements from a collection.
*
* <p>There are no bounds on the type for this method and therefore to find matches objects are
* compared using {@link Object#equals} If you are not checking for equality use
* {@link #contains(Query[])}.
*/
<H extends Collection<F>> E containsAll(H... collection);
/**
* Used to query whether a list does not contain any elements given in a collection.
*
* <p>There are no bounds on the type for this method and therefore to find matches objects are
* compared using {@link Object#equals} If you are not checking for equality use
* {@link #contains(Query[])}.
*/
<H extends Collection<F>> E doesNotContainAny(H... collections);
}
|
using UnityEngine;
/// <summary>
/// Represents different states of the game.
/// </summary>
public enum GameStatus
{
Stick, // Rocketball is attached to the stick.
Fly, // Rocketball is flying through the air.
Death, // The game is over due to some reason.
Reset // Resetting the game to its initial state.
}
public class GameManager : MonoBehaviour
{
public static GameManager instance; // Singleton instance of the GameManager.
public GameObject Rocketball;
public Transform topboneend; // the end of the rod on which the ball is attached
public GameStatus currentStatus;
public GameObject Restart_UI;
Vector3 initialPosition; // Initial position of the Rocketball.
public StickController stickcontrol;
private void Awake()
{
// Singleton pattern implementation.
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
private void Start()
{
initialPosition = Rocketball.transform.position;
Debug.Log("RocketBall's Initial Position: " + initialPosition);
// Set the initial game status when the game starts.
SetGameStatus(GameStatus.Stick);
}
private void Update()
{
// Check for a specific key input to trigger game reset.
if (Input.GetKey(KeyCode.B))
{
ResetGame();
}
}
// Method to set the game status and perform necessary actions.
public void SetGameStatus(GameStatus newStatus)
{
currentStatus = newStatus;
// Actions based on the new game status.
switch (newStatus)
{
case GameStatus.Stick:
// Prepare for sticking phase.
stickcontrol.enabled = false;
stickcontrol.IsStickReleased = false;
stickcontrol.enabled = true;
Rocketball.transform.SetParent(topboneend);
Restart_UI.SetActive(false);
Time.timeScale = 1;
break;
case GameStatus.Fly:
// Rocketball is in the flying phase.
Debug.Log("Fly Status");
Rocketball.GetComponent<Animator>().enabled = true;
Rocketball.GetComponent<BallController>().enabled = true;
BallController.rotatingToZero = false;
BallController.isMoving = false;
break;
case GameStatus.Death:
// The ball fell to the ground
Debug.Log("Death Status");
Time.timeScale = 0;
Restart_UI.SetActive(true);
break;
case GameStatus.Reset:
// Reset the game to its initial state.
Debug.Log("Reset Status");
Rocketball.transform.rotation = Quaternion.identity;
Rocketball.transform.position = initialPosition;
Rocketball.GetComponent<BallController>().TriggerWingAnimation(false);
Rocketball.GetComponent<BallController>().enabled = false;
Rocketball.GetComponent<Rigidbody>().isKinematic = true;
StickController.Instance.ResetStick();
break;
default:
break;
}
}
// Method to change the game status.
public void ChangeGameStatus(GameStatus newStatus)
{
SetGameStatus(newStatus);
}
public void ResetGame()
{
SetGameStatus(GameStatus.Reset);
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>Azure ChatGPT3.5</title>
<style>
.message {
margin-bottom: 10px;
white-space: pre-wrap;
}
.chat-interface {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
font-size: 18px; /* Adjust the font size as desired */
}
.chat-wrapper {
width: calc(33.33vw);
}
.user {
color: blue;
}
.assistant {
color: green;
}
.user-input-form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 10px;
width: 100%;
overflow: auto;
}
.user-input-form input[type="text"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
resize: none;
}
h1 {
font-family: monospace;
text-align: center;
}
</style>
</head>
<body>
<h1>Azure ChatGPT3.5</h1>
<div class="chat-interface">
<div class="chat-wrapper">
<div id="chat-history">
{% for message in chat_history %}
{% if message.role == "user" %}
<p class="message user"><code>I: {{ message.content }}</code></p>
{% elif message.role == "assistant" %}
<p class="message assistant"><code>O: {{ message.content }}</code></p>
{% endif %}
{% endfor %}
</div>
<form class="user-input-form" method="POST" action="/">
<input type="text" name="user_input" placeholder="Enter your message">
<input type="submit" value="Submit" hidden>
</form>
</div>
</div>
<script>
// Scroll to the bottom of the chat history
function scrollToBottom() {
const chatHistory = document.getElementById("chat-history");
chatHistory.scrollTop = chatHistory.scrollHeight;
}
scrollToBottom();
// Stream new messages as they come in
const chatHistoryContainer = document.getElementById("chat-history");
const socket = new WebSocket("wss://your-socket-url"); // Replace with your WebSocket server URL
socket.onmessage = function (event) {
const message = JSON.parse(event.data);
const messageElement = document.createElement("p");
if (message.role === "user") {
messageElement.className = "message user";
messageElement.innerHTML = "<code>I: " + message.content + "</code>";
} else if (message.role === "assistant") {
messageElement.className = "message assistant";
messageElement.innerHTML = "<code>O: " + message.content + "</code>";
}
chatHistoryContainer.appendChild(messageElement);
scrollToBottom();
};
</script>
</body>
</html>
|
import Card from './Card'
import { DateTime } from 'luxon'
import Sort from './Sort'
import { useState } from 'react'
import { useSelector } from 'react-redux'
import { posts } from '../posts'
interface RootState {
searchedPosts: any
searchMode: Boolean
}
const Main = () => {
const selectSearchedPosts = (state: RootState) => state.searchedPosts
const selectSearchMode = (state: RootState) => state.searchMode
const searchMode = useSelector(selectSearchMode)
const searchedPosts = useSelector(selectSearchedPosts)
const [trendingTab, setTrendingTab] = useState(true)
const sortPostsByTrending = (posts: any) => {
const sortedPosts = posts.slice().sort((a: any, b: any) => {
const beforeLikes = a.likes
const afterLikes = b.likes
return afterLikes - beforeLikes
})
return sortedPosts
}
const sortPostsByLatestDate = (posts: any) => {
const sortedPosts = posts.slice().sort((a: any, b: any) => {
const beforeDate: any = DateTime.fromFormat(a.date, 'yyyy-MM-dd')
const afterDate: any = DateTime.fromFormat(b.date, 'yyyy-MM-dd')
return afterDate - beforeDate
})
return sortedPosts
}
return (
<div>
<Sort trendingTab={trendingTab} setTrendingTab={setTrendingTab} />
<div className='grid grid-cols-1 md:grid-cols-2 md:gap-4 lg:grid-cols-3 mt-4'>
{searchMode
? trendingTab
? sortPostsByTrending(searchedPosts).map(
(post: any, index: any) => {
return <Card post={post} key={index} />
}
)
: sortPostsByLatestDate(searchedPosts).map(
(post: any, index: any) => {
return <Card post={post} key={index} />
}
)
: trendingTab
? sortPostsByTrending(posts).map((post: any, index: any) => {
return <Card post={post} key={index} />
})
: sortPostsByLatestDate(posts).map((post: any, index: any) => {
return <Card post={post} key={index} />
})}
</div>
</div>
)
}
export default Main
|
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Product;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Validation\ValidationException;
class ProductController extends Controller
{
// public function product()
// {
// return view('admin.product');
// }
public function index()
{
// Your code to display a list of products
$products=Product::paginate(5);
return view('admin.products.index', compact('products'));
}
public function create()
{
$categories = Category::all();
return view('admin.products.create',compact('categories'));
}
public function store(Request $request)
{
try {
$validatedData = $request->validate([
'category_id' => 'required|exists:categories,id',
'name' => 'required|string|max:255',
'description'=> 'required|string|max:255',
'imgurl' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
'discount' => 'required|numeric|min:0|max:100',
'price' => 'required|numeric|min:0',
]);
// Upload and store the image
if ($request->hasFile('imgurl')) {
$image=$request->imgurl;
$imagename=time().'.'.$image->getClientOriginalExtension();
// return ($imagename);
$request->imgurl->move('products',$imagename);
}
// Create a new product
$product = new Product();
$product->category_id = $validatedData['category_id'];
$product->name = $validatedData['name'];
$product->imgurl = $imagename; // Store the image path
$product->discount = $validatedData['discount'];
$product->price = $validatedData['price'];
$product->description=$validatedData['description'];
$product->save();
return redirect()->route('admin.product')
->with('success', 'Product added successfully.');
} catch (ValidationException $e) {
return redirect()->back()->withErrors($e->errors())->withInput();
} catch (\Throwable $th) {
return redirect()->back()->withErrors(['error' => 'An error occurred while processing your request.'])->withInput();
}
}
public function show($id)
{
// Your code to display details of a specific product
}
public function edit($id)
{
$categories = Category::all();
$product = Product::findOrFail($id);
return view('admin.products.edit', compact('product','categories'));
}
public function update(Request $request, $id)
{
try {
$product = Product::findOrFail($id);
$validatedData = $request->validate([
'category_id' => 'required|exists:categories,id',
'name' => 'required|string|max:255',
'description'=> 'required|string|max:255',
'imgurl' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
'discount' => 'required|numeric|min:0|max:100',
'price' => 'required|numeric|min:0',
]);
$product->category_id = $validatedData['category_id'];
$product->name = $validatedData['name'];
$product->discount = $validatedData['discount'];
$product->price = $validatedData['price'];
$product->description=$validatedData['description'];
if ($request->hasFile('imgurl')) {
$image = $request->imgurl;
$imagename = time().'.'.$image->getClientOriginalExtension();
$request->imgurl->move('products', $imagename);
$product->imgurl = $imagename;
}
// Save the changes
$product->save();
return redirect()->route('admin.product')
->with('success', 'Product updated successfully.');
} catch (ValidationException $e) {
return redirect()->back()->withErrors($e->errors())->withInput();
} catch (\Throwable $th) {
return redirect()->back()->withErrors(['error' => 'An error occurred while processing your request.'])->withInput();
}
}
public function destroy($id)
{
try {
$product = Product::findOrFail($id);
$product->delete();
return redirect()->route('admin.product')
->with('success', 'Category deleted successfully.');
} catch (\Throwable $th) {
return redirect()->route('admin.product')
->with('success', 'Category deleted failed.');
}
}
}
|
local status_ok, lspconfig = pcall(require, "lspconfig")
if not status_ok then
return
end
-- Change diagnostic sign
local signs = {
{ name = "DiagnosticSignError", text = "" },
{ name = "DiagnosticSignWarn", text = "" },
{ name = "DiagnosticSignHint", text = "" },
{ name = "DiagnosticSignInfo", text = "" },
}
for _, sign in ipairs(signs) do
vim.fn.sign_define(sign.name, { texthl = sign.name, text = sign.text, numhl = "" })
end
-- On attach
local on_attach = function(_, curbuff)
-- Keymap
vim.keymap.set("n", "gd", vim.lsp.buf.definition, {})
vim.keymap.set("n", "gr", vim.lsp.buf.references, {})
vim.keymap.set("n", "<space>r", vim.lsp.buf.rename, {})
-- Lsp message
vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, {
underline = false,
virtual_text = true,
signs = true,
update_in_insert = false,
})
-- Format on save
vim.api.nvim_create_autocmd("BufWritePre", {
group = vim.api.nvim_create_augroup("LspFormatting", { clear = true }),
buffer = curbuff,
callback = function()
vim.lsp.buf.format()
end,
})
end
-- Neovim lua config
require("neodev").setup({})
-- Ensure installed languages
local ensure_installed = {
"yamlls",
"lua_ls",
"pyright",
-- "gopls",
}
-- Language server configurations
local server_configs = {
-- YAML
yamlls = {
yaml = {
schemas = {
-- kubernetes = "*.yml",
-- ["https://raw.githubusercontent.com/compose-spec/compose-spec/master/schema/compose-spec.json"] = "*docker-compose*.{yml,yaml}",
-- ["https://json.schemastore.org/gitlab-ci"] = "*gitlab-ci*.{yml,yaml}",
["http://json.schemastore.org/github-workflow"] = ".github/workflows/*",
-- ["http://json.schemastore.org/github-action"] = ".github/action.{yml,yaml}",
-- ["http://json.schemastore.org/ansible-playbook"] = "playbooks/*.{yml,yaml}",
},
},
},
-- Lua
lua_ls = {
Lua = {
workspace = { checkThirdParty = false },
telemetry = { enable = false },
},
},
-- Python
pyright = {},
-- Golang
gopls = {
completeUnimported = true,
usePlaceholders = true,
analyses = {
unusedparams = true,
},
},
}
-- Completion configuration
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require("cmp_nvim_lsp").default_capabilities(capabilities)
-- Mason configuration
require("mason").setup()
local mason_lspconfig = require("mason-lspconfig")
mason_lspconfig.setup({
ensure_installed = ensure_installed,
})
local mason_null_ls = require("mason-null-ls")
mason_null_ls.setup({
ensure_installed = {
"stylua",
"black",
"gofumpt",
"goimports_reviser",
"golines",
"prettier",
},
})
mason_lspconfig.setup_handlers({
function(server_name)
lspconfig[server_name].setup({
on_attach = on_attach,
settings = server_configs[server_name],
capabilities = capabilities,
})
end,
})
|
# BuddyPress xProfile fields administration
Highlight the best of your community members by creating an unlimited number of Extended Profile (xProfile) Fields and/or groups of Extended Profile Fields custom-made for your community site.
To start creating xProfile fields, go to administration menu Users > Profile Fields. If you have a multisite installation with BuddyPress activated network-wide via Network Admin > Plugins, you’ll find the Profile Fields admin screen via Network Admin > Users > Profile Fields.

The BuddyPress xProfile component comes with 2 default groups of profile fields:
- the "Base" profile field group
- the "Signup Fields" group (fields attached to this group are only displayed into the registration page of your site).
> [!NOTE]
> **NB**: As shown above, groups of profile fields are listed using tabs just over the list of profile fields they are including.
It also adds a primary profile field (to store the display "Name" of your members) inside these two groups. The "Name" xProfile field as well as the "Base" & "Signup fields" xProfile field group cannot be deleted.
## Adding a new field to a profile field group
Activate the group's tab you want to add your profile field into and then click on the "Add new field" button to reach the below xprofile field form:

### Name
Use this form field to define the label to use for your xProfile field. This label will be displayed just before the input to set the xProfile field value into single Members' profile edit screen and just before the the xProfile field value into the single Members' profile view screen.
### Description
Use this form field to define the member's guidance to use for your xProfile field. This guidance will be displayed just around the input to guide the logged in member about how the field should be filled into the single Members' profile edit screen.

### Type
Using the select box of this form field, you can pick the xProfile field type according to the data you need to store. Types are organized in 3 categories.
#### Multi fields
Use this type when you need to let a member select one or more values inside an options list. As soon as you pick one of these types, a new metabox will let you define the options list for the field type.
#### Single fields
Use this type when you need to let a member define a unique value for your xProfile field. Depending on the xProfile field type you choose, a new metabox might show to let you customize the behavior of the xProfile field on your community site’s front-end. For instance, when you choose the "Date selector" type, this metabox help you define the displayed date format.
#### WordPress fields

The goal of these field types is to incorpore regular WordPress user fields into a BP xProfile fields loop. Using these will let your members to also edit their corresponding values on the front-end from their profile‘s page edit screen. You can pick the Biography or one of the available text fields: First Name, Last Name or like shown above the Website one. If some custom code is adding specific WordPress contact methods, these will be also available into the text fields list.
### Requirement
Use the select box to make your xProfile field "Required" or "Not required". Required fields have an asterisk sign appended to their label into the single Members' profile edit screen.
### Signups
Use the checkbox if you need the xProfile field to be inserted into the registration form of your community site.
### Member Types
If you created one or more member types for you community site, you'll be able to restrict your xProfile field usage to members having one or more of your registered member types.
### Visibility
Using the xProfile Field visibility select box you can define the default visibility of it between 3 to 4 levels: an xProfile field can be visible to "everyone", only the member viewing its own profile ("only me"), only to logged in members ("All members"), or - if the BP Friends component is active - only to friends of the displayed member. Once you selected this default visibility for your xProfile field, you can choose whether each member can customize this visibility or not.
### Autolink
If you enable this xProfile field property, then, on the single Member's profile view screen, a link to search all members who defined the field's value the same way than the one you're seeing will be applied to the field value.
## Modifying/Deleting an existing xProfile field
Activate the xProfile field group tab containing the field you need to modify. From the list of displayed fields, you'll find:
- at the left of these the "Edit" button to open the xProfile field edit form and perform your changes from it;
- at the right of these a red "Delete" link (except for the primary field) will let you remove existing fields.

The xProfile Admin UI also supports drag & drop edits. As shown above, you can reorder the list of xProfile fields for the activated group tab. You can also move an xProfile field to another group of fields as shown below.

To do so, simply hover the group's tab untill a green shadow is displayed around it, then drop the field.
> [!NOTE]
> **NB**: When you drop a field inside the "Signup fields" group, it won't remove it from the active group tab but will add it to the fields to display into the registration form.
## Adding a new profile field group
You first need to click on the "Add new field group" located immediately to the right of the Administration’s screen title. Doing so you will reach the form to create a new group of fields.

From there you can define the name of your group and optionally its description.
## Modifying/Deleting an existing xProfile field group
Activate the xProfile field group tab you need to modify. Just under the tab, you'll find:
- on the left: the "Add new field" button will let you populate your group with new fields and clicking on the "Edit Group" button will open the xProfile field group edit form and perform your changes from it;
- on the right: a red "Delete Group" link (except for the primary field group) will let you remove existing fields.

To reorder xProfile field groups, use the xProfile Admin UI drag & drop support. To do so, click & move the group's tab of your choice according to your preferred order.

|
/*
* Example of 'Flyweight' design pattern.
* Copyright (C) 2016 Leo Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <map>
using namespace std;
class CFlyweight
{
public:
virtual void Do(string exstate)=0;
};
class CConcreteFlyweight:public CFlyweight
{
private:
string m_instate;
string m_id;
public:
CConcreteFlyweight(string id)
{
m_instate="Instate is invariable in general.";
m_id=id;
};
public:
void Do(string exstate)
{
cout<<m_instate<<endl;
cout<<"Exstate is "<<exstate<<endl;
};
};
class CFlyweightFactory
{
public:
map<string,CFlyweight*> flyweights;
public:
CFlyweight* GetFlyweight(string id)
{
CFlyweight* p_flyweight;
auto it=flyweights.find(id);
if(it==flyweights.end())
{
p_flyweight=new CConcreteFlyweight(id);
flyweights[id]=p_flyweight;
}
else
{
p_flyweight=it->second;
};
return p_flyweight;
};
};
int main()
{
CFlyweightFactory* cp_factory=new CFlyweightFactory();
CFlyweight* cp_flyweight1=cp_factory->GetFlyweight("A");
CFlyweight* cp_flyweight2=cp_factory->GetFlyweight("B");
CFlyweight* cp_flyweight3=cp_factory->GetFlyweight("A");
cp_flyweight1->Do("Hello world!");
cp_flyweight1->Do("Hello China!");
cp_flyweight1->Do("Hello America!");
return 1;
};
|
/*
* $Id$
*
* Copyright (c) 2019-2024, CIAD Laboratory, Universite de Technologie de Belfort Montbeliard
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.utbm.ciad.labmanager.views.components.addons;
import static fr.utbm.ciad.labmanager.views.ViewConstants.DEFAULT_MINIMAL_WIDTH_FOR_2_COLUMNS_FORM;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.regex.Pattern;
import com.google.common.base.Strings;
import com.ibm.icu.text.Normalizer2;
import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.Unit;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog.ConfirmEvent;
import com.vaadin.flow.component.contextmenu.HasMenuItems;
import com.vaadin.flow.component.contextmenu.MenuItem;
import com.vaadin.flow.component.contextmenu.SubMenu;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Anchor;
import com.vaadin.flow.component.html.AnchorTarget;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.icon.IconFactory;
import com.vaadin.flow.component.menubar.MenuBar;
import com.vaadin.flow.component.menubar.MenuBarVariant;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.function.SerializableBiConsumer;
import com.vaadin.flow.function.SerializableComparator;
import com.vaadin.flow.function.SerializableConsumer;
import com.vaadin.flow.i18n.I18NProvider;
import com.vaadin.flow.internal.LocaleUtil;
import com.vaadin.flow.server.StreamResource;
import fr.utbm.ciad.labmanager.data.IdentifiableEntity;
import fr.utbm.ciad.labmanager.data.conference.Conference;
import fr.utbm.ciad.labmanager.data.journal.Journal;
import fr.utbm.ciad.labmanager.data.member.Membership;
import fr.utbm.ciad.labmanager.data.member.Person;
import fr.utbm.ciad.labmanager.data.organization.ResearchOrganization;
import fr.utbm.ciad.labmanager.data.project.Project;
import fr.utbm.ciad.labmanager.data.user.User;
import fr.utbm.ciad.labmanager.data.user.UserRole;
import fr.utbm.ciad.labmanager.utils.country.CountryCode;
import fr.utbm.ciad.labmanager.utils.io.filemanager.FileManager;
import fr.utbm.ciad.labmanager.views.ViewConstants;
import fr.utbm.ciad.labmanager.views.components.addons.avatars.AvatarItem;
import fr.utbm.ciad.labmanager.views.components.addons.entities.AbstractEntityEditor;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.arakhne.afc.vmutil.FileSystem;
import org.springframework.context.support.MessageSourceAccessor;
import org.vaadin.lineawesome.LineAwesomeIcon;
/** Factory of Vaadin components.
*
* @author $Author: sgalland$
* @version $Name$ $Revision$ $Date$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 4.0
*/
@org.springframework.stereotype.Component
public final class ComponentFactory {
/** Define the color of the border of the regular user avatars: red.
*/
private static final int ADMINISTRATOR_BORDER_COLOR = 0;
/** Define the color of the border of the regular user avatars: dark blue.
*/
private static final int USER_BORDER_COLOR = 5;
private static final String FOR_MANY = "%"; //$NON-NLS-1$
private static final Normalizer2 NORMALIZER = Normalizer2.getNFKDInstance();
private static final Pattern PATTERN = Pattern.compile(".[\\p{M}]"); //$NON-NLS-1$
private static final String FOR_ONE = "_"; //$NON-NLS-1$
private ComponentFactory() {
//
}
/** Create a form layout with multiple columns.
*
* @param columns the number of columns between 1 and 2.
* @return the layout.
*/
public static FormLayout newColumnForm(int columns) {
assert columns >= 1 && columns <= 2;
final var content = new FormLayout();
switch (columns) {
case 1:
// No specific configuration for a single column
break;
case 2:
content.setResponsiveSteps(
new FormLayout.ResponsiveStep("0", 1), //$NON-NLS-1$
new FormLayout.ResponsiveStep(DEFAULT_MINIMAL_WIDTH_FOR_2_COLUMNS_FORM, 2));
break;
default:
throw new IllegalArgumentException();
}
return content;
}
/** Create a text field with a clickable 16x16 icon as suffix.
*
* @param href the URL of the target page.
* @param iconPath the path of the icon in the JAva resources, starting with a slash character.
* @return the field.
* @see #newClickableIconTextField(String, String, int)
*/
public static TextField newClickableIconTextField(String href, String iconPath) {
return newClickableIconTextField(href, iconPath, 16);
}
/** Create a text field with a clickable icon as suffix.
*
* @param href the URL of the target page.
* @param iconPath the path of the icon in the JAva resources, starting with a slash character.
* @param iconSize the size of the icon in points.
* @return the field.
* @see #newClickableIconTextField(String, String)
*/
public static TextField newClickableIconTextField(String href, String iconPath, int iconSize) {
assert !Strings.isNullOrEmpty(href);
final var content = new TextField();
final var imageResource = newStreamImage(iconPath);
final var image = new Image(imageResource, href);
image.setMinHeight(iconSize, Unit.POINTS);
image.setMaxHeight(iconSize, Unit.POINTS);
image.setMinWidth(iconSize, Unit.POINTS);
image.setMaxWidth(iconSize, Unit.POINTS);
final var anchor = new Anchor(href, image);
anchor.setTitle(href);
anchor.setTarget(AnchorTarget.BLANK);
anchor.setTabIndex(-1);
content.setSuffixComponent(anchor);
return content;
}
/** Create a image stream with the image representing an empty background.
*
* @return the stream.
*/
public static StreamResource newEmptyBackgroundStreamImage() {
return newStreamImage("/images/empty_background.png"); //$NON-NLS-1$
}
/** Create a image stream from an URL pointing a Java resource.
*
* @param iconPath the path of the icon in the Java resources, starting with a slash character.
* @return the stream.
*/
public static StreamResource newStreamImage(String iconPath) {
assert !Strings.isNullOrEmpty(iconPath);
final URL url;
try {
url = FileSystem.convertStringToURL(iconPath, false);
} catch (Throwable ex) {
throw new IllegalArgumentException(ex);
}
return new StreamResource(FileSystem.largeBasename(url),
() -> ComponentFactory.class.getResourceAsStream(iconPath));
}
/** Create a resource stream from an URL pointing a Java resource.
*
* @param resourceFile the path to the server-side file.
* @return the resource to the server-side file.
*/
public static StreamResource newStreamImage(File resourceFile) {
return new StreamResource(resourceFile.getName(), () -> {
try {
return new FileInputStream(resourceFile);
} catch (IOException ex) {
throw new IOError(ex);
}
});
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(MenuBar menu, IconFactory icon, String label, String ariaLabel,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
return addIconItem(menu, icon, label, ariaLabel, false, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(MenuBar menu, IconFactory icon, String label, String ariaLabel) {
return addIconItem(menu, icon, label, ariaLabel, false, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(SubMenu menu, IconFactory icon, String label, String ariaLabel,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
return addIconItem(menu, icon, label, ariaLabel, false, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(SubMenu menu, IconFactory icon, String label, String ariaLabel) {
return addIconItem(menu, icon, label, ariaLabel, false, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(SubMenu menu, StreamResource icon, String label, String ariaLabel,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
return addIconItem(menu, icon, label, ariaLabel, false, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(SubMenu menu, StreamResource icon, String label, String ariaLabel) {
return addIconItem(menu, icon, label, ariaLabel, false, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param receiver the receiver of the new item.
* @param icon the icon of the item, never {@code null}.
* @param label the label of the item. It may be {@code null} for creating an item without text.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param isChild indicates if the item is for a sub-menu, when {@code true}; or the root item, when {@code false}.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(HasMenuItems receiver, IconFactory icon, String label, String ariaLabel, boolean isChild) {
return addIconItem(receiver, icon, label, ariaLabel, isChild, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param receiver the receiver of the new item.
* @param icon the icon of the item, never {@code null}.
* @param label the label of the item. It may be {@code null} for creating an item without text.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param isChild indicates if the item is for a sub-menu, when {@code true}; or the root item, when {@code false}.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(HasMenuItems receiver, IconFactory icon, String label, String ariaLabel, boolean isChild,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
assert icon != null;
return addIconItem(receiver, icon.create(), label, ariaLabel, isChild, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(MenuBar menu, LineAwesomeIcon icon, String label, String ariaLabel,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
return addIconItem(menu, icon, label, ariaLabel, false, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(MenuBar menu, LineAwesomeIcon icon, String label, String ariaLabel) {
return addIconItem(menu, icon, label, ariaLabel, false, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param receiver the receiver of the new item.
* @param icon the icon of the item, never {@code null}.
* @param label the label of the item. It may be {@code null} for creating an item without text.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param isChild indicates if the item is for a sub-menu, when {@code true}; or the root item, when {@code false}.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(HasMenuItems receiver, LineAwesomeIcon icon, String label, String ariaLabel, boolean isChild) {
return addIconItem(receiver, icon, label, ariaLabel, isChild, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param receiver the receiver of the new item.
* @param icon the icon of the item, never {@code null}.
* @param label the label of the item. It may be {@code null} for creating an item without text.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param isChild indicates if the item is for a sub-menu, when {@code true}; or the root item, when {@code false}.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static MenuItem addIconItem(HasMenuItems receiver, LineAwesomeIcon icon, String label, String ariaLabel, boolean isChild,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
assert icon != null;
return addIconItem(receiver, icon.create(), label, ariaLabel, isChild, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(MenuBar menu, StreamResource icon, String label, String ariaLabel,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
return addIconItem(menu, icon, label, ariaLabel, false, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param menu the receiver of the new item.
* @param icon the icon of the item..
* @param label the label of the item.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(MenuBar menu, StreamResource icon, String label, String ariaLabel) {
return addIconItem(menu, icon, label, ariaLabel, false, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param receiver the receiver of the new item.
* @param icon the icon of the item, never {@code null}.
* @param label the label of the item. It may be {@code null} for creating an item without text.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param isChild indicates if the item is for a sub-menu, when {@code true}; or the root item, when {@code false}.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(HasMenuItems receiver, StreamResource icon, String label, String ariaLabel, boolean isChild) {
return addIconItem(receiver, icon, label, ariaLabel, isChild, null);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param receiver the receiver of the new item.
* @param icon the icon of the item, never {@code null}.
* @param label the label of the item. It may be {@code null} for creating an item without text.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param isChild indicates if the item is for a sub-menu, when {@code true}; or the root item, when {@code false}.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @since 4.0
*/
public static MenuItem addIconItem(HasMenuItems receiver, StreamResource icon, String label, String ariaLabel, boolean isChild,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
assert icon != null;
final var image = new Image(icon, label);
image.setMinWidth(ViewConstants.ICON_SIZE, Unit.PIXELS);
image.setMinHeight(ViewConstants.ICON_SIZE, Unit.PIXELS);
image.setMaxWidth(ViewConstants.MAX_ICON_SIZE, Unit.PIXELS);
image.setMaxHeight(ViewConstants.MAX_ICON_SIZE, Unit.PIXELS);
return addIconItem(receiver, image, label, ariaLabel, isChild, clickListener);
}
/** Create a menu item with an icon and text and add it into the given receiver.
*
* @param receiver the receiver of the new item.
* @param iconInstance the icon of the item, never {@code null}.
* @param label the label of the item. It may be {@code null} for creating an item without text.
* @param ariaLabel the aria label of the item. It is recommended to have this aria label not {@code null} or empty when
* the {@code label} is {@code null} or empty, to enable disabled persons to have information on the feature of
* the menu item.
* @param isChild indicates if the item is for a sub-menu, when {@code true}; or the root item, when {@code false}.
* @param clickListener the listener on clicks on the item.
* @return the created item.
* @see #setIconItemText(MenuItem, String)
*/
public static <T extends com.vaadin.flow.component.Component & HasStyle> MenuItem addIconItem(
HasMenuItems receiver, T iconInstance, String label, String ariaLabel, boolean isChild,
ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
assert iconInstance != null;
if (isChild) {
iconInstance.getStyle().setWidth("var(--lumo-icon-size-s)"); //$NON-NLS-1$
iconInstance.getStyle().setHeight("var(--lumo-icon-size-s)"); //$NON-NLS-1$
iconInstance.getStyle().set("marginRight", "var(--lumo-space-s)"); //$NON-NLS-1$ //$NON-NLS-2$
}
final var item = receiver.addItem(iconInstance, clickListener);
if (!Strings.isNullOrEmpty(ariaLabel)) {
item.setAriaLabel(ariaLabel);
}
if (!Strings.isNullOrEmpty(label)) {
item.add(new Text(label));
}
return item;
}
/** Change te text of the given menu item assuming it was build with an icon.
*
* @param item the item to change..
* @param text the new text.
* @return the item.
* @see #addIconItem(MenuBar, LineAwesomeIcon, String, String)
* @see #addIconItem(MenuBar, IconFactory, String, String)
* @see #addIconItem(HasMenuItems, LineAwesomeIcon, String, String, boolean, ComponentEventListener)
* @see #addIconItem(HasMenuItems, IconFactory, String, String, boolean, ComponentEventListener)
*/
public static MenuItem setIconItemText(MenuItem item, String text) {
final var eltOpt = item.getElement().getChildren()
.filter(it -> it.getComponent().isPresent() && it.getComponent().get() instanceof Text)
.map(it -> (Text) it.getComponent().get())
.findAny();
if (Strings.isNullOrEmpty(text)) {
if (eltOpt.isPresent()) {
final var elt = eltOpt.get();
elt.removeFromParent();
}
} else if (eltOpt.isPresent()) {
final var elt = eltOpt.get();
elt.setText(text);
} else {
item.add(new Text(text));
}
return item;
}
/** Create a dialog that asks for a critical question and that is modal.
* This function does not attach an event handler to the confirm and cancel buttons.
*
* @param parent the parent component; mostly used for obtaining the translation of text.
* @param title the title of the box.
* @param message the message in the box.
* @return the dialog.
*/
public static ConfirmDialog newDeletionDialog(com.vaadin.flow.component.Component parent, String title, String message) {
return newDeletionDialog(parent, title, message, null);
}
/** Create a dialog that asks for a critical question and that is modal.
*
* @param parent the parent component; mostly used for obtaining the translation of text.
* @param title the title of the box.
* @param message the message in the box.
* @param confirmHandler the handler invoked when the confirm button is pushed.
* @return the dialog.
*/
public static ConfirmDialog newDeletionDialog(com.vaadin.flow.component.Component parent, String title, String message,
ComponentEventListener<ConfirmEvent> confirmHandler) {
return newCriticalQuestionDialog(
title, message,
parent.getTranslation("views.delete"), //$NON-NLS-1$
confirmHandler);
}
/** Create a dialog that asks for a critical question and that is modal.
* This function does not attach an event handler to the confirm and cancel buttons.
*
* @param title the title of the box.
* @param message the message in the box.
* @param confirmText the text of the confirm button.
* @param confirmHandler the handler invoked when the confirm button is pushed.
* @return the dialog.
*/
public static ConfirmDialog newCriticalQuestionDialog(String title, String message, String confirmText) {
return newCriticalQuestionDialog(title, message, confirmText, null);
}
/** Create a dialog that asks for a critical question and that is modal.
*
* @param title the title of the box.
* @param message the message in the box.
* @param confirmText the text of the confirm button.
* @param confirmHandler the handler invoked when the confirm button is pushed.
* @return the dialog.
*/
public static ConfirmDialog newCriticalQuestionDialog(String title, String message, String confirmText,
ComponentEventListener<ConfirmEvent> confirmHandler) {
final var dialog = new ConfirmDialog();
dialog.setConfirmButtonTheme("error primary"); //$NON-NLS-1$
dialog.setHeader(title);
dialog.setText(message);
dialog.setConfirmText(confirmText);
dialog.setCancelable(true);
dialog.setCloseOnEsc(true);
if (confirmHandler != null) {
dialog.addConfirmListener(confirmHandler);
}
return dialog;
}
/** Add an hidden column in the grid (usually the last column) for supporting the hover menu bar.
*
* @param <T> the type of data in the grid.
* @param grid the grid to update.
* @param generator the callback function for creating the buttons of the menu bar.
*/
public static <T> void addGridCellHoverMenuBar(Grid<T> grid, BiConsumer<T, MenuBar> generator) {
grid.addComponentColumn(it -> {
final var menuBar = new MenuBar();
menuBar.addClassName("hoverGridHlHide"); //$NON-NLS-1$
menuBar.addThemeVariants(MenuBarVariant.LUMO_ICON, MenuBarVariant.LUMO_SMALL, MenuBarVariant.LUMO_TERTIARY_INLINE);
generator.accept(it, menuBar);
return menuBar;
}).setTextAlign(ColumnTextAlign.END).setKey("controls").setAutoWidth(true).setFlexGrow(0).setWidth("0px"); //$NON-NLS-1$ //$NON-NLS-2$
}
/** Open a standard dialog box for editing an information.
* This function provides three callbacks. One is the standard saving callback that is verifying the validity of
* the input data. Second, it is the standard validation callback that is saving the data after
* turning on the validation flag by the local authority. Third is the standard deletion callback that invoked
* after querying the user for accepting the deletion.
*
* @param <T> the type of the edited entity.
* @param title the title of the dialog.
* @param content the content of the dialog, where the editing fields are located.
* @param mapEnterKeyToSave if {@code true}, the "save" button is activated when the {@code Enter}
* is pushed. If {@code false}, the {@code Enter} is not mapped to a component.
* @param enableValidationButton indicates if the 'Validate' button is enabled or not.
* @param saveDoneCallback the callback that is invoked after saving
* @param deleteDoneCallback the callback that is invoked after deleting
*/
public static <T extends IdentifiableEntity> void openEditionModalDialog(String title, AbstractEntityEditor<T> content,
boolean mapEnterKeyToSave, SerializableBiConsumer<Dialog, T> saveDoneCallback, SerializableBiConsumer<Dialog, T> deleteDoneCallback) {
final SerializableBiConsumer<Dialog, T> validateCallback;
if (content.isBaseAdmin()) {
validateCallback = (dialog, entity) -> {
content.validateByOrganizationalStructureManager();
if (content.isValidData()) {
content.save();
} else {
content.notifyInvalidity();
}
};
} else {
validateCallback = null;
}
openEditionModalDialog(title, content, mapEnterKeyToSave,
saveDoneCallback,
validateCallback,
deleteDoneCallback);
}
/** Open a standard dialog box for editing an information.
* This function provides a standard saving callback that is verifying the validity of
* the input data.
*
* @param <T> the type of the edited entity.
* @param title the title of the dialog.
* @param content the content of the dialog, where the editing fields are located.
* @param mapEnterKeyToSave if {@code true}, the "save" button is activated when the {@code Enter}
* is pushed. If {@code false}, the {@code Enter} is not mapped to a component.
* @param enableValidationButton indicates if the 'Validate' button is enabled or not.
* @param saveDoneCallback the callback that is invoked after saving
* @param validateCallback the callback for validating the information.
* @param deleteDoneCallback the callback that is invoked after deleting
*/
public static <T extends IdentifiableEntity> void openEditionModalDialog(String title, AbstractEntityEditor<T> content, boolean mapEnterKeyToSave,
SerializableBiConsumer<Dialog, T> saveDoneCallback,
SerializableBiConsumer<Dialog, T> validateCallback,
SerializableBiConsumer<Dialog, T> deleteDoneCallback) {
final SerializableConsumer<Dialog> validateCallback0;
if (validateCallback != null) {
validateCallback0 = dialog -> validateCallback.accept(dialog, content.getEditedEntity());
} else {
validateCallback0 = null;
}
final SerializableConsumer<Dialog> deleteCallback;
if (deleteDoneCallback != null) {
deleteCallback = dialog -> {
final var confirmDialog = new ConfirmDialog();
confirmDialog.setHeader(content.getTranslation("views.delete.entity")); //$NON-NLS-1$
confirmDialog.setText(content.getTranslation("views.delete.entity.text")); //$NON-NLS-1$
confirmDialog.setCancelable(true);
confirmDialog.setConfirmText(content.getTranslation("views.delete")); //$NON-NLS-1$
confirmDialog.setConfirmButtonTheme("error primary"); //$NON-NLS-1$
confirmDialog.addConfirmListener(event -> {
if (content.delete()) {
dialog.close();
deleteDoneCallback.accept(dialog, content.getEditedEntity());
}
});
confirmDialog.open();
};
} else {
deleteCallback = null;
}
doOpenEditionModalDialog(title, content, mapEnterKeyToSave,
dialog -> {
if (content.isValidData()) {
if (content.save()) {
dialog.close();
if (saveDoneCallback != null) {
saveDoneCallback.accept(dialog, content.getEditedEntity());
}
}
} else {
content.notifyInvalidity();
}
},
validateCallback0,
deleteCallback);
}
/** Open a standard dialog box for editing an information.
*
* @param title the title of the dialog.
* @param content the content of the dialog, where the editing fields are located.
* @param mapEnterKeyToSave if {@code true}, the "save" button is activated when the {@code Enter}
* is pushed. If {@code false}, the {@code Enter} is not mapped to a component.
* @param saveCallback the callback for saving the information.
* @param validateCallback the callback for validating the information.
* @param deleteCallback the callback for deleting the information.
*/
public static void doOpenEditionModalDialog(String title, Component content, boolean mapEnterKeyToSave,
SerializableConsumer<Dialog> saveCallback,
SerializableConsumer<Dialog> validateCallback,
SerializableConsumer<Dialog> deleteCallback) {
final var dialog = new Dialog();
dialog.setModal(true);
dialog.setCloseOnEsc(true);
dialog.setCloseOnOutsideClick(true);
dialog.setDraggable(true);
dialog.setResizable(true);
dialog.setWidthFull();
dialog.setHeaderTitle(title);
dialog.add(content);
final var saveButton = new Button(content.getTranslation("views.save"), e -> saveCallback.accept(dialog)); //$NON-NLS-1$
saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
if (mapEnterKeyToSave) {
saveButton.addClickShortcut(Key.ENTER);
}
saveButton.setIcon(LineAwesomeIcon.SAVE_SOLID.create());
final var cancelButton = new Button(content.getTranslation("views.cancel"), e -> dialog.close()); //$NON-NLS-1$
final Button deletionButton;
if (deleteCallback != null) {
deletionButton = new Button(content.getTranslation("views.delete"), //$NON-NLS-1$
event -> deleteCallback.accept(dialog));
deletionButton.addThemeVariants(ButtonVariant.LUMO_ERROR);
deletionButton.setIcon(LineAwesomeIcon.TRASH_SOLID.create());
} else {
deletionButton = null;
}
final Button validateButton;
if (validateCallback != null) {
validateButton = new Button(content.getTranslation("views.validate"), //$NON-NLS-1$
event -> validateCallback.accept(dialog));
validateButton.addThemeVariants(ButtonVariant.LUMO_SUCCESS);
validateButton.setIcon(LineAwesomeIcon.CHECK_DOUBLE_SOLID.create());
} else {
validateButton = null;
}
if (deletionButton != null) {
if (validateButton != null) {
dialog.getFooter().add(validateButton, cancelButton, deletionButton, saveButton);
} else {
dialog.getFooter().add(cancelButton, deletionButton, saveButton);
}
} else if (validateButton != null) {
dialog.getFooter().add(validateButton, cancelButton, saveButton);
} else {
dialog.getFooter().add(cancelButton, saveButton);
}
dialog.open();
}
/** Create a combo box that contains the countries.
*
* @param locale the locale for rendering the country names.
* @return the combo box.
*/
public static ComboBox<CountryCode> newCountryComboBox(Locale locale) {
final var combo = new ComboBox<CountryCode>();
combo.setItems(CountryCode.getAllDisplayCountries(locale));
combo.setItemLabelGenerator(it -> getCountryLabelForCombo(it, locale));
combo.setValue(CountryCode.getDefault());
return combo;
}
/** Update the items of the given combo box for displaying the country names according to the locale.
*
* @param combo the combo box to update.
* @param locale the locale for rendering the country names.
*/
public static void updateCountryComboBoxItems(ComboBox<CountryCode> combo, Locale locale) {
combo.setItemLabelGenerator(it -> getCountryLabelForCombo(it, locale));
}
private static String getCountryLabelForCombo(CountryCode country, Locale locale) {
return country.getDisplayCountry(locale);
}
/** Create a combo box that contains the languages.
*
* @param locale the locale for rendering the language names.
* @return the combo box.
*/
public static ComboBox<CountryCode> newLanguageComboBox(Locale locale) {
final var combo = new ComboBox<CountryCode>();
combo.setItems(CountryCode.getAllDisplayLanguages(locale));
combo.setItemLabelGenerator(it -> getLanguageLabelForCombo(it, locale));
combo.setValue(CountryCode.getDefault());
return combo;
}
/** Update the items of the given combo box for displaying the country names according to the locale.
*
* @param combo the combo box to update.
* @param locale the locale for rendering the country names.
*/
public static void updateLanguageComboBoxItems(ComboBox<CountryCode> combo, Locale locale) {
combo.setItemLabelGenerator(it -> getLanguageLabelForCombo(it, locale));
}
private static String getLanguageLabelForCombo(CountryCode country, Locale locale) {
return StringUtils.capitalize(country.getDisplayLanguage(locale));
}
/** Convert the given comparator to a serializable comparator.
*
* @param <T> the type of data that is compared.
* @param comparator the comparator to convert.
* @return the serializable comparator.
*/
public static <T> SerializableComparator<T> toSerializableComparator(Comparator<T> comparator) {
if (comparator == null) {
return null;
}
if (comparator instanceof SerializableComparator<T> cmp) {
return cmp;
}
return (a, b) -> comparator.compare(a, b);
}
/** Create the standard avatar item for the given person.
*
* @param person the person to show in the avatar item, never {@code null}.
* @return the avatar item for the person.
*/
public static AvatarItem newPersonAvatar(Person person) {
return newPersonAvatar(person, null, null);
}
/** Create the standard avatar item for the given person.
*
* @param person the person to show in the avatar item, never {@code null}.
* @param associatedUser the user associated to the person, or {@code null}.
* @param detailsProvider the provider of the details string from the user information, or {@code null}.
* @return the avatar item for the person.
*/
public static AvatarItem newPersonAvatar(Person person, User associatedUser, PersonDetailProvider detailsProvider) {
assert person != null;
final var fullName = person.getFullNameWithLastNameFirst();
final var photo = person.getPhotoURL();
String contactDetails = null;
Integer avatarBorder = null;
if (associatedUser != null) {
final var login = associatedUser.getLogin();
if (!Strings.isNullOrEmpty(login)) {
final var role = associatedUser.getRole();
avatarBorder = Integer.valueOf(role == UserRole.ADMIN ? ADMINISTRATOR_BORDER_COLOR : USER_BORDER_COLOR);
if (detailsProvider != null) {
contactDetails = detailsProvider.getUserDetails(login, role);
}
}
}
final var avatar = new AvatarItem();
avatar.setHeading(fullName);
avatar.setAvatarBorderColor(avatarBorder);
if (!Strings.isNullOrEmpty(contactDetails)) {
avatar.setDescription(contactDetails);
} else if (detailsProvider != null) {
avatar.setDescription(Strings.emptyToNull(detailsProvider.getPersonDetails(person.getEmail())));
} else {
avatar.setDescription(Strings.emptyToNull(person.getEmail()));
}
if (photo != null) {
avatar.setAvatarURL(photo.toExternalForm());
}
return avatar;
}
/** Create the standard avatar item for the given organization, without the organization logo.
*
* @param organization the organization to show in the avatar item, never {@code null}.
* @return the avatar item for the organization.
*/
public static AvatarItem newOrganizationAvatar(ResearchOrganization organization) {
return newOrganizationAvatar(organization, null);
}
/** Create the standard avatar item for the given organization.
*
* @param organization the organization to show in the avatar item, never {@code null}.
* @param fileManager the manager of files that may be used for obtaining the organization logo in the avatar item.
* @return the avatar item for the organization.
*/
public static AvatarItem newOrganizationAvatar(ResearchOrganization organization, FileManager fileManager) {
assert organization != null;
final var acronym = organization.getAcronym();
final var name = organization.getName();
final var logo = organization.getPathToLogo();
final var identifier = organization.getNationalIdentifier();
final var rnsr = organization.getRnsr();
final var details = new StringBuilder();
if (!Strings.isNullOrEmpty(acronym)) {
details.append(acronym);
}
if (!Strings.isNullOrEmpty(identifier)) {
if (details.length() > 0) {
details.append(' ');
}
details.append(identifier);
}
if (!Strings.isNullOrEmpty(rnsr)) {
if (details.length() > 0) {
details.append(" - "); //$NON-NLS-1$
}
details.append("RNSR ").append(rnsr); //$NON-NLS-1$
}
final var avatar = new AvatarItem();
avatar.setHeading(name);
if (details.length() > 0) {
avatar.setDescription(details.toString());
}
if (organization.isMajorOrganization()) {
avatar.setAvatarBorderColor(Integer.valueOf(3));
}
if (fileManager != null) {
var logoFile = FileSystem.convertStringToFile(logo);
if (logoFile != null) {
logoFile = fileManager.normalizeForServerSide(logoFile);
if (logoFile != null) {
avatar.setAvatarResource(ComponentFactory.newStreamImage(logoFile));
}
}
}
return avatar;
}
/** Create the standard avatar item for the given membership.
*
* @param membership the membership to show in the avatar item, never {@code null}.
* @param messages the accessor to the localized messages.
* @param locale the locale to use for building the details.
* @return the avatar item for the membership.
*/
public static AvatarItem newMembershipAvatar(Membership membership, MessageSourceAccessor messages, Locale locale) {
return newMembershipAvatar(membership, messages, locale, null);
}
/** Create the standard avatar item for the given membership.
*
* @param membership the membership to show in the avatar item, never {@code null}.
* @param detailsProvider the provider of the details string from the membership information, never {@code null}.
* @return the avatar item for the membership.
*/
public static AvatarItem newMembershipAvatar(Membership membership, Function<Membership, String> detailsProvider) {
assert detailsProvider != null;
return newMembershipAvatar(membership, null, null, detailsProvider);
}
/** Create the standard avatar item for the given membership.
*
* @param membership the membership to show in the avatar item, never {@code null}.
* @param messages the accessor to the localized messages.
* @param locale the locale to use for building the details.
* @param detailsProvider the provider of the details string from the membership information, or {@code null}.
* @return the avatar item for the membership.
*/
private static AvatarItem newMembershipAvatar(Membership membership, MessageSourceAccessor messages, Locale locale, Function<Membership, String> detailsProvider) {
assert membership != null;
final var person = membership.getPerson();
final var fullName = person.getFullNameWithLastNameFirst();
final var photo = person.getPhotoURL();
final String details;
if (detailsProvider != null) {
details = detailsProvider.apply(membership);
} else {
final StringBuilder label = new StringBuilder();
final var gender = person.getGender();
final var status = membership.getMemberStatus().getLabel(messages, gender, false, locale);
label.append(status);
final var organization = membership.getDirectResearchOrganization().getAcronymOrName();
if (!Strings.isNullOrEmpty(organization)) {
if (label.length() > 0) {
label.append(" - "); //$NON-NLS-1$
}
label.append(organization);
}
details = label.toString();
}
final var avatar = new AvatarItem();
avatar.setHeading(fullName);
avatar.setDescription(Strings.emptyToNull(details));
if (photo != null) {
avatar.setAvatarURL(photo.toExternalForm());
}
return avatar;
}
/** Replies the default label of a membership.
*
* @param membership the membership to show in the avatar item, never {@code null}.
* @param messages the accessor to the localized messages.
* @param locale the locale to use for building the details.
* @return the avatar item for the membership.
*/
public static String newMembershipLabel(Membership membership, MessageSourceAccessor messages, Locale locale) {
assert membership != null;
final var person = membership.getPerson();
final StringBuilder label = new StringBuilder();
final var fullName = person.getFullNameWithLastNameFirst();
label.append(fullName);
final var gender = person.getGender();
final var status = membership.getMemberStatus().getLabel(messages, gender, false, locale);
if (label.length() > 0) {
label.append(" - "); //$NON-NLS-1$
}
label.append(status);
final var organization = membership.getDirectResearchOrganization().getAcronymOrName();
if (!Strings.isNullOrEmpty(organization)) {
if (label.length() > 0) {
label.append(" - "); //$NON-NLS-1$
}
label.append(organization);
}
return label.toString();
}
/** Create the standard avatar item for the given conference, without the year.
*
* @param conference the conference to show in the avatar item, never {@code null}.
* @return the avatar item for the conference.
*/
public static AvatarItem newConferenceAvatar(Conference conference) {
return newConferenceAvatar(conference, 0);
}
/** Create the standard avatar item for the given conference.
*
* @param conference the conference to show in the avatar item, never {@code null}.
* @param year the year of the conference.
* @return the avatar item for the conference.
*/
public static AvatarItem newConferenceAvatar(Conference conference, int year) {
assert conference != null;
final var acronym = conference.getAcronym();
final var name = conference.getName();
final var details = new StringBuilder();
if (!Strings.isNullOrEmpty(acronym)) {
details.append(acronym);
}
if (year > 0) {
details.append("-").append(Integer.toString(year)); //$NON-NLS-1$
}
final var avatar = new AvatarItem();
avatar.setHeading(name);
if (details.length() > 0) {
avatar.setDescription(details.toString());
}
return avatar;
}
/** Create the standard avatar item for the given journal, without the year.
*
* @param journal the journal to show in the avatar item, never {@code null}.
* @return the avatar item for the journal.
*/
public static AvatarItem newJournalAvatar(Journal journal) {
assert journal != null;
final var name = journal.getJournalName();
final var publisher = journal.getPublisher();
final var issn = journal.getISSN();
final var isbn = journal.getISBN();
final var details = new StringBuilder();
if (!Strings.isNullOrEmpty(publisher)) {
details.append(publisher);
}
if (!Strings.isNullOrEmpty(issn)) {
if (details.length() > 0) {
details.append(" - "); //$NON-NLS-1$
}
details.append(issn);
} else if (!Strings.isNullOrEmpty(isbn)) {
if (details.length() > 0) {
details.append(" - "); //$NON-NLS-1$
}
details.append(isbn);
}
final var avatar = new AvatarItem();
avatar.setHeading(name);
if (details.length() > 0) {
avatar.setDescription(details.toString());
}
return avatar;
}
/** Create the standard avatar item for the given project.
*
* @param project the project to show in the avatar item, never {@code null}.
* @return the avatar item for the project.
*/
public static AvatarItem newProjectAvatar(Project project) {
return newProjectAvatar(project, null);
}
/** Create the standard avatar item for the given project.
*
* @param project the project to show in the avatar item, never {@code null}.
* @param fileManager the accessor to the files that are stored on the server.
* @return the avatar item for the project.
*/
public static AvatarItem newProjectAvatar(Project project, FileManager fileManager) {
final var acronym = project.getAcronym();
final var logo = project.getPathToLogo();
final var avatar = new AvatarItem();
avatar.setHeading(acronym);
var emptyLogo = true;
if (fileManager != null) {
var logoFile = FileSystem.convertStringToFile(logo);
if (logoFile != null) {
logoFile = fileManager.normalizeForServerSide(logoFile);
if (logoFile != null) {
avatar.setAvatarResource(ComponentFactory.newStreamImage(logoFile));
emptyLogo = false;
}
}
}
if (emptyLogo) {
avatar.setAvatarResource(ComponentFactory.newEmptyBackgroundStreamImage());
}
return avatar;
}
private static List<StringBuilder> buildCases(String filter) {
final var allCases = new ArrayList<StringBuilder>();
for (final var filterItem : filter.split("[ \n\r\t\f%]+")) { //$NON-NLS-1$
final var filter0 = new StringBuilder(FOR_MANY);
var normedFilter0 = NORMALIZER.normalize(filterItem);
normedFilter0 = normedFilter0.toLowerCase();
final var matcher = PATTERN.matcher(normedFilter0);
normedFilter0 = matcher.replaceAll(FOR_ONE);
filter0.append(normedFilter0);
filter0.append(FOR_MANY);
allCases.add(filter0);
}
return allCases;
}
/** Create a collection of predicate that matches the given keywords.
* The keywords are considered separately as separated words (separator
* is a spacing character) and each word may be part of a larger value.
*
* @param <T> the type of entity.
* @param keywords the keywords to match.
* @param root the root element that must be used for the query.
* @param query the query.
* @param criteriaBuilder the builder of criteria component.
* @param filterBuilder the builder of the filter query. First argument is the query keyword.
* Second argument is the list of predicates to fill up, assuming that they are merged with
* "or". Third argument is {@code root}. Fourth argument is {@code critriaBuilder}.
* @return the predicate for the query.
*/
public static <T> Predicate newPredicateContainsOneOf(String keywords, Root<T> root, CriteriaQuery<?> query,
CriteriaBuilder criteriaBuilder, HqlQueryFilterBuilder<T> filterBuilder) {
assert filterBuilder != null;
final var kws = Strings.nullToEmpty(keywords).trim();
if (!Strings.isNullOrEmpty(kws)) {
final var cases = buildCases(kws);
final var predicates = new ArrayList<Predicate>();
for (final var acase : cases) {
final var predicates0 = new ArrayList<Predicate>();
filterBuilder.buildQueryFor(acase.toString(), predicates0, root, criteriaBuilder);
predicates.add(criteriaBuilder.or(predicates0.toArray(new Predicate[predicates0.size()])));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
return null;
}
/** Show an error notification with the given message.
*
* @param message the message to show up.
* @return the notification object.
*/
public static Notification showErrorNotification(String message) {
final var notification = new Notification(message, ViewConstants.DEFAULT_POPUP_DURATION, ViewConstants.DEFAULT_POPUP_POSITION);
notification.addThemeVariants(NotificationVariant.LUMO_ERROR);
notification.open();
return notification;
}
/** Show a warning notification with the given message.
*
* @param message the message to show up.
* @return the notification object.
*/
public static Notification showWarningNotification(String message) {
final var notification = new Notification(message, ViewConstants.DEFAULT_POPUP_DURATION, ViewConstants.DEFAULT_POPUP_POSITION);
notification.addThemeVariants(NotificationVariant.LUMO_WARNING);
notification.open();
return notification;
}
/** Show a success notification with the given message.
*
* @param message the message to show up.
* @return the notification object.
*/
public static Notification showSuccessNotification(String message) {
final var notification = new Notification(message, ViewConstants.DEFAULT_POPUP_DURATION, ViewConstants.DEFAULT_POPUP_POSITION);
notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);
notification.open();
return notification;
}
/** Show an information notification with the given message.
*
* @param message the message to show up.
* @return the notification object.
*/
public static Notification showInfoNotification(String message) {
final var notification = new Notification(message, ViewConstants.DEFAULT_POPUP_DURATION, ViewConstants.DEFAULT_POPUP_POSITION);
notification.addThemeVariants(NotificationVariant.LUMO_PRIMARY);
notification.open();
return notification;
}
/** Replies the locale that is defined by Vaadin app.
*
* @return the locale.
* @see #getTranslation(String, Object...)
* @see #getTranslation(Locale, String, Object...)
*/
public static Locale getLocale() {
return LocaleUtil.getLocale(LocaleUtil::getI18NProvider);
}
/**
* Get the translation for the locale.
*
* <p>The method never returns a null. If there is no {@link I18NProvider}
* available or no translation for the {@code key} it returns an exception
* string e.g. '!{key}!'.
*
* @param key translation key.
* @param parameters the parameters used in translation string.
* @return translation text.
* @see #getLocale()
* @see #getTranslation(Locale, String, Object...)
*/
public static String getTranslation(String key, Object... parameters) {
final var i18NProvider = LocaleUtil.getI18NProvider();
return i18NProvider.map(i18n -> i18n.getTranslation(key, LocaleUtil.getLocale(() -> i18NProvider), parameters)).orElseGet(() -> "!{" + key + "}!"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Get the translation for the locale.
*
* <p>The method never returns a null. If there is no {@link I18NProvider}
* available or no translation for the {@code key} it returns an exception
* string e.g. '!{key}!'.
*
* @param locale the locale to be used for the message.
* @param key translation key.
* @param parameters the parameters used in translation string.
* @return translation text.
* @see #getLocale()
* @see #getTranslation(String, Object...)
*/
public static String getTranslation(Locale locale, String key, Object... parameters) {
final var i18NProvider = LocaleUtil.getI18NProvider();
return i18NProvider.map(i18n -> i18n.getTranslation(key, locale, parameters)).orElseGet(() -> "!{" + key + "}!"); //$NON-NLS-1$ //$NON-NLS-2$
}
/** Builder of a HQL query filter.
*
* @param <T> the type of entity.
* @author $Author: sgalland$
* @version $Name$ $Revision$ $Date$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 4.0
*/
public interface HqlQueryFilterBuilder<T> extends Serializable {
/** Build the HQL query for the filtering.
*
* @param keyword the keyword to search for.
* @param predicates the list of filtering criteria with "or" semantic, being filled by this function.
* @param root the root not for the search.
* @param criteriaBuilder the criteria builder. It is the Hibernate version in order to
* have access to extra functions, e.g. {@code collate}.
*/
void buildQueryFor(String keyword, List<Predicate> predicates, Root<T> root, CriteriaBuilder criteriaBuilder);
}
/** Provider of details for a person's avatar item.
*
* @author $Author: sgalland$
* @version $Name$ $Revision$ $Date$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 4.0
*/
@FunctionalInterface
public interface PersonDetailProvider extends Serializable {
/** Replies the details string.
*
* @param login the login of the user.
* @param role the role of the user.
* @return the details string.
*/
String getUserDetails(String login, UserRole role);
/** Replies the details string.
*
* @param email the email of the person
* @return the details string.
*/
default String getPersonDetails(String email) {
return Strings.emptyToNull(email);
}
}
}
|
import { createAsyncThunk } from "@reduxjs/toolkit";
import URL from "../../api/URL";
import API_KEY from "../../api/api_key";
import { addSearchQuery } from "../Slices/videoSlice";
export const searchVideosAsync = createAsyncThunk(
"videos/searchVideos",
async function (searchQuery, { rejectedWithValue, dispatch }) {
try {
const {
data: { items: videos },
} = await URL.get("search", {
params: {
part: "snippet",
maxResults: 2,
key: API_KEY,
q: searchQuery,
},
});
// dispatch(addSearchQuery(searchQuery));
return videos;
} catch (e) {
return rejectedWithValue(e.message);
}
}
);
|
import {Test, TestingModule} from '@nestjs/testing';
import {CompetenzeService} from './competenze.service';
import {HttpModule} from '@nestjs/axios';
import {Observable} from 'rxjs';
import {AxiosResponse} from 'axios';
import {CompetenzeModule} from './competenze.module';
import {UpdateCompetenzeDto} from './dto/update-competenze.dto';
import {NotFoundException} from '@nestjs/common';
describe('CompetenzeService', () => {
let service: CompetenzeService;
let apiEsterna: jest.SpyInstance<
Observable<AxiosResponse<CompetenzeModule[], any>>,
[]
>;
let createUUID: jest.SpyInstance<
CompetenzeModule[],
[data: CompetenzeModule[]]
>;
let conpetenzeSet: UpdateCompetenzeDto;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CompetenzeService],
imports: [HttpModule],
}).compile();
service = module.get<CompetenzeService>(CompetenzeService);
apiEsterna = jest.spyOn(service, 'getPersonaAPI');
createUUID = jest.spyOn(service, 'createListWithUUID');
conpetenzeSet = {
id: '1',
nome: 'prova',
obsoleta: false,
descrizione: 'descrizione',
tipologia: 'ambito',
versione: 'V1',
};
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should lista conoscenza vuota', function () {
expect(service.lista.length).toBe(0);
});
it('should lista vuota non chiama api esterna e lista rimane vuota', async () => {
//const spy = jest.spyOn(service, 'getPersonaAPI');
expect(service.lista.length).toBe(0);
await service.findAll();
expect(apiEsterna).not.toBeCalled();
expect(createUUID).not.toBeCalled();
expect(service.lista).toHaveLength(0);
});
it('should con lista piena non chiama api esterna e nemmeno la funzione per uuid', async () => {
service.lista = [
{
id: '1',
nome: 'prova',
obsoleta: false,
descrizione: 'descrizione',
tipologia: 'ambito',
versione: 'V1',
},
];
await service.findAll();
expect(apiEsterna).toBeCalledTimes(0);
expect(createUUID).toBeCalledTimes(0);
expect(service.lista).toHaveLength(1);
});
it('should errore ricerca conoscenza', function () {
expect(() => service.findOne('')).toThrow(NotFoundException);
});
it('should findOne', async () => {
// let res = service.findOne('');
service.lista = [
{
id: '1',
nome: 'prova',
obsoleta: false,
descrizione: 'descrizione',
tipologia: 'ambito',
versione: 'V1',
},
];
// await service.findAll();
const id = service.lista.at(0).id;
const res = service.findOne(id);
expect(res).toEqual({
find: 1,
message: 'OK',
competenze: service.lista.at(0),
});
});
it('should remove conoscenza con lista vuota NotfoundException', function () {
expect(() => service.remove('')).toThrow(NotFoundException);
});
it('should remove persona con id sbagliato', async () => {
// let res = service.findOne('');
service.lista = [
{
id: '1',
nome: 'prova',
obsoleta: false,
descrizione: 'descrizione',
tipologia: 'ambito',
versione: 'V1',
},
];
await service.findAll();
const numeroConpetenze = service.lista.length;
const id = service.lista.at(0).id;
expect(() => service.remove(id + 1)).toThrow(NotFoundException);
const res = service.remove(id);
expect(service.lista).not.toContain(res.persona);
expect(numeroConpetenze).toEqual(service.lista.length + 1);
});
it('should modifica conoscenza con lista vuota oppure con id sbagliato Errore NotFoundException', function () {
expect(() => service.update('', conpetenzeSet)).toThrow(NotFoundException);
service.lista = [
{
id: '1',
nome: 'prova',
obsoleta: false,
descrizione: 'descrizione',
tipologia: 'ambito',
versione: 'V1',
},
];
expect(() => service.update('2', conpetenzeSet)).toThrow(NotFoundException);
expect(() => service.update('1', conpetenzeSet)).not.toThrow(
NotFoundException,
);
});
it('should creazione competenza', async () => {
const objCreate = await service.create({
nome: 'Proviamo',
descrizione: 'Adesso che posiamo',
obsoleta: true,
tipologia: 'ambito',
versione: 'uno',
id: null,
});
const res = service.lista.at(0);
expect(res).toBeDefined();
expect(res).toEqual(objCreate);
});
it('should modifica conoscenza response con conoscenza modificata e lista persona con persona modificata', function () {
service.lista = [
{
id: '1',
nome: 'prova',
obsoleta: false,
descrizione: 'descrizione',
tipologia: 'ambito',
versione: 'V1',
},
];
const res = service.update('1', conpetenzeSet);
expect(res.competenze).toEqual({...conpetenzeSet, id: '1'});
expect(service.lista).toContain(res.competenze);
});
});
|
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
public class Quick5Sample {
public static void sort(Comparable[] a){
StdRandom.shuffle(a);
sort(a,0,a.length-1);
}
private static void sort(Comparable[] a ,int lo,int hi){
if(hi<=lo+4){
Insertion.sort(a, lo, hi);
return;
}
else{
int j= partition(a,lo,hi);
sort(a,lo,j-1);
sort(a,j+1,hi);
}
}
private static int partition(Comparable[] a,int lo,int hi){
Insertion.sort(a, lo, lo+4);
exch(a,lo+4,hi);
int i=lo+2,j=hi+1;
Comparable v =a[lo+2];
while(true){
while(less(a[++i],v));
while(less(v,a[--j]));
if(i>j) break;
exch(a,i,j);
}
exch(a,lo+2,j);
return j;
}
private static boolean less(Comparable v,Comparable w){
return v.compareTo(w)<0;
}
private static void exch(Comparable[] a,int i,int j){
Comparable t =a[i];
a[i]=a[j];
a[j]=t;
}
private static void show(Comparable[] a){
for(int i=0;i<a.length;i++)
StdOut.print(a[i]+" ");
StdOut.println();
}
public static boolean isSorted(Comparable[] a){
for(int i=1;i<a.length;i++)
if(less(a[i],a[i-1])) return false;
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] test ={22,4,2,1,6,8,0,-1,4,12,-9,7,3,-99,23,76,1,90,-2,7,-8,13,27,89,12,17};
sort(test);
show(test);
}
}
|
<?php
namespace App\Providers\App\Listeners;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailer;
use Illuminate\Queue\InteractsWithQueue;
class RegisteredListener
{
private $mailer;
private $eloquent;
/**
* Create the event listener.
*
* @return void
*/
public function __construct(Mailer $mailer, User $eloquent)
{
$this->mailer = $mailer;
$this->eloquent = $eloquent;
}
/**
* Handle the event.
*
* @param \Illuminate\Auth\Events\Registered $event
* @return void
*/
public function handle(Registered $event)
{
$user = $this->eloquent->findOrFail($event->user->getAuthIdentifier());
$this->mailer->raw('회원 등록을 완료했습니다.', function ($message) use ($user) {
$message->subject('회원 등록 메일')->to($user->email);
});
}
}
|
import { mkdirSync, writeFileSync } from "fs";
import { execSync } from "child_process";
import { generateConfigFiles } from "../configfiles/generateConfigFiles";
import { generateReactFiles } from "../reactTemplate/reactTemplate";
import { generateHtmlTemplate } from "../htmlTemplate/htmlTemplate";
import { generateWebpackTemplate } from "../webpackTemplate/webpackTemplate";
function buildProject(projectName: string, projectType: string) {
console.log("Creating TS Project...");
createProjectStructure(projectName);
initializeNpm(projectType);
createConfigFiles(projectName);
createOtherFiles(projectName, projectType);
getTypescriptTypes();
setNpmScripts(projectType);
setUpGit();
process.chdir("../");
console.log("Successfully created ts project.");
}
function createProjectStructure(projectName: string): void {
try {
mkdirSync(`./${projectName}`);
process.chdir(`${projectName}`);
mkdirSync(`./src`);
} catch (error) {
console.error(error);
}
}
function initializeNpm(projectType: string): void {
const devDependencies = fetchDevDependencies(projectType);
console.log("Initializing npm...");
executeCommand("npm init -y");
console.log("Installing dependencies...");
executeCommand(`npm i -D ${devDependencies}`);
if (projectType === "React") {
executeCommand("npm i react react-dom");
}
}
function setNpmScripts(projectType: string) {
executeCommand("npm set-script get-types 'typesync && npm i'");
executeCommand(
`npm set-script format "prettier --config .prettierrc 'src/**/*.ts' --write"`
);
executeCommand("npm set-script lint 'eslint src --ext .ts --fix'");
executeCommand("npm set-script test 'jest --watch'");
switch (projectType) {
case "React":
executeCommand("npm set-script start 'BROWSER=none react-scripts start'");
executeCommand("npm set-script build 'react-scripts build'");
executeCommand("npm set-script test 'react-scripts test'");
executeCommand("npm set-script eject 'react-scripts eject'");
break;
case "Webpack":
executeCommand("npm set-script build 'webpack --watch'");
executeCommand(
`npm set-script dev "concurrently 'npm run build' 'webpack serve --live-reload'"`
);
break;
default:
executeCommand("npm set-script build 'tsc'");
executeCommand("npm set-script watch 'tsc --watch'");
executeCommand("npm set-script start 'ts-node src/index.ts'");
break;
}
}
function setUpGit() {
const ignore = `
node_modules
build
dist
.env
`;
try {
executeCommand("git init");
writeFileSync("./.gitignore", ignore);
executeCommand("git add .");
} catch (error) {
console.error(error);
}
}
function createConfigFiles(projectName: string) {
const configObject = generateConfigFiles(projectName);
try {
writeFileSync("./.eslintrc", configObject.eslint);
writeFileSync("./.prettierrc", configObject.prettier);
writeFileSync("./tsconfig.json", configObject.typescript);
} catch (error) {
console.error(error);
}
}
function getTypescriptTypes(): void {
executeCommand("npx typesync && npm i");
}
function executeCommand(command: string) {
try {
execSync(command, { encoding: "utf-8", stdio: "inherit" });
} catch (error) {
console.log(error);
}
}
function fetchDevDependencies(projectType: string): string {
const devDependencies = [
"typescript",
"typesync",
"@typescript-eslint/parser",
"@typescript-eslint/eslint-plugin",
"prettier",
"jest",
"eslint"
];
switch (projectType) {
case "Nodejs":
devDependencies.push("ts-node");
break;
case "React":
devDependencies.push("react-scripts");
devDependencies.push("@testing-library/react");
devDependencies.push("@testing-library/jest-dom");
devDependencies.push("@testing-library/user-event");
devDependencies.push("eslint-config-react-app");
break;
case "Webpack":
devDependencies.push("webpack");
devDependencies.push("webpack-cli");
devDependencies.push("webpack-dev-server");
devDependencies.push("concurrently");
devDependencies.push("html-webpack-plugin");
devDependencies.push("html-webpack-tags-plugin");
devDependencies.push("ts-loader");
break;
default:
break;
}
return devDependencies.join(" ");
}
function createOtherFiles(projectName: string, projectType: string) {
try {
mkdirSync("./public");
writeFileSync("./src/index.css", "");
if (projectType === "React") {
const files = generateReactFiles(projectName);
mkdirSync("./src/components");
writeFileSync("./public/index.html", files.html);
writeFileSync("./src/components/App.tsx", files.app);
writeFileSync("./src/index.tsx", files.index);
return;
}
if (projectType === "Webpack") {
const config = generateWebpackTemplate();
const html = generateHtmlTemplate(projectName);
writeFileSync("./webpack.config.js", config);
writeFileSync("./src/index.html", html);
}
writeFileSync("./src/index.ts", "//Hello, World!");
} catch (error) {
console.error(error);
}
}
export { buildProject };
|
# Copyright 2023, Erik Myklebust, Andreas Koehler, MIT license
"""
Various variations of PhaseNet
Author: Erik Myklebust
"""
import tensorflow as tf
import tensorflow.keras.layers as tfl
import tensorflow.keras.backend as K
import numpy as np
def crop_and_concat(x, y):
to_crop = x.shape[1] - y.shape[1]
if to_crop < 0:
to_crop = abs(to_crop)
of_start, of_end = to_crop // 2, to_crop // 2
of_end += to_crop % 2
y = tfl.Cropping1D((of_start, of_end))(y)
elif to_crop > 0:
of_start, of_end = to_crop // 2, to_crop // 2
of_end += to_crop % 2
y = tfl.ZeroPadding1D((of_start, of_end))(y)
return tfl.concatenate([x,y])
def crop_and_add(x, y):
to_crop = x.shape[1] - y.shape[1]
if to_crop < 0:
to_crop = abs(to_crop)
of_start, of_end = to_crop // 2, to_crop // 2
of_end += to_crop % 2
y = tfl.Cropping1D((of_start, of_end))(y)
elif to_crop > 0:
of_start, of_end = to_crop // 2, to_crop // 2
of_end += to_crop % 2
y = tfl.ZeroPadding1D((of_start, of_end))(y)
return x + y
class TransformerBlock(tfl.Layer):
def __init__(self, key_dim, num_heads, ff_dim, value_dim=None, rate=0.1):
super().__init__()
self.att = tfl.MultiHeadAttention(num_heads=num_heads,
key_dim=key_dim,
value_dim=value_dim)
self.ffn = tf.keras.Sequential(
[tfl.Dense(ff_dim, activation="relu"), tfl.Dense(key_dim)]
)
self.layernorm1 = tfl.LayerNormalization(epsilon=1e-6)
self.layernorm2 = tfl.LayerNormalization(epsilon=1e-6)
self.dropout1 = tfl.Dropout(rate)
self.dropout2 = tfl.Dropout(rate)
def call(self, inputs, training):
if isinstance(inputs, (list, tuple)):
query, value = inputs
else:
query, value = inputs, inputs
attn_output = self.att(query, value)
attn_output = self.dropout1(attn_output, training=training)
out1 = self.layernorm1(query + attn_output)
ffn_output = self.ffn(out1)
ffn_output = self.dropout2(ffn_output, training=training)
return self.layernorm2(out1 + ffn_output)
class ResnetBlock1D(tfl.Layer):
def __init__(self,
filters,
kernelsize,
activation='linear',
dropout=0.1, **kwargs):
"""1D resnet block
Args:
filters (int): number of filters .
kernel_size (int): size of filters .
activation (str): layer activation.
dropout (float): dropout fraction .
"""
super(ResnetBlock1D, self).__init__()
self.filters = filters
self.projection = tfl.Conv1D(filters, 1, padding='same', **kwargs)
self.conv1 = tfl.Conv1D(filters, kernelsize, activation=None, padding='same', **kwargs)
self.conv2 = tfl.Conv1D(filters, kernelsize, activation=None, padding='same', **kwargs)
self.dropout1 = tfl.Dropout(dropout)
self.bn1 = tfl.BatchNormalization()
self.bn2 = tfl.BatchNormalization()
self.bn3 = tfl.BatchNormalization()
self.add = tfl.Add()
self.relu = tfl.Activation(activation)
def call(self, inputs, training=None):
x = self.projection(inputs)
fx = self.bn1(inputs)
fx = self.conv1(fx)
fx = self.bn2(fx)
fx = self.relu(fx)
fx = self.dropout1(fx)
fx = self.conv2(fx)
x = self.add([x, fx])
x = self.bn3(x)
x = self.relu(x)
return x
class ResidualConv1D(tfl.Layer):
def __init__(self,
filters=32,
kernel_size=3,
stacked_layer=1,
activation='relu',
causal=False):
"""1D residual convolution
Args:
filters (int): number of filters.
kernel_size (int): size of filters .
stacked_layers (int): number of stacked layers .
"""
super(ResidualConv1D, self).__init__()
self.filters = filters
self.kernel_size = kernel_size
self.stacked_layer = stacked_layer
self.causal = causal
self.activation = activation
def build(self, input_shape):
self.sigmoid_layers = []
self.tanh_layers = []
self.conv_layers = []
self.shape_matching_layer = tfl.Conv1D(self.filters, 1, padding = 'same')
self.add = tfl.Add()
self.final_activation = tf.keras.activations.get(self.activation)
for dilation_rate in [2 ** i for i in range(self.stacked_layer)]:
self.sigmoid_layers.append(
tfl.Conv1D(self.filters, self.kernel_size, dilation_rate=dilation_rate,
padding='causal' if self.causal else 'same',
activation='sigmoid'))
self.tanh_layers.append(
tfl.Conv1D(self.filters, self.kernel_size, dilation_rate=dilation_rate,
padding='causal' if self.causal else 'same',
activation='tanh'))
self.conv_layers.append(tfl.Conv1D(self.filters, 1, padding='same'))
def get_config(self):
return dict(name=self.name,
filters=self.filters,
kernel_size=self.kernel_size,
stacked_layer=self.stacked_layer)
def call(self, inputs):
out = self.shape_matching_layer(inputs)
residual_output = out
x = inputs
for sl, tl, cl in zip(self.sigmoid_layers, self.tanh_layers, self.conv_layers):
sigmoid_x = sl(x)
tanh_x = tl(x)
x = tfl.multiply([sigmoid_x, tanh_x])
x = cl(x)
residual_output = tfl.add([residual_output, x])
return self.final_activation(self.add([out, x]))
class PhaseNet(tf.keras.Model):
def __init__(self,
num_classes=2,
filters=None,
kernelsizes=None,
output_activation='linear',
kernel_regularizer=None,
dropout_rate=0.2,
pool_type='max',
activation='relu',
initializer='glorot_normal',
conv_type='default',
name='PhaseNet'):
"""Adapted to 1D from https://keras.io/examples/vision/oxford_pets_image_segmentation/
Args:
num_classes (int, optional): number of outputs. Defaults to 2.
filters (list, optional): list of number of filters. Defaults to None.
kernelsizes (list, optional): list of kernel sizes. Defaults to None.
output_activation (str, optional): output activation, eg., 'softmax' for multiclass problems. Defaults to 'linear'.
kernel_regularizer (tf.keras.regualizers.Regualizer, optional): kernel regualizer. Defaults to None.
dropout_rate (float, optional): dropout. Defaults to 0.2.
initializer (tf.keras.initializers.Initializer, optional): weight initializer. Defaults to 'glorot_normal'.
name (str, optional): model name. Defaults to 'PhaseNet'.
"""
super(PhaseNet, self).__init__(name=name)
self.num_classes = num_classes
self.initializer = initializer
self.kernel_regularizer = kernel_regularizer
self.dropout_rate = dropout_rate
self.output_activation = output_activation
self.activation = activation
if filters is None:
self.filters = [4, 8, 16, 32]
else:
self.filters = filters
if kernelsizes is None:
self.kernelsizes = [7, 7, 7, 7]
else:
self.kernelsizes = kernelsizes
if pool_type == 'max':
self.pool_layer = tfl.MaxPooling1D
else:
self.pool_layer = tfl.AveragePooling1D
if conv_type == 'seperable':
self.conv_layer = tfl.SeparableConv1D
else:
self.conv_layer = tfl.Conv1D
def _down_block(self, f, ks, x):
x = self.conv_layer(f,
ks,
padding="same",
kernel_regularizer=self.kernel_regularizer,
kernel_initializer=self.initializer)(x)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
x = self.pool_layer(4, 2, padding='same')(x)
return x
def _up_block(self, f, ks, x):
x = self.conv_layer(f,
ks,
padding="same",
kernel_regularizer=self.kernel_regularizer,
kernel_initializer=self.initializer)(x)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
x = tfl.UpSampling1D(2)(x)
return x
def build(self, input_shape):
inputs = tf.keras.Input(shape=input_shape[1:])
### [First half of the network: downsampling inputs] ###
# Entry block
x = self.conv_layer(self.filters[0],
self.kernelsizes[0],
kernel_regularizer=self.kernel_regularizer,
padding="same",
name='entry')(inputs)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
skips = [x]
# Blocks 1, 2, 3 are identical apart from the feature depth.
for i, _ in enumerate(self.filters):
x = self._down_block(self.filters[i], self.kernelsizes[i], x)
skips.append(x)
skips = skips[:-1]
self.encoder = tf.keras.Model(inputs, x)
for i in list(range(len(self.filters)))[::-1]:
x = self._up_block(self.filters[i], self.kernelsizes[i], x)
x = crop_and_concat(x, skips[i])
to_crop = x.shape[1] - input_shape[1]
if to_crop != 0:
of_start, of_end = to_crop // 2, to_crop // 2
of_end += to_crop % 2
x = tfl.Cropping1D((of_start, of_end))(x)
#Exit block
x = self.conv_layer(self.filters[0],
self.kernelsizes[0],
kernel_regularizer=self.kernel_regularizer,
padding="same",
name='exit')(x)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
# Add a per-pixel classification layer
if self.num_classes is not None:
x = tfl.Conv1D(self.num_classes,
1,
padding="same")(x)
outputs = tfl.Activation(self.output_activation, dtype='float32')(x)
else:
outputs = x
# Define the model
self.model = tf.keras.Model(inputs, outputs)
@property
def num_parameters(self):
return sum([np.prod(K.get_value(w).shape) for w in self.model.trainable_weights])
def summary(self):
return self.model.summary()
def call(self, inputs):
return self.model(inputs)
class EPick(PhaseNet):
def __init__(self,
num_classes=2,
output_layer=None,
filters=None,
kernelsizes=None,
output_activation='linear',
kernel_regularizer=None,
dropout_rate=0.2,
att_type='additive',
activation='relu',
pool_type='max',
initializer='glorot_normal',
residual_attention=None,
name='EPick'):
"""
https://arxiv.org/abs/2109.02567
Args:
num_classes (int, optional): number of outputs. Defaults to 2.
filters (list, optional): list of number of filters. Defaults to None.
kernelsizes (list, optional): list of kernel sizes. Defaults to None.
residual_attention (list: optional): list of residual attention sizes, one longer that filters.
att_type (str): dot or concat
output_activation (str, optional): output activation, eg., 'softmax' for multiclass problems. Defaults to 'linear'.
kernel_regularizer (tf.keras.regualizers.Regualizer, optional): kernel regualizer. Defaults to None.
dropout_rate (float, optional): dropout. Defaults to 0.2.
initializer (tf.keras.initializers.Initializer, optional): weight initializer. Defaults to 'glorot_normal'.
name (str, optional): model name. Defaults to 'PhaseNet'.
"""
super(EPick, self).__init__(num_classes=num_classes,
filters=filters,
kernelsizes=kernelsizes,
output_activation=output_activation,
kernel_regularizer=kernel_regularizer,
dropout_rate=dropout_rate,
pool_type=pool_type,
activation=activation,
initializer=initializer,
name=name)
if residual_attention is None:
self.residual_attention = [16, 16, 16, 16, 16]
else:
self.residual_attention = residual_attention
def _down_block(self, f, ks, x):
x = tfl.Conv1D(f, ks, padding="same",
kernel_regularizer=self.kernel_regularizer,
kernel_initializer=self.initializer,
)(x)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
x = self.pool_layer(4, strides=2, padding='same')(x)
return x
def _up_block(self, f, ks, x, upsample=True):
x = tfl.Conv1DTranspose(f, ks, padding="same",
kernel_regularizer=self.kernel_regularizer,
kernel_initializer=self.initializer,
)(x)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
if upsample:
x = tfl.UpSampling1D(2)(x)
return x
def build(self, input_shape):
inputs = tf.keras.Input(shape=input_shape[1:])
### [First half of the network: downsampling inputs] ###
# Entry block
x = tfl.Conv1D(self.filters[0], self.kernelsizes[0],
strides=1,
kernel_regularizer=self.kernel_regularizer,
padding="same",
name='entry')(inputs)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
skips = [x]
# Blocks 1, 2, 3 are identical apart from the feature depth.
for ks, f in zip(self.kernelsizes[1:], self.filters[1:]):
x = self._down_block(f, ks, x)
skips.append(x)
attentions = []
for i, skip in enumerate(skips):
if self.residual_attention[i] <= 0:
att = skip
elif i == 0:
att = tfl.MultiHeadAttention(num_heads=8,
key_dim=self.residual_attention[i],)(skip, skip, return_attention_scores=False)
else:
tmp = []
z = skips[i]
for j, skip2 in enumerate(skips[:i]):
if self.residual_attention[j] <= 0:
att = tfl.Conv1D(self.filters[j], 3, activation='relu', padding='same')(z)
else:
att = tfl.MultiHeadAttention(num_heads=8,
key_dim=self.residual_attention[j])(z, skip2, return_attention_scores=False)
tmp.append(att)
att = tfl.Concatenate()(tmp)
attentions.append(att)
x = crop_and_concat(x, attentions[-1])
self.encoder = tf.keras.Model(inputs, x)
i = len(self.filters) - 1
for f, ks in zip(self.filters[::-1][:-1], self.kernelsizes[::-1][:-1]):
x = self._up_block(f, ks, x, upsample = i != 0)
x = crop_and_concat(x, attentions[i-1])
i -= 1
to_crop = x.shape[1] - input_shape[1]
if to_crop != 0:
of_start, of_end = to_crop // 2, to_crop // 2
of_end += to_crop % 2
x = tfl.Cropping1D((of_start, of_end))(x)
# Add a per-pixel classification layer
if self.num_classes is not None:
x = tfl.Conv1D(self.num_classes,
1,
padding="same")(x)
outputs = tfl.Activation(self.output_activation, dtype='float32')(x)
elif self.output_layer is not None:
outputs = self.output_layer(x)
else:
outputs = x
# Define the model
self.model = tf.keras.Model(inputs, outputs)
@property
def num_parameters(self):
return sum([np.prod(K.get_value(w).shape) for w in self.model.trainable_weights])
def summary(self):
return self.model.summary()
def call(self, inputs):
return self.model(inputs)
class EarthQuakeTransformer(tf.keras.Model):
def __init__(self,
input_dim,
filters=None,
kernelsizes=None,
resfilters=None,
reskernelsizes=None,
lstmfilters=None,
attention_width=3,
dropout=0.0,
transformer_sizes=None,
kernel_regularizer=None,
classify=True,
pool_type='max',
att_type='additive',
activation='relu',
name='EarthQuakeTransformer'):
"""
https://www.nature.com/articles/s41467-020-17591-w
Example usage:
import numpy as np
test = np.random.random(size=(16,1024,3))
detection = np.random.randint(2, size=(16,1024,1))
p_arrivals = np.random.randint(2, size=(16,1024,1))
s_arrivals = np.random.randint(2, size=(16,1024,1))
model = EarthQuakeTransformer(input_dim=test.shape[1:])
model.compile(optimizer='adam', loss=['binary_crossentropy',
'binary_crossentropy',
'binary_crossentropy'])
model.fit(test, (detection,p_arrivals,s_arrivals))
Args:
input_dim (tuple): input size of the model.
filters (list, optional): list of number of filters. Defaults to None.
kernelsizes (list, optional): list of kernel sizes. Defaults to None.
resfilters (list, optional): list of number of residual filters. Defaults to None.
reskernelsizes (list, optional): list of residual filter sizes. Defaults to None.
lstmfilters (list, optional): list of number of lstm filters. Defaults to None.
attention_width (int, optional): width of attention mechanism. Defaults to 3. Use None for full.
dropout (float, optional): dropout. Defaults to 0.0.
transformer_sizes (list, optional): list of sizes of attention layers. Defaults to [64, 64].
kernel_regularizer (tf.keras.regualizers.Regualizer, optional): kernel regualizer. Defaults to None.
classify (bool, optional): whether to classify phases or provide raw output. Defaults to True.
att_type (str, optional): attention type. Defaults to 'additive'. 'multiplicative' is also supported.
name (str, optional): model name. Defaults to 'EarthQuakeTransformer'.
"""
super(EarthQuakeTransformer, self).__init__(name=name)
if filters is None:
filters = [8, 16, 16, 32, 32, 64, 64]
if kernelsizes is None:
kernelsizes = [11, 9, 7, 7, 5, 5, 3]
invfilters = filters[::-1]
invkernelsizes = kernelsizes[::-1]
if resfilters is None:
resfilters = [64, 64, 64, 64, 64]
if reskernelsizes is None:
reskernelsizes = [3, 3, 3, 2, 2]
if lstmfilters is None:
lstmfilters = [16, 16]
if transformer_sizes is None:
transformer_sizes = [64,64]
pool_layer = tfl.MaxPooling1D if pool_type == 'max' else tfl.AveragePooling1D
def conv_block(f,kz):
return tf.keras.Sequential([tfl.Conv1D(f, kz, padding='same', kernel_regularizer=kernel_regularizer),
tfl.BatchNormalization(),
tfl.Activation(activation),
tfl.Dropout(dropout),
pool_layer(4, strides=2, padding="same")])
def block_BiLSTM(f, x):
'Returns LSTM residual block'
x = tfl.Bidirectional(tfl.LSTM(f, return_sequences=True))(x)
x = tfl.Conv1D(f, 1, padding='same', kernel_regularizer=kernel_regularizer)(x)
x = tfl.BatchNormalization()(x)
return x
def _encoder():
inp = tfl.Input(input_dim)
def encode(x):
for f, kz in zip(filters, kernelsizes):
x = conv_block(f, kz)(x)
for f, kz in zip(resfilters, reskernelsizes):
x = ResnetBlock1D(f,
kz,
activation=activation,
dropout=dropout,
kernel_regularizer=kernel_regularizer)(x)
for f in lstmfilters:
x = block_BiLSTM(f, x)
x = tfl.LSTM(f, return_sequences=True, kernel_regularizer=kernel_regularizer)(x)
for ts in transformer_sizes:
x = TransformerBlock(num_heads=8, key_dim=ts, ff_dim=ts*4, rate=dropout)(x)
return x
return tf.keras.Model(inp, encode(inp))
def inv_conv_block(f,kz):
return tf.keras.Sequential([tfl.UpSampling1D(2),
tfl.Conv1D(f, kz, padding='same', kernel_regularizer=kernel_regularizer),
tfl.BatchNormalization(),
tfl.Activation(activation),
tfl.Dropout(dropout)])
def _decoder(input_shape, attention=False, activation='sigmoid', output_name=None):
inp = tfl.Input(input_shape)
x = inp
if attention:
x = tfl.LSTM(filters[-1],
return_sequences=True,
kernel_regularizer=kernel_regularizer)(x)
x = TransformerBlock(num_heads=8, ff_dim=filters[-1]*4, key_dim=filters[-1])(x)
x = tf.keras.Sequential([inv_conv_block(f, kz) for f, kz in zip(invfilters, invkernelsizes)])(x)
to_crop = x.shape[1] - input_dim[0]
of_start, of_end = to_crop//2, to_crop//2
of_end += to_crop % 2
x = tfl.Cropping1D((of_start, of_end))(x)
if activation is not None:
x = tfl.Conv1D(1, 1,
padding='same')(x)
x = tfl.Activation(activation,
name=output_name,
dtype=tf.float32)(x)
return tf.keras.Model(inp, x)
self.feature_extractor = _encoder()
encoded_dim = self.feature_extractor.layers[-1].output.shape[1:]
self.detector = _decoder(encoded_dim, attention=False, activation='sigmoid' if classify else None, output_name='detection')
self.p_picker = _decoder(encoded_dim, attention=True, activation='sigmoid' if classify else None, output_name='p_phase')
self.s_picker = _decoder(encoded_dim, attention=True, activation='sigmoid' if classify else None, output_name='s_phase')
@property
def num_parameters(self):
s = 0
for m in [self.feature_extractor, self.detector, self.s_picker, self.p_picker]:
s += sum([np.prod(K.get_value(w).shape) for w in m.trainable_weights])
return s
def call(self, inputs):
encoded = self.feature_extractor(inputs)
d = self.detector(encoded)
p = self.p_picker(encoded)
s = self.s_picker(encoded)
return d, p, s
class TransPhaseNet(PhaseNet):
def __init__(self,
num_classes=2,
filters=None,
kernelsizes=None,
output_activation='linear',
kernel_regularizer=None,
dropout_rate=0.2,
initializer='glorot_normal',
residual_attention=None,
pool_type='max',
att_type='across',
num_transformers=1,
rnn_type='lstm',
additive_att=True,
stacked_layer=4,
activation='relu',
name='TransPhaseNet'):
"""Adapted to 1D from https://keras.io/examples/vision/oxford_pets_image_segmentation/
Args:
num_classes (int, optional): number of outputs. Defaults to 2.
filters (list, optional): list of number of filters. Defaults to None.
kernelsizes (list, optional): list of kernel sizes. Defaults to None.
residual_attention (list: optional): list of residual attention sizes, one longer that filters.
output_activation (str, optional): output activation, eg., 'softmax' for multiclass problems. Defaults to 'linear'.
kernel_regularizer (tf.keras.regualizers.Regualizer, optional): kernel regualizer. Defaults to None.
dropout_rate (float, optional): dropout. Defaults to 0.2.
initializer (tf.keras.initializers.Initializer, optional): weight initializer. Defaults to 'glorot_normal'.
name (str, optional): model name. Defaults to 'PhaseNet'.
att_type (str, optional): if the attention should work during downstep or across (self attention).
rnn_type (str, optional): use "lstm" rnns or "causal" dilated conv.
"""
super(TransPhaseNet, self).__init__(num_classes=num_classes,
filters=filters,
kernelsizes=kernelsizes,
output_activation=output_activation,
kernel_regularizer=kernel_regularizer,
dropout_rate=dropout_rate,
pool_type=pool_type,
activation=activation,
initializer=initializer,
name=name)
self.att_type = att_type
self.rnn_type = rnn_type
self.stacked_layer = stacked_layer
self.additive_att = additive_att
self.num_transformers = num_transformers
if residual_attention is None:
self.residual_attention = [16, 16, 16, 16]
else:
self.residual_attention = residual_attention
def _down_block(self, f, ks, x):
x = ResnetBlock1D(f,
ks,
activation=self.activation,
dropout=self.dropout_rate)(x)
x = self.pool_layer(4, strides=2, padding="same")(x)
return x
def _up_block(self, f, ks, x):
x = ResnetBlock1D(f,
ks,
activation=self.activation,
dropout=self.dropout_rate)(x)
x = tfl.UpSampling1D(2)(x)
return x
def _att_block(self, x, y, ra):
if self.rnn_type == 'lstm':
x = tfl.Bidirectional(tfl.LSTM(ra, return_sequences=True))(x)
elif self.rnn_type == 'causal':
x1 = ResidualConv1D(ra, 3, stacked_layer=self.stacked_layer, causal=True)(x)
x2 = ResidualConv1D(ra, 3, stacked_layer=self.stacked_layer, causal=True)(tf.reverse(x, axis=[1]))
x = tf.concat([x1, tf.reverse(x2, axis=[1])], axis=-1)
else:
raise NotImplementedError('rnn type:' + self.rnn_type + ' is not supported')
x = tfl.Conv1D(ra, 1, padding='same')(x)
att = TransformerBlock(num_heads=8,
key_dim=ra,
ff_dim=ra*4,
rate=self.dropout_rate)([x,y])
if self.num_transformers > 1:
for _ in range(1, self.num_transformers):
att = TransformerBlock(num_heads=8,
key_dim=ra,
ff_dim=ra*4,
rate=self.dropout_rate)(att)
return att
def build(self, input_shape):
inputs = tf.keras.Input(shape=input_shape[1:])
# Entry block
x = ResnetBlock1D(self.filters[0],
self.kernelsizes[0],
activation=self.activation,
dropout=self.dropout_rate)(inputs)
skips = [x]
# Blocks 1, 2, 3 are identical apart from the feature depth.
for i in range(1, len(self.filters)):
x = self._down_block(self.filters[i], self.kernelsizes[i], x)
if self.residual_attention[i] > 0 and self.att_type == 'downstep':
att = self._att_block(x, skips[-1], self.residual_attention[i])
if self.additive_att:
x += att
else:
x = crop_and_add(x, att)
x = tfl.Conv1D(self.filters[i], 1, padding='same')(x)
skips.append(x)
if self.residual_attention[-1] > 0:
att = self._att_block(x, x, self.residual_attention[-1])
if self.additive_att:
x = crop_and_add(x, att)
else:
x = crop_and_concat(x, att)
x = tfl.Conv1D(self.filters[-1], 1, padding='same')(x)
self.encoder = tf.keras.Model(inputs, x)
### [Second half of the network: upsampling inputs] ###
for i in range(1, len(self.filters)):
x = self._up_block(self.filters[::-1][i], self.kernelsizes[::-1][i], x)
if self.residual_attention[::-1][i] > 0 and self.att_type == 'across':
att = self._att_block(skips[::-1][i], skips[::-1][i], self.residual_attention[::-1][i])
if self.additive_att:
x = crop_and_add(x, att)
else:
x = crop_and_concat(x, att)
x = tfl.Conv1D(self.filters[::-1][i], 1, padding='same')(x)
to_crop = x.shape[1] - input_shape[1]
if to_crop != 0:
of_start, of_end = to_crop // 2, to_crop // 2
of_end += to_crop % 2
x = tfl.Cropping1D((of_start, of_end))(x)
#Exit block
x = tfl.Conv1D(self.filters[0],
self.kernelsizes[0],
strides=1,
kernel_regularizer=self.kernel_regularizer,
padding="same",
name='exit')(x)
x = tfl.BatchNormalization()(x)
x = tfl.Activation(self.activation)(x)
x = tfl.Dropout(self.dropout_rate)(x)
# Add a per-pixel classification layer
if self.num_classes is not None:
x = tfl.Conv1D(self.num_classes,
1,
padding="same")(x)
outputs = tfl.Activation(self.output_activation, dtype='float32')(x)
else:
outputs = x
# Define the model
self.model = tf.keras.Model(inputs, outputs)
@property
def num_parameters(self):
return sum([np.prod(K.get_value(w).shape) for w in self.model.trainable_weights])
def summary(self):
return self.model.summary()
def call(self, inputs):
return self.model(inputs)
|
import { Item } from "./Item";
import { Pages } from "./pages";
export class Comics extends Item {
constructor(protected _title: string, protected _artist: string ,protected _author: string, readonly pages: Pages){
super();
}
get title(): string{
return this._title;
}
set title(newTitle: string){
this._title = newTitle;
}
get author(): string{
return this._author;
}
set author(newAuthor: string){
this._author = newAuthor;
}
get artist(): string{
return this._artist;
}
set artist(newArtist: string){
this._artist = newArtist;
}
toString(): string {
return `Comics: ${this.title} by ${this.artist}, the artist is ${this.author}, number of pages: ${this.pages.pages.length}`
}
}
|
import cv2
import os
import tempfile
import time
import gradio as gr
from gradio_rerun import Rerun
import rerun as rr
import rerun.blueprint as rrb
from color_grid import build_color_grid
# NOTE: Functions that work with Rerun should be decorated with `@rr.thread_local_stream`.
# This decorator creates a generator-aware thread-local context so that rerun log calls
# across multiple workers stay isolated.
# A task can directly log to a binary stream, which is routed to the embedded viewer.
# Incremental chunks are yielded to the viewer using `yield stream.read()`.
#
# This is the preferred way to work with Rerun in Gradio since your data can be immediately and
# incrementally seen by the viewer. Also, there are no ephemeral RRDs to cleanup or manage.
@rr.thread_local_stream("rerun_example_streaming_blur")
def streaming_repeated_blur(img):
stream = rr.binary_stream()
if img is None:
raise gr.Error("Must provide an image to blur.")
blueprint = rrb.Blueprint(
rrb.Horizontal(
rrb.Spatial2DView(origin="image/original"),
rrb.Spatial2DView(origin="image/blurred"),
),
collapse_panels=True,
)
rr.send_blueprint(blueprint)
rr.set_time_sequence("iteration", 0)
rr.log("image/original", rr.Image(img))
yield stream.read()
blur = img
for i in range(100):
rr.set_time_sequence("iteration", i)
# Pretend blurring takes a while so we can see streaming in action.
time.sleep(0.1)
blur = cv2.GaussianBlur(blur, (5, 5), 0)
rr.log("image/blurred", rr.Image(blur))
# Each time we yield bytes from the stream back to Gradio, they
# are incrementally sent to the viewer. Make sure to yield any time
# you want the user to be able to see progress.
yield stream.read()
# However, if you have a workflow that creates an RRD file instead, you can still send it
# directly to the viewer by simply returning the path to the RRD file.
#
# This may be helpful if you need to execute a helper tool written in C++ or Rust that can't
# be easily modified to stream data directly via Gradio.
#
# In this case you may want to clean up the RRD file after it's sent to the viewer so that you
# don't accumulate too many temporary files.
@rr.thread_local_stream("rerun_example_cube_rrd")
def create_cube_rrd(x, y, z, pending_cleanup):
cube = build_color_grid(int(x), int(y), int(z), twist=0)
rr.log("cube", rr.Points3D(cube.positions, colors=cube.colors, radii=0.5))
# We eventually want to clean up the RRD file after it's sent to the viewer, so tracking
# any pending files to be cleaned up when the state is deleted.
temp = tempfile.NamedTemporaryFile(prefix="cube_", suffix=".rrd", delete=False)
pending_cleanup.append(temp.name)
blueprint = rrb.Spatial3DView(origin="cube")
rr.save(temp.name, default_blueprint=blueprint)
# Just return the name of the file -- Gradio will convert it to a FileData object
# and send it to the viewer.
return temp.name
def cleanup_cube_rrds(pending_cleanup):
for f in pending_cleanup:
os.unlink(f)
with gr.Blocks() as demo:
with gr.Tab("Streaming"):
with gr.Row():
img = gr.Image(interactive=True, label="Image")
with gr.Column():
stream_blur = gr.Button("Stream Repeated Blur")
with gr.Tab("Dynamic RRD"):
pending_cleanup = gr.State(
[], time_to_live=10, delete_callback=cleanup_cube_rrds
)
with gr.Row():
x_count = gr.Number(
minimum=1, maximum=10, value=5, precision=0, label="X Count"
)
y_count = gr.Number(
minimum=1, maximum=10, value=5, precision=0, label="Y Count"
)
z_count = gr.Number(
minimum=1, maximum=10, value=5, precision=0, label="Z Count"
)
with gr.Row():
create_rrd = gr.Button("Create RRD")
with gr.Tab("Hosted RRD"):
with gr.Row():
# It may be helpful to point the viewer to a hosted RRD file on another server.
# If an RRD file is hosted via http, you can just return a URL to the file.
choose_rrd = gr.Dropdown(
label="RRD",
choices=[
f"{rr.bindings.get_app_url()}/examples/arkit_scenes.rrd",
f"{rr.bindings.get_app_url()}/examples/dna.rrd",
f"{rr.bindings.get_app_url()}/examples/plots.rrd",
],
)
# Rerun 0.16 has issues when embedded in a Gradio tab, so we share a viewer between all the tabs.
# In 0.17 we can instead scope each viewer to its own tab to clean up these examples further.
with gr.Row():
viewer = Rerun(
streaming=True,
)
stream_blur.click(streaming_repeated_blur, inputs=[img], outputs=[viewer])
create_rrd.click(
create_cube_rrd,
inputs=[x_count, y_count, z_count, pending_cleanup],
outputs=[viewer],
)
choose_rrd.change(lambda x: x, inputs=[choose_rrd], outputs=[viewer])
if __name__ == "__main__":
demo.launch()
|
import { Component, OnInit, ViewChild } from '@angular/core';
import { User } from '../../models/interfaces/user.interface';
import { Message, STATES } from '../../models/interfaces/message.interface';
import { Storage } from '@ionic/storage';
import { IonInfiniteScroll, NavParams } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { UserService } from '../../services/user/user.service';
import { MessageService } from '../../services/message/message.service';
import { LoggerService } from '../../services/logger/logger.service';
import { PushService } from '../../services/push/push.service';
@Component({
selector: 'app-conversation',
templateUrl: './conversation.page.html',
styleUrls: ['./conversation.page.scss'],
})
export class ConversationPage implements OnInit {
idLog = 'ConversationPage'
conversation: Message[] = []
user: User;
to: User;
message: string = ''
lastDocument: any = {}
load: boolean = false
conversationId
limit: number = 5;
constructor(
private storage: Storage,
private route: ActivatedRoute,
private userService: UserService,
private messageService: MessageService,
private logger: LoggerService,
private pushService: PushService
) {
}
async ngOnInit() {
this.user = await this.storage.get('currentUser')
}
ionViewWillEnter() {
const id = this.route.snapshot.params.id;
this.getUserById(id)
}
async sendMessage() {
if (this.message.trim() == '') {
return;
}
try {
let message: Message = {
id: '',
conversationId: this.conversationId,
date: Date.now(),
from: this.user.id,
to: this.to.id,
state: STATES.SENT,
message: this.message
}
this.conversation.push({ ...message, state: STATES.SENDING });
const response = await this.messageService.saveMessage(message);
this.logger.log(this.idLog, 'sendMessage', { info: 'Success', message, response })
const sendMessage = this.message
if (this.to.pushId && this.to.pushId != '') {
await this.pushService.sendMessage({ message: sendMessage, toId: [this.to.pushId] })
}
this.message = ''
this.conversation[this.conversation.length - 1].state = STATES.SENT;
this.goToBottom()
} catch (e) {
this.logger.error(this.idLog, 'sendMessage', { info: 'Error send message', error: e })
}
}
async getUserById(userId) {
try {
this.to = await this.userService.getUserById(userId)
let idsArray = [this.user.userId, this.to.userId].sort()
this.conversationId = idsArray.join('||')
this.logger.log(this.idLog, 'getUserById', { info: 'Success get user', response: this.to })
await this.getMessages()
setTimeout(() => {
this.goToBottom()
}, 1000)
} catch (e) {
this.logger.error(this.idLog, 'getUserById', { info: 'Error get user', error: e })
}
}
async getMessages() {
try {
let params = {
id: this.conversationId,
lastDocument: this.lastDocument,
order: 'date',
limit: this.limit,
}
this.messageService.getMessages(params)
.subscribe(resp => {
this.logger.log(this.idLog, 'getMessages', { info: 'Success get messages', response: resp })
this.lastDocument = resp[resp.length - 1]
this.conversation = resp.reverse();
})
} catch (e) {
this.logger.error(this.idLog, 'getMessages', { info: 'Error get messages', error: e })
}
}
goToBottom() {
setTimeout(() => {
if (document.getElementById('chat-container')) {
let height = document.getElementById('chat-container').scrollHeight
let content = document.querySelector('ion-content').scrollHeight
console.log({ height, content })
setTimeout(() => {
console.log({ height, content })
document.getElementById('chat-container').scrollTop = height
}, 10)
}
}, 100);
}
doRefresh(event) {
this.getBackMessages()
let height = document.getElementById('chat-container').scrollHeight
let content = document.querySelector('ion-content').scrollHeight
let position = document.body.scrollTop
let scrollTop = document.documentElement.scrollTop
console.log({ height, content, position, scrollTop })
setTimeout(() => {
event.target.complete();
}, 2000);
}
getBackMessages() {
this.limit += 5;
this.getMessages()
}
}
|
STRING digits = "123456789";
[4]CHAR chosen;
STRING available := digits;
FOR i TO UPB chosen DO
INT c = ENTIER(random*UPB available)+1;
chosen[i] := available[c];
available := available[:c-1]+available[c+1:]
OD;
COMMENT print((chosen, new line)); # Debug # END COMMENT
OP D = (INT d)STRING: whole(d,0); # for formatting an integer #
print (("I have chosen a number from ",D UPB chosen," unique digits from 1 to 9 arranged in a random order.", new line,
"You need to input a ",D UPB chosen," digit, unique digit number as a guess at what I have chosen", new line));
PRIO WITHIN = 5, NOTWITHIN = 5;
OP WITHIN = (CHAR c, []CHAR s)BOOL: char in string(c,LOC INT,s);
OP NOTWITHIN = (CHAR c, []CHAR s)BOOL: NOT ( c WITHIN s );
INT guesses := 0, bulls, cows;
WHILE
STRING guess;
guesses +:= 1;
WHILE
# get a good guess #
print((new line,"Next guess [",D guesses,"]: "));
read((guess, new line));
IF UPB guess NE UPB chosen THEN
FALSE
ELSE
BOOL ok;
FOR i TO UPB guess WHILE
ok := guess[i] WITHIN digits AND guess[i] NOTWITHIN guess[i+1:]
DO SKIP OD;
NOT ok
FI
DO
print(("Problem, try again. You need to enter ",D UPB chosen," unique digits from 1 to 9", new line))
OD;
# WHILE #
guess NE chosen
DO
bulls := cows := 0;
FOR i TO UPB chosen DO
IF guess[i] = chosen[i] THEN
bulls +:= 1
ELIF guess[i] WITHIN chosen THEN
cows +:= 1
FI
OD;
print((" ",D bulls," Bulls",new line," ",D cows," Cows"))
OD;
print((new line, "Congratulations you guessed correctly in ",D guesses," attempts.",new line))
|
@page "/EstadoPrestamos"
@inject PagosBLL PagosBLL
@inject NotificationService notificationService
@inject PersonasBLL PersonasBLL
@inject PrestamosBLL prestamosBll
<EditForm Model="Listaprestamos">
<DataAnnotationsValidator />
<div class="card">
<div class="container">
<div class="card-body">
<label>Introduzca el Numero Prestamo</label>
<div class="input-group mb-3">
<button @onclick="Buscar" type="button" class="btn btn-info"> <i class="oi oi-magnifying-glass"></i></button>
<input class="form-control" type="number" @bind="Id" placeholder="Prestamo Id" />
</div>
</div>
<div class="input-group">
<table class="table table-sm">
<thead>
<tr>
<th>PrestamosId</th>
<th>Inicio</th>
<th>Vencimiento</th>
<th>Balance Pendiente</th>
</tr>
</thead>
<tbody>
@foreach (var prestamo in Listaprestamos)
{
<tr>
<td>@prestamo.PrestamoId</td>
<td>@prestamo.Fecha</td>
<td>@prestamo.Vence</td>
<td>@prestamo.Balance</td>
</tr>
}
</tbody>
</table>
<table class="table table-sm">
<thead>
<tr>
<th>#Pago</th>
<th>Monto Pago</th>
</tr>
</thead>
<tbody>
@foreach (var pago in detalle)
{
<tr>
<td>@(cont = cont + 1)</td>
<td>@pago.ValorPagado</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</EditForm>
@code {
public Prestamos prestamos { get; set; } = new Prestamos();
public int Id { get; set; } = 0;
public int cont { get; set; } = 0;
public double Total { get; set; } = 0.0;
public List<Prestamos> Listaprestamos { get; set; } = new List<Prestamos>();
public List<PagosDetalle> detalle { get; set; } = new List<PagosDetalle>();
protected override void OnInitialized()
{
base.OnInitialized();
}
public async Task Buscar()
{
if (Id > 0)
{
Listaprestamos = prestamosBll.Filtro2(Id);
detalle = await PagosBLL.Filtro(Id);
}
else if (Id <= 0)
{
ShowNotification(
new NotificationMessage
{
Severity = NotificationSeverity.Error,
Summary = "No se Encontro Esta persona"
});
}
}
void ShowNotification(NotificationMessage message)
{
notificationService.Notify(message);
}
}
|
import React, { useState } from "react";
import { useForm, Controller, SubmitHandler } from "react-hook-form";
import {
Flex,
VStack,
Input as ChakraInput,
InputGroup,
FormLabel,
FormControl,
InputLeftElement,
FormHelperText,
Button,
FormErrorMessage,
Image,
Box,
SimpleGrid,
RadioGroup,
Radio,
Stack,
PopoverTrigger,
Popover,
PopoverContent,
PopoverArrow,
PopoverCloseButton,
PopoverHeader,
PopoverBody,
UnorderedList,
ListItem,
Grid,
GridItem,
HStack,
Select,
Heading,
useToast
} from "@chakra-ui/react";
import { IUserForm } from "../../@types/interfaces";
import UF from "../../utils/UF.json";
import InputMask from "react-input-mask"
import { UserService } from "../../services/UserService";
import { useRouter } from "next/dist/client/router";
interface Props {
type?: "edit | register";
}
interface IUserFormData {
data: IUserForm;
}
const FormUser = ({ type = "register" }) => {
const [passwordConfirmationError, setPasswordConfirmationError] = useState<boolean>(false);
const [passwordConfirmation, setPasswordConfirmation] = useState<string>("")
const [loading, setLoading] = useState<boolean>(false)
const route = useRouter()
const toast = useToast()
const {
handleSubmit,
control,
reset,
getValues,
setValue,
formState: { errors },
} = useForm<IUserFormData>({
defaultValues: {} as IUserFormData,
});
const onSubmit: SubmitHandler<IUserFormData> = (data) => {
if(data.data.password !== passwordConfirmation){
setPasswordConfirmationError(true)
return
}
setLoading(true)
UserService().signin({...data.data}).then((resp) => {
toast({
title: 'Sucesso',
description: "Conta criada com sucesso",
status: 'success',
duration: 5000,
isClosable: true,
})
setLoading(false)
route.push("/")
}).catch((e)=> {
toast({
title: 'Erro',
description: e.response.data.message,
status: 'error',
duration: 5000,
isClosable: true,
})
console.log()
setLoading(false)
})
};
return (
<>
<Flex
as={"form"}
w="100%"
maxWidth={["360px", "1420px"]}
direction={"column"}
borderRadius="8"
onSubmit={handleSubmit(onSubmit)}
mb="3"
px="2"
>
<Heading my="2">{type === "register" ? "CADASTRAR" : "EDITAR"}</Heading>
<SimpleGrid
column={2}
mt={["0px", "0px"]}
minChildWidth={["none", "500px"]}
spacingX={2}
spacingY={2}
bg={"gray.100"}
boxShadow={"0 0 4px RGBA(0, 0, 0, 0.16)"}
p={5}
px="8"
borderRadius="8"
>
<FormControl isInvalid={errors.data?.name ? true : false}>
<FormLabel>Primeiro Nome</FormLabel>
<Controller
name="data.name"
control={control}
defaultValue={getValues("data.name")}
rules={{ required: "O primeiro nome é obrigatório", maxLength: 50 }}
render={({ field }) => (
<ChakraInput
id="data.name"
size={"md"}
type="text"
bg="white"
focusBorderColor="primary.normal"
{...field}
/>
)}
/>
<FormErrorMessage>{errors.data?.name?.message}</FormErrorMessage>
</FormControl>
<FormControl isInvalid={errors.data?.email ? true : false}>
<FormLabel>Email</FormLabel>
<Controller
name="data.email"
control={control}
defaultValue={getValues("data.email")}
rules={{ required: "O Email é obrigatório", maxLength: 50 }}
render={({ field }) => (
<ChakraInput
id="data.email"
size={"md"}
bg="white"
type="email"
focusBorderColor="primary.normal"
{...field}
/>
)}
/>
<FormErrorMessage>{errors.data?.email?.message}</FormErrorMessage>
</FormControl>
{type === "edit" ? (
<></>
) : (
<>
<FormControl isInvalid={errors.data?.password ? true : false}>
<FormLabel>Senha</FormLabel>
<Controller
name="data.password"
control={control}
defaultValue={getValues("data.password")}
rules={{ required: "A senha é obrigatório", maxLength: 40 }}
render={({ field }) => (
<Popover>
<PopoverTrigger>
<ChakraInput
id="data.password"
size={"md"}
bg="white"
type="password"
focusBorderColor="primary.normal"
{...field}
/>
</PopoverTrigger>
<PopoverContent>
<PopoverArrow />
<PopoverCloseButton />
<PopoverHeader>Requisitos</PopoverHeader>
<PopoverBody mx="auto">
<UnorderedList>
<ListItem>A senha deve conter 1 Letra Maiuscula</ListItem>
<ListItem>A senha deve conter 1 Letra Minuscula</ListItem>
<ListItem>A senha deve conter 1 numero</ListItem>
<ListItem>A senha deve conter 1 caractere especial</ListItem>
<ListItem>A senha deve conter min 8 e max 20 caracteres</ListItem>
</UnorderedList>
</PopoverBody>
</PopoverContent>
</Popover>
)}
/>
<FormErrorMessage>{errors.data?.password?.message}</FormErrorMessage>
</FormControl>
<FormControl isInvalid={passwordConfirmationError}>
<FormLabel>Confirmação de senha</FormLabel>
<ChakraInput size={"md"} bg="white" type="password" value={passwordConfirmation} onChange={e => setPasswordConfirmation(e.target.value)} focusBorderColor="primary.normal" />
{passwordConfirmationError && ( <FormErrorMessage>As senhas não conferem</FormErrorMessage>)}
</FormControl>
</>
)}
</SimpleGrid>
<Flex justify={"flex-end"} mt="5">
<Button isLoading={loading} as={"button"} colorScheme={"yellow"} type="submit">
Cadastrar
</Button>
</Flex>
</Flex>
</>
);
};
export default FormUser;
|
package com.cs407.bluedrop.receiver
import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.cs407.bluedrop.Constants
import com.cs407.bluedrop.models.FileTransfer
import com.cs407.bluedrop.models.ViewState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.ObjectInputStream
import java.net.InetSocketAddress
import java.net.ServerSocket
class FileReceiverViewModel(context: Application) :
AndroidViewModel(context) {
private val _viewState = MutableSharedFlow<ViewState>()
val viewState: SharedFlow<ViewState> = _viewState
private val _log = MutableSharedFlow<String>()
val log: SharedFlow<String> = _log
private var job: Job? = null
fun startListener() {
if (job != null) {
return
}
job = viewModelScope.launch(context = Dispatchers.IO) {
_viewState.emit(value = ViewState.Idle)
var serverSocket: ServerSocket? = null
var clientInputStream: InputStream? = null
var objectInputStream: ObjectInputStream? = null
var fileOutputStream: FileOutputStream? = null
try {
_viewState.emit(value = ViewState.Connecting)
log(log = "Start Socket")
serverSocket = ServerSocket()
serverSocket.bind(InetSocketAddress(Constants.PORT))
serverSocket.reuseAddress = true
serverSocket.soTimeout = 30000
log(log = "Socket Accepted, abort if no connection is made within thirty seconds")
val client = serverSocket.accept()
_viewState.emit(value = ViewState.Receiving)
clientInputStream = client.getInputStream()
objectInputStream = ObjectInputStream(clientInputStream)
val fileTransfer = objectInputStream.readObject() as FileTransfer
val file = File(getCacheDir(context = getApplication()), fileTransfer.fileName)
log(log = "Connected successful, waiting to receive: $fileTransfer")
log(log = "File saved to: $file")
log(log = "Start transferring file")
fileOutputStream = FileOutputStream(file)
val buffer = ByteArray(1024 * 100)
while (true) {
val length = clientInputStream.read(buffer)
if (length > 0) {
fileOutputStream.write(buffer, 0, length)
} else {
break
}
log(log = "Transferring,length : $length")
}
_viewState.emit(value = ViewState.Success(file = file))
log(log = "File Recived")
} catch (e: Throwable) {
log(log = "Exception: " + e.message)
_viewState.emit(value = ViewState.Failed(throwable = e))
} finally {
serverSocket?.close()
clientInputStream?.close()
objectInputStream?.close()
fileOutputStream?.close()
}
}
job?.invokeOnCompletion {
job = null
}
}
private fun getCacheDir(context: Context): File {
val cacheDir = File(context.cacheDir, "FileTransfer")
cacheDir.mkdirs()
return cacheDir
}
private suspend fun log(log: String) {
_log.emit(value = log)
}
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { FormattedMessage, injectIntl, intlShape } from '../../util/reactIntl';
import { propTypes } from '../../util/types';
import { parse } from '../../util/urlHelpers';
import { isScrollingDisabled } from '../../ducks/UI.duck';
import {
Page,
NamedLink,
IconKeys,
IconKeysSuccess,
LayoutSingleColumn,
LayoutWrapperTopbar,
LayoutWrapperMain,
LayoutWrapperFooter,
Footer,
} from '../../components';
import { PasswordResetForm } from '../../forms';
import { TopbarContainer } from '../../containers';
import { resetPassword } from './PasswordResetPage.duck';
import css from './PasswordResetPage.module.css';
const parseUrlParams = location => {
const params = parse(location.search);
const { t: token, e: email } = params;
return { token, email };
};
export class PasswordResetPageComponent extends Component {
constructor(props) {
super(props);
this.state = { newPasswordSubmitted: false };
}
render() {
const {
intl,
scrollingDisabled,
location,
resetPasswordInProgress,
resetPasswordError,
onSubmitPassword,
} = this.props;
const title = intl.formatMessage({
id: 'PasswordResetPage.title',
});
const { token, email } = parseUrlParams(location);
const paramsValid = !!(token && email);
const handleSubmit = values => {
const { password } = values;
this.setState({ newPasswordSubmitted: false });
onSubmitPassword(email, token, password).then(() => {
this.setState({ newPasswordSubmitted: true });
});
};
const recoveryLink = (
<NamedLink name="PasswordRecoveryPage">
<FormattedMessage id="PasswordResetPage.recoveryLinkText" />
</NamedLink>
);
const paramsErrorContent = (
<div className={css.content}>
<p>
<FormattedMessage id="PasswordResetPage.invalidUrlParams" values={{ recoveryLink }} />
</p>
</div>
);
const resetFormContent = (
<div className={css.content}>
<IconKeys className={css.modalIcon} />
<h1 className={css.modalTitle}>
<FormattedMessage id="PasswordResetPage.mainHeading" />
</h1>
<p className={css.modalMessage}>
<FormattedMessage id="PasswordResetPage.helpText" />
</p>
{resetPasswordError ? (
<p className={css.error}>
<FormattedMessage id="PasswordResetPage.resetFailed" />
</p>
) : null}
<PasswordResetForm
className={css.form}
onSubmit={handleSubmit}
inProgress={resetPasswordInProgress}
/>
</div>
);
const resetDoneContent = (
<div className={css.content}>
<IconKeysSuccess className={css.modalIcon} />
<h1 className={css.modalTitle}>
<FormattedMessage id="PasswordResetPage.passwordChangedHeading" />
</h1>
<p className={css.modalMessage}>
<FormattedMessage id="PasswordResetPage.passwordChangedHelpText" />
</p>
<NamedLink name="LoginPage" className={css.submitButton}>
<FormattedMessage id="PasswordResetPage.loginButtonText" />
</NamedLink>
</div>
);
let content;
if (!paramsValid) {
content = paramsErrorContent;
} else if (!resetPasswordError && this.state.newPasswordSubmitted) {
content = resetDoneContent;
} else {
content = resetFormContent;
}
return (
<Page title={title} scrollingDisabled={scrollingDisabled} referrer="origin">
<LayoutSingleColumn>
<LayoutWrapperTopbar>
<TopbarContainer />
</LayoutWrapperTopbar>
<LayoutWrapperMain className={css.layoutWrapperMain}>
<div className={css.root}>{content}</div>
</LayoutWrapperMain>
<LayoutWrapperFooter>
<Footer />
</LayoutWrapperFooter>
</LayoutSingleColumn>
</Page>
);
}
}
PasswordResetPageComponent.defaultProps = {
resetPasswordError: null,
};
const { bool, func, shape, string } = PropTypes;
PasswordResetPageComponent.propTypes = {
scrollingDisabled: bool.isRequired,
resetPasswordInProgress: bool.isRequired,
resetPasswordError: propTypes.error,
onSubmitPassword: func.isRequired,
// from withRouter
location: shape({
search: string,
}).isRequired,
// from injectIntl
intl: intlShape.isRequired,
};
const mapStateToProps = state => {
const { resetPasswordInProgress, resetPasswordError } = state.PasswordResetPage;
return {
scrollingDisabled: isScrollingDisabled(state),
resetPasswordInProgress,
resetPasswordError,
};
};
const mapDispatchToProps = dispatch => ({
onSubmitPassword: (email, token, password) => dispatch(resetPassword(email, token, password)),
});
// Note: it is important that the withRouter HOC is **outside** the
// connect HOC, otherwise React Router won't rerender any Route
// components since connect implements a shouldComponentUpdate
// lifecycle hook.
//
// See: https://github.com/ReactTraining/react-router/issues/4671
const PasswordResetPage = compose(
withRouter,
connect(
mapStateToProps,
mapDispatchToProps
),
injectIntl
)(PasswordResetPageComponent);
export default PasswordResetPage;
|
using System;
namespace VirtualPet
{
class Pet
{
public string Name { get; }
public string Type { get; }
public int Hunger { get; private set; }
public int Happiness { get; private set; }
public int Health { get; private set; }
public Pet(string name, string type)
{
Name = name;
Type = type;
Hunger = 5;
Happiness = 5;
Health = 10;
}
public void Feed()
{
Hunger = Math.Max(0, Hunger - 2);
Happiness = Math.Min(10, Happiness + 1);
Console.WriteLine("You feed {0}. Hunger decreases.", Name);
}
public void Play()
{
Happiness = Math.Min(10, Happiness + 2);
Hunger = Math.Min(10, Hunger + 1);
Console.WriteLine("You play with {0}. Happiness increases.", Name);
}
public void Rest()
{
Health = Math.Min(10, Health + 2);
Happiness = Math.Max(0, Happiness - 1);
Console.WriteLine("You let {0} rest. Health improves.", Name);
}
public void CheckStatus()
{
Console.WriteLine("status:", Name);
Console.WriteLine("• Hunger: {0}", Hunger);
Console.WriteLine("• Happiness: {0}", Happiness);
Console.WriteLine("• Health: {0}", Health);
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please choose a type of pet:");
Console.WriteLine("1. Cat");
Console.WriteLine("2. Dog");
Console.WriteLine("3. Rabbit");
int choice = Convert.ToInt32(Console.ReadLine());
string type = "";
switch (choice)
{
case 1:
type = "Cat";
break;
case 2:
type = "Dog";
break;
case 3:
type = "Rabbit";
break;
default:
Console.WriteLine("Invalid choice. Defaulting to cat.");
type = "cat";
break;
}
Console.WriteLine("What would you like to name your {0}?", type);
string name = Console.ReadLine();
Pet pet = new Pet(name, type);
Console.WriteLine("Welcome, {0}! Let’s take good care of {1}.", name, name);
int userInput;
do
{
Console.WriteLine("\nMain menu:");
Console.WriteLine("1. Feed {0}", name);
Console.WriteLine("2. Play with {0}", name);
Console.WriteLine("3. Let {0} rest", name);
Console.WriteLine("4. Check {0}’s status", name);
Console.WriteLine("5. Exit");
Console.Write("User input: ");
userInput = Convert.ToInt32(Console.ReadLine());
switch (userInput)
{
case 1:
pet.Feed();
break;
case 2:
pet.Play();
break;
case 3:
pet.Rest();
break;
case 4:
pet.CheckStatus();
break;
case 5:
Console.WriteLine("Thank you for playing with {0}!", name);
break;
default:
Console.WriteLine("Invalid input. Please try again.");
break;
}
} while (userInput != 5);
}
}
}
}
|
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const db = require('./models/sequelize').sequelize
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const app = express();
// db 연결
db.sync({force:false})
.then(()=>{
console.log("db 연결 성공")
})
.catch(()=>{
console.log("db 연결 실패")
})
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
function [FitPa,fval,exitflag,fitx,fity] = FitRatioOfGaussians(x,y, ...
varargin)
%hn 9/18/12
%fits ratio of Gaussian model (based on Cavanaugh, Bair, Movshon, 2002)
%to size tuning data.
%R(x) = k_c*L_c(x)/(1+k_s*L_s(x)),
%where
% k_c: gain of center RF
% k_s: gain of surround field
% L_c = (2/(pi) * integral over 0 to x of exp(-(y/w_c)^2) dy)^2
% w_c: width (SD of Gaussian) of center RF
% L_s = (2/(pi) * integral over 0 to x of exp(-(y/w_s)^2) dy)^2
% w_s: width (SD of Gaussian) of surround field
%
% constraint: w_c < w_s
FitPa.k_c = [];
FitPa.k_s = [];
FitPa.w_c = [];
FitPa.w_s = [];
fitx = [];
fity = [];
%options = optimset('MaxFunEvals',1000000,'maxiter',100000);
options = optimset('MaxFunEvals',10000,'maxiter',10000);
LB = [ 0 0 0 0 0 0 0 0 0];
exitflag = 0;
fval = NaN;
fit_flag=0;
idx = find(y>=0.98*max(y));
if ~isempty(idx)
w_c_guess = x(idx(1));
else
w_c_guess = x(end);
end
%guess = [w_c_guess w_c_guess+1 0.05 0.1] ; % w_c, w_s, k_c, k_s --> starting for mouse (HN)
guess = [w_c_guess w_c_guess+1 0.05 0.1] ; % w_c, w_s, k_c, k_s --> starting for monkey (CL)
[fitparams,fval,exitflag,output]= fminsearch(@MyRatioOfGaussians,...
guess,options,x,y,LB); %,lower_bound,upper_bound,options)
FitPa.k_c = fitparams(3);
FitPa.k_s = fitparams(4);
FitPa.w_c = fitparams(1);
FitPa.w_s = fitparams(2);
function f = MyRatioOfGaussians(X0,x,y,LB);
f1 = @(t1) exp(-(t1/X0(1)).^2);
f2 = @(t2) exp(-(t2/X0(2)).^2);
for n=1:length(x)
Q(n) = X0(3)*(2/sqrt(pi)*integral(f1,0,x(n)))^2/...
(1+(2/sqrt(pi)*X0(4)*integral(f2,0,x(n)))^2);
% Q(n) = X0(3)*(2/sqrt(pi)*integral(f1,0,x(n)))^2/...
% (1+X0(4)*(2/sqrt(pi)*integral(f2,0,x(n)))^2);
end
f = sum((Q-y).^2);
if (X0(1)>X0(2) | X0(1)<0 |X0(2)<0 |X0(3)<0 |X0(4)<0)
f=inf;
end
|
//
// Copyright(c) 2002 Mediatrix Telecom, Inc. ("Mediatrix")
// Copyright(c) 2003 M5T Centre d'Excellence en Telecom Inc. ("M5T")
// Copyright(c) 2007 Media5 Corporation ("Media5")
//
// NOTICE:
// This document contains information that is confidential and proprietary to
// Media5.
//
// Media5 reserves all rights to this document as well as to the Intellectual
// Property of the document and the technology and know-how that it includes
// and represents.
//
// This publication cannot be reproduced, neither in whole nor in part, in any
// form whatsoever without prior written approval by Media5.
//
// Media5 reserves the right to revise this publication and make changes at
// any time and without the obligation to notify any person and/or entity of
// such revisions and/or changes.
//
#ifndef MXG_IASYNCSERVERSOCKETMGR_H
//M5T_INTERNAL_USE_BEGIN
#define MXG_IASYNCSERVERSOCKETMGR_H
//M5T_INTERNAL_USE_END
//-- M5T Global definitions
//---------------------------
#ifndef MXG_MXCONFIG_H
#include "Config/MxConfig.h"
#endif
//-- M5T Framework Configuration
//-------------------------------
#ifndef MXG_FRAMEWORKCFG_H
#include "Config/FrameworkCfg.h" // MXD_NETWORK_ENABLE_SUPPORT
// MXD_ECOM_ENABLE_SUPPORT
#endif
#if defined(MXD_NETWORK_ENABLE_SUPPORT) && \
defined(MXD_ECOM_ENABLE_SUPPORT)
MX_NAMESPACE_START(MXD_GNS)
//-- Forward Declarations
class IAsyncIoSocket;
class CSocketAddr;
//== Class: IAsyncServerSocketMgr
//<GROUP NETWORK_CLASSES>
//
// Summary:
// This is the interface through which server sockets report events.
//
// Description:
// This is the interface through which server sockets report events. All
// events are reported asynchronously with respect to the manager's execution
// context.
//
// Location:
// Network/IAsyncServerSocketMgr.h
//
// See Also:
// IAsyncServerSocket
//
class IAsyncServerSocketMgr
{
//-- Published Interface
public:
//==
//== EvAsyncServerSocketMgrBound
//==
//
// Summary:
// Notifies that the server socket has been bound.
//
// Parameters:
// opq:
// Opaque value associated with the socket that is being bound.
//
// pEffectiveLocalAddress:
// Effective local address where the socket is bound.
//
// Description:
// This is the event generated by the asynchronous server socket upon
// being bound.
//
// Unsuccessful binding attempts are reported through the
// IAsyncSocketMgr::EvAsyncSocketMgrErrorDetected event.
//
// See Also:
// IAsyncSocketMgr::EvAsyncSocketMgrErrorDetected
//
virtual void EvAsyncServerSocketMgrBound(IN mxt_opaque opq,
IN CSocketAddr* pEffectiveLocalAddress) = 0;
//==
//== EvAsyncServerSocketMgrConnectionAccepted
//==
//
// Summary:
// The user accepted a connection request and now the accepting process
// is complete.
//
// Parameters:
// opqServerSocketOpaque:
// Opaque value associated with the server socket on which the accept
// has been requested.
//
// pAsyncIoSocket:
// Pointer to an IAsyncIoSocket interface representing the accepted
// connection.
//
// Description:
// This event is reported by a server socket when an incoming
// connection attempt has been accepted and the accepting process is
// complete.
//
// #Deprecation Note:#
// The opaque parameter for the accepted socket that used to be a
// parameter to this event is now deprecated. To set the opaque value of
// an accepted socket, the application must use the
// IAsyncSocket::SetOpaque method inside this event. An IAsyncIoSocket
// interface is received as a parameter to this event on which the
// IAsyncSocket interface can be queried.
//
// Furthermore, the application can also use the socket factory's
// IAsyncSocketFactoryConfigurationMgr interface instead to set the
// opaque value. See the interface's documentation for more details.
//
// See Also:
// IAsyncServerSocket::AcceptA
//
virtual void EvAsyncServerSocketMgrConnectionAccepted(IN mxt_opaque opqServerSocketOpaque,
IN IAsyncIoSocket* pAsyncIoSocket) = 0;
//==
//== EvAsyncServerSocketMgrConnectionFailed
//==
//
// Summary:
// The user accepted a connection request and now the accepting process
// failed.
//
// Parameters:
// opqServerSocketOpaque:
// Opaque value associated with the server socket on which the accept
// was requested.
//
// res:
// The error detected on the socket.
//
// Description:
// This event is reported by a server socket when an incoming
// connection attempt has been accepted and the accepting process failed.
//
// #Deprecation Note:#
// The opaque parameter that used to be a parameter to this method is now
// deprecated. The opaque value of an accepted socket is now set only
// when the application receives the
// IAsyncServerSocketMgr::EvAsyncServerSocketMgrConnectionAccepted event
// and uses the IAsyncSocket::SetOpaque method or the socket factory'
// IAsyncSocketFactoryConfigurationMgr interface. This event being
// exclusive with the
// IAsyncServerSocketMgr::EvAsyncServerSocketMgrConnectionAccepted event,
// it no longer has access to the opaque value of the accepted socket nor
// does it need that opaque value.
//
// See Also:
// IAsyncServerSocket::AcceptA
//
virtual void EvAsyncServerSocketMgrConnectionFailed(IN mxt_opaque opqServerSocketOpaque,
IN mxt_result res) = 0;
//==
//== EvAsyncServerSocketMgrConnectionRequested
//==
//
// Summary:
// An incoming connection attempt was detected on a server socket.
//
// Parameters:
// opqServerSocketOpaque:
// Opaque parameter associated with the server socket.
//
// Description:
// This event is reported by a server socket when an incoming
// connection attempt is detected. In order to correctly establish the
// incoming connection, IAsyncServerSocket::AcceptA must be called on the
// server socket.
//
// See Also:
// IAsyncServerSocket::AcceptA
//
virtual void EvAsyncServerSocketMgrConnectionRequested(IN mxt_opaque opqServerSocketOpaque) = 0;
//M5T_INTERNAL_USE_BEGIN
protected:
//==
//== IAsyncServerSocketMgr
//==
//
// Summary:
// Constructor.
//
// Description:
// Default Constructor.
//
IAsyncServerSocketMgr(){};
//==
//== ~IAsyncServerSocketMgr
//==
//
// Summary:
// Destructor.
//
// Description:
// Destructor.
//
virtual ~IAsyncServerSocketMgr(){};
private:
// Deactivated Constructors / Destructors / Operators
IAsyncServerSocketMgr(const IAsyncServerSocketMgr& from);
IAsyncServerSocketMgr& operator=(const IAsyncServerSocketMgr& from);
//M5T_INTERNAL_USE_END
};
MX_NAMESPACE_END(MXD_GNS)
#endif // #if defined(MXD_NETWORK_ENABLE_SUPPORT) &&
// defined(MXD_ECOM_ENABLE_SUPPORT)
#endif // MXG_IASYNCSERVERSOCKETMGR_H
|
import Image from 'next/image';
import Link from 'next/link';
import { useState, useCallback } from 'react';
import ContentInner from 'components/Common/ContentInner';
import LinkBtn from 'components/Common/LinkBtn';
import Title from 'components/Common/Title';
import styled from 'styled-components';
import { mediaQuery768 } from 'styles/mediaQuery';
import { buttonNone, flexbox } from 'styles/mixin';
import homeLogo from 'images/common/home_logo.svg';
import { HOME, LOGIN, DOCS, NOTICES, GAME } from 'constants/navigation';
import { TMenuLinkItem } from 'types/home';
import { useSession } from 'next-auth/react';
import defaultProfile from 'images/mypage/profile.svg';
import { useReduxSelector } from 'hooks/useRedux';
const linkList: TMenuLinkItem[] = [
{
id: 'docs',
link: DOCS,
},
{
id: 'notices',
link: NOTICES,
},
{
id: 'game',
link: GAME,
},
];
const Header = () => {
const { data: session } = useSession();
const [isOpenNav, setIsOpenNav] = useState<boolean>(false);
const { user } = useReduxSelector(state => state.auth);
const onClickOpenNav = useCallback(() => {
setIsOpenNav(prev => !prev);
}, []);
return (
<HomeHeader>
<Inner>
<h1>
<LogoLink href={HOME}>
<Logo src={homeLogo} alt="doWork" />
</LogoLink>
</h1>
<HamburgerBtn aria-label="모바일 메뉴" type="button" onClick={onClickOpenNav} className={isOpenNav ? 'on' : ''}>
<HamburgerSpan />
<HamburgerSpan />
<HamburgerSpan />
</HamburgerBtn>
<Nav className={isOpenNav ? 'on' : ''}>
<Title className="blind">네비게이션</Title>
<NavList>
{linkList.map(({ id, link }) => (
<NavItem key={id}>
<NavLink href={link}>{id}</NavLink>
</NavItem>
))}
{session ? (
<NavItem key="profile">
<MainBtn type="button" aria-label="메인으로 가기">
<Profile src={user?.profile || defaultProfile} width={30} height={30} alt="profile" />
</MainBtn>
</NavItem>
) : (
<NavItem key="try it out">
<LinkBtn href={LOGIN} type="secondary" fontSize="1.4rem" lineheight="38px">
Try it out
</LinkBtn>
</NavItem>
)}
</NavList>
</Nav>
</Inner>
</HomeHeader>
);
};
export default Header;
const HomeHeader = styled.header`
position: fixed;
left: 0;
top: 0;
z-index: 3;
min-width: 360px;
width: 100%;
padding: 15px 0;
background: ${({ theme }) => theme.white};
box-shadow: ${({ theme }) => theme.box_shadow_gray_2};
`;
const Inner = styled(ContentInner)`
${flexbox('row', 'nowrap', 'space-between', 'center')}
`;
const LogoLink = styled(Link)`
display: block;
margin: 8px 0;
height: 24px;
`;
const Logo = styled(Image)`
width: auto;
height: 100%;
`;
const HamburgerBtn = styled.button`
${buttonNone}
width: 40px;
height: 40px;
margin-right: -10px;
&.on {
span:first-child {
transform: translate3d(0, 8px, 0) rotate(45deg);
}
span:nth-child(2) {
transform: rotate(45deg);
}
span:last-child {
transform: translate3d(0, -8px, 0) rotate(-45deg);
}
}
${mediaQuery768} {
display: none;
}
`;
const HamburgerSpan = styled.span`
display: block;
width: 20px;
height: 2px;
margin: 0 auto;
background: ${({ theme }) => theme.color_gray_70};
transition: transform 0.3s ease;
&:nth-child(2) {
margin: 6px auto;
}
`;
const Nav = styled.nav`
position: fixed;
left: 0;
top: 70px;
overflow: hidden;
width: 100%;
height: 0;
border-top: 1px solid ${({ theme }) => theme.color_gray_10};
background: ${({ theme }) => theme.white};
transition: height 0.3s ease;
&.on {
display: block;
height: 250px;
box-shadow: 0 5px 5px 0 ${({ theme }) => theme.black_transparent_15};
}
${mediaQuery768} {
position: static;
width: auto;
height: auto;
overflow: auto;
padding: 0;
border-top: none;
background: transparent;
&.on {
height: auto;
box-shadow: none;
}
${flexbox('row', 'nowrap', 'normal', 'center')}
}
`;
const NavList = styled.ul`
padding: 15px 5% 25px;
${mediaQuery768} {
padding: 0;
${flexbox('row', 'nowrap')}
gap: 20px;
}
`;
const NavItem = styled.li`
margin-bottom: 15px;
&:last-child {
margin-bottom: 0;
}
${mediaQuery768} {
margin-bottom: 0;
}
`;
const NavLink = styled(Link)`
display: block;
padding: 0 4px;
color: ${({ theme }) => theme.color_gray_100};
font-size: 1.6rem;
line-height: 40px;
text-transform: capitalize;
`;
const Profile = styled(Image)`
border-radius: 50%;
object-fit: cover;
`;
const MainBtn = styled.button`
height: 40px;
${flexbox('row', 'nowrap', 'center', 'center')}
${buttonNone}
`;
|
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import HomePage from './Pages/Home/HomePage';
import NavBarLogin from './Components/Utility/NavBarLogin';
import Footer from './Components/Utility/Footer';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import LoginPage from './Pages/Auth/LoginPage';
import RegisterPage from './Pages/Auth/RegisterPage';
import AllCategoryPage from './Pages/Category/AllCategoryPage';
import AllBrand from './Pages/Brand/AllBrandPage';
import ShopProductsPage from './Pages/Products/ShopProductsPage'
function App() {
return (
<div className='font'>
<NavBarLogin/>
<BrowserRouter>
<Routes>
<Route index element={<HomePage/> } />
<Route path='/login' element={<LoginPage/> } />
<Route path='/register' element={<RegisterPage/> } />
<Route path='/allcategory' element={<AllCategoryPage/>}/>
<Route path='/allbrand' element={<AllBrand/>}/>
<Route path='/products' element={<ShopProductsPage/>}/>
</Routes>
</BrowserRouter>
<Footer/>
</div>
);
}
export default App;
|
/**
* Copyright © 2007-2008 Glaxstar Ltd. All rights reserved.
*/
#include "nsISupports.idl"
/**
* The data transfer object to be user between API methods and API consumers.
*/
[scriptable, uuid(2025DE0D-7CC2-4264-A8DD-D625F2E496F6)]
interface gsICMTransferObject : nsISupports
{
/**
* Parses the given JSON string and initializes the object. Existing name /
* value mappings will be removed.
* The code is based on Mozilla code,
* http://lxr.mozilla.org/mozilla/source/browser/components/search/
* nsSearchSuggestions.js#525
* @param aJSONString the string used to initialize the object.
* @param aDomain the domain from which the JSON string was obtained.
* @throws Exception for any parse error that may occur.
*/
void fromJSON(in AUTF8String aJSONString, in AUTF8String aDomain);
/**
* Outputs the contents of this object as a POST string.
* XXX: an object can be converted to POST only if it contains either:
* - Simple (not object or array) values.
* - String arrays.
* - Arrays of objects with simple (not object or array) values.
* Different data structures are not guaranteed to work.
* @return POST string representation of this object.
* @throws Exception if the object doesn't have the expected structure.
*/
AUTF8String toPOST();
/**
* Indicates if this object represents an array or not.
* @return true if the object represents an array. false otherwise.
* @throws Exception if the object has not been initialized.
*/
boolean isArray();
/**
* Indicates if the object holds a value identified by the given name.
* @param aName the name of the value to look for.
* @return true if the object has a value with the given name. false
* otherwise.
* @throws Exception if the object has not been initialized or if the object
* represents an array.
*/
boolean hasValue(in AUTF8String aName);
/**
* Removes a value from the transfer object by its name.
* @param aName The name of the value to look for.
* @return True if the value was found and removed, false otherwise.
* @throws Exception if the object has not been initialized or if the object
* represents an array.
*/
boolean removeValue(in AUTF8String aName);
/**
* Gets the boolean value identified by the given name.
* @param aName the name of the boolean value to obtain.
* @return boolean value that corresponds to the name.
* @throws Exception if the object has not been initialized, if the type
* does not match the given name, or if the name is null or empty.
*/
boolean getBooleanValue(in AUTF8String aName);
/**
* Gets the boolean array represented by this object.
* @param aLength the length of the resulting array.
* @param aArray the resulting array.
* @throws Exception if the object has not been initialized or if the object
* is not an array or doesn't match the requested type.
*/
void getBooleanArray(
out PRUint32 aLength, [array, size_is(aLength)] out boolean aArray);
/**
* Sets the boolean value identified by the given name.
* @param aName the name of the boolean value to set.
* @param aValue the value to set.
* @throws Exception if the name is null or empty.
*/
void setBooleanValue(in AUTF8String aName, in boolean aValue);
/**
* Sets this object to be a boolean array.
* @param aLength the length of the array.
* @param aArray the array to set.
*/
void setBooleanArray(
in PRUint32 aLength, [array, size_is(aLength)] in boolean aArray);
/**
* Gets the integer value identified by the given name.
* @param aName the name of the integer value to obtain.
* @return integer value that corresponds to the name.
* @throws Exception if the object has not been initialized, if the type
* does not match the given name, or if the name is null or empty.
*/
long getIntegerValue(in AUTF8String aName);
/**
* Gets the integer array represented by this object.
* @param aLength the length of the resulting array.
* @param aArray the resulting array.
* @throws Exception if the object has not been initialized or if the object
* is not an array or doesn't match the requested type.
*/
void getIntegerArray(
out PRUint32 aLength, [array, size_is(aLength)] out long aArray);
/**
* Sets the integer value identified by the given name.
* @param aName the name of the integer value to set.
* @param aValue the value to set.
* @throws Exception if the name is null or empty.
*/
void setIntegerValue(in AUTF8String aName, in long aValue);
/**
* Sets this object to be an integer array.
* @param aLength the length of the array.
* @param aArray the array to set.
*/
void setIntegerArray(
in PRUint32 aLength, [array, size_is(aLength)] in long aArray);
/**
* Gets the string value identified by the given name.
* @param aName the name of the string value to obtain.
* @return string value that corresponds to the name.
* @throws Exception if the object has not been initialized, if the type
* does not match the given name, or if the name is null or empty.
*/
AUTF8String getStringValue(in AUTF8String aName);
/**
* Gets the string array represented by this object.
* @param aLength the length of the resulting array.
* @param aArray the resulting array.
* @throws Exception if the object has not been initialized or if the object
* is not an array or doesn't match the requested type.
*/
void getStringArray(
out PRUint32 aLength, [array, size_is(aLength)] out string aArray);
/**
* Sets the string value identified by the given name.
* @param aName the name of the string value to set.
* @param aValue the value to set.
* @throws Exception if a null string is passed or if the name is null or
* empty.
*/
void setStringValue(in AUTF8String aName, in AUTF8String aValue);
/**
* Sets this object to be a string array.
* @param aLength the length of the array.
* @param aArray the array to set.
* @throws Exception if a null string is passed.
*/
void setStringArray(
in PRUint32 aLength, [array, size_is(aLength)] in string aArray);
/**
* Gets the object value identified by the given name.
* @param aName the name of the object value to obtain.
* @return gsICMTransferObject value that corresponds to the name.
* @throws Exception if the object has not been initialized, if the type
* does not match the given name, or if the name is null or empty.
*/
gsICMTransferObject getObjectValue(in AUTF8String aName);
/**
* Gets the object array represented by this object.
* @param aLength the length of the resulting array.
* @param aArray the resulting array.
* @throws Exception if the object has not been initialized or if the object
* is not an array or doesn't match the requested type.
*/
void getObjectArray(
out PRUint32 aLength,
[array, size_is(aLength)] out gsICMTransferObject aArray);
/**
* Sets the object value identified by the given name.
* @param aName the name of the object value to set.
* @param aValue the gsICMTransferObject value to set.
* @throws Exception if a null object is passed or if the name is null or
* empty.
*/
void setObjectValue(in AUTF8String aName, in gsICMTransferObject aValue);
/**
* Sets this object to be an object array.
* @param aLength the length of the array.
* @param aArray the array to set.
* @throws Exception if a null object is passed.
*/
void setObjectArray(
in PRUint32 aLength,
[array, size_is(aLength)] in gsICMTransferObject aArray);
};
|
syntax = "proto3";
package member.v1;
option go_package = "go-mall/server/user/api/gen/v1/user;memberpb";
import "google/protobuf/empty.proto";
import "google/protobuf/timestamp.proto";
service MemberService {
rpc GetMemberById(IdRequest) returns(MemberEntity); // 通过用户id获取会员信息
rpc GetMemberByPhone(PhoneRequest) returns(MemberEntity); // 通过手机号码获取会员信息
rpc CreateMember(CreateRequest) returns (CreateResponse); // 创建会员
rpc UpdateMember(MemberEntity) returns (google.protobuf.Empty); // 更新会员
rpc CheckPassWord(PasswordCheckInfo) returns (CheckResponse); //检查密码
}
enum MemberStatus {
DISABLED = 0;
ENABLED = 1;
}
enum MemberGender {
MAN = 0;
WOMAN = 1;
}
message PhoneRequest {
string phone = 1;
}
message PasswordCheckInfo {
string password = 1;
string encryptedPassword = 2;
}
message CreateResponse {
uint64 id = 1;
}
message CheckResponse{
bool success = 1;
}
message IdRequest {
uint64 id = 1;
}
message MemberEntity {
uint64 id = 1;
uint64 member_level_id = 2;
string username = 3;
string password = 4;
string phone = 5;
string icon = 6;
MemberStatus status = 7;
MemberGender gender = 8;
google.protobuf.Timestamp birthday = 9;
string city = 10;
string job = 11;
int32 growth = 12;
string created_at = 13;
}
message BasicInfo {
uint64 id = 1;
string username = 2;
}
message CreateRequest {
string username = 1;
string phone = 2;
string password = 3;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.