text
stringlengths
184
4.48M
const { takeNotifications, createNotifications, getPostNotification, getOwnerCommentPostNotification, getFriendRequestNotification, getUserById, getAcceptFriendRequest, getPageNotification, addMoreNotification, } = require('../repository/index') const moment = require('moment/moment') // const { v4: uuidv4 } = require("uuid"); moment.locale('vi') const handleTakeNotification = async (req, res) => { const { userId } = req.query try { const response = await takeNotifications(userId) if (response) { const notifications = JSON.parse(response.notifications) const dataForFontend = await Promise.all( notifications.map(async (e) => { if (e?.type === 'friend post') { const dataOfNotification = await getPostNotification(e.post_id) const date = new Date(e.time) const notificationForFontend = { postId: dataOfNotification.post_id, ownerId: dataOfNotification.user_id, ownerFullName: dataOfNotification.fullName, ownerAvatar: dataOfNotification.avatar, notificationTime: moment(date).fromNow(), notificationType: e.type, notificationId: e.notification_id, unread: e.unread, } return notificationForFontend } else if (e?.type === 'friend request') { const dataOfNotification = await getFriendRequestNotification( e.from_user_id, ) if (dataOfNotification) { const date = new Date(e.time) const notificationForFontend = { ownerId: dataOfNotification.user_id, ownerFullName: dataOfNotification.fullName, ownerAvatar: dataOfNotification.avatar, requestId: dataOfNotification.request_id, senderId: dataOfNotification.sender_id, notificationTime: moment(date).fromNow(), notificationType: e.type, notificationId: e.notification_id, unread: e.unread, } return notificationForFontend } } else if (e?.type === 'comment your post') { const dataOfNotification = await getOwnerCommentPostNotification( e.comment_id, ) const date = new Date(e.time) const notificationForFontend = { ownerId: dataOfNotification.user_id, ownerFullName: dataOfNotification.fullName, ownerAvatar: dataOfNotification.avatar, commentId: dataOfNotification.id, postId: dataOfNotification.post_id, notificationTime: moment(date).fromNow(), notificationType: e.type, notificationId: e.notification_id, unread: e.unread, } return notificationForFontend } else if (e?.type === 'react your post') { const date = new Date(e.time) const user = await getUserById(e.owner_id) const notification = { ownerId: e.owner_id, ownerFullName: user.fullName, unread: e.unread, ownerAvatar: user.avatar, notificationTime: moment(date).fromNow(), postId: e.post_id, ownerAction: e.ownerAction, notificationId: e.notification_id, notificationType: e.type, } return notification } else if (e?.type === 'accept your friend request') { const dataOfNotification = await getAcceptFriendRequest(e.owner_id) const date = new Date(e.time) const notification = { ownerId: e.owner_id, ownerFullName: dataOfNotification.fullName, ownerAvatar: dataOfNotification.avatar, unread: e.unread, notificationTime: moment(date).fromNow(), notificationId: e.notification_id, notificationType: e.type, } return notification } else if (e?.type === 'page post') { const page = await getPageNotification(e.page_id) const date = new Date(e.time) const notification = { pageId: page.page_id, pageFullName: page.fullName, pageAvatar: page.avatar, postId: page.postId, unread: e.unread, notificationId: e.notification_id, notificationType: e.type, notificationTime: moment(date).fromNow(), } return notification } }), ) return res.status(200).json(dataForFontend) } else { await createNotifications(userId) res.status(200).json([]) } } catch (error) { console.log(error) res.status(500).json(error) } } const handleSeenNotification = async (req, res) => { const { userId, notificationId } = req.body console.log(userId, notificationId, 'LINE 133') try { const result = await takeNotifications(userId) const notifications = JSON.parse(result.notifications) const index = notifications.findIndex((e) => { return e.notification_id === notificationId }) notifications[index] = { ...notifications[index], unread: false } await addMoreNotification(JSON.stringify(notifications), userId) res.status(200).json('success') } catch (error) { console.log(error) } } module.exports = { handleTakeNotification, handleSeenNotification }
import { useId } from "@radix-ui/react-id"; import * as Label from "@radix-ui/react-label"; import * as PrimitiveSwitch from "@radix-ui/react-switch"; import React from "react"; import classNames from "@calcom/lib/classNames"; const Switch = ( props: React.ComponentProps<typeof PrimitiveSwitch.Root> & { label?: string; } ) => { const { label, ...primitiveProps } = props; const id = useId(); return ( <div className="flex h-[20px] items-center"> <PrimitiveSwitch.Root className={classNames( props.checked ? "bg-gray-900" : "bg-gray-200 hover:bg-gray-300", "focus:ring-brand-800 h-[24px] w-[40px] rounded-full p-0.5 shadow-none focus:ring-1" )} {...primitiveProps}> <PrimitiveSwitch.Thumb id={id} className="block h-[18px] w-[18px] translate-x-0 rounded-full bg-white transition-transform" /> </PrimitiveSwitch.Root> {label && ( <Label.Root htmlFor={id} className="ml-2 cursor-pointer align-text-top text-sm font-medium text-neutral-700 ltr:ml-3 rtl:mr-3 dark:text-white"> {label} </Label.Root> )} </div> ); }; export default Switch;
<template> <v-container> <v-row> <v-col cols="6"> <VDataTable v-model:expanded="expanded" :items-per-page="5" :headers="headers" :items="requests" item-value="id" class="elevation-1" show-expand :loading="loading" > <template v-slot:top> <VToolbar flat> <v-toolbar-title>Estimate Requests</v-toolbar-title> </VToolbar> </template> <template #item.customer_name="{ item }"> {{ item.raw.customer.fname }} {{ item.raw.customer.lname }} </template> <template #item.status="{ item }"> <v-select v-model="form[item.index].status" :items="statuses" /> </template> <template v-slot:expanded-row="{ columns, item }"> <tr> <td :colspan="columns.length"> <address>{{item.raw.address}}<br />{{item.raw.city}}, {{item.raw.state}} {{item.raw.zip}}</address> </td> </tr> </template> </VDataTable> </v-col> </v-row> </v-container> </template> <script> export default { components: { }, data () { return { form: [ { status: 1 }, { status: 2 } ], statuses: [1, 2], requests: [ { id: 1, name: "James Brown", email: "[email protected]" }, { id: 2, name: "Eli Brown", email: "[email protected]" } ], expanded:[], headers: [ { title: 'ID', align: 'start', key: 'id' }, { title: 'Name', align: 'start', key: 'name' }, { title: 'Email', align: 'start', key: 'email' }, { title: 'Status', align: 'start', key: 'status' }, ] } }, computed: { }, created() { }, methods: { }, // end methods } </script>
import React, { useState } from "react"; import { useSelector } from "react-redux"; import Hero from "../components/Hero"; import ReportForm from "../components/ReportForm"; import SavedReports from "../components/SavedReports"; import icon from "../assets/icon-img.png"; import SectionTextImgContent from "../sections/SectionTextImgContent"; const Home = () => { const [reportSubmitted, setReportSubmitted] = useState( useSelector((state) => state.report.reports.length > 0) ); const [showReports, setShowReports] = useState(false); const handleReportSubmit = () => { setReportSubmitted(true); }; const handleShowReports = () => { setShowReports(true); }; const handleCloseReports = () => { setShowReports(false); }; return ( <main> <Hero imageUrl="https://images.unsplash.com/photo-1635109836848-770dde2ea546?q=80&w=1470&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" subTitle="Cruelty Alert" text="Speak for the Voiceless, Report for Change" buttonText="Learn more" buttonLink="/about" altText="Profile of a golden retriver" /> <SectionTextImgContent subTitle="Cruelty Alert" text="Report and combat animal cruelty with us. Speak up for the voiceless. Together, let's create a world where animals are treated with kindness and respect. Join the movement for a brighter, compassionate future. " imageSrc={icon} altText="animal cruelty icon" /> <div className="container flex flex-col pb-4 mx-auto lg:flex-row lg:items-center"> <div className="order-2 sm:my-4 lg:order-1 lg:w-1/2 lg:mr-4"> <img className="w-full h-auto lg:max-w-full lg:h-auto" src="https://images.unsplash.com/photo-1592664858934-40ca080ab56b?q=80&w=1170&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="sad dogs in a cage" /> </div> <div className="order-1 lg:order-2 lg:w-1/2"> <ReportForm onReportSubmit={handleReportSubmit} /> </div> </div> {reportSubmitted && ( <div className="my-4 text-center"> {showReports ? ( <SavedReports onCloseReports={handleCloseReports} /> ) : ( <button className="p-2 mb-4 text-sm font-semibold border border-stone-100 " onClick={handleShowReports} > Show my Reports </button> )} </div> )} </main> ); }; export default Home;
<script> import axios from 'axios' import reservation from '../../components/reservations/reservation.vue' import _ from "lodash"; import viewModalVue from '../../components/reservations/viewModal.vue'; export default { components: { "dm-reservation": reservation, "view-modal": viewModalVue, }, data() { return { reservations: [], pages: [], currentPage: 1, maxPages: [], searchQuery: "", popup: { open: false, reservation: [], } } }, computed: { getPages() { return this.maxPages; }, getPager() { return this.pages; } }, mounted() { this.fetchRequests(); }, methods: { fetchRequests(searchQuery = null) { axios.get(`/api/v1/reservations/${this.currentPage}${searchQuery !== null ? `?s=${searchQuery}` : ''}`) .then((response) => { this.reservations = response.data.reservations; this.pages = response.data.pages; this.maxPages = response.data.maxPages; }) }, _handlePagerClick(page) { this.currentPage = page; this.fetchRequests(this.searchQuery); }, _handleViewReseration(reservation) { this.popup.open = true; this.popup.reservation = reservation; }, _handleClosePopup() { this.popup.open = false; this.popup.reservation = []; } }, watch: { searchQuery: _.debounce(function (searchQuery) { this.page = 1; this.fetchRequests(searchQuery) }, 500) } } </script> <template> <div class="py-9 px-1 sm:px-10 min-[1225px]:px-32"> <view-modal :reservation="popup.reservation" @closeModal="_handleClosePopup" v-if="popup.open"></view-modal> <div class="flex justify-between"> <div> <div class="filter-on-name w-fit"> <div class="flex items-center relative"> <input v-model="searchQuery" type="text" class="searcher focus:ring-0 focus:border-primary h-10 border-2 rounded-md border-primary" placeholder="Zoeken..."> <i class="fas fa-search absolute text-primary right-2 pointer-events-none"></i> </div> </div> </div> </div> <div class="w-full"> <table class="w-full flex flex-row flex-no-wrap min-[1225px]:bg-white rounded-lg overflow-auto min-[1225px]:overflow-hidden min-[1225px]:shadow-lg my-5"> <thead class="text-white" v-if="reservations.length > 0"> <tr v-for="reservation in reservations" :key="reservation.id" class="bg-primary flex flex-col flex-no wrap min-[1225px]:table-row rounded-l-lg min-[1225px]:rounded-none mb-2 min-[1225px]:mb-0"> <th class="p-2 min-[1225px]:p-3 text-left">Naam</th> <th class="p-2 min-[1225px]:p-3 text-left">E-mailadres</th> <th class="p-2 min-[1225px]:p-3 text-left">Leverprijs</th> <th class="p-2 min-[1225px]:p-3 text-left">Machine</th> <th class="p-2 min-[1225px]:p-3 text-left">Tijd</th> <th class="p-2 min-[1225px]:p-3 text-left">Datum</th> <th class="p-2 min-[1225px]:p-3 text-left">Status</th> <th class="p-2 min-[1225px]:p-3 text-left">Acties</th> </tr> </thead> <thead v-else class="text-white"> <tr class="bg-primary flex flex-col flex-no wrap min-[1225px]:table-row rounded-l-lg min-[1225px]:rounded-none mb-2 min-[1225px]:mb-0"> <th class="p-2 min-[1225px]:p-3 text-left">Naam</th> <th class="p-2 min-[1225px]:p-3 text-left">E-mailadres</th> <th class="p-2 min-[1225px]:p-3 text-left">Leverprijs</th> <th class="p-2 min-[1225px]:p-3 text-left">Machine</th> <th class="p-2 min-[1225px]:p-3 text-left">Tijd</th> <th class="p-2 min-[1225px]:p-3 text-left">Datum</th> <th class="p-2 min-[1225px]:p-3 text-left">Status</th> <th class="p-2 min-[1225px]:p-3 text-left">Acties</th> </tr> </thead> <tbody class="flex-1 min-[1225px]:flex-none"> <dm-reservation @_handleView="_handleViewReseration" v-for="reservation in reservations" :key="reservation.id" :reservation="reservation"></dm-reservation> </tbody> </table> <div class="flex gap-2 justify-end"> <div @click="_handlePagerClick(1)" v-if="(this.currentPage != 1)" class="flex font-bold justify-center items-center border-2 border-primary w-9 h-9 rounded-xl cursor-pointer"> <i class="fas fa-angle-double-left text-primary"></i> </div> <div class="flex font-bold justify-center items-center border-2 border-primary w-9 h-9 rounded-xl cursor-pointer" :key="index" v-for="page, index in getPager" :class="[this.currentPage == page ? 'bg-primary' : 'bg-transparent']" > <div :class="[this.currentPage == page ? 'text-white' : 'text-primary']" @click="_handlePagerClick(page)"> {{ page }}</div> </div> <div @click="_handlePagerClick(getPages)" v-if="(this.currentPage != maxPages)" class="flex justify-center items-center border-2 border-primary w-9 h-9 rounded-xl cursor-pointer"> <i class="fas fa-angle-double-right text-primary"></i> </div> </div> </div> </div> </template> <style> html, body { height: 100%; } @media (min-width: 1225px) { table { display: inline-table !important; } thead tr:not(:first-child) { display: none; } } td:not(:last-child) { border-bottom: 0; } th:not(:last-child) { border-bottom: 2px solid rgba(0, 0, 0, .1); } </style>
<?php /* * This code is an addon for GOsa² (https://gosa.gonicus.de) * Copyright (C) 2022 Daniel Teichmann * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ namespace SchoolManager\Objects\Traits; trait Gender { /** * @var string $gender (M, F or D) */ private $gender; /** * @param string $gender Gender of this user. * For format see Utils->normalizeGenderString() * @return bool true if input was valid, false if invalid. */ public function setGender(string $gender): bool { $returned_gender = $this->utils->normalizeGenderString($gender); if (empty($returned_gender)) { return false; } else { $this->gender = $returned_gender; return true; } } /** * @return string Gender in format 'F' => Female, 'M' => Male or 'D' => Diverse * or **empty** if unknown. */ public function getGender(): string { return is_null($this->gender) ? "" : $this->gender; } }
// SPDX-License-Identifier: BUSL-1.1 // // Copyright (C) 2023, Berachain Foundation. All rights reserved. // Use of this software is govered by the Business Source License included // in the LICENSE file of this repository and at www.mariadb.com/bsl11. // // ANY USE OF THE LICENSED WORK IN VIOLATION OF THIS LICENSE WILL AUTOMATICALLY // TERMINATE YOUR RIGHTS UNDER THIS LICENSE FOR THE CURRENT AND ALL OTHER // VERSIONS OF THE LICENSED WORK. // // THIS LICENSE DOES NOT GRANT YOU ANY RIGHT IN ANY TRADEMARK OR LOGO OF // LICENSOR OR ITS AFFILIATES (PROVIDED THAT YOU MAY USE A TRADEMARK OR LOGO OF // LICENSOR AS EXPRESSLY REQUIRED BY THIS LICENSE). // // TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON // AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, // EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND // TITLE. package polar import ( "math/big" "time" "github.com/berachain/polaris/eth/params" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/txpool/legacypool" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/ethereum/go-ethereum/eth/gasprice" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/miner" ethparams "github.com/ethereum/go-ethereum/params" ) const ( // gpoDefault is the default gpo starting point. gpoDefault = 1000000000 // developmentCoinbase is the address used for development. // DO NOT USE IN PRODUCTION. // 0xf8637fa70e8e329ecb8463b788d96914f8cfe191d15ae36f161227629e3f5693. developmentCoinbase = "0xAf15f95bed0D3913a29092Fd7837451Ce4de64D3" ) // DefaultConfig returns the default JSON-RPC config. func DefaultConfig() *Config { gpoConfig := ethconfig.FullNodeGPO gpoConfig.Default = big.NewInt(gpoDefault) gpoConfig.MaxPrice = big.NewInt(ethparams.GWei * 10000) //nolint:gomnd // default. minerCfg := miner.DefaultConfig minerCfg.Etherbase = common.HexToAddress(developmentCoinbase) minerCfg.GasPrice = big.NewInt(1) legacyPool := legacypool.DefaultConfig legacyPool.NoLocals = true legacyPool.PriceLimit = 8 // to handle the low base fee. legacyPool.Journal = "" return &Config{ Chain: *params.DefaultChainConfig, Miner: minerCfg, GPO: gpoConfig, LegacyTxPool: legacyPool, RPCGasCap: ethconfig.Defaults.RPCGasCap, RPCTxFeeCap: ethconfig.Defaults.RPCTxFeeCap, RPCEVMTimeout: ethconfig.Defaults.RPCEVMTimeout, } } // SafetyMessage is a safety check for the JSON-RPC config. func (c *Config) SafetyMessage() { if c.Miner.Etherbase == common.HexToAddress(developmentCoinbase) { log.Error( "development etherbase in use - please verify this is intentional", "address", c.Miner.Etherbase, ) } } // Config represents the configurable parameters for Polaris. type Config struct { // The chain configuration to use. Chain ethparams.ChainConfig // Mining options Miner miner.Config // Gas Price Oracle config. GPO gasprice.Config // Transaction pool options LegacyTxPool legacypool.Config // RPCGasCap is the global gas cap for eth-call variants. RPCGasCap uint64 // RPCEVMTimeout is the global timeout for eth-call. RPCEVMTimeout time.Duration // RPCTxFeeCap is the global transaction fee(price * gaslimit) cap for // send-transaction variants. The unit is ether. RPCTxFeeCap float64 }
package repository_test import ( "AvoxiCodingChallenge/repository" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "testing" ) var repo = repository.New() func Test_GetNetworks(t *testing.T) { t.Run("GetNetworks by country name", func(t *testing.T) { countryName := "United States" networks, err := repo.GetNetworks(countryName) require.NoError(t, err) assert.NotEmpty(t, networks) }) t.Run("GetNetworks by country name lowercase", func(t *testing.T) { countryName := "united states" networks, err := repo.GetNetworks(countryName) require.NoError(t, err) assert.NotEmpty(t, networks) }) t.Run("GetNetworks by country iso code", func(t *testing.T) { countryName := "US" networks, err := repo.GetNetworks(countryName) require.NoError(t, err) assert.NotEmpty(t, networks) }) t.Run("GetNetworks by country iso code lowercase", func(t *testing.T) { countryName := "us" networks, err := repo.GetNetworks(countryName) require.NoError(t, err) assert.NotEmpty(t, networks) }) t.Run("GetNetworks country not found", func(t *testing.T) { countryName := "fake country" networks, err := repo.GetNetworks(countryName) require.NoError(t, err) assert.Empty(t, networks) }) }
Output Status : Runtime: 8 ms, faster than 31.50% of C++ online submissions for Binary Tree Right Side View. Memory Usage: 11.9 MB, less than 66.66% of C++ online submissions for Binary Tree Right Side View. // Iterative Sol :: Time : O(N) :: Aux_Space : O(N) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> rightSideView(TreeNode* root) { if(!root) return {}; vector<int> res; queue<TreeNode*> q; q.push(root); while(!q.empty()){ int n = q.size(); for(int i=0;i<n;i++){ TreeNode*curr = q.front(); q.pop(); if(i == n-1) res.push_back(curr->val); if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); } } return res; } }; // Recursive Sol :: Time : O(N) :: Aux_Space : O(H) [H is the Height of the Tree] /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void reversePreorder(TreeNode* root, int level , vector<int> &res){ if(root == NULL) return; if(res.size() == level){ res.push_back(root->val); } reversePreorder(root->right,level+1,res); reversePreorder(root->left,level+1,res); } vector<int> rightSideView(TreeNode* root) { vector<int> res; reversePreorder(root,0,res); return res; } };
package org.lntu.online.ui.activity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import android.widget.ExpandableListView; import android.widget.TextView; import org.lntu.online.R; import org.lntu.online.model.api.ApiClient; import org.lntu.online.model.api.BackgroundCallback; import org.lntu.online.model.entity.UnpassCourse; import org.lntu.online.model.storage.LoginShared; import org.lntu.online.ui.adapter.UnpassCourseAdapter; import org.lntu.online.ui.base.StatusBarActivity; import org.lntu.online.ui.listener.NavigationFinishClickListener; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit.client.Response; public class UnpassCourseActivity extends StatusBarActivity { @BindView(R.id.toolbar) protected Toolbar toolbar; @BindView(R.id.ex_list_view) protected ExpandableListView exListView; @BindView(R.id.icon_loading) protected View iconLoading; @BindView(R.id.icon_empty) protected View iconEmpty; @BindView(R.id.icon_loading_anim) protected View iconLoadingAnim; @BindView(R.id.tv_load_failed) protected TextView tvLoadFailed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_unpass_course); ButterKnife.bind(this); toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); Animation dataLoadAnim = AnimationUtils.loadAnimation(this, R.anim.data_loading); dataLoadAnim.setInterpolator(new LinearInterpolator()); iconLoadingAnim.startAnimation(dataLoadAnim); startNetwork(); } private void startNetwork() { ApiClient.service.getUnpassCourseList(LoginShared.getLoginToken(this), new BackgroundCallback<List<UnpassCourse>>(this) { @Override public void handleSuccess(List<UnpassCourse> unpassCourseList, Response response) { if (unpassCourseList.size() == 0) { showIconEmptyView("目前没有未通过的课程。"); } else { exListView.setAdapter(new UnpassCourseAdapter(UnpassCourseActivity.this, unpassCourseList)); exListView.setVisibility(View.VISIBLE); iconLoading.setVisibility(View.GONE); iconEmpty.setVisibility(View.GONE); } } @Override public void handleFailure(String message) { showIconEmptyView(message); } }); } private void showIconEmptyView(String message) { iconLoading.setVisibility(View.GONE); iconEmpty.setVisibility(View.VISIBLE); tvLoadFailed.setText(message); } @OnClick(R.id.icon_empty) protected void onBtnIconEmptyClick() { iconLoading.setVisibility(View.VISIBLE); iconEmpty.setVisibility(View.GONE); startNetwork(); } }
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; import { updateThemeVariables } from "@/helpers/updateThemeVariables"; const setLocalStorageTheme = (newTheme: string) => { localStorage.setItem("currentTheme", newTheme); }; const getLocalStorageTheme = () => { return localStorage.getItem("currentTheme") || "dark"; }; export const toggleTheme = createAsyncThunk( "theme/toggleTheme", async (newTheme: string) => { updateThemeVariables(newTheme); setLocalStorageTheme(newTheme); return newTheme; } ); const themeSlice = createSlice({ name: "theme", initialState: { currentTheme: getLocalStorageTheme(), }, reducers: {}, extraReducers: (builder) => { builder.addCase(toggleTheme.fulfilled, (state, action) => { state.currentTheme = action.payload; }); }, }); export default themeSlice.reducer;
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <!-- For Responsive --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="{{ asset('css/template.css', 'mix') }}" type="text/css"{{ sri('css/template.css') }}> {% if appDebug %} <link rel="stylesheet" href="{{ asset('css/debugbar.css') }}" type="text/css"> {% endif %} <!-- End for Responsive --> <!-- For SEO --> <title>{% block title %}Joomla! Framework, a framework for developing PHP applications{% endblock %}</title> <meta charset="utf-8"> <meta name="description" content="{% block metaDescription %}The Joomla! Framework provides a structurally sound foundation on which to build applications in PHP, which is easy to adapt and extend. Let's find out more!{% endblock %}"> <meta name="generator" content="Joomla! Framework" /> <meta property="og:description" content="{{ block('metaDescription') }}" /> <meta property="og:locale" content="en_US" /> <meta property="og:site_name" content="Joomla! Framework" /> <meta property="og:title" content="{{ block('title') }}" /> <meta property="og:type" content="{% block metaOgType %}website{% endblock %}" /> <meta property="og:url" content="{{ request_uri() }}" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@JoomlaFramework" /> <meta name="twitter:description" content="{{ block('metaDescription') }}" /> <meta name="twitter:title" content="{{ block('title') }}" /> {% block metadata %}{% endblock %} <!-- End for SEO --> <!-- For Misc --> <link href="favicon.ico" rel="shortcut icon" /> <!-- End for misc --> {% block headJavaScript %} {% endblock %} </head> <body id="go"> {% block bodyNavigation %} <nav class="container-fluid"> <ul> <li><a href="{{ route() }}"><span class="fab fa-joomla" aria-hidden="true"></span><span class="title">Framework</span></a></li> <li><a href="{{ route('status') }}"><span class="fas fa-wrench" aria-hidden="true"></span><span class="title">Status</span></a></li> </ul> </nav> {% endblock %} <main> {% block content %}{% endblock %} </main> <footer class="clearfix" role="contentinfo" id="resources"> {% block footerContent %} {% import 'macros.twig' as macros %} <div class="container"> {{ macros.footer_copyright() }} </div> {% endblock %} </footer> <script src="{{ asset('js/template.js', 'mix') }}"{{ sri('js/template.js') }}></script> {% block bodyJavaScript %}{% endblock %} {% if appDebug %} <script src="{{ asset('js/debugbar.js') }}"></script> {% endif %} </body> </html>
#------------------------------------------------------------------------- # AUTHOR: Jessica Ortega # FILENAME: title of the source file # SPECIFICATION: description of the program # FOR: CS 4210- Assignment #5 # TIME SPENT: how long it took you to complete the assignment #-----------------------------------------------------------*/ #importing some Python libraries from sklearn.cluster import KMeans from sklearn.cluster import AgglomerativeClustering import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import silhouette_score from sklearn import metrics df = pd.read_csv('training_data.csv', sep=',', header=None) #reading the data by using Pandas library #assign your training data to X_training feature matrix X_training = df.values #run kmeans testing different k values from 2 until 20 clusters #Use: kmeans = KMeans(n_clusters=k, random_state=0) # kmeans.fit(X_training) #--> add your Python code silhouette_scores = [] best_silhouette_score = -1 best_k = 0 for k in range(2, 21): kmeans = KMeans(n_clusters=k, random_state=0) kmeans.fit(X_training) #for each k, calculate the silhouette_coefficient by using: silhouette_score(X_training, kmeans.labels_) #find which k maximizes the silhouette_coefficient #--> add your Python code here silhouette_coefficient = silhouette_score(X_training, kmeans.labels_) silhouette_scores.append(silhouette_coefficient) if silhouette_coefficient > best_silhouette_score: best_silhouette_score = silhouette_coefficient best_k = k #plot the value of the silhouette_coefficient for each k value of kmeans so that we can see the best k #--> add your Python code here plt.plot(range(2, 21), silhouette_scores) plt.xlabel('K Values') plt.ylabel('Silhouette Coefficient') plt.title('Silhouette Coefficient') plt.show() #reading the test data (clusters) by using Pandas library #--> add your Python code here df_test = pd.read_csv('testing_data.csv', sep=',', header=None) #assign your data labels to vector labels (you might need to reshape the row vector to a column vector) # do this: np.array(df.values).reshape(1,<number of samples>)[0] #--> add your Python code here labels = np.array(df_test.values).reshape(1, -1)[0] #Calculate and print the Homogeneity of this kmeans clustering kmeans = KMeans(n_clusters = best_k, random_state=0) kmeans.fit(X_training) print("K-Means Homogeneity Score = " + metrics.homogeneity_score(labels, kmeans.labels_).__str__())
import React, { useState } from "react"; import { StaticImageData } from 'next/image'; import Image from "next/image"; export interface Technology { icon: string | StaticImageData; color: string; } export interface Image { src: string | StaticImageData; } export interface Project { id: string; technologies: Technology[]; title: string; preview: string; desc: string; imgs: Image[]; repository: string; live: string; icon: React.ReactElement; bg: string; scale: number; } interface HighlightProjectProps { project: Project; handleDetails: (project: Project) => void; setImageModalProject: (project: Project) => void; setShowImageModal: (value: boolean) => void; setImageModalSrc: (src: number) => void; } const HighlightProject: React.FC<HighlightProjectProps> = ({ project, handleDetails, setImageModalProject, setImageModalSrc, setShowImageModal, }) => { const [mainImgIndex, setMainImgIndex] = useState(0); const handleMainImg = (i: number) => { setImageModalProject(project); setImageModalSrc(i); setShowImageModal(true); }; // map project technologies const mapTech = (techArr: Technology[]) => { return techArr.map((tech, index) => ( <div className="flex pointer-events-auto" key={index}> <div className={`${tech.color} techBox flex items-center justify-center m-1 p-1 text-black font-bold overflow-hidden cursor-pointer transition-all ease-in duration-200`} style={{flex:2}} > <div className="min-w-6 max-w-6 min-h-6 max-h-6 flex justify-center items-center mr-1 overflow-hidden"> <Image src={tech.icon} alt="Tech Icon" className="min-w-4 max-w-4 min-h-4 max-h-4" /> </div> <div className="text-lg leading-6 mr-2 px-1">{tech.color}</div> </div> </div> )); }; return ( <div className="highlightWrapper pointer-events-auto md:pointer-events-none overflow-scroll flex flex-col pr-6 md:pr-0 mix-blend-overlay md:flex-row"> {/* LEFT */} <div className="flex flex-col" style={{flex:"2"}}> <div className="pointer-events-auto title-container flex flex-col md:flex-row items-center gap-3"> {/* PROJECT LOGO */} <div onClick={() => handleDetails(project)} className="h-full cursor-pointer w-20 p-4 rounded-2xl flex justify-center items-center text-black" style={{ background: project.bg, }} > <span className={`scale-105 `}>{project.icon}</span> </div> {/* TITLE */} <div className="flex gap-5 md:gap-7 justify-center items-center"> <p className="text-xl md:text-2xl tracking-wider smallHeading relative uppercase italic text-[#ccc]" style={{ fontFamily: "Russo One, sans-serif" }} onClick={() => handleDetails(project)} > {project.title} </p> {/* CLOSE DETAILS */} <i onClick={() => handleDetails(project)} className="fa-solid fa-down-left-and-up-right-to-center text-[#a2a0a0] cursor-pointer hover:text-[#FFD474]"></i> {/* LIVE LINK */} <a href={project.live} target='_blank' rel="noopener noreferrer"><i className="fa-solid fa-globe text-[#a2a0a0] cursor-pointer hover:text-[#FFD474]"></i></a> {/* REPO */} <a href={project.repository} target='_blank' rel="noopener noreferrer"><i className="fa-solid fa-code text-[#a2a0a0] cursor-pointer hover:text-[#FFD474]"></i></a> </div> </div> {/* DESCRIPTION */} <div className="text-sm md:text-lg font-semibold tracking-wide p-3 my-1 z-20"> <p className="text-[#ccc]"> <i className="fa-solid fa-angle-right mr-3 text-[#ffd474]"></i>{project.desc} </p> </div> {/* TECH */} <div className="flex flex-wrap justify-start items-start"> {mapTech(project.technologies)} </div> </div> {/* RIGHT */} <div className="w-full flex mx-auto my-10 bg-[#1a1e21] ImageContainerNotch" style={{flex:"2"}}> <div className="pointer-events-auto inner my-4 mx-3 overflow-y-scroll w-full flex items-start justify-center ImageInnerNotch"> <div className="gallery flex flex-col"> {project.imgs.map((img, i) => { return ( <div key={i} className="min-w-full max-w-full p-5 m flex justify-center items-center" onClick={() => handleMainImg(i)}> <Image src={img.src} className={`object-contain max-w-full max-h-80 cursor-pointer ${mainImgIndex === i && "current"}`} alt="Project Image" style={{border:"7px solid #2b2f33"}} /> </div> ); })} </div> </div> </div> </div> ); }; export default HighlightProject;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/Users/nguyenducanh/Documents/GitHub/HTMLAndCSS/CSSLayout/facebook/fontawesome-free-6.1.2-icon/css/all.css"> <style> * { box-sizing: border-box; } .head_link { height: 50px; background-color: rgb(0, 0, 0, 0.7); } .head_link ul { list-style-type: none; padding: 0; } ul li { opacity: 0.7; display: inline; font-size: 20px; padding: 10px ; float: left; color: white; height: 50px; } button { float: right; font-size: 20px; padding: 10px; background-color: rgb(0, 0, 0, 0.0); border: none; color: white; opacity: 0.7; height: 50px; } li:hover, button:hover { background-color: black; opacity: 1.0; } .link { background-color: #cdcdcd; width: 15%; float: left; height: 500px; } .link a { display: block; text-decoration: none; text-align: center; padding: 10px; } a:hover { color: white; background-color: dodgerblue; } .main { width: 70%; padding: 20px; text-align: left; float: left; height: 500px; } .right { background-color: #cdcdcd; width: 15%; float: left; height: 500px; } .right div { background-color: #f5f5f5; margin: 30px 10px; text-align: center; height: 100px; padding: 30px; font-size: 20px; } .footer { background-color: rgb(58, 55, 55); text-align: center; padding: 20px; height: 50px; color: white; font-size: 16px; clear: both; } @media only screen and (max-width:680px) { .link { width: 30%; height:400px } .main { width: 70%; height: auto; } .right { display: none; height: auto; } .head_link { height: 45px; } .head_link ul li , button { font-size: 18px; padding: 15px; height: 45px; } .footer { height: 45px; font-size: 15px; padding: 15px; } } @media only screen and (max-width:500px) { .link, .main, .right { width: 100%; } .link { height: auto; } .head_link { height: 40px; text-align: left; } .head_link ul li , button { font-size: 16px; padding: 10px; height: 40px; } .footer { height: 40px; font-size: 14px; padding: 10px; } } </style> </head> <body> <div class="head_link"> <ul> <li>Logo</li> <li>Home</li> <li>About</li> <li>Project</li> <li>Contact</li> </ul> <button><i class="fa-solid fa-right-to-bracket"></i>Login</button> </div> <div class="link"> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> </div> <div class="main"> <div> <h2>Welcome</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim venam, quis nostrud exercitation ulamco laboris nisi ut aliquip ex es commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui offcia deserunt mollit anm id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt at labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <hr> <div> <h4>Test</h4> <p>Lorem ipsum...</p> </div> </div> <div class="right"> <div>ADS</div> <div>ADS</div> </div> <div class="footer">Footer Text</div> </body> </html>
// adapted from: https://www.npmjs.com/package/intrinsic-scale import { Fiber } from "../types"; import { calculateDistance } from "@coszio/react-measurements"; /** * * @param contains Type of fitting: object-contain = `true`, object-cover = `false` * @param image HTML image reference * @returns The real fitted dimensions of the image, along with its offset */ export function getObjectFitSize( contains: boolean /* true = contain, false = cover */, image: HTMLImageElement ) { let doRatio = image.naturalWidth / image.naturalHeight; let cRatio = image.width / image.height; let targetWidth = 0; let targetHeight = 0; let test = contains ? doRatio > cRatio : doRatio < cRatio; if (test) { targetWidth = image.width; targetHeight = targetWidth / doRatio; } else { targetHeight = image.height; targetWidth = targetHeight * doRatio; } return { width: targetWidth, height: targetHeight, x: (image.width - targetWidth) / 2, y: (image.height - targetHeight) / 2, }; } /** * Calculates the real size of the image from a measurement and its length */ export const calculateRealImageSize = ( measurement: any, length: number, imageDims: { width: number; height: number } ) => { let percentage_dx = Math.abs(measurement.startX - measurement.endX); let percentage_dy = Math.abs(measurement.startY - measurement.endY); let pixel_dx = percentage_dx * imageDims.width; let pixel_dy = percentage_dy * imageDims.height; let pixel_length = Math.sqrt(pixel_dx ** 2 + pixel_dy ** 2); return { width: (imageDims.width * length) / pixel_length, height: (imageDims.height * length) / pixel_length, }; }; export const average = (arr: number[]) => { return arr.reduce((a, b) => a + b, 0) / arr.length; }; export const fibersToCSV = ( fibers: Fiber[], realDims: { width: number; height: number }, magnitude: string ) => { const headers = [ "fiberId", `measureLength (${magnitude})`, "startX (%)", "startY (%)", "endX (%)", "endY (%)", ].join(","); const data = fibers .map( (fiber) => fiber.measurements .map((line) => { const realLength = calculateDistance( line, realDims.width, realDims.height ); return [ fiber.id, realLength, line.startX, line.startY, line.endX, line.endY, ].join(","); // line }) .join("\n") // lines in fiber ) .join("\n"); // all lines of all fibers return [headers, data].join("\n"); };
import Control.Monad (replicateM) main :: IO () main = do t <- readLn :: IO Int inputs <- replicateM t $ do line <- getLine let [a, b] = read <$> words line return (a, b) mapM_ (uncurry printFormat) (zip [1..] inputs) printFormat :: Int -> (Int, Int) -> IO () printFormat idx (a, b) = putStrLn $ "Case #" ++ show idx ++ ": " ++ show a ++ " + " ++ show b ++ " = " ++ show (a + b)
// Copyright (C) 2024 owoDra #pragma once #include "Engine/CancellableAsyncAction.h" #include "Type/OnlineServiceResultTypes.h" #include "Type/OnlineLobbyAttributeTypes.h" #include "AsyncAction_ModifyLobbyAttributes.generated.h" class UOnlineLobbySubsystem; class ULobbyResult; class APlayerController; /** * Delegate to notifies modify lobby attributes complete */ DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FAsyncModifyLobbyAttributesDelegate , const APlayerController* , PlayerController , const ULobbyResult* , LobbyResult , FOnlineServiceResult , ServiceResult); /** * Async action to modify lobby attributes */ UCLASS() class GCONLINE_API UAsyncAction_ModifyLobbyAttributes : public UCancellableAsyncAction { GENERATED_BODY() protected: TWeakObjectPtr<UOnlineLobbySubsystem> Subsystem; TWeakObjectPtr<APlayerController> PC; TWeakObjectPtr<const ULobbyResult> Lobby; TSet<FLobbyAttribute> ToChange; TSet<FLobbyAttribute> ToRemove; public: UPROPERTY(BlueprintAssignable) FAsyncModifyLobbyAttributesDelegate OnComplete; public: /** * Modify hosting lobby's attributes */ UFUNCTION(BlueprintCallable, Category = "Lobby", meta = (AutoCreateRefTerm = "AttrToChange, AttrToRemove", BlueprintInternalUseOnly = "true")) static UAsyncAction_ModifyLobbyAttributes* ModifyLobbyAttributes( UOnlineLobbySubsystem* Target , APlayerController* PlayerController , const ULobbyResult* LobbyResult , const TSet<FLobbyAttribute>& AttrToChange , const TSet<FLobbyAttribute>& AttrToRemove); protected: virtual void Activate() override; virtual void HandleFailure(); virtual void HandleModifyLobbyAttributeComplete(const ULobbyResult* LobbyResult, FOnlineServiceResult Result); };
var levens = 2; var kolommenMetBom = []; var spelActief = true; //var levens geeft het aantal levens aan (begin is 2 levens), kolommenMetBom is een lijst waar de kollomen in staan waar een bom zich op de x waarde bevind, spelActief is om te bepalen of het spel actief is of niet class Raster { constructor(r,k) { this.aantalRijen = r; this.aantalKolommen = k; this.celGrootte = null; } berekenCelGrootte() { this.celGrootte = canvas.width / this.aantalKolommen; } // berekent de grootte van de cel teken() { push(); noFill(); stroke('grey'); for (var rij = 0;rij < this.aantalRijen;rij++) { for (var kolom = 0;kolom < this.aantalKolommen;kolom++) { rect(kolom*this.celGrootte,rij*this.celGrootte, this.celGrootte,this.celGrootte); // Het raster is grijs en 12x18 if (rij == 5 || kolom == 5) { fill('orange'); rect(kolom * this.celGrootte, rij * this.celGrootte, this.celGrootte, this.celGrootte); noFill(); } // Maakt rij en kolom 5 oranje } } pop(); } } class Jos { constructor() { this.x = 400; this.y = 300; this.animatie = []; this.frameNummer = 3; this.stapGrootte = null; this.gehaald = false; this.staOpBom = false; } // Kenmerken van Jos, x en y coordinaten, reeks van animaties in array eetAppel(appel) { const afstand = dist(this.x, this.y, appel.x, appel.y); if (afstand < this.stapGrootte / 2) { appel.verplaats(); levens++; return true; } return false; } // zorgt ervoor dat wanneer de appel gegeten wordt er een leven bij komt( er komt + 1 bij de variabele levens). En beweeg() { if (keyIsDown(65)) { this.x -= this.stapGrootte; this.frameNummer = 2; } if (keyIsDown(68)) { this.x += this.stapGrootte; this.frameNummer = 1; } if (keyIsDown(87)) { this.y -= this.stapGrootte; this.frameNummer = 4; } if (keyIsDown(83)) { this.y += this.stapGrootte; this.frameNummer = 5; } this.x = constrain(this.x,0,canvas.width); this.y = constrain(this.y,0,canvas.height - raster.celGrootte); if (this.x == canvas.width) { this.gehaald = true; } } //zorgt ervoor dat wasd wordt gebruit als input om jos te laten bewegen, constrain wordt gebruikt om jos zijn beweging te limiteren tot de randen van het canvas. wordtGeraakt(vijand) { if (this.x == vijand.x && this.y == vijand.y) { return true; } else { return false; } } toon() { image(this.animatie[this.frameNummer],this.x,this.y,raster.celGrootte,raster.celGrootte); } } //de gegevens hoe jos wordt afgebeeld class Vijand { constructor(x,y) { this.x = x; this.y = y; this.sprite = null; this.stapGrootte = null; } beweeg() { this.x += floor(random(-1,2))*this.stapGrootte; this.y += floor(random(-1,2))*this.stapGrootte; this.x = constrain(this.x,0,canvas.width - raster.celGrootte); this.y = constrain(this.y,0,canvas.height - raster.celGrootte); } // Bewegen van de vijand is random met steeds stappen van 1 rasterhokje, ook is de beweging gelimiteerd tot slechts het canvas toon() { image(this.sprite,this.x,this.y,raster.celGrootte,raster.celGrootte); } } class Bom { constructor(grootteStap, x, y,snelheid){ this.x = x; this.y = y; this.grootteStap = grootteStap; this.snelheid = snelheid; this.omhoog = true; this.sprite = null; } // beweeg() { if (this.omhoog) { this.y -= this.snelheid; } else { this.y += this.snelheid; } if (this.y <= 0) { this.omhoog = false; } else if (this.y >= canvas.height - raster.celGrootte) { this.omhoog = true; } } // methode beweeg wordt gebruikt om de bommen over de y-as op en neer te laten bewegen binnen de randen van het canvas. toon() { image(this.sprite,this.x,this.y,raster.celGrootte,raster.celGrootte); } wordtGeraakt(jos) { // Bereken de afstand tussen de huidige bom en de speler 'jos'. const afstand = dist(this.x, this.y, jos.x, jos.y); // Als de afstand tussen de bom en 'jos' kleiner is dan de helft van de stapgrootte van 'jos', if (afstand < jos.stapGrootte / 2) { levens--; this.reset(); return true; } return false; } // als de bom wordt geraakt door jos zal er 1 leven van de speler af gaan reset() { var kolom; do { kolom = floor(random(raster.aantalKolommen / 2, raster.aantalKolommen - 1)); } while (kolommenMetBom.includes(kolom)); kolommenMetBom.push(kolom); this.x = kolom * raster.celGrootte + 5; this.y = floor(random(0, raster.aantalRijen)) * raster.celGrootte + 4; } } // checkt of de kolom een bom bevat, zo ja wordt de kolom bij de array kolommenMetBom toegevoegd, vervolgens wordt de positie van de bom op basis van de nieuw toegevoegde kolom ingesteld. Dit zorgt ervoor dat de bom op een nieuwe locatie wordt geplaatst als de gekozen kolom al een bom bevatte. class Appel { constructor() { this.x = floor(random(1,raster.aantalKolommen))*raster.celGrootte + 5; this.y = floor(random(0,raster.aantalRijen))*raster.celGrootte + 4; } //de appel wordt perfect in een hokje geplaatst toon() { image(this.sprite,this.x,this.y,raster.celGrootte - 10,raster.celGrootte - 10); } // Appel die zorgt voor +1 leven na het eten. verplaats() { this.x = 900 this.y = floor(random(0, raster.aantalRijen - 1)) * raster.celGrootte + 4; } //nadat de appel wordt gegeten verdwijnt de appel buiten het canvas raakJos (jos) { // Bereken de afstand tussen de huidige bom en de speler 'jos'. const afstand = dist(this.x, this.y, jos.x, jos.y); // Als de afstand tussen de bom en 'jos' kleiner is dan de helft van de stapgrootte van 'jos', if (afstand < jos.stapGrootte / 2) { // Genereer een nieuwe positie voor de bom na de botsing. this.x = floor(random(1, raster.aantalKolommen)) * raster.celGrootte + 5; this.y = floor(random(0, raster.aantalRijen)) * raster.celGrootte + 4; return true; } return false; } } function preload() { brug = loadImage("images/backgrounds/dame_op_brug_1800.jpg"); } function setup() { canvas = createCanvas(900,600); canvas.parent(); frameRate(10); textFont("Verdana"); textSize(90); raster = new Raster(12,18); raster.berekenCelGrootte(); // Code van de Canvas eve = new Jos(); eve.stapGrootte = 1*raster.celGrootte; for (var b = 0;b < 6;b++) { frameEve = loadImage("images/sprites/Eve100px/Eve_" + b + ".png"); eve.animatie.push(frameEve); } // Plaatje van Eve/Jos afgebeeld op grootte gebaseerd op het hokje van het raster alice = new Vijand(700,200); alice.stapGrootte = 1*eve.stapGrootte; alice.sprite = loadImage("images/sprites/Alice100px/Alice.png"); // Plaatje van vijand Alice bob = new Vijand(600,400); bob.stapGrootte = 1*eve.stapGrootte; bob.sprite = loadImage("images/sprites/Bob100px/Bob.png"); // Plaatje van vijand Bob Appel = new Appel(); Appel.sprite = loadImage("images/sprites/appel_1.png"); // Plaatje van de groene appel. bommenLijst = []; //lijst met bommen // Een lus die vijf keer wordt uitgevoerd om vijf bommen aan het spel toe te voegen. for (var i = 0; i < 5; i++) { // Genereert willekeurig een kolom waarin de bom wordt geplaatst. var kolom; do { kolom = floor(random(raster.aantalKolommen / 2, raster.aantalKolommen - 1)); } while (kolommenMetBom.includes(kolom)); // // Zorg ervoor dat de kolom nog geen bom bevat. kolommenMetBom.push(kolom); // Voeg de gekozen kolom toe aan de lijst van kolommen met bommen. // Bereken de x- en y-coördinaten waar de bom zal worden geplaatst. var x = kolom * raster.celGrootte + 5; var y = floor(random(0, raster.aantalRijen)) * raster.celGrootte + 4; // Genereer een willekeurige snelheid voor de bom tussen 10 en 20. var snelheid = random(10, 20); // Maak een nieuw 'Bom'-object aan met de berekende eigenschappen. var bom = new Bom(raster.celGrootte, x, y, snelheid); bom.sprite = loadImage("images/sprites/bom.png"); //gegeven plaatje en file path bommenLijst.push(bom); // Voeg de bom toe aan de lijst van bommen in het spel. } } function draw() { background(brug); raster.teken(); //raster en achtergrond wordt getekend if (spelActief) { eve.beweeg(); alice.beweeg(); bob.beweeg(); eve.toon(); alice.toon(); bob.toon(); Appel.toon(); //eve alice bob en hun beweging en de appel worden getekend als spelactief true is //loop door de lijst van de bommen in het spel for (var i = 0; i < bommenLijst.length; i++) { //haalt de bommen uit de lijst var bom = bommenLijst[i]; bom.beweeg(); bom.toon(); // laat de bom tonen en bewegen if (bom.wordtGeraakt(eve)) { if (levens > 0) { levens - 1; } else { spelActief = false; } } } } // -1 leven elke keer dat je geraakt wordt door een bom fill("black"); textSize(24); text("Levens: " + levens, 30, 30); //tekst van levens if (eve.wordtGeraakt(alice) || eve.wordtGeraakt(bob)) { if (levens > 1) { levens--; } else { spelActief = false; } } //Als de levens groter is dan 1 is blijft het spel actief en gaat er 1 leven van de speler af, is de levens minder dan 1 is spelactief false en gaat het spel af en stopt de loop. if (eve.gehaald) { background('green'); fill('white'); textSize(80); text("Gefeliciteerd", 210,250); text("je hebt gewonnen!", 100,340); noLoop(); } // Groene achtergrond nadat je gewonnen hebt en winnende tekst( win scherm). if (!spelActief) { background('red'); fill('white'); textSize(80); text("Helaas", 300, 250); text("je hebt verloren", 130, 350); } // Rode achtergrond nadat je verloren hebt. if (eve.eetAppel(Appel)) { } } // Zorgt er voor dat de appel gegeten wordt
import { Editor, TLFrameShape, TLShapeId, TLSvgOptions } from '@tldraw/editor' import { exportToBlob } from './export' /** @public */ export type TLExportType = 'svg' | 'png' | 'jpeg' | 'webp' | 'json' /** * Export the given shapes as files. * * @param editor - The editor instance. * @param ids - The ids of the shapes to export. * @param format - The format to export as. * @param name - Name of the exported file. If undefined a predefined name, based on the selection, will be used. * @param opts - Options for the export. * * @public */ export async function exportAs( editor: Editor, ids: TLShapeId[], format: TLExportType = 'png', name: string | undefined, opts = {} as Partial<TLSvgOptions> ) { // If we don't get name then use a predefined one if (!name) { name = `shapes at ${getTimestamp()}` if (ids.length === 1) { const first = editor.getShape(ids[0])! if (editor.isShapeOfType<TLFrameShape>(first, 'frame')) { name = first.props.name ?? 'frame' } else { name = `${first.id.replace(/:/, '_')} at ${getTimestamp()}` } } } name += `.${format}` const blob = await exportToBlob({ editor, ids, format, opts }) const file = new File([blob], name, { type: blob.type }) downloadFile(file) } function getTimestamp() { const now = new Date() const year = String(now.getFullYear()).slice(2) const month = String(now.getMonth() + 1).padStart(2, '0') const day = String(now.getDate()).padStart(2, '0') const hours = String(now.getHours()).padStart(2, '0') const minutes = String(now.getMinutes()).padStart(2, '0') const seconds = String(now.getSeconds()).padStart(2, '0') return `${year}-${month}-${day} ${hours}.${minutes}.${seconds}` } function downloadFile(file: File) { const link = document.createElement('a') const url = URL.createObjectURL(file) link.href = url link.download = file.name link.click() URL.revokeObjectURL(url) }
MIT Department of Biology 7.014 Introductory Biology, Spring 2005 7.014 Quiz II Handout **This will be a closed book exam** Question 1 Shown below is a representation of an origin of replication. template 1 CAAGG A GGAAC C template 3 3' 5' 5' 3' B CAAGG template 2 fork 1 ORI fork 2 D GGAAC template 4 a) For the following, use sites A and B with respect to fork 1 and sites C and D with respect to fork 2. i) On which strand(s) will replication be continuous? template 3 template 2 template 1 template 4 ii) To which site or sites (A, B, C, or D) can the primer 5'-GUUCC-3' bind to initiate replication? iii) When DNA ligase is inhibited, it differentially affects the synthesis from the leading and the lagging strands. Explain which strand (leading or lagging) is more affected by the lack of DNA ligase and why. 2 Question 1, continued b) The next nucleotide to be added to a growing DNA strand is dCTP (shown). • Circle the part of the growing DNA chain to which the next base is attached. • Circle the part of the dCTP that is incorporated into the growing DNA chain. Growing DNA chain CH3 O CH 2 O C N N C O C C OH H - O O P O - O O P - O O O P - O NH 2 dCTP O CH 2 C O N O N C C C OH H c) DNA Replication involves many different enzymatic activities. Match each enzyme activity listed below with the function(s) that it has in the replication process. The first one is done for you. Enzyme Activity Function(s) Choose From: Topoiosmerase k a) 3’ 5’ growth of new DNA strand Primase (synthesizes primer) DNA polymerase to elongate new DNA strand Helicase to unwind DNA DNA polymerase to replace RNA with DNA Processivity factor b) 5’ 3’ growth of new DNA strand c) 3’ 5’ exonuclease d) 5’ 3’ exonuclease e) Makes RNA primer complementary to the lagging strand f) Makes RNA primer complementary to the leading strand g) Makes peptide bonds h) Separates the two DNA strands i) Ma in ta ins DNA po lymerase on template j) Provides 3’ hydroxyl for initiation of DNA polymerization k) Untangles super-coiled DNA 3 Question 2 Below is the partial sequence of the sevenohwunforin (7014in) gene, hypothesized to be mutant in students who take 7.013 Introductory Biology and in those students at the other school up the river. The promoter is underlined and transcription begins at and includes the bold G/C base pair. 5’ TGCCA TCCGA TTGGT GTTCC TTCCA TGAAG GATGC ACAAC GCAAA 3’ 3’ ACGGT AGGCT AACCA CAAGG AAGGT ACTTC CTACG TGTTG CGTTT 5’ 5’ TACAC GCTTA GCTGA CTATA AGGAC GAATC GCTAC AACGA TGCGA 3’ 3’ ATGTG CGAAT CGACT GATAT TCCTG CTTAG CGATG TTGCT ACGCT 5’ 5’ TGCCA TCCGA TTGGT GTTCC TTCCA TGAAG GATGC ACAAC GCAAA 3’ 3’ ACGGT AGGCT AACCA CAAGG AAGGT ACTTC CTACG TGTTG CGTTT 5’ a) What are the first 12 nucleotides of the transcript encoded by the 7014in gene? Label the 5’ and 3’ ends. __’- -__’ b) On the DNA sequence above, circle the DNA bases that encode the first amino acid of the protein. c) What are the first four amino acids encoded by the 7014in transcript? Label the N- and C- terminus ____- - ___ d) You want to create a system to translate a specific mRNA in a test tube. To an appropriate water and salt solution you add many copies of this mRNA and ATP (energy). What other key components must you add? You succeed in translating the mRNA in your test tube. You repeat the experiment with two identical test tubes. You add limiting amounts of the antibiotic puromycin to test tube 2 only. Puromycin is a molecule that has structural similarities to the 3’ end of a charged tRNA. It can enter the ribosome and be incorporated into the growing protein. When puromycin is incorporated into the polypeptide, it stalls the ribosome and the polypeptide is released. You do not know if puromycin recognizes a specific codon or not. e) What effect would puromycin have on transcription? f) What effect would puromycin have on translation? 4 Question 2, continued g) You examine the length of the polypeptide produced in both test tubes. i) In test tube 1 (no puromycin) you get a polypeptide that is 100 amino acids long. At least how many bases was the mRNA that you added? ii) Which of the following would you find in test tube 2 (has limiting amounts of puromycin) if puromycin does NOT recognize a specific codon. Only a single type of polypeptide Only 2 types of polypeptides that are each different lengths Only 3 types of polypeptides that are each different lengths Only 4 types of polypeptides that are each different lengths Polypeptides of all sizes, i.e., dipeptides, tripeptides, … a polypeptide that is 100 amino acids long iii) Which of the following would you find in test tube 2 (has limiting amounts of puromycin) if puromycin recognizes a specific codon that occurs three times in the mRNA. Only a single type of polypeptide Only 2 types of polypeptides that are each different lengths Only 3 types of polypeptides that are each different lengths Only 4 types of polypeptides that are each different lengths Polypeptides of all sizes, i.e., dipeptides, tripeptides, … a polypeptide that is 100 amino acids long 5 Question 2, continued The 7014in gene encodes a protein (7014IN) that binds the neurotransmitter serotonin, as shown below. The five amino acids 7014IN involved in binding serotonin are shown. To understand the difference between introductory biology students, you have determined the DNA sequence for the 7014in gene in a group of 7.013 and 7.014 students. Below is the 7014IN protein and the DNA sequence that encodes it. The amino acids depicted in the picture above are underlined. From a 7.014 student: 5’ ACC AAT GGA CCA GCA GGA AGC GGG GTA GCT GAG TAC 3’ DNA 3’ TGG TTA CCT GGT CGT CCT TCG CCC CAT CGA CTC ATG 5’ Protein N- Thr Asn Gly Pro Ala Gly Ser Gly Val Ala Glu Tyr –C h) You find that 7.013 student 1 has the following DNA sequence for the 7014IN: 5’ ACC AAT GGA CCA GCA GGA TAG CGG GGT AGC TGA GTAC 3’ 3’ TGG TTA CCT GGT CGT CCT ATC GCC CCA TCG ACT CATG 5’ i) Indicate (circle/underline) the site of the mutation on the sequence directly above. ii) Does student 1 have an insertion, deletion, or substitution mutation? iii) Would you expect this DNA sequence to encode a protein that binds serotonin? Why or why not? A chart of the amino acids is found on page 10. i) You find that 7.013 student 2 has the following DNA sequence for the 7014IN: 5’ ACC AAT GGA CCA GCA GGA AGC GGG GTA GCT GAT TAC 3’ 3’ TGG TTA CCT GGT CGT CCT TCG CCC CAT CGA CTA ATG 5’ i) Indicate (circle/underline) the site of the mutation on the above sequence. ii) Does student 2 have an insertion, deletion, or substitution mutation? iii) Would you expect this DNA sequence to encode a protein that binds serotonin? Why or why not? A chart of the amino acids is found on page 10. 6 Question 3, continued You construct the following diploids by inserting a second copy of the operon into each mutant. + indicates that the component is wild type, - indicates that the component is non- functional. with maltose without maltose Enzyme A activity high Enzyme B activity high Enzyme A activity low Enzyme B activity low low low Strain Wild type with R+ Penz + O+A+ B+ m1 with R+ Penz + O+ A- B- m1 with R+ Penz + O+A+ B+ m2 with R+ Penz + O+ A- B- m3 with R+ Penz + O+ A- B- d) Which one of the three mutants (m1, m2 or m3) has a mutation in the gene for the repressor protein? Briefly explain your reasoning. high high low low low low high high high high high low high low e) You examine the number of mRNA molecules (transcripts) produced from the maltose operon(s) in each cell. Complete the table below. with maltose Number of transcripts 1000 2000 without maltose Number of transcripts 10 20 Cell Wild type Wild type with R+ P+ O+ A- B- R+ P- O+ A- B- R+ P+ O+ A- B- R+ P+ O- A- B- R+ P+ O+ A- B- R- P+ O+ A- B- R+ P+ O+ A- B- 8 C A C U phe (F) ser (S) tyr U UUU UCU UAU tyr ser phe UAC UCC UUC STOP ser leu (L) UAA UUA UCA STOP ser leu UAG UCG UUG leu pro (P) his CUU CCU CAU his pro leu CAC CCC CUC gln pro leu CAA CCA CUA gln pro leu CUG CCG CAG ile (I) thr (T) asn A AUU ACU AAU asn thr ile AAC ACC AUC lys thr ile AAA AUA ACA met (M) thr lys AUG ACG AAG asp ala (A) val (V) G GUU GCU GAU asp ala val GAC GCC GUC glu ala val GAA GCA GUA val ala glu GUG GCG GAG (H) (Q) G (Y) UGU cys cys UGC STOP UGA trp UGG arg CGU arg CGC arg CGA arg CGG ser AGU ser AGC arg AGA arg AGG gly GGU gly GGC gly GGA gly GGG (N) (E) (K) (D) (C) U C A (W) G (R) U C A G U C A G (G) U C A G (S) (R) STRUCTURES OF AMINO ACIDS - O O C H C CH3 NH3 + ALANINE (ala) - O O C H H C CH2CH2CH2 N NH3 + ARGININE (arg) NH2 C NH2 + - O O C O C H C CH2 NH3 + ASPARAGINE (asN) NH2 - O O C H C CH2 SH NH3 + CYSTEINE (cys) - O O O C - O C H C CH2CH2 NH3 + GLUTAMIC ACID (glu) - O O C H C CH2CH2 C NH3 + GLUTAMINE (glN) O NH2 - O O C O - O C H C CH2 NH3 + ASPARTIC ACID (asp) - O O C H C H NH3 + GLYCINE (gly) - O O H N + C H C CH2 NH3 + C C N H HISTIDINE (his) H H O - O C H H C C CH2CH3 NH3 CH3 + ISOLEUCINE (ile) - O O C H H C CH2 C CH3 NH3 CH3 + LEUCINE (leu) - O O C H C CH2CH2CH2CH2 NH3 NH3 + LYSINE (lys) - O O C H C CH2CH2 S CH3 NH3 + METHIONINE (met) - O O H H H C H C CH2 NH3 + H H PHENYLALANINE (phe) H - O O CH2 H H C C N CH2 + H PROLINE (pro) CH2 - O O O C H C CH2 C NH3 + - O C H H C C CH3 NH3 OH + H THREONINE TRYPTOPHAN (thr) (trp) H N H H H H - O O C H C CH2 NH3 + H TYROSINE (tyr) H H OH - O O C H C CH2 OH NH3 + SERINE (ser) - O O CH3 C CH3 H C C NH3 H + VALINE (val) + 10 Solutions: Question 1 i) a) template 1 ii) B and C iii) The lagging strand is more affected by the lack of DNA ligase. DNA replication on the lagging strand occurs in small stretches called Okasaki fragments. For replication of the lagging strand to be complete, a phosphodiester bond must be formed between the 3'OH on one Okasaki fragment and the 5' phosphate on the other. DNA ligase makes this bond. template 3 template 2 template 4 Growing DNA chain CH3 O O CH 2 C N N C C OH C H O dCTP NH 2 - O O P O - O O P - O O O P O - O CH 2 C O N N O C C OH C H b) c) Enzyme Activity Function(s) Topoiosmerase Primase (synthesizes primer) DNA polymerase to elongate new DNA strand Helicase to unwind DNA DNA polymerase to replace RNA with DNA Processivity factor k e, f, j b, c h b, d i Question 2 a) 5’ G A A U C G C U A C A A 3’ 11
import { createAction } from './helper'; import { apiUrl, ApiService } from '../services/ApiService'; import { PokemonsListActions, PokemonActions, PokemonAbilityActions, } from '../constants/actionTypes'; export const getPokemonList = () => { const loadStart = createAction(PokemonsListActions.POKEMONS_LIST_LOADING); const loadSuccess = (list) => createAction(PokemonsListActions.POKEMINS_LIST_LOADED, { pokemonList: list, }); const loadError = createAction(PokemonsListActions.POKEMONS_LIST_LOAD_ERROR); const asyncAction = { actions: [loadStart, loadSuccess, loadError], apiCall: () => fetch(`${apiUrl}/pokemon?limit=20`), }; return ApiService.request(asyncAction); }; export const getPokemon = (name: string) => { const loadStart = createAction(PokemonActions.POKEMON_LOADING); const loadSuccess = (pokemon) => createAction(PokemonActions.POKEMIN_LOADED, { pokemon, }); const loadError = createAction(PokemonActions.POKEMON_LOAD_ERROR); const asyncAction = { actions: [loadStart, loadSuccess, loadError], apiCall: () => fetch(`${apiUrl}/pokemon/${name}`), }; return ApiService.request(asyncAction); }; export const getPokemonAbility = (abilityName: string) => { const loadStart = createAction(PokemonAbilityActions.ABILITY_LOADING); const loadSuccess = (ability) => createAction(PokemonAbilityActions.ABILITY_LOADED, { ability, }); const loadError = createAction(PokemonAbilityActions.ABILITY_LOAD_ERROR); const asyncAction = { actions: [loadStart, loadSuccess, loadError], apiCall: () => fetch(`${apiUrl}/ability/${abilityName}`), }; return ApiService.request(asyncAction); }; export const searchPokemons = (value: string) => createAction(PokemonsListActions.SEARCH_POKEMONS, { value });
import React from "react"; import Typed from "typed.js"; export function TypedTextPrompt({ text }) { // Create reference to store the DOM element containing the animation const el = React.useRef(null); React.useEffect(() => { const typed = new Typed(el.current, { strings: [text], typeSpeed: 50, startDelay: 600, }); return () => { // Destroy Typed instance during cleanup to stop animation typed.destroy(); }; }, []); return ( <span className="typed-text-prompt"> <span className="prompt">$ </span> <span className="inline-block min-w-[21px] accent-text-gradient"> <span className="typed-text" ref={el} /> </span> </span> ); }
<p align="center"> <img src="./docs/he-full-2000x564.png" width="100%" alt="react-json-editor"><br /> <img src="./docs/title-react-700x76.png" width="350px" alt="react-json-editor"> </p> > Simple and extensible React component capable of using JSON Schema to declaratively build and customize user forms. <p align="center"> <a href="https://sagold.github.io/json-editor/">demo</a> | <a href="#overview">overview</a> | <a href="#widgets">widgets</a> | <a href="#validators">validators</a> | <a href="#plugins">plugins</a> | <a href="#advanced">advanced</a> </p> install `yarn add @sagold/react-json-editor` [![Npm package version](https://badgen.net/npm/v/@sagold/react-json-editor)](https://github.com/sagold/json-editor/tree/main/packages/react-json-editor) ![Types](https://badgen.net/npm/types/@sagold/react-json-editor) ```tsx import { JsonForm } from '@sagold/react-json-editor'; import { widgets } from '@sagold/rje-widgets'; import '@sagold/rje-widgets/rje-widgets.css'; import '@sagold/react-json-editor/react-json-editor.css'; function MyForm({ schema, data }) { return ( <JsonForm widgets={widgets} schema={schema} data={data} onChange={(data) => { console.log('data', data); }} /> ); } ``` **JsonForm Props** the only required property is a valid json-schema passed to `schema`. | Name | Type | Description | | :--------- | :------------------------- | :------------------------------------------------- | ------------------------------------------------- | | cacheKey | number | string | optionally change key to completely recreate form | | data | any | initial data matching json schema | | draft | DraftConfig | json schema draft config (json-schema-library) | | liveUpdate | boolean | omit changes for each keystroke instead of on blur | | onChange | (data, node) => void | change listener for data updates | | options | extends DefaultNodeOptions | options to override for root widget | | plugins | Plugin[] | list of plugins for json editor | | pointer | string | json-pointer to root node. Defaults to root ('#') | | ref | React.Ref<JsonEditor> | get instance of json editor after first render | | schema | JsonSchema | json schema describing data | | validate | boolean | set to true to validate and show errors on create | | widgets | WidgetPlugin[] | list of widgets used to create user form | # overview > react implementation of [headless-json-editor](../headless-json-editor) using [semantic-ui](https://semantic-ui.com/) ## widgets <p align="left"> <a href="#widget-options">widget options</a> | <a href="#widget-registry">widget registry</a> | <a href="#default-widgets">default widgets</a> | <a href="#custom-widgets">custom widgets</a> </p> A user form built with json-editor solely consists of a tree of widgets. Each widget is responsible to render a part of a json-schema. In many cases a sub schema is completely rendered by a widget, in others they render other widgets (an object rendering properties) and sometimes a widget is used to wrap another widget (seen in oneOfSelectWidget). So any point in data can be customized with a specific widget, improving usability, adding json-schema features or adding a fitting preview of the value, e.g. showing a url as image. ### widget options > For individual widget options please refer to the [storybook widget section](https://sagold.github.io/json-editor/?path=/story/widget-arraywidget--default-widget) Each widget registers to a sub schema on which an `options` object can be passed directly to a widget instance. e.g. ```json { "type": "string", "options": { "title": "Unique Id", "disabled": true } } ``` What follows are options that are supported by each [default widget](#default-widgets) and should be supported by a [custom widget](#custom-widgets): ```ts type DefaultNodeOptions = { /** * Pass in a list of _css classes_ that should be added on the root * element of this widget. Use this to easily identify or style a specific * widget instance. */ classNames?: string[]; /** * description of this data point, overwrites description on sub schema */ description?: string; /** * If the form at this data point should be disabled. * Defaults to `false`. */ disabled?: boolean; /** * Set to `true` if this form should be hidden from rendering. Usually * helpful to hide static variables. * Defaults to `false`. */ hidden: boolean; /** * title of this data point, overwrites title on this sub schema */ title?: string; /** * If set to false, will not render a title for this widget. * Defaults to `true` */ showTitle: boolean; /** * If set to false, will not render a description for this widget. * Defaults to `true` */ showDescription: boolean; }; ``` In addition, each widget exposes its own options. For more details refer to the [storybook widget section](https://sagold.github.io/json-editor/?path=/story/widget-arraywidget--default-widget) _Options passed through component_ Note that when rendering a widget using the _widget_ decorator, options can be overriden within the rendering cycle. This, it is recommended to access the iptions from props, not from node.options. ### widget registry \*list of widgets that test a schema\*\* json-editor works on a list of widgets that are used to render each json sub-schema. Thus, to fully support a user form for any json-schema we will need to have a widget for any of those types, be it for a simple string `{ "type": "string" }` or a complex object `{ "type": "object", "properties": { ... } }`. You can also have specialized widgets for compound sub schemas, e.g. an array of strings `{ "type": "array", "items": { "type": "string" }}`. To make this work, json-editor scans the list until of widgets until one widgets registers for the given schema. **return first matching schema** With this, very general widgets (string, number, etc) are on the bottom of this list, specialized schemas (image, coordinates, etc) are on top. The first widget returning `true` on `widget.use` will be instantiated with the corresponding schema. Note that, very specialized schemas can encompass multiple subschemas and generic schemas only describe the object or array but pass actual children back to the list of widgets for rendering. **can modify test of a widget** json-editor comes with a set of widgets exposed as _defaultWidgets_. These can completely build a user form for any possible json-data. In addtion, some more specialized widgets are exposed and some complex widgets can be added to this list. Just remember that the order is important: first to test `true` will be used to render the user form. **can modify list of widgets** Assembling the list of widgets on your own, you can select the widgets available, the order they should be taken and also modify the actual test-function for when to use a widget: ### default widgets `react-json-editor` comes with a list of default widgets that cover inputs for all possible json-data as well as catching possible data errors and rendering to them into the form. Note that in some cases a specialized widget is required for a better user experience. For this you can add a any editor into the list of default widgets or replace them completely with your own widgets. The `Jsonform` component add the defaultWidgets per default. If you are using `useJsonEditor` hook you have to pass the defaultWidgets on your own, e.g. ```tsx import { defaultWidgets, useJsonEditor, Widget } from '@sagold/react-json-editor'; function Myform() { const [rootNode, editor] = useJsonEditor({ schema, widgets: defaultWidgets }); return ( <Form error> <Widget node={rootNode} editor={editor} /> </Form> ); } ``` ### custom widgets You can create a custom widget for any input data and add a specific function to register for a specific json-schema. **create your widget** ```tsx import { widget, WidgetPlugin } from '@sagold/react-json-editor'; const MyStringWidget = widget<StringNode, string>(({ node, options, setValue }) => ( <input type="text" defaultValue={node.value} disabled={options.disabled === true} onChange={(e) => { setValue(e.target.value); }}> )); ``` In order to register the widget in `react-json-editor` and hook into specific json-schema a plugin wrapper is required **create a plugin wrapper for your widget** ```tsx export const MyStringWidgetPlugin = { // a unique id is required for each widget plugin id: 'my-widget-plugin', // return true to register to this node/schema use: (node, options) => node.schema.type === 'string', // expose the widget to be rendered with this node Widget: MyStringWidget }; ``` For more details check [any default widget](https://github.com/sagold/json-editor/tree/main/packages/react-json-editor/src/lib/widgets) or take a look at the additional widget packages like [rje-code-widgets](https://github.com/sagold/json-editor/tree/main/packages/rje-code-widgets) ## validation > - schema validations > - custom validators ## plugins ### adding plugins ```tsx import { Jsonform } from '@sagold/react-json-editor'; import { EventLoggerPlugin } from 'headless-json-editor'; function Myform() { return <JsonForm plugins={[EventLoggerPlugin]} />; } ``` ### existing plugins #### `EventLoggerPlugin` #### `HistoryPlugin` ```tsx import { Jsonform, JsonEditor } from '@sagold/react-json-editor'; import { HistoryPlugin } from 'headless-json-editor'; import { useState } from 'react'; function Myform() { const [editor, setEditor] = useState<JsonEditor>(); if (editor) { const history = editor.plugin('history'); console.log('undo count', history?.getUndoCount()); } <JsonForm editor={setEditor} plugins={[HistoryPlugin]} />; } ``` #### `OnChangePlugin` ### create custom plugin ```ts export type Plugin = (he: HeadlessJsonEditor, options: HeadlessJsonEditorOptions) => PluginInstance | undefined; export type PluginObserver = (root: Node, event: PluginEvent) => void | [Node, Change[]]; export interface PluginInstance { id: string; onEvent: PluginObserver; [p: string]: unknown; } ``` ## advanced ### `useJsonEditor` hook For more control you can create a json-editor using the `useJsonEditor` hook: ```tsx import { Form } from 'semantic-ui-react'; import { useJsonEditor } from '@sagold/react-json-editor'; function MyForm({ schema, data }) { const [node, jsonEditor] = useJsonEditor({ schema, data, onChange: (data, state) => { console.log('data', data, 'root', state); } }); const Widget = jsonEditor.getWidget(node); return ( <Form error> <Widget node={node} editor={jsonEditor} /> </Form> ); } ```
<?php namespace Database\Seeders; use App\Models\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Hash; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { User::create([ 'full_name' => 'Admin', 'email' => '[email protected]', 'role' => 'Pelatih', 'password' => Hash::make('[email protected]'), ]); $this->call([ CriteriaSeeder::class, ]); if (env('WITH_FAKER')) { $this->call([ CoachSeeder::class, AthleteSeeder::class, ExerciseSeeder::class, ExerciseEvaluationSeeder::class, TournamentSeeder::class, HistorySeeder::class, ]); } } }
import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useParams } from "react-router-dom"; import { Dialog, DialogHeader, DialogBody, IconButton, } from "@material-tailwind/react"; import { XMarkIcon } from "@heroicons/react/24/solid"; import EditProfileForm from "../../pages/profile/components/edit-profile-form"; import userService from "../../services/user-service"; import { selectEditMyProfileModal, setEditMyProfileModalOpen, } from "../../redux/features/edit-my-profile-modal-slice"; const EditMyProfileModal = () => { const { username } = useParams(); const { editMyProfileModalOpen } = useSelector(selectEditMyProfileModal); const [userProfile, setUserProfile] = useState(); const dispatch = useDispatch(); useEffect(() => { const getUser = async () => { if (username) { const { response } = await userService.getUser({ username, }); if (response) { setUserProfile(response.data.result); } } }; getUser(); }, [username, dispatch]); const handleClose = () => dispatch(setEditMyProfileModalOpen(false)); return ( <> <Dialog size="md" open={editMyProfileModalOpen} handler={() => {}} animate={{ mount: { scale: 1, y: 0 }, unmount: { scale: 0.9, y: -100 }, }} className="dark:bg-gray-800" > <DialogHeader className="flex items-center justify-between dark:text-gray-300"> Edit Profile <IconButton variant="text" color="red" onClick={handleClose} className="rounded-full" > <XMarkIcon className="w-8 h-8" /> </IconButton> </DialogHeader> <DialogBody className="p-0 border-t dark:border-gray-300"> {userProfile ? <EditProfileForm user={userProfile} /> : <></>} </DialogBody> </Dialog> </> ); }; export default EditMyProfileModal;
<?php /** * Portfolio Meta Box Options * @param array $args * @return array * @since 1.0.7 */ function themify_theme_portfolio_meta_box( $args = array() ) { extract( $args ); return array( // Content Width array( 'name'=> 'content_width', 'title' => __('Content Width', 'themify'), 'description' => '', 'type' => 'layout', 'show_title' => true, 'meta' => array( array( 'value' => 'default_width', 'img' => 'themify/img/default.png', 'selected' => true, 'title' => __( 'Default', 'themify' ) ), array( 'value' => 'full_width', 'img' => 'themify/img/fullwidth.png', 'title' => __( 'Fullwidth', 'themify' ) ) ) ), // Post Image array( 'name' => 'post_image', 'title' => __('Featured Image', 'themify'), 'description' => '', 'type' => 'image', 'meta' => array() ), // Gallery Shortcode array( 'name' => 'gallery_shortcode', 'title' => __('Slider Gallery', 'themify'), 'description' => '', 'type' => 'gallery_shortcode' ), // Media Type array( 'name' => 'media_type', 'title' => __('Show Media', 'themify'), 'description' => __('Show whether the featured image or gallery slider on the index view.', 'themify'), 'type' => 'dropdown', 'meta' => array( array( 'value' => 'slider', 'name' => __('Slider', 'themify'), 'selected' => true ), array( 'value' => 'image', 'name' => __('Image', 'themify') ) ) ), // Featured Image Size array( 'name' => 'feature_size', 'title' => __('Image Size', 'themify'), 'description' => sprintf(__('Image sizes can be set at <a href="%s">Media Settings</a> and <a href="%s" target="_blank">Regenerated</a>', 'themify'), 'options-media.php', 'https://wordpress.org/plugins/regenerate-thumbnails/'), 'type' => 'featimgdropdown', 'display_callback' => 'themify_is_image_script_disabled' ), // Multi field: Image Dimension themify_image_dimensions_field(), // Hide Title array( "name" => "hide_post_title", "title" => __('Hide Post Title', 'themify'), "description" => '', "type" => 'dropdown', "meta" => array( array("value" => "default", "name" => "", "selected" => true), array("value" => "yes", 'name' => __('Yes', 'themify')), array("value" => "no", 'name' => __('No', 'themify')) ) ), // Unlink Post Title array( "name" => "unlink_post_title", "title" => __('Unlink Post Title', 'themify'), "description" => __('Unlink post title (it will display the post title without link)', 'themify'), "type" => "dropdown", "meta" => array( array("value" => "default", "name" => "", "selected" => true), array("value" => "yes", 'name' => __('Yes', 'themify')), array("value" => "no", 'name' => __('No', 'themify')) ) ), // Hide Post Date array( "name" => "hide_post_date", "title" => __('Hide Post Date', 'themify'), "description" => "", "type" => "dropdown", "meta" => array( array("value" => "default", "name" => "", "selected" => true), array("value" => "yes", 'name' => __('Yes', 'themify')), array("value" => "no", 'name' => __('No', 'themify')) ) ), // Hide Post Meta array( "name" => "hide_post_meta", "title" => __('Hide Post Meta', 'themify'), "description" => "", "type" => "dropdown", "meta" => array( array("value" => "default", "name" => "", "selected" => true), array("value" => "yes", 'name' => __('Yes', 'themify')), array("value" => "no", 'name' => __('No', 'themify')) ) ), // Hide Post Image array( "name" => "hide_post_image", "title" => __('Hide Featured Image', 'themify'), "description" => "", "type" => "dropdown", "meta" => array( array("value" => "default", "name" => "", "selected" => true), array("value" => "yes", 'name' => __('Yes', 'themify')), array("value" => "no", 'name' => __('No', 'themify')) ) ), // Unlink Post Image array( "name" => "unlink_post_image", "title" => __('Unlink Featured Image', 'themify'), "description" => __('Display the Featured Image without link', 'themify'), "type" => "dropdown", "meta" => array( array("value" => "default", "name" => "", "selected" => true), array("value" => "yes", 'name' => __('Yes', 'themify')), array("value" => "no", 'name' => __('No', 'themify')) ) ), // External Link array( 'name' => 'external_link', 'title' => __('External Link', 'themify'), 'description' => __('Link Featured Image and Post Title to external URL', 'themify'), 'type' => 'textbox', 'meta' => array() ), // Lightbox Link themify_lightbox_link_field(), ); } /************************************************************************************************** * Portfolio Class - Shortcode **************************************************************************************************/ if ( ! class_exists( 'Themify_Portfolio' ) ) { class Themify_Portfolio { var $instance = 0; var $atts = array(); var $post_type = 'portfolio'; var $tax = 'portfolio-category'; var $taxonomies; function __construct( $args = array() ) { $this->atts = array( 'id' => '', 'title' => '', 'unlink_title' => '', 'image' => 'yes', // no 'image_w' => 221, 'image_h' => 221, 'display' => 'none', // excerpt, content 'post_meta' => '', // yes 'post_date' => '', // yes 'more_link' => false, // true goes to post type archive, and admits custom link 'more_text' => __('More &rarr;', 'themify'), 'limit' => 4, 'category' => 'all', // integer category ID 'order' => 'DESC', // ASC 'orderby' => 'date', // title, rand 'style' => '', // grid4, grid3, grid2 'sorting' => 'no', // yes 'paged' => '0', // internal use for pagination, dev: previously was 1 'use_original_dimensions' => 'no' // yes ); add_shortcode( $this->post_type, array( $this, 'init_shortcode' ) ); add_shortcode( 'themify_'.$this->post_type.'_posts', array( $this, 'init_shortcode' ) ); add_action( 'save_post', array($this, 'set_default_term'), 100, 2 ); add_filter( "builder_is_{$this->post_type}_active", '__return_true' ); } /** * Set default term for custom taxonomy and assign to post * @param number * @param object */ function set_default_term( $post_id, $post ) { if ( 'publish' === $post->post_status ) { $terms = wp_get_post_terms( $post_id, $this->tax ); if ( empty( $terms ) ) { wp_set_object_terms( $post_id, __( 'Uncategorized', 'themify' ), $this->tax ); } } } /** * Includes new post types registered in theme to array of post types managed by Themify * @param array * @return array */ function extend_post_types( $types ) { return array_merge( $types, array( $this->post_type ) ); } /** * Add shortcode to WP * @param $atts Array shortcode attributes * @return String * @since 1.0.0 */ function init_shortcode( $atts ) { $this->instance++; return do_shortcode( $this->shortcode( shortcode_atts( $this->atts, $atts ), $this->post_type ) ); } /** * Parses the arguments given as category to see if they are category IDs or slugs and returns a proper tax_query * @param $category * @param $post_type * @return array */ function parse_category_args( $category, $post_type ) { if ( 'all' != $category ) { $tax_query_terms = explode(',', $category); if ( preg_match( '#[a-z]#', $category ) ) { return array( array( 'taxonomy' => $post_type . '-category', 'field' => 'slug', 'terms' => $tax_query_terms ) ); } else { return array( array( 'taxonomy' => $post_type . '-category', 'field' => 'id', 'terms' => $tax_query_terms ) ); } } } /** * Returns link wrapped in paragraph either to the post type archive page or a custom location * @param bool|string $more_link False does nothing, true goes to archive page, custom string sets custom location * @param string $more_text * @param string $post_type * @return string */ function section_link( $more_link = false, $more_text, $post_type ) { if ( $more_link ) { if ( 'true' == $more_link ) { $more_link = get_post_type_archive_link( $post_type ); } return '<p class="more-link-wrap"><a href="' . esc_url( $more_link ) . '" class="more-link">' . $more_text . '</a></p>'; } return ''; } /** * Returns class to add in columns when querying multiple entries * @param string $style Entries layout * @return string $col_class CSS class for column */ function column_class( $style ) { $col_class = ''; switch ( $style ) { case 'grid4': $col_class = 'col4-1'; break; case 'grid3': $col_class = 'col3-1'; break; case 'grid2': $col_class = 'col2-1'; break; default: $col_class = ''; break; } return $col_class; } /** * Main shortcode rendering * @param array $atts * @param $post_type * @return string|void */ function shortcode($atts = array(), $post_type){ extract($atts); // Pagination global $paged; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // Parameters to get posts $args = array( 'post_type' => $post_type, 'posts_per_page' => $limit, 'order' => $order, 'orderby' => $orderby, 'suppress_filters' => false, 'paged' => $paged ); // Category parameters $args['tax_query'] = $this->parse_category_args($category, $post_type); // Defines layout type $cpt_layout_class = $this->post_type.'-multiple clearfix type-multiple'; $multiple = true; // Single post type or many single post types if( '' != $id ){ if(strpos($id, ',')){ $ids = explode(',', str_replace(' ', '', $id)); foreach ($ids as $string_id) { $int_ids[] = intval($string_id); } $args['post__in'] = $int_ids; $args['orderby'] = 'post__in'; } else { $args['p'] = intval($id); $cpt_layout_class = $this->post_type.'-single'; $multiple = false; } } // Get posts according to parameters $portfolio_query = new WP_Query(); $posts = $portfolio_query->query(apply_filters('themify_'.$post_type.'_shortcode_args', $args)); // Grid Style if( '' == $style ){ $style = themify_check('setting-default_portfolio_index_post_layout')? themify_get('setting-default_portfolio_index_post_layout'): 'grid4'; } if( is_singular('portfolio') ){ if( '' == $image_w ){ $image_w = themify_check('setting-default_portfolio_single_image_post_width')? themify_get('setting-default_portfolio_single_image_post_width'): '670'; } if( '' == $image_h ){ $image_h = themify_check('setting-default_portfolio_single_image_post_height')? themify_get('setting-default_portfolio_single_image_post_height'): '0'; } if( '' == $post_date ){ $post_date = themify_check('setting-default_portfolio_single_post_date')? themify_get('setting-default_portfolio_index_post_date'): 'yes'; } if( '' == $title ){ $title = themify_check('setting-default_portfolio_single_title')? themify_get('setting-default_portfolio_single_title'): 'yes'; } if( '' == $unlink_title ){ $unlink_title = themify_check('setting-default_portfolio_single_unlink_post_title')? themify_get('setting-default_portfolio_single_unlink_post_title'): 'no'; } if( '' == $post_meta ){ $post_meta = themify_check('setting-default_portfolio_single_meta')? themify_get('setting-default_portfolio_single_meta'): 'yes'; } } else { if( '' == $image_w ){ $image_w = themify_check('setting-default_portfolio_index_image_post_width')? themify_get('setting-default_portfolio_index_image_post_width'): '221'; } if( '' == $image_h ){ $image_h = themify_check('setting-default_portfolio_index_image_post_height')? themify_get('setting-default_portfolio_index_image_post_height'): '221'; } if( '' == $title ){ $title = themify_check('setting-default_portfolio_index_title')? themify_get('setting-default_portfolio_index_title'): 'yes'; } if( '' == $unlink_title ){ $unlink_title = themify_check('setting-default_portfolio_index_unlink_post_title')? themify_get('setting-default_portfolio_index_unlink_post_title'): 'no'; } // Reverse logic if( '' == $post_date ){ $post_date = themify_check('setting-default_portfolio_index_post_date')? 'no' == themify_get('setting-default_portfolio_index_post_date')? 'yes' : 'no': 'no'; } if( '' == $post_meta ){ $post_meta = themify_check('setting-default_portfolio_index_post_meta_category')? 'no' == themify_get('setting-default_portfolio_index_post_meta_category')? 'yes' : 'no' : 'no'; } } // Collect markup to be returned $out = ''; if( $posts ) { global $themify; $themify_save = clone $themify; // save a copy // override $themify object $themify->hide_title = 'yes' == $title? 'no': 'yes'; $themify->unlink_title = ( '' == $unlink_title || 'no' == $unlink_title )? 'no' : 'yes'; $themify->hide_image = 'yes' == $image? 'no': 'yes'; $themify->hide_meta = 'yes' == $post_meta? 'no': 'yes'; $themify->hide_date = 'yes' == $post_date? 'no': 'yes'; if(!$multiple) { if( '' == $image_w || get_post_meta($args['p'], 'image_width', true ) ){ $themify->width = get_post_meta($args['p'], 'image_width', true ); } if( '' == $image_h || get_post_meta($args['p'], 'image_height', true ) ){ $themify->height = get_post_meta($args['p'], 'image_height', true ); } } else { $themify->width = $image_w; $themify->height = $image_h; } $themify->use_original_dimensions = 'yes' == $use_original_dimensions? 'yes': 'no'; $themify->display_content = $display; $themify->more_link = $more_link; $themify->more_text = $more_text; $themify->post_layout = $style; $themify->portfolio_instance = $this->instance; $out .= '<div class="loops-wrapper shortcode ' . $post_type . ' ' . $style . ' '. $cpt_layout_class .'">'; $out .= themify_get_shortcode_template($posts, 'includes/loop-portfolio', 'index'); $out .= $this->section_link($more_link, $more_text, $post_type); $out .= '</div>'; $themify = clone $themify_save; // revert to original $themify state } wp_reset_postdata(); return $out; } } } if ( ! function_exists( 'themify_theme_portfolio_image' ) ) { /** * Returns the image for the portfolio slider * @param int $attachment_id Image attachment ID * @param int $width Width of the returned image * @param int $height Height of the returned image * @param string $size Size of the returned image * @return string * @since 1.0.0 */ function themify_theme_portfolio_image($attachment_id, $width, $height, $size = 'large') { $size = apply_filters( 'themify_portfolio_image_size', $size ); if ( themify_check( 'setting-img_settings_use' ) ) { // Image Script is disabled, use WP image $html = wp_get_attachment_image( $attachment_id, $size ); } else { // Image Script is enabled, use it to process image $img = wp_get_attachment_image_src($attachment_id, $size); $html = themify_get_image('ignore=true&src='.$img[0].'&w='.$width.'&h='.$height); } return apply_filters( 'themify_portfolio_image_html', $html, $attachment_id, $width, $height, $size ); } } /************************************************************************************************** * Initialize Type Class **************************************************************************************************/ new Themify_Portfolio(); /************************************************************************************************** * Themify Theme Settings Module **************************************************************************************************/ if ( ! function_exists( 'themify_default_portfolio_single_layout' ) ) { /** * Default Single Portfolio Layout * @param array $data * @return string */ function themify_default_portfolio_single_layout( $data=array() ) { /** * Associative array containing theme settings * @var array */ $data = themify_get_data(); /** * Variable prefix key * @var string */ $prefix = 'setting-default_portfolio_single_'; /** * Basic default options '', 'yes', 'no' * @var array */ $default_options = array( array('name'=>'','value'=>''), array('name'=>__('Yes', 'themify'),'value'=>'yes'), array('name'=>__('No', 'themify'),'value'=>'no') ); /** * HTML for settings panel * @var string */ $output = '<p> <span class="label">' . __('Hide Portfolio Title', 'themify') . '</span> <select name="'.$prefix.'title">' . themify_options_module($default_options, $prefix.'title') . ' </select> </p>'; $output .= '<p> <span class="label">' . __('Unlink Portfolio Title', 'themify') . '</span> <select name="'.$prefix.'unlink_post_title">' . themify_options_module($default_options, $prefix.'unlink_post_title') . ' </select> </p>'; $output .= '<p> <span class="label">' . __('Hide Portfolio Meta', 'themify') . '</span> <select name="'.$prefix.'post_meta_category">' . themify_options_module($default_options, $prefix.'post_meta_category', true, 'yes') . ' </select> </p>'; $output .= '<p> <span class="label">' . __('Hide Portfolio Date', 'themify') . '</span> <select name="'.$prefix.'post_date">' . themify_options_module($default_options, $prefix.'post_date') . ' </select> </p>'; /** * Image Dimensions */ $output .= ' <p> <span class="label">' . __('Image Size', 'themify') . '</span> <input type="text" class="width2" name="'.$prefix.'image_post_width" value="'.$data[$prefix.'image_post_width'].'" /> ' . __('width', 'themify') . ' <small>(px)</small> <input type="text" class="width2" name="'.$prefix.'image_post_height" value="'.$data[$prefix.'image_post_height'].'" /> ' . __('height', 'themify') . ' <small>(px)</small> </p>'; // Portfolio Navigation $prefix = 'setting-portfolio_nav_'; $output .= ' <p> <span class="label">' . __('Portfolio Navigation', 'themify') . '</span> <label for="'. $prefix .'disable"> <input type="checkbox" id="'. $prefix .'disable" name="'. $prefix .'disable" '. checked( themify_get( $prefix.'disable' ), 'on', false ) .'/> ' . __('Remove Portfolio Navigation', 'themify') . ' </label> <span class="pushlabel vertical-grouped"> <label for="'. $prefix .'same_cat"> <input type="checkbox" id="'. $prefix .'same_cat" name="'. $prefix .'same_cat" '. checked( themify_get( $prefix. 'same_cat' ), 'on', false ) .'/> ' . __('Show only portfolios in the same category', 'themify') . ' </label> </span> </p>'; return $output; } } if ( ! function_exists( 'themify_default_portfolio_index_layout' ) ) { /** * Default Archive Portfolio Layout * @param array $data * @return string */ function themify_default_portfolio_index_layout( $data=array() ) { /** * Associative array containing theme settings * @var array */ $data = themify_get_data(); /** * Variable prefix key * @var string */ $prefix = 'setting-default_portfolio_index_'; /** * Basic default options '', 'yes', 'no' * @var array */ $default_options = array( array('name'=>'','value'=>''), array('name'=>__('Yes', 'themify'),'value'=>'yes'), array('name'=>__('No', 'themify'),'value'=>'no') ); /** * Sidebar Layout * @var string */ $layout = isset( $data[$prefix.'layout'] ) ? $data[$prefix.'layout'] : ''; /** * Sidebar Layout Options * @var array */ $sidebar_options = array( array('value' => 'sidebar1', 'img' => 'images/layout-icons/sidebar1.png', 'title' => __('Sidebar Right', 'themify')), array('value' => 'sidebar1 sidebar-left', 'img' => 'images/layout-icons/sidebar1-left.png', 'title' => __('Sidebar Left', 'themify')), array('value' => 'sidebar-none', 'img' => 'images/layout-icons/sidebar-none.png', 'selected' => true, 'title' => __('No Sidebar', 'themify')), ); /** * Post Layout Options * @var array */ $post_layout_options = array( array('value' => 'list-post', 'img' => 'images/layout-icons/list-post.png', 'title' => __('List Post', 'themify')), array('value' => 'grid4', 'img' => 'images/layout-icons/grid4.png', 'title' => __('Grid 4', 'themify')), array('value' => 'grid3', 'img' => 'images/layout-icons/grid3.png', 'title' => __('Grid 3', 'themify')), array('value' => 'grid2', 'img' => 'images/layout-icons/grid2.png', 'title' => __('Grid 2', 'themify')) ); /** * HTML for settings panel * @var string */ $output = '<p> <span class="label">' . __('Portfolio Sidebar Option', 'themify') . '</span>'; foreach($sidebar_options as $option){ if ( ( '' == $layout || !$layout || ! isset( $layout ) ) && ( isset( $option['selected'] ) && $option['selected'] ) ) { $layout = $option['value']; } if($layout == $option['value']){ $class = 'selected'; } else { $class = ''; } $output .= '<a href="#" class="preview-icon '.$class.'" title="'.$option['title'].'"><img src="'.THEME_URI.'/'.$option['img'].'" alt="'.$option['value'].'" /></a>'; } $output .= '<input type="hidden" name="'.$prefix.'layout" class="val" value="'.$layout.'" />'; $output .= '</p>'; /** * Post Layout */ $output .= '<p> <span class="label">' . __('Portfolio Layout', 'themify') . '</span>'; $val = isset( $data[$prefix.'post_layout'] ) ? $data[$prefix.'post_layout'] : ''; foreach($post_layout_options as $option){ if ( ( '' == $val || ! $val || ! isset( $val ) ) && ( isset( $option['selected'] ) && $option['selected'] ) ) { $val = $option['value']; } if ( $val == $option['value'] ) { $class = "selected"; } else { $class = ""; } $output .= '<a href="#" class="preview-icon '.$class.'" title="'.$option['title'].'"><img src="'.THEME_URI.'/'.$option['img'].'" alt="'.$option['value'].'" /></a>'; } $output .= ' <input type="hidden" name="'.$prefix.'post_layout" class="val" value="'.$val.'" /> </p>'; /** * Display Content */ $output .= '<p> <span class="label">' . __('Display Content', 'themify') . '</span> <select name="'.$prefix.'display">'. themify_options_module(array( array('name' => __('None', 'themify'),'value'=>'none'), array('name' => __('Full Content', 'themify'),'value'=>'content'), array('name' => __('Excerpt', 'themify'),'value'=>'excerpt') ), $prefix.'display').' </select> </p>'; $output .= '<p> <span class="label">' . __('Hide Portfolio Title', 'themify') . '</span> <select name="'.$prefix.'title">' . themify_options_module($default_options, $prefix.'title') . ' </select> </p>'; $output .= '<p> <span class="label">' . __('Unlink Portfolio Title', 'themify') . '</span> <select name="'.$prefix.'unlink_post_title">' . themify_options_module($default_options, $prefix.'unlink_post_title') . ' </select> </p>'; $output .= '<p> <span class="label">' . __('Hide Portfolio Meta', 'themify') . '</span> <select name="'.$prefix.'post_meta_category">' . themify_options_module($default_options, $prefix.'post_meta_category', true, 'yes') . ' </select> </p>'; $output .= '<p> <span class="label">' . __('Hide Portfolio Date', 'themify') . '</span> <select name="'.$prefix.'post_date">' . themify_options_module($default_options, $prefix.'post_date', true, 'yes') . ' </select> </p>'; /** * Image Dimensions */ $output .= '<p> <span class="label">' . __('Image Size', 'themify') . '</span> <input type="text" class="width2" name="'.$prefix.'image_post_width" value="'.$data[$prefix.'image_post_width'].'" /> ' . __('width', 'themify') . ' <small>(px)</small> <input type="text" class="width2" name="'.$prefix.'image_post_height" value="'.$data[$prefix.'image_post_height'].'" /> ' . __('height', 'themify') . ' <small>(px)</small> </p>'; return $output; } } if ( ! function_exists( 'themify_portfolio_slug' ) ) { /** * Portfolio Slug * @param array $data * @return string */ function themify_portfolio_slug($data=array()){ $data = themify_get_data(); $portfolio_slug = isset($data['themify_portfolio_slug'])? $data['themify_portfolio_slug']: apply_filters('themify_portfolio_rewrite', 'project'); return ' <p> <span class="label">' . __('Portfolio Base Slug', 'themify') . '</span> <input type="text" name="themify_portfolio_slug" value="'.$portfolio_slug.'" class="slug-rewrite"> <br /> <span class="pushlabel"><small>' . __('Use only lowercase letters, numbers, underscores and dashes.', 'themify') . '</small></span> <br /> <span class="pushlabel"><small>' . sprintf(__('After changing this, go to <a href="%s">permalinks</a> and click "Save changes" to refresh them.', 'themify'), admin_url('options-permalink.php')) . '</small></span><br /> </p>'; } } /** * Creates portfolio slider module * @return string */ function themify_portfolio_slider() { return themify_generic_slider_controls('setting-portfolio_slider_'); } /************************************************************************************************** * Body Classes for Portfolio index and single **************************************************************************************************/ /** * Changes condition to filter post layout class * @param $condition * @return bool */ function themify_portfolio_post_layout_condition($condition) { return $condition || is_tax('portfolio-category'); } /** * Returns modified post layout class * @return string */ function themify_portfolio_post_layout() { global $themify; // get default layout $class = $themify->post_layout; if('portfolio' == $themify->query_post_type) { $class = themify_check('portfolio_layout') ? themify_get('portfolio_layout') : themify_get('setting-default_post_layout'); } elseif (is_tax('portfolio-category')) { $class = themify_check('setting-default_portfolio_index_post_layout')? themify_get('setting-default_portfolio_index_post_layout') : 'list-post'; } return $class; } /** * Changes condition to filter sidebar layout class * @param bool $condition * @return bool */ function themify_portfolio_layout_condition($condition) { global $themify; // if layout is not set or is the home page and front page displays is set to latest posts return $condition || (is_home() && 'posts' == get_option('show_on_front')) || '' != $themify->query_category || is_tax('portfolio-category') || is_singular('portfolio'); } /** * Returns modified sidebar layout class * @param string $class Original body class * @return string */ function themify_portfolio_layout($class) { global $themify; // get default layout $class = $themify->layout; if (is_tax('portfolio-category')) { $class = themify_check('setting-default_portfolio_index_layout')? themify_get('setting-default_portfolio_index_layout') : 'sidebar-none'; } return $class; } add_filter('themify_default_post_layout_condition', 'themify_portfolio_post_layout_condition', 12); add_filter('themify_default_post_layout', 'themify_portfolio_post_layout', 12); add_filter('themify_default_layout_condition', 'themify_portfolio_layout_condition', 12); add_filter('themify_default_layout', 'themify_portfolio_layout', 12);
package br.ba.carlosrogerio.siscobrapi4.util; import java.util.Properties; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import br.ba.carlosrogerio.siscobrapi4.model.Usuario; import br.ba.carlosrogerio.siscobrapi4.model.Pessoa; import br.ba.carlosrogerio.siscobrapi4.model.Divida; import br.ba.carlosrogerio.siscobrapi4.model.Pagamento; public class HibernateUtil { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { Configuration configuration = new Configuration(); // Hibernate settings equivalent to hibernate.cfg.xml's properties Properties settings = new Properties(); settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver"); settings.put(Environment.URL, "jdbc:mysql://localhost:3306/siscobdb?useSSL=false&serverTimezone=UTC"); settings.put(Environment.USER, "root"); settings.put(Environment.PASS, ""); settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQLInnoDBDialect"); settings.put(Environment.SHOW_SQL, "true"); settings.put(Environment.FORMAT_SQL, "true"); settings.put(Environment.USE_SQL_COMMENTS, "true"); settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); //settings.put(Environment.HBM2DDL_AUTO, "validate"); configuration.setProperties(settings); configuration.addAnnotatedClass(Usuario.class); configuration.addAnnotatedClass(Pessoa.class); configuration.addAnnotatedClass(Divida.class); configuration.addAnnotatedClass(Pagamento.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); System.out.println("Hibernate Java Config serviceRegistry created"); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Exception e) { e.printStackTrace(); } } return sessionFactory; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no"> <title>Get started with SceneView - Create a 3D map</title> <style> html, body, #viewDiv { padding: 0; margin: 0; height: 100%; width: 100%; } </style> <link rel="stylesheet" href="https://js.arcgis.com/4.1/esri/css/main.css"> <script src="https://js.arcgis.com/4.1/"></script> <script> require([ "esri/Map", "esri/views/SceneView", "esri/layers/FeatureLayer", "esri/widgets/Search", "esri/widgets/Locate", "dojo/domReady!" ], function(Map, SceneView, FeatureLayer, Search, Locate){ var map = new Map({ basemap: "streets", ground: "world-elevation" }); var view = new SceneView({ container: "viewDiv", // Reference to the scene div created in step 5 map: map, // Reference to the map object created before the scene scale: 50000000, // Sets the initial scale to 1:50,000,000 center: [-101.17, 21.78] // Sets the center point of view with lon/lat }); var fl = new FeatureLayer({ url: "http://services7.arcgis.com/cS890GsOFd26sODz/arcgis/rest/services/ProjectD/FeatureServer/0" }); map.add(fl); // adds the layer to the map var searchWidget = new Search({ view: view }); // Adds the search widget below other elements in // the top left corner of the view view.ui.add(searchWidget, { position: "top-left", index: 2 }); // This graphics layer will store the graphic used to display the user's location var gl = new GraphicsLayer(); map.add(gl); var locateWidget = new Locate({ view: view, // Attaches the Locate button to the view graphicsLayer: gl // The layer the locate graphic is assigned to }); // startup() must be called to start the widget locateWidget.startup(); view.ui.add(locateWidget, "top-right"); }); </script> </head> <body> <div id="viewDiv"></div> </body> </html>
import { describe } from "@ardenthq/sdk-test"; import { IoC, Signatories } from "@ardenthq/sdk"; import { identity } from "../test/fixtures/identity"; import { createService } from "../test/mocking"; import { BindingType } from "./constants"; import { AddressService } from "./address.service.js"; import { AddressFactory } from "./address.factory.js"; import { MessageService } from "./message.service.js"; describe("MessageService", async ({ beforeEach, it, assert }) => { beforeEach(async (context) => { context.subject = await createService(MessageService, undefined, (container) => { container.singleton(BindingType.AddressFactory, AddressFactory); container.singleton(IoC.BindingType.AddressService, AddressService); }); }); it("should sign and verify a message", async (context) => { const result = await context.subject.sign({ message: "This is an example of a signed message.", signatory: new Signatories.Signatory( new Signatories.MnemonicSignatory({ signingKey: "5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss", address: identity.address, publicKey: identity.publicKey, privateKey: identity.privateKey, options: { bip44: { account: 0, }, }, }), ), }); assert.true(await context.subject.verify(result)); }); });
import { Form, FormError, FieldError, Label, TextField, NumberField, Submit, } from '@redwoodjs/forms' const SubredditForm = (props) => { const onSubmit = (data) => { props.onSave(data, props?.subreddit?.id) } return ( <div className="rw-form-wrapper"> <Form onSubmit={onSubmit} error={props.error}> <FormError error={props.error} wrapperClassName="rw-form-error-wrapper" titleClassName="rw-form-error-title" listClassName="rw-form-error-list" /> <Label name="title" className="rw-label" errorClassName="rw-label rw-label-error" > Title </Label> <TextField name="title" defaultValue={props.subreddit?.title} className="rw-input" errorClassName="rw-input rw-input-error" validation={{ required: true }} /> <FieldError name="title" className="rw-field-error" /> <Label name="description" className="rw-label" errorClassName="rw-label rw-label-error" > Description </Label> <TextField name="description" defaultValue={props.subreddit?.description} className="rw-input" errorClassName="rw-input rw-input-error" validation={{ required: true }} /> <FieldError name="description" className="rw-field-error" /> <Label name="slug" className="rw-label" errorClassName="rw-label rw-label-error" > Slug </Label> <TextField name="slug" defaultValue={props.subreddit?.slug} className="rw-input" errorClassName="rw-input rw-input-error" validation={{ required: true }} /> <FieldError name="slug" className="rw-field-error" /> <Label name="userId" className="rw-label" errorClassName="rw-label rw-label-error" > User id </Label> <TextField name="userId" defaultValue={props.subreddit?.userId} className="rw-input" errorClassName="rw-input rw-input-error" validation={{ required: true }} /> <FieldError name="userId" className="rw-field-error" /> <Label name="newsletterId" className="rw-label" errorClassName="rw-label rw-label-error" > Newsletter id </Label> <NumberField name="newsletterId" defaultValue={props.subreddit?.newsletterId} className="rw-input" errorClassName="rw-input rw-input-error" validation={{ required: true }} /> <FieldError name="newsletterId" className="rw-field-error" /> <div className="rw-button-group"> <Submit disabled={props.loading} className="rw-button rw-button-blue"> Save </Submit> </div> </Form> </div> ) } export default SubredditForm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modifica</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous"> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <div class="container my-2"> <h1>Modifica prodotto</h1> <div> @if($errors->any()) <ul> @foreach($errors->all() as $error) <li>{{$error}}</li> @endforeach </ul> @endif </div> <div class="container my-1"> <form method="post" action="{{route('update-prodotto',['product' => $product])}}" enctype="multipart/form-data"> @csrf @method('put') <div class="form-group mb-5"> <label for="category_id">Categoria</label> <select class="form-control mb-2" id="category_id" name="category_id"> <option value="">Seleziona una Categoria</option> @foreach($categories as $category) <option value="{{ $category->id }}" {{ $product->category_id == $category->id ? 'selected' : '' }}> {{ $category->nome_categoria }} </option> @endforeach </select> </div> <div class="form-group mb-2"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">@</span> </div> <input type="text" class="form-control" name="nome" placeholder="Nome" aria-label="Username" aria-describedby="basic-addon1" value="{{$product->nome}}"> </div> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">#</span> </div> <input type="text" class="form-control" name="qnt" placeholder="Quantità" aria-label="Quantità" value="{{$product->qnt}}"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">€</span> </div> <input type="text" class="form-control" name="prezzo" placeholder="Prezzo" aria-label="Prezzo" value="{{$product->prezzo}}"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">📝</span> </div> <input type="text" class="form-control" name="descrizione" placeholder="Descrizione" aria-label="Descrizione" value="{{$product->descrizione}}"> </div> <div> <div class="form-group mb-2"> <label for="image">Immagine Attuale:</label> @if($product->image) <div class="mb-3"> <img src="{{ asset('storage/images/' . $product->image) }}" alt="Immagine attuale" style="max-width: 100px;"> </div> @else <p>Nessuna immagine caricata</p> @endif </div> <div class="form-group mb-2"> <label for="newImage">Carica Nuova Immagine:</label> <input type="file" class="form-control" id="newImage" name="image"> </div> <button type="submit" class="btn btn-primary">Update</button> </div> </div> <script src="{{ asset('js/alertHandler.js') }}"></script> </body> </html>
using System.Text; using Microsoft.Extensions.Logging; using ZLogger; namespace Mobsub.SubtitleParse.AssTypes; public class AssData(ILogger? logger = null) { public bool CarriageReturn = false; public Encoding CharEncoding = Utils.EncodingRefOS(); public HashSet<AssSection> Sections = []; public AssScriptInfo ScriptInfo {get; set;} = new AssScriptInfo(logger){}; public AssStyles Styles { get; set; } = new AssStyles(logger) {}; public AssEvents Events {get; set;} = new AssEvents(logger) {}; public Dictionary<string, string?> AegisubProjectGarbage = []; public List<string> AegiusbExtradata = []; public List<AssEmbedded.Font> Fonts = []; public List<AssEmbedded.Graphic> Graphics = []; private readonly ILogger? _logger = logger; private const string sectionNameFonts = "[Fonts]"; private const string sectionNameGraphics = "[Graphics]"; private const string sectionNameAegisubProjectGarbage = "[Aegisub Project Garbage]"; private const string sectionNameAegisubExtradata = "[Aegisub Extradata]"; public AssData ReadAssFile(FileStream fs) { using var sr = new StreamReader(fs); string? line; var lineNumber = 0; var parseFunc = AssSection.ScriptInfo; Utils.GuessEncoding(fs, out CharEncoding, out CarriageReturn); _logger?.ZLogInformation($"File use {CharEncoding.EncodingName} and {(CarriageReturn ? "CRLF" : "LF")}"); _logger?.ZLogInformation($"Start parse ass"); while ((line = sr.ReadLine()) != null) { lineNumber++; var sp = line.AsSpan(); if (lineNumber == 1 && !sp.SequenceEqual("[Script Info]".AsSpan())) { throw new Exception("Please check first line"); } if (sp.Length == 0) { continue; } if (sp[0] == '[') { _logger?.ZLogInformation($"Start parse section {line}"); parseFunc = line switch { AssScriptInfo.sectionName => AssSection.ScriptInfo, AssStyles.sectionNameV4 => AssSection.StylesV4, AssStyles.sectionNameV4P => AssSection.StylesV4P, AssStyles.sectionNameV4PP => AssSection.StylesV4PP, AssEvents.sectionName => AssSection.Events, sectionNameFonts => AssSection.Fonts, sectionNameGraphics => AssSection.Graphics, sectionNameAegisubProjectGarbage => AssSection.AegisubProjectGarbage, sectionNameAegisubExtradata => AssSection.AegisubExtradata, _ => throw new Exception($"Unknown section: {line}."), }; if (!Sections.Add(parseFunc)) { throw new Exception($"Duplicate section: {line}"); } continue; } switch (parseFunc) { case AssSection.ScriptInfo: ScriptInfo.Read(sp, lineNumber); break; case AssSection.StylesV4: case AssSection.StylesV4P: case AssSection.StylesV4PP: Styles.Read(sp, lineNumber); break; case AssSection.Events: Events.Read(sp, ScriptInfo.ScriptType, lineNumber); break; case AssSection.AegisubProjectGarbage: Utils.TrySplitKeyValue(sp, out var k, out var v); AegisubProjectGarbage.TryAdd(k, v); break; case AssSection.AegisubExtradata: Utils.TrySplitKeyValue(sp, out var k1, out var v1); AegiusbExtradata.Add(v1); break; case AssSection.Fonts: Fonts = AssEmbedded.ParseFontsFromAss(sp, lineNumber, _logger); break; case AssSection.Graphics: Graphics = AssEmbedded.ParseGraphicsFromAss(sp, lineNumber, _logger); break; default: break; } } _logger?.ZLogInformation($"Ass parsing completed"); return this; } public AssData ReadAssFile(string filePath) { using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); _logger?.ZLogInformation($"Open ass file: {filePath}"); return ReadAssFile(fs); } public void WriteAssFile(string filePath, bool forceEnv, bool ctsRounding) { _logger?.ZLogInformation($"File will write to {filePath}"); var newline = forceEnv ? [.. Environment.NewLine] : (CarriageReturn ? new char[] { '\r', '\n' } : ['\n']); var charEncoding = forceEnv ? Utils.EncodingRefOS() : CharEncoding; using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write); using var memStream = new MemoryStream(); using var sw = new StreamWriter(memStream, charEncoding); foreach (var s in Sections) { switch (s) { case AssSection.ScriptInfo: ScriptInfo.Write(sw, newline); break; case AssSection.StylesV4P: case AssSection.StylesV4: Styles.Write(sw, newline, ScriptInfo.ScriptType); break; case AssSection.Events: Events.Write(sw, newline, ctsRounding); break; case AssSection.Fonts: sw.Write(sectionNameFonts); sw.Write(newline); foreach (var o in Fonts) { o.Write(sw, newline); } break; case AssSection.Graphics: sw.Write(sectionNameGraphics); sw.Write(newline); foreach (var o in Fonts) { o.Write(sw, newline); } break; case AssSection.AegisubProjectGarbage: sw.Write(sectionNameAegisubProjectGarbage); sw.Write(newline); foreach (var kvp in AegisubProjectGarbage) { sw.Write($"{kvp.Key}: {kvp.Value}"); sw.Write(newline); } sw.Write(newline); break; case AssSection.AegisubExtradata: sw.Write(sectionNameAegisubExtradata); sw.Write(newline); for (var i = 0; i < AegiusbExtradata.Count; i++) { sw.Write(AegiusbExtradata.ToArray()[i]); sw.Write(newline); } sw.Write(newline); break; } } sw.Flush(); _logger?.ZLogInformation($"Sections write completed"); memStream.Seek(0, SeekOrigin.Begin); memStream.CopyTo(fileStream); fileStream.Close(); _logger?.ZLogInformation($"File write completed"); } public void WriteAssFile(string filePath) => WriteAssFile(filePath, false, false); }
import { Dispatch, FormEvent, SetStateAction } from "react" import { islandCreateSchema } from "../db/schema/island.schema"; import { shortToast } from "../helpers/shorter-function"; type SetIsLoading = Dispatch<SetStateAction<boolean>> /** * Creates an array of objects with id and name * * @param countriesString - string of countries separated by commas * @returns array of objects with id and name */ const createCountiresArray = (countriesString: string) => { const countriesArray = countriesString.split(",").map((country) => country.trim()); const countries = countriesArray.map((country, index) => { return { id: index + 1, name: country, }; }); return countries; } /** * Creates a island to send to the database * * @param e - form event * @param setIsLoading - set loading state * @param setError - set error state */ export const createIsland = async (e: FormEvent, setIsLoading: SetIsLoading) => { setIsLoading(true); try { const target = e.target as typeof e.target & { name: { value: string }; area_km2: { value: string }; population: { value: string }; latitude: { value: string }; longitude: { value: string }; continent: { value: string }; countries: { value: string }; }; const island = islandCreateSchema.parse({ name: target.name.value, area_km2: Number(target.area_km2.value), population: Number(target.population.value), latitude: target.latitude.value, longitude: target.longitude.value, continent: target.continent.value, countries: createCountiresArray(target.countries.value) }); const res = await fetch("/api/data/islands", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(island), }) if (res.status === 201) { shortToast("Success", "Island created successfully", "success", 3000); } else if (res.status === 401) { shortToast("Error", "You are not authorized to create a island", "error", 5000); } setIsLoading(false); return "success" } catch (error: any) { if (error.error) { shortToast("Error", error.error[0].message, "error", 10000); } else if (error.message) { const messages: any = JSON.parse(error.message); shortToast("Error", messages[0].path[0] + ": " + messages[0].message, "error", 10000); } else { shortToast("Error", error.message, "error", 10000); } setIsLoading(false); return "error" } } /** * Updates a island to send to the database * * @param e - form event * @param setIsLoading - set loading state * @param setError - set error state */ export const updateIsland = async (id: string, e: FormEvent, setIsLoading: SetIsLoading) => { setIsLoading(true); try { const target = e.target as typeof e.target & { name: { value: string }; area_km2: { value: string }; population: { value: string }; latitude: { value: string }; longitude: { value: string }; continent: { value: string }; countries: { value: string }; }; const island = islandCreateSchema.parse({ name: target.name.value, area_km2: Number(target.area_km2.value), population: Number(target.population.value), latitude: target.latitude.value, longitude: target.longitude.value, continent: target.continent.value, countries: createCountiresArray(target.countries.value) }); const data = { id, island } const res = await fetch("/api/data/islands", { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) if (res.status === 200) { shortToast("Success", "Island updated successfully", "success", 3000); } else if (res.status === 401) { shortToast("Error", "You are not authorized to updated a island", "error", 5000); } } catch (error: any) { if (error.error) { shortToast("Error", error.error[0].message, "error", 10000); } else if (error.message) { const messages: any = JSON.parse(error.message); shortToast("Error", messages[0].path[0] + ": " + messages[0].message, "error", 10000); } else { shortToast("Error", error.message, "error", 10000); } } setIsLoading(false); }
import React, { useState } from "react"; import Deadline from "./Deadline"; import { AddDeadline } from "./AddDeadline"; import Tooltip from "@mui/material/Tooltip"; import type { TDeadline } from "../types"; import Fab from "@mui/material/Fab"; import AddIcon from "@mui/icons-material/Add"; import MuiList from "@mui/material/List"; import { Box } from "@mui/material"; import Typography from "@mui/material/Typography"; import Stack from "@mui/material/Stack"; type Props = { deadlines: TDeadline[]; addDeadline: (args: { title: string; timestamp: number }) => void; removeDeadline: (id: number) => void; role: string; }; type State = | { state: "addingDeadline"; } | { state: "normal"; }; const List: React.FC<Props> = ({ deadlines, addDeadline, removeDeadline, role, }) => { const [state, setState] = useState<State>({ state: "normal" }); if (state.state === "addingDeadline") { return ( <AddDeadline addDeadline={(deadline) => { addDeadline(deadline); setState({ state: "normal", }); }} cancel={() => { setState({ state: "normal" }); }} /> ); } return ( <Box sx={{ maxWidth: 480 }}> <Stack direction="row" alignItems="center" justifyContent="space-between"> <Typography variant="h3" component="h1" sx={{ m: 2 }}> Deadliner </Typography> {role === "broadcaster" && ( <Tooltip title="Add new deadline"> <Fab aria-label="Add new deadline" onClick={() => setState({ state: "addingDeadline" })} size="small" sx={{ m: 2 }} > <AddIcon /> </Fab> </Tooltip> )} </Stack> <MuiList> {deadlines .sort((a, b) => a.timestamp - b.timestamp) .map((deadline) => ( <Deadline key={deadline.id} {...deadline} canDelete={role === "broadcaster"} deleteMe={() => removeDeadline(deadline.id)} /> ))} </MuiList> </Box> ); }; export default List;
package dev.robocode.tankroyale.server.score import dev.robocode.tankroyale.server.dev.robocode.tankroyale.server.model.ParticipantId import dev.robocode.tankroyale.server.rules.RAM_DAMAGE /** Bot record that tracks damage and survival of a bot, and can calculate score. */ class ScoreAndDamage { private val bulletDamage = mutableMapOf<ParticipantId, Double>() private val ramHits = mutableMapOf<ParticipantId, Int>() private val bulletKillEnemyIds = mutableSetOf<ParticipantId>() private val ramKillEnemyIds = mutableSetOf<ParticipantId>() /** The survival count, which is the number of rounds where the bot has survived. */ var survivalCount: Int = 0 private set /** The last survivor count, which is the number of bots that was killed, before this bot became the last survivor. */ var lastSurvivorCount: Int = 0 private set /** The total bullet damage dealt by this bot to other bots. */ fun getTotalBulletDamage() = bulletDamage.keys.sumOf { getBulletDamage(it) } /** The total ram damage dealt by this bot to other bots. */ fun getTotalRamDamage() = ramHits.keys.sumOf { getRamHits(it) } * RAM_DAMAGE /** Returns the bullet kill enemy ids. */ fun getBulletKillEnemyIds(): Set<ParticipantId> = bulletKillEnemyIds /** Returns the ram kill enemy ids. */ fun getRamKillEnemyIds(): Set<ParticipantId> = ramKillEnemyIds /** * Returns the bullet damage dealt by this bot to specific bot. * @param enemyId is the enemy bot to retrieve the damage for. * @return the bullet damage dealt to a specific bot. */ private fun getBulletDamage(enemyId: ParticipantId): Double = bulletDamage[enemyId] ?: 0.0 /** * Returns the number of times ram damage has been dealt by this bot to specific bot. * @param enemyId is the enemy bot to retrieve the ram count for. * @return the ram count for a specific bot. */ private fun getRamHits(enemyId: ParticipantId): Int = ramHits[enemyId] ?: 0 fun getTotalDamage(enemyId: ParticipantId): Double = getBulletDamage(enemyId) + getRamHits(enemyId) * RAM_DAMAGE /** * Adds bullet damage to a specific enemy bot. * @param enemyId is the identifier of the enemy bot * @param damage is the amount of damage that the enemy bot has received */ fun addBulletDamage(enemyId: ParticipantId, damage: Double) { bulletDamage[enemyId] = getBulletDamage(enemyId) + damage } /** * Increment the number of ram hits to a specific bot or team. * @param id is the identifier of the bot/team. */ fun incrementRamHit(id: ParticipantId) { ramHits[id] = getRamHits(id) + 1 } /** * Increment the survival count, meaning that this bot has survived an additional round. */ fun incrementSurvivalCount() { survivalCount++ } /** * Add number of dead enemies to the last survivor count, which only counts, if this bot becomes the last survivor. * @param numberOfDeadEnemies is the number of dead bots that must be added to the last survivor count. */ fun addLastSurvivorCount(numberOfDeadEnemies: Int) { lastSurvivorCount += numberOfDeadEnemies } /** * Adds the identifier of an enemy bot to the set over bots killed by a bullet from this bot. * @param enemyId is the identifier of the enemy bot that was killed by this bot */ fun addBulletKillEnemyId(enemyId: ParticipantId) { bulletKillEnemyIds += enemyId } /** * Adds the identifier of an enemy bot to the set over bots killed by ramming by this bot. * @param enemyId is the identifier of the enemy bot that was killed by this bot */ fun addRamKillEnemyId(enemyId: ParticipantId) { ramKillEnemyIds += enemyId } }
import { errorDefinition } from "@/lib/constants" import { db } from "@/server/db" import { Staff } from "@/server/db/schema" import { toStaffResponse } from "@/server/models/responses/staff" import { useAuth } from "@/server/security/auth" import { defineHandler } from "@/server/web/handler" import { bindJson } from "@/server/web/request" import { sendData, sendErrors } from "@/server/web/response" import { eq } from "drizzle-orm" import { z } from "zod" const Param = z.object({ name: z.string(), email: z.string().email().optional(), phone: z.string(), role: z.enum(["admin", "secretary", "treasurer", "security_guard"]), }) export const PUT = defineHandler( async (req, { params }: { params: { id: number } }) => { useAuth(req, { staff: ["admin"], }) const param = await bindJson(req, Param) if (param.email) { let staffExists = await db().query.Staff.findFirst({ where: eq(Staff.email, param.email), }) if (staffExists) return sendErrors(409, errorDefinition.email_registered) } let staffExists = await db().query.Staff.findFirst({ where: eq(Staff.phone, param.phone), }) if (staffExists) return sendErrors(409, errorDefinition.phone_registered) let staff = await db().query.Staff.findFirst({ where: eq(Staff.id, params.id), }) if (!staff) return sendErrors(404, errorDefinition.staff_not_found) staff.name = param.name staff.email = param.email ?? null staff.phone = param.phone staff.role = param.role staff.updatedAt = new Date() await db().update(Staff).set(staff).where(eq(Staff.id, params.id)) return sendData(201, toStaffResponse(staff)) }, )
d<-data.frame(year=c(2009:2020), dissimilarity=runif(12, 0.5, 1), centroid_distance=runif(12, 0.5, 1), volume_change=runif(12, 0.5, 1), SST=runif(12, 0, 1), SSS=runif(12, 0, 1), red_tides=runif(12, 0, 1), abundance=runif(12, 0, 1), occurrence=runif(12, 0, 1), effort=runif(12, 0, 1)) d<-reshape2::melt(d,id='year') d$effect<-ifelse(d$variable %in% c('dissimilarity','centroid_distance','volume_change'),'fixed effects','factors') library(ggplot2) library(ggthemes) p1<-ggplot()+ #geom_line(data=subset(d,effect=='fixed effects'),aes(x=year,y=value,group=variable,color=variable),linetype='dashed')+ geom_line(data=subset(d,effect=='factors'),aes(x=year,y=value,group=variable,color=variable),linetype='solid',size=0.8)+ ggtitle(label='factors afffecting ENM estimation')+ labs(color = "")+ theme_bw()+ xlab('')+ ylab('standardized value')+ theme(legend.title = element_blank(),strip.text.x = element_text(size = 9,color='black'), #plot.title = element_blank(), plot.title = element_text(hjust = 0.5,size = 14), panel.grid.minor = element_line(color = col_grid, size = 0.3, linetype = 'dashed'), panel.grid.major = element_line(color = col_grid, size = 0.5))+ expand_limits(y=0)+ scale_color_tableau()+ scale_x_continuous(breaks = c(2009:2020),minor_breaks = c(2009,2011:2014,2016:2019)) p2<-ggplot()+ geom_line(data=subset(d,effect=='fixed effects'),aes(x=year,y=value,group=variable,color=variable),linetype='dashed',size=0.8)+ ggtitle(label='hypervolume metrics')+ labs(color = "")+ theme_bw()+ ylab('metric value')+ theme(legend.title = element_blank(),strip.text.x = element_text(size = 9,color='black'), #plot.title = element_blank(), plot.title = element_text(hjust = 0.5,size = 14), panel.grid.minor = element_line(color = col_grid, size = 0.3, linetype = 'dashed'), panel.grid.major = element_line(color = col_grid, size = 0.5))+ expand_limits(y=0)+ scale_color_tableau()+ scale_x_continuous(breaks = c(2009:2020),minor_breaks = c(2009,2011:2014,2016:2019)) #geom_line(data=subset(d,effect=='factors'),aes(x=year,y=value,group=variable,color=variable),linetype='solid') plot_grid(p1,p2,nrow = 2,align = 'v')
--- title: "Hogares" author: "Cesar Poggi" date: "29/1/2022" output: html_document --- ***DATA 2019*** A) Cargar la Data DESCARGAR Y DESCOMPRIMIR ARCHIVO enaho2019.dta para poder leerlo ```{r} library(haven) data1=read_dta("enaho2019.dta") ``` B) Agrupar los casos por departamento en una nueva variable. Es decir, por los dos primeros dígitos su ubigeo ```{r} library(stringr) data1$loeschen1=substr(data1$ubigeo, 1, 2) ``` C) Sacamos la media de los grupos de valores de la nueva variable. Utilizando el factor de ponderación "factor07". ```{r} library(Hmisc) library(plyr) tab.descr <- ddply(data1,~loeschen1,summarise, Media=wtd.mean(p1144,factor07, na.rm=T)*100) ``` ***DATA 2020*** D) Cargar la data DESCARGAR Y DESCOMPRIMIR ARCHIVO enaho2020.dta para poder leerlo ```{r} data2=read_dta("enaho2020.dta") ``` E) Agrupar los casos por departamento en una nueva variable. Es decir, por los dos primeros dígitos su ubigeo ```{r} library(stringr) data2$loeschen2=substr(data2$ubigeo, 1, 2) ``` F) Sacamos la media de los grupos de valores de la nueva variable. Utilizando el factor de ponderación "factor07" o "factor_p". ```{r} library(Hmisc) library(plyr) #FACTOR DE EXPANSION FACTOR07 tab.descr2 <- ddply(data2,~loeschen2,summarise, Media=wtd.mean(p1144,factor07, na.rm=T)*100) #FACTOR DE EXPANSIÓN FACTOR_P tab.descr3 <- ddply(data2,~loeschen2,summarise, Media=wtd.mean(p1144,factor_p, na.rm=T)*100) ``` ***DATA VARIACIÓN ANUAL*** G) Extracción, modificación y transformación de la data de variación del acceso a internet por región ```{r} library(rio) #varia19=import("varia.csv", encoding ="UTF-8") linkData1="https://github.com/PULSO-PUCP/ProyectoHCE/raw/main/Varia.csv" varia19=import(linkData1,encoding ="UTF-8") varia19[1, 2]<-"loeschen2" colnames(varia19)=varia19[c(1),] varia19=varia19[-c(1),] varia19[c(14,15)]=NULL varia19$loeschen2<-c("01","02","03","04","05","06","07","08","09","10","11", "12","13","14","15","16","17","18","19","20","21","22","23","24","25") varia19=merge(varia19, tab.descr2, by="loeschen2") colnames(varia19)[14] <- "2020" ``` H) Gráfico del porcentaje de hogares con acceso a internet (2020), por regiones. ```{r} tab.descr2$departamento = varia19$Var.2 library(plotly) tab.descr2$Media<-round(tab.descr2$Media, digits=1) y<-tab.descr2$Media #y=rev(y) fig5=plot_ly(tab.descr2, x = ~Media, y = ~departamento, type = 'bar', text = y, textposition = 'auto') fig5 <- fig5 %>% layout(xaxis = list(title = 'Cuenta'), barmode = 'group') fig5 <- fig5 %>% layout(yaxis = list(title = 'Departamento'), barmode = 'group') fig5 ``` I) Creación de una nueva data y modificación de esta para un nuevo gráfico. ```{r} varia19$`2020`<-round(varia19$`2020`, digits=1) varia19PLOTLY=as.data.frame(t(varia19)) library(data.table) setDT(varia19PLOTLY, keep.rownames = TRUE) varia19PLOTLY=varia19PLOTLY[-c(1),] varia19PLOTLY<-as.data.frame(varia19PLOTLY) colnames(varia19PLOTLY)=varia19PLOTLY[c(1),] varia19PLOTLY=varia19PLOTLY[-c(1,2,4,5,6,7,9,10,11),] colnames(varia19PLOTLY)[1] <- "Año" library(janitor) varia19PLOTLY <- clean_names(varia19PLOTLY) ``` J) Gráfico que muestra la evolución del acceso de los hogares a internet, por región y hasta el 2020. ```{r} library(plotly) fig6 <- plot_ly(varia19PLOTLY, x = ~ano, y = ~amazonas, name = 'AMAZONAS', type = 'scatter', mode = 'lines', line = list(color = 'rgb(205, 12, 24)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~ancash, name = 'ANCASH', type = 'scatter', mode = 'lines', line = list(color = 'rgb(0,100,0)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~apurimac, name = 'APURIMAC', type = 'scatter', mode = 'lines', line = list(color = 'rgb(138,43,226)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~arequipa, name = 'AREQUIPA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(205,133,63)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~ayacucho, name = 'AYACUCHO', type = 'scatter', mode = 'lines', line = list(color = 'rgb(176,196,222)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~cajamarca, name = 'CAJAMARCA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(255,215,0)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~prov_const_callao, name = 'CALLAO', type = 'scatter', mode = 'lines', line = list(color = 'rgb(0,128,128)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~cusco, name = 'CUSCO', type = 'scatter', mode = 'lines', line = list(color = 'rgb(255,160,122)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~huancavelica, name = 'HUANCAVELICA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(65,105,225)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~huanuco, name = 'HUANUCO', type = 'scatter', mode = 'lines', line = list(color = 'rgb(255,105,180)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~ica, name = 'ICA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(128,0,0)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~junin, name = 'JUNIN', type = 'scatter', mode = 'lines', line = list(color = 'rgb(128,0,128)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~la_libertad, name = 'LA LIBERTAD', type = 'scatter', mode = 'lines', line = list(color = 'rgb(128,128,0)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~lambayeque, name = 'LAMBAYEQUE', type = 'scatter', mode = 'lines', line = list(color = 'rgb(255,255,0)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~lima, name = 'LIMA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(0,255,0)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~loreto, name = 'LORETO', type = 'scatter', mode = 'lines', line = list(color = 'rgb(75,0,130)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~madre_de_dios, name = 'MADRE DE DIOS', type = 'scatter', mode = 'lines', line = list(color = 'rgb(30,144,255)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~moquegua, name = 'MOQUEGUA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(143,188,143)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~pasco, name = 'PASCO', type = 'scatter', mode = 'lines', line = list(color = 'rgb(175,238,238)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~piura, name = 'PIURA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(50,205,50)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~puno, name = 'PUNO', type = 'scatter', mode = 'lines', line = list(color = 'rgb(218,165,32)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~san_martin, name = 'SAN MARTIN', type = 'scatter', mode = 'lines', line = list(color = 'rgb(0,0,139)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~tacna, name = 'TACNA', type = 'scatter', mode = 'lines', line = list(color = 'rgb(205, 12, 24)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~tumbes, name = 'TUMBES', type = 'scatter', mode = 'lines', line = list(color = 'rgb(100,149,237)', width = 4)) fig6 <- fig6 %>% add_trace(y = ~ucayali, name = 'UCAYALI', type = 'scatter', mode = 'lines', line = list(color = 'rgb(220,20,60)', width = 4)) fig6 ```
import React, { useState, useEffect } from "react"; import axios from "axios"; import RepoUser from "../repouser/RepoUser"; import "./UserInfo.css" export default function UserInfo({ setUserInfoVisible }) { const [username, setUsername] = useState(""); const [userInfo, setUserInfo] = useState(null); const [buttonClicked, setButtonClicked] = useState(false); const [error, setError] = useState(null); useEffect(() => { const getUserInfo = async () => { if (username.trim() !== "") { try { const response = await axios.get( `https://api.github.com/users/${username}` ); setUserInfo(response.data); setError(null); } catch (error) { console.log(error); setUserInfo(null); setError("User not found"); } } else { setUserInfo(null); setError(null); } }; if (buttonClicked) { getUserInfo(); } }, [username, buttonClicked]); const handleInputChange = (event) => { setUsername(event.target.value); }; const handleButtonClick = () => { setButtonClicked(true); setUserInfoVisible(true); }; return ( <div className="Container"> <input type="text" placeholder="Enter username" value={username} onChange={handleInputChange} className="Input" /> <button onClick={handleButtonClick} className="Btn">Get User Info</button> {error && <p>{error}</p>} {userInfo && ( <div className="User"> <img src={userInfo.avatar_url} alt={userInfo.login} className="Img" /> <div> <p className="List-item"> <b>Fullname: </b> {userInfo.login} </p> <hr className="Line" /> <p className="List-item"> <b>Username: </b> {userInfo.name} </p> <hr className="Line" /> <p className="List-item"> <b>Location: </b> {userInfo.location} </p> <hr className="Line" /> <p> <b>Email Address: </b> {userInfo.email} </p> <hr className="Line" /> </div> </div> )} {buttonClicked && <RepoUser username={username} />} </div> ); }
import 'package:dinesh_s_application42/core/app_export.dart'; import 'package:dinesh_s_application42/widgets/app_bar/appbar_image.dart'; import 'package:dinesh_s_application42/widgets/app_bar/appbar_image_1.dart'; import 'package:dinesh_s_application42/widgets/app_bar/appbar_subtitle_1.dart'; import 'package:dinesh_s_application42/widgets/app_bar/custom_app_bar.dart'; import 'package:flutter/material.dart'; class CashOnlyBudgetingScreen extends StatelessWidget { const CashOnlyBudgetingScreen({Key? key}) : super( key: key, ); @override Widget build(BuildContext context) { mediaQueryData = MediaQuery.of(context); return SafeArea( child: Scaffold( extendBody: true, extendBodyBehindAppBar: true, appBar: CustomAppBar( height: getVerticalSize(72), leadingWidth: double.maxFinite, leading: AppbarImage( onTap:() { onTapArrowleftone(context); }, imagePath: ImageConstant.imgLessthan, margin: getMargin( left: 9, right: 341, ), ), ), body: Container( width: mediaQueryData.size.width, height: mediaQueryData.size.height, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( ImageConstant.imgGroup886, ), fit: BoxFit.cover, ), ), child: SingleChildScrollView( padding: getPadding( top: 8, ), child: Padding( padding: getPadding( left: 2, bottom: 5, ), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( "Cash-only budgeting", style: theme.textTheme.titleSmall, ), Container( width: getHorizontalSize(388), margin: getMargin( top: 27, ), child: Text( "Cash-only budgeting is a straightforward method of managing your money where you primarily use physical cash for your expenses instead of relying on credit cards or digital payments. Here's a simple explanation:", maxLines: 6, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: CustomTextStyles.titleLargeBlack900_2, ), ), Container( height: getVerticalSize(567), width: getHorizontalSize(378), margin: getMargin( top: 12, ), child: Stack( alignment: Alignment.center, children: [ Align( alignment: Alignment.center, child: Container( height: getVerticalSize(565), width: getHorizontalSize(378), decoration: BoxDecoration( color: appTheme.gray700.withOpacity(0.7), borderRadius: BorderRadius.circular( getHorizontalSize(40), ), ), ), ), Align( alignment: Alignment.center, child: SizedBox( width: getHorizontalSize(374), child: RichText( text: TextSpan( children: [ TextSpan( text: "Using Physical Cash:", style: CustomTextStyles.titleLargeBlack900_1, ), TextSpan( text: "With cash-only budgeting, you withdraw a specific amount of money in cash at the beginning of each budgeting period (like a week or a month).\n", style: theme.textTheme.titleLarge, ), TextSpan( text: "Envelope System:", style: CustomTextStyles.titleLargeBlack900_1, ), TextSpan( text: "You then divide this cash into envelopes labeled with different spending categories, like groceries, entertainment, transportation, etc.\n", style: theme.textTheme.titleLarge, ), TextSpan( text: "Spending Limit:", style: CustomTextStyles.titleLargeBlack900_1, ), TextSpan( text: "Each envelope represents the maximum amount you're allowed to spend in that category for the chosen period. Once the cash in the envelope is used up, you stop spending in that category until the next budgeting period.\n", style: theme.textTheme.titleLarge, ), TextSpan( text: "No Credit or Digital Payments:", style: CustomTextStyles.titleLargeBlack900_1, ), TextSpan( text: "The key is that you only spend the cash you have in the envelopes. You don't use credit cards or digital payments, which can make it easier to stick to your budget and avoid overspending.", style: theme.textTheme.titleLarge, ), ], ), textAlign: TextAlign.center, ), ), ), ], ), ), Container( width: getHorizontalSize(372), margin: getMargin( left: 4, top: 21, right: 12, ), child: Text( "This method can be effective because it makes your spending tangible and gives you a clear visual of how much money you have left for each category. It can help you become more mindful about your spending and encourages you to make conscious choices about where your money goes. However, it might require more effort and planning, as well as some adjustments if you encounter unexpected expenses.", maxLines: 12, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: CustomTextStyles.titleLargeBlack900_2, ), ), ], ), ), ), ), ), ); } /// Navigates back to the previous screen. /// /// This function takes a [BuildContext] object as a parameter, which is used /// to navigate back to the previous screen. onTapArrowleftone(BuildContext context) { Navigator.pop(context); } }
import React, { useState, useContext } from "react"; import NavigateNextIcon from "@mui/icons-material/NavigateNext"; import NavigateBeforeIcon from "@mui/icons-material/NavigateBefore"; import { CarouselData } from "../CarouselData"; import { AppContext } from "../context/AppContext"; import { Modal } from "./Modal"; import "../styles/components/CarouselContainer.css"; const CarouselContainer = () => { const { searchValue, setNotificationState } = useContext(AppContext); const slides = CarouselData; const [current, setCurrent] = useState(0); const [modalState, setModalState] = useState(false); const lenght = slides.length; var t = 0; const nextSlide = () => { setCurrent(current === lenght - 1 ? 0 : current + 1); }; const prevSlide = () => { setCurrent(current === 0 ? lenght - 1 : current - 1); }; if (!Array.isArray(slides) || slides.length <= 0) { return null; } const classChanger = () => { if (current === 0) { return "starboy"; } else if (current === 1) { return "blonde"; } else if (current === 2) { return "igor"; } else { return "ye"; } }; return ( <div className={ searchValue.length > 0 ? "hidden" : `carousel__container ${classChanger()}` } > <div className="carousel__text"> <p>THE GREATEST ALBUMS</p> </div> <div className="carousel"> <NavigateBeforeIcon className="left-arrow" onClick={prevSlide} fontSize="large" /> {slides.map((item, index) => { return ( <div className={index === current ? "slide active" : "slide"} key={index} onClick={() => { setModalState(!modalState); clearTimeout(t); }} > {index === current && ( <> <img loading="lazy" src={item.attributes.image} alt={item.attributes.title} className="image" /> <Modal product={item} modalState={modalState} setModalState={setModalState} setNotificationState={setNotificationState} /> </> )} </div> ); })} <NavigateNextIcon className="right-arrow" onClick={nextSlide} fontSize="large" /> </div> </div> ); }; export { CarouselContainer };
using AutoFixture; using Core.Tests; using Core.Tests.Attributes; using FluentValidation; using Users.Application.Handlers.Queries.GetUser; using Xunit.Abstractions; namespace Users.UnitTests.Tests.Queries.GetUser; public class GetUserQueryValidatorTests : ValidatorTestBase<GetUserQuery> { public GetUserQueryValidatorTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } protected override IValidator<GetUserQuery> TestValidator => TestFixture.Create<GetUserQueryValidator>(); [Theory, FixtureAutoData] public void Should_BeValid_When_RequestFieldsAreFilledCorrectly(Guid id) { // arrange var query = new GetUserQuery { Id = id.ToString() }; // act & assert AssertValid(query); } [Theory] [FixtureInlineAutoData("")] [FixtureInlineAutoData(null)] [FixtureInlineAutoData("123")] public void Should_NotBeValid_When_IncorrectGuid(string id) { // arrange var query = new GetUserQuery { Id = id }; // act & assert AssertNotValid(query); } }
import { FiArrowUp, FiMessageSquare } from "react-icons/fi"; import { FormEvent, useEffect, useState } from "react"; import { GetServerSideProps, NextPage } from "next"; import { IUserHunter, IUserProvisioner, THunterBlogPost, TProvBlogPost, } from "@/lib/types"; import { MdArrowBack, MdCheckCircle, MdComment, MdDelete, MdEdit, MdFavorite, MdFavoriteBorder, MdMoreHoriz, MdShare, MdVisibility, MdVisibilityOff, } from "react-icons/md"; import { $accountDetails } from "@/lib/globalStates"; import { AnimPageTransition } from "@/lib/animations"; import { AnimatePresence } from "framer-motion"; import Image from "next/image"; import Link from "next/link"; import { ReactMarkdown } from "react-markdown/lib/react-markdown"; import dayjs from "dayjs"; import { motion } from "framer-motion"; import rehypeRaw from "rehype-raw"; import relative from "dayjs/plugin/relativeTime"; import { supabase } from "@/lib/supabase"; import { toast } from "react-hot-toast"; import { useAutoAnimate } from "@formkit/auto-animate/react"; import { useQuery } from "@tanstack/react-query"; import { useRouter } from "next/router"; import { useStore } from "@nanostores/react"; import { uuid } from "uuidv4"; dayjs.extend(relative); interface BlogEventPostProps { content: string; createdAt: string | null; id: string; updatedAt: string | null; uploader: IUserProvisioner; upvoters: string[]; type: "provblog" | "event"; draft: boolean; } const ProvBlogPostPage: NextPage = () => { const currentUser = useStore($accountDetails) as IUserHunter; const [isEditing, setIsEditing] = useState(false); const [isCommentingRef] = useAutoAnimate(); const [isEditingRef] = useAutoAnimate(); const router = useRouter(); const [tempData, setTempData] = useState({} as BlogEventPostProps); const [isUpvoted, setIsUpvoted] = useState(false); const fetchBlogData = async () => { const { id } = router.query; const { data: blogData, error } = await supabase .from("public_provposts") .select("*,uploader(*)") .eq("id", id) .single(); if (error) { console.log(error); return {} as BlogEventPostProps; } return blogData as BlogEventPostProps; }; const _blogData = useQuery({ queryKey: ["prov_blog_post"], queryFn: fetchBlogData, refetchOnWindowFocus: false, refetchOnMount: true, enabled: !!router.query.id, onSuccess: (data) => { setTempData(data); }, }); const handleDeleteBlog = async () => { toast.loading("Processing..."); if (!router.query.id) { toast.error("Something went wrong"); return; } const { error } = await supabase .from("public_posts") .delete() .eq("id", router.query.id); if (error) { toast.error("Something went wrong"); return; } toast.dismiss(); router.push("/p/blog"); }; const handleUpdateBlog = async () => { toast.loading("Processing..."); const { error } = await supabase .from("public_provposts") .update({ content: tempData.content, draft: tempData.draft, }) .eq("id", router.query.id); if (error) { toast.error("Something went wrong"); return; } setTempData({ ...tempData, content: tempData.content, draft: tempData.draft, }); toast.dismiss(); setIsEditing(false); toast.success("Blog updated"); _blogData.refetch(); }; const handleUpvoteBlog = async () => { // get current upvoters const { data: upvoters, error } = await supabase .from("public_provposts") .select("upvoters") .eq("id", router.query.id) .single(); if (error) { console.log(error); return; } // check if user has already upvoted const hasUpvoted = upvoters?.upvoters.includes(currentUser.id); // if user has already upvoted, remove user from upvoters if (hasUpvoted) { const newUpvoters = upvoters?.upvoters.filter( (id: string) => id !== currentUser.id, ); const { error } = await supabase .from("public_provposts") .update({ upvoters: newUpvoters, }) .eq("id", router.query.id); if (error) { console.log(error); return; } setIsUpvoted(false); _blogData.refetch(); return; } // if user has not upvoted, add user to upvoters const { error: error2 } = await supabase .from("public_provposts") .update({ upvoters: [...upvoters?.upvoters, currentUser.id], }) .eq("id", router.query.id); if (error2) { console.log(error2); return; } setIsUpvoted(true); _blogData.refetch(); }; const checkIfUpvoted = async () => { const { data: upvoters, error } = await supabase .from("public_provposts") .select("upvoters") .eq("id", router.query.id) .single(); if (error) { console.log(error); return; } if (upvoters?.upvoters.includes(currentUser.id)) { setIsUpvoted(true); } }; useEffect(() => { if (currentUser) { checkIfUpvoted(); } }, [currentUser]); return ( <> {_blogData.isSuccess && !!currentUser && ( <> <motion.main variants={AnimPageTransition} initial="initial" animate="animate" exit="exit" className="relative min-h-screen w-full pt-24 pb-36 overflow-y-hidden" > <div className="flex items-center gap-2 mb-10"> <button className="btn btn-square btn-primary btn-ghost" onClick={() => router.back()} > <MdArrowBack className="text-2xl" /> </button> <p>Go Back</p> </div> {/* header */} <div className="flex items-center gap-4 0"> <Image src={ _blogData.data.uploader.avatar_url ?? `https://api.dicebear.com/6.x/shapes/png?seed=${_blogData.data.uploader.legalName}` } alt="avatar" width={40} height={40} className="mask mask-squircle" /> <div className="flex flex-col"> <Link href={ currentUser.id === _blogData.data.uploader.id ? "/p/me" : `/drift/company?id=${_blogData.data.uploader.id}` } className="font-semibold hover:underline underline-offset-2 leading-tight flex items-center" > {_blogData.data.uploader.legalName} </Link> <p className="leading-none"> {dayjs(_blogData.data.createdAt).fromNow()} </p> </div> {currentUser.id === _blogData.data.uploader.id && ( <div className="ml-auto"> {/* mobile dropdown */} <div className="dropdown dropdown-end dropdown-bottom lg:hidden"> <div tabIndex={0} className="btn btn-ghost"> <MdMoreHoriz className="text-xl" /> </div> <div className="dropdown-content"> <ul className="menu bg-base-200 p-3 rounded-btn w-max"> <li> <p onClick={() => { setIsEditing(!isEditing); }} > <MdEdit /> Edit Blog </p> </li> <li> <label htmlFor="modal-delete-post"> <MdDelete /> Delete Blog </label> </li> </ul> </div> </div> {/* desktop buttons */} <div className="hidden lg:flex items-center gap-3"> <label className="flex items-center gap-2"> <span>Draft</span> <input type="checkbox" className="checkbox checkbox-primary" checked={tempData.draft} onChange={(e) => { setTempData({ ...tempData, draft: e.target.checked, }); }} /> </label> <button onClick={() => { setIsEditing(!isEditing); }} className="btn btn-ghost gap-2" > <MdEdit /> Edit Blog </button> <label htmlFor="modal-delete-post" className="btn btn-error gap-2" > <MdDelete /> Delete Blog </label> </div> </div> )} </div> {/* content grid */} <div className="flex flex-col gap-4 mt-10"> {/* content */} <div ref={isEditingRef}> {!isEditing ? ( <ReactMarkdown className="prose prose-lg max-w-max"> {tempData.content} </ReactMarkdown> ) : ( <textarea value={tempData.content} onChange={(e) => setTempData({ ...tempData, content: e.target.value, }) } rows={30} className="textarea textarea-primary w-full" /> )} </div> {/* sidebar */} <div className="mt-10" ref={isCommentingRef}> {/* upvote and comment toggler */} <div className="flex items-center gap-1"> <button onClick={handleUpvoteBlog} className="btn btn-ghost gap-2 text-xl" > {isUpvoted ? ( <MdFavorite className="text-red-500" /> ) : ( <MdFavoriteBorder /> )} {_blogData.data.upvoters.length} </button> <button onClick={() => { navigator.clipboard.writeText(window.location.href); toast.success("Link copied to clipboard!"); }} className="btn btn-ghost gap-2 text-xl ml-auto" > <MdShare /> </button> </div> </div> </div> </motion.main> </> )} <AnimatePresence mode="wait"> {JSON.stringify(tempData) !== JSON.stringify(_blogData.data) && ( <motion.div initial={{ y: 100, opacity: 0 }} animate={{ y: 0, opacity: 1, transition: { easings: "circOut" }, }} exit={{ y: 100, opacity: 0, transition: { easings: "circIn" } }} className="fixed bottom-0 left-0 right-0 flex justify-center bg-base-100 p-5" > <div className="flex justify-end gap-2 w-full max-w-5xl"> <button onClick={handleUpdateBlog} className="btn btn-primary"> Save Changes </button> <button onClick={() => { setTempData(_blogData.data as BlogEventPostProps); setIsEditing(false); }} className="btn btn-ghost" > Clear Changes </button> </div> </motion.div> )} </AnimatePresence> {/* confirm delete post modal */} <input type="checkbox" id="modal-delete-post" className="modal-toggle" /> <div className="modal"> <div className="modal-box"> <h3 className="font-bold text-lg">Confirm Delete</h3> <p className="py-4"> Are you sure you want to delete this post? This action cannot be undone. All comments will also be deleted. </p> <div className="modal-action"> <label htmlFor="modal-delete-post" className="btn"> Cancel </label> <button onClick={handleDeleteBlog} className="btn btn-error"> Delete </button> </div> </div> </div> </> ); }; export default ProvBlogPostPage;
import {FC, useEffect, useState} from "react"; import {Navbar} from "../application/Navbar"; import {Footer} from "../application/Footer"; import axios, {AxiosResponse} from "axios"; import {CarDetailsStateType, CarReservationType, CarType} from "../../types/cars/cars.types"; import {useLocation} from "react-router"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {faGaugeHigh, faGears, faSackDollar, faUserGroup} from "@fortawesome/free-solid-svg-icons"; import {ReserveCarForm} from "./ReserveCarForm"; import {GiveCarFeedbackForm} from "./GiveCarFeedbackForm"; export const CarDetails: FC = () => { const [state, setState] = useState<CarDetailsStateType>(); const location = useLocation() useEffect(() => { axios.get<number, AxiosResponse<CarType>>(`${process.env.REACT_APP_SERVER_NAME}${location.pathname}`).then(response => { let car = response.data; car.reservations = structuredClone(car.reservations).sort((a: CarReservationType, b: CarReservationType) => { if (new Date(a.from).getTime() === new Date(b.from).getTime()) return new Date(b.to).getTime() - new Date(a.to).getTime(); return new Date(b.from).getTime() - new Date(a.from).getTime(); }) setState({...state, data: car}); }) }, []) return ( <main className={"car-details"}> <Navbar navbarTheme={"white"} changeNavbarThemeCheckpoint={0} /> <div className={"content"}> <div className={"car-info"}> { state ? <> <header className={"car-info-header"}> <img src={`${process.env.PUBLIC_URL}/${state?.data.image}`} alt={state?.data.title} /> <h3>{state?.data.title}</h3> </header> <div className={'car-info-content'}> <div className={"content-item price-per-day"}> <label> Price per day: <br/> <span> <FontAwesomeIcon icon={faSackDollar} /> {state?.data.pricePerDay}$ </span> </label> </div> <div className={"content-item number-of-seats"}> <label> Number of seats: <br/> <span> <FontAwesomeIcon icon={faUserGroup} /> {state?.data.seats} </span> </label> </div> <div className={"content-item mileage"}> <label> Mileage: <br/> <span> <FontAwesomeIcon icon={faGaugeHigh} /> {state?.data.mileage} km </span> </label> </div> <div className={"content-item transmission"}> <label> Transmission type: <br/> <span> <FontAwesomeIcon icon={faGears} /> {state?.data.transmission} </span> </label> </div> </div> <footer className={'car-info-footer'}> <h3>Reservations: </h3> <div className={"reservations"}> <div className={'car-reservation'}> <div>From</div> <div>To</div> </div> { state?.data && state.data.reservations.length > 0 ? state.data.reservations.map((reservation, index) => ( <div className={"car-reservation"} key={index}> <div className={"from"}> {new Date(reservation.from).toLocaleDateString()} {new Date(reservation.from).toLocaleTimeString()} </div> <div className={"to"}> {new Date(reservation.from).toLocaleDateString()} {new Date(reservation.from).toLocaleTimeString()} </div> </div> )) : <div className={"car-reservation"}> <div className={'no-reservations'}> This car has not been reserved yet </div> </div> } </div> <h3>Feedbacks:</h3> <div className={"feedbacks"}> { state?.data && state.data.feedbacks.length > 0 ? state.data.feedbacks.map((feedback, index) => ( <div className={"car-feedback"} key={index}> <div className={"author"}> <h4>{feedback.name}</h4> </div> <div className={"text"}> <p>{feedback.feedback}</p> </div> </div> )) : <></> } </div> </footer> </> : <div className={"loading-page"}> <img src={`${process.env.PUBLIC_URL}/images/loading.gif`} alt={"Loading"} /> </div> } </div> <div className={"forms"}> <ReserveCarForm car={state?.data} /> <GiveCarFeedbackForm car={state?.data} /> </div> </div> <Footer /> </main> ) }
import { useEffect, useState } from "react"; import useFetchPackages from "../../hooks/useFetchPackage"; import { PackageContainer, SortingBarContainer, SortingBarInput, SortingBarDropdown, SortingBarDropdownContainer, SortingBarDropdownItems, NoMatchMessage, ClearSortBarButton, } from "./Packages.style"; import PackageCard from "./PackageCard/PackageCard"; function Packages() { const { packages, error, loading } = useFetchPackages(); const [filteredPackages, setFilteredPackages] = useState([]); const [country, setCountry] = useState(""); const [city, setCity] = useState(""); const [priceRange, setPriceRange] = useState(""); const [currency, setCurrency] = useState(""); const [currencies, setCurrencies] = useState([]); const handleClearSortingBar = () => { setCountry(""); setCity(""); setPriceRange(""); setCurrency(""); }; useEffect(() => { if (!localStorage.getItem("reloaded")) { localStorage.setItem("reloaded", "true"); window.location.reload(); } else { localStorage.removeItem("reloaded"); } }, []); useEffect(() => { if (packages) { const uniqueCurrencies = [ ...new Set(packages.map((pkg) => pkg.moneda_sejur)), ]; setCurrencies(uniqueCurrencies); } }, [packages]); useEffect(() => { let filtered = packages; if (country) { filtered = filtered.filter((pkg) => pkg.tara.toLowerCase().includes(country.toLowerCase()) ); } if (city) { filtered = filtered.filter((pkg) => pkg.oras.toLowerCase().includes(city.toLowerCase()) ); } if (currency) { filtered = filtered.filter( (pkg) => pkg.moneda_sejur.toLowerCase() === currency.toLowerCase() ); } if (priceRange) { const [minPriceStr, maxPriceStr] = priceRange.split("-"); let minPrice = parseFloat(minPriceStr); let maxPrice = maxPriceStr ? parseFloat(maxPriceStr) : Infinity; if (maxPriceStr === "+") { minPrice = 5000; maxPrice = Infinity; } filtered = filtered.filter((pkg) => { const price = parseFloat(pkg.pret_sejur); return price >= minPrice && price <= maxPrice; }); } setFilteredPackages(filtered); }, [country, city, priceRange, currency, packages]); return ( <> <SortingBarContainer> <ClearSortBarButton onClick={handleClearSortingBar}> Clear </ClearSortBarButton> <SortingBarInput type="text" placeholder="Filter by Country" value={country} onChange={(e) => setCountry(e.target.value)} /> <SortingBarInput type="text" placeholder="Filter by City" value={city} onChange={(e) => setCity(e.target.value)} /> <SortingBarDropdownContainer> <SortingBarDropdown value={currency} onChange={(e) => setCurrency(e.target.value)} > <SortingBarDropdownItems value=""> Select Currency </SortingBarDropdownItems> {currencies.map((currency, index) => ( <SortingBarDropdownItems key={index} value={currency}> {currency} </SortingBarDropdownItems> ))} </SortingBarDropdown> <SortingBarDropdown value={priceRange} onChange={(e) => setPriceRange(e.target.value)} > <SortingBarDropdownItems value=""> Filter by Price </SortingBarDropdownItems> <SortingBarDropdownItems value="0-500"> 0-500 </SortingBarDropdownItems> <SortingBarDropdownItems value="500-1000"> 500-1000 </SortingBarDropdownItems> <SortingBarDropdownItems value="1000-2000"> 1000-2000 </SortingBarDropdownItems> <SortingBarDropdownItems value="2000-3000"> 2000-3000 </SortingBarDropdownItems> <SortingBarDropdownItems value="3000-4000"> 3000-4000 </SortingBarDropdownItems> <SortingBarDropdownItems value="4000-5000"> 4000-5000 </SortingBarDropdownItems> <SortingBarDropdownItems value="5000+"> 5000+ </SortingBarDropdownItems> </SortingBarDropdown> </SortingBarDropdownContainer> </SortingBarContainer> <PackageContainer loc="PackageContainer"> {loading && <div>Loading...</div>} {error && <div>{error} Error on getting data, server is down.</div>} {!loading && !error && filteredPackages.length === 0 && ( <NoMatchMessage>Sorry, no match for your search</NoMatchMessage> )} {filteredPackages.length > 0 && filteredPackages.map((my_package) => ( <PackageCard key={my_package.tara} {...my_package} /> ))} </PackageContainer> </> ); } export default Packages;
import {Injectable} from '@angular/core'; import {Subject} from 'rxjs'; import Web3 from 'web3'; import {Employee} from "../../model/employee"; import {BalanceService} from "./balance.service"; import {EmployeeService} from "../backend/employee.service"; declare let window: any; @Injectable({ providedIn: 'root' }) export class WalletService { public accountObservable = new Subject<Employee[]>(); private accounts: Employee[] | undefined; private web3: any; private intervalId: NodeJS.Timeout | undefined; constructor(private balanceService: BalanceService, private employeeService: EmployeeService) { if (typeof window !== 'undefined') { window.addEventListener('load', () => { this.initializeEthereumContext(); }); } } public async initializeEthereumContext() { if (typeof window.ethereum !== 'undefined') { window.ethereum.request({method: 'eth_requestAccounts'}).then(() => { this.web3 = new Web3(window.ethereum); }).catch((error: any) => { console.error('Error while initializing ethereum context:', error); }); } else { console.warn('No ethereum context found!'); } this.intervalId = setInterval(() => this.refreshAccounts(), 1000); } public async refreshAccounts() { if (this.web3 === undefined) { return; } const metamaskAccounts = await this.web3.eth.getAccounts(); if (metamaskAccounts === undefined || metamaskAccounts.length === 0) { console.warn('Couldn\'t get any accounts!'); return; } if (!this.accounts || this.accounts.length !== metamaskAccounts.length || this.accounts[0] !== metamaskAccounts[0]) { const result: Employee[] = []; for (let account of metamaskAccounts) { const balance = await this.balanceService.getCurrencyCoinBalance(account); let employee = new Employee("", account); employee.balance = Number(balance); try { this.employeeService.getEmployee(account).subscribe((employeeResult) => { if (employeeResult !== undefined) { employee.email = employeeResult.email; } }); } finally { result.push(employee); } } this.accountObservable.next(result); this.accounts = result; } if (this.accounts !== undefined && this.accounts.length > 0) { clearInterval(this.intervalId); } } public getAccounts(): Employee[] | undefined { return this.accounts; } }
import { includes } from 'lodash' import React, { Component } from 'react' import styles from './DraggableModalContainer.module.css' type Props = React.PropsWithChildren<{ draggableTarget: string; }> type State = { isDragging: boolean; currentPosition: { x: number; y: number; }; movePosition: { x: number; y: number; }; startDragPosition?: { x: number; y: number; }; } export default class DraggableModalContainer extends Component<Props, State> { constructor(props: Props) { super(props) document.addEventListener('mousedown', this.startDrag) document.addEventListener('mousemove', this.move) document.addEventListener('mouseup', this.endDrag) this.state = { isDragging: false, currentPosition: { x: 0, y: 0, }, movePosition: { x: 0, y: 0, }, } } private containerNode: HTMLDivElement | null = null private targetNodes: NodeListOf<Element> | null = null componentWillUnmount(): void { document.removeEventListener('mousedown', this.startDrag) document.removeEventListener('mousemove', this.move) document.removeEventListener('mouseup', this.endDrag) } render(): React.JSX.Element { const containerPosition = { top: this.state.movePosition.y, left: this.state.movePosition.x, } return ( <div ref={this.setContainerNode} className={styles.Container} style={containerPosition} > {this.props.children} </div> ) } private startDrag = (event: MouseEvent): void => { if (!this.targetNodes) { this.setTargetNode() } if (this.hasClickedOnTheCurrentElement(event.target)) { this.setState({ isDragging: true, startDragPosition: { x: event.x, y: event.y, }, }) } } private move = (event: MouseEvent): void => { if (this.state.isDragging) { this.setState((state) => { const newX = state.currentPosition.x + (event.x - (state.startDragPosition?.x ?? 0)) const newY = state.currentPosition.y + (event.y - (state.startDragPosition?.y ?? 0)) return { movePosition: { x: newX, y: newY, }, } }) } } private endDrag = (): void => { if (this.state.isDragging) { this.setState((state) => { return { isDragging: false, currentPosition: state.movePosition, } }) } } private hasClickedOnTheCurrentElement(target: EventTarget | null): boolean { let currentNode = target while (currentNode) { if (includes(this.targetNodes, currentNode)) { return true } currentNode = (currentNode as HTMLElement).parentNode } return false } private setTargetNode(): void { if (!this.containerNode) { return } this.targetNodes = this.containerNode.querySelectorAll(this.props.draggableTarget) } private setContainerNode = (node: HTMLDivElement | null): void => { this.containerNode = node } }
<script setup> import { reactive, ref } from "vue"; import NavBar from "./components/navbar.vue"; import FeatureCard from "./components/card.vue"; const features = reactive([ { image: "icon-access-anywhere.svg", title: "Access your files, anywhere", details: "The ability to use a smartphone, tablet or computer to access your account means your files follow you anywhere.", }, { image: "icon-security.svg", title: "Security you can trust", details: "2 factor authentication and user-controlled encryption are just a couple of the security features we allow to help secure your files.", }, { image: "icon-collaboration.svg", title: "Real-time collaboration", details: "Securely share files and folders with firends , family and collegues for live collaboratiom, No email attachments required.", }, { image: "icon-any-file.svg", title: "Store any type of file", details: "Whether you're sharing holidays photos or work documents.Fylo has you covered allowing for all the types to be securely stored and shared.", }, ]); </script> <template> <main id="app"> <NavBar /> <section class="intro"> <div class=" container flex flex-col max-w-sm items-center justify-center text-center " > <img src="./assets/images/illustration-intro.png" alt="All file in one place illustration" class="w-full" /> <h4>All your files in one secure location, accessible anywhere.</h4> <p class="larger"> Fylo stores all your most important files in one secure location. Access them wherever you need, share and collaborate with friends family, co-workers. </p> <button class="btn btn-primary">Get started</button> </div> <div class="container flex justify-center"> <div class="grid grid-cols-2 gap-2 max-w-sm"> <div v-for="feature in features" :key="feature.title" class="h-34 max-w-36" > <FeatureCard :title="feature.title" :details="feature.details" :image="feature.image" /> </div> </div> </div> </section> </main> </template> <style> body { @apply bg-black; } #app { @apply bg-primary; } h1, h2, h3, h4, h5 { @apply text-white font-semibold; } h1 { @apply text-4xl; } h2 { @apply text-3xl; } h3 { @apply text-2xl; } h4 { @apply text-xl my-4; } h5 { @apply text-lg my-3; } p { @apply text-gray-100 text-sm text-gray-300 my-1; } p.larger { @apply text-base; } .btn { @apply px-16 py-2 my-2 rounded-3xl font-semibold; } .btn-primary { @apply text-white bg-secondary-200 hover:bg-secondary; } </style>
import os import time import datetime import argparse from download import Download from extract import Extract from utils import wet_paths parser = argparse.ArgumentParser() parser.add_argument( "--path", required = True, type = str, help = "Directory storing the wet path indexes" ) # parser.add_argument( # "--dst", # required = True, # type = str, # help = "Directory to store the output result" # ) WET_DATA_DIR = "src/wet_data/" LANG_MODEL = "lid.176.bin" EXTRACTED_DIR = "src/extracted_data" def run(path_indexes): ''' Run pipeline. Parameters ---------- path_indexs: str Directory of wet index file. det: Attributes ---------- cc_path: list list of cc index path, read from directory. cc_path: str Name of cc path file in list ''' cc_paths = wet_paths.get_files(path_indexes) for cc_path in cc_paths: # 1. download ts_download = time.time() print(f"Indexes: {cc_path}") print(f"Download start at: {datetime.datetime.now()}") download = Download(cc_path, WET_DATA_DIR) is_downloaded = download.start_download() # 2. extract (get the dst from download) if not is_downloaded: print(f"Failed download:", cc_path) continue print(f"Download finish at {datetime.datetime.now()}") print(f"Download completed for {(time.time() - ts_download):.2f} sec.") ts_extract = time.time() print("Start extracting...") extract = Extract(WET_DATA_DIR, LANG_MODEL, EXTRACTED_DIR, cc_path) extract.start_extract() print(f"Extract completed for {(time.time() - ts_extract):.2f} sec") print("Done!") if __name__ == '__main__': args = parser.parse_args() path = args.path run(path)
[.white_bg] == Icons and Images image::angele-kamp-bDuh4oK_MCU-unsplash.jpg[background] [.white_bg] === Background images image::angele-kamp-bDuh4oK_MCU-unsplash.jpg[background] [source,asciidoc] ---- [.white_bg] === Background images image::angele-kamp-bDuh4oK_MCU-unsplash.jpg[background] ---- [.columns.is-vcentered] === Limited height [.column] [source,asciidoc] ---- image::martin-pechy-....jpg[height=600] ---- [.column] image::martin-pechy-iXHdGk8JVYU-unsplash.jpg[height=600] [.white_bg] === Background Images contained TIP: Use it for screenshots [source,asciidoc] ---- === ! image::martin-pechy-....jpg[background, size=contain] ---- image::martin-pechy-iXHdGk8JVYU-unsplash.jpg[background, size=contain] === icon:font-awesome[] Font Awesome icons icon:font-awesome[] With `\icon:font-awesome[]` you can improve the eye cachiness of your slides icon:search[] https://fontawesome.com/v5/search?q=world&o=r&m=free&f=brands%2Cclassic[v.5.13.0 Free and Brands icons available] icon:search[] [.columns.is-vcentered] === icon:font-awesome[] Icon customization icon:font-awesome[] [.column] -- Play with the extra variables `size` and `set` for variation as well as your css styles [source,asciidoc] ---- [.red] icon:python[set=fab,size=7x] ---- .`css/reveal-override.css` [source,css] ---- /* Main color */ .icon > i, svg { color: #009fe3; } /* Specify custom colors */ div.red > p > span.icon > i { color: red; } ---- -- [.column] [.red] icon:python[set=fab,size=7x]
<div id="Chart-<?=$id?>" class="mb"></div> <script> let ChartOptions<?=$id?> = { series: [ <?php if (is_array($metric)): ?> <?php foreach ($metric as $index => $currentMetric): ?> { name: '<?php if (is_array($name)): ?><?=$name[$index]?><?php else: ?><?=$name?><?php endif; ?>', <?php if (is_array($color)): ?>color: '<?=$color[$index]?>',<?php endif; ?> data: <?=$currentMetric?>, }, <?php endforeach; ?> <?php else: ?> { name: '<?=$name?>', color: '<?=$color?>', data: <?=$metric?>, }, <?php endif; ?> ], chart: { type: 'bar', toolbar: {show:false}, height: <?=$height ?? 300?>, <?php if (isset($animation) && $animation == false): ?> animations: {enabled: false}, <?php else: ?> animations: {enabled: true}, <?php endif; ?> <?php if (isset($stacked) && $stacked == true): ?> stacked: true, <?php if (isset($stackedTo100) && $stackedTo100 == true): ?> stackType: '100%', <?php endif; ?> <?php else: ?> stacked: false, <?php endif; ?> animations: { enabled: true, easing: 'easeinout', speed: 300, animateGradually: { enabled: true, delay: 20 }, } }, <?php if (is_array($metric) && !is_array($color)): ?> theme: { monochrome: { enabled: true, color: '<?=$color?>', shadeTo: 'light', shadeIntensity: 0.7 } }, <?php endif; ?> tooltip: { <?php if (isset($showValues) && $showValues == true): ?> enabled: false, <?php else: ?> enabled: true, <?php endif; ?> <?php if (isset($percent) && $percent == true): ?> y: { formatter: function(value) { return value + '&thinsp;%' }, }, <?php endif; ?> <?php if (isset($seconds) && $seconds == true): ?> y: { formatter: function(value) { return value + '&thinsp;s' }, }, <?php endif; ?> }, grid: { show: true, }, plotOptions: { bar: { borderRadius: 0, horizontal: false, //columnWidth: '25%', } }, <?php if (is_array($metric)): ?> stroke: { show: true, width: 1, colors: ['#fff'] }, <?php endif; ?> <?php if (isset($legend)): ?> legend: {position: '<?=$legend?>'}, <?php else: ?> legend: {show:false,}, <?php endif; ?> dataLabels: { textAnchor: 'middle', <?php if (isset($showValues) && $showValues == false): ?> enabled: false, <?php else: ?> enabled: true, <?php endif; ?> offsetX: 0, offsetY: 20, style: { fontSize: '18px', fontFamily: 'fira sans condensed, sans-serif', colors: ['#fff'] }, background: { enabled: true, foreColor: '#444', padding: 4, borderRadius: 5, borderWidth: 0, opacity: 0.5, }, }, grid: {row: {colors: ['#e5e5e5', 'transparent'], opacity: 0.2}}, xaxis: { categories: <?=$dimension?>, <?php if (isset($tickamount)): ?>tickAmount: <?=$tickamount?>,<?php endif; ?> labels: { rotate: -90, style: { <?php if (isset($xfont)): ?> fontSize: '<?=$xfont?>', <?php else: ?> fontSize: '12px', <?php endif; ?> fontFamily: 'fira sans, sans-serif', fontWeight: 400, }, <?php if (isset($prefix)): ?> formatter: function (value) { return '<?=$prefix?>' + value; }, <?php endif; ?> <?php if (isset($suffix)): ?> formatter: function (value) { return value + '<?=$suffix?>'; }, <?php endif; ?> }, }, yaxis: { tickAmount: 4, labels: { rotate: 0, //formatter: function(val) {return val.toFixed(1);} }, } }; let Chart<?=$id?> = new ApexCharts(document.querySelector("#Chart-<?=$id?>"), ChartOptions<?=$id?>); Chart<?=$id?>.render(); </script>
export function createStore(rootReducer, initialState = {}) { let state = rootReducer({ ...initialState }, { type: "__INIT__" }); let listeners = []; return { subscribe(fn) { listeners.push(fn); return { unsubscribe() { listeners = listeners.filter((l) => l !== fn); }, }; }, dispatch(action) { state = rootReducer(state, action); listeners.forEach((listener) => listener(state)); }, getState() { return JSON.parse(JSON.stringify(state)); }, }; } // Class example // export class createStore { // constructor(rootReducer, initialState) { // (this.rootReducer = rootReducer), // (this.state = this.rootReducer( // { ...initialState }, // { type: "__INIT__" } // )); // this.listeners = []; // } // subscribe(fn) { // this.listeners.push(fn); // return { // unsubscribe: () => { // this.listeners = this.listeners.filter((l) => l !== fn); // }, // }; // } // dispatch(action) { // state = this.rootReducer(state, action); // this.listeners.forEach((listener) => listener(state)); // } // getState() { // return this.state; // } // }
package com.health.service; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.health.model.User; public class MyUserDetails implements UserDetails{ private String username; private String password; private boolean active; private String role; public MyUserDetails() { // TODO Auto-generated constructor stub } public MyUserDetails(User user) { this.username=user.getUsername(); this.password=user.getPassword(); this.active=user.isEnabled(); this.role=user.getRole().getRoleName(); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { // TODO Auto-generated method stub List<GrantedAuthority> authorities=new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(role)); return authorities; } @Override public String getPassword() { // TODO Auto-generated method stub return password; } @Override public String getUsername() { // TODO Auto-generated method stub return username; } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return true; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return active; } @Override public String toString() { return "MyUserDetails [username=" + username + ", password=" + password + ", active=" + active + ", role=" + role + "]"; } }
package com.pb.nikolaenko.hw14; import java.io.*; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; class ClientWork { // Объявляем рабочие переменные private Socket socket; private BufferedReader in; // поток чтения из сокета private BufferedWriter out; // поток чтения в сокет private BufferedReader inputUser; // поток чтения с консоли private String addr; // ip адрес клиента private int port; // порт соединения private String clientName; // имя клиента private Date dateTime; private String stringTime; private SimpleDateFormat time; // Обмен сообщениями клиент-сервер public ClientWork(String addr, int port) { this.addr = addr; this.port = port; try { this.socket = new Socket(addr, port); } catch (IOException e) { System.err.println("Ошибка подключения"); } try { inputUser = new BufferedReader(new InputStreamReader(System.in)); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); this.inputClientName(); new ReadMsg().start(); new WriteMsg().start(); } catch (IOException e) { ClientWork.this.clientShutdown(); } } // Ввод имени пользователя (клиента) private void inputClientName() { System.out.print("Введите свое имя: "); try { clientName = inputUser.readLine(); out.write("Начинаем общение, " + clientName + "! Для завершения достаточно ввести \"end\".\n"); out.flush(); } catch (IOException ignored) { } } // Корректное завершение подключения private void clientShutdown() { try { if (!socket.isClosed()) { socket.close(); in.close(); out.close(); } } catch (IOException ignored) {} } // Получение сообщений от сервера private class ReadMsg extends Thread { @Override public void run() { String str; try { while (true) { str = in.readLine(); if (str.equals("end")) { ClientWork.this.clientShutdown(); break; } System.out.println(str); } } catch (IOException e) { ClientWork.this.clientShutdown(); } } } // Передача сообщений на сервер public class WriteMsg extends Thread { @Override public void run() { while (true) { String userMessage; try { dateTime = new Date(); time = new SimpleDateFormat("HH:mm:ss"); stringTime = time.format(dateTime); userMessage = inputUser.readLine(); if (userMessage.equals("end")) { out.write("end" + "\n"); ClientWork.this.clientShutdown(); break; } else { out.write("(" + stringTime + ") " + clientName + ": " + userMessage + "\n"); } out.flush(); } catch (IOException e) { ClientWork.this.clientShutdown(); } } } } }
package com.avs.habithero.ui.fragments import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.avs.habithero.R import com.avs.habithero.databinding.FragmentStatsBinding import com.avs.habithero.models.Habit import com.avs.habithero.repositories.HabitRepository import com.avs.habithero.viewmodel.StatsViewModel import com.github.mikephil.charting.components.Legend import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.data.BarData import com.github.mikephil.charting.data.BarDataSet import com.github.mikephil.charting.data.BarEntry import com.github.mikephil.charting.formatter.IndexAxisValueFormatter import com.github.mikephil.charting.formatter.ValueFormatter class StatsFragment: Fragment() { private var _binding: FragmentStatsBinding? = null private val binding get() = _binding!! private lateinit var viewModel: StatsViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentStatsBinding.inflate(inflater, container, false) viewModel = StatsViewModel(HabitRepository()) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeHabits() } private fun observeHabits() { viewModel.habits.observe(viewLifecycleOwner) { habits -> if (habits != null && habits.isNotEmpty()) { setupBarChart(habits) } else { Log.d("StatsFragment", "No se recibieron hábitos o la lista está vacía") } } } // Método que configura el gráfico de barras con los hábitos recibidos // El gráfico viene dado por MPAndroidChart private fun setupBarChart(habits: List<Habit>) { val (completed, notCompleted) = viewModel.calculateHabitsCompletion(habits) val entriesCompleted = mutableListOf<BarEntry>() val entriesNotCompleted = mutableListOf<BarEntry>() for (i in completed.indices) { entriesCompleted.add(BarEntry(i.toFloat(), completed[i])) entriesNotCompleted.add(BarEntry(i.toFloat(), notCompleted[i])) } val dataSetCompleted = createDataSet(entriesCompleted, getString(R.string.completed), android.R.color.holo_green_light) val dataSetNotCompleted = createDataSet(entriesNotCompleted, getString(R.string.incompleted), android.R.color.holo_red_light) val data = BarData(dataSetCompleted, dataSetNotCompleted) data.barWidth = 0.4f configureChartAxis() configureLegend() binding.chartDaily.apply { description.text = "" this.data = data groupBars(-0.5f, 0.1f, 0.05f) invalidate() } } private fun configureChartAxis() { val daysOfWeek = listOf( getString(R.string.monday), getString(R.string.tuesday), getString(R.string.wednesday), getString(R.string.thursday), getString(R.string.friday), getString(R.string.saturday), getString(R.string.sunday) ) binding.chartDaily.apply { xAxis.apply { position = XAxis.XAxisPosition.BOTTOM granularity = 1f setDrawGridLines(false) valueFormatter = IndexAxisValueFormatter(daysOfWeek) axisMinimum = -0.5f axisMaximum = 6.5f } axisLeft.apply { axisMinimum = 0f granularity = 1f valueFormatter = object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return value.toInt().toString() } } } axisRight.isEnabled = false } } private fun configureLegend() { binding.chartDaily.legend.apply { verticalAlignment = Legend.LegendVerticalAlignment.TOP horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT orientation = Legend.LegendOrientation.HORIZONTAL setDrawInside(false) yOffset = 12f } } private fun createDataSet(entries: List<BarEntry>, label: String, color: Int): BarDataSet { return BarDataSet(entries, label).apply { setColor(resources.getColor(color, null)) setDrawValues(false) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hexcolor/hexcolor.dart'; import 'package:wazzaf/styles/colors/colors.dart'; ThemeData lightTheme = ThemeData( primarySwatch: Colors.amber, scaffoldBackgroundColor: Colors.yellow[50], appBarTheme: AppBarTheme( titleSpacing: 20.0, systemOverlayStyle: SystemUiOverlayStyle( statusBarIconBrightness: Brightness.light, statusBarColor: Colors.amber[50]), backgroundColor: Colors.yellow[50], elevation: 0.0, iconTheme: const IconThemeData(color: Colors.black), titleTextStyle: const TextStyle( fontFamily: 'Oswald', color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.bold)), textTheme: const TextTheme( bodyText1: TextStyle( fontSize: 18.0, fontWeight: FontWeight.w600, color: Colors.black), subtitle1: TextStyle( fontSize: 16.0, fontWeight: FontWeight.w600, color: Colors.black, height: 1.3), ), fontFamily: 'Oswald'); ThemeData darkTheme = ThemeData( primarySwatch: Colors.amber, scaffoldBackgroundColor: HexColor('333739'), appBarTheme: AppBarTheme( titleSpacing: 20.0, systemOverlayStyle: SystemUiOverlayStyle( statusBarIconBrightness: Brightness.dark, statusBarColor: Colors.amber[50]), backgroundColor: Colors.amber[300], elevation: 0.0, iconTheme: const IconThemeData(color: Colors.black), titleTextStyle: const TextStyle( fontFamily: 'Oswald', color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)), textTheme: const TextTheme( bodyText1: TextStyle( fontSize: 18.0, fontWeight: FontWeight.w600, color: Colors.white), subtitle1: TextStyle( fontSize: 16.0, fontWeight: FontWeight.w600, color: Colors.white, height: 1.3), ), fontFamily: 'Oswald');
/* create EventTarget class with methods //addEventListener //input: name of event as string, callback function to be called when event is dispatched to target //target should be able to have multiple event listeneres for same event eg. target.addEventListener('click', onClick) target.addEventListener('click', onClick1) //removeEventListener input: name of event as string, callback function to be called when event is dispatched to target removes the relevant event listener eg. target.removeEventListener('click', onClick) should undo effects of addEventListener //if no current event listener for the args, removeEventListener has no effect //if 2 diff callbacks added for same event, removing listener from one event shouldn't affect other eg. click event removed from onClick, should not affect onClick1 click event //dispatchEvent input: name of event as string //if no event listeners -> no affect //if event listeners -> dispatchEvent invokes callback functions of event listeners eg. dispatchEvent('click') -> calls onClick //can be invoked multiple times //2 event targets w same event listener -> dispatch event to one target w/out triggering the other target event.events = { click: [onClick1, onClick2..], hello: [logHello], world: [logWorld] } addEventListener callbacks logHello = () => console.log('hello') logWorld = () => console.log('world') makes it so when you call dispatch on an event with the name, it knows which callback func to call dispatch */ // class EventTarget { // constructor() { // this.events = {} // } // addEventListener(name, callback) { // //check if event name is already in obj // //if it is , check if its array already includes the callback // //if event exists, but callback not in arr -> push to arr // //if event exists and callback is already in array -> nothing // //if event name is not in object, instantiate new set // if (this.events[name]) { // if (!this.events[name].has(callback)) { // this.events[name].add(callback) // } // } // else this.events[name] = new Set().add(callback) // } // removeEventListener(name, callback) { // if (this.events[name] && this.events[name].has(callback)) this.events[name].delete(callback) // } // dispatchEvent(name) { // if (this.events[name]) { // this.events[name].forEach(callback => callback()) // } // } // } //optimized class EventTarget { constructor() { this.events = new Map() } addEventListener(name, callback) { if(!this.events.has(name)) this.events.set(name, new Set()); this.events.get(name).add(callback); } removeEventListener(name, callback) { this.events.get(name)?.delete(callback); } dispatchEvent(name) { this.events.get(name)?.forEach(callback => callback()); } } logHello = () => console.log('hello') logHello1 = () => console.log('hello1') logHello2 = () => console.log('hello2') logHello3 = () => console.log('hello3') logWorld = () => console.log('world') const target = new EventTarget(); target.addEventListener('hello', logHello); target.addEventListener('hello', logHello1); target.addEventListener('hello', logHello2); target.addEventListener('world', logWorld); // target.dispatchEvent('hello') // target.dispatchEvent('world') target.removeEventListener('hello', logHello) target.dispatchEvent('hello') // target.dispatchEvent('world') // target.removeEventListener('job') console.log(target.events)
/******************************************************************************* * PSHDL is a library and (trans-)compiler for PSHDL input. It generates * output suitable for implementation or simulation of it. * * Copyright (C) 2014 Karsten Becker (feedback (at) pshdl (dot) org) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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/>. * * This License does not grant permission to use the trade names, trademarks, * service marks, or product names of the Licensor, except as required for * reasonable and customary use in describing the origin of the Work. * * Contributors: * Karsten Becker - initial API and implementation ******************************************************************************/ package org.pshdl.model; import java.util.ArrayList; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.pshdl.model.impl.AbstractHDLInstantiation; import org.pshdl.model.utils.HDLQuery.HDLFieldAccess; /** * The class HDLInstantiation contains the following fields * <ul> * <li>IHDLObject container. Can be <code>null</code>.</li> * <li>ArrayList&lt;HDLAnnotation&gt; annotations. Can be <code>null</code>.</li> * <li>HDLVariable var. Can <b>not</b> be <code>null</code>.</li> * <li>ArrayList&lt;HDLArgument&gt; arguments. Can be <code>null</code>.</li> * </ul> */ public abstract class HDLInstantiation extends AbstractHDLInstantiation { /** * Constructs a new instance of {@link HDLInstantiation} * * @param id * a unique ID for this particular node * @param container * the value for container. Can be <code>null</code>. * @param annotations * the value for annotations. Can be <code>null</code>. * @param var * the value for var. Can <b>not</b> be <code>null</code>. * @param arguments * the value for arguments. Can be <code>null</code>. * @param validate * if <code>true</code> the parameters will be validated. */ public HDLInstantiation(int id, @Nullable IHDLObject container, @Nullable Iterable<HDLAnnotation> annotations, @Nonnull HDLVariable var, @Nullable Iterable<HDLArgument> arguments, boolean validate) { super(id, container, annotations, var, arguments, validate); } public HDLInstantiation() { super(); } /** * Returns the ClassType of this instance */ @Override public HDLClass getClassType() { return HDLClass.HDLInstantiation; } /** * The accessor for the field annotations which is of type ArrayList&lt;HDLAnnotation&gt;. */ public static HDLFieldAccess<HDLInstantiation, ArrayList<HDLAnnotation>> fAnnotations = new HDLFieldAccess<HDLInstantiation, ArrayList<HDLAnnotation>>("annotations", HDLAnnotation.class, HDLFieldAccess.Quantifier.ZERO_OR_MORE) { @Override public ArrayList<HDLAnnotation> getValue(HDLInstantiation obj) { if (obj == null) { return null; } return obj.getAnnotations(); } @Override public HDLInstantiation setValue(HDLInstantiation obj, ArrayList<HDLAnnotation> value) { if (obj == null) { return null; } return obj.setAnnotations(value); } }; /** * The accessor for the field var which is of type HDLVariable. */ public static HDLFieldAccess<HDLInstantiation, HDLVariable> fVar = new HDLFieldAccess<HDLInstantiation, HDLVariable>("var", HDLVariable.class, HDLFieldAccess.Quantifier.ONE) { @Override public HDLVariable getValue(HDLInstantiation obj) { if (obj == null) { return null; } return obj.getVar(); } @Override public HDLInstantiation setValue(HDLInstantiation obj, HDLVariable value) { if (obj == null) { return null; } return obj.setVar(value); } }; /** * The accessor for the field arguments which is of type ArrayList&lt;HDLArgument&gt;. */ public static HDLFieldAccess<HDLInstantiation, ArrayList<HDLArgument>> fArguments = new HDLFieldAccess<HDLInstantiation, ArrayList<HDLArgument>>("arguments", HDLArgument.class, HDLFieldAccess.Quantifier.ZERO_OR_MORE) { @Override public ArrayList<HDLArgument> getValue(HDLInstantiation obj) { if (obj == null) { return null; } return obj.getArguments(); } @Override public HDLInstantiation setValue(HDLInstantiation obj, ArrayList<HDLArgument> value) { if (obj == null) { return null; } return obj.setArguments(value); } }; @Override public HDLFieldAccess<?, ?> getContainingFeature(Object obj) { if (annotations.contains(obj)) { return fAnnotations; } if (var == obj) { return fVar; } if (arguments.contains(obj)) { return fArguments; } return super.getContainingFeature(obj); } // $CONTENT-BEGIN$ // $CONTENT-END$ }
<script setup lang="ts"> import { ref } from 'vue' import HelloWorld from '@/components/Parent.vue' import useFetch from '@/hooks/useFetcher' import { computed } from 'vue' // Custom hook const { data, isPending, isSuccess, isError, error } = useFetch('queryKey', { url: '/api/search', params: { part: 'snippet', q: 'music', type: 'video,playlist,channel', maxResults: 20, safeSearch: 'strict', key: 'AIzaSyBGf5faKOkeLceCwRfN0fv4LJ1CWKrjG-U', }, }) console.log(data) const count = ref<number>(0) const num1 = ref<number>(50) const num2 = ref<number>(10) const sum = computed(() => num1.value + num2.value) const increment = () => { count.value++ } </script> <template> <!-- {{ (count as number).toFixed(1) }} --> <!-- <button @click="increment">증가</button> --> <v-row no-gutters> <v-col> <!-- <v-sheet class="pa-2 ma-2"> .v-col-auto </v-sheet> --> </v-col> <v-col cols="2"> <h1>This is App</h1> <HelloWorld /> <br /> <br /> <v-sheet class="pa-2 ma-2"> <v-text-field label="값1" variant="outlined" v-model.number="num1"></v-text-field> <v-text-field label="값2" variant="outlined" v-model.number="num2"></v-text-field> <!-- <v-btn prepend-icon="$vuetify"> 합산 </v-btn> --> </v-sheet> <v-sheet class="pa-2 ma-2"> <div> <span>computed sum:</span> <br /> <h3>{{ sum }}</h3> </div> </v-sheet> <br /> <br /> <!-- <v-sheet class="pa-2 ma-2"> <h2>사용자 리스트 (useQuery)</h2> <div v-if="isPending"><h1>Loading...</h1></div> <div v-else-if="isError">An error has occurred: {{ error }}</div> <div v-else> <ul v-if="isSuccess"> <li v-for="item in data.items" :key="item.id"> <a>{{ item.name }}</a> </li> </ul> </div> </v-sheet> --> </v-col> <v-col> <!-- <v-sheet class="pa-2 ma-2"> .v-col-auto </v-sheet> --> </v-col> </v-row> </template>
import 'dart:async'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:twitter_clone_client/twitter_clone_client.dart'; import '../../repositories/post_repository.dart'; part 'feed_event.dart'; part 'feed_state.dart'; class FeedBloc extends Bloc<FeedEvent, FeedState> { final PostRepository _postRepository; FeedBloc({ required PostRepository postRepository, }) : _postRepository = postRepository, super(const FeedState()) { on<FeedLoadEvent>(_onLoadFeed); on<FeedCreatePostEvent>(_onCreatePost); on<FeedDeletePostEvent>(_onDeletePost); } Future<void> _onLoadFeed( FeedLoadEvent event, Emitter<FeedState> emit, ) async { emit(state.copyWith(status: FeedStatus.loading)); try { final posts = await _postRepository.getPosts(); emit(state.copyWith(status: FeedStatus.loaded, posts: posts)); } catch (_) { emit(state.copyWith(status: FeedStatus.error)); } } Future<void> _onCreatePost( FeedCreatePostEvent event, Emitter<FeedState> emit, ) async { try { await _postRepository.createPost(event.post); add(const FeedLoadEvent()); } catch (_) { emit(state.copyWith(status: FeedStatus.error)); } } Future<void> _onDeletePost( FeedDeletePostEvent event, Emitter<FeedState> emit, ) async { try { await _postRepository.deletePost(event.post); add(const FeedLoadEvent()); } catch (_) { emit(state.copyWith(status: FeedStatus.error)); } } }
import { useForm } from "react-hook-form"; import { useNavigate } from "react-router-dom"; import { useRegisterUserMutation } from "../redux/features/auth/authApiSlice"; import { useEffect } from "react"; import { toast } from "react-toastify"; const RegisterTwo = () => { const navigate = useNavigate(); const { register, formState: { errors }, handleSubmit, reset } = useForm(); const [registerUser, { isLoading, isSuccess, isError, error }] = useRegisterUserMutation(); console.log({ error }) const onSubmit = async (data) => { if (data.password !== data.confirm_password) { toast.error("password and confirm password must have to same") } else { const info = { password: data?.password, email: data?.email } await registerUser(info) reset() } } useEffect(() => { if (isSuccess) { navigate('/login') toast("check email to verify your email") } if (isError) { toast.error(error.data.errorMessage[0].message) } }, [isLoading]) return ( <div className="mx-8"> <div className="flex items-center gap-20 mt-6"> <img onClick={() => navigate(-1)} className="h-9 w-9" src="https://cdn-icons-png.flaticon.com/128/3877/3877262.png" alt="" /> <h2 className="font-bold text-black text-[22px] text-center"> Registrati </h2> </div> <form onSubmit={handleSubmit(onSubmit)}> <div className="flex items-center space-x-2 bg-base-200 p-2 border border-black w-80 py-4 mt-8 "> <input type="text" placeholder="Email" {...register("email", { required: { value: true, message: "email is required" } })} className="focus:outline-0 placeholder:text-sm font-md placeholder:text-black bg-base-200 w-full" /> </div> {errors.email?.type === 'required' && <p className="text-red-500 text-xs italic">{errors.email.message}</p>} <div className="mb-4 mt-6 relative"> <div className="flex items-center space-x-2 bg-base-200 p-2 border border-black w-80 py-4 "> <input type="text" placeholder="Password" {...register("password", { required: { value: true, message: "password is required" } })} className="focus:outline-0 placeholder:text-[18px] font-sans placeholder:text-black bg-base-200 w-full" /> <span> {" "} <img className="h-6 w-6" src="https://cdn-icons-png.flaticon.com/128/9428/9428781.png" alt="" /> </span> </div> </div> {errors.password?.type === 'required' && <p className="text-red-500 text-xs italic">{errors.password.message}</p>} <div className="mb-4 mt-6 relative"> <div className="flex items-center space-x-2 bg-base-200 p-2 border border-black w-80 py-4 "> <input type="text" placeholder="Ripeti password" {...register("confirm_password", { required: { value: true, message: "confirm password is required" } })} className="focus:outline-0 placeholder:text-[18px] font-sans placeholder:text-black bg-base-200 w-full" /> <span> {" "} <img className="h-6 w-6" src="https://cdn-icons-png.flaticon.com/128/9428/9428781.png" alt="" /> </span> </div> </div> {errors.confirm_password?.type === 'required' && <p className="text-red-500 text-xs italic">{errors.confirm_password.message}</p>} <div className="flex items-center mt-6 gap-2"> <input type="checkbox" className="mr-2 w-5 h-5" /> <p className="text-md">Accetto termini e condizioni</p> </div> <button type="submit" className="bg-black text-white font-bold py-4 focus:outline-none focus:shadow-outline w-80 font-sans text-[20px] mt-7"> Register </button> </form> </div> ); }; export default RegisterTwo;
import React, {useState, useRef} from 'react'; import { View, TextInput, TouchableOpacity, Text, StyleSheet, SafeAreaView, } from 'react-native'; import {useSelector, useDispatch} from 'react-redux'; import {Formik} from 'formik'; import * as Yup from 'yup'; import Colors from '../styles/Colors'; import Metrics from '../styles/Metrics'; import Fonts from '../styles/Fonts'; import Icon from 'react-native-vector-icons/dist/FontAwesome'; import axios from 'axios'; import {GUID, URLS} from '../networks'; import {setUser, setCart} from '../redux/actions'; import AsyncStorage from '@react-native-async-storage/async-storage'; const Profile = () => { const [secure, setSecure] = useState(true); const user = useSelector(state => state.user); const dispatch = useDispatch(); const passwordRef = useRef(); const initialValues = { email: '[email protected]', password: 'at253545', }; const validationSchema = Yup.object().shape({ email: Yup.string() .email('Please enter a valid email address.') .required('Email address is required.'), password: Yup.string().required('Password field cannot be empty.'), }); const eyeIconOnPress = () => { setSecure(!secure); }; const onSubmitEditing = () => { passwordRef.current.focus(); }; const onSubmit = async values => { await axios .post( URLS.login, { username: values.email, password: values.password, }, { headers: { GUID: GUID, }, }, ) .then(({data}) => { console.log(data); dispatch( setUser({ firstName: 'Akıllı', lastName: 'Ticaret', email: values.email, isLoggedIn: true, }), ); getCart(data.data.token); AsyncStorage.setItem('token', data.data.token); AsyncStorage.setItem('expiration', data.data.expiration); AsyncStorage.setItem('refreshToken', data.data.refreshToken); }); }; const getCart = token => { axios .get(URLS.cart, { headers: { GUID: GUID, Authorization: `Bearer ${token}`, }, }) .then(({data}) => { dispatch(setCart(data.data)); }); }; return ( <SafeAreaView style={styles.container}> <View style={styles.logoContainer}> <Text style={styles.logo}>Akıllı Ticaret</Text> </View> {user.isLoggedIn ? ( <View> <Text style={styles.email}>{user.email}</Text> </View> ) : ( <Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}> {({values, handleChange, handleSubmit, errors}) => ( <View style={styles.form}> <TextInput style={[styles.input, errors.email && {borderColor: 'red'}]} value={values.email} onChangeText={handleChange('email')} placeholder="Email*" keyboardType="email-address" returnKeyType="next" onSubmitEditing={onSubmitEditing} /> <View> <TextInput ref={passwordRef} style={[ styles.input, errors.password && {borderColor: 'red'}, ]} value={values.password} onChangeText={handleChange('password')} placeholder="Password*" secureTextEntry={secure} returnKeyType="done" onSubmitEditing={handleSubmit} /> <TouchableOpacity style={styles.icon} onPress={eyeIconOnPress}> <Icon name={secure ? 'eye-slash' : 'eye'} size={Metrics(20)} color={Colors.black} /> </TouchableOpacity> </View> <TouchableOpacity onPress={handleSubmit} style={styles.button}> <Text style={styles.buttonText}>Log In</Text> </TouchableOpacity> </View> )} </Formik> )} </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.white, alignItems: 'center', justifyContent: 'center', }, form: {alignItems: 'center'}, input: { width: Metrics(320), height: Metrics(50), backgroundColor: Colors.categoryBorder, marginBottom: Metrics(10), borderRadius: 10, paddingHorizontal: Metrics(10), fontFamily: Fonts.regular, borderWidth: 1, borderColor: Colors.categoryBorder, }, button: { width: Metrics(100), height: Metrics(50), backgroundColor: Colors.primary, borderRadius: 10, alignItems: 'center', justifyContent: 'center', marginTop: Metrics(20), }, buttonText: { fontFamily: Fonts.regular, color: Colors.white, fontSize: Fonts.size(14), }, logoContainer: { backgroundColor: Colors.primary, padding: Metrics(10), borderRadius: 10, marginBottom: Metrics(50), }, logo: { fontFamily: Fonts.bold, color: Colors.white, fontSize: Fonts.size(30), }, icon: {position: 'absolute', right: Metrics(10), top: Metrics(15)}, email: {fontFamily: Fonts.regular}, }); export default Profile;
<div> <div *ngIf="isEdit"> <div class="header"><span>{{'add.title' | translate}}</span></div> <div class="container"> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" class="main-content"> <div nz-col nzXs="24" nzSm="24" nzMd="24" nzLg="24"> <form nz-form [formGroup]="validateForm"> <div class="group-content"> <div class="group-label"><span nz-icon nzType="home" style="margin-right: 8px;"></span>{{'add.overview' | translate}}</div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.roomType' | translate}}<span class="mark-require">*</span></div> <div *ngFor="let key of ['roomType']"> <nz-form-item> <nz-form-control > <nz-select [formControlName]="key" [nzOptions]="roomTypeList" style="width:100%;" [nzPlaceHolder]="'add.roomType' | translate"></nz-select> </nz-form-control> </nz-form-item> </div> <!-- <nz-select ngModel="room" [nzOptions]="roomTypeList" [ngModelOptions]="{standalone: true}" style="width:100%; margin-bottom: 24px;" (ngModelChange)="onChangeValue('roomType', $event)"></nz-select> --> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.roomStatus' | translate}}<span class="mark-require">*</span></div> <div *ngFor="let key of ['roomStatus']"> <nz-form-item> <nz-form-control > <nz-select [formControlName]="key" [nzOptions]="roomStatusList" style="width:100%;" [nzPlaceHolder]="'add.roomStatus' | translate"></nz-select> </nz-form-control> </nz-form-item> </div> <!-- <nz-select ngModel="available" [nzOptions]="roomStatusList" [ngModelOptions]="{standalone: true}" style="width:100%; margin-bottom: 24px;" (ngModelChange)="onChangeValue('roomStatus', $event)"></nz-select> --> </div> </div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.roomName' | translate}}<span class="mark-require">*</span></div> <div *ngFor="let key of ['roomName']"> <nz-form-item> <nz-form-control > <input type="text" nz-input [formControlName]="key" [placeholder]="'add.roomName' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.floor' | translate}}</div> <div *ngFor="let key of ['numberOfFloors']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.floorShort' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.area' | translate}} (m<sup>2</sup> {{'add.eachFloor' | translate}})<span class="mark-require">*</span></div> <div *ngFor="let key of ['area']" style="max-width: 600px;"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.areaFloor' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.duration' | translate}}</div> <div *ngFor="let key of ['duration']"> <nz-form-item> <nz-form-control > <nz-select [formControlName]="key" [nzOptions]="durationList" style="width:100%;" [nzPlaceHolder]="'add.duration' | translate"></nz-select> </nz-form-control> </nz-form-item> </div> </div> </div> </div> <div class="seperator"></div> <div class="group-content"> <div class="group-label"><span nz-icon nzType="dollar" style="margin-right: 8px;"></span>{{'add.price' | translate}}</div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="12"> <div class="label">{{'add.priceMonth' | translate}}<span class="mark-require">*</span></div> <div *ngFor="let key of ['price']" style="display: flex;"> <nz-form-item style="width: 60%" > <nz-form-control> <input type="number" nz-input [formControlName]="key" [placeholder]="'add.price' | translate"/> </nz-form-control> </nz-form-item> <nz-form-item style="width: 40%; height: 32px;"> <nz-form-control > <nz-select formControlName="currencyUnit" nzPlaceHolder="Unit" (ngModelChange)="onChangeValue('currencyUnit', $event)"> <nz-option *ngFor="let unit of currencyUnits" [nzValue]="unit" [nzLabel]="unit"></nz-option> </nz-select> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="12"> <div class="label">{{'add.depositLabel' | translate}}<span class="mark-require">*</span></div> <div *ngFor="let key of ['deposit']" style="display: flex;"> <nz-form-item style="width: 60%"> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.deposit' | translate"/> </nz-form-control> </nz-form-item> <nz-select [ngModel]="selectedCurrencyUnits" [ngModelOptions]="{standalone:true}" nzDisabled style="width: 40%; height: 32px;"> <nz-option [nzValue]="selectedCurrencyUnits" [nzLabel]="selectedCurrencyUnits"></nz-option> </nz-select> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="12"> <div class="label">{{'add.electricPriceLabel' | translate}} {{'add.standardPrice' | translate}}</div> <div *ngFor="let key of ['electricPrice']" style="display: flex;"> <nz-form-item style="width: 60%"> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.electricPrice' | translate" /> </nz-form-control> </nz-form-item> <nz-select [ngModel]="selectedCurrencyUnits" [ngModelOptions]="{standalone:true}" nzDisabled style="width: 40%; height: 32px;"> <nz-option [nzValue]="selectedCurrencyUnits" [nzLabel]="selectedCurrencyUnits"></nz-option> </nz-select> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="12"> <div class="label">{{'add.waterPrice' | translate}}/m<sup>3</sup> {{'add.standardPrice' | translate}}</div> <div *ngFor="let key of ['waterPrice']" style="display: flex;"> <nz-form-item style="width: 60%" > <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.waterPrice' | translate" /> </nz-form-control> </nz-form-item> <nz-select [ngModel]="selectedCurrencyUnits" [ngModelOptions]="{standalone:true}" nzDisabled style="width: 40%; height: 32px;"> <nz-option [nzValue]="selectedCurrencyUnits" [nzLabel]="selectedCurrencyUnits"></nz-option> </nz-select> </div> </div> </div> </div> <div class="seperator"></div> <div class="group-content"> <div class="group-label"> <span nz-icon nzType="info-circle" style="margin-right: 8px;"></span>{{'add.moreInfo' | translate}} </div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.direction' | translate}}</div> <div *ngFor="let key of ['directions']"> <nz-form-item> <nz-form-control > <nz-select [formControlName]="key" [nzOptions]="directionList" style="width:100%;" [nzPlaceHolder]="'add.direction' | translate"></nz-select> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.sameHouseWithOwner' | translate}}</div> <div *ngFor="let key of ['sameHouseWithOwner']"> <nz-form-item> <nz-form-control > <nz-select [formControlName]="key" [nzOptions]="yesNoList" style="width:100%;" [nzPlaceHolder]="'add.sameHouseWithOwner' | translate"></nz-select> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.renterRequirement' | translate}}</div> <div *ngFor="let key of ['renterRequirement']"> <nz-form-item> <nz-form-control > <nz-select [formControlName]="key" [nzOptions]="renterRequirementList" style="width:100%;" [nzPlaceHolder]="'add.renterRequirement' | translate"></nz-select> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.parkingArea' | translate}}</div> <div *ngFor="let key of ['hasParkingArea']"> <nz-form-item> <nz-form-control > <nz-select [formControlName]="key" [nzOptions]="yesNoList" style="width:100%;" [nzPlaceHolder]="'add.parkingArea' | translate"></nz-select> </nz-form-control> </nz-form-item> </div> </div> </div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.washingMachine' | translate}}</div> <div *ngFor="let key of ['numberOfWashingMachine']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.washingMachine' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.air-conditioner' | translate}}</div> <div *ngFor="let key of ['numberOfAirConditioners']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.air-conditioner' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.water-heater' | translate}}</div> <div *ngFor="let key of ['numberOfWaterHeaters']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.water-heater' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.wardrobe' | translate}}</div> <div *ngFor="let key of ['numberOfWardrobes']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.wardrobe' | translate" /> </nz-form-control> </nz-form-item> </div> </div> </div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.bathroom' | translate}}</div> <div *ngFor="let key of ['numberOfBathrooms']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.bathroom' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.bedroom' | translate}}</div> <div *ngFor="let key of ['numberOfBedrooms']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.bedroom' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.bed' | translate}}</div> <div *ngFor="let key of ['numberOfBeds']"> <nz-form-item> <nz-form-control > <input type="number" nz-input [formControlName]="key" [placeholder]="'add.bed' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="label">{{'add.note' | translate}}</div> <div *ngFor="let key of ['note']"> <nz-form-item> <nz-form-control > <textarea nz-input [formControlName]="key" [placeholder]="'add.note' | translate" nzAutosize></textarea> </nz-form-control> </nz-form-item> </div> </div> </div> </div> <div class="seperator"></div> <div class="group-content"> <div class="group-label"><span nz-icon nzType="environment" style="margin-right: 8px;"></span>{{'add.motelLocation' | translate}}</div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="12"> <div class="label">{{'add.address' | translate}} {{'add.addressSuggest' | translate}}<span class="mark-require">*</span></div> <div *ngFor="let key of ['address']"> <nz-form-item> <nz-form-control > <input type="text" #inputField nz-input [formControlName]="key" [placeholder]="'add.address' | translate" /> </nz-form-control> </nz-form-item> </div> </div> <div class="item" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="12"> <div class="label">{{'add.location' | translate}}<span class="mark-require">*</span></div> <div *ngFor="let key of ['location']"> <nz-form-item> <nz-form-control > <nz-cascader [nzOptions]="provinceList" [ngModelOptions]="{standalone: true}" [(ngModel)]="location" [nzShowSearch]="true" class="form-location-picker" [nzPlaceHolder]="'add.location' | translate"></nz-cascader> </nz-form-control> </nz-form-item> </div> </div> </div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24"> <div style="margin-bottom: 10px;">{{'add.instructionMap' | translate}}</div> <nz-form-item> <nz-form-control > <div map-component [latLng]="latLng" (placeChanged)="onPlaceChange($event)"></div> </nz-form-control> </nz-form-item> </div> </div> </div> <div class="seperator"></div> <div class="group-content"> <div class="group-label"><span nz-icon nzType="camera" style="margin-right: 8px;"></span>{{'add.imageMotel' | translate}}</div> <div nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="item" nz-col nzXs="24"> <div style="margin-bottom: 10px; font-size: 16px;">{{'add.uploadInstruction' | translate}}</div> <div *ngIf="previews.length" class="image-container"> <div><span class="icon-watch-image" nz-icon nzType="left" nzTheme="outline" (click)="prevImage()"></span></div> <nz-carousel nzEffect="scrollx" nzDotPosition="top" (nzBeforeChange)="onChangeImageIndex($event)"> <div nz-carousel-content *ngFor="let image of previews"> <img class="image-preview" [src]="image"> </div> </nz-carousel> <div><span class="icon-watch-image" nz-icon nzType="right" nzTheme="outline" (click)="nextImage()"></span></div> </div> <div class="button-image-container" nz-row [nzGutter]="{ xs: 8, sm: 16, md: 24, lg: 24 }" style="width:100%;"> <div class="image-button label" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <label for="many-files"> <div class="choose-image-button label"> <span>{{'add.upload' | translate}}</span> </div> </label> <input type="file" id="many-files" class="hidden" accept="image/png, image/jpeg" multiple (change)="onChangeImage($event)"> </div> <div class="image-button label" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="choose-image-button danger-button label" (click)="confirmDeleteImage('one')"> <span>{{'add.deleteOne' | translate}}</span> </div> </div> <div class="image-button label" nz-col nzXs="24" nzSm="12" nzMd="12" nzLg="6"> <div class="choose-image-button danger-button label" (click)="confirmDeleteImage('all')"> <span>{{'add.deleteAll' | translate}}</span> </div> </div> </div> </div> </div> </div> <div class="seperator"></div> <div class="group-content" style="padding-bottom: 16px;"> <div class="group-label"> <span nz-icon nzType="user-add" style="margin-right: 8px;"></span> {{'add.addRenter' | translate}} </div> <div>{{'add.addRenterInfo' | translate}}</div> <div add-renter-component (renterListChanged)="onRenterListChanged($event)"></div> </div> </form> <div class="seperator"></div> <div class="button"> <button nz-button class="login-form-button" [nzShape]="'round'" [nzType]="'primary'" (click)="onBtnAdd()"> <span nz-icon nzType="save" nzTheme="outline"></span>{{'add.confirm' | translate}} <span *ngIf="isLoading" style="margin-left: 8px;" nz-icon nzType="loading" nzTheme="outline"></span> </button> </div> </div> </div> </div> </div> <div *ngIf="!isEdit"> <nz-result nzStatus="success" [nzTitle]="'add.addSuccess' | translate"> <div nz-result-extra> <button nz-button nzType="primary" (click)="goList()" style="margin-bottom: 8px;">{{'add.viewDetail' | translate}}</button> <button nz-button (click)="newProduct()">{{'add.addAgain' | translate}}</button> </div> </nz-result> </div> </div>
#pragma once #include <ctime> #include <string> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <boost/thread/thread.hpp> #include <iostream> #include "PersonInRoom.h" namespace clientServer { using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> class server { public: server(boost::asio::io_context& io_service, boost::asio::io_context::strand& strand, const tcp::endpoint& endpoint) : io_service_(io_service), strand_(strand), acceptor_(io_service, endpoint), timer_(io_service_,boost::asio::chrono::seconds(1)), gameTimer_(io_service_,boost::asio::chrono::minutes(5)) { /// <summary> /// ADD DATABASE INFO HERE OR ENGINE WILL NOT WORK /// COMPILE WITH DETAILS /// </summary> std::string DATABASE_USER = "ENTER USER"; std::string DATABASE_PASSWORD = "ENER PASSWORD"; std::string DATABASE_IP = "127.0.0.1"; int DATABASE_PORT = 3306; /// <summary> /// ADD DATABASE INFO HERE OR ENGINE WILL NOT WORK /// COMPILE WITH DETAILS /// </summary> port_ = acceptor_.local_endpoint().port(); database_ = std::make_shared<db::database>(db::database(DATABASE_IP, DATABASE_PORT,DATABASE_USER,DATABASE_PASSWORD)); database_->insertGamePort(port_); std::shared_ptr<game::Game>game(new game::Game(room_,database_,port_, gameTimer_)); game_ = game; timer_.async_wait(boost::bind(&server::checkGame, this)); run(); } private: void run() { std::shared_ptr<gameServer::personInRoom> new_participant(new gameServer::personInRoom(io_service_, strand_, room_, port_, *game_,database_)); acceptor_.async_accept(new_participant->socket(), strand_.wrap(boost::bind(&server::onAccept, this, new_participant, _1))); } void onAccept(std::shared_ptr<gameServer::personInRoom> new_participant, const boost::system::error_code& error) { if (!error) { new_participant->start(); participants.push_back(new_participant); } run(); } void checkGame() { if (!game_->isStarted()) { timer_.expires_after(boost::asio::chrono::minutes(1)); timer_.async_wait(boost::bind(&server::queueGameForDestruction, this)); } else if (game_->hasEnded()) { timer_.expires_after(boost::asio::chrono::minutes(3)); timer_.async_wait(boost::bind(&server::queueGameForDestruction, this)); } else { timer_.expires_after(boost::asio::chrono::minutes(1)); timer_.async_wait(boost::bind(&server::checkGame, this)); } } void finishGame() { for (auto ptr : participants) { ptr.reset(); } acceptor_.close(); io_service_.stop(); } void queueGameForDestruction() { if (game_->isEmpty()) { database_->deleteGame(); database_->deleteGamePort(port_); for (auto ptr : participants) { ptr.reset(); } acceptor_.close(); io_service_.stop(); } else if (game_->hasEnded()) { game_->kickAllPlayers(); timer_.expires_after(boost::asio::chrono::minutes(2)); timer_.async_wait(boost::bind(&server::finishGame, this)); } else { timer_.expires_after(boost::asio::chrono::minutes(1)); timer_.async_wait(boost::bind(&server::checkGame, this)); } } uint64_t port_; boost::asio::io_context& io_service_; boost::asio::io_context::strand& strand_; tcp::acceptor acceptor_; chat::chatRoom room_; std::shared_ptr<db::database> database_; std::shared_ptr<game::Game> game_; std::vector<std::shared_ptr<gameServer::personInRoom>> participants; boost::asio::steady_timer timer_; boost::asio::steady_timer gameTimer_; }; class workerThread { public: static void run(std::shared_ptr<boost::asio::io_context> io_service) { { std::lock_guard < std::mutex > lock(m); std::cout << "[" << std::this_thread::get_id() << "] Thread starts" << std::endl; } io_service->run(); { std::lock_guard < std::mutex > lock(m); std::cout << "[" << std::this_thread::get_id() << "] Thread ends" << std::endl; } } private: static std::mutex m; }; std::mutex workerThread::m; };
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DateService { formatDate(date: Date) { return this.formatDateFromNumber(date.getFullYear(), date.getMonth(), date.getDate()); } formatDateUTC(date: Date) { return this.formatDateFromNumber(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); } private formatDateFromNumber(year: number, monthIndex: number, day: number) { const month = (monthIndex + 1); return `${year.toString()}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; } formatTime(date: Date) { return this.formatTimeFromNumber(date.getHours(), date.getMinutes(), date.getSeconds()); } formatTimeUTC(date: Date) { return this.formatTimeFromNumber(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); } private formatTimeFromNumber(hours: number, minutes: number, seconds: number) { return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } formatDateTime(date: Date, separator = ' ') { return `${this.formatDate(date)}${separator}${this.formatTime(date)}`; } formatDateTimeUTC(date: Date, separator = ' ') { return `${this.formatDateUTC(date)}${separator}${this.formatTimeUTC(date)}`; } formatDateTimeWithTimezone(date: Date) { const timezone = date.getTimezoneOffset() const timezoneAbs = Math.abs(timezone); const timezoneHours = Math.floor(timezoneAbs / 60); const timezoneMinutes = timezoneAbs % 60; const timezoneString = `${timezoneHours.toString().padStart(2, '0')}:${timezoneMinutes.toString().padStart(2, '0')}`; if (timezone >= 0) { return `${this.formatDateTimeUTC(date, 'T')}+${timezoneString}`; } return `${this.formatDateTimeUTC(date, 'T')}-${timezoneString}`; } makeDateFromString(str: string): Date { const [dateStr, timeStr] = str.split(' '); const [yearStr, monthStr, dayStr] = dateStr.split('-'); const [hoursStr, minutesStr, secondsStr] = timeStr.split(':'); const year = parseInt(yearStr || '0'); const month = parseInt(monthStr || '1') - 1; const day = parseInt(dayStr || '0'); const hours = parseInt(hoursStr || '0'); const minutes = parseInt(minutesStr || '0'); const seconds = parseInt(secondsStr || '0'); return new Date(year, month, day, hours, minutes, seconds); } }
#%% # reverseString the idea is to swap the letters that are symmetric # wrt the middle of the string # use two index, one at the begining and one at the end # swap letters of these two index # then move the left index one position to right and # right index one position to left # swap letters of these two index # continue this process until right index < left index #%% class Solution: def reverseString(self, s: list[str]) -> None: """ Do not return anything, modify s in-place instead. """ if s is None: return left, right = 0, len(s) - 1 while left <= right: self.swap(s, left, right) left += 1 right -= 1 return def swap(self, s, i, j): temp = s[i] s[i] = s[j] s[j] = temp return #%% S = Solution() s = ["h","e","l","l","o"] S.reverseString(s) print(s)
# Plot cell-types in UMAP setwd("../../") library(Seurat) library(ggplot2) library(ggrepel) library(scales) library(gridExtra) library(reshape2) source("scripts/ggplot_raster.R") source("scripts/color_pal.R") source("scripts/get_enr_mat.R") # Functions create_dir <- function(p){ dir.create(p, showWarnings=FALSE, recursive=TRUE) } #' @param datf data frame to get median points from #' @param x character vector of column names to calculate median for #' @param groupby the column name to group the rows of the data frame by get_med_points <- function(datf, x, groupby){ groups <- sort(unique(datf[,groupby])) gs.l <- lapply(groups, function(gr){ k <- datf[,groupby] == gr datf.s <- datf[k, x, drop=FALSE] r <- apply(datf.s, 2, median) return(r) }) names(gs.l) <- groups gs <- as.data.frame(do.call(rbind, gs.l)) colnames(gs) <- x rownames(gs) <- groups return(gs) } log10_rev_breaks <- function(x, n=5){ rng <- range(x, na.rm = TRUE) lxmin <- floor(log10(rng[1])) + log10(2) lxmax <- ceiling(log10(rng[2])) - log10(2) lby <- floor((lxmax - lxmin)/n) + 1 breaks <- rev(10^seq(lxmax, lxmin, by=-lby)) return(breaks) } format_power10 <- function(x){ x <- signif(x, digits = 2) sapply(x, function(y){ pow_num <- floor(log10(y)) base_num <- y * 10^-pow_num ret <- bquote(.(base_num) %*% 10^.(pow_num)) as.expression(ret) }) } log10_rev_trans <- function(x){ trans <- function(x) -log(x, 10) inv <- function(x) 10^(-x) trans_new("log10_rev", trans, inv, breaks = log10_rev_breaks, format = format_power10, domain = c(1e-100, Inf)) } # Gene data gene_info <- read.table("data/ref/gencode26/gencode.v26.annotation.txt", header = TRUE, row.names = 1, stringsAsFactors = FALSE, sep = "\t") gene_info[,"Name"] <- make.unique(gene_info[,"Name"]) symb2ens <- rownames(gene_info) names(symb2ens) <- gene_info[,"Name"] # Set directories dir_plt <- "exp/sharma_aiz/plots/"; dir.create(dir_plt, showWarnings=FALSE, recursive=TRUE) fn <- "data/processed/sharma_aiz/liver.int_rand.rds" integrated <- readRDS(fn) udf <- integrated@[email protected] colnames(udf) <- c("UMAP1", "UMAP2") udf <- cbind(udf, [email protected][rownames(udf),]) # plotting theme theme_txt <- theme(text = element_text(size = 8), plot.title = element_text(hjust = 0.5)) theme_leg <- theme(legend.key.size = unit(6, "points"), legend.spacing.x = unit(2,"points"), legend.spacing.y = unit(5,"points"), legend.title = element_text(vjust = 0.5, hjust = 0), legend.margin = margin(0,0,0,0), legend.text = element_text(size = 6, hjust = 0, margin = margin(0,5,0,0)), legend.box.spacing = unit(0.5, "strheight", "0")) theme_axs <- theme(axis.text=element_blank(), axis.ticks=element_blank()) theme_s <- theme_classic() + theme_txt + theme_leg + theme_axs # UMAP of cell-type assignments # Cell type labels labs <- c("cell_type_main", "cell_type_fine") names(labs) <- labs leg <- c('Main', 'Fine') names(leg) <- labs # generate color palettes ctu <- lapply(labs, function(lab){ sort(unique(udf[,lab])) }) pal_labs <- lapply(labs, function(l){ nct <- length(ctu[[l]]) hcl_pal(nct, chr = c(80, 80), lum = c(60,80), offset = 0, rand = TRUE, seedn = 321) }) meds <- get_med_points(udf, c("UMAP1", "UMAP2"), "cell_type_main") for (l in labs){ p <- ggplot(udf, aes_string(x="UMAP1",y="UMAP2",color=l)) + geom_point(shape=16, size=.01) + scale_color_manual(values=pal_labs[[l]], name=leg[l]) + theme_s + guides(color = guide_legend(override.aes = list(size=1), ncol=1)) + geom_text_repel(data=meds, aes(x=UMAP1, y=UMAP2), size = 3, label=rownames(meds), color="black") g <- raster_ggpoints(ggplotGrob(p), w=3, h=3, res=600) outfn <- file.path(dir_plt, paste0("UMAP.", l, ".pdf")) pdf(outfn, width = 3.5, height = 3) grid.draw(g) dev.off() } # pathway enrichment plots fn <- "exp/sharma_aiz/clust2ct/res1_to_fine.txt" ctmap <- read.table(fn, header=TRUE, colClasses = "character") rownames(ctmap) <- ctmap[,1] fn <- "exp/sharma_aiz/path_enr/markers.res.1.path_gse.rds" gse_all <- readRDS(fn) fn <- "data/ref/colors/red_colrs.csv" reds <- read.table(fn, header=FALSE) reds <- reds[,1] theme_e <- theme_bw() + theme(text = element_text(size = 10), axis.text.y = element_text(size = 6, margin=margin(0,1,0,0)), axis.text.x = element_text(size = 6, margin=margin(0,0,0,0), angle = 90, hjust = 1, vjust = 0.5), panel.border = element_blank(), panel.background = element_blank(), panel.grid.major = element_line(colour = reds[1]), plot.title = element_text(hjust = 0.5), axis.ticks = element_line(colour = reds[1]), legend.key.width = unit(1, "strwidth", "0")) dir_plt <- "exp/sharma_aiz/path_enr/"; e_col <- "NES" p_col <- "qvalues" for (a in names(gse_all)){ react_l <- gse_all[[a]] names(react_l) <- ctmap[names(react_l),"cell_type"] react_l <- lapply(react_l, function(x){ k <- x[,e_col] >= 0 x <- x[k,,drop=FALSE] return(x) }) react_l <- get_enr_mat(react_l, idcol = "ID", dcol = "Description", ctcol = "CellType", pcol = p_col, ecol = e_col, max_terms = 3) e_df <- react_l[["E"]] p_df <- react_l[["P"]] # wrap strings rn <- rownames(e_df) rn <- sapply(rn, function(x){ if (nchar(x) > 80){ x <- strtrim(x, 77) x <- paste(x, "...", sep="") } return(x) }) # rn <- sapply(rn, function(x) paste(strwrap(x), collapse='\n')) rownames(e_df) <- rownames(p_df) <- rn # order cell types ro <- hclust(dist(e_df))$order co <- hclust(dist(t(e_df)))$order rl <- rownames(e_df)[ro] cl <- colnames(e_df)[co] # melt p_dfm <- reshape2::melt(as.matrix(p_df)) e_dfm <- reshape2::melt(as.matrix(e_df)) for (i in 1:2){ p_dfm[,i] <- factor(as.character(p_dfm[,i]), levels=list(rl,cl)[[i]]) e_dfm[,i] <- factor(as.character(e_dfm[,i]), levels=list(rl,cl)[[i]]) } enr_datf <- data.frame("path" = p_dfm[,1], "cluster" = p_dfm[,2], "enr" = e_dfm[,3], "p" = p_dfm[,3]) p <- ggplot(enr_datf, aes(x = cluster, y = path, color = enr, size = p)) + geom_point() + theme_e + labs(x=NULL, y=NULL) + ggtitle(a) + scale_size(name = "q-value", trans="log10_rev", range = c(0,3)) + scale_color_gradientn(colors = reds) + guides(size = guide_legend(override.aes = list(shape = 1, color = "black"))) fn <- file.path(dir_plt, paste0("markers.fine.", a, ".bubble.pdf")) ggsave(fn, width = 7, height = 5) }
import { ReactElement } from "react"; import { Box, Button } from "@mui/material"; import { actionsButtons, buttonStyle } from "./modalStyles"; import CancelIcon from "@mui/icons-material/Cancel"; const ActionsButtons = (props: { cancel: () => void; submit: () => void; submitText: string; submitIcon: ReactElement; }) => { return ( <Box sx={actionsButtons}> <Button variant="contained" sx={buttonStyle} endIcon={<CancelIcon />} onClick={props.cancel} > Cancel </Button> <Button variant="contained" color="success" endIcon={props.submitIcon} onClick={props.submit} > {props.submitText} </Button> </Box> ); }; export default ActionsButtons;
package ru.nlct.mylovelyplace.presentation.ui.home.utils import android.graphics.Bitmap import android.util.LruCache /** * LruCache for caching background bitmaps for [DecodeBitmapTask]. */ internal class BackgroundBitmapCache { private val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt() / 5 private val cacheSize = maxMemory / 5 private val cache: LruCache<Int?, Bitmap> = object : LruCache<Int?, Bitmap>(cacheSize) { // The cache size will be measured in kilobytes rather than number of items. override fun sizeOf(key: Int?, bitmap: Bitmap) = bitmap.byteCount / 1024 } fun addBitmapToBgMemoryCache(key: Int?, bitmap: Bitmap) { if (getBitmapFromBgMemCache(key) == null) { cache.put(key, bitmap) } } fun getBitmapFromBgMemCache(key: Int?): Bitmap? { return cache[key] } companion object { val instance = BackgroundBitmapCache() } }
transform middleright: xalign 0.7 ypos 0.06 define flash = Fade(.25, 0.0, .75, color="#fff") screen quest_menu(id_tavern,quests,label,label_retour): frame: background Solid("#000000ae") vbox: spacing 5 textbutton "Retour" action Jump(label_retour) style "retour_taverne" viewport: draggable True scrollbars "vertical" mousewheel True grid 3 calculate_rows(quests, 3): # Dynamiquement calculé spacing 10 python: #liste_quete = sorted(list(quests), key=lambda x: float(x[1])) if quests is not None: liste_quete = sorted(list(quests)) else: liste_quete= [] for quest in liste_quete: frame: style "quest_frame" vbox: text quest[0] text "Difficulté: {}".format(quest[2]) textbutton quest[1] action Function(handle_quest_and_redirect, quest, site,id_tavern,label) screen ecran_victoire(nom_quete,or_gagne,chap=0): frame: xalign 0.5 yalign 0.5 xpadding 20 ypadding 20 background "#444444" # Une couleur de fond gris foncé vbox: align (0.5, 0.5) spacing 10 text "Victoire !": style "titre_victoire" text "Quête: [nom_quete]": style "details_quete" if chap == 1: text "Or gagné: [or_gagne]": style "details_or" text "Or total: [persistent.gold]": style "details_or" elif chap == 2: text "Point de valeur gagné: [or_gagne]": style "details_or" text "Point de valeur total: [persistent.point_de_valeur]": style "details_or" elif chap == 3: text "Argent gagné: [or_gagne]": style "details_or" text "Argent total: [persistent.argent]": style "details_or" text "Score Total: [persistent.score]": style "details_score" textbutton "Retour au jeu" action Return() style "bouton_retour" screen Map(ch): add "carte_fin.png" imagebutton: xpos 1249 ypos 649 hover "village1_hover.png" idle "village1_idle.png" action Jump("place_village") if ch >=2: imagebutton : xpos 827 ypos 653 hover "dedale_hover.png" idle "dedale_idle.png" action Jump("place_dedale") if ch >=3: imagebutton : xpos 744 ypos 473 hover "temporium_hover.png" idle "temporium_idle.png" action Jump("auberge") define get_fct=[ ["Vous avez compris comment utiliser le print()\n","Le print sert à écrire ce qui est marqué dans ses parentheses que ce soit une phrase, un nombre ou la valeur d'une variable","nbr=4\nprint(\"nbr\")\nprint(nbr)\nprint(5)","nbr\n4\n5"], ["Vous avez appris à utiliser le input()\n","La fonction input() permet de recuperer une ligne de la liste des inputs. Vous pouvez par apres stocker cette ligne dans une variable mais attention par defaut la fonction input() va recuperer la ligne sous la forme d'un string c'est-à-dire qu'il va considerer que c'est un suite de lettres et il sera donc pas possible de faire des operations mathematiques dessus.\n\nPour transformer ce string en un autre type de variable plus pratique il faudra preciser à quel type de variable appartient l'input de cette facon:\n\n int(input()) pour recuperer un entier\n float(input()) pour recuperer un nombre à virgule\n etc.","{color=#13ad0d}#Les inputs sont dans l'ordre \"hello world,5,5\"{/color}\nstr1=input()\nnbr1=int(input())\nnbr2=float(input())\n\nprint(str1)\nprint(nbr1)\nprint(nbr2)","hello world\n5\n5.0"], ["Vous avez appris à utiliser le if\n","Le if est une operation qui permet au programme de faire des decisions. Autrement dit le programme va lancer un certain code quand certaines conditions sont respectées.\n\nLa condition sera ecrite juste apres le if sur la meme ligne et se terminera par \":\"\nLe code qui sera executé quand la condition est respectée doit se trouver sur la ligne en-dessous du if et doit absolument etre decalé vers la droite en appuyant sur la touche \"tab\"\nLe fait de decaler une partie du code vers la droite s'appelle l'indentation et est un concept tres important en python si l'indentation n'est pas respecté alors le code risque ne pas donner les bonnes reponses ou de juste ne pas se lancer","a=3\nb=5\nif b>a: {color=#13ad0d}#La condition a respecter{/color}\n {color=#13ad0d}#Le code a executer si la condition est respectée{/color}\n print(\"b est plus grand que a\")","b est plus grand que a"], ["Vous avez debloqué le elif\n","Le elif s'utilise apres le code d'un if et est le moyen d'exprimer en python que \"Si la condition precedente n'est pas respectée alors essaye cette condition\"\n\nIl s'utilise de la meme facon que le if","a=5\nb=3\nif b>a: {color=#13ad0d}#La 1ere condition a respecter{/color}\n print(\"b est plus grand que a\")\nelif a>b: {color=#13ad0d}#La 2eme condition a respecter{/color}\n {color=#13ad0d}#Le code a executer si la 1ere condition n'est pas respectée mais la deuxieme condition oui{/color}\n print(\"a est plus grand que b\")","a est plus grand que b"], ["Vous avez debloqué le else\n","Le else sert a executer un code quand aucune des conditons precedantes n'a été respecté\n\nIl s'utilise de la meme facon qu'un if ou un elif sauf qu'il ne faut pas specifier de condition","a=5\nb=5\nif b>a: {color=#13ad0d}#La 1ere condition a respecter{/color}\n print(\"b est plus grand que a\")\nelif a>b: {color=#13ad0d}#La 2eme condition a respecter{/color}\n print(\"a est plus grand que b\")\nelse:\n {color=#13ad0d}#Le code a executer si aucune des conditions n'a été respecté{/color}\n print(\"a et b sont egaux\")","a et b sont egaux"], ["Vous avez debloqué le while\n","Le while est une boucle qui peut executer un code en boucle tant qu'une certaine condition est respectée\n\nLa condition en question sera écrite sur la meme ligne que le while de la meme facon que pour le if.\nLe code à executer en boucle devra luio aussi étre decalé d'un cran vers la droite.","i=1\nwhile i<6: {color=#13ad0d}#La condition a respecter{/color}\n print(i)\n i=i+1","1\n2\n3\n4\n5"], ["Vous avez debloqué le for\n","Le for sert à faire une boucle sur une sequence et ainsi executer un code sur chaque élement de cette sequence\n\nLe for s'ecrit de la maniere suivante:\n for x in seq1:\n #reste du code\n\nseq1 sera la sequance qu'il faudra parcourir et x prendra la valeur de chaque element de la sequence, un à la fois.\n\nLa sequence la plus simple qu'on peut avoir est obtenu par la fonction range(n) qui va renvoyer une sequence de nombre allant de 0 à n-1 compris","for x in range(6):\n print(x)","0\n1\n2\n3\n4\n5"] ] screen debloquer(id): frame: ypadding 20 xalign 0.5 yalign 0.5 xpadding 20 background None vbox: xalign 0.5 yalign 0.5 frame: xalign 0.5 background "#d1b30a" vbox: text "Felicitation !": xalign 0.5 bold True color "#000" frame: xalign 0.5 xpadding 20 ypadding 20 background "#ffd700" vbox: text get_fct[id][0]: color "#000" line_leading 2 text get_fct[id][1]: color "#000" line_spacing 2 textbutton "Next" action Show("debloquer_2",id=id),Hide("debloquer"): xalign 1.0 screen debloquer_2(id): frame: ypadding 20 xalign 0.5 yalign 0.5 xpadding 20 background None vbox: xalign 0.5 yalign 0.5 frame: xalign 0.5 background "#d1b30a" vbox: text "En pratique": xalign 0.5 bold True underline True color "#000" frame: xalign 0.5 yalign 0.5 xpadding 20 ypadding 20 background "#ffd700" vbox: text "Exemple de code": color "#000" frame: background "#26282A" text get_fct[id][2] text "Output": color "#000" frame: background "#26282A" text get_fct[id][3] hbox: textbutton "Precedent" action Show("debloquer",id=id),Hide("debloquer_2") textbutton "Retour au jeu" action Hide("debloquer_2"),Return()
# 文件类型识别 ## `文本文件`识别 对于一个文件是否是`文本文件`,并没有完全行之有效的识别方案。只能通过尝试去理解内容,这是有一定误差的。 可行的方案有:`文件名后缀匹配`、`magic number 过滤`等,虽然会有一定误差,但在比较稳定的环境下,这也是有效的。 对文本内容全量解码,这在文本较小的时候非常行之有效。若环境中出现图片、压缩文件等,这会有极大的性能损耗。 这里提供一种思路,即对文本内容主动进行多个位置的截取解码,以较小的性能开销来对文本文件进行识别。 ### 命令 ``` hlvdump istext xxx.md > YES, This Is Text File.(or "NO, This Not Text File.") ``` ### Code ``` import HLVFileDump let r = HLVFile.isText(path), encoding: .utf8) print("\(r ? "YES, This Is Text File." : "NO, This Not Text File.")") ``` ## 文件 magic number 识别 通过 `magic number` 可以非常准确的识别特定的文件类型,这基于 ELF 等类似的二进制文件均具有表现一致的文件头。 ### 命令 ``` hlvdump MyI.zip > type: zip, alias: jar zipx hlvdump test.log > type: text ``` ### Code ``` import HLVFileDump let r = HLVFileDump.default.dump(path) switch r { case let .magic(name, alias, _): if let alias { print("type: \(name), alias: \(alias.joined(separator: " "))") } else { print("type: \(name)") } case .error(let msg): print(msg) case .unknow: print("type: unknow") } ``` ## Installation By Swift Package Manager. ``` let package = Package( dependencies: [ .package(url: "https://github.com/yigegongjiang/HLVFileDump.git", .upToNextMajor(from: "1.0.0")) ], targets: [ .target(dependencies: [...,"HLVFileDump"]) ] ) ```
/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2017 Roman Lebedev This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "io/FileReader.h" #include "adt/AlignedAllocator.h" #include "adt/Casts.h" #include "adt/DefaultInitAllocatorAdaptor.h" #include "io/Buffer.h" #include "io/FileIOException.h" #include <cstdint> #include <cstdio> #include <limits> #include <memory> #include <utility> #include <vector> #if !(defined(__unix__) || defined(__APPLE__)) #ifndef NOMINMAX #define NOMINMAX // do not want the min()/max() macros! #endif #include "io/FileIO.h" #include <Windows.h> #include <io.h> #include <tchar.h> #endif namespace rawspeed { std::pair<std::unique_ptr<std::vector< uint8_t, DefaultInitAllocatorAdaptor< uint8_t, AlignedAllocator<uint8_t, 16>>>>, Buffer> FileReader::readFile() const { size_t fileSize = 0; #if defined(__unix__) || defined(__APPLE__) auto fclose = [](std::FILE* fp) { std::fclose(fp); }; using file_ptr = std::unique_ptr<FILE, decltype(fclose)>; file_ptr file(fopen(fileName, "rb"), fclose); if (file == nullptr) ThrowFIE("Could not open file \"%s\".", fileName); fseek(file.get(), 0, SEEK_END); const auto size = ftell(file.get()); if (size <= 0) ThrowFIE("File is 0 bytes."); fileSize = size; if (fileSize > std::numeric_limits<Buffer::size_type>::max()) ThrowFIE("File is too big (%zu bytes).", fileSize); fseek(file.get(), 0, SEEK_SET); auto dest = std::make_unique<std::vector< uint8_t, DefaultInitAllocatorAdaptor<uint8_t, AlignedAllocator<uint8_t, 16>>>>( fileSize); if (auto bytes_read = fread(dest->data(), 1, fileSize, file.get()); fileSize != bytes_read) { ThrowFIE("Could not read file, %s.", feof(file.get()) ? "reached end-of-file" : (ferror(file.get()) ? "file reading error" : "unknown problem")); } #else // __unix__ auto wFileName = widenFileName(fileName); using file_ptr = std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&CloseHandle)>; file_ptr file(CreateFileW(wFileName.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr), &CloseHandle); if (file.get() == INVALID_HANDLE_VALUE) ThrowFIE("Could not open file \"%s\".", fileName); LARGE_INTEGER size; GetFileSizeEx(file.get(), &size); static_assert( std::numeric_limits<Buffer::size_type>::max() == std::numeric_limits<decltype(size.LowPart)>::max(), "once Buffer migrates to 64-bit index, this needs to be updated."); if (size.HighPart > 0) ThrowFIE("File is too big."); if (size.LowPart <= 0) ThrowFIE("File is 0 bytes."); auto dest = std::make_unique<std::vector< uint8_t, DefaultInitAllocatorAdaptor<uint8_t, AlignedAllocator<uint8_t, 16>>>>( size.LowPart); DWORD bytes_read; if (!ReadFile(file.get(), dest->data(), size.LowPart, &bytes_read, nullptr)) ThrowFIE("Could not read file."); if (size.LowPart != bytes_read) ThrowFIE("Could not read file."); fileSize = size.LowPart; #endif // __unix__ return {std::move(dest), Buffer(dest->data(), implicit_cast<Buffer::size_type>(fileSize))}; } } // namespace rawspeed
use time::{OffsetDateTime}; use serde::{Deserialize, Serialize}; use crate::ids::{RecipientId, BankAccountId}; use crate::resources::{CreateBankAccount, BankAccount}; use crate::params::{Page, unpack_contained}; use crate::{Client, Response}; use crate::build_map; #[derive(Clone, Debug, Default, Serialize)] pub struct CreateRecipient<'a> { pub email: &'a str, pub name: Option<&'a str>, pub bank_account: Option<CreateBankAccount<'a>>, pub bank_account_token: Option<BankAccountId> } #[derive(Clone, Debug, Default, Deserialize)] pub struct Recipient { pub token: RecipientId, pub email: String, pub name: Option<String>, #[serde(with = "time::serde::iso8601::option")] pub created_at: Option<OffsetDateTime>, pub bank_account: BankAccount } impl Recipient { pub fn create(client: &Client, params: CreateRecipient<'_>) -> Response<Recipient> { unpack_contained(client.post_form(&format!("/recipients"), &params)) } pub fn list(client: &Client, page: Option<u32>, per_page: Option<u32>) -> Response<Page<Recipient>> { let page = page.map(|s| s.to_string()); let per_page = per_page.map(|s| s.to_string()); let params = build_map([ ("page", page.as_deref()), ("per_page", per_page.as_deref()) ]); client.get_query("/recipients", &params) } pub fn retrieve(client: &Client, token: &RecipientId) -> Response<Recipient> { unpack_contained(client.get(&format!("/recipients/{}", token))) } }
using Asp.Versioning; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OutputCaching; using ProsperityPartners.Application.Features.BatchFeatures.Queries; using ProsperityPartners.Application.Features.CompanyFeatures.Commands; using ProsperityPartners.Application.Features.CompanyFeatures.Queries; using ProsperityPartners.Application.Features.DeductionCodeFeatures.Queries; using ProsperityPartners.Application.Features.RecordFeatures.Queries; using ProsperityPartners.Application.Shared.CompanyDTOs; using ProsperityPartners.Presentation.API.ActionFilters; using ProsperityPartners.Presentation.API.ModelBinders; namespace ProsperityPartners.Presentation.API.Controllers { [ApiVersion("1.0")] [Route("api/v{v:apiversion}/companies")] //[ResponseCache(CacheProfileName = "120SecondsDuration")] [OutputCache(PolicyName = "120SecondsDuration")] [ApiController] public class CompaniesController : ControllerBase { private readonly ISender _sender; public CompaniesController(ISender sender) => _sender = sender; [HttpGet] //[ResponseCache(Duration = 60)] public async Task<IActionResult> GetAllCompanies() { //throw new Exception("Exception"); var result = await _sender.Send(new GetAllCompaniesQuery()); return Ok(result); } [HttpGet("{Id:guid}/deductionCodes")] public async Task<IActionResult> GetCompanyDeductionCodes(Guid Id) { var deductionCodes = await _sender.Send(new GetCompanyDeductionCodesQuery(Id)); return Ok(deductionCodes); } [HttpGet("{Id:guid}/batches")] public async Task<IActionResult> GetCompanyBatches(Guid Id) { var batches = await _sender.Send(new GetCompanyBatchesQuery(Id)); return Ok(batches); } [HttpGet("{Id:guid}/records")] public async Task<IActionResult> GetCompanyRecords(Guid Id) { var records = await _sender.Send(new GetCompanyRecordsQuery(Id)); return Ok(records); } [HttpGet("{Id:guid}", Name = "CompanyById")] //[ResponseCache(Duration = 60)] [OutputCache(Duration = 60)] public async Task<IActionResult> GetCompany(Guid Id) { var company = await _sender.Send(new GetCompanyQuery() { CompanyId = Id }); return Ok(company); } [HttpPost] [ServiceFilter(typeof(ValidationFilterAttribute))] [OutputCache(NoStore = true)] public async Task<IActionResult> CreateCompany([FromBody] CreateCompanyDto createCompanyDto) { var company = await _sender.Send(new CreateCompanyCommand() { CreateCompanyDto = createCompanyDto }); return CreatedAtRoute("CompanyById", new {id = company.Id},company); } [HttpGet("collection/({ids})",Name ="CompanyCollection")] public async Task<IActionResult> GetCompanyCollection([ModelBinder(BinderType = typeof(ArrayModelBinder))]IEnumerable<Guid> ids) { var companies = await _sender.Send(new GetCompaniesByIdsQuery(ids)); return Ok(companies); //http://localhost:5041/api/companies/collection/(08dc79fa-4014-4c90-8b41-b7fc5e4ec45d,08dc79fa-4019-4d10-886e-c5997934a3c4) } [HttpPost("collection")] [ServiceFilter(typeof(ValidationFilterAttribute))] public async Task<IActionResult> CreateCompanyCollection([FromBody] IEnumerable<CreateCompanyDto> companyCollection) { var result = await _sender.Send(new CreateCompanyCollectionCommand(companyCollection)); return CreatedAtRoute("CompanyCollection", new { result.ids }, result.companies); } [HttpDelete("{id:guid}")] [OutputCache(NoStore = true)] public async Task<IActionResult> DeleteCompany(Guid id) { await _sender.Send(new DeleteCompanyCommand(id)); return NoContent(); } [HttpPut("{id:guid}")] [ServiceFilter(typeof(ValidationFilterAttribute))] public async Task<IActionResult> UpdateCompany(Guid id, [FromBody] UpdateCompanyDto updateCompanyDto) { await _sender.Send(new UpdateCompanyCommand(id, updateCompanyDto,trackChanges:true)); return NoContent(); } } }
#ifndef __HID_H #define __HID_H /* * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2001 Vojtech Pavlik * Copyright (c) 2006-2007 Jiri Kosina */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Should you need to contact me, the author, you can do so either by * e-mail - mail your message to <[email protected]>, or by paper mail: * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic */ /* * USB HID (Human Interface Device) interface class code */ #define USB_INTERFACE_CLASS_HID 3 /* * USB HID interface subclass and protocol codes */ #define USB_INTERFACE_SUBCLASS_BOOT 1 #define USB_INTERFACE_PROTOCOL_KEYBOARD 1 #define USB_INTERFACE_PROTOCOL_MOUSE 2 /* * HID class requests */ #define HID_REQ_GET_REPORT 0x01 #define HID_REQ_GET_IDLE 0x02 #define HID_REQ_GET_PROTOCOL 0x03 #define HID_REQ_SET_REPORT 0x09 #define HID_REQ_SET_IDLE 0x0A #define HID_REQ_SET_PROTOCOL 0x0B /* * HID class descriptor types */ #define HID_DT_HID (USB_TYPE_CLASS | 0x01) #define HID_DT_REPORT (USB_TYPE_CLASS | 0x02) #define HID_DT_PHYSICAL (USB_TYPE_CLASS | 0x03) #define HID_MAX_DESCRIPTOR_SIZE 4096 #ifdef __KERNEL__ #include <linux/types.h> #include <linux/slab.h> #include <linux/list.h> #include <linux/mod_devicetable.h> /* hid_device_id */ #include <linux/timer.h> #include <linux/workqueue.h> #include <linux/input.h> /* * We parse each description item into this structure. Short items data * values are expanded to 32-bit signed int, long items contain a pointer * into the data area. */ struct hid_item { unsigned format; __u8 size; __u8 type; __u8 tag; union { __u8 u8; __s8 s8; __u16 u16; __s16 s16; __u32 u32; __s32 s32; __u8 *longdata; } data; }; /* * HID report item format */ #define HID_ITEM_FORMAT_SHORT 0 #define HID_ITEM_FORMAT_LONG 1 /* * Special tag indicating long items */ #define HID_ITEM_TAG_LONG 15 /* * HID report descriptor item type (prefix bit 2,3) */ #define HID_ITEM_TYPE_MAIN 0 #define HID_ITEM_TYPE_GLOBAL 1 #define HID_ITEM_TYPE_LOCAL 2 #define HID_ITEM_TYPE_RESERVED 3 /* * HID report descriptor main item tags */ #define HID_MAIN_ITEM_TAG_INPUT 8 #define HID_MAIN_ITEM_TAG_OUTPUT 9 #define HID_MAIN_ITEM_TAG_FEATURE 11 #define HID_MAIN_ITEM_TAG_BEGIN_COLLECTION 10 #define HID_MAIN_ITEM_TAG_END_COLLECTION 12 /* * HID report descriptor main item contents */ #define HID_MAIN_ITEM_CONSTANT 0x001 #define HID_MAIN_ITEM_VARIABLE 0x002 #define HID_MAIN_ITEM_RELATIVE 0x004 #define HID_MAIN_ITEM_WRAP 0x008 #define HID_MAIN_ITEM_NONLINEAR 0x010 #define HID_MAIN_ITEM_NO_PREFERRED 0x020 #define HID_MAIN_ITEM_NULL_STATE 0x040 #define HID_MAIN_ITEM_VOLATILE 0x080 #define HID_MAIN_ITEM_BUFFERED_BYTE 0x100 /* * HID report descriptor collection item types */ #define HID_COLLECTION_PHYSICAL 0 #define HID_COLLECTION_APPLICATION 1 #define HID_COLLECTION_LOGICAL 2 /* * HID report descriptor global item tags */ #define HID_GLOBAL_ITEM_TAG_USAGE_PAGE 0 #define HID_GLOBAL_ITEM_TAG_LOGICAL_MINIMUM 1 #define HID_GLOBAL_ITEM_TAG_LOGICAL_MAXIMUM 2 #define HID_GLOBAL_ITEM_TAG_PHYSICAL_MINIMUM 3 #define HID_GLOBAL_ITEM_TAG_PHYSICAL_MAXIMUM 4 #define HID_GLOBAL_ITEM_TAG_UNIT_EXPONENT 5 #define HID_GLOBAL_ITEM_TAG_UNIT 6 #define HID_GLOBAL_ITEM_TAG_REPORT_SIZE 7 #define HID_GLOBAL_ITEM_TAG_REPORT_ID 8 #define HID_GLOBAL_ITEM_TAG_REPORT_COUNT 9 #define HID_GLOBAL_ITEM_TAG_PUSH 10 #define HID_GLOBAL_ITEM_TAG_POP 11 /* * HID report descriptor local item tags */ #define HID_LOCAL_ITEM_TAG_USAGE 0 #define HID_LOCAL_ITEM_TAG_USAGE_MINIMUM 1 #define HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM 2 #define HID_LOCAL_ITEM_TAG_DESIGNATOR_INDEX 3 #define HID_LOCAL_ITEM_TAG_DESIGNATOR_MINIMUM 4 #define HID_LOCAL_ITEM_TAG_DESIGNATOR_MAXIMUM 5 #define HID_LOCAL_ITEM_TAG_STRING_INDEX 7 #define HID_LOCAL_ITEM_TAG_STRING_MINIMUM 8 #define HID_LOCAL_ITEM_TAG_STRING_MAXIMUM 9 #define HID_LOCAL_ITEM_TAG_DELIMITER 10 /* * HID usage tables */ #define HID_USAGE_PAGE 0xffff0000 #define HID_UP_UNDEFINED 0x00000000 #define HID_UP_GENDESK 0x00010000 #define HID_UP_SIMULATION 0x00020000 #define HID_UP_KEYBOARD 0x00070000 #define HID_UP_LED 0x00080000 #define HID_UP_BUTTON 0x00090000 #define HID_UP_ORDINAL 0x000a0000 #define HID_UP_CONSUMER 0x000c0000 #define HID_UP_DIGITIZER 0x000d0000 #define HID_UP_PID 0x000f0000 #define HID_UP_HPVENDOR 0xff7f0000 #define HID_UP_MSVENDOR 0xff000000 #define HID_UP_CUSTOM 0x00ff0000 #define HID_UP_LOGIVENDOR 0xffbc0000 #define HID_USAGE 0x0000ffff #define HID_GD_POINTER 0x00010001 #define HID_GD_MOUSE 0x00010002 #define HID_GD_JOYSTICK 0x00010004 #define HID_GD_GAMEPAD 0x00010005 #define HID_GD_KEYBOARD 0x00010006 #define HID_GD_KEYPAD 0x00010007 #define HID_GD_MULTIAXIS 0x00010008 #define HID_GD_X 0x00010030 #define HID_GD_Y 0x00010031 #define HID_GD_Z 0x00010032 #define HID_GD_RX 0x00010033 #define HID_GD_RY 0x00010034 #define HID_GD_RZ 0x00010035 #define HID_GD_SLIDER 0x00010036 #define HID_GD_DIAL 0x00010037 #define HID_GD_WHEEL 0x00010038 #define HID_GD_HATSWITCH 0x00010039 #define HID_GD_BUFFER 0x0001003a #define HID_GD_BYTECOUNT 0x0001003b #define HID_GD_MOTION 0x0001003c #define HID_GD_START 0x0001003d #define HID_GD_SELECT 0x0001003e #define HID_GD_VX 0x00010040 #define HID_GD_VY 0x00010041 #define HID_GD_VZ 0x00010042 #define HID_GD_VBRX 0x00010043 #define HID_GD_VBRY 0x00010044 #define HID_GD_VBRZ 0x00010045 #define HID_GD_VNO 0x00010046 #define HID_GD_FEATURE 0x00010047 #define HID_GD_UP 0x00010090 #define HID_GD_DOWN 0x00010091 #define HID_GD_RIGHT 0x00010092 #define HID_GD_LEFT 0x00010093 #define HID_DG_DIGITIZER 0x000d0001 #define HID_DG_PEN 0x000d0002 #define HID_DG_LIGHTPEN 0x000d0003 #define HID_DG_TOUCHSCREEN 0x000d0004 #define HID_DG_TOUCHPAD 0x000d0005 #define HID_DG_STYLUS 0x000d0020 #define HID_DG_PUCK 0x000d0021 #define HID_DG_FINGER 0x000d0022 #define HID_DG_TIPPRESSURE 0x000d0030 #define HID_DG_BARRELPRESSURE 0x000d0031 #define HID_DG_INRANGE 0x000d0032 #define HID_DG_TOUCH 0x000d0033 #define HID_DG_UNTOUCH 0x000d0034 #define HID_DG_TAP 0x000d0035 #define HID_DG_TABLETFUNCTIONKEY 0x000d0039 #define HID_DG_PROGRAMCHANGEKEY 0x000d003a #define HID_DG_INVERT 0x000d003c #define HID_DG_TIPSWITCH 0x000d0042 #define HID_DG_TIPSWITCH2 0x000d0043 #define HID_DG_BARRELSWITCH 0x000d0044 #define HID_DG_ERASER 0x000d0045 #define HID_DG_TABLETPICK 0x000d0046 /* * as of May 20, 2009 the usages below are not yet in the official USB spec * but are being pushed by Microsft as described in their paper "Digitizer * Drivers for Windows Touch and Pen-Based Computers" */ #define HID_DG_CONFIDENCE 0x000d0047 #define HID_DG_WIDTH 0x000d0048 #define HID_DG_HEIGHT 0x000d0049 #define HID_DG_CONTACTID 0x000d0051 #define HID_DG_INPUTMODE 0x000d0052 #define HID_DG_DEVICEINDEX 0x000d0053 #define HID_DG_CONTACTCOUNT 0x000d0054 #define HID_DG_CONTACTMAX 0x000d0055 /* * HID report types --- Ouch! HID spec says 1 2 3! */ #define HID_INPUT_REPORT 0 #define HID_OUTPUT_REPORT 1 #define HID_FEATURE_REPORT 2 /* * HID connect requests */ #define HID_CONNECT_HIDINPUT 0x01 #define HID_CONNECT_HIDINPUT_FORCE 0x02 #define HID_CONNECT_HIDRAW 0x04 #define HID_CONNECT_HIDDEV 0x08 #define HID_CONNECT_HIDDEV_FORCE 0x10 #define HID_CONNECT_FF 0x20 #define HID_CONNECT_DEFAULT (HID_CONNECT_HIDINPUT|HID_CONNECT_HIDRAW| \ HID_CONNECT_HIDDEV|HID_CONNECT_FF) /* * HID device quirks. */ /* * Increase this if you need to configure more HID quirks at module load time */ #define MAX_USBHID_BOOT_QUIRKS 4 #define HID_QUIRK_INVERT 0x00000001 #define HID_QUIRK_NOTOUCH 0x00000002 #define HID_QUIRK_IGNORE 0x00000004 #define HID_QUIRK_NOGET 0x00000008 #define HID_QUIRK_HIDDEV_FORCE 0x00000010 #define HID_QUIRK_BADPAD 0x00000020 #define HID_QUIRK_MULTI_INPUT 0x00000040 #define HID_QUIRK_HIDINPUT_FORCE 0x00000080 #define HID_QUIRK_SKIP_OUTPUT_REPORTS 0x00010000 #define HID_QUIRK_FULLSPEED_INTERVAL 0x10000000 #define HID_QUIRK_NO_INIT_REPORTS 0x20000000 #define HID_QUIRK_NO_IGNORE 0x40000000 #define HID_QUIRK_NO_INPUT_SYNC 0x80000000 /* * This is the global environment of the parser. This information is * persistent for main-items. The global environment can be saved and * restored with PUSH/POP statements. */ struct hid_global { unsigned usage_page; __s32 logical_minimum; __s32 logical_maximum; __s32 physical_minimum; __s32 physical_maximum; __s32 unit_exponent; unsigned unit; unsigned report_id; unsigned report_size; unsigned report_count; }; /* * This is the local environment. It is persistent up the next main-item. */ #define HID_MAX_USAGES 12288 #define HID_DEFAULT_NUM_COLLECTIONS 16 struct hid_local { unsigned usage[HID_MAX_USAGES]; /* usage array */ unsigned collection_index[HID_MAX_USAGES]; /* collection index array */ unsigned usage_index; unsigned usage_minimum; unsigned delimiter_depth; unsigned delimiter_branch; }; /* * This is the collection stack. We climb up the stack to determine * application and function of each field. */ struct hid_collection { unsigned type; unsigned usage; unsigned level; }; struct hid_usage { unsigned hid; /* hid usage code */ unsigned collection_index; /* index into collection array */ /* hidinput data */ __u16 code; /* input driver code */ __u8 type; /* input driver type */ __s8 hat_min; /* hat switch fun */ __s8 hat_max; /* ditto */ __s8 hat_dir; /* ditto */ }; struct hid_input; struct hid_field { unsigned physical; /* physical usage for this field */ unsigned logical; /* logical usage for this field */ unsigned application; /* application usage for this field */ struct hid_usage *usage; /* usage table for this function */ unsigned maxusage; /* maximum usage index */ unsigned flags; /* main-item flags (i.e. volatile,array,constant) */ unsigned report_offset; /* bit offset in the report */ unsigned report_size; /* size of this field in the report */ unsigned report_count; /* number of this field in the report */ unsigned report_type; /* (input,output,feature) */ __s32 *value; /* last known value(s) */ __s32 logical_minimum; __s32 logical_maximum; __s32 physical_minimum; __s32 physical_maximum; __s32 unit_exponent; unsigned unit; struct hid_report *report; /* associated report */ unsigned index; /* index into report->field[] */ /* hidinput data */ struct hid_input *hidinput; /* associated input structure */ __u16 dpad; /* dpad input code */ }; #define HID_MAX_FIELDS 128 struct hid_report { struct list_head list; unsigned id; /* id of this report */ unsigned type; /* report type */ struct hid_field *field[HID_MAX_FIELDS]; /* fields of the report */ unsigned maxfield; /* maximum valid field index */ unsigned size; /* size of the report (bits) */ struct hid_device *device; /* associated device */ }; struct hid_report_enum { unsigned numbered; struct list_head report_list; struct hid_report *report_id_hash[256]; }; #define HID_REPORT_TYPES 3 #define HID_MIN_BUFFER_SIZE 64 /* make sure there is at least a packet size of space */ #define HID_MAX_BUFFER_SIZE 4096 /* 4kb */ #define HID_CONTROL_FIFO_SIZE 256 /* to init devices with >100 reports */ #define HID_OUTPUT_FIFO_SIZE 64 struct hid_control_fifo { unsigned char dir; struct hid_report *report; char *raw_report; }; struct hid_output_fifo { struct hid_report *report; char *raw_report; }; #define HID_CLAIMED_INPUT 1 #define HID_CLAIMED_HIDDEV 2 #define HID_CLAIMED_HIDRAW 4 #define HID_STAT_ADDED 1 #define HID_STAT_PARSED 2 struct hid_input { struct list_head list; struct hid_report *report; struct input_dev *input; }; enum hid_type { HID_TYPE_OTHER = 0, HID_TYPE_USBMOUSE }; struct hid_driver; struct hid_ll_driver; struct hid_device { /* device report descriptor */ __u8 *rdesc; unsigned rsize; struct hid_collection *collection; /* List of HID collections */ unsigned collection_size; /* Number of allocated hid_collections */ unsigned maxcollection; /* Number of parsed collections */ unsigned maxapplication; /* Number of applications */ __u16 bus; /* BUS ID */ __u32 vendor; /* Vendor ID */ __u32 product; /* Product ID */ __u32 version; /* HID version */ enum hid_type type; /* device type (mouse, kbd, ...) */ unsigned country; /* HID country */ struct hid_report_enum report_enum[HID_REPORT_TYPES]; struct device dev; /* device */ struct hid_driver *driver; struct hid_ll_driver *ll_driver; unsigned int status; /* see STAT flags above */ unsigned claimed; /* Claimed by hidinput, hiddev? */ unsigned quirks; /* Various quirks the device can pull on us */ struct list_head inputs; /* The list of inputs */ void *hiddev; /* The hiddev structure */ void *hidraw; int minor; /* Hiddev minor number */ int open; /* is the device open by anyone? */ char name[128]; /* Device name */ char phys[64]; /* Device physical location */ char uniq[64]; /* Device unique identifier (serial #) */ void *driver_data; /* temporary hid_ff handling (until moved to the drivers) */ int (*ff_init)(struct hid_device *); /* hiddev event handler */ int (*hiddev_connect)(struct hid_device *, unsigned int); void (*hiddev_disconnect)(struct hid_device *); void (*hiddev_hid_event) (struct hid_device *, struct hid_field *field, struct hid_usage *, __s32); void (*hiddev_report_event) (struct hid_device *, struct hid_report *); /* handler for raw input (Get_Report) data, used by hidraw */ int (*hid_get_raw_report) (struct hid_device *, unsigned char, __u8 *, size_t, unsigned char); /* handler for raw output data, used by hidraw */ int (*hid_output_raw_report) (struct hid_device *, __u8 *, size_t, unsigned char); /* debugging support via debugfs */ unsigned short debug; struct dentry *debug_dir; struct dentry *debug_rdesc; struct dentry *debug_events; struct list_head debug_list; wait_queue_head_t debug_wait; }; static inline void *hid_get_drvdata(struct hid_device *hdev) { return dev_get_drvdata(&hdev->dev); } static inline void hid_set_drvdata(struct hid_device *hdev, void *data) { dev_set_drvdata(&hdev->dev, data); } #define HID_GLOBAL_STACK_SIZE 4 #define HID_COLLECTION_STACK_SIZE 4 struct hid_parser { struct hid_global global; struct hid_global global_stack[HID_GLOBAL_STACK_SIZE]; unsigned global_stack_ptr; struct hid_local local; unsigned collection_stack[HID_COLLECTION_STACK_SIZE]; unsigned collection_stack_ptr; struct hid_device *device; }; struct hid_class_descriptor { __u8 bDescriptorType; __le16 wDescriptorLength; } __attribute__ ((packed)); struct hid_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 bcdHID; __u8 bCountryCode; __u8 bNumDescriptors; struct hid_class_descriptor desc[1]; } __attribute__ ((packed)); #define HID_DEVICE(b, ven, prod) \ .bus = (b), \ .vendor = (ven), .product = (prod) #define HID_USB_DEVICE(ven, prod) HID_DEVICE(BUS_USB, ven, prod) #define HID_BLUETOOTH_DEVICE(ven, prod) HID_DEVICE(BUS_BLUETOOTH, ven, prod) #define HID_REPORT_ID(rep) \ .report_type = (rep) #define HID_USAGE_ID(uhid, utype, ucode) \ .usage_hid = (uhid), .usage_type = (utype), .usage_code = (ucode) /* we don't want to catch types and codes equal to 0 */ #define HID_TERMINATOR (HID_ANY_ID - 1) struct hid_report_id { __u32 report_type; }; struct hid_usage_id { __u32 usage_hid; __u32 usage_type; __u32 usage_code; }; /** * struct hid_driver * @name: driver name (e.g. "Footech_bar-wheel") * @id_table: which devices is this driver for (must be non-NULL for probe * to be called) * @dyn_list: list of dynamically added device ids * @dyn_lock: lock protecting @dyn_list * @probe: new device inserted * @remove: device removed (NULL if not a hot-plug capable driver) * @report_table: on which reports to call raw_event (NULL means all) * @raw_event: if report in report_table, this hook is called (NULL means nop) * @usage_table: on which events to call event (NULL means all) * @event: if usage in usage_table, this hook is called (NULL means nop) * @report_fixup: called before report descriptor parsing (NULL means nop) * @input_mapping: invoked on input registering before mapping an usage * @input_mapped: invoked on input registering after mapping an usage * @feature_mapping: invoked on feature registering * @input_register: called just before input device is registered after reports * are parsed. * @suspend: invoked on suspend (NULL means nop) * @resume: invoked on resume if device was not reset (NULL means nop) * @reset_resume: invoked on resume if device was reset (NULL means nop) * * raw_event and event should return 0 on no action performed, 1 when no * further processing should be done and negative on error * * input_mapping shall return a negative value to completely ignore this usage * (e.g. doubled or invalid usage), zero to continue with parsing of this * usage by generic code (no special handling needed) or positive to skip * generic parsing (needed special handling which was done in the hook already) * input_mapped shall return negative to inform the layer that this usage * should not be considered for further processing or zero to notify that * no processing was performed and should be done in a generic manner * Both these functions may be NULL which means the same behavior as returning * zero from them. */ struct hid_driver { char *name; const struct hid_device_id *id_table; struct list_head dyn_list; spinlock_t dyn_lock; int (*probe)(struct hid_device *dev, const struct hid_device_id *id); void (*remove)(struct hid_device *dev); const struct hid_report_id *report_table; int (*raw_event)(struct hid_device *hdev, struct hid_report *report, u8 *data, int size); const struct hid_usage_id *usage_table; int (*event)(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value); __u8 *(*report_fixup)(struct hid_device *hdev, __u8 *buf, unsigned int *size); int (*input_mapping)(struct hid_device *hdev, struct hid_input *hidinput, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max); int (*input_mapped)(struct hid_device *hdev, struct hid_input *hidinput, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max); void (*feature_mapping)(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage); int (*input_register)(struct hid_device *hdev, struct hid_input *hidinput); #ifdef CONFIG_PM int (*suspend)(struct hid_device *hdev, pm_message_t message); int (*resume)(struct hid_device *hdev); int (*reset_resume)(struct hid_device *hdev); #endif /* private: */ struct device_driver driver; }; /** * hid_ll_driver - low level driver callbacks * @start: called on probe to start the device * @stop: called on remove * @open: called by input layer on open * @close: called by input layer on close * @hidinput_input_event: event input event (e.g. ff or leds) * @parse: this method is called only once to parse the device data, * shouldn't allocate anything to not leak memory */ struct hid_ll_driver { int (*start)(struct hid_device *hdev); void (*stop)(struct hid_device *hdev); int (*open)(struct hid_device *hdev); void (*close)(struct hid_device *hdev); int (*power)(struct hid_device *hdev, int level); int (*hidinput_input_event) (struct input_dev *idev, unsigned int type, unsigned int code, int value); int (*parse)(struct hid_device *hdev); }; #define PM_HINT_FULLON 1<<5 #define PM_HINT_NORMAL 1<<1 /* Applications from HID Usage Tables 4/8/99 Version 1.1 */ /* We ignore a few input applications that are not widely used */ #define IS_INPUT_APPLICATION(a) (((a >= 0x00010000) && (a <= 0x00010008)) || (a == 0x00010080) || (a == 0x000c0001) || ((a >= 0x000d0002) && (a <= 0x000d0006))) /* HID core API */ extern int hid_debug; extern int hid_add_device(struct hid_device *); extern void hid_destroy_device(struct hid_device *); extern int __must_check __hid_register_driver(struct hid_driver *, struct module *, const char *mod_name); static inline int __must_check hid_register_driver(struct hid_driver *driver) { return __hid_register_driver(driver, THIS_MODULE, KBUILD_MODNAME); } extern void hid_unregister_driver(struct hid_driver *); extern void hidinput_hid_event(struct hid_device *, struct hid_field *, struct hid_usage *, __s32); extern void hidinput_report_event(struct hid_device *hid, struct hid_report *report); extern int hidinput_connect(struct hid_device *hid, unsigned int force); extern void hidinput_disconnect(struct hid_device *); int hid_set_field(struct hid_field *, unsigned, __s32); int hid_input_report(struct hid_device *, int type, u8 *, int, int); int hidinput_find_field(struct hid_device *hid, unsigned int type, unsigned int code, struct hid_field **field); void hid_output_report(struct hid_report *report, __u8 *data); struct hid_device *hid_allocate_device(void); struct hid_report *hid_register_report(struct hid_device *device, unsigned type, unsigned id); int hid_parse_report(struct hid_device *hid, __u8 *start, unsigned size); int hid_check_keys_pressed(struct hid_device *hid); int hid_connect(struct hid_device *hid, unsigned int connect_mask); void hid_disconnect(struct hid_device *hid); /** * hid_map_usage - map usage input bits * * @hidinput: hidinput which we are interested in * @usage: usage to fill in * @bit: pointer to input->{}bit (out parameter) * @max: maximal valid usage->code to consider later (out parameter) * @type: input event type (EV_KEY, EV_REL, ...) * @c: code which corresponds to this usage and type */ static inline void hid_map_usage(struct hid_input *hidinput, struct hid_usage *usage, unsigned long **bit, int *max, __u8 type, __u16 c) { struct input_dev *input = hidinput->input; usage->type = type; usage->code = c; switch (type) { case EV_ABS: *bit = input->absbit; *max = ABS_MAX; break; case EV_REL: *bit = input->relbit; *max = REL_MAX; break; case EV_KEY: *bit = input->keybit; *max = KEY_MAX; break; case EV_LED: *bit = input->ledbit; *max = LED_MAX; break; } } /** * hid_map_usage_clear - map usage input bits and clear the input bit * * The same as hid_map_usage, except the @c bit is also cleared in supported * bits (@bit). */ static inline void hid_map_usage_clear(struct hid_input *hidinput, struct hid_usage *usage, unsigned long **bit, int *max, __u8 type, __u16 c) { hid_map_usage(hidinput, usage, bit, max, type, c); clear_bit(c, *bit); } /** * hid_parse - parse HW reports * * @hdev: hid device * * Call this from probe after you set up the device (if needed). Your * report_fixup will be called (if non-NULL) after reading raw report from * device before passing it to hid layer for real parsing. */ static inline int __must_check hid_parse(struct hid_device *hdev) { int ret; if (hdev->status & HID_STAT_PARSED) return 0; ret = hdev->ll_driver->parse(hdev); if (!ret) hdev->status |= HID_STAT_PARSED; return ret; } /** * hid_hw_start - start underlaying HW * * @hdev: hid device * @connect_mask: which outputs to connect, see HID_CONNECT_* * * Call this in probe function *after* hid_parse. This will setup HW buffers * and start the device (if not deffered to device open). hid_hw_stop must be * called if this was successful. */ static inline int __must_check hid_hw_start(struct hid_device *hdev, unsigned int connect_mask) { int ret = hdev->ll_driver->start(hdev); if (ret || !connect_mask) return ret; ret = hid_connect(hdev, connect_mask); if (ret) hdev->ll_driver->stop(hdev); return ret; } /** * hid_hw_stop - stop underlaying HW * * @hdev: hid device * * This is usually called from remove function or from probe when something * failed and hid_hw_start was called already. */ static inline void hid_hw_stop(struct hid_device *hdev) { hid_disconnect(hdev); hdev->ll_driver->stop(hdev); } /** * hid_hw_open - signal underlaying HW to start delivering events * * @hdev: hid device * * Tell underlying HW to start delivering events from the device. * This function should be called sometime after successful call * to hid_hiw_start(). */ static inline int __must_check hid_hw_open(struct hid_device *hdev) { return hdev->ll_driver->open(hdev); } /** * hid_hw_close - signal underlaying HW to stop delivering events * * @hdev: hid device * * This function indicates that we are not interested in the events * from this device anymore. Delivery of events may or may not stop, * depending on the number of users still outstanding. */ static inline void hid_hw_close(struct hid_device *hdev) { hdev->ll_driver->close(hdev); } /** * hid_hw_power - requests underlying HW to go into given power mode * * @hdev: hid device * @level: requested power level (one of %PM_HINT_* defines) * * This function requests underlying hardware to enter requested power * mode. */ static inline int hid_hw_power(struct hid_device *hdev, int level) { return hdev->ll_driver->power ? hdev->ll_driver->power(hdev, level) : 0; } void hid_report_raw_event(struct hid_device *hid, int type, u8 *data, int size, int interrupt); extern int hid_generic_init(void); extern void hid_generic_exit(void); /* HID quirks API */ u32 usbhid_lookup_quirk(const u16 idVendor, const u16 idProduct); int usbhid_quirks_init(char **quirks_param); void usbhid_quirks_exit(void); void usbhid_set_leds(struct hid_device *hid); #ifdef CONFIG_HID_PID int hid_pidff_init(struct hid_device *hid); #else #define hid_pidff_init NULL #endif #define dbg_hid(format, arg...) \ do { \ if (hid_debug) \ printk(KERN_DEBUG "%s: " format, __FILE__, ##arg); \ } while (0) #define hid_printk(level, hid, fmt, arg...) \ dev_printk(level, &(hid)->dev, fmt, ##arg) #define hid_emerg(hid, fmt, arg...) \ dev_emerg(&(hid)->dev, fmt, ##arg) #define hid_crit(hid, fmt, arg...) \ dev_crit(&(hid)->dev, fmt, ##arg) #define hid_alert(hid, fmt, arg...) \ dev_alert(&(hid)->dev, fmt, ##arg) #define hid_err(hid, fmt, arg...) \ dev_err(&(hid)->dev, fmt, ##arg) #define hid_notice(hid, fmt, arg...) \ dev_notice(&(hid)->dev, fmt, ##arg) #define hid_warn(hid, fmt, arg...) \ dev_warn(&(hid)->dev, fmt, ##arg) #define hid_info(hid, fmt, arg...) \ dev_info(&(hid)->dev, fmt, ##arg) #define hid_dbg(hid, fmt, arg...) \ dev_dbg(&(hid)->dev, fmt, ##arg) #endif /* __KERNEL__ */ #endif
# Summary MVVM ## MVVM Architecture - Merupakan singkatan dari Model-View ViewModel - Memisahkan logic dengan tampilan (view) ke dalam View Model ### Keuntungan 1. Reusability > jika ada beberapa tampilan yang memerlukan alur logic yang sama, mereka bisa menggunakan ViewModel yang sama 2. Maintainabillity > Mudah dirawat karena pekerjaan terkait tampilan tidak tertumpuk bersama logic 3. Testabillity Pengujian menjadi terpisa antara pengujian tampilan dengan pengujian logic sehingga dapat meningkatkan produktivitas pada pengujian ### Struktur Direktori - Model memiliki 2 bagian, yaitu bentuk data yang akan digunakan dan sumber dari data tersebut - Tiap screen diletakkan dalam sebuah direktori yang di dalamnya terdapat View dan ViewModel #### Model - Bentuk data yang akan digunakan, dibuat dalam bentuk class - Data-data yang dimuat, diletakkan pada property #### Model API Merupakan class yang digunakan untuk melakukan interaksi dengan API (get, post, put, delete), yang dimana data responsenya akan di ubah menjadi class Model. #### ViewModel - Menyimpan data-data dan logic yang diperlukan halaman ContactScreen - Jika widget lain memerlukan logic yang sama, dapat menggunakan ViewModel ini juga #### Menampilkan Data di View - Letakkan pada bagian build - Menggunakan getters yang ada pada ViewModel - Data dapat langsung ditampilkan pada widgets
import { Router } from 'express'; import ProductManager from '../clases/productManager.js'; const products = Router(); export const PERSISTENT_PRODUCTS = new ProductManager('src/data/products.json'); products.get('/', async (req,res) => { try { const limit = req.query.limit; const products = await PERSISTENT_PRODUCTS.getProducts(); if(!limit) return res.send({products}) res.send({products: products.slice(0, limit)}); } catch(e) { res.send(e) } }) products.get('/:pid', async (req,res) => { try { const id = req.params.pid; const users = await PERSISTENT_PRODUCTS.getProducts(); const prod = users.find(user => user.id == id) if(!prod) throw {status: 404, message: 'Producto no encontrado'} res.send({prod}) } catch(e) { res.status(e.status).send(e); } }) products.post('/', async (req,res) => { try { const { title, description, code, price, status, stock, category, thumbnails } = req.body; if( !title || !description || !code || !price || !status || !stock || !category ) throw {status: 400, message: 'Faltan datos para crear el producto'} PERSISTENT_PRODUCTS.addProduct({ title, description, code, price, status, stock, category, thumbnails }); res.status(201).send({message: 'Producto creado correctamente!'}); } catch(e) { res.status(e.status).send(e); } }) products.put('/:pid', async(req,res) => { try { const {title, description, price, code, stock, status, category} = req.body; const id = req.params.pid; const products = await PERSISTENT_PRODUCTS.getProducts(); const prod = products.find(prod => prod.id == id); if(!prod) throw {status: 404, message: 'No se encontró el producto'}; if(!title || !description || !price || !code || !stock || !status || !category) throw {status: 400, message: 'Faltan campos para actualizar el producto'} if(req.body.id) throw {status: 404, message: 'No puedes alterar el id del producto'}; await PERSISTENT_PRODUCTS.updateProduct(id, req.body); res.status(201).send({message: 'Objeto actualizado correctamente!'}); } catch(error) { res.status(error.status).send(error); } }) products.delete("/:pid", async (req,res) => { try { const id = req.params.pid; const prod = await PERSISTENT_PRODUCTS.getProducts().find(product => product.id == id) if(!prod) throw {status: 400, message:'No se encontro el producto!'}; await PERSISTENT_PRODUCTS.deleteProduct(id); res.send({message: 'Producto borrado con exito'}) } catch(e) { res.status(e.status).send(e) } }) export default products;
// // ProfileHeader.swift // TwitterClone // // Created by Saleh Masum on 5/7/2022. // import UIKit class ProfileTableViewHeader: UIView { private let joinedDateLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Joined October 2012" label.textColor = .secondaryLabel label.font = .systemFont(ofSize: 14, weight: .regular) return label }() private let joinedDateImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(systemName: "calendar", withConfiguration: UIImage.SymbolConfiguration(pointSize: 14)) imageView.tintColor = .secondaryLabel imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private let userBioLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .label label.numberOfLines = 3 label.text = "iOS Engineer" return label }() private let userNameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "@salehmasum" label.textColor = .secondaryLabel label.font = .systemFont(ofSize: 18, weight: .regular) return label }() private let displayNameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Saleh Masum" label.textColor = .label label.font = .systemFont(ofSize: 22, weight: .bold) return label }() private let profileAvatarImageView: UIImageView = { let imageView = UIImageView() imageView.clipsToBounds = true imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 40 imageView.image = UIImage(systemName: "person") imageView.backgroundColor = .yellow imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private let profileHeaderImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = UIImage(named: "header") imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() override init(frame: CGRect) { super.init(frame: frame) addSubview(profileHeaderImageView) addSubview(profileAvatarImageView) addSubview(displayNameLabel) addSubview(userNameLabel) addSubview(userBioLabel) addSubview(joinedDateImageView) addSubview(joinedDateLabel) configureConstraints() } private func configureConstraints() { let profileHeaderImageConstraints = [ profileHeaderImageView.leadingAnchor.constraint(equalTo: leadingAnchor), profileHeaderImageView.topAnchor.constraint(equalTo: topAnchor), profileHeaderImageView.trailingAnchor.constraint(equalTo: trailingAnchor), profileHeaderImageView.heightAnchor.constraint(equalToConstant: 180) ] let profileAvatarImageViewConstraints = [ profileAvatarImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), profileAvatarImageView.centerYAnchor.constraint(equalTo: profileHeaderImageView.bottomAnchor, constant: 10), profileAvatarImageView.widthAnchor.constraint(equalToConstant: 80), profileAvatarImageView.heightAnchor.constraint(equalToConstant: 80) ] let displayNameLabelConstraints = [ displayNameLabel.leadingAnchor.constraint(equalTo: profileAvatarImageView.leadingAnchor), displayNameLabel.topAnchor.constraint(equalTo: profileAvatarImageView.bottomAnchor, constant: 20) ] let userNameLabelConstraints = [ userNameLabel.leadingAnchor.constraint(equalTo: displayNameLabel.leadingAnchor), userNameLabel.topAnchor.constraint(equalTo: displayNameLabel.bottomAnchor, constant: 5) ] let userBioLabelConstraints = [ userBioLabel.leadingAnchor.constraint(equalTo: displayNameLabel.leadingAnchor), userBioLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5), userBioLabel.topAnchor.constraint(equalTo: userNameLabel.bottomAnchor, constant: 15) ] let joinedDateImageViewConstraints = [ joinedDateImageView.leadingAnchor.constraint(equalTo: displayNameLabel.leadingAnchor), joinedDateImageView.topAnchor.constraint(equalTo: userBioLabel.bottomAnchor, constant: 5) ] let joinedDateLabelConstraints = [ joinedDateLabel.leadingAnchor.constraint(equalTo: joinedDateImageView.trailingAnchor, constant: 2), joinedDateLabel.bottomAnchor.constraint(equalTo: joinedDateImageView.bottomAnchor) ] NSLayoutConstraint.activate(profileHeaderImageConstraints) NSLayoutConstraint.activate(profileAvatarImageViewConstraints) NSLayoutConstraint.activate(displayNameLabelConstraints) NSLayoutConstraint.activate(userNameLabelConstraints) NSLayoutConstraint.activate(userBioLabelConstraints) NSLayoutConstraint.activate(joinedDateImageViewConstraints) NSLayoutConstraint.activate(joinedDateLabelConstraints) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Type Ahead 👀</title> <link rel="stylesheet" href="style.css"> </head> <body> <form class="search-form"> <input type="text" class="search" placeholder="City or State"> <ul class="suggestions"> <li>Filter for a city</li> <li>or a state</li> </ul> </form> <script> // STEPS INLVOLVED // // ------ GET DATA FROM MY URL AND STORE IT INTO MY CITIES ARRAY ------ // //----- NEED TO CONVERT MY RAW DATA INTO JSON -------// // ------ ONCE I'VE STORED MY DATA INTO MY ARRAY I NEED TO SET UP THE FILTER FUNCTIONALITY // // ------ CHECK IF WHAT USER IS INPUTTING MATCHES ANY OF THE CITIES IN MY JSON FILE ------- // // -------- IF IT DOES MATCH THEN DISPLAY THAT DATA TO MY HTML PAGE -------- // const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; console.log(endpoint); const cities = []; fetch(endpoint) .then(blob => blob.json()) .then(data => cities.push(...data)) function findMatches(wordToMatch, cities){ return cities.filter(place => { const regex = new RegExp(wordToMatch, 'gi'); return place.city.match(regex) || place.state.match(regex); }); } function displayMatches(){ const matchArray = findMatches(this.value, cities); // gives to me all the matches we have in our data // Once we have our matches as per above we then need to loop through each match and output it to our html page // Old way would be for loop which I'm used to but with es6 we can use the map method const html = matchArray.map(place =>{ return` <li> <span class="name">${place.city},${place.state}</span> <span class="population">${place.population}</span> </li> `; }).join(''); console.log(html); suggestions.innerHTML = html; } const searchInput = document.querySelector('.search'); const suggestions = document.querySelector('.suggestions'); searchInput.addEventListener('change', displayMatches); searchInput.addEventListener('keyup', displayMatches); // fetch(endpoint); // .then(function(blob){ // return blob.json(); // }) // .then(function(data){ // console.log(data); // }); </script> </body> </html>
from fastapi import APIRouter,status,Depends from fastapi.exceptions import HTTPException from database import Session,engine from schemas import SignUpModel,LoginModel from models import User from fastapi.exceptions import HTTPException from werkzeug.security import generate_password_hash , check_password_hash from fastapi_jwt_auth import AuthJWT from fastapi.encoders import jsonable_encoder auth_router=APIRouter( prefix='/auth', tags=['auth'] ) session=Session(bind=engine) @auth_router.get('/') async def hello(Authorize:AuthJWT=Depends()): """ ## Sample hello world route """ try: Authorize.jwt_required() except Exception as e: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Token" ) return {"message":"Hello World"} @auth_router.post('/signup', status_code=status.HTTP_201_CREATED ) async def signup(user:SignUpModel): """ ## Create a user This requires the following ``` username:int email:str password:str is_staff:bool is_active:bool ``` """ db_email=session.query(User).filter(User.email==user.email).first() if db_email is not None: return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="User with the email already exists" ) db_username=session.query(User).filter(User.username==user.username).first() if db_username is not None: return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="User with the username already exists" ) new_user=User( username=user.username, email=user.email, password=generate_password_hash(user.password), is_active=user.is_active, is_staff=user.is_staff ) session.add(new_user) session.commit() return new_user #login route @auth_router.post('/login',status_code=200) async def login(user:LoginModel,Authorize:AuthJWT=Depends()): """ ## Login a user This requires ``` username:str password:str ``` and returns a token pair `access` and `refresh` """ db_user=session.query(User).filter(User.username==user.username).first() if db_user and check_password_hash(db_user.password, user.password): access_token=Authorize.create_access_token(subject=db_user.username) refresh_token=Authorize.create_refresh_token(subject=db_user.username) response={ "access":access_token, "refresh":refresh_token } return jsonable_encoder(response) raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid Username Or Password" ) #refreshing tokens @auth_router.get('/refresh') async def refresh_token(Authorize:AuthJWT=Depends()): """ ## Create a fresh token This creates a fresh token. It requires an refresh token. """ try: Authorize.jwt_refresh_token_required() except Exception as e: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Please provide a valid refresh token" ) current_user=Authorize.get_jwt_subject() access_token=Authorize.create_access_token(subject=current_user) return jsonable_encoder({"access":access_token}) # from fastapi import APIRouter, status, Depends # from fastapi.exceptions import HTTPException # from database import Session, engine # from schemas import SignUpModel, LoginModel # from models import User # from fastapi.exceptions import HTTPException # from werkzeug.security import generate_password_hash, check_password_hash # from fastapi_jwt_auth import AuthJWT # from fastapi.encoders import jsonable_encoder # auth_router=APIRouter( # prefix='/auth', # tags=['auth'] # ) # session=Session(bind=engine) # @auth_router.get('/') # async def hello(Authorize:AuthJWT=Depends()): # """ # ## Sample hello world route # """ # try: # Authorize.jwt_required() # except Exception as e: # raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, # detail="Invalid Token" # ) # return {"message":"Hello World"} # @auth_router.post('/signup', # status_code=status.HTTP_201_CREATED # ) # async def signup(user:SignUpModel): # """ # ## Create a user # This requires the following # ``` # username:int # email:str # password:str # is_staff:bool # is_active:bool # ``` # """ # db_email=session.query(User).filter(User.email==user.email).first() # if db_email is not None: # return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, # detail="User with the email already exists" # ) # db_username=session.query(User).filter(User.username==user.username).first() # if db_username is not None: # return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, # detail="User with the username already exists" # ) # new_user=User( # username=user.username, # email=user.email, # password=generate_password_hash(user.password), # is_active=user.is_active, # is_staff=user.is_staff # ) # session.add(new_user) # session.commit() # return new_user # @auth_router.post('/login', status_code=200) # async def login(user:LoginModel, Authorize:AuthJWT=Depends()): # """ # ## Login a user # This requires # ``` # username:str # password:str # ``` # and returns a token pair `access` and `refresh` # """ # db_user=session.query(User).filter(User.username==user.username).first() # if db_user and check_password_hash(db_user.password, user.password): # access_token=Authorize.create_access_token(subject=db_user.username) # refresh_token=Authorize.create_refresh_token(subject=db_user.username) # response={ # "access":access_token, # "refresh":refresh_token # } # return jsonable_encoder(response) # raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, # detail="Invalid Username Or Password" # ) # @auth_router.get('/refresh') # async def refresh_token(Authorize:AuthJWT=Depends()): # """ # ## Create a fresh token # This creates a fresh token. It requires an refresh token. # """ # try: # Authorize.jwt_refresh_token_required() # except Exception as e: # raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, # detail="Please provide a valid refresh token" # ) # current_user=Authorize.get_jwt_subject() # access_token=Authorize.create_access_token(subject=current_user) # return jsonable_encoder({"access":access_token})
<?php /** * @file * Module file for Teamleader CRM. * * Provides support for Teamleader's Contact/Company API. * * @see http://apidocs.teamleader.be/crm.php */ define('TEAMLEADER_CRM_CONTACT_OPERATION_LINK', 'link'); define('TEAMLEADER_CRM_CONTACT_OPERATION_UNLINK', 'unlink'); /** * Create a new contact in the Teamleader. * * @param string $forename * Forename of the person. * @param string $surname * Surname of the person. * @param string $email * Email address of the person. * @param array $additional_info * An associative array of optional information about the person. * Ex.: telephone, language, location (country, city, street, ...), ... . * * @return int|bool * If the API operation was successful, then it returns the contact id of * the new contact, else it returns FALSE. */ function teamleader_crm_add_contact($forename, $surname, $email, array $additional_info = array()) { $parameters = array( 'forename' => $forename, 'surname' => $surname, 'email' => $email, ); if (!empty($additional_info)) { $parameters += $additional_info; } $result = teamleader_query_execute('addContact', $parameters); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Fetch contact information from Teamleader. * * @param int $contact_id * Teamleader contact id of the person. * * @return array|bool * If the API operation was successful, then it returns an associative array * of the contact infos, else it returns FALSE. */ function teamleader_crm_get_contact_info($contact_id) { $result = teamleader_query_execute('getContact', array( 'contact_id' => $contact_id, )); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Update an existing contact in the Teamleader. * * @param int $contact_id * Teamleader contact id of the person. * @param array $changes * An associative array of new values of the contact. * Ex.: forename, surname, email, telephone, ... . * @param bool $track_changes * Determine whether this change should be visible to the users on the * web-interface or not. * * @return bool * If the API operation was successful, then it returns TRUE, else it * returns FALSE. */ function teamleader_crm_update_contact($contact_id, array $changes = array(), $track_changes = TRUE) { $parameters = array( 'contact_id' => $contact_id, 'track_changes' => $track_changes, ); if (!empty($changes)) { $parameters += $changes; } $result = teamleader_query_execute('updateContact', $parameters); return $result['status'] == TEAMLEADER_API_STATUS_OK; } /** * Delete a contact from the Teamleader. * * @param int $contact_id * Teamleader contact id of the person. * * @return bool * If the API operation was successful, then it returns TRUE, else it * returns FALSE. */ function teamleader_crm_delete_contact($contact_id) { $result = teamleader_query_execute('deleteContact', array('contact_id' => $contact_id)); return $result['status'] == TEAMLEADER_API_STATUS_OK; } /** * Link or unlink a contact to a company on the Teamleader. * * @param int $contact_id * Teamleader contact id of the person. * @param int $company_id * Teamleader company id of the organization. * @param string $mode * One from TEAMLEADER_CRM_CONTACT_OPERATION_LINK or * TEAMLEADER_CRM_CONTACT_OPERATION_UNLINK, if it set to * TEAMLEADER_CRM_CONTACT_OPERATION_LINK, then the contact will be added to * the company. * If it set to TEAMLEADER_CRM_CONTACT_OPERATION_UNLINK, then the relation * will be removed. * @param string $job_title * Job title of the contact holds at the company. * * @return bool * If the API operation was successful, then it returns TRUE, else it * returns FALSE. */ function teamleader_crm_link_unlink_contact_to_a_company($contact_id, $company_id, $mode, $job_title = '') { $parameters = array( 'contact_id' => $contact_id, 'company_id' => $company_id, 'mode' => $mode, ); if (isset($job_title)) { $parameters['function'] = $job_title; } $result = teamleader_query_execute('linkContactToCompany', $parameters); return $result['status'] == TEAMLEADER_API_STATUS_OK; } /** * Get all contacts from Teamleader. * * @param int $amount * Number of contacts to return in this request. * The default value is the maximum number of contacts per request: 100. * @param int $pageno * The current page id. Default is the first page. * * @return array|bool * If the API operation was successful, then it returns an array * of contacts, else it returns FALSE. */ function teamleader_crm_get_contacts($amount = 100, $pageno = 0) { $result = teamleader_query_execute('getContacts', array( 'amount' => $amount, 'pageno' => $pageno, )); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Search contacts on Teamleader. * * @param string $search_by * Query string. Teamleader will try to match each part of the string to the * forename, surname, company name and email address. * @param int $modified_since * Unix timestamp. Teamleader will only return contacts that have been added * or modified since that timestamp. * @param int $amount * Number of contacts to return in this request. * The default value is the maximum number of contacts per request: 100. * @param int $pageno * The current page id. Default is the first page. * * @return array|string|bool * If the API operation was successful, then it returns an array * of matching contacts or a "[]" string, if there were not match; * else it returns FALSE. */ function teamleader_crm_search_contacts($search_by, $modified_since = NULL, $amount = 100, $pageno = 0) { $parameters = array( 'searchby' => $search_by, 'amount' => $amount, 'pageno' => $pageno, ); if (isset($modified_since)) { $parameters['modifiedsince'] = $modified_since; } $result = teamleader_query_execute('getContacts', $parameters); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Get all contacts from Teamleader, which related to the given company. * * @param int $company_id * Teamleader company id of the organization. * * @return array|bool * If the API operation was successful, then it returns an array * of related contacts, else it returns FALSE. */ function teamleader_crm_get_all_company_contacts($company_id) { $result = teamleader_query_execute('getContactsByCompany', array( 'company_id' => $company_id, )); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Create a new company in the Teamleader. * * @param string $name * Name of the organization. * @param array $additional_info * An associative array of optional information about the organization. * Ex.: email, vat_code, location (country, city, street, ...), ... . * * @return int|bool * If the API operation was successful, then it returns the company id of * the new company, else it returns FALSE. */ function teamleader_crm_add_company($name, $additional_info = array()) { $parameters = array( 'name' => $name, ); if (!empty($additional_info)) { $parameters += $additional_info; } $result = teamleader_query_execute('addCompany', $parameters); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Fetch company information from Teamleader. * * @param int $company_id * Teamleader company id of the organization. * * @return array|bool * If the API operation was successful, then it returns an associative array * of the company infos, else it returns FALSE. */ function teamleader_crm_get_company_info($company_id) { $result = teamleader_query_execute('getCompany', array( 'company_id' => $company_id, )); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Update an existing company in the Teamleader. * * @param int $company_id * Teamleader company id of the organization. * @param array $changes * An associative array of new values of the company. * Ex.: name, vat_code, email, website, ... . * @param bool $track_changes * Determine whether this change should be visible to the users on the * web-interface or not. * * @return bool * If the API operation was successful, then it returns TRUE, else it * returns FALSE. */ function teamleader_crm_update_company($company_id, array $changes = array(), $track_changes = TRUE) { $parameters = array( 'company_id' => $company_id, 'track_changes' => $track_changes, ); if (!empty($changes)) { $parameters += $changes; } $result = teamleader_query_execute('updateCompany', $parameters); return $result['status'] == TEAMLEADER_API_STATUS_OK; } /** * Delete a company from the Teamleader. * * @param int $company_id * Teamleader company id of the organization. * * @return bool * If the API operation was successful, then it returns TRUE, else it * returns FALSE. */ function teamleader_crm_delete_company($company_id) { $result = teamleader_query_execute('deleteCompany', array('company_id' => $company_id)); return $result['status'] == TEAMLEADER_API_STATUS_OK; } /** * Get all companies from Teamleader. * * @param int $amount * Number of companies to return in this request. * The default value is the maximum number of companies per request: 100. * @param int $pageno * The current page id. Default is the first page. * * @return array|bool * If the API operation was successful, then it returns an array * of companies, else it returns FALSE. */ function teamleader_crm_get_companies($amount = 100, $pageno = 0) { $result = teamleader_query_execute('getCompanies', array( 'amount' => $amount, 'pageno' => $pageno, )); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Search companies on Teamleader. * * @param string $search_by * Query string. Teamleader will try to match each part of the string to the * company name and email address. * @param int $modified_since * Unix timestamp. Teamleader will only return companies that have been added * or modified since that timestamp. * @param int $amount * Number of companies to return in this request. * The default value is the maximum number of companies per request: 100. * @param int $pageno * The current page id. Default is the first page. * * @return array|string|bool * If the API operation was successful, then it returns an array * of matching companies or a "[]" string, if there were not match; * else it returns FALSE. */ function teamleader_crm_search_companies($search_by, $modified_since = NULL, $amount = 100, $pageno = 0) { $parameters = array( 'searchby' => $search_by, 'amount' => $amount, 'pageno' => $pageno, ); if (isset($modified_since)) { $parameters['modifiedsince'] = $modified_since; } $result = teamleader_query_execute('getCompanies', $parameters); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; } /** * Getting all possible business types in a country. * * @param string $country_code * Country code according to ISO 3166-1 alpha-2. For Belgium: "BE". * * @return array|bool * If the API operation was successful, then it returns an array of * associative arrays. Each of them contains a name of business type * (legal structure), that a company can have within a certain country. * Else it returns FALSE. */ function teamleader_crm_get_business_types_in_this_country($country_code) { $result = teamleader_query_execute('getBusinessTypes', array( 'country' => $country_code, )); if ($result['status'] == TEAMLEADER_API_STATUS_OK) { return $result['response']; } else { drupal_set_message($result['message'], 'error'); } return FALSE; }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Float</title> <style> body { background-color: #222; } .c1 { background-color: red; float: right; } .c2 { background-color: green; clear: right; /* Faz com que os elementos não invada a area block do outro elemento que está "flutuando". */ float: left; } .c3 { background-color: blue; clear: both; /* Faz o papel do clear right e left. */ } .c4 { background-color: orange; float: right; } div { height: 150px; width: 150px; /*float: right; Joga os elementos para o lado direito. */ /*float: left; Joga os elementos para o lado esquerdo. */ } </style> </head> <body> <div class="c1"></div> <div class="c2"></div> <div class="c3"></div> <div class="c4"></div> </body> </html>
// Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 import QtQuick 2.4 /* This is a manual test for the dummy context described here: http://blog.qt.io/blog/2011/07/28/mockup-data-for-the-qml-designer The dummy context that defines parent and root is dummydata/context/main.qml. Without the dummy context the root item does not have a defined size and the color of the inner rectangle is not defined. When Designer shows an error message about the missing parent, click "Ignore" to see the rendering. */ Rectangle { width: parent.width height: parent.height Rectangle { anchors.centerIn: parent width: parent.width / 2 height: parent.height / 2 color: root.color } }
;quiz01_1.asm ;unsigned char num1 = 250; //data type: 8 bits ;unsigned char num2 = 200; //data type: 8 bits ;unsigned char num3 = 120; //data type: 8 bits ;unsigned short sum = 0 //data type: 16 bits ;unsigned int product = 0; //data type: 32 bits ;sum = short(num1 + num2); ;product = sum * short(num3); section .data num1 db 250 ;num1 = FAh num2 db 200 ;num2 = C8h num3 db 120 ;num3 = 78h sum dw 0 ;sum = 0000h product dd 0 ;product = 0000 0000h section .text global _start _start: mov ah, 0 ;ah = 0 mov al, byte[num1] ;al = num1 = FAh add al, byte[num2] ;al = al+num2 = FAh+C8h = C2h adc ah, 0 ;ah = ah+0+CF = 01h mov word[sum], ax ;sum = ax = 01C2h mov al, byte[num3] ;al = num3 = 78h cbw ;convert al to ax = 0078h mul word[sum] ;dx:ax = ax*sum = 0000:D2F0h mov word[product+2], dx ;product+2 = dx = 0000h mov word[product+0], ax ;product+0 = ax = D2F0h mov rax, 60 ;terminate excuting process mov rdi, 0 ;exit status syscall ;calling system services
<?php class Daemon { /** @var $TTY the console to output to/from */ public $TTY; /** @var $interface the interface to connect with */ public $interface = NULL; /** @var $interfaceSettingName the interface name */ public $interfaceSettingName = NULL; /** @var $DaemonName the name of the Daemon */ public $DaemonName; /** @var $config the configuration class */ private $config; /** @var $mysqli the mysqli connection */ private $mysqli; /** @function __construct() Construct daemon class * @param $DaemonName the name to test * @param $interfaceSettingName the interface name * @return void */ public function __construct($DaemonName,$interfaceSettingName) { require_once(WEBROOT."/lib/fog/Config.class.php"); $this->config = new Config(); $this->TTY = constant(strtoupper($DaemonName).'DEVICEOUTPUT'); $this->DaemonName = ucfirst(strtolower($DaemonName)); $this->interfaceSettingName = $interfaceSettingName; } /** @function __destruct() * @return void */ public function __destruct() { unset($this->config); unset($this->mysqli); } /** @function clear_screen() Clears the screen for information. * @return void */ public function clear_screen() { $this->out(chr(27)."[2J".chr(27)."[;H"); } /** @function wait_db_ready() Waits until mysql is ready to accept connections. * @return void */ public function wait_db_ready() { $this->mysqli = @new mysqli(DATABASE_HOST,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME); // try connection while ($this->mysqli->connect_errno) { $this->out("FOGService:{$this->DaemonName} - Waiting for mysql to be available..\n"); sleep(10); // wait some time @$this->mysqli->connect(DATABASE_HOST,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME); // try again before loop continues } return; } /** @function wait_interface_ready() Waits for the network interface to be ready * so the system can report if it will work or not * @return void */ public function wait_interface_ready() { if ($this->interface == NULL) { $this->out("Getting interface name.. "); $this->FOGCore = $GLOBALS['FOGCore']; $this->out("$this->interface\n"); } while (true) { $retarr = array(); $retarr = $this->FOGCore->getIPAddress(); foreach ($retarr as $line) { if ($line !== false) { $this->out("Interface now ready, with IPAddr $line\n"); break 2; } } $this->out("Interface not ready, waiting..\n"); sleep(10); } } /** @function out() prints the information to the service console files. * @param $string the data to put to log * @param $device the screen to print to defaults to default tty * @return void */ public function out($string,$device=NULL) { if ($device === NULL) {$device = $this->TTY;} file_put_contents($this->TTY,$string,FILE_APPEND); } /** @function getBanner() Prints the FOG banner * @return the banner */ public function getBanner() { $str = " ___ ___ ___ \n"; $str .= " /\ \ /\ \ /\ \ \n"; $str .= " /::\ \ /::\ \ /::\ \ \n"; $str .= " /:/\:\ \ /:/\:\ \ /:/\:\ \ \n"; $str .= " /::\-\:\ \ /:/ \:\ \ /:/ \:\ \ \n"; $str .= " /:/\:\ \:\__\ /:/__/ \:\__\ /:/__/_\:\__\ \n"; $str .= " \/__\:\ \/__/ \:\ \ /:/ / \:\ /\ \/__/ \n"; $str .= " \:\__\ \:\ /:/ / \:\ \:\__\ \n"; $str .= " \/__/ \:\/:/ / \:\/:/ / \n"; $str .= " \::/ / \::/ / \n"; $str .= " \/__/ \/__/ \n"; $str .= "\n"; $str .= " ###########################################\n"; $str .= " # Free Computer Imaging Solution #\n"; $str .= " # #\n"; $str .= " # Created by: #\n"; $str .= " # Chuck Syperski #\n"; $str .= " # Jian Zhang #\n"; $str .= " # Tom Elliott #\n"; $str .= " # #\n"; $str .= " # GNU GPL Version 3 #\n"; $str .= " ###########################################\n"; $str .= "\n"; return $str; } }
Overview ======== CMSIS-Driver defines generic peripheral driver interfaces for middleware making it reusable across a wide range of supported microcontroller devices. The API connects microcontroller peripherals with middleware that implements for example communication stacks, file systems, or graphic user interfaces. More information and usage method please refer to http://www.keil.com/pack/doc/cmsis/Driver/html/index.html. The cmsis_i2c_edma_b2b_transfer_master example shows how to use i2c driver as master to do board to board transfer with EDMA: In this example, one i2c instance as master and another i2c instance on the other board as slave. Master sends a piece of data to slave, and receive a piece of data from slave. This example checks if the data received from slave is correct. Toolchain supported - IAR embedded Workbench 9.10.2 - Keil MDK 5.34 - MCUXpresso 11.5.0 - GCC ARM Embedded 10.2.1 Hardware requirements - Mini/micro USB cable - Two MIMXRT1170-EVK board - Personal Computer Board settings LPI2C one board: + Transfer data from MASTER_BOARD to SLAVE_BOARD of LPI2C interface, LPI2C1 pins of MASTER_BOARD are connected with LPI2C1 pins of SLAVE_BOARD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MASTER_BOARD CONNECTS TO SLAVE_BOARD Pin Name Board Location Pin Name Board Location LPI2C1_SCL J26-12 LPI2C1_SCL J26-12 LPI2C1_SDA J26-10 LPI2C1_SDA J26-10 GND J10-14 GND J10-14 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Prepare the Demo 1. Connect a micro USB cable between the PC host and the OpenSDA USB port on the board. 2. Open a serial terminal on PC for OpenSDA serial device with these settings: - 115200 baud rate - 8 data bits - No parity - One stop bit - No flow control 3. Download the program to the target board. 4. Either press the reset button on your board or launch the debugger in your IDE to begin running the demo. Running the demo When the example runs successfully, you can see the similar information from the terminal as below. ~~~~~~~~~~~~~~~~~~~~~~~~ CMSIS I2C board2board interrupt example -- Master transfer. Master will send data : 0x 0 0x 1 0x 2 0x 3 0x 4 0x 5 0x 6 0x 7 0x 8 0x 9 0x a 0x b 0x c 0x d 0x e 0x f 0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f Receive sent data from slave : 0x 0 0x 1 0x 2 0x 3 0x 4 0x 5 0x 6 0x 7 0x 8 0x 9 0x a 0x b 0x c 0x d 0x e 0x f 0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f End of I2C example . ~~~~~~~~~~~~~~~~~~~~~~~~
import { Todo, Params } from '@/store/todo/types' import { TodoClientInterface } from './types' export class TodoClient implements TodoClientInterface { async getAll() { await new Promise((resolve) => setTimeout(resolve, 3000)) return Promise.resolve( Object.keys(localStorage) .filter((key) => !isNaN(Number(key))) .map((key) => { const todo = JSON.parse(localStorage.getItem(key) as string) as Todo todo.createdAt = new Date(todo.createdAt) todo.updatedAt = new Date(todo.updatedAt) return todo }) ) } get(id: number) { const item = localStorage.getItem(String(id)) if (item === null) { return Promise.reject(new Error(`id: ${id} is not found`)) } return Promise.resolve(JSON.parse(item) as Todo) } create(params: Params) { const todo = this.intitializeTodo(params) localStorage.setItem(String(todo.id), JSON.stringify(todo)) return Promise.resolve(todo) } update(id: number, todo: Todo) { localStorage.removeItem(String(id)) todo.updatedAt = new Date() localStorage.setItem(String(id), JSON.stringify(todo)) return Promise.resolve(todo) } delete(id: number) { localStorage.removeItem(String(id)) return Promise.resolve() } initializeTodo(todo: Params) { const date = new Date() return { id: date.getTime(), title: todo.title, description: todo.description, status: todo.status, createdAt: date, updatedAt: date, } as Todo } }
# MIT License # # Copyright (c) 2022 Mathieu Imfeld # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # class Person: """ A simple class to hold the first and last name of a Person. The first_name only has a read-only property. The last_name is read/write (you may get married) """ def __init__(self, first_name: str, last_name: str): self._first_name = first_name self._last_name = last_name @property def first_name(self): return self._first_name @property def last_name(self): return self._last_name @last_name.setter def last_name(self, value: str): self._last_name = value
import React, { useState } from "react"; import "./FilesTab.css"; // Import your CSS file for styling function FilesTab({ files, activeFile, setActiveFile, DEFAULT_CODE, setFiles, }) { const [fileNameInput, setFileNameInput] = useState(""); const [inputVisible, setInputVisible] = useState(false); const handleAddFile = () => { setInputVisible(true); // Show the input box }; const handleFileClick = (fileName) => { setActiveFile(fileName); }; const handleInputChange = (e) => { setFileNameInput(e.target.value); }; const handleInputBlur = () => { if (fileNameInput.trim() !== "") { saveFileName(); } setInputVisible(false); // Hide the input box }; const handleInputKeyPress = (e) => { if (e.key === "Enter") { saveFileName(); setInputVisible(false); // Hide the input box } }; const saveFileName = () => { const newFile = { name: fileNameInput.trim(), }; setFiles((oldFiles) => ({ ...oldFiles, [newFile.name]: DEFAULT_CODE, })); setFileNameInput(""); }; return ( <div className="FilesTab"> {/* Button to add a new file */} <div className="inputContainer"> <button className="addButton" onClick={handleAddFile}> <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" > <path fill="currentColor" d="M3 1h12.414L21 6.586V12h-2V9h-6V3H5v18h7v2H3zm12 2.414V7h3.586zM20 14v4h4v2h-4v4h-2v-4h-4v-2h4v-4z" /> </svg> </button> </div> {/* Display the list of files */} <div className="fileList"> {/* {files.map((file, index) => ( <div className={`fileItem`} id={`${activeFile === file.name ? 'active' : ''}`} key={index} onClick={() => handleFileClick(file.name)} > {file.name} </div> ))} */} {Object.keys(files).map((fileName, index) => ( <div className={`fileItem`} id={`${activeFile === fileName ? "active" : ""}`} key={index} onClick={() => handleFileClick(fileName)} > {fileName} </div> ))} </div> {/* Input box for adding a new file */} {inputVisible && ( <div className="inputContainer"> <input className="fileInput" type="text" placeholder="Enter file name" value={fileNameInput} onChange={handleInputChange} onBlur={handleInputBlur} onKeyPress={handleInputKeyPress} // Handle Enter key press autoFocus // Auto-focus the input box when it appears /> </div> )} </div> ); } export default FilesTab;
<?php session_start(); require_once "pdo.php"; require_once "util.php"; if (!isset($_SESSION['name'])) { die('Not logged in'); } if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email']) && isset($_POST['headline']) && isset($_POST['summary'])) { if (strlen($_POST['first_name']) < 1 || strlen($_POST['last_name']) < 1 || strlen($_POST['email']) < 1 || strlen($_POST['headline']) < 1 || strlen($_POST['summary']) < 1) { $_SESSION['error'] = "All values are required"; header("Location: add.php"); return; } elseif (strpos($_POST['email'], '@') === false) { $_SESSION['error'] = 'Bad Email'; } elseif (!validatePos()) { $_SESSION['error'] = validatePos(); } else { $stmt = $pdo->prepare('INSERT INTO Profile (user_id, first_name, last_name, email, headline, summary) VALUES ( :uid, :fn, :ln, :em, :he, :su)'); $stmt->execute(array( ':uid' => $_SESSION['user_id'], ':fn' => $_POST['first_name'], ':ln' => $_POST['last_name'], ':em' => $_POST['email'], ':he' => $_POST['headline'], ':su' => $_POST['summary']) ); $profile_id = $pdo->lastInsertId(); $rank = 1; for ($i = 1; $i <= 9; $i++) { if (!isset($_POST['year' . $i])) continue; if (!isset($_POST['desc' . $i])) continue; if(is_numeric($_POST['year' . $i])) { $_SESSION['error'] = 'Position year must be numeric'; } $year = $_POST['year' . $i]; $desc = $_POST['desc' . $i]; $stmt = $pdo->prepare('INSERT INTO Position (profile_id, rank, year, description) VALUES ( :pid, :rank, :year, :desc)'); $stmt->execute(array( ':pid' => $profile_id, ':rank' => $rank, ':year' => $year, ':desc' => $desc) ); $rank++; } // $rank = 1; // for ($i = 1; $i <= 9; $i++) { // if (!isset($_POST['edu_year' . $i])) continue; // if (!isset($_POST['edu_school' . $i])) continue; // $edu_year = $_POST['edu_year' . $i]; // $edu_school = $_POST['edu_school' . $i]; // $stmt = $pdo->prepare("SELECT * FROM Institution where name = :xyz"); // $stmt->execute(array(":xyz" => $edu_school)); // $row = $stmt->fetch(PDO::FETCH_ASSOC); // if ($row) { // $institution_id = $row['institution_id']; // } else { // $stmt = $pdo->prepare('INSERT INTO Institution (name) VALUES ( :name)'); // $stmt->execute(array( // ':name' => $edu_school, // )); // $institution_id = $pdo->lastInsertId(); // } // $stmt = $pdo->prepare('INSERT INTO Education // (profile_id, institution_id, year, rank) // VALUES ( :pid, :institution, :edu_year, :rank)'); // $stmt->execute(array( // ':pid' => $profile_id, // ':institution' => $institution_id, // ':edu_year' => $edu_year, // ':rank' => $rank) // ); // $rank++; // } $_SESSION['success'] = "Record added."; header("Location: index.php"); return; } } ?> <!DOCTYPE html> <html> <head> <?php require_once "head.php"; ?> <title>Abhay Singh Add Page</title> </head> <body> <div class="container"> <h1>Adding Profile for UMSI</h1> <?php flashMessage(); ?> <form method="post"> <p>First Name: <input type="text" name="first_name" size="60"/></p> <p>Last Name: <input type="text" name="last_name" size="60"/></p> <p>Email: <input type="text" name="email" size="30"/></p> <p>Headline:<br/> <input type="text" name="headline" size="80"/></p> <p>Summary:<br/> <textarea name="summary" rows="8" cols="80"></textarea> <!-- <p> Education: <input type="submit" id="addEdu" value="+"> <div id="edu_fields"> </div> </p> --> <p> Position: <input type="submit" id="addPos" value="+"> <div id="position_fields"> </div> </p> <p> <input type="submit" value="Add"> <input type="submit" name="cancel" value="Cancel"> </p> </form> <script> countPos = 0; countEdu = 0; // http://stackoverflow.com/questions/17650776/add-remove-html-inside-div-using-javascript $(document).ready(function () { window.console && console.log('Document ready called'); $('#addPos').click(function (event) { // http://api.jquery.com/event.preventdefault/ event.preventDefault(); if (countPos >= 9) { alert("Maximum of nine position entries exceeded"); return; } countPos++; window.console && console.log("Adding position " + countPos); $('#position_fields').append( '<div id="position' + countPos + '"> \ <p>Year: <input type="text" name="year' + countPos + '" value="" /> \ <input type="button" value="-" onclick="$(\'#position' + countPos + '\').remove();return false;"><br>\ <textarea name="desc' + countPos + '" rows="8" cols="80"></textarea>\ </div>'); }); // $('#addEdu').click(function (event) { // event.preventDefault(); // if (countEdu >= 9) { // alert("Maximum of nine education entries exceeded"); // return; // } // countEdu++; // window.console && console.log("Adding education " + countEdu); // $('#edu_fields').append( // '<div id="edu' + countEdu + '"> \ // <p>Year: <input type="text" name="edu_year' + countEdu + '" value="" /> \ // <input type="button" value="-" onclick="$(\'#edu' + countEdu + '\').remove();return false;"><br>\ // <p>School: <input type="text" size="80" name="edu_school' + countEdu + '" class="school" value="" />\ // </p></div>' // ); // $('.school').autocomplete({ // source: "school.php" // }); // }); }); </script> </div> </body> </html>
<?php namespace App\Livewire; use Livewire\Component; use App\Models\Product as Prd; use App\Http\Requests\ProductRequest; class Product extends Component { public $products, $name, $price, $qty, $id,$searchTerm = ''; public $isOpen = 0; public function render() { $this->products = Prd::where('name', 'like', '%' . $this->searchTerm . '%')->get(); return view('livewire.product'); } public function search() { $this->render(); } public function create() { $this->resetInputFields(); $this->openModal(); } public function openModal(){ $this->isOpen = true; } public function closeModal(){ $this->isOpen = false; } public function resetInputFields(){ $this->name = ''; $this->price = ''; $this->qty = ''; $this->id = ''; } public function store() { $validatedData = $this->validate((new ProductRequest)->rules()); Prd::updateOrCreate(['id' => $this->id], $validatedData ); session()->flash('message', $this->id ? 'Product Updated Successfully.' : 'Product Created Successfully.'); $this->closeModal(); $this->resetInputFields(); } public function edit($id) { $product = Prd::findOrFail($id); $this->id = $id; $this->name = $product->name; $this->price = $product->price; $this->qty = $product->qty; $this->openModal(); } public function delete($id) { Prd::find($id)->delete(); session()->flash('message', 'Product Deleted Successfully.'); } }
package main import ( "fmt" "strings" ) // as a function parameters func customMessage(fn func(m string), msg string) { msg = strings.ToUpper(msg) fn(msg) } func surround() func(msg string) { return func(msg string) { fmt.Printf("%.*s\n", len(msg), "-------------") fmt.Println(msg) fmt.Printf("%.*s\n", len(msg), "-------------") } } func main() { customMessage(surround(), "hello") }
import { StringUtils, getStringInfo, toUpperCase } from '../app/Utils' describe('Utils test suit', () => { // oops test describe('StringUtils tests', () => { let sut: StringUtils; beforeEach(() => { sut = new StringUtils(); console.log('Setup'); }) afterEach(() => { console.log('Teardown'); }) it('should return upperCase', () => { const actual = sut.toUpperCase('abc'); expect(actual).toBe('ABC'); console.log('Actual test'); }); it('should through error invalid args - functions ', () => { function expectError() { const actual = sut.toUpperCase(''); } expect(expectError).toThrow(); expect(expectError).toThrowError('Invalid arguments'); }); it('should through error invalid args - arrow functions ', () => { expect(() => { sut.toUpperCase('') }).toThrowError('Invalid arguments'); }); it('should through error invalid args - try catch ', (done) => { try { sut.toUpperCase(''); done('GetStringInfo should throw error for invalid arg'); // it will fail test if error is not thrown } catch (error) { expect(error).toBeInstanceOf(Error); expect(error).toHaveProperty('message', 'Invalid arguments'); done() } }); }) it('should return uppercase', () => { //arrange const sut = toUpperCase; const expected = 'ABC' //act const actual = sut('abc'); //assert expect(actual).toBe(expected); }); // test for multiple test params describe('ToUpperCase Example', () => { it.each([ { input: 'abc', expected: 'ABC' }, { input: 'cba', expected: 'CBA' }, { input: 'xYZ', expected: 'XYZ' }, ])('$input toUpperCase should be $expected', ({ input, expected }) => { const actual = toUpperCase(input); expect(actual).toBe(expected) }); }) // proper structure for test describe("getStringInfo for arg My-String", () => { test('return right length', () => { const actual = getStringInfo('My-String'); expect(actual.characters.length).toBe(9); }); test('return right lower-case', () => { const actual = getStringInfo('My-String'); expect(actual.lowerCase).toBe('my-string'); }); test('return right upper-case', () => { const actual = getStringInfo('My-String'); expect(actual.upperCase).toBe('MY-STRING'); }); test('return right characters', () => { const actual = getStringInfo('My-String'); expect(actual.characters.length).toBe(9); expect(actual.characters).toContain<string>('M'); }); test('return right extra info', () => { const actual = getStringInfo('My-String'); expect(actual.extraInfo).not.toBe(undefined); expect(actual.extraInfo).not.toBeUndefined(); expect(actual.extraInfo).toBeDefined(); expect(actual.extraInfo).toBeTruthy(); }); }) })
package com.dbc.trabalhovemser.controller; import com.dbc.trabalhovemser.dto.UsuarioCreateDTO; import com.dbc.trabalhovemser.dto.UsuarioDTO; import com.dbc.trabalhovemser.exceptions.RegraDeNegocioException; import com.dbc.trabalhovemser.service.UsuarioService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.List; @RestController @RequestMapping("/usuario") @Validated @Slf4j @RequiredArgsConstructor public class UsuarioController { private final UsuarioService usuarioService; @ApiOperation(value = "Retorna todos usuarios") @ApiResponses(value ={ @ApiResponse(code = 200, message = "Lista gerada com sucesso"), @ApiResponse(code = 400, message = "Algum dado inconsistente"), @ApiResponse(code = 500, message = "Foi gerada uma exceção"), }) @GetMapping public List<UsuarioDTO> list() {return usuarioService.list(); } @ApiOperation(value = "Retorna usuario Pelo ID") @ApiResponses(value ={ @ApiResponse(code = 200, message = "Usuario encontrado sucesso"), @ApiResponse(code = 400, message = "Algum dado inconsistente"), @ApiResponse(code = 500, message = "Foi gerada uma exceção"), }) @GetMapping("/{idUsuario}") public UsuarioDTO listById(@PathVariable("idUsuario") Integer idUsuario) throws RegraDeNegocioException { return usuarioService.getPorId(idUsuario); } @ApiOperation(value = "Cria um novo usuario") @ApiResponses(value ={ @ApiResponse(code = 200, message = "Usuario criado com sucesso"), @ApiResponse(code = 400, message = "Algum dado inconsistente"), @ApiResponse(code = 500, message = "Foi gerada uma exceção"), }) @PostMapping public UsuarioDTO create(@RequestBody @Valid UsuarioCreateDTO usuarioCreateDTO) throws RegraDeNegocioException{ log.info("Criando usuario"); UsuarioDTO usuarioDTO = usuarioService.create(usuarioCreateDTO); log.info("Usuario criado com sucesso"); return usuarioDTO; } @ApiOperation(value = "Atualizar um usuario") @ApiResponses(value ={ @ApiResponse(code = 200, message = "Usuario atualizado com sucesso"), @ApiResponse(code = 400, message = "Algum dado inconsistente"), @ApiResponse(code = 500, message = "Foi gerada uma exceção"), }) @PutMapping("/{idUsuario}") public UsuarioDTO update(@PathVariable("idUsuario") Integer id, @RequestBody @Valid UsuarioCreateDTO usuarioCreateDTO) throws RegraDeNegocioException { log.info("Atualizar usuario"); UsuarioDTO usuarioDTO = usuarioService.update(id, usuarioCreateDTO); log.info("Usuario atualizado"); return usuarioDTO; } @ApiOperation(value = "Deletar um usuario") @ApiResponses(value ={ @ApiResponse(code = 200, message = "Usuario deletado com sucesso"), @ApiResponse(code = 400, message = "Algum dado inconsistente"), @ApiResponse(code = 500, message = "Foi gerada uma exceção"), }) @DeleteMapping("/{idUsuario}") public void delete(@PathVariable("idUsuario") @NotNull Integer id) throws RegraDeNegocioException { log.info("Deletando usuario"); usuarioService.delete(id); log.info("Usuario deletado com sucesso"); } }
import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; // Service import { createProduct } from "../../../services/productService" // Helper import { fieldEmptyValidation } from "../../../helpers/fieldEmptyValidation"; // Component import Input from "../../../components/Input"; import TextArea from "../../../components/Textarea" import ComboBox from "../../../components/ComboBox" import FileUpload from "../../../components/FileUpload" import Button from "../../../components/ActionButton"; import OutlineButton from "../../../components/OutlineButton"; import Alert from "../../../components/Alert"; import Preview from "./Preview"; // Image import backBtn from "../../../assets/images/fi_arrow-left.png"; import { getAllCategory } from "../../../services/categoryService"; const InputForm = () => { const navigate = useNavigate(); const initialValues = { name: "", price: "", description: "", categories: [] }; const [categories, setCategories] = useState([]); const [formValues, setFormValues] = useState(initialValues); const [formErrors, setFormErrors] = useState({}); const [file, setFile] = useState([]); const [fileUrl, setFileUrl] = useState([]); const [showAlert, setShowAlert] = useState(false); const [isLoading, setIsLoading] = useState(false); const [status, setStatus] = useState([]); const [message, setMessage] = useState([]); const handleChange = (e) => { const { name, value } = e.target; setFormValues({ ...formValues, [name]: value }); }; const onSelect = (e) => { setFormValues({ ...formValues, categories: e.map(item => item.key) }); } const onRemove = (e) => { setFormValues({ ...formValues, categories: e.map(item => item.key) }); } const handleOnChangeFile = (event) => { setFile([...file, event.target.files[0]]) }; const handleToggleAlert = () => { setShowAlert(!showAlert); }; const validate = (value) => { const errors = {}; if(fieldEmptyValidation(value.name)) { errors.name = 'Kolom nama produk tidak boleh kosong'; } if (fieldEmptyValidation(value.price)) { errors.price = "Kolom harga tidak boleh kosong"; } if (fieldEmptyValidation(value.description)) { errors.description = "Kolom deskripsi tidak boleh kosong"; } if (fieldEmptyValidation(value.categories)) { errors.categories = "Kolom kategori tidak boleh kosong"; }else if(value.categories.length > 5){ errors.categories = "kategori yang dipilih tidak boleh lebih dari 5"; } return errors; }; const handleSubmit = async () => { setFormErrors(validate(formValues)); if (Object.keys(validate(formValues)).length === 0) { setIsLoading(true); let apiRes = null; let formData = new FormData(); formData.append("name", formValues.name); formData.append("price", formValues.price); formData.append("description", formValues.description); formData.append("categories", formValues.categories.join(',')); file.forEach(item => { formData.append("image", item); }) try { apiRes = await createProduct(formData); } finally { setIsLoading(false); setShowAlert(true); if (apiRes.data.meta.status === "success") { setStatus("success"); setMessage("Produk berhasil diterbitkan"); setTimeout(() => { window.location.reload(); }, 700); } else { setStatus("error"); setMessage("terjadi kesalahan ulangi lagi nanti"); } } } }; // Handling Preview File useEffect( () => { const promises = file.map((blob) => { return new Promise((res) => { const reader = new FileReader(); reader.readAsDataURL(blob); reader.onload = (e) => { res(e.target.result); } }); }); Promise.all(promises).then((results) => { setFileUrl(results); }); }, [file]); useEffect(() => { getAllCategory().then(response => setCategories(response.data.data)); }, []); return ( <> <section class="input-form"> <div class="container"> <Alert show={showAlert} close={handleToggleAlert} type={status} message={message} optionClass={'ms-5'} /> <div class="row d-flex flex-wrap align-content-center justify-content-center"> <div class="col-1 col-lg-1 mt-4"> <button class="btn" onClick={() => navigate(-1)}> <img src={backBtn} alt="back-button" /> </button> </div> <div class="col-11 mt-4"> <h5 class="text-center fw-bold">Lengkapi Detail Product</h5> </div> <div class="col-12 col-lg-11 mt-4"> <Input label="Nama Produk" type="text" name="name" id="name" width="100%" placeholder="Nama Produk" value={formValues.name} erorr={formErrors.name} onChange={(value) => handleChange(value)} /> <Input label="Harga" type="number" name="price" id="price" width="100%" placeholder="Rp. 0,00" value={formValues.price} erorr={formErrors.price} onChange={(value) => handleChange(value)} /> <ComboBox label="Kategori" options={categories.map(category => ({ name: category.name, key: category.id }))} displayValue="name" placeholder="Pilih Kategori" onRemove={(value) => onRemove(value)} onSelect={(value) => onSelect(value)} erorr={formErrors.categories} /> <TextArea label={"Deskripsi Produk"} name="description" id="description" placeholder="Masukkan deskripsi produk" erorr={formErrors.description} value={formValues.description} onChange={(value) => handleChange(value)} /> <div class="d-flex"> {/* {fileUpload} */} {fileUrl.length > 0 ?( <> {fileUrl.map((item) => { {console.log(item)} return ( <FileUpload fileUrl={item} onChange={(value) => handleOnChangeFile(value)} /> ) })} {file.length === 5 ? ( <></> ):( <FileUpload fileUrl={''} onChange={(value) => handleOnChangeFile(value)} /> )} </> ):( <> <FileUpload fileUrl={fileUrl} onChange={(value) => handleOnChangeFile(value)} /> </> )} </div> <div class="row mt-4 mb-4"> <div class="col-6"> <OutlineButton color="#4B1979" bg="#4B1979" width="100%" text="Preview" data-bs-toggle="modal" data-bs-target="#modalPreview" /> <Preview data={{ formValues, fileUrl }} /> </div> <div class="col-6"> {isLoading ? <Button color="#ffffff" bg="#4B1979" width="100%" icon={'https://media0.giphy.com/media/L05HgB2h6qICDs5Sms/giphy.gif?cid=ecf05e47l4kvh3wbfq7ekl58oelu5421j48s9fyiu5k8cf8n&rid=giphy.gif&ct=s'} disabled /> : <Button color="#ffffff" bg="#4B1979" width="100%" text="Terbitkan" onClick={handleSubmit} /> } </div> </div> </div> </div> </div> </section> </> ); }; export default InputForm;
library(tidyverse) library(lubridate) source(here::here("R", "src", "utils_cohorts.R"), encoding = "utf8") # TEST UTILS -------------------------------------------------------------- # Cohortes por mes de cumpleaños ------------------------------------------ res_fun <- simul_births_deaths(N = 10000, vida_media = 60, f_gen_ini = "2003-01-01", f_gen_fin = "2022-12-31", f_obs_ini = "2020-01-01", f_obs_fin = "2022-12-31", seed = 2023) res_lifelines <- make_lifelines_month(res_fun, 2) make_lifelines_month(res_fun, 12) %>% select(id:yr_dth, ((ncol(.)-35):ncol(.))) %>% align_lifelines() %>% colSums(na.rm = TRUE) %>% plot() aligned_lifelines <- align_lifelines(res_lifelines) make_emp_survivor_curve(aligned_lifelines) make_lifelines_month(res_fun, mth = 1) %>% align_lifelines() %>% make_emp_survivor_curve() %>% plot(type = "l") make_lifelines_month(res_fun, mth = 3) %>% align_lifelines() %>% make_emp_survivor_curve() %>% plot(type = "l") make_lifelines_month(res_fun, mth = 12) %>% align_lifelines() %>% make_emp_survivor_curve() %>% plot(type = "l") make_lifelines_month(res_fun, mth = 9) %>% align_lifelines() %>% make_emp_survivor_curve() %>% make_emp_survivor_rate() %>% plot(type = "l") # Vida media empírica make_lifelines_month(res_fun, mth = 3) %>% align_lifelines() %>% make_emp_survivor_curve(perc = TRUE) %>% sum() # Cohortes por mes de nacimiento ------------------------------------------ # Cohorte de los nacidos en los meses de febrero en los años de observación make_lifelines_month(res_fun, 2) %>% filter(yr_bth %in% 2020:2022) %>% align_lifelines()%>% make_emp_survivor_curve() %>% plot(type = "l") make_lifelines_month(res_fun, 2) %>% filter(yr_bth %in% 2020:2022) %>% align_lifelines()%>% make_emp_survivor_curve() %>% make_emp_survivor_rate() %>% plot(type = "l") # ORIGINAL ---------------------------------------------------------------- # Simulate cohorts N <- 100000 # Nº de individuos # Duración de la vida - Distr. geométrica, vida media = 60 p = 1/60 # Tiempo discreto aux_dates <- tibble(t = 1:240, date = seq.Date(as_date("2003-01-01"), as_date("2022-12-31"), by = "month")) %>% mutate(mth = lubridate::month(date), yr = lubridate::year(date)) # Los nacimientos se distribuyen uniformemente set.seed(2023) probe <- tibble(t_bth = sample(1:240, size = N, replace = TRUE), dur_vida = rgeom(N, p), t_dth = t_bth + dur_vida) %>% arrange(t_bth) %>% left_join(aux_dates, by = c("t_bth" = "t")) %>% mutate(date_dth = date + months(dur_vida)) %>% mutate(mth_dth = lubridate::month(date_dth, label = TRUE, abbr = FALSE), yr_dth = lubridate::year(date_dth)) %>% select(t_bth, dur_vida, t_dth, date_bth = date, mth_bth = mth, yr_bth = yr, date_dth, mth_dth, yr_dth) %>% # Cojo los activos en el periodo 2020-2022 filter(yr_dth > 2019) %>% mutate(date_dth = ifelse(date_dth >= as_date("2023-01-01"), NA, date_dth) %>% as_date()) %>% mutate(mth_dth = ifelse(date_dth >= as_date("2023-01-01"), NA, mth_dth)) %>% mutate(yr_dth = ifelse(date_dth >= as_date("2023-01-01"), NA, yr_dth)) %>% # mutate(dur_vida = ifelse(date_dth >= as_date("2023-01-01"), NA, dur_vida)) mutate(id = row_number(), .before = 1) probe %>% group_by(mth_bth) %>% summarise(n = n(), avg_dur_vida = mean(dur_vida, na.rm = TRUE)) probe %>% group_by(mth_dth) %>% summarise(n = n(), avg_dur_vida = mean(dur_vida, na.rm = TRUE)) kk <- purrr::map2(probe %>% filter(mth_bth == 1) %>% pull(date_bth), probe %>% filter(mth_bth == 1) %>% pull(date_dth), function(x,y) { if (is.na(y)) y <- as_date("2022-12-31") the_names <- seq.Date(x, y, by = "month") out <- rep(1, length(the_names)) names(out) <- the_names return(out) }) res <- bind_cols(probe %>% filter(mth_bth == 1)) %>% bind_cols(kk %>% bind_rows()) res %>% select(-(id:yr_dth)) %>% summarise_all(~ sum(., na.rm = TRUE)) %>% gather(date, obs) %>% mutate(date = as_date(date)) %>% filter(date > as_date("2019-12-31")) %>% plot(type = "l", ylim = c(0, 300)) res res2 <- res %>% select(-(id:yr_dth)) %>% rowSums(na.rm = TRUE) %>% map(~ { out <- rep(1, .x) names(out) <- paste0("mth_", 1:length(out)) return(out) }) %>% bind_rows() %>% colSums(na.rm = TRUE) res %>% select(-(id:yr_dth)) %>% rowSums(na.rm = TRUE) %>% table %>% as_tibble() %>% rename(age_mths = 1) %>% mutate(age_mths = as.integer(age_mths)) %>% arrange(desc(age_mths)) %>% plot() res %>% select(-(id:yr_dth)) %>% rowSums(na.rm = TRUE) %>% hist() # Función supervivencia (res2/lag(res2))[-1] %>% cumprod() %>% plot curve((1-p)^x, 1, 240, add = TRUE) bayes_data <- (-diff(res2)) sbg_model_0 <- sampling(model_sbg_0, iter = 1000, chains = 1, data = list(N = length(bayes_data), n = bayes_data, n_0 = res2[1], mean_alpha = 1, mean_beta = 1), verbose = TRUE) sbg_model_0 (res2/lag(res2))[-1] extract(sbg_model_0)$sim_r %>% apply(2, median) plot((res2/lag(res2))[-1], extract(sbg_model_0)$sim_r %>% apply(2, median)) extract(sbg_model_0)$alpha %>% median() extract(sbg_model_0)$beta %>% median() extract(sbg_model_0)$alpha %>% hist() extract(sbg_model_0)$beta %>% hist() library(BTYD) BTYD::bgbb.EstimateParameters()
import React, { Component } from "react"; import Downshift, { resetIdCounter } from "downshift"; import Router from "next/router"; import { ApolloConsumer } from "react-apollo"; import gql from "graphql-tag"; import debounce from "lodash.debounce"; import { DropDownItem, DropDown, SearchStyles } from "./styles/DropDown"; const SEARCH_ITEMS_QUERY = gql` query SEARCH_ITEMS_QUERY($searchTerm: String!) { items(where: { OR: [{ title_contains: $searchTerm }, { description_contains: $searchTerm }] }) { id image title } } `; function routeToitem(item) { Router.push({ pathname: "/item", query: { id: item.id, }, }); } class AutoComplete extends Component { state = { items: [], loading: false }; onChange = debounce(async (e, client) => { // console.log("se"); this.setState({ loading: true }); const res = await client.query({ query: SEARCH_ITEMS_QUERY, variables: { searchTerm: e.target.value, }, }); this.setState({ items: res.data.items, loading: false }); }, 350); render() { resetIdCounter(); return ( <SearchStyles> <Downshift onChange={routeToitem} itemToString={i => (i === null ? "" : i.title)}> {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex }) => { return ( <div> <ApolloConsumer> {client => ( <input {...getInputProps({ type: "search", placeholder: "search for an item", id: "search", className: this.state.loading ? "loading " : "", onChange: e => { e.persist(); this.onChange(e, client); }, })} /> )} </ApolloConsumer> {isOpen && ( <DropDown> {this.state.items.map((i, index) => ( <DropDownItem {...getItemProps({ item: i })} highlighted={index === highlightedIndex} key={i.id}> <img width="50" src={i.image} alt={i.title} /> {i.title} </DropDownItem> ))} {!this.state.items.length && !this.state.loading && <DropDownItem>Nothing Found {inputValue}</DropDownItem>} </DropDown> )} </div> ); }} </Downshift> </SearchStyles> ); } } export default AutoComplete;
import React from 'react'; import { TouchableOpacity, Text, StyleSheet, TouchableOpacityProps, StyleProp, TextStyle, } from 'react-native'; import useTheme from '../core/theme'; import TextTopography from '../core/textTopography'; import { responsiveHeight, responsiveRadius, responsiveWidth, } from '../core/sizes'; interface OutlinedButtonProps extends TouchableOpacityProps { title: string; buttonStyle?: StyleProp<TextStyle>; textStyle?: StyleProp<TextStyle>; } const OutlinedButton: React.FC<OutlinedButtonProps> = ({ title, buttonStyle, textStyle, ...props }) => { const colors = useTheme(); return ( <TouchableOpacity style={[{borderColor: colors.secondary}, styles.button, buttonStyle]} {...props}> <Text style={[{color: colors.secondary}, styles.text, textStyle]}> {title} </Text> </TouchableOpacity> ); }; const styles = StyleSheet.create({ button: { paddingVertical: responsiveHeight(4.5), paddingHorizontal: responsiveWidth(15), borderRadius: responsiveRadius(17), alignItems: 'center', justifyContent: 'center', borderWidth: 2.5, }, text: { ...TextTopography.buttonText, textTransform: 'uppercase', }, }); export default OutlinedButton;
import { createRouter, createWebHistory } from "vue-router"; import { useStore } from "vuex"; import TheMain from "@/components/layout/TheMain"; import LoginForm from "@/auth/LoginForm.vue"; import resource from "@/helper/resource"; import HomePage from "@/views/HomePage.vue"; import AssetOverview from "@/views/overview/AssetOverview.vue"; import AssetList from "@/views/AssetList.vue"; import RecordIncrease from "@/views/record-increase/RecordIncrease.vue"; const routes = [ { path: "/", redirect: resource.Link.Login, component: LoginForm }, { path: resource.Link.Login, name: "LoginForm", component: LoginForm, beforeEnter: (to, from, next) => { const store = useStore(); const isValidToken = localStorage.getItem("qlts")?.isValidToken; if (isValidToken) { next({ name: "HomePage" }); } else { next(); } }, }, { path: "/", name: "HomePage", component: HomePage, children: [ { path: resource.Link.Overview, name: "Overview", component: AssetOverview, }, { path: resource.Link.Asset, name: "Asset", component: AssetList, children: [ { path: "/", component: AssetList }, { path: "/tai-san/ghi-tang", component: RecordIncrease }, { path: "/tai-san/khac" }, ], }, ], meta: { requireAuth: true, }, }, ]; const route = createRouter({ history: createWebHistory(), routes: routes, }); // route.beforeEach((to) => { // if (to.meta.requireAuth && !localStorage.getItem("qlts")?.isValidToken) // return { // path: "/dang-nhap", // }; // }); export default route;