text
stringlengths
184
4.48M
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title></title> <script src="js/mui.min.js"></script> <link href="css/mui.min.css" rel="stylesheet"/> <script type="text/javascript" charset="utf-8"> mui.init(); </script> <!--<style> input, button, .mui-btn { margin: 5px 15px 10px 5px; } .mui-spinner { display: inline-block; width: 24px; height: 24px; -webkit-transform-origin: 50%; transform-origin: 50%; -webkit-animation: spinner-spin 1s step-end infinite; animation: spinner-spin 1s step-end infinite; } </style>--> </head> <body> <header class="mui-bar mui-bar-nav"> <h1 class="mui-title">练习</h1> </header> <div class="mui-content"> <!--折叠面板--> <ul class="mui-table-view"> <li class="mui-table-view-cell mui-collapse"> <a href="#" class="mui-navigate-right">面板1</a> <div class="mui-collapse-content"> <a>面板1子内容</a> </div> </li> </ul> <!--操作表--> <div id="sheet" class="mui-popover mui-popover-bottom mui-popover-action"> <!--可选菜单--> <ul class="mui-table-view"> <li class="mui-table-view-cell"> <a href="#">菜单1</a> </li> <li class="mui-table-view-cell"> <a href="#">菜单2</a> </li> </ul> <!--取消菜单--> <ul class="mui-table-view"> <li class="mui-table-view-cell"> <a href="#sheet"> <b>取消</b> </a> </li> </ul> </div> <a href="#sheet" id="openSheet" class="mui-btn mui-btn-primary mui-btn-block">打开操作表</a> <!--数字角标--> <span class="mui-badge mui-badge-blue">1</span> <span class="mui-badge mui-badge-inverted mui-btn-blue">1</span> <!--普通按钮--> <button type="button" class="mui-btn">默认</button> <button type="button" class="mui-btn mui-btn-primary">蓝色</button> <button type="button" class="mui-btn mui-btn-success">绿色</button> <button type="button" class="mui-btn mui-btn-warning">黄色</button> <button type="button" class="mui-btn mui-btn-danger">红色</button> <button class="mui-btn mui-btn-royal mui-btn-outlined">紫色</button> <!--加载中按钮--> <button type="button" id="loading" class="mui-btn mui-btn-primary">确认</button> <!--卡片视图--> <div class="mui-card"> <!--页眉,放置标题--> <div class="mui-card-header mui-card-media"> <img src="images/gh.png" /> <div class="mui-media-body"> 小M <p>发表于2016-11-20 11:59</p> </div> </div> <!--内容区--> <div class="mui-card-content"> 内容区 <img src="images/2.png" alt="" /> </div> <!--页脚,放置补充信息或支持的操作--> <div class="mui-card-footer">页脚</div> </div> <!--复选框--> <div class="mui-input-row mui-checkbox mui-left"> <label>checkbox demo</label> <input name="checkbox1" value="Item 1" type="checkbox" checked="" /> </div> <!--对话框--> <button type="button" id="alert" class="mui-btn mui-btn-blue mui-btn-outlined">警告框</button> <button type="button" id="confirm" class="mui-btn mui-btn-blue mui-btn-outlined">确认框</button> <button type="button" id="prompt" class="mui-btn mui-btn-blue mui-btn-outlined">输入对话框</button> <button type="button" id="toast" class="mui-btn mui-btn-blue mui-btn-outlined">消息提示框</button> <div id="info"> whenever we can become ricker... </div> <!--图片轮播--> <div class="mui-slider"> <div class="mui-slider-group mui-slider-loop"> <!--支持循环,需要重复图片节点--> <div class="mui-slider-item mui-slider-item-duplicate"> <a href="#"> <img src="images/yuantiao.jpg" alt="" /> </a> </div> <div class="mui-slider-item"> <a href="#"> <img src="images/shuijiao.jpg" alt="" /> </a> </div> <div class="mui-slider-item"> <a href="#"> <img src="images/cbd.jpg" alt="" /> </a> </div> <div class="mui-slider-item"> <a href="#"> <img src="images/muwu.jpg" alt="" /> </a> </div> <div class="mui-slider-item"> <a href="#"> <img src="images/yuantiao.jpg" alt="" /> </a> </div> <!--支持循环,需要重复图片节点--> <div class="mui-slider-item mui-slider-item-duplicate"> <a href="#"> <img src="images/shuijiao.jpg" alt="" /> </a> </div> </div> </div> </div> </body> <script> mui.init({ swipeBack: true //启用右滑关闭功能 }); mui(document.body).on('tap', '#loading', function(e) { mui(this).button('loading'); setTimeout(function() { mui(this).button('reset'); }.bind(this), 2000); }); /**** 设置提醒框 ****/ var info = document.getElementById("info"); document.getElementById("alert").addEventListener('tap', function(){ mui.alert('Hello,world!', 'Tip', function(){ info.innerText = '点击了确认按钮'; }); }); document.getElementById("confirm").addEventListener('tap', function(){ mui.confirm('Are you sure?', 'choose', ['Yes', 'No'], function(e){ if (e.index == 1) { info.innerText = 'you not sure'; } else{ info.innerText = 'you make sure'; } }); }); document.getElementById("prompt").addEventListener('tap', function(e){ e.detail.gesture.preventDefault();//修复iOS 8.x平台存在的bug,使用plus.nativeUI.prompt会造成输入法闪一下又没了 mui.prompt('Please input your evaluate for me.', 'handsome', 'Thank you', ['sure', 'cancel'], function(e){ if (e.index == 0) { info.innerText="thank you for your evaluate: " + e.value; } else{ info.innerText="you click cancel button"; } }); }); document.getElementById("toast").addEventListener('tap', function(){ mui.toast('yes, this is toast'); }); /**** 设置图片轮播 ****/ var gallery = mui('.mui-slider'); gallery.slider({ interval: 2000 }); </script> </html>
import { CheckOutlined, CloseOutlined, DeleteOutlined, EditOutlined, PlusOutlined, UserOutlined, } from "@ant-design/icons"; import { Button, Divider, Form, Popconfirm, Row, Typography } from "antd"; import { useEffect, useState } from "react"; import { AccountAPI } from "../../apis/account.api"; import { TeamAPI } from "../../apis/team.api"; import { useAppDispatch, useAppSelector } from "../../app/hooks"; import { DeleteTeam, GetTeam, SetTeam, UpdateTeam, } from "../../app/reducers/Team/Team.reducer"; import ModalTeam from "../../components/team/ModalTeam"; import { IAccount } from "../../interface/Account.interface"; import { ITeam } from "../../interface/Team.interface"; import "./index.css"; const { Text } = Typography; export default function Team() { const dataTeam = useAppSelector(GetTeam); const dispatch = useAppDispatch(); const [showModal, setShowModal] = useState<boolean>(false); const [accountDrag, setAccountDrag] = useState<IAccount>({}); const [teamDrag, setTeamDrag] = useState<ITeam>({}); const [dataModal, setDataModal] = useState<ITeam>({}); const [editing, setEditing] = useState<boolean>(false); const widthWidget = (1 / dataTeam.length) * 100 - 2; useEffect(() => { search(); // eslint-disable-next-line }, [dispatch]); const search = async () => { const emptyTeam = await AccountAPI.fetchWhereNoTeam().then((res) => ({ name: "Chưa vào team", members: res.data, })); await TeamAPI.fetchAllMembers().then((res) => { dispatch(SetTeam([emptyTeam, ...res.data])); }); }; const handleOnDrag = (e: React.DragEvent, account: IAccount, team: ITeam) => { setAccountDrag(account); setTeamDrag(team); }; const handleOnDrop = async (e: React.DragEvent, team: ITeam) => { const updateAccount: IAccount = { ...accountDrag, teamId: team.id ? team.id : null, }; if (accountDrag.id && team.id !== teamDrag.id) { await AccountAPI.update(accountDrag.id, updateAccount).then(() => { dispatch( UpdateTeam({ ...teamDrag, leaderId: teamDrag.leaderId === accountDrag.id ? null : teamDrag.leaderId, members: teamDrag.members?.filter((el) => el.id !== accountDrag.id), }) ); if (team.members) dispatch( UpdateTeam({ ...team, members: [...team.members, updateAccount] }) ); }); } }; const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); }; const remove = async (record: Partial<ITeam>) => { const emptyTeam = dataTeam[0]; if (record.id) { const memberOfTeam = record.members; const updateAccount: IAccount[] = []; memberOfTeam?.map((el) => updateAccount.push({ ...el, teamId: null })); await TeamAPI.delete(record.id).then(() => { dispatch(DeleteTeam(record)); dispatch( UpdateTeam({ ...emptyTeam, members: emptyTeam.members ? [...emptyTeam.members, ...updateAccount] : [...updateAccount], }) ); }); } }; return ( <> <ModalTeam modalOpen={showModal} setModalOpen={setShowModal} team={dataModal} /> <Row className="flex justify-between"> <Button type="primary" disabled={!editing} icon={<PlusOutlined />} className="mb-4" onClick={() => { setDataModal({}); setShowModal(true); }} ></Button> {!editing ? ( <Button type="primary" className="mb-4" onClick={() => setEditing(true)} > <EditOutlined /> </Button> ) : ( <Row className="w-24 justify-between"> <Button type="dashed" onClick={() => setEditing(false)} icon={ <CloseOutlined style={{ fontSize: "130%", color: "797978" }} /> } className="flex justify-center items-center" ></Button> <Button type="primary" className="flex justify-center items-center" icon={<CheckOutlined style={{ fontSize: "130%" }} />} onClick={() => setEditing(false)} ></Button> </Row> )} </Row> <div className="flex justify-between"> {dataTeam.length > 0 && dataTeam.map((el: ITeam, index) => { return ( <Form disabled={!editing} className="boxs rounded-lg bg-[#dcd5d5] overflow-hidden p-2 " style={ !editing ? { width: `${widthWidget}%`, opacity: 0.7 } : { width: `${widthWidget}%` } } key={index} onDrop={(e) => { if (editing) handleOnDrop(e, el); }} onDragOver={(e) => handleDragOver(e)} > <div className="w-full h-[60px] text-[15px] font-bold flex justify-between uppercase items-center gap-2"> <Text className="flex items-center justify-between"> <div className="text-blue-500" title={el.name}> {el.name} </div> <span className="ml-2 leading-[5px] p-2"> {el.members?.length} &nbsp; <UserOutlined /> </span> </Text> {index > 0 && ( <Row> <Typography.Link disabled={!editing} className="mr-4" onClick={() => { setDataModal(el); setShowModal(true); }} > <EditOutlined style={{ fontSize: "130%" }} /> </Typography.Link> <Popconfirm title="Bạn có chắc chắn muốn xóa không?" onConfirm={() => { remove(el); }} > <Typography.Link disabled={!editing}> <DeleteOutlined style={{ fontSize: "130%" }} /> </Typography.Link> </Popconfirm> </Row> )} </div> <Divider style={{ marginTop: 0, marginBottom: 8 }} /> <div className="widgets h-[400px] w-full flex justify-start items-center flex-col gap-2"> {el.members?.map((mem, index) => { return ( <div className="text-[20px] rounded-[5px] bg-white min-h-10 flex flex-col justify-center items-start p-4 w-full" key={index} draggable={editing} onDragStart={(e) => handleOnDrag(e, mem, el)} > <p className="text-[15px]"> {mem.name} {mem.id === el.leaderId ? "(Leader)" : ""} </p> <p className="text-[10px]">{mem.email}</p> </div> ); })} </div> </Form> ); })} </div> </> ); }
const express = require('express') const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb'); const cors = require('cors') require('dotenv').config(); const app = express() const port = process.env.PORT || 5000 // middleware app.use(cors()) app.use(express.json()) // mongoDB const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.mt6zv6m.mongodb.net/?retryWrites=true&w=majority`; // Create a MongoClient with a MongoClientOptions object to set the Stable API version const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } }); async function run() { try { //change menuCollection with database name and collection. const taskCollection = client.db('taskyDB').collection("task") app.get('/task/:email', async (req, res) => { const email = req.params.email const query = { email: email } const result = await taskCollection.find(query).toArray() res.send(result) }) app.post('/task', async (req, res) => { const task = req.body; const result = await taskCollection.insertOne(task) res.send(result) }) app.delete('/task/:id', async (req, res) => { const id = req.params.id const query = { _id: new ObjectId(id) } const result = await taskCollection.deleteOne(query) res.send(result) }) app.put('/task/:id', async (req, res) => { const id = req.params.id const filter = { _id: new ObjectId(id) } const updatedTask = req.body; const task = { $set: { priority: updatedTask.priority, Title: updatedTask.Title, Description: updatedTask.Description, Deadline: updatedTask.Deadline, status: updatedTask.status, } } const result = await taskCollection.updateOne(filter, task) res.send(result) }) app.patch("/task", async (req, res) => { const id = req.query.id; const data = req.body; const query = { _id: new ObjectId(id) }; const updatedDoc = { $set: { status: data.status, }, }; const result = await taskCollection.updateOne(query, updatedDoc); res.send(result); }); // Send a ping to confirm a successful connection // await client.db("admin").command({ ping: 1 }); // console.log("Pinged your deployment. You successfully connected to MongoDB!"); } finally { // Ensures that the client will close when you finish/error // await client.close(); } } run().catch(console.dir); // testing app.get('/', (req, res) => { res.send('Server is running re baba') }) app.listen(port, () => { console.log(`Server is running on port: ${port}`); })
<p>Welcome to the Advanced Rocketry(AR) advanced configuration readme!</p> <p>This document will guide you through manually or semi-manually defining planets for your world!</p> <p>To use manual xml planet configuration, download and modify https://github.com/zmaster587/AdvancedRocketry/blob/master/Template.xml and rename to "planetDefs.xml" in the config/advancedRocketry folder</p> <p> <br />Explaination of usable tags:</p> <hr> <p>The "planets" tag should be at the root of the document, this tells AR you are defining your set of planets in the body of this tag. The "numPlanet" attribute defines how many random planets should be defined in the solar systems, if not specified then AR will default to six.</p> <p>Example usage; generates one random planet around a star named Sol with the temperature of the sun at origin:</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; ... &#60;/star&#62; &#60;/galaxy&#62;</code> <hr> <p>The "planet" tag surrounds the definition of a planet. If a planet tag is used in the body of another planet tag, the inner planet tag defines a moon of the outer planet. The planet tag can have the attribute "name". The name attribute specifies the name of the planet. If the name attribute is not present then the planet is automatically named "Sol-planet_id".</p> <p>Example usage; generates one random planet and one planet with manually specified properties named "Earth" with a moon named "Luna" and another manually specified planet "Mars"</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; ... &#60;planet name="Luna"&#62; ... &#60;/planet&#62; &#60;/planet&#62; &#60;planet name="Mars"&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "fogColor" tag specifes the color of the fog on a planet. The body takes three comma seperated values corresponding to Red, Green, and Blue respectivly. These values can be any decimal number between 0 and 1 inclusive. A 24-bit (6-byte) Hex color can also be specified by prepending the code with "0x".</p> <code> Example usage; specifes a teal color fog using the RGB format. &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;fogColor&#62;0.5,1,1&#60;/fogColor&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <p>Example usage; specifes the same teal color fog as the previous example using hex format.</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;fogColor&#62;0x7FFFFFF&#60;/fogColor&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "fogColor" tag specifes the color of the sky on a planet. The body takes three comma seperated values corresponding to Red, Green, and Blue respectivly. These values can be any decimal number between 0 and 1 inclusive. A 24-bit (6-byte) Hex color can also be specified by prepending the code with "0x".</p> <p>Example usage; specifes a teal color sky using the RGB format.</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;skyColor&#62;0.5,1,1&#60;/skyColor&#62; ... &#60;/planet&#62; &#60;/star&#62; </code> <p>Example usage; specifes the same teal color sky as the previous example using hex format.</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;fogColor&#62;0x7FFFFFF&#60;/fogColor&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "atmosphereDensity" tag specifes the density of the atmosphere on a planet. Any value greater than 75 is breathable, 100 is Earthlike, anything higher than 100 has a denser atmosphere than Earth and will have thicker fog. Any value less than 75 is unbreathable and will require a spacesuit and will generate craters.</p> <p>Atmosphere density also has an impact on the temerature of the planets, planets with thinner will be colder and planets with thicker atmospheres will be warmer.</p> <p>Max: 200<br /> Default: 100<br /> Min: 0</p> <p>Example usage; specifes an atmosphere with the same density as Earth</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;atmosphereDensity&#62;100&#60;/atmosphereDensity&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "gravitationalMultiplier" tag specifes the density of the atmosphere on a planet. 100 is earthlike. Any value less than 100 will result in a gravitational pull less than that of Earth. Any value higher than 110 may result in players being UNABLE to jump up blocks without assistance from stairs. Values very close to 0 ( &#60; 10) may result in players being unable to fall. YOU HAVE BEEN WARNED.</p> <ul> <li>Max: 200</li> <li>Default: 100</li> <li>Min: 0</li> <li>Recommended Max: 110</li> <li>Recommended Min: 10</li> </ul> <p>Example usage; specifes an atmosphere with the same density as Earth</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;gravitationalMultiplier&#62;100&#60;/gravitationalMultiplier&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; <code> <hr> <p>The "orbitalDistance" tag specifes the distance of the planet from the body it is orbiting. For planets orbiting the SUN:<br /> <div>100 is defined as an earthlike and will result in the sun appearing normal in size. 200 is very far from the sun and will result in the sun appearing very small. 0 is nearly touching the surface of the host star and will result in the host star taking up a majority of the sky. Orbital distance also has an impact on the temerature of the planets, planets far away will be colder and planets closer to the host star will be warmer.<.div><br /> For MOONS orbiting other planets: <br /> <div>The effects are the same as for planets orbiting a star except the observed host star size is determined by the planet orbiting the sun. I.E. the apparent size of the sun as seen from the moon is determined by the distance between the Earth and the sun. The apparent distance of the host planet, however, will be changed by this value. The apparent size of the moon as viewed from the host planet is also the direct result of this value.</div></p> <p>For planets orbiting the sun, lower values result in higher temperatures. For moons, this value has no effect on temperatures.</p> <ul> <li>Max: 200</li> <li>Default: 100</li> <li>Min: 0</li> </ul> <p>Example usage; specifes a distance from the host star to be the same as Earth</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;orbitalDistance&#62;100&#60;/orbitalDistance&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "orbitalTheta" tag specifes the starting angular displacement relative to the origin in degrees.</p> <ul> <li>Max: 360 </li> <li>Default: 0</li> <li>Min: 0 </li> </ul> <p>Example usage; specifes a planet to start exactly opposite the sun from Earth</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;orbitalTheta&#62;180&#60;/orbitalTheta&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "orbitalTheta" tag specifes the angle of the plane on which the planet rotates around the star or it's host planet, 90 will cause the planet or sun to rise and set in the north and south (the planet would orbit such that it would pass over both poles) whereas 0 with be the normal procession (like orbit over the equator)</p> <ul> <li>Max: 360 </li> <li>Default: 0</li> <li>Min: 0 </li> </ul> <p>Example usage; specifes a planet to start exactly opposite the sun from Earth</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;orbitalPhi&#62;180&#60;/orbitalPhi&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "rotationalPeriod" tag specifes length of a day night cycle for the planet in ticks. Where 20 ticks = 1 second. 24,000/20 = 1,200 seconds = 20 minutes. I strongly recommend not using values &#60; 400 as I found them to be very disorienting and somewhat motion sickness inducing.</p> <ul> <li>Max: 2^31 - 1 = 2,147,483,647 (java has no unsigned int...)</li> <li>Default: 24000</li> <li>Min: 1</li> </ul> <p>Example usage; specifes a planet to start exactly opposite the sun from Earth</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;orbitalTheta&#62;180&#60;/orbitalTheta&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "biomeIds" tag specifes a comma seperated list of biome ids to generate on the planet. This list can include both vanilla and modded biome ids. If this tag is not included then the planet will automatically generate a list of biomes from its atmosphere density, gravitationalMultiplier, and distance from the sun.</p> A list of vanilla biomes can be found <a href=http://minecraft.gamepedia.com/Biome>here</a> <p>Example usage; Planet will generate only ocean and ice plains</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth"&#62; &#60;biomeIds&#62;0,12&#60;/biomeIds&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "DIMID" attribute allows a user to specify the exact dimension id that the planet is going to occupy, useful for custom ore gen mods and more control in general</p> <p>Example usage; Planet will generate with the dimid 99</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth" DIMID="99"&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code> <hr> <p>The "dimMapping" attribute allows a user to specify that the following planet is a dimension from another mod. Note that it must be accompanied by a DIMID tag!!!</p> <p>Be warned, if another mod does not have a dimension with that ID it will cause a crash if somebody tries to go there!</p> <p>Example usage; Adding Twilight forests (with default configs) as a planet around Sol</p> <code> &#60;galaxy&#62; &#60;star name="Sol" temp="100" x="0" y="0" numPlanets="1"&#62; &#60;planet name="Earth" DIMID="7" dimMapping=""&#62; ... &#60;/planet&#62; &#60;/star&#62; &#60;/galaxy&#62; </code>
import { Message } from '@app/models/message'; import { AppState } from '..'; import { doFetchLatestMessages, doFetchLatestMessagesFulfilled, doFetchLatestMessagesRejected, doFetchMoreMessages, doFetchMoreMessagesFulfilled, doFetchMoreMessagesRejected, doSendMessage, doSendMessageFulfilled, doSendMessageRejected, initialState, MessageState, reducer, FEATURE_KEY, selectAllMessages, selectIsFetchingLatestMessage, selectIsLoading, selectUnsentMessageIds, } from '.'; describe('Message Feature Store', () => { describe('Reducer', () => { describe('doFetchLatestMessage', () => { const state = { ...initialState }; it(`should add ${doFetchLatestMessages.type} to loading actions`, () => { const updatedState = reducer( state, doFetchLatestMessages({ channelId: '1' }), ); expect(updatedState.loadingActions).toContain( doFetchLatestMessages.type, ); }); it('should set all message entities', () => { const mockMessages: Message[] = [ { messageId: '1', datetime: '2021-10-19T09:48:25.084Z', text: 'message 1', userId: 'Joyse', }, { messageId: '2', text: 'message 2', userId: 'Sam', datetime: '2021-10-19T11:21:26.438Z', }, ]; const updatedState = reducer( state, doFetchLatestMessagesFulfilled({ messages: mockMessages }), ); expect(updatedState.ids).toEqual(['1', '2']); expect(updatedState.entities['1']).toEqual(mockMessages[0]); expect(updatedState.entities['2']).toEqual(mockMessages[1]); }); it('should update errorMessage', () => { const errorMessage = 'error message'; const updatedState = reducer( state, doFetchLatestMessagesRejected({ error: errorMessage }), ); expect(updatedState.errorMessage).toEqual(errorMessage); }); }); describe('doFetchMoreMessage', () => { const state: MessageState = { ...initialState, ids: ['1'], entities: { '1': { messageId: '1', datetime: '2021-10-19T09:48:25.084Z', text: 'message 1', userId: 'Joyse', }, }, }; it('should update loading actions', () => { const updatedState = reducer( state, doFetchMoreMessages({ channelId: '1', messageId: '1', old: false }), ); expect(updatedState.loadingActions).toContain(doFetchMoreMessages.type); }); it('should update entities', () => { const mockMessages: Message[] = [ { messageId: '2', text: 'message 2', userId: 'Sam', datetime: '2021-10-19T11:21:26.438Z', }, ]; const updatedState = reducer( state, doFetchMoreMessagesFulfilled({ messages: mockMessages }), ); expect(updatedState.ids).toEqual(['1', '2']); expect(updatedState.entities['1']).toEqual(state.entities['1']); expect(updatedState.entities['2']).toEqual(mockMessages[0]); }); it('should update error message', () => { const mockMessage = 'error'; const updatedState = reducer( state, doFetchMoreMessagesRejected({ error: mockMessage }), ); expect(updatedState.errorMessage).toEqual(mockMessage); }); }); describe('doSendMessage', () => { const state: MessageState = { ...initialState, ids: ['1'], entities: { '1': { messageId: '1', datetime: '2021-10-19T09:48:25.084Z', text: 'message 1', userId: 'Joyse', }, }, }; it('should update entities when send message then replace temporary entity with real entity', () => { const mockMessage: Message = { datetime: '2021-10-19T11:21:26.438Z', messageId: '2', text: 'message 1', userId: 'Sam', }; jest .spyOn(Date.prototype, 'toISOString') .mockReturnValue(mockMessage.datetime); const updatedState = reducer( state, doSendMessage({ text: mockMessage.text, userId: mockMessage.userId, channelId: '1', temporaryMessageId: mockMessage.messageId, }), ); expect(updatedState.entities[mockMessage.messageId]).toEqual( mockMessage, ); expect(updatedState.loadingActions).toContain(doSendMessage.type); const latestState = reducer( updatedState, doSendMessageFulfilled({ message: { ...mockMessage, messageId: '3', }, temporaryMessageId: mockMessage.messageId, }), ); expect(latestState.ids).toEqual(['1', '3']); expect(latestState.ids).not.toContain(mockMessage.messageId); }); it('should update unsent message id when send message failed', () => { const mockError = 'error'; const mockMessageId = '99'; const updatedState = reducer( state, doSendMessageRejected({ error: mockError, unsentMessageId: mockMessageId, }), ); expect(updatedState.errorMessage).toEqual(mockError); expect(updatedState.unsentMessageIds).toContain(mockMessageId); }); }); }); describe('Selector', () => { const state: AppState = { [FEATURE_KEY]: { ...initialState, ids: ['1'], entities: { '1': { messageId: '1', datetime: '2021-10-19T09:48:25.084Z', text: 'message 1', userId: 'Joyse', }, }, loadingActions: [doSendMessageRejected.type], unsentMessageIds: ['5'], }, }; it(selectIsLoading.name, () => { expect(selectIsLoading(state)).toBeTruthy(); }); it(selectIsFetchingLatestMessage.name, () => { expect(selectIsFetchingLatestMessage(state)).toBeFalsy(); }); it(selectAllMessages.name, () => { const messages = [state[FEATURE_KEY].entities['1']]; expect(selectAllMessages(state)).toEqual(messages); }); it(selectUnsentMessageIds.name, () => { expect(selectUnsentMessageIds(state)).toEqual(['5']); }); }); });
class Forest extends Zone { constructor(zoneLevel = 1) { super(zoneLevel); this.maxZoneLevel = 9; this.shopCode = [3,3,3,2,1]; //shop gen [weaponNumber, armorNumber, statNumber, usableNumber] this.pathGen = [20, //max spaces, [['shop', 50, 15, 0, 2], //[shop start, shop grow, shop reset, shop burn], ['event', 30, 15, 0, 2], //[event start, event grow, event reset, event burn], ['rest', 5, 5, 5, 2], //[rest start, rest grow, rest reset, rest burn], ['enemy', 50, 15, 35, 0]], //[enemy start, enemy grow, enemy reset, enemy burn], { // set consistent levels here 0 : 'empty', 16 : 'pathEvent', 20 : 'boss' }]; this.zoneLable = 'forest'; this.zoneMessage = 'A narrow path, surrounded by trees...'; //could also do this through classes if you wanted to add more complex behavior to individual enemies this.zoneEnemies = { 0: ['large worm', 'bark beetle', 'shieldbug', 'hawk', 'owl', 'bat'], 1: ['boar', 'elk', 'wolf', 'falcon', 'red fox', 'koala'], 2: ['green slime', 'lime slime', 'shrunk elf', 'little goblin', 'reindeer', 'massic termite'], 3: ['brown bear', 'black bear', 'moose', 'gorilla', 'chimpanzee', 'anaconda'], 4: ['elven scout', 'elven gatherer', 'elven rancher', 'goblin', 'forest snuffler', 'living sap-ooze'], 5: ['pixie', 'sentry bird', 'goblin clawer', 'elven charger', 'mint slime', 'forest-green slime'], 6: ['leaf wisp', 'tree wisp', 'mist wisp', 'spirit snake', 'goblin ranger', 'walking weed'], 7: ['tribal dryad', 'hunter dryad', 'harvesting dryad', 'healer dryad', 'sprinter dryad', 'knight dryad'], 8: ['goblin commander', 'elf chieftain', 'forest wisp', 'dryad prince', 'possessed grizzly', 'forest slime'] }; this.xpDist = { 0 : 10, 1 : 10, 2 : 10, 3 : 11, 4 : 11, 5 : 11, 6 : 12, 7 : 12, 8 : 12 } this.bossXp = 30; this.zoneBosses = [ 'the goblin king', 'the elven mystic', 'the dryad oracle' ]; this.bossWeapon = [ 'magic thick rod', 'long grass wand', 'barbed wire blade', 'elven dryad staff' ] this.bossUsable = [ 'razor paper stars', 'the hungry bag' ] this.bossMagic = [ 'river draft', 'wood chuck' ] this.bossArmor = [ 'magician\'s vest', 'light leave leggings' ] //could assign this in the parent class if this distribution holds across zones this.levelDifficultyDist = { //zoneLevel : [easyPercent, mediumPercent] (hard is excluded because it is defaulted to) 1: [0.50, 1.00], 2: [0.28, 0.85], 3: [0.28, 0.85], 4: [0.28, 0.90], 5: [0.28, 0.90], 6: [0.28, 0.85], 7: [0.35, 0.75], 8: [0, 0.25], 9: [0, 0] } this.zoneItems = [ 'copper hand axe', 'copper battle axe', 'copper short sword', 'copper long sword', 'bronze hand axe', 'bronze battle axe', 'bronze short sword', 'bronze long sword', 'bark bat', 'elven gloves', 'goblin claws', 'charcoal spear', 'ornate dagger', 'elven dagger', 'bark cleaver', 'water oak staff', 'dryad staff', 'leaf-rope whip', 'elf whip', 'dryad sleeve', 'leather cap', 'leaf beret', 'bark helmet', 'forest turban', 'leaf headband', 'elven visor', 'crystal headdress', 'dryad bonnet', 'pinecone helmet', 'wrapped snake', 'copper chestplate', 'bronze chestplate', 'bark chestplate', 'elven robes', 'wolf pelt', 'dryad coat', 'razor leaf coat', 'goblin garment', 'sewed leaf shirt', 'pinecone chain mail', 'copper leggings', 'bronze leggings', 'leafy pants', 'bark shinguards', 'elven skirt', 'dryad stockings', 'goblin skin-leggings', 'camouflage pants', 'pineneedle pants', 'forest sandals', 'leather boots', 'steel-toed boots', 'bark clogs', 'bronze boots', 'goblin loafers', 'elven shoes', 'dryad boots', 'hollowed out fish', 'locust wrap feet', 'maple leef sandals', 'hardened sap shoes', 'shiny apple', 'dark red apple', 'white chocolate bar', 'milk', 'water canteen', 'bass fish', 'cat fish', 'perch fish', 'trout', 'salmon', 'blood acorn', 'elven trinket', 'sluggish mushrooms', 'pinecone pudding', 'heal ointment', 'cooked chicken', 'battle blood', 'bucket of ice', 'carrot', 'medium bond', 'golden fish', 'bark pamphlette', 'small gold rune', 'charcoal tonic', 'dryad scrap', 'transfixed sap', 'goblin bomb', 'dryad throwing leaves', 'elf bandages', 'elven battle book', 'dryad battle book', 'goblin sacks', 'dryad berries', 'pine needle attachments', 'pine cone attachments', 'elven nectar', 'dryad root potion', 'spirit invocation', 'goblin fire dance', 'grass overgrowth', 'elf rumination', 'dryad pose', 'armor recover', 'daydream', 'rock drop' ]; this.zoneEvents = [ //[first possible space, last possible space, event id] [1, 5, 'A Long River'], [3, 6, "The Wanderer's Trailmix"], [5, 8, "A Bird's Nest"], [6, 10, 'The Trapped Totem'], [9, 12, 'Friendly Elves'], [11, 14, 'A Deep Fog'], [12, 19, 'The Cave Shrine'], [16, 19, 'The Goblin Village'] ]; this.zoneRests = [ [1, 19, 'A Tree House', 0.33], [1, 19, 'A Dryad Temple', 0.66], [1, 19, 'A Dam', 1] ]; this.pathEvent = 'The End of the Forest'; } advanceToNextZone(){ setBackgroundZone(3); return new Beach(this.game); } }
<?php /* Metalizer, a MVC php Framework. Copyright (C) 2012 David Reignier 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/> */ /** * Can find the called Page and the method to use. * @author David Reignier * */ class PageResolver extends MetalizerObject { /** * The pathInfo * @var string */ private $pathInfo; /** * The page to use * @var string */ private $page; /** * The method to use * @var string */ private $method; /** * Params for the method * @var array[string] */ private $params; /** * Construct a new PageResolver. All test are done. * @param $pathInfo string * The path info to use. */ public function __construct($pathInfo) { $this->pathInfo = $pathInfo; if ($this->log()->isInfoEnabled()) { $this->log()->info(getIp() . ":" . getRequestMethod() . ":$pathInfo"); } $this->page = null; $this->method = config('page.default_method'); $this->params = array(); if ($pathInfo && $pathInfo != '/') { foreach (config('page.patterns') as $pattern => $name) { if (preg_match("@^$pattern$@", $pathInfo, $this->params)) { $this->page = $name; if ($this->log()->isTraceEnabled()) { $this->log()->trace("Page pattern : $pattern"); $this->log()->trace("Page name : $name"); } // The first matching pattern must be the used one. So don't remove that. break; } } } else { $this->page = config('page.home'); } if (!$this->page) { throw new NotFoundException(); } // Handle the http method if (is_array($this->page)) { $method = getRequestMethod(); if (isset($this->page[$method])) { $this->page = $this->page[$method]; } else { throw new MethodNotAllowedException(); } } $separatorPos = strpos($this->page, ':'); if ($separatorPos !== false) { $splittedPage = explode(":", $this->page); $this->page = $splittedPage[0]; $this->method = $splittedPage[1]; } if (sizeof($this->params)) { $this->params = array_slice($this->params, 1); } if ($this->log()->isTraceEnabled()) { $this->log()->trace("Page class : $this->page"); $this->log()->trace("Page method : $this->method"); $this->log()->trace("Page parameters : " . implode(' / ', $this->params)); } util('Page')->check($this->page, $this->method, $this->params); } /** * Execute the page of the resolver with the method and parameters. * @return Page * The page object. */ public function run() { return util('Page')->run($this->page, $this->method, $this->params); } }
package org.choongang.board; import com.fasterxml.jackson.databind.ObjectMapper; import org.choongang.board.controllers.RequestBoardConfig; import org.choongang.board.repositories.BoardRepository; import org.choongang.board.service.BoardConfigSaveService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @TestPropertySource(properties = "spring.profiles.active=test") public class SaveTest { @Autowired private BoardConfigSaveService saveService; @Autowired private BoardRepository repository; @Autowired private MockMvc mockMvc; @Autowired private ObjectMapper om; private RequestBoardConfig form; @BeforeEach void init() { form = new RequestBoardConfig(); form.setBid("notice"); form.setBName("공지사항"); } @Test @DisplayName("게시판 설정 저장 테스트") void saveServiceTest() { saveService.save(form); String bid = form.getBid(); assertTrue(repository.existsById(bid)); } @Test @WithMockUser @DisplayName("[통합테스트] 게시판 설정 저장 테스트") void saveTest() throws Exception { //form.setBid(null); //form.setBName(null); String params = om.writeValueAsString(form); mockMvc.perform(post("/api/v1/board/config") .contentType(MediaType.APPLICATION_JSON) .content(params)) .andDo(print()) .andExpect(status().isCreated()); assertTrue(repository.existsById(form.getBid())); } }
{% extends 'base.html.twig' %} {% block title %}Equipment index {% endblock %} {% block body %} <div class="d-flex justify-content-between align-items-center"> <h1>Equipment index</h1> <a href="{{ path('app_equipment_new') }}" class="btn btn-outline-dark py-auto" style="width: 130px;"> Create </a> </div> <table class="table"> <thead class="table-dark"> <tr> <th>Id</th> <th>Serial_number</th> <th>Name</th> <th>Description</th> <th>Status</th> <th>User</th> <th>Category</th> <th>actions</th> </tr> </thead> <tbody> {% for equipment in equipments %} <tr> <td>{{ equipment.id }}</td> <td>{{ equipment.serialNumber }}</td> <td>{{ equipment.name }}</td> <td>{{ equipment.description }}</td> <td>{{ equipment.status }}</td> <td> {% if equipment.getStatus() == STATUS_IN_USE %} {{ equipment.getLastUser() ? equipment.getLastUser().getName(): "" }} {% else %} <span class="text-danger"> Not assign </span> {% endif %} </td> <td>{{ equipment.category.name }}</td> <td class="d-flex align-items-center "> <a href="{{ path('app_equipment_show', {'id': equipment.id}) }}" class="btn btn-rounded btn-dark"> <i class="fa-solid fa-eye"></i> SHOW</a> <a href="{{ path('app_equipment_edit', {'id': equipment.id}) }} " class="btn btn-rounded btn-dark"> <i class="far fa-edit fa-fw editor"></i> EDIT</a> {% if equipment.getStatus() == STATUS_IN_USE %} {# <a href="{{ path('app_equipment_unassign', {'id': equipment.id}) }} " class="btn btn-danger"> #} <form method="post" action="{{ path('app_equipment_unassign', {'id': equipment.id}) }}" onsubmit="return confirm('Are you sure you want to Unassign this item?');" style="height: 36px"> <input type="hidden" name="_token" value="{{ csrf_token('unassign' ~ equipment.id) }}"> <button class="btn btn-light btn-rounded px-3"> <i class="fa-solid fa-user-slash"></i> UNASSIGN </button> </form> {# </a> #} {% else %} {# <a href="{{ path('app_equipment_edit', {'id': equipment.id}) }} "> <i class="fa-solid fa-user-check" style="color: #000"></i> ASSIGN</a> #} <!-- Button trigger Assign modal --> <button type="button" class="btn btn-dark btn-rounded button-assign" data-mdb-toggle="modal" data-mdb-target="#assignModal"> <i class="fa-solid fa-user-check"></i> ASSIGN </button> <!-- Assign Modal --> <div class="modal fade" id="assignModal" tabindex="-1" aria-labelledby="assignModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="assignModalLabel">Assign User</h5> <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form action="{{ path('app_equipment_assign', {'id': equipment.id}) }}" method="post" id="formAssign"> <input type="hidden" name="_token" value="{{ csrf_token('assign' ~ equipment.id) }}"> <div class="form-group"> <label for="formAssignUser" class="form-label">User</label> <input autocomplete="off" type="search" class="form-control rounded searchassign" placeholder='Search ID or User Name' style="min-width: 250px" id="searchUpdate" {# data-token="{{ csrf_token() }}" #} ></input> <select class="form-select formAssignUser" id="formAssignUser" aria-label="Default select example" name="user_id"> {% for user in users %} <option value="{{user.id}}">{{user.id}} {{user.name}}</option> {% endfor %} </select> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary" id="modalAssign">Assign</button> </div> </form> </div> </div> </div> </div> {% endif %} </tr> </td> </tbody> </tr> {% else %} <tr> <td colspan="6">no records found</td> </tr> {% endfor %} </tbody> </table> {% endblock %} {% block scripts %} <script> window.addEventListener('DOMContentLoaded', (event) => { const btnAssign = $('.button-assign') btnAssign.click(function() { let btnModelAssign = $("#modalAssign") let formAssign = $("#formAssign") btnModelAssign.on("click", function(e) { e.preventDefault(); name = $('#formAssignName').val() label = $('#label-form-assign') if (name === "") label.text("The name field is required.") if (name) formAssign.submit(); }) }) $('.searchassign').on('keyup', function() { $value = $(this).val(); var token = $(this).data('token'); console.log($value); $.ajax({ type: 'get', url: '{{ (path("app_equipment_search_user")) }}', data: { 'value': $value }, success: function(data) { console.log(data) $('.formAssignUser') .find('option') .remove() .end() data.forEach((element) => { $('.formAssignUser') .append($('<option>') .val(element.id).text(element.name)); }) } }); }) }); </script> {% endblock %}
<h1>Pseudo-clases</h1> <p>Las pseudo-clases son palabras clave añadidas a un selector que especifica un estado especial del elemento seleccionado</p> <table> <caption>Lista de Pseudo-clases</caption> <thead> <tr class= "tablehead"> <th scope="col">Keyword</th> <th scope="col">Utilidad</th> <th scope="col">Documentacion</th> </tr> </thead> <tbody> <tr> <td class = "element" >:active</td> <td>Representa un elemento que sera activa con el click del mouse</td> <td> <a id = "link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:active">Documentacion</a> </td> </tr> <tr> <td class = "element" >:any-link</td> <td>Representa un elemento que actua como un hiperlink</td> <td> <a id = "link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:any-link">Documentacion</a> </td> </tr> <tr> <td class = "element" >:autofill</td> <td>Cuando se utiliza con un elemento &lt;input&gt; el navegador llenara el espacio con texto recomendado</td> <td> <a id = "link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:autofill">Documentacion</a> </td> </tr> <tr> <td class = "element" >:disabled</td> <td>Representa un elemento que estara desactivo en la pagina, no se podra interactuar con ella</td> <td> <a id = "link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled">Documentacion</a> </td> </tr> <tr> <td class = "element" >:enabled</td> <td>Representa un elemento que estara activado en la pagina, se podra interactuar con ella</td> <td> <a id = "link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled">Documentacion</a> </td> </tr> <tr> <td class = "element" >:empty</td> <td>Identifica si un elemento no tiene hijos</td> <td> <a id = "link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/:empty">Documentacion</a> </td> </tr> </tbody> </table>
CREATE SEQUENCE seq_storeID INCREMENT BY 10 MINVALUE 100 NO CYCLE; CREATE SEQUENCE seq_registerNr INCREMENT BY 5 MINVALUE 2 NO CYCLE; CREATE TYPE ModellEnum AS ENUM ('OLYMPIA', 'QUIO', 'STAR'); CREATE TABLE Mitarbeiterin ( Name VARCHAR(255) NOT NULL, SVNR INTEGER NOT NULL, Filialnr INTEGER NOT NULL, PRIMARY KEY(SVNR) ); CREATE TABLE Filiale ( Filialnr INTEGER NOT NULL DEFAULT NEXTVAL('seq_storeID'), Land VARCHAR(255) NOT NULL, Adresse VARCHAR(255) NOT NULL, SVNR INTEGER NOT NULL, HauptkassaFilialnr INTEGER NOT NULL, HauptkassaKNR INTEGER NOT NULL, FOREIGN KEY(SVNR) REFERENCES Mitarbeiterin(SVNR), PRIMARY KEY(Filialnr) ); ALTER TABLE Mitarbeiterin ADD CONSTRAINT fk_WorkPlace FOREIGN KEY (Filialnr) REFERENCES Filiale(Filialnr) DEFERRABLE INITIALLY DEFERRED; CREATE TABLE Kassa ( Filialnr INTEGER NOT NULL, KNR INTEGER NOT NULL DEFAULT NEXTVAL('seq_registerNr'), Modell ModellEnum NOT NULL, FOREIGN KEY(Filialnr) REFERENCES Filiale(Filialnr), PRIMARY KEY(Filialnr, KNR) ); ALTER TABLE Filiale ADD CONSTRAINT fk_MainCashRegister FOREIGN KEY (HauptkassaFilialnr, HauptkassaKNR) REFERENCES Kassa(Filialnr, KNR) DEFERRABLE INITIALLY DEFERRED; CREATE TABLE Rechnung ( Filialnr INTEGER NOT NULL, KNR INTEGER NOT NULL, Jahr INTEGER NOT NULL, RNR INTEGER NOT NULL, Rabatt NUMERIC(10,2) NOT NULL CHECK(Rabatt >= 0 AND Rabatt < 100), FOREIGN KEY(Filialnr, KNR) REFERENCES Kassa(Filialnr, KNR), PRIMARY KEY(Filialnr, KNR, Jahr, RNR) ); CREATE TABLE Versandlager ( Filialnr INTEGER NOT NULL, m2 INTEGER NOT NULL, FOREIGN KEY(Filialnr) REFERENCES Filiale(Filialnr), PRIMARY KEY(Filialnr) ); CREATE TABLE Produktion ( Filialnr INTEGER NOT NULL, SecLvl INTEGER NOT NULL, FOREIGN KEY(Filialnr) REFERENCES Versandlager(Filialnr), PRIMARY KEY(Filialnr) ); CREATE TABLE Ware ( VNr INTEGER NOT NULL, Herstellerin VARCHAR(255) NOT NULL, SerNr INTEGER NOT NULL, Bezeichnung VARCHAR(255) NOT NULL CHECK(Bezeichnung ~* $$^([A-Z]){4}\#\w{5}$$), Preis NUMERIC(10,2) NOT NULL CHECK(Preis > 0), PRIMARY KEY(VNr, Herstellerin, SerNr) ); CREATE TABLE enthaelt ( Filialnr INTEGER NOT NULL, KNR INTEGER NOT NULL, Jahr INTEGER NOT NULL, RNR INTEGER NOT NULL, VNr INTEGER NOT NULL, Herstellerin VARCHAR(255) NOT NULL, SerNr INTEGER NOT NULL, Anzahl INTEGER NOT NULL, FOREIGN KEY(Filialnr, KNR, Jahr, RNR) REFERENCES Rechnung(Filialnr, KNR, Jahr, RNR), FOREIGN KEY(VNr, Herstellerin, SerNr) REFERENCES Ware(VNr, Herstellerin, SerNr), PRIMARY KEY(Filialnr, KNR, Jahr, RNR, VNr, Herstellerin, SerNr) ); CREATE TABLE hergestellt ( VNr INTEGER NOT NULL, Herstellerin VARCHAR(255) NOT NULL, SerNr INTEGER NOT NULL, Filialnr INTEGER NOT NULL, Datum DATE NOT NULL CHECK(Datum > '2020-04-10'::DATE), FOREIGN KEY(Filialnr) REFERENCES Produktion(Filialnr), FOREIGN KEY(VNr, Herstellerin, SerNr) REFERENCES Ware(VNr, Herstellerin, SerNr), PRIMARY KEY(VNr, Herstellerin, SerNr) ); CREATE TABLE angeworben ( Neuling INTEGER NOT NULL, Werberin INTEGER NOT NULL, Datum DATE NOT NULL, FOREIGN KEY(Neuling) REFERENCES Mitarbeiterin(SVNR), FOREIGN KEY(Werberin) REFERENCES Mitarbeiterin(SVNR), PRIMARY KEY(Neuling) ); CREATE TABLE schult ( Azubi INTEGER NOT NULL, Trainerin INTEGER NOT NULL, Filialnr INTEGER NOT NULL, KNR INTEGER NOT NULL, Bewertung VARCHAR(255) NOT NULL, UNIQUE(Azubi, Filialnr, KNR), FOREIGN KEY(Azubi) REFERENCES Mitarbeiterin(SVNR), FOREIGN KEY(Trainerin) REFERENCES Mitarbeiterin(SVNR), FOREIGN KEY(Filialnr, KNR) REFERENCES Kassa(Filialnr, KNR), PRIMARY KEY(Azubi, Trainerin, Filialnr, KNR) );
using Duende.IdentityServer.Models; using ExpertPlanner.Models; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using System; using System.Threading.Tasks; public static class DbSeeder { public static async Task Seed(ApplicationDbContext context, UserManager<ApplicationUser> userManager) { if (!context.Users.Any()) { await SeedUsers(userManager, context); } } private static async Task SeedUsers(UserManager<ApplicationUser> userManager, ApplicationDbContext context) { try { var passwordHasher = new PasswordHasher<ApplicationUser>(); ApplicationUser[] users = { new ApplicationUser { UserName = "zero50x",Link="@zero50x", NormalizedUserName = "zero50x", Email = "zero50x@example.com", NormalizedEmail = "zero50x@example.com", Role = UserRole.Admin, FirstName = "Вадим", MiddleName = "Дроздов", LastName = "Эдуардович", Position = Position.Senior, City = "Москва", PasswordHash = passwordHasher.HashPassword(null, "zero50x") }, new ApplicationUser { UserName = "zaikin88",Link="@zaikin88", NormalizedUserName = "zaikin88", Email = "zaikin88@example.com", NormalizedEmail = "zaikin88@example.com", Role = UserRole.RegularUser, FirstName = "Ваня", MiddleName = "Заикин", LastName = "Александрович", Position = Position.Senior, City = "Москва", PasswordHash = passwordHasher.HashPassword(null, "zaikin88") }, new ApplicationUser { UserName = "nikonovnn",Link="@nikonovnn", NormalizedUserName = "nikonovnn", Email = "nikonovnn@example.com", NormalizedEmail = "nikonovnn@example.com", Role = UserRole.RegularUser, FirstName = "Николай", MiddleName = "Никонов", LastName = "Николаевич", Position = Position.Senior, City = "Москва", PasswordHash = passwordHasher.HashPassword(null, "nikonovnn") }, new ApplicationUser { UserName = "jewestyes",Link="@jewestyes", NormalizedUserName = "jewestyes", Email = "jewestyes@example.com", NormalizedEmail = "jewestyes@example.com", Role = UserRole.Admin, FirstName = "Кузин", MiddleName = "Артемий", LastName = "Вадимович", Position = Position.Middle, City = "Москва", PasswordHash = passwordHasher.HashPassword(null, "jewestyes") }, new ApplicationUser { UserName = "kurier_express",Link="@kurier_express", NormalizedUserName = "kurier_express", Email = "kurier_express@example.com", NormalizedEmail = "kurier_express@example.com", Role = UserRole.RegularUser, FirstName = "Белеза", MiddleName = "Никита", LastName = "Эдуардович", Position = Position.Middle, City = "Москва", PasswordHash = passwordHasher.HashPassword(null, "kurier_express") }, new ApplicationUser { UserName = "IVkulakov",Link="@IVkulakov", NormalizedUserName = "IVkulakov", Email = "IVkulakov@example.com", NormalizedEmail = "IVkulakov@example.com", Role = UserRole.RegularUser, FirstName = "Ваня", MiddleName = "Кулаков", LastName = "Андреевич", Position = Position.Middle, City = "Москва", PasswordHash = passwordHasher.HashPassword(null, "IVkulakov") } }; foreach (var user in users) await userManager.CreateAsync(user); } catch (Exception ex) { Console.WriteLine($"Error during user seeding: {ex.Message}"); } } }
package com.yusuf.bridgely import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.google.firebase.Firebase import com.google.firebase.auth.auth import com.google.firebase.firestore.firestore import com.squareup.picasso.Picasso import com.yusuf.bridgely.databinding.CartRecyclerviewBinding class CartAdapter(var cartProductArrayList: ArrayList<Product>): RecyclerView.Adapter<CartAdapter.CartHolder>() { class CartHolder(var binding:CartRecyclerviewBinding): RecyclerView.ViewHolder(binding.root) { } //firebase init. var firebaseFirestore= Firebase.firestore var firebaseAuth=Firebase.auth var firebaseUser=firebaseAuth.currentUser var balance: Long =0 var newSellerBalance:Long =0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartHolder { var binding=CartRecyclerviewBinding.inflate(LayoutInflater.from(parent.context),parent,false) return CartHolder(binding) } override fun getItemCount(): Int { return cartProductArrayList.size } override fun onBindViewHolder(holder: CartHolder, position: Int) { holder.binding.cartName.text=cartProductArrayList[position].productName holder.binding.cartPrice.text=cartProductArrayList[position].productPrice.toString() Picasso.get().load(cartProductArrayList[position].productImageUrl).into(holder.binding.cartImage) holder.binding.buyButton.setOnClickListener { //codes to be executed when buy button pressed var email=firebaseUser!!.email.toString() firebaseFirestore.collection("Users").document(email).get().addOnSuccessListener { documentSnapshot -> if (documentSnapshot.exists()) { val documentMap = documentSnapshot.data balance = documentMap?.get("balance") as Long if (cartProductArrayList[position].productPrice <= balance) { //balance is higher than the product value. buy it. var dataForReceiver= hashMapOf<String,Long>() dataForReceiver.put("balance",balance-cartProductArrayList[position].productPrice.toLong()) firebaseFirestore.collection("Users").document(email).set(dataForReceiver).addOnSuccessListener { Toast.makeText(holder.itemView.context,"Item bought successfully.",Toast.LENGTH_SHORT).show() //item bought. //delete it from cart and delete it from products. //from cart : firebaseFirestore.collection("Users").document(email).collection("Details").addSnapshotListener { value, error -> if(error!=null){ error.printStackTrace() }else{ if(value!=null){ var documentMap1=value.documents for(document12 in documentMap1){ var deletingProductName=document12.get("productName") as String var deletingProductDescription=document12.get("productDescription") as String var deletingProductPrice=document12.get("productPrice") as Long if(cartProductArrayList.get(position).productName==deletingProductName&&cartProductArrayList.get(position).productDescription==deletingProductDescription&&cartProductArrayList.get(position).productPrice==deletingProductPrice){ //we bought this item. delete it firebaseFirestore.collection("Users").document(email).collection("Details").document(document12.id).delete().addOnSuccessListener { //deleted from details. (Cart) Toast.makeText(holder.itemView.context,"Product has been bought. Thanks!",Toast.LENGTH_SHORT).show() holder.itemView.findNavController().navigate(CartFragmentDirections.actionCartFragmentToProfileFragment()) }.addOnFailureListener { it.printStackTrace() } } } } } } //from products firebaseFirestore.collection("Products").addSnapshotListener { value, error -> if(error!=null){ error.printStackTrace() }else{ if(value!=null){ var docsCheck=value.documents for(docCheck in docsCheck){ var docDeleteName=docCheck.get("productName") as String var docDeleteDescription=docCheck.get("productDescription") as String var docDeletePrice=docCheck.get("productPrice") as Long if(cartProductArrayList.get(position).productName==docDeleteName&&cartProductArrayList.get(position).productDescription==docDeleteDescription&&cartProductArrayList.get(position).productPrice==docDeletePrice){ //delete from products. main store screen firebaseFirestore.collection("Products").document(docCheck.id).delete().addOnSuccessListener { //deleted successfully from products }.addOnFailureListener { it.printStackTrace() } } } } } } }.addOnFailureListener { it.printStackTrace() } //increase the balance of seller firebaseFirestore.collection("Users").document(cartProductArrayList[position].productSeller.toString()).get().addOnSuccessListener { documentSnapshot -> if (documentSnapshot.exists()) { var data2=documentSnapshot.data var sellerBalance=data2!!.get("balance") as Long newSellerBalance=sellerBalance+cartProductArrayList[position].productPrice.toLong() var dataForSeller= hashMapOf<String,Long>() dataForSeller.put("balance",newSellerBalance) firebaseFirestore.collection("Users").document(cartProductArrayList[position].productSeller.toString()).set(dataForSeller).addOnSuccessListener { //seller has increased money }.addOnFailureListener { it.printStackTrace() } } } } else { Toast.makeText(holder.itemView.context,"Insufficient balance.",Toast.LENGTH_SHORT).show() } } } } holder.binding.deleteButton.setOnClickListener { //codes to be executed when delete button is clicked var email=firebaseUser!!.email firebaseFirestore.collection("Users").document(email!!).collection("Details").addSnapshotListener { value, error -> if(error!=null){ error.printStackTrace() }else{ if(value!=null){ var documentMap1=value.documents for(document12 in documentMap1){ var deletingProductName=document12.get("productName") as String var deletingProductDescription=document12.get("productDescription") as String var deletingProductPrice=document12.get("productPrice") as Long if(cartProductArrayList.get(position).productName==deletingProductName&&cartProductArrayList.get(position).productDescription==deletingProductDescription&&cartProductArrayList.get(position).productPrice==deletingProductPrice){ //we bought this item. delete it firebaseFirestore.collection("Users").document(email!!).collection("Details").document(document12.id).delete().addOnSuccessListener { //deleted from details. (Cart) Toast.makeText(holder.itemView.context,"Product has been deleted",Toast.LENGTH_SHORT).show() holder.itemView.findNavController().navigate(CartFragmentDirections.actionCartFragmentToProfileFragment()) }.addOnFailureListener { it.printStackTrace() } } } } } } } } }
import React from "react"; import Router from "next/router"; import ReactMarkdown from "react-markdown"; import { GetServerSideProps, GetStaticProps } from "next"; import prisma from "../lib/prisma"; import { Text } from "@nextui-org/react"; /*export const getServerSideProps: GetServerSideProps = async ({ params }) => { const comments = await prisma.comments.findMany({ where: {postId: String(params.id)} }); return { props: { comments }, revalidate: 10, } }*/ export type PostProps = { id: string; title: string; author: { name: string; email: string; } | null; content: string; published: boolean; }; const Post: React.FC<{ post: PostProps }> = ({ post }) => { const authorName = post.author ? post.author.name : "Unknown author"; return ( <div onClick={() => Router.push("/p/[id]", `/p/${post.id}`)}> <Text h2>{post.title}</Text> <small>By {authorName}</small> <ReactMarkdown children={post.content} /> <p>Commentaire</p> <style jsx>{` div { color: inherit; padding: 2rem; } `}</style> </div> ); }; export default Post;
clc; clear all; addpath('../Utils') %--------------------------------------% %--------Starlink FRAME TEST-----------% %--------------------------------------% % ----------- Test 1 N = 1024; % # of s.c Ng = 32; % c.p length Midx = 4; % subcarrier constellation size Nsym = 300; % # of symbols to simulate Nprovided = Nsym; % # of provided data sequences to generate % Test input params s.SNRdB = nan(); % Signal to noise ratio, in dB s.Fsr = 240e6; % Receiver sample rate, in Hz. s.Fcr = 12075117187.5; % Receiver center frequency, in Hz s.beta = 0; % Doppler parameter s.type = 'QAM'; % subcarrier constellation type s.data = randi([0 Midx-1],N,Nprovided); % Input data % Generate frame, zero pad, and process y = genStrlkFrame(s); y = [y; zeros((N+Ng)*ceil(length(y)/(N+Ng)) - length(y),1)]; % zero pad y = reshape(y,N+Ng,[]); % break up in symbols y = y(Ng+1:end,3:302); % remove CP Y = 1/sqrt(N).*fft(y); % set gutter values to nan() for easier comparison Y(1:2,:) = nan(); Y(end-1:end,:) = nan(); % Expected decoded input data if ( upper(string(s.type)) == "PSK") for ii=1:Nprovided seq = pskmod(s.data(:,ii),2^nextpow2(max(s.data(:,ii)))); seq(1:2) = nan(); seq(end-1:end) = nan(); data_in(:,ii) = getDiffEnc(seq); end elseif( upper(string(s.type)) == "QAM") for ii=1:Nprovided seq = qammod(s.data(:,ii),2^nextpow2(max(s.data(:,ii))),'UnitAveragePower',true); seq(1:2) = nan(); seq(end-1:end) = nan(); data_in(:,ii) = getDiffEnc(seq); end end if (Nsym - Nprovided > 0) Nreps = floor(Nsym/Nprovided); Nremain = mod(Nsym,Nprovided); data_in = repmat(data_in,[1,Nreps]); data_in = [data_in , data_in(:,1:Nremain)]; end % decoded output data data_out = getDiffEnc(Y); % Compare comp = data_out==data_in; for ii = 1:Nsym match(ii) = sum(isnan(data_in(isnan(data_out(:,ii)),ii))); end match = sum(comp) + match; if (Nsym == sum(match == N)) str = 'pass'; else str = 'Failed'; warning("Test failed, %d / %d symbols correctly decoded",sum(match == N),Nsym) end fprintf('1. Starlink Frame Test no noise : %30s \n',str) clear all; % ----------- Test 2 N = 1024; % # of s.c Ng = 32; % c.p length Midx = 4; % subcarrier constellation size Nsym = 300; % # of data symbols in starlink frame Nprovided = 1; % # of provided data sequences to generate SNRdb = 5; avgSCdecodethresh = 0.8; snrthresh_dB = 2; % Test input params s.SNRdB = SNRdb; % Signal to noise ratio, in dB s.Fsr = 240e6; % Receiver sample rate, in Hz. s.Fcr = 12075117187.5; % Receiver center frequency, in Hz s.beta = 0; % Doppler parameter s.type = 'QAM'; % subcarrier constellation type s.data = randi([0 Midx-1],N,Nprovided); % Input data % Generate frame, zero pad, and process y = genStrlkFrame(s); y = [y; zeros((N+Ng)*ceil(length(y)/(N+Ng)) - length(y),1)]; % zero pad y = reshape(y,N+Ng,[]); % break up in symbols p.N = N; p.Ng = Ng; p.Nsym = Nsym; datasyms = y(:,3:302); p.y = datasyms; [snr_dB, nitter] = ofdmSnrEstimator(p); y = y(Ng+1:end,3:302); % remove CP & PSS and SSS Y = 1/sqrt(N).*fft(y); % set gutter values to nan() for easier comparison Y(1:2,:) = nan(); Y(end-1:end,:) = nan(); % Expected decoded input data if ( upper(string(s.type)) == "PSK") for ii=1:Nprovided seq = pskmod(s.data(:,ii),2^nextpow2(max(s.data(:,ii)))); seq(1:2) = nan(); seq(end-1:end) = nan(); data_in(:,ii) = getDiffEnc(seq); end elseif( upper(string(s.type)) == "QAM") for ii=1:Nprovided seq = qammod(s.data(:,ii),2^nextpow2(max(s.data(:,ii))),'UnitAveragePower',true); seq(1:2) = nan(); seq(end-1:end) = nan(); data_in(:,ii) = getDiffEnc(seq); end end if (Nsym - Nprovided > 0) Nreps = floor(Nsym/Nprovided); Nremain = mod(Nsym,Nprovided); data_in = repmat(data_in,[1,Nreps]); data_in = [data_in , data_in(:,1:Nremain)]; end % decoded output data data_out = getDiffEnc(Y); % Compare comp = data_out==data_in; for ii = 1:Nsym match(ii) = sum(isnan(data_in(isnan(data_out(:,ii)),ii))); end match = sum(comp) + match; if ( mean(match)/N > avgSCdecodethresh) str = 'pass'; else str = 'Failed'; warning("Test failed, %.2f / %d subcarriers correctly decoded on average",mean(match),N) end if (abs(snr_dB-SNRdb)>snrthresh_dB) str = 'Failed'; warning("Test failed, SNR estimate off by %.2f dB",abs(snr_dB-SNRdb)) end fprintf('2. Starlink Frame Test noise, full BW : %24s \n',str) clear all; % ----------- Test 3 % No noise, , partial BW, 1 frame N = 1024; % # of s.c Ng = 32; % c.p length Fs = 240e6; % Starlink signal BW Midx = 4; % subcarrier constellation size Nsym = 300; % # of symbols to simulate Nprovided = Nsym; % # of provided data sequences to generate Fsr = 120e6; % Test input params s.SNRdB = nan(); % Signal to noise ratio, in dB s.Fsr = Fsr; % Receiver sample rate, in Hz. s.Fcr = 12075117187.5; % Receiver center frequency, in Hz s.beta = 0; % Doppler parameter s.type = 'QAM'; % subcarrier constellation type s.data = randi([0 Midx-1],N,Nprovided); % Input data % Generate frame, resample, and process y = genStrlkFrame(s); % Resample if (s.Fsr < Fs) tVec = (0:length(y)-1)'/s.Fsr; y = resample(y,tVec,Fs); end y = [y; zeros((N+Ng)*ceil(length(y)/(N+Ng)) - length(y),1)]; % zero pad y = reshape(y,N+Ng,[]); % break up in symbols y = y(Ng+1:end,:); % remove CP Y = 1/sqrt(N).*fft(y); % Disregard PSS and SSS for decoding Y = Y(:,3:302); % Expected decoded input data if ( upper(string(s.type)) == "PSK") for ii=1:Nprovided seq = pskmod(s.data(:,ii),2^nextpow2(max(s.data(:,ii)))); data_in(:,ii) = getDiffEnc(seq); end elseif( upper(string(s.type)) == "QAM") for ii=1:Nprovided seq = qammod(s.data(:,ii),2^nextpow2(max(s.data(:,ii))),'UnitAveragePower',true); data_in(:,ii) = getDiffEnc(seq); end end if (Nsym - Nprovided > 0) Nreps = floor(Nsym/Nprovided); Nremain = mod(Nsym,Nprovided); data_in = repmat(data_in,[1,Nreps]); data_in = [data_in , data_in(:,1:Nremain)]; end % decoded output data data_out = getDiffEnc(Y); % Compare comp = data_out==data_in; for ii = 1:Nsym match(ii) = sum(isnan(data_in(isnan(data_out(:,ii)),ii))); end match = sum(comp) + match; str = 'pass'; if (floor(s.Fsr/Fs*N) > match) str = 'fail'; end fprintf('3. Starlink Frame no noise, %.1f/%.1f MHz BW : %15s \n',s.Fsr/(1e6),Fs/(1e6),str) clear all; % ----------- Test 4 % noise, , full BW, 1 frame, doppler smallgrid = 1; N = 1024; % # of s.c Ng = 32; % c.p length Fs = 240e6; % Starlink signal BW Midx = 4; % subcarrier constellation size Nsym = 300; % # of symbols to simulate Nprovided = Nsym; % # of provided data sequences to generate Fd_target = 200e3; Fcr = getClosestFch(12075117187); beta = -Fd_target./getClosestFch(Fcr); offset = 200e3; SNRdb = 15; if (smallgrid) fmax = Fd_target+offset; fstep = 5e3; fmin = Fd_target-offset; else fmax = 400e3; fstep = 5e3; fmin = -400e3; end fstepFine = 10; Pfa = 0.01; threshold_dopp = 500; threshold_tau = 1/Fs; tau_start = 0; avgSCdecodethresh = 0.95; snrthresh_dB = 2; % Test input params s.SNRdB = SNRdb; % Signal to noise ratio, in dB s.Fsr = Fs; % Receiver sample rate, in Hz. s.Fcr = Fcr; % Receiver center frequency, in Hz s.beta = beta; % Doppler parameter s.type = 'QAM'; % subcarrier constellation type s.data = randi([0 Midx-1],N,Nprovided); % Input data % Generate frame, resample, and process y = genStrlkFrame(s); % Extract doppler estimate a.Fsr = s.Fsr; a.Fcr = s.Fcr; a.fmax = fmax; a.fstep = fstep; a.fstepFine = fstepFine; a.fmin = fmin; a.y = y; a.Pfa = Pfa; out = fftAcqStrlk(a); % Resample if (s.Fsr < Fs) tVec = (0:length(y)-1)'/s.Fsr; y = resample(y,tVec,Fs); end y = [y; zeros((N+Ng)*ceil(length(y)/(N+Ng)) - length(y),1)]; % zero pad str = 'pass'; if (out.values(4) ~= 1) str = 'fail'; warning("Frame incorectly not detected") elseif (abs(out.values(1)-Fd_target) > threshold_dopp) str = 'fail'; warning("Doppler off by %.1f",abs(out.values(1)-Fd_target)) elseif (abs(out.values(2)-tau_start) > threshold_tau) str = 'fail'; warning("Tau off by %.1f",abs(out.values(2)-tau_start)) elseif (~isnan(s.SNRdB) && abs(out.values(3)-SNRdb) > snrthresh_dB) str = 'fail'; warning("SNR estimate off by %.1f",abs(out.values(3)-SNRdb)) end % Doppler correct tVec = [0:length(y)-1]'/(Fs); Fshift = getClosestFch(s.Fcr) - s.Fcr + out.values(1); y = y.*exp(-1j*2*pi*Fshift*tVec); y = reshape(y,N+Ng,[]); % break up in symbols y = y(Ng+1:end,:); % remove CP Y = 1/sqrt(N).*fft(y); % Disregard PSS and SSS for decoding Y = Y(:,3:302); % Expected decoded input data if ( upper(string(s.type)) == "PSK") for ii=1:Nprovided seq = pskmod(s.data(:,ii),2^nextpow2(max(s.data(:,ii)))); data_in(:,ii) = getDiffEnc(seq); end elseif( upper(string(s.type)) == "QAM") for ii=1:Nprovided seq = qammod(s.data(:,ii),2^nextpow2(max(s.data(:,ii))),'UnitAveragePower',true); data_in(:,ii) = getDiffEnc(seq); end end if (Nsym - Nprovided > 0) Nreps = floor(Nsym/Nprovided); Nremain = mod(Nsym,Nprovided); data_in = repmat(data_in,[1,Nreps]); data_in = [data_in , data_in(:,1:Nremain)]; end % decoded output data data_out = getDiffEnc(Y); % Compare comp = data_out==data_in; for ii = 1:Nsym match(ii) = sum(isnan(data_in(isnan(data_out(:,ii)),ii))); end match = sum(comp) + match; if ( mean(match)/N > avgSCdecodethresh) str = 'pass'; else str = 'Failed'; warning("Test failed, %.2f / %d subcarriers correctly decoded on average",mean(match),N) end fprintf('4. Starlink Frame noise, doppler, %.1f/%.1f MHz BW : %9s \n',s.Fsr/(1e6),Fs/(1e6),str) clear all; % ----------- Test 5 % No noise, , full BW, 1 frame, doppler smallgrid = 1; N = 1024; % # of s.c Ng = 32; % c.p length Fs = 240e6; % Starlink signal BW Fsr = 120e6; Midx = 4; % subcarrier constellation size Nsym = 300; % # of symbols to simulate Nprovided = Nsym; % # of provided data sequences to generate Fd_target = 200e3; Fcr = getClosestFch(12075117187); beta = -Fd_target./getClosestFch(Fcr); offset = 200e3; SNRdb = 15; if (smallgrid) fmax = Fd_target+offset; fstep = 5e3; fmin = Fd_target-offset; else fmax = 400e3; fstep = 5e3; fmin = -400e3; end fstepFine = 10; Pfa = 0.01; threshold_dopp = 500; threshold_tau = 1/Fs; tau_start = 0; avgSCdecodethresh = 0.95; snrthresh_dB = 2.5; % Test input params s.SNRdB = SNRdb; % Signal to noise ratio, in dB s.Fsr = Fsr; % Receiver sample rate, in Hz. s.Fcr = Fcr; % Receiver center frequency, in Hz s.beta = beta; % Doppler parameter s.type = 'QAM'; % subcarrier constellation type s.data = randi([0 Midx-1],N,Nprovided); % Input data % Generate frame, resample, and process y = genStrlkFrame(s); % Extract doppler estimate a.Fsr = s.Fsr; a.Fcr = s.Fcr; a.fmax = fmax; a.fstep = fstep; a.fstepFine = fstepFine; a.fmin = fmin; a.y = y; a.Pfa = Pfa; out = fftAcqStrlk(a); % Resample if (s.Fsr < Fs) tVec = (0:length(y)-1)'/s.Fsr; y = resample(y,tVec,Fs); end y = [y; zeros((N+Ng)*ceil(length(y)/(N+Ng)) - length(y),1)]; % zero pad str = 'pass'; if (out.values(4) ~= 1) str = 'fail'; warning("Frame incorectly not detected") elseif (abs(out.values(1)-Fd_target) > threshold_dopp) str = 'fail'; warning("Doppler off by %.1f",abs(out.values(1)-Fd_target)) elseif (abs(out.values(2)-tau_start) > threshold_tau) str = 'fail'; warning("Tau off by %.1f",abs(out.values(2)-tau_start)) elseif (~isnan(s.SNRdB) && abs(out.values(3)-SNRdb) > snrthresh_dB) str = 'fail'; warning("SNR estimate off by %.1f",abs(out.values(3)-SNRdb)) end % Doppler correct tVec = [0:length(y)-1]'/(Fs); Fshift = getClosestFch(s.Fcr) - s.Fcr + out.values(1); y = y.*exp(-1j*2*pi*Fshift*tVec); y = reshape(y,N+Ng,[]); % break up in symbols y = y(Ng+1:end,:); % remove CP Y = 1/sqrt(N).*fft(y); % Disregard PSS and SSS for decoding Y = Y(:,3:302); % Expected decoded input data if ( upper(string(s.type)) == "PSK") for ii=1:Nprovided seq = pskmod(s.data(:,ii),2^nextpow2(max(s.data(:,ii)))); data_in(:,ii) = getDiffEnc(seq); end elseif( upper(string(s.type)) == "QAM") for ii=1:Nprovided seq = qammod(s.data(:,ii),2^nextpow2(max(s.data(:,ii))),'UnitAveragePower',true); data_in(:,ii) = getDiffEnc(seq); end end if (Nsym - Nprovided > 0) Nreps = floor(Nsym/Nprovided); Nremain = mod(Nsym,Nprovided); data_in = repmat(data_in,[1,Nreps]); data_in = [data_in , data_in(:,1:Nremain)]; end % decoded output data data_out = getDiffEnc(Y); % Only look at valid indices data_out = data_out(getValidSC(s.Fcr,s.Fsr),:); data_in = data_in(getValidSC(s.Fcr,s.Fsr),:); Nvalid = length(data_in); % Compare comp = data_out==data_in; for ii = 1:Nsym match(ii) = sum(isnan(data_in(isnan(data_out(:,ii)),ii))); end match = sum(comp) + match; if ( mean(match)/Nvalid > avgSCdecodethresh) str = 'pass'; else str = 'Failed'; warning("Test failed, %.2f / %d subcarriers correctly decoded on average",mean(match),Nvalid) end fprintf('5. Starlink Frame noise, doppler, %.1f/%.1f MHz BW : %9s \n',s.Fsr/(1e6),Fs/(1e6),str)
use std::{ collections::{BTreeMap, BTreeSet}, convert::identity, string::FromUtf8Error, sync::{Arc, OnceLock}, }; use async_trait::async_trait; use bytes::Bytes; use futures::{FutureExt, TryFutureExt}; use http::{HeaderMap, HeaderValue}; use regex::bytes::{Captures, Match, Regex, RegexBuilder}; use reqwest::{Client as ReqwestClient, Error as ReqwestError, Response as ReqwestResponse}; use thiserror::Error; use tokio::task::JoinSet; use toml::Value; use chain_comms::client::Client as NodeClient; use crate::{ config::{self, ProviderConfigExt, Ticker, TickerUnsized}, deviation, price::{self, Coin, CoinWithDecimalPlaces, CoinWithoutDecimalPlaces, Price, Ratio}, provider::{ComparisonProvider, FromConfig, PriceComparisonGuardError}, }; pub(crate) struct SanityCheck { mandatory: bool, http_client: Arc<ReqwestClient>, ticker_mapping: BTreeMap<Arc<TickerUnsized>, Arc<str>>, supported_vs_currencies: BTreeSet<Arc<str>>, } impl SanityCheck { fn extract_mandatory_check_flag<Config>(config: &mut Config) -> Result<bool, ConstructError> where Config: ProviderConfigExt<true>, { const MANDATORY_CHECK_FIELD: &str = "mandatory"; config .misc_mut() .remove(MANDATORY_CHECK_FIELD) .ok_or(ConstructError::MissingField(MANDATORY_CHECK_FIELD)) .and_then(|value: Value| { value.try_into().map_err(|error: toml::de::Error| { ConstructError::DeserializeField(MANDATORY_CHECK_FIELD, error) }) }) } fn construct_http_client<Config>(id: &str) -> Result<Arc<ReqwestClient>, ConstructError> where Config: ProviderConfigExt<true>, { const API_KEY_FIELD: &str = "api_key"; const API_KEY_HEADER: &str = "x-cg-pro-api-key"; ReqwestClient::builder() .default_headers({ let mut headers: HeaderMap = HeaderMap::new(); headers.insert( API_KEY_HEADER, Config::fetch_from_env(id, API_KEY_FIELD) .map_err(ConstructError::EnvVariable) .and_then(|api_key: String| { HeaderValue::from_str(&api_key) .map_err(ConstructError::ConstructApiKeyHeaderValue) })?, ); headers }) .build() .map(Arc::new) .map_err(ConstructError::ConstructHttpClient) } fn extract_ticker_mapping<Config>( config: &mut Config, ) -> Result<BTreeMap<Arc<TickerUnsized>, Arc<str>>, ConstructError> where Config: ProviderConfigExt<true>, { const TICKER_MAPPING_FIELD: &str = "ticker_mapping"; config .misc_mut() .remove(TICKER_MAPPING_FIELD) .ok_or(ConstructError::MissingField(TICKER_MAPPING_FIELD)) .and_then(|value: Value| { value .try_into() .map(|mappings: BTreeMap<Ticker, String>| { mappings .into_iter() .map(|(ticker, mapping): (Ticker, String)| { (ticker.into(), mapping.into()) }) .collect() }) .map_err(|error: toml::de::Error| { ConstructError::DeserializeField(TICKER_MAPPING_FIELD, error) }) }) } async fn fetch_supported_vs_currencies( http_client: &ReqwestClient, ticker_mappings: &BTreeMap<Arc<TickerUnsized>, Arc<str>>, ) -> Result<BTreeSet<Arc<str>>, ConstructError> { const SUPPORTED_VS_CURRENCIES_URL: &str = "https://pro-api.coingecko.com/api/v3/simple/supported_vs_currencies"; http_client .get(SUPPORTED_VS_CURRENCIES_URL) .send() .map_err(ConstructError::SendSupportedVsCurrencies) .and_then(|response: ReqwestResponse| { response .bytes() .map_err(ConstructError::FetchSupportedVsCurrencies) }) .map(|result: Result<Bytes, ConstructError>| { result.and_then(|body: Bytes| { serde_json_wasm::from_slice(&body) .map_err(ConstructError::DeserializeSupportedVsCurrencies) }) }) .map_ok(|currencies: BTreeSet<String>| { currencies .into_iter() .filter_map(|currency: String| { ticker_mappings .values() .find(|mapping: &&Arc<str>| currency == mapping.as_ref()) .cloned() }) .collect() }) .await } fn get_mappings(&self, price: &Price<CoinWithDecimalPlaces>) -> Option<Mappings> { self.ticker_mapping .get_key_value(price.amount().ticker()) .and_then( |(base_ticker, base_mapping): (&Arc<TickerUnsized>, &Arc<str>)| { self.ticker_mapping .get_key_value(price.amount_quote().ticker()) .and_then( |(quote_ticker, quote_mapping): (&Arc<TickerUnsized>, &Arc<str>)| { (self.supported_vs_currencies.contains(base_mapping.as_ref()) || self .supported_vs_currencies .contains(quote_mapping.as_ref())) .then_some(false) .or_else(|| { self.supported_vs_currencies .contains(base_mapping.as_ref()) .then_some(true) }) .map(|inverted: bool| { let base: Mapping = Mapping { ticker: base_ticker.clone(), mapping: base_mapping.clone(), }; let quote: Mapping = Mapping { ticker: quote_ticker.clone(), mapping: quote_mapping.clone(), }; if inverted { Mappings { base: quote, quote: base, } } else { Mappings { base, quote } } }) }, ) }, ) } async fn query( http_client: Arc<ReqwestClient>, mappings: Mappings, regex: &'static Regex, ) -> Result<Price<CoinWithoutDecimalPlaces>, BenchmarkError> { const PRICE_URL: &str = "https://pro-api.coingecko.com/api/v3/simple/price"; http_client .get(PRICE_URL) .query(&[ ("ids", mappings.base.mapping.as_ref()), ("vs_currencies", mappings.quote.mapping.as_ref()), ("precision", "full"), ]) .send() .map_err(BenchmarkError::SendQuery) .and_then(|response: ReqwestResponse| { response .bytes() .map_err(BenchmarkError::ReceiveResponseBody) }) .map(|result: Result<Bytes, BenchmarkError>| { result.and_then(|body: Bytes| { regex .captures(&body) .and_then(|captures: Captures<'_>| captures.name("price")) .ok_or(BenchmarkError::PriceNotFoundInResponse) .and_then(|price: Match<'_>| { String::from_utf8(price.as_bytes().to_vec()) .map_err(BenchmarkError::InvalidUtf8) }) .and_then(|price: String| { Ratio::parse_string(price) .map(|price| { price.to_price( mappings.base.ticker.to_string(), mappings.quote.ticker.to_string(), ) }) .map_err(BenchmarkError::ParsePrice) }) }) }) .await } fn regex() -> &'static Regex { static REGEX: OnceLock<Regex> = OnceLock::new(); REGEX.get_or_init(|| { let Ok(regex): Result<Regex, regex::Error> = RegexBuilder::new( r#"^\{\s*"\w+"\s*:\s*\{\s*"\w*"\s*:\s*(?<price>\d+(?:\.\d+)?)\s*\}\s*\}$"#, ) .case_insensitive(true) .ignore_whitespace(false) .multi_line(true) .build() else { unreachable!() }; regex }) } } struct Mapping { ticker: Arc<TickerUnsized>, mapping: Arc<str>, } struct Mappings { base: Mapping, quote: Mapping, } #[async_trait] impl ComparisonProvider for SanityCheck { async fn benchmark_prices( &self, benchmarked_provider_id: &str, prices: &[Price<CoinWithDecimalPlaces>], max_deviation_exclusive: u64, ) -> Result<(), PriceComparisonGuardError> { let mut prices: Vec<Price<CoinWithDecimalPlaces>> = prices.to_vec(); let mut comparison_prices: Vec<Price<CoinWithoutDecimalPlaces>> = Vec::new(); let regex: &'static Regex = Self::regex(); let mut set: JoinSet<Result<Price<CoinWithoutDecimalPlaces>, BenchmarkError>> = JoinSet::new(); for index in (0..prices.len()).rev() { let price: &Price<CoinWithDecimalPlaces> = &prices[index]; let Some(mappings): Option<Mappings> = self.get_mappings(price) else { let _: Price<CoinWithDecimalPlaces> = prices.remove(index); continue; }; set.spawn(Self::query(self.http_client.clone(), mappings, regex)); } if prices.is_empty() { debug_assert!(set.is_empty()); if self.mandatory { tracing::error!( "Sanity check failed for provider with ID: {id}! No intersection of prices is empty!", id = benchmarked_provider_id, ); Err(PriceComparisonGuardError::ComparisonProviderSpecific( Box::new(BenchmarkError::EmptyPricesIntersection), )) } else { tracing::warn!( "Sanity check unavailable for provider with ID: {id}! No intersection of prices is empty!", id = benchmarked_provider_id, ); Ok(()) } } else { while let Some(result) = set.join_next().await { result .map_err(BenchmarkError::JoinQueryTask) .and_then(identity) .map(|price: Price<CoinWithoutDecimalPlaces>| comparison_prices.push(price)) .map_err(|error: BenchmarkError| { PriceComparisonGuardError::ComparisonProviderSpecific(Box::new(error)) })?; } let result: Result<(), PriceComparisonGuardError> = deviation::compare_prices(&prices, &comparison_prices, max_deviation_exclusive) .await; if result.is_ok() { tracing::info!( "Sanity check passed for provider with ID: {id}.", id = benchmarked_provider_id, ); } else { tracing::error!( "Sanity check failed for provider with ID: {id}!", id = benchmarked_provider_id, ); } result } } } #[derive(Debug, Error)] enum BenchmarkError { #[error("Failed sending price query! Cause: {0}")] SendQuery(ReqwestError), #[error("Failed to receive price query response body! Cause: {0}")] ReceiveResponseBody(ReqwestError), #[error("Failed to retrieve price from response! No price found!")] PriceNotFoundInResponse, #[error("Failed to parse response body as string! Cause: {0}")] InvalidUtf8(FromUtf8Error), #[error("Failed to parse price! Cause: {0}")] ParsePrice(price::Error), #[error("Failed to benchmark prices because intersection is empty!")] EmptyPricesIntersection, #[error("Failed to join price query task into main one! Cause: {0}")] JoinQueryTask(tokio::task::JoinError), } #[async_trait] impl FromConfig<true> for SanityCheck { const ID: &'static str = "coin_gecko_sanity_check"; type ConstructError = ConstructError; async fn from_config<Config>( id: &str, mut config: Config, _: &NodeClient, ) -> Result<Self, Self::ConstructError> where Config: ProviderConfigExt<true>, { let mandatory: bool = Self::extract_mandatory_check_flag(&mut config)?; let http_client: Arc<ReqwestClient> = Self::construct_http_client::<Config>(id)?; let ticker_mapping: BTreeMap<Arc<TickerUnsized>, Arc<str>> = Self::extract_ticker_mapping(&mut config)?; if let Some(fields) = config .into_misc() .into_keys() .reduce(|mut accumulator: String, key: String| { accumulator.reserve(key.len() + 2); accumulator.push_str(", "); accumulator.push_str(&key); accumulator }) { Err(ConstructError::UnknownFields(fields.into_boxed_str())) } else { Self::fetch_supported_vs_currencies(&http_client, &ticker_mapping) .await .map(|supported_vs_currencies: BTreeSet<Arc<str>>| Self { mandatory, http_client, ticker_mapping, supported_vs_currencies, }) } } } #[derive(Debug, Error)] pub(crate) enum ConstructError { #[error("Failed to fetch value from environment! Cause: {0}")] EnvVariable(config::EnvError), #[error("Missing \"{0}\" field in configuration file!")] MissingField(&'static str), #[error("Failed to deserialize field \"{0}\"! Cause: {1}")] DeserializeField(&'static str, toml::de::Error), #[error("Failed to construct header value containing API key! Cause: {0}")] ConstructApiKeyHeaderValue(#[from] http::header::InvalidHeaderValue), #[error("Failed to construct HTTP client! Cause: {0}")] ConstructHttpClient(ReqwestError), #[error("Unknown fields found! Unknown fields: {0}")] UnknownFields(Box<str>), #[error("Failed to send \"supported versus currencies\"! Cause: {0}")] SendSupportedVsCurrencies(ReqwestError), #[error("Failed to fetch \"supported versus currencies\"! Cause: {0}")] FetchSupportedVsCurrencies(ReqwestError), #[error("Failed to deserialize \"supported versus currencies\"! Cause: {0}")] DeserializeSupportedVsCurrencies(serde_json_wasm::de::Error), #[error("Failed to parse prices RPC's URL! Cause: {0}")] InvalidPricesRpcUrl(#[from] url::ParseError), }
import os import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # SMTP credentials smtp_server = os.getenv('SMTP_SERVER') smtp_port = int(os.getenv('SMTP_PORT')) smtp_username = os.getenv('SMTP_USERNAME') smtp_password = os.getenv('SMTP_PASSWORD') # Email parameters from_address = os.getenv('FROM_ADDRESS') to_addresses = os.getenv('TO_ADDRESSES').split(',') # Assume the addresses are comma-separated in the environment variable subject = 'Hello' body = 'Hello World' # Function to send email def send_email(): message = MIMEMultipart() message['From'] = from_address message['To'] = ', '.join(to_addresses) message['Subject'] = subject message.attach(MIMEText(body, 'plain')) print(f"Sending email to {message['To']}: {message['Subject']}\n{message['From']}\n") try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() # Secure the connection server.login(smtp_username, smtp_password) text = message.as_string() server.sendmail(from_address, ', '.join(to_addresses), text) # Send the email server.quit() print("Email sent successfully!") except Exception as e: print(f"Failed to send email: {e}") # Send the email send_email()
1. Loops are great when you want to do the same task/run the same code over and over again, and each time with a different value. They are great when working with arrays. 2. For loop syntax higher level: for(initialization; condition; final-expression){statement} For loop syntax basic syntax: for (step1; step2; step3){} 3. The for loop loops through a block of code a specified number of times. 4. For loop example: for (I = 0; i < 5; i++){ text += "the number is " + i + "<br>"; } Statement 1 sets a variable before the loop starts (var i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). Statement 3 increases a value (i++) each time the code block in the loop has been executed. 5. Two characters represent the for loop code block: ({}) 6. After the code block has been executed, the program returns to step 2. Step2(aka condition): Defines the condition for executing the code block. If the value of the condition is true, the loop statement executes. If the value of the condition is false, the for loop terminates. if on the other the condition is not present, the condition is assumed to be true. 7. Break statement example: function myFunction() { var text = "" var i; for (i = 0; i < 5; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; } 8. continue statement example: function myFunction() { var text = ""; var i; for (i = 0; i < 5; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; } 9. example of an array: var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; // Saab,Volvo,BMW 10. Another example of an array: let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'] console.log(vegetables) // ["Cabbage", "Turnip", "Radish", "Carrot"] 11. var cars = ['BMW', 'Volvo', 'Mini']; var x; for (x of cars) { document.write(x + "<br >"); } //BMW //Volvo //Mini 12. function myFunction() { var person = {fname:"John", lname:"Doe", age:25}; var text = ""; var x; for (x in person) { text += person[x] + " "; } document.getElementById("demo").innerHTML = text; } //John Doe 25 the for/in statement loops through the properties of an object. the block of code inside the loop will be executed once for each property. 13. For of loop example: const array1 = ['a', 'b', 'c']; for (const element of array1) { console.log(element); } // a // b // c Loops through the values of an iterable objects. In this case an array. For-in loop example: var txt = ""; var person = {fname:"John", lname:"Doe", age:25}; var x; for (x in person) { txt += person[x] + " "; } document.getElementById("demo").innerHTML = txt; 14. For-in: loops through the properties of an object. For-of: loops through the values of an iterable object. 15. do while loop example: var text = "" var i = 0; do { text += "<br>The number is " + i; i++; } while (i < 10); document.getElementById("demo").innerHTML = text; //The number is 0 //The number is 1 //The number is 2 //The number is 3 //The number is 4 //The number is 5 //The number is 6 //The number is 7 //The number is 8 //The number is 9 Loops through a block of code while a specified condition is true. In this case number less than 10. 16. When the break statement is used with a switch statement, it breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block. When the break statement is used in a loop, it breaks the loop and continues executing the code after the loop.
import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { logOut } from 'redux/auth/operations'; import { selectUser } from 'redux/auth/selectors'; import { Box, IconButton, Tooltip } from '@mui/material'; import { LogoutOutlined } from '@mui/icons-material'; const UserMenu = () => { const { name } = useSelector(selectUser); const dispatch = useDispatch(); return ( <Box component="div" sx={{ display: 'flex', gap: '16px', alignItems: 'center', color: 'green', }} > <p>Welcome, {name}. </p> <Tooltip title="LogOut" placement="bottom"> <IconButton type="button" size="small" sx={{ border: 1, borderRadius: 2, color: 'red' }} onClick={() => dispatch(logOut())} > <LogoutOutlined /> LogOut </IconButton> </Tooltip> </Box> ); }; export default UserMenu;
@page "/Account/Manage" @using System.ComponentModel.DataAnnotations; @using System.Security.Claims @using Microsoft.AspNetCore.Identity; @using MyApp.Data; @using MyApp.Identity @inject AuthenticationStateProvider AuthenticationStateProvider @inject UserManager<ApplicationUser> UserManager @inject SignInManager<ApplicationUser> SignInManager @inject UserAccessor UserAccessor; @inject IdentityRedirectManager RedirectManager <PageTitle>Profile</PageTitle> <Heading3>Profile</Heading3> <StatusMessage /> <div class="max-w-xl"> <div class="shadow overflow-hidden sm:rounded-md"> <EditForm id="profile-form" Model="Input" FormName="profile" OnValidSubmit="OnValidSubmitAsync" method="post" class="px-4 bg-white dark:bg-black sm:p-6"> <DataAnnotationsValidator /> <ValidationSummary class="mb-3 text-danger text-center font-semibold" /> <div class="flex flex-col gap-y-4"> <div> <label for="username" class="@TextInput.LabelClasses">Username</label> <div class="mt-1 relative rounded-md shadow-sm"> <input id="username" type="text" value="@_username" class="@TextInput.InputClasses" placeholder="Please choose your username." disabled /> </div> </div> <div> <label for="phone-number" class="@TextInput.LabelClasses">Phone number</label> <div class="mt-1 relative rounded-md shadow-sm"> <InputText id="phone-number" type="text" @bind-Value="Input.PhoneNumber" class="@TextInput.InputClasses" placeholder="Please enter your phone number." /> </div> <ValidationMessage For="() => Input.PhoneNumber" class="mt-2 text-danger text-sm" /> </div> <div> <PrimaryButton id="update-profile-button" type="submit">Save</PrimaryButton> </div> </div> </EditForm> </div> </div> @code { private ApplicationUser _user = default!; private string? _username; private string? _phoneNumber; [SupplyParameterFromForm] private InputModel Input { get; set; } = default!; protected override async Task OnInitializedAsync() { Input ??= new(); _user = await UserAccessor.GetRequiredUserAsync(); _username = await UserManager.GetUserNameAsync(_user); _phoneNumber = await UserManager.GetPhoneNumberAsync(_user); Input.PhoneNumber ??= _phoneNumber; } private async Task OnValidSubmitAsync() { if (Input.PhoneNumber != _phoneNumber) { var setPhoneResult = await UserManager.SetPhoneNumberAsync(_user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { RedirectManager.RedirectToCurrentPageWithStatus("Unexpected error when trying to set phone number."); return; } } await SignInManager.RefreshSignInAsync(_user); RedirectManager.RedirectToCurrentPageWithStatus("Your profile has been updated"); } private sealed class InputModel { [Phone] [Display(Name = "Phone number")] public string? PhoneNumber { get; set; } } }
package advantageair_test import ( "encoding/json" "testing" advantageair "github.com/axatol/go-advantage-air" "github.com/stretchr/testify/assert" ) func assertJSONEq(t *testing.T, expected, actual interface{}) { t.Helper() expectedJSON, err := json.Marshal(expected) assert.NoError(t, err) actualJSON, err := json.Marshal(actual) assert.NoError(t, err) assert.JSONEq(t, string(expectedJSON), string(actualJSON)) } func TestChangeSetAirconState(t *testing.T) { expected := map[string]any{"aircons": map[string]any{"ac1": map[string]any{"info": map[string]any{"state": "on"}}}} actual := advantageair.NewChange().SetAirconState("ac1", "on") assertJSONEq(t, expected, actual) } func TestChangeSetAirconMode(t *testing.T) { expected := map[string]any{"aircons": map[string]any{"ac1": map[string]any{"info": map[string]any{"mode": "cool"}}}} actual := advantageair.NewChange().SetAirconMode("ac1", "cool") assertJSONEq(t, expected, actual) } func TestChangeSetAirconFan(t *testing.T) { expected := map[string]any{"aircons": map[string]any{"ac1": map[string]any{"info": map[string]any{"fan": "high"}}}} actual := advantageair.NewChange().SetAirconFan("ac1", "high") assertJSONEq(t, expected, actual) } func TestChangeSetAirconZoneTemperature(t *testing.T) { expected := map[string]any{"aircons": map[string]any{"ac1": map[string]any{"zones": map[string]any{"z1": map[string]any{"setTemp": 24}}}}} actual := advantageair.NewChange().SetAirconZoneTemperature("ac1", "z1", 24) assertJSONEq(t, expected, actual) } func TestChangeSetAirconZoneState(t *testing.T) { expected := map[string]any{"aircons": map[string]any{"ac1": map[string]any{"zones": map[string]any{"z1": map[string]any{"state": "open"}}}}} actual := advantageair.NewChange().SetAirconZoneState("ac1", "z1", "open") assertJSONEq(t, expected, actual) } func TestChangeComposite(t *testing.T) { expected := map[string]any{ "aircons": map[string]any{ "ac1": map[string]any{ "info": map[string]any{ "state": "on", "mode": "cool", "fan": "high", }, "zones": map[string]any{ "z1": map[string]any{ "setTemp": 24, "state": "open", }, }, }, }, } actual := advantageair.NewChange(). SetAirconState("ac1", "on"). SetAirconMode("ac1", "cool"). SetAirconFan("ac1", "high"). SetAirconZoneTemperature("ac1", "z1", 24). SetAirconZoneState("ac1", "z1", "open") assertJSONEq(t, expected, actual) }
import json import numpy as np import pytorch_lightning as pl import torch import unitraj.datasets.common_utils as common_utils class BaseModel(pl.LightningModule): def __init__(self, config): super().__init__() self.config = config self.pred_dicts = [] if config.get('eval_nuscenes', False): self.init_nuscenes() def init_nuscenes(self): if self.config.get('eval_nuscenes', False): from nuscenes import NuScenes from nuscenes.eval.prediction.config import PredictionConfig from nuscenes.prediction import PredictHelper nusc = NuScenes(version='v1.0-trainval', dataroot=self.config['nuscenes_dataroot']) # Prediction helper and configs: self.helper = PredictHelper(nusc) with open('models/base_model/nuscenes_config.json', 'r') as f: pred_config = json.load(f) self.pred_config5 = PredictionConfig.deserialize(pred_config, self.helper) def forward(self, batch): """ Forward pass for the model :param batch: input batch :return: prediction: { 'predicted_probability': (batch_size,modes)), 'predicted_trajectory': (batch_size,modes, future_len, 2) } loss (with gradient) """ raise NotImplementedError def training_step(self, batch, batch_idx): prediction, loss = self.forward(batch) self.compute_official_evaluation(batch, prediction) self.log_info(batch, prediction, status='train') return loss def validation_step(self, batch, batch_idx): prediction, loss = self.forward(batch) self.compute_official_evaluation(batch, prediction) self.log_info(batch, prediction, status='val') return loss def on_validation_epoch_end(self): if self.config.get('eval_waymo', False): metric_results, result_format_str = self.compute_metrics_waymo(self.pred_dicts) print(metric_results) print(result_format_str) elif self.config.get('eval_nuscenes', False): metric_results = self.compute_metrics_nuscenes(self.pred_dicts) print('\n', metric_results) self.pred_dicts = [] def configure_optimizers(self): raise NotImplementedError def compute_metrics_nuscenes(self, pred_dicts): from nuscenes.eval.prediction.compute_metrics import compute_metrics metric_results = compute_metrics(pred_dicts, self.helper, self.pred_config5) return metric_results def compute_metrics_waymo(self, pred_dicts): from unitraj.models.base_model.waymo_eval import waymo_evaluation try: num_modes_for_eval = pred_dicts[0]['pred_trajs'].shape[0] except: num_modes_for_eval = 6 metric_results, result_format_str = waymo_evaluation(pred_dicts=pred_dicts, num_modes_for_eval=num_modes_for_eval) metric_result_str = '\n' for key in metric_results: metric_results[key] = metric_results[key] metric_result_str += '%s: %.4f \n' % (key, metric_results[key]) metric_result_str += '\n' metric_result_str += result_format_str return metric_result_str, metric_results def compute_official_evaluation(self, batch_dict, prediction): if self.config.get('eval_waymo', False): input_dict = batch_dict['input_dict'] pred_scores = prediction['predicted_probability'] pred_trajs = prediction['predicted_trajectory'] center_objects_world = input_dict['center_objects_world'].type_as(pred_trajs) num_center_objects, num_modes, num_timestamps, num_feat = pred_trajs.shape pred_trajs_world = common_utils.rotate_points_along_z_tensor( points=pred_trajs.reshape(num_center_objects, num_modes * num_timestamps, num_feat), angle=center_objects_world[:, 6].reshape(num_center_objects) ).reshape(num_center_objects, num_modes, num_timestamps, num_feat) pred_trajs_world[:, :, :, 0:2] += center_objects_world[:, None, None, 0:2] + input_dict['map_center'][:, None, None, 0:2] pred_dict_list = [] for bs_idx in range(batch_dict['batch_size']): single_pred_dict = { 'scenario_id': input_dict['scenario_id'][bs_idx], 'pred_trajs': pred_trajs_world[bs_idx, :, :, 0:2].cpu().numpy(), 'pred_scores': pred_scores[bs_idx, :].cpu().numpy(), 'object_id': input_dict['center_objects_id'][bs_idx], 'object_type': input_dict['center_objects_type'][bs_idx], 'gt_trajs': input_dict['center_gt_trajs_src'][bs_idx].cpu().numpy(), 'track_index_to_predict': input_dict['track_index_to_predict'][bs_idx].cpu().numpy() } pred_dict_list.append(single_pred_dict) assert len(pred_dict_list) == batch_dict['batch_size'] self.pred_dicts += pred_dict_list elif self.config.get('eval_nuscenes', False): from nuscenes.eval.prediction.data_classes import Prediction input_dict = batch_dict['input_dict'] pred_scores = prediction['predicted_probability'] pred_trajs = prediction['predicted_trajectory'] center_objects_world = input_dict['center_objects_world'].type_as(pred_trajs) num_center_objects, num_modes, num_timestamps, num_feat = pred_trajs.shape # assert num_feat == 7 pred_trajs_world = common_utils.rotate_points_along_z_tensor( points=pred_trajs.reshape(num_center_objects, num_modes * num_timestamps, num_feat), angle=center_objects_world[:, 6].reshape(num_center_objects) ).reshape(num_center_objects, num_modes, num_timestamps, num_feat) pred_trajs_world[:, :, :, 0:2] += center_objects_world[:, None, None, 0:2] + input_dict['map_center'][:, None, None, 0:2] pred_dict_list = [] for bs_idx in range(batch_dict['batch_size']): single_pred_dict = { 'instance': input_dict['scenario_id'][bs_idx].split('_')[1], 'sample': input_dict['scenario_id'][bs_idx].split('_')[2], 'prediction': pred_trajs_world[bs_idx, :, 4::5, 0:2].cpu().numpy(), 'probabilities': pred_scores[bs_idx, :].cpu().numpy(), } pred_dict_list.append( Prediction(instance=single_pred_dict["instance"], sample=single_pred_dict["sample"], prediction=single_pred_dict["prediction"], probabilities=single_pred_dict["probabilities"]).serialize()) self.pred_dicts += pred_dict_list def log_info(self, batch, prediction, status='train'): ## logging # Split based on dataset inputs = batch['input_dict'] gt_traj = inputs['center_gt_trajs'].unsqueeze(1) # .transpose(0, 1).unsqueeze(0) gt_traj_mask = inputs['center_gt_trajs_mask'].unsqueeze(1) center_gt_final_valid_idx = inputs['center_gt_final_valid_idx'] predicted_traj = prediction['predicted_trajectory'] predicted_prob = prediction['predicted_probability'].detach().cpu().numpy() # Calculate ADE losses ade_diff = torch.norm(predicted_traj[:, :, :, :2] - gt_traj[:, :, :, :2], 2, dim=-1) ade_losses = torch.sum(ade_diff * gt_traj_mask, dim=-1) / torch.sum(gt_traj_mask, dim=-1) ade_losses = ade_losses.cpu().detach().numpy() minade = np.min(ade_losses, axis=1) # Calculate FDE losses bs, modes, future_len = ade_diff.shape center_gt_final_valid_idx = center_gt_final_valid_idx.view(-1, 1, 1).repeat(1, modes, 1).to(torch.int64) fde = torch.gather(ade_diff, -1, center_gt_final_valid_idx).cpu().detach().numpy().squeeze(-1) minfde = np.min(fde, axis=-1) best_fde_idx = np.argmin(fde, axis=-1) predicted_prob = predicted_prob[np.arange(bs), best_fde_idx] miss_rate = (minfde > 2.0) brier_fde = minfde + (1 - predicted_prob) loss_dict = { 'minADE6': minade, 'minFDE6': minfde, 'miss_rate': miss_rate.astype(np.float32), 'brier_fde': brier_fde} important_metrics = list(loss_dict.keys()) new_dict = {} dataset_names = inputs['dataset_name'] unique_dataset_names = np.unique(dataset_names) for dataset_name in unique_dataset_names: batch_idx_for_this_dataset = np.argwhere([n == str(dataset_name) for n in dataset_names])[:, 0] for key in loss_dict.keys(): new_dict[dataset_name + '/' + key] = loss_dict[key][batch_idx_for_this_dataset] # # calculate the average metrics of all the datasets # avg_dict = {} # for key in important_metrics: # key_for_all_dataset = [dataset_name+'/'+key for dataset_name in unique_dataset_names] # avg_dict['avg/'+key] = np.array(np.mean([new_dict[k].mean() for k in key_for_all_dataset])).reshape(1) # merge new_dict with log_dict loss_dict.update(new_dict) # loss_dict.update(avg_dict) if status == 'val' and self.config.get('eval', False): # Split scores based on trajectory type new_dict = {} trajectory_types = inputs["trajectory_type"].cpu().numpy() trajectory_correspondance = {0: "stationary", 1: "straight", 2: "straight_right", 3: "straight_left", 4: "right_u_turn", 5: "right_turn", 6: "left_u_turn", 7: "left_turn"} for traj_type in range(8): batch_idx_for_traj_type = np.where(trajectory_types == traj_type)[0] if len(batch_idx_for_traj_type) > 0: for key in important_metrics: new_dict["traj_type/" + trajectory_correspondance[traj_type] + "_" + key] = loss_dict[key][ batch_idx_for_traj_type] loss_dict.update(new_dict) # Split scores based on kalman_difficulty @6s new_dict = {} kalman_difficulties = inputs["kalman_difficulty"][:, -1].cpu().numpy() # Last is difficulty at 6s (others are 2s and 4s) for kalman_bucket, (low, high) in {"easy": [0, 30], "medium": [30, 60], "hard": [60, 9999999]}.items(): batch_idx_for_kalman_diff = \ np.where(np.logical_and(low <= kalman_difficulties, kalman_difficulties < high))[0] if len(batch_idx_for_kalman_diff) > 0: for key in important_metrics: new_dict["kalman/" + kalman_bucket + "_" + key] = loss_dict[key][batch_idx_for_kalman_diff] loss_dict.update(new_dict) new_dict = {} agent_types = [1, 2, 3] agent_type_dict = {1: "vehicle", 2: "pedestrian", 3: "bicycle"} for type in agent_types: batch_idx_for_type = np.where(inputs['center_objects_type'] == type)[0] if len(batch_idx_for_type) > 0: for key in important_metrics: new_dict["agent_types" + '/' + agent_type_dict[type] + "_" + key] = loss_dict[key][ batch_idx_for_type] # merge new_dict with log_dict loss_dict.update(new_dict) # Take mean for each key but store original length before (useful for aggregation) size_dict = {key: len(value) for key, value in loss_dict.items()} loss_dict = {key: np.mean(value) for key, value in loss_dict.items()} for k, v in loss_dict.items(): self.log(status + "/" + k, v, on_step=False, on_epoch=True, sync_dist=True, batch_size=size_dict[k]) return
package com.lcwd.blog.service; import java.util.List; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.lcwd.blog.entity.Category; import com.lcwd.blog.exception.ResourceNotFoundException; import com.lcwd.blog.payload.CategoryDto; import com.lcwd.blog.repository.CategoryRepo; @Service public class CategoryServiceImpl implements CategoryServiceI { @Autowired private CategoryRepo repo; @Autowired private ModelMapper mapper; @Override public CategoryDto addCategory(CategoryDto categoryDto) { Category map = mapper.map(categoryDto, Category.class); Category save = repo.save(map); CategoryDto map2 = mapper.map(save, CategoryDto.class); return map2; } @Override public CategoryDto updateCategory(Integer categoryId, CategoryDto categoryDto) { Category existingCategory = repo.findById(categoryId).orElseThrow(() -> new ResourceNotFoundException()); existingCategory.setCategoryDescription(categoryDto.getCategoryDescription()); existingCategory.setCategoryTitle(categoryDto.getCategoryTitle()); Category save = repo.save(existingCategory); CategoryDto map = mapper.map(save, CategoryDto.class); return map; } @Override public CategoryDto getCategoryById(Integer categoryId) { Category existingCategory = repo.findById(categoryId).orElseThrow(() -> new ResourceNotFoundException()); CategoryDto map = mapper.map(existingCategory, CategoryDto.class); return map; } @Override public List<CategoryDto> getAllCategories() { List<Category> findAll = repo.findAll(); List<CategoryDto> collect = findAll.stream().map(category -> mapper.map(category, CategoryDto.class)) .collect(Collectors.toList()); return collect; } @Override public void deleteCategory(Integer categoryId) { Category existingCategory = repo.findById(categoryId).orElseThrow(() -> new ResourceNotFoundException()); repo.delete(existingCategory); } }
using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using ModelLibrary.Model.Report; using PetsServer.Auth.Authentication; using PetsServer.Auth.Authorization.Model; using PetsServer.Auth.Authorization.Service; using PetsServer.Domain.Log.Service; using PetsServer.Domain.Report.Model; using PetsServer.Domain.Report.Service; namespace PetsServer.Domain.Report.Controller { [Route("reports")] [ApiController] [Authorize] public class ReportController(IMapper mapper) : ControllerBase { private readonly IMapper _mapper = mapper; private readonly ReportService _service = new(); private readonly AuthenticationService _authenticationService = new(); private readonly LoggerFacade _logger = new(new DbLogger(), new TxtLogger()); [HttpPost(Name = "CreateReport")] public IActionResult Create(string from, string to) { var user = _authenticationService.GetUser(User.Identity.Name); if (!AuthorizationService.IsPossible(Possibilities.Insert, Entities.Report, user)) return Problem(null, null, 403, "У вас нет привилегий"); if (!DateOnly.TryParse(from, out var fromDate) || !DateOnly.TryParse(to, out var toDate)) return BadRequest("Не правильный формат дат"); var id = _service.Create(fromDate, toDate); _logger.Log(user, Entities.Report, Possibilities.Insert, typeof(ReportModel), id); return Ok(); } [HttpGet(Name = "GetReports")] public IActionResult Get(int? page, int? pages, string? filter, string? sortField, int? sortType) { var user = _authenticationService.GetUser(User.Identity.Name); if (!AuthorizationService.IsPossible(Possibilities.Read, Entities.Report, user)) return Problem(null, null, 403, "У вас нет привилегий"); var views = _service.Get(page, pages, filter, sortField, sortType, user, _mapper); return Ok(views); } [HttpGet("{id}", Name = "GetReport")] public IActionResult Get(int id) { var user = _authenticationService.GetUser(User.Identity.Name); if (!AuthorizationService.IsPossible(Possibilities.Read, Entities.Report, user)) return Problem(null, null, 403, "У вас нет привилегий"); var entity = _service.Get(id); var view = _mapper.Map<ReportViewOne>(entity); return Ok(view); } [HttpDelete("{id}", Name = "DeleteReport")] public ActionResult Delete(int id) { var user = _authenticationService.GetUser(User.Identity.Name); if (!AuthorizationService.IsPossible(Possibilities.Delete, Entities.Report, user)) return Problem(null, null, 403, "У вас нет привилегий"); _service.Delete(id); _logger.Log(user, Entities.Report, Possibilities.Delete, typeof(ReportModel), id); return Ok(); } [HttpPost("{reportId}/statuses/{statusId}",Name = "SetReportStatus")] public IActionResult SetReportStatus(int reportId, int statusId) { var user = _authenticationService.GetUser(User.Identity.Name); if (!AuthorizationService.IsPossible(Possibilities.ChangeStatus, Entities.Report, user)) return Problem(null, null, 403, "У вас нет привилегий"); _service.SetReportStatus(reportId, statusId); _logger.Log(user, Entities.Report, Possibilities.ChangeStatus, typeof(ReportModel), reportId); return Ok(); } [HttpGet("{reportId}/statuses", Name = "GetReportStatuses")] public IActionResult GetStatuses(int reportId) { var user = _authenticationService.GetUser(User.Identity.Name); var statuses = _service.GetStatuses(reportId, user); return Ok(statuses); } [HttpGet("{reportId}/actual-status", Name = "GetReportActualStatuses")] public IActionResult GetActualStatus(int reportId) { var status = _service.GetActualStatus(reportId); return Ok(status); } } }
#ifndef MERGE_AND_SHRINK_SHRINK_STRATEGY_H #define MERGE_AND_SHRINK_SHRINK_STRATEGY_H #include "types.h" #include <string> #include <vector> namespace utils { class LogProxy; } namespace merge_and_shrink { class Distances; class TransitionSystem; class ShrinkStrategy { protected: virtual std::string name() const = 0; virtual void dump_strategy_specific_options(utils::LogProxy &log) const = 0; public: ShrinkStrategy() = default; virtual ~ShrinkStrategy() = default; /* Compute a state equivalence relation over the states of the given transition system such that its new number of states after abstracting it according to this equivalence relation is at most target_size (currently violated; see issue250). dist must be the distances information associated with the given transition system. Note that if target_size equals the current size of the transition system, the shrink strategy is not required to compute an equivalence relation that results in actually shrinking the size of the transition system. However, it may attempt to e.g. compute an equivalence relation that results in shrinking the transition system in an information-preserving way. */ virtual StateEquivalenceRelation compute_equivalence_relation( const TransitionSystem &ts, const Distances &distances, int target_size, utils::LogProxy &log) const = 0; virtual bool requires_init_distances() const = 0; virtual bool requires_goal_distances() const = 0; void dump_options(utils::LogProxy &log) const; std::string get_name() const; }; } #endif
# # (C) Tenable Network Security, Inc. # include("compat.inc"); if (description) { script_id(22189); script_version("$Revision: 1.34 $"); script_cvs_date("$Date: 2016/06/30 19:55:38 $"); script_cve_id("CVE-2006-3649"); script_bugtraq_id(19414); script_osvdb_id(27849); script_xref(name:"CERT", value:"159484"); script_xref(name:"MSFT", value:"MS06-047"); script_name(english:"MS06-047: Vulnerability in Microsoft Visual Basic for Applications Could Allow Remote Code Execution (921645)"); script_summary(english:"Determines the version of vbe6.dll"); script_set_attribute(attribute:"synopsis", value:"Arbitrary code can be executed on the remote host through VBA."); script_set_attribute(attribute:"description", value: "The remote host is running a version of Microsoft Visual Basic for Applications that is vulnerable to a buffer overflow when handling malformed documents. An attacker may exploit this flaw to execute arbitrary code on this host by sending a malformed file to a user of the remote host."); script_set_attribute(attribute:"see_also", value:"https://technet.microsoft.com/library/security/ms06-047"); script_set_attribute(attribute:"solution", value:"Microsoft has released a set of patches for Office."); script_set_cvss_base_vector("CVSS2#AV:N/AC:H/Au:N/C:P/I:P/A:P"); script_set_cvss_temporal_vector("CVSS2#E:F/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"exploited_by_malware", value:"true"); script_set_attribute(attribute:"vuln_publication_date", value:"2006/08/08"); script_set_attribute(attribute:"patch_publication_date", value:"2006/08/08"); script_set_attribute(attribute:"plugin_publication_date", value:"2006/08/08"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"cpe:/a:microsoft:office"); script_set_attribute(attribute:"cpe", value:"cpe:/a:microsoft:access"); script_set_attribute(attribute:"cpe", value:"cpe:/a:microsoft:project"); script_set_attribute(attribute:"cpe", value:"cpe:/a:microsoft:visio"); script_set_attribute(attribute:"cpe", value:"cpe:/a:microsoft:works"); script_set_attribute(attribute:"cpe", value:"cpe:/a:microsoft:visual_basic_software_development_kit"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2006-2016 Tenable Network Security, Inc."); script_family(english:"Windows : Microsoft Bulletins"); script_dependencies("smb_hotfixes.nasl", "ms_bulletin_checks_possible.nasl"); script_require_keys("SMB/MS_Bulletin_Checks/Possible"); script_require_ports(139, 445, 'Host/patch_management_checks'); exit(0); } include("audit.inc"); include("smb_func.inc"); include("smb_hotfixes.inc"); include("smb_hotfixes_fcheck.inc"); include("misc_func.inc"); get_kb_item_or_exit("SMB/MS_Bulletin_Checks/Possible"); bulletin = 'MS06-047'; kb = '921645'; kbs = make_list(kb); if (get_kb_item("Host/patch_management_checks")) hotfix_check_3rd_party(bulletin:bulletin, kbs:kbs, severity:SECURITY_WARNING); common = hotfix_get_commonfilesdir(); if ( ! common ) exit(1, "Failed to get the Common Files directory."); #VBA 6- C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\vbe6.dll = 6.4.99.72 share = ereg_replace(pattern:"^([A-Za-z]):.*", replace:"\1$", string:common); vba6 = ereg_replace(pattern:"^[A-Za-z]:(.*)", replace:"\1\Microsoft Shared\VBA\VBA6\vbe6.dll", string:common); port = kb_smb_transport(); if(! smb_session_init()) audit(AUDIT_FN_FAIL, "smb_session_init"); r = NetUseAdd(login:kb_smb_login(), password:kb_smb_password(), domain:kb_smb_domain(), share:share); if ( r != 1 ) { NetUseDel(); audit(AUDIT_SHARE_FAIL,share); } handle = CreateFile (file:vba6, desired_access:GENERIC_READ, file_attributes:FILE_ATTRIBUTE_NORMAL, share_mode:FILE_SHARE_READ, create_disposition:OPEN_EXISTING); if ( ! isnull(handle) ) { v = GetFileVersion(handle:handle); CloseFile(handle:handle); if ( ! isnull(v) ) { if ( v[0] == 6 && ( v[1] < 4 || ( v[1] == 4 && v[2] < 99 ) || ( v[1] == 4 && v[2] == 99 && v[3] < 72 ) ) ) { { hotfix_add_report('\nPath : '+share-'$'+':'+vba6+ '\nVersion : '+join(v, sep:'.')+ '\nShould be : 6.4.99.72\n', bulletin:bulletin, kb:kb); set_kb_item(name:"SMB/Missing/MS06-047", value:TRUE); hotfix_security_warning(); } NetUseDel(); exit(0); } } else { NetUseDel(); exit(1, "Failed to get file version."); } } NetUseDel();
<template> <div class="component-wrapper"> <izy-loader v-show="isLoading" /> <div class="row"> <div class="col-6"> <div class="block-container"> <div class="pd-20"> <form class="_form mb mt-10" @submit.prevent="save"> <div class="form-group"> <div class="field-wrapper"> <div class="field-placeholder"> <span>{{ t('Cuisine name') }}</span> </div> <input type="text" name="name" autocomplete="off" placeholder="Cuisine name" v-model="ghost.name" v-validate="'required|min:2'" > <izy-error :name="'name'" :show="showErrors" :err="errors"/> </div> </div> <div class="text-right"> <button class="btn btn-primary w-150" :disabled="isLoading" type="submit" >{{ isLoading ? 'Loading...' : 'Save Cuisine' }}</button> </div> </form> </div> </div> </div> <div class="col-6"> <div class="block-container"> <div class="pd-20"> <img :src="ghost.cover" class="img-fluid"/> <div class="text-right mt-20"> <vue-dropzone ref="myVueDropzone" id="dropzone" :options="dropzoneOptions" /> </div> </div> </div> </div> </div> </div> </template> <script> import vue2Dropzone from 'vue2-dropzone' const CUISINE_ADMIN_LINK = '/admin/lists/cuisines' export default { name: 'admin-cuisine', components: { vueDropzone: vue2Dropzone }, data: () => ({ model: {}, dropzoneOptions: {} }), created () { this.setupDropzone() }, methods: { async save () { this.isLoading = true let url = `/cuisines` const res = await axios.post(url, this.ghost) .catch (e => { console.log(e) const message = e.response.data.message || e.response.data.msg || e.response.data this.$swal.error(message) }) this.isLoading = false if (res) { this.$toastr.success('Update successful', 'The cuisine has been successfully updaed') setTimeout(() => { window.location.href = CUISINE_ADMIN_LINK }, 500) } }, setupDropzone () { const self = this this.dropzoneOptions = { dictDefaultMessage: this.$translate.text('Click or Drop a file here to upload (Max: 5MB)'), url: '/api/v1/upload', thumbnailWidth: 180, uploadMultiple: true, acceptedFiles: ".png,.jpg,.jpeg", paramName: 'file', addRemoveLinks: false, maxFilesize: 5, maxFiles: 1, timeout: 0, headers: { 'Authorization': 'Bearer ' + _auth }, sending: () => { self.isLoading = true }, complete: (file) => { self.isLoading = false self.$refs.myVueDropzone.removeFile(file) }, success: function (file, response) { self.$set(self.ghost, 'cover', response) } } } } } </script>
// // YRNetworkConfiguration.h // YRHttpManager // // Created by sunwu on 2018/2/27. // Copyright © 2018年 PYYX. All rights reserved. // #import <Foundation/Foundation.h> @class YRHttpResponse; /** * 缓存策略 */ typedef NS_ENUM(NSInteger, YRHttpResponseCachePolicy) { YRHttpResponseCachePolicyNone, // 不缓存,默认 YRHttpResponseCachePolicyNormal // 普通缓存,一直保持,不删除 // YRHttpResponseCachePolicyDay, // 保存一天,过期删除 // YRHttpResponseCachePolicyWeek, // 保存一周,过期删除 // YRHttpResponseCachePolicyMonth, // 保存一个月,过期删除 // YRHttpResponseCachePolicyQuarter, // 保存一个季度,过期删除 // YRHttpResponseCachePolicyYear, // 保存一年,过期删除 }; /** * 请求类型 */ typedef NS_ENUM(NSInteger, YRHttpRequestType) { YRHttpRequestTypeGet, YRHttpRequestTypePost, YRHttpRequestTypePut, YRHttpRequestTypeDelete, YRHttpRequestTypeUpload, YRHttpRequestTypeDownload, YRHttpRequestTypeCache //没有网络请求 }; /** * 请求响应结果,成功和失败 */ typedef void (^YRHttpCompletion) (YRHttpResponse *response); /** * 上传进度 */ typedef void (^YRHttpUploadProgress)(NSProgress *uploadProgress); /** * 上传进度 */ typedef void (^YRHttpDownloadProgress)(NSProgress *downloadProgress); /** * 配置信息协议,业务方必须实现该协议 */ @protocol YRNetworkConfiguration <NSObject> @optional /** * 设置基础URL */ - (NSURL *)baseUrl; /** * 设置基础http header头,在 YRNetworkManager 初始化时设置的固定值 */ - (NSDictionary *)httpHeaderFields; /** * 设置http header头,在请求接口数据时设置,例如,接口加密等动态计算的参数 */ - (NSDictionary *)httpHeaderFields:(NSDictionary *) params; /** * 设置http header头,在请求接口数据时设置,例如,接口加密等动态计算的参数 */ - (NSDictionary *)httpHeaderFields:(NSDictionary *) params url:(NSString *) url; /** * 处理请求数据,可进行解析处理,返回解析的后的数据 */ - (id)response:(YRHttpResponse *) response completion:(YRHttpCompletion) completion; /** * 网络异常 */ - (void)networkError:(YRHttpResponse *) response; /** * 用户缓存标识符,如果业务端需要缓存不同用户的数据,需要设置一个标识符,每个用户必须不一样 */ - (NSString *)userIdentifier; @end
import { Pipe, PipeTransform } from '@angular/core'; import { Livro } from './livro'; @Pipe({ name: 'filtroPesquisa', pure: false }) export class FiltroPesquisaPipe implements PipeTransform { transform(listaLivros: Livro[], nomePesq: string): Livro [] { return listaLivros.filter ( (livro:Livro) => { return livro.titulo?.toLowerCase().includes(nomePesq.toLowerCase()) }) } }
package config import ( "github.com/reubenmiller/go-c8y-cli/v2/pkg/flags" "github.com/reubenmiller/go-c8y-cli/v2/pkg/jsonfilter" ) // CommonCommandOptions control the handling of the response which are available for all commands // which interact with the server type CommonCommandOptions struct { ConfirmText string OutputFile string OutputFileRaw string OutputTemplate string CommandFlags map[string]string Filters *jsonfilter.JSONFilters ResultProperty string IncludeAll bool WithTotalPages bool WithTotalElements bool PageSize int CurrentPage int64 TotalPages int64 } // AddQueryParameters adds the common query parameters to the given query values func (options CommonCommandOptions) AddQueryParameters(query *flags.QueryTemplate) { if query == nil { return } if options.CurrentPage > 0 { query.SetVariable(flags.FlagCurrentPage, options.CurrentPage) } if options.PageSize > 0 { query.SetVariable(flags.FlagPageSize, options.PageSize) } if options.WithTotalPages { query.SetVariable(flags.FlagWithTotalPages, "true") } if options.WithTotalElements { query.SetVariable(flags.FlagWithTotalElements, "true") } } func shouldIgnoreValue(v string) bool { return v == "" || v == "-" } func (options CommonCommandOptions) AddQueryParametersWithMapping(query *flags.QueryTemplate, aliases map[string]string) { if query == nil { return } if options.CurrentPage > 0 { if alias, ok := aliases[flags.FlagCurrentPage]; ok { if !shouldIgnoreValue(alias) { query.SetVariable(alias, options.CurrentPage) } } else { query.SetVariable(flags.FlagCurrentPage, options.CurrentPage) } } if options.PageSize > 0 { if alias, ok := aliases[flags.FlagPageSize]; ok { if !shouldIgnoreValue(alias) { query.SetVariable(alias, options.PageSize) } } else { query.SetVariable(flags.FlagPageSize, options.PageSize) } } if options.WithTotalPages { if alias, ok := aliases[flags.FlagWithTotalPages]; ok { if !shouldIgnoreValue(alias) { query.SetVariable(alias, "true") } } else { query.SetVariable(flags.FlagWithTotalPages, "true") } } if options.WithTotalElements { if alias, ok := aliases[flags.FlagWithTotalElements]; ok { if !shouldIgnoreValue(alias) { query.SetVariable(alias, "true") } } else { query.SetVariable(flags.FlagWithTotalElements, "true") } } }
import * as React from "react"; import AppBar from "@mui/material/AppBar"; import Box from "@mui/material/Box"; import Toolbar from "@mui/material/Toolbar"; import Typography from "@mui/material/Typography"; import IconButton from "@mui/material/IconButton"; import AccountCircle from "@mui/icons-material/AccountCircle"; import Menu from "@mui/material/Menu"; import Cookies from "js-cookie"; import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined"; import { Link } from "react-router-dom"; import { useNavigate } from "react-router-dom"; import MenuItem from "@mui/material/MenuItem"; import NotificationsNoneOutlinedIcon from "@mui/icons-material/NotificationsNoneOutlined"; export default function MenuAppBar() { const [auth, setAuth] = React.useState(true); const [anchorEl, setAnchorEl] = React.useState(null); const navigate = useNavigate(); const handleChange = (event) => { setAuth(event.target.checked); }; const handleMenu = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const logout = () => { Cookies.remove("token"); Cookies.remove("user"); Cookies.remove("role"); localStorage.removeItem("PROFILE_DATA"); window.location.href = "/"; }; function renderBackButton() { if (location.pathname === "/" || location.pathname === "/home/home/user") { // If the current route is either '/' or '/home/user', don't render the back button return null; } else { // Otherwise, render a back button that navigates to the previous page return ( // <Link to="#" > <HomeOutlinedIcon onClick={() => navigate("../../home/home/user")} /> // </Link> ); } } return ( <Box sx={{ flexGrow: 1 }}> <AppBar position="static" style={{ display: "flex", justifyContent: "center", background: "white", height: "70px", }} > <Toolbar> <IconButton size="large" edge="start" color="black" aria-label="menu" sx={{ mr: 1 }} > {renderBackButton()} </IconButton> <Typography variant="h6" component="div" sx={{ flexGrow: 1, color: "black" }} > Sx Bank </Typography> {auth && ( <div> {Cookies.get("role") === "admin" && ( <IconButton size="large" aria-label="account of current user" aria-controls="menu-appbar" aria-haspopup="true" onClick={handleMenu} color="black" > <NotificationsNoneOutlinedIcon onClick={() => navigate("../../home/admin/notification")} /> </IconButton> )} <IconButton size="large" aria-label="account of current user" aria-controls="menu-appbar" aria-haspopup="true" onClick={handleMenu} color="black" > <AccountCircle /> </IconButton> <Menu id="menu-appbar" anchorEl={anchorEl} anchorOrigin={{ vertical: "top", horizontal: "right", }} keepMounted transformOrigin={{ vertical: "top", horizontal: "right", }} open={Boolean(anchorEl)} onClose={handleClose} > <MenuItem onClick={() => navigate("../../home/profile")}> Profile </MenuItem> {Cookies.get("role") === "admin" && ( <> <MenuItem onClick={() => navigate("../../home/home/admin")}> Admin Panel </MenuItem> <MenuItem onClick={() => navigate("../../home/admin/newUser")}> New User </MenuItem> </> )} <MenuItem onClick={() => navigate("/settings")}> Setting </MenuItem> <MenuItem onClick={logout}>Logout</MenuItem> </Menu> </div> )} </Toolbar> </AppBar> </Box> ); }
import { i18n } from '@/i18n-config'; import { Metadata } from 'next'; import { calSans, inter } from '../fonts'; import og from '@/public/og.png'; import '../../globals.css'; export const metadata: Metadata = { metadataBase: new URL('https://martincamer.vercel.app'), title: 'Martín Camer | Portfolio', description: 'Desarrollador Frontend con conocimientos Full-Stack', openGraph: { title: 'Martín Camer | Portfolio', description: 'Desarrollador Frontend con conocimientos Full-Stack', url: 'https://martincamer.vercel.app', siteName: 'martincamer.vercel.app', type: 'website', images: [ { url: og.src, width: 1920, height: 1080, }, ], }, robots: { index: true, follow: true, nocache: true, googleBot: { index: true, follow: false, noimageindex: true, 'max-video-preview': -1, 'max-image-preview': 'large', 'max-snippet': -1, }, }, twitter: { title: 'Martín Camer', card: 'summary_large_image', }, alternates: { canonical: 'https://martincamer.vercel.app', languages: { es: 'https://martincamer.vercel.app/es', en: 'https://martincamer.vercel.app/en', }, }, category: 'programming', }; export async function generateStaticParams() { return i18n.locales.map(locale => ({ lang: locale })); } export default function RootLayout({ children, params, }: { children: React.ReactNode; params: { lang: string }; }) { return ( <html lang={params.lang} className={[inter.variable, calSans.variable].join(' ')} > <body className={inter.className}>{children}</body> </html> ); }
import React from 'react' import Link from "next/link" import Image from "next/image" import styles from "./page.module.css" async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/posts') if (!res.ok) { throw new Error('Failed to fetch data') } return res.json() } export const Blog = async () => { const data = await getData(); return ( <div className={styles.mainContainer} > {data.map((item) => ( <Link passHref href={`\/blog/${item.id}`} className={styles.container} key={item.id}> <div className={styles.imageContainer}> <Image src="https://code.org/images/fill-480x360/tutorials/hoc2022/dance-party-2022.jpg" alt="" width={100} height={100} className={styles.image} /> </div> <div className={styles.content}> <h1 className={styles.title}>{item.title}</h1> <p className={styles.desc}>{item.desc}</p> </div> </Link> ))}; </div> );} export default Blog;
import React, { useEffect, useRef } from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faAngleDown } from '@fortawesome/free-solid-svg-icons' import faqs from '../utils/faqs.json' import Aos from 'aos' import 'aos/dist/aos.css' function Faq() { const MoreOrLess = <FontAwesomeIcon icon={faAngleDown} /> function showorHide(e) { var par = e.target.nextElementSibling if (par === null) { e.preventDefault() } else { par.classList.toggle('h-0') } } useEffect(() => { Aos.init() }, []) return ( <div className='my-10 text-slate-700'> <div > <h1 className='text-2xl md:text-3xl font-semibold text-center pt-10'>Frequently Asked Questions</h1> <p className='text-center text-lg my-2 md:my-5'> Find answers to commonly asked questions </p> <ul data-aos="fade-up" data-aos-duration="1500" className='my-10'> { faqs.map((faq, index) => ( <li key={index} className='border-b-2 hover:border-purple-500'> <div onClick={showorHide} className='flex justify-between py-4 text-black cursor-pointer'> <h1 className="font-bold text-lg "> {faq.question} </h1> <button className='cursor-pointer' disabled>{MoreOrLess}</button> </div> <p className='my-2 text-lg overflow-y-auto ease-in h-0 duration-300'> {faq.answer} </p> </li> )) } </ul> </div> </div > ) } export default Faq
# WebGL 图像处理 Web 前端可以利用 Canvas API 和 WebGL 这两种技术实现在浏览器本地的图像处理。Canvas API 是最直观且方便的图像处理方式,但缺点是如果图片的像素数过高,逐像素的处理速度就会很慢,毕竟 JavaScript 这门语言的执行效率摆在这里,肯定不如更贴近底层的诸如 C++ 这种语言跑得快(Python 也是解释型语言,虽然没试过,但 Python 估计要更快一点)。 WebGL 为 Web 端的图像处理提供了弯道超车的机会,作为 OpenGL 的子集,通过借助 GPU 硬件加速,WebGL 理论上可以得到比使用 Canvas API 快得多的处理速度。我的本科毕业论文基于的一个重要技术点就是这个,虽然对于图形学开发者来说,这种处理没比 Hello World 难多少,但对我自己来说还算有点说头吧。 ## 原理 WebGL 在向一个二维的平面上绘制纹理的时候主要会经历如图所示的以下步骤: ![WebGL 绘制纹理的过程](https://raw.githubusercontent.com/banqinghe/blog/main/images/webgl-image-processing/webgl-process.png) 对于一张矩形的图片来说,要将其显示到 WebGL 的画布上主要是经过两步的处理: 1. 利用顶点着色器将图片的四个顶点和画布的四个顶点联系起来 2. 利用片元着色器逐像素地对图像进行绘制操作 我们要处理的图像都是矩形的图像,所以顶点着色器这部分对于任何一种图像处理方式来说,都无需变化,毕竟只是简单地绑定图像顶点而已。图像处理算法实现的部分则是实现在片元着色器当中。 图形学中的“片元”这个概念,其实就是图片的像素,片元着色器会逐片元执行,也就是说,这套逻辑会自动对图片的每个像素执行一遍,这不就是一个拥有 GPU 加速的巨大 for 循环吗? 因此只需要在片元着色器里写好每个像素需要执行的逻辑,就可以愉快地完成图像处理操作了。例如,如果要进行一个最简单的反色操作,只需要在片元着色器代码中这样写: ``` precision mediump float; uniform sampler2D u_Sampler; varying vec2 v_TexCoord; void main() { vec4 sample = texture2D(u_Sampler, v_TexCoord); gl_FragColor = vec4(1.0 - sample.r, 1.0 - sample.g, 1.0 - sample.b, sample.a); } ``` 这玩意儿的语法类似 C 语言,逻辑编写上没有什么困难的地方。用 `texture2D()` 获取图片原始像素颜色数据,为 `gl_FragColor` 赋值新的处理后颜色数即可。 GLSL 代码里可以 if、while、for、根据相对位置获取周边像素的信息,有了这些实现各种图像处理算法基本上是水到渠成的。 ## 实现 WebGL 比较费劲的操作是初始化,编译、链接着色器程序,绑定顶点这些操作都要纯手工打造,还是比较费劲的,我感觉这些繁琐的步骤也是一个劝退因素吧😵‍💫。每个着色器程序在编译和链接完成之后,会成为一个可以被 WebGL Context 利用 `useProgram()` 方法选择调用的 `WebGLProgram` 对象,这样的一个很大的好处是,所有的程序在程序刚刚初始化的时候就可以准备完毕,如果使用过程中需要切换图像处理算法,只需要直接调用即可,而不是调用一次编译一次。 每个图像处理算法可以写成一个单独的模块,由一个会被外部调用的 js 文件和算法实现的片元着色器代码文件实现。最开始顶点位置绑定的操作只需要执行一次,所以这里可以分离出一个单纯进行图像渲染的模块,而别的模块则进行不同的图像处理。 `<canvas>` 元素的 `width` 和 `height` 设置了画布的大小(在这里就是和图像宽高完全一致),而 CSS 样式则可以进一步在这个尺寸上进行拉伸。如果一张图片尺寸大到浏览器视口显示不完全,我们依然可以使用 CSS 减小其显示大小,而不破坏在画布上渲染的精度。 ## 我遇到的问题 虽然原理看起来挺简单,但是我在构建整个应用的时候还是遇到了挺多问题的。 ### 画布内容转化为图像 一开始我发现 WebGL 的画布保存为图片之后就是一片黑,后来发现源头是在 `getContext` 的时候需要传递 `preserveDrawingBuffer` 这个参数为 `true` 才可以顺利保存。此参数默认值为 `false`,效果是会自动 clear 整个画布。 ### 转化为图像速度很慢 我写的应用里有 WebGL 和 Canvas 两种处理方式相互转换的需求,在发生这种模式转换的时候,由于需要新的 context,所以需要保存当前图像并且渲染到新的 `<canvas>` 上去。转换的过程很慢,看了火焰图大概了解了速度是被 `<canvas> -> 图片 URL` 这个过程拖慢的。 一开始我使用的转化图像的方式是 `canvas.toDataURL()`,方法,结果慢得离谱。后来使用更先进的 `toBlob()` 方法,转化速度有所提升,但是图像较大时依然卡顿比较明显。 然后……过了挺久之后,我才看文档发现 `<canvas>` 元素之间传递 canvas DOM 对象也能实现图像的传递,根本不需要转化图片这个过程💢 > `drawImage()` 接受 `HTMLCanvasElement` 作为参数(Canvas) > > `texImage2D()` 接受 `HTMLCanvasElement` 作为参数(WebGL) ## 执行效率 虽然理论上 WebGL 的处理速度可以完爆使用 JavaScript 计算的 Canvas API,但是我测试的时候发现,对于一些较小的图片,Canvas API 执行的会更快,这应该是由于 WebGL 需要一定的启动时间导致的。另外,由于 V8 引擎有 JIT 的机制,如果多次利用 Canvas API 执行相同的操作,执行速度会越来越快,最终稳定在一个较小的值,WebGL 则没有这一特点。 这里放一个不权威也不负责的测试结果: ![WebGL 和 Canvas 处理速度同一张图片10次速度对比](https://raw.githubusercontent.com/banqinghe/blog/main/images/webgl-image-processing/duration.png) 其实我感觉 WebGL 处理速度还是太慢了,按理这么底层的技术处理起来应该很快啊,可是使用起来老是卡顿明显。为啥手机上的照片编辑就跑的这么丝滑? ## 应用 毕设项目是这个:[web-image-processing](https://github.com/banqinghe/web-image-processing),后来还想重构一下,但是写了两天之后又搁置了(懒),不知道啥时候还能再捡起来。 后来因为最近老是要搞电子签名这种东西,又做了一个原理一模一样,但是只是用来进行二值化的东西 [thresholding](https://github.com/banqinghe/thresholding),这个 repo 代码质量能稍微强点(我应该是比几个月之前有所进步了)。
import _ from 'lodash'; import { GetServerSidePropsContext } from 'next'; import { useSession } from 'next-auth/react'; import { getPortfolioDetail } from '../../../gql'; import PortfolioForm from '../../../components/forms/PortfolioForm'; import CMSPageTemplate from '../../../components/page-templates/CMSPageTemplate'; import PageTitle from '../../../components/page-components/PageTitle'; import usePortfolioDetail from '../../../hooks/usePortfolioDetail'; interface Props { slug: string; initialData: any; } const PortfolioPage = ({ slug, initialData }: Props) => { const { data: session } = useSession(); const token = _.get(session, 'token') || ''; const { data: projectData } = usePortfolioDetail({ slug, initialData, token }); return ( <CMSPageTemplate> <PageTitle title='Edit Shipped Project' /> <PortfolioForm isEditable slug={slug} initialData={projectData} /> </CMSPageTemplate> ); }; // export async function getStaticPaths() { // const portfolios = await getPortfolioList(); // const paths = portfolios.map((portfolio: any) => ({ // params: { project: portfolio.slug }, // })); // return { // paths, // fallback: false, // }; // } export const getServerSideProps = async (context: GetServerSidePropsContext) => { let slug = _.get(context, 'params.project'); if (_.isArray(slug)) slug = _.first(slug); if (!slug) { return { props: {}, }; } const result = await getPortfolioDetail(slug); return { props: { slug, initialData: result || null, }, }; }; export default PortfolioPage;
import math from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def calc_perimeter(self) -> float: pass @abstractmethod def calc_area(self) -> float: pass class Rectangle(Shape): def __init__(self, a: int, b: int): self.length = a self.width = b def calc_perimeter(self) -> float: return 2 * (self.length + self.width) def calc_area(self) -> float: return self.length * self.width # I know the UML diagram inherits from Shape directly, but this is nicer. class Square(Rectangle): def __init__(self, a: int): super().__init__(a, a) class RightAngledTriangle(Shape): def __init__(self, height: int, base: int): self.height = height self.base = base def calc_perimeter(self) -> float: hypotenuse_squared = self.height ** 2 + self.base ** 2 hypotenuse = math.sqrt(hypotenuse_squared) return self.base + self.height + hypotenuse def calc_area(self) -> float: return (self.base * self.height) / 2
"use client"; import Link from "next/link"; import React, { useState } from "react"; import NavLink from "./NavLink"; import MenuOverlay from "./MenuOverlay"; import { Bars3Icon, XMarkIcon } from "@heroicons/react/24/solid"; const navLinks = [ { title: "About", path: "#about", }, { title: "Projects", path: "#projects", }, { title: "Contact", path: "#contact", }, ]; const Navbar = () => { const [navbarOpen, setNavbarOpen] = useState(false); return ( <nav className="fixed mx-auto border border-[#33353F] top-0 left-0 right-0 z-10 bg-[#121212] bg-opacity-100"> <div className="flex container lg:py-4 flex-wrap items-center justify-between mx-auto px-4 py-2"> <Link href={"/"} className="text-2xl md:text-5xl text-white font-semibold" style={{ textDecoration: 'none', /* Remove underline */ fontFamily: 'Arial, sans-serif', /* Change font */ letterSpacing: '1px', /* Adjust letter spacing */ textShadow: '2px 2px 4px rgba(0, 0, 0, 0.4)', /* Add text shadow */ transition: 'transform 0.3s ease-in-out', /* Add transition effect */ display: 'inline-block', /* Display as block element */ border: '2px solid #9C27B0', /* Add border */ padding: '10px 20px', /* Add padding */ borderRadius: '5px', /* Add border radius */ }}> Jenish Maru </Link> {/* <Link href={"/"} className="text-2xl md:text-5xl text-white font-semibold"> LOGO </Link> */} <div className="mobile-menu block md:hidden"> {!navbarOpen ? ( <button onClick={() => setNavbarOpen(true)} className="flex items-center px-3 py-2 border rounded border-slate-200 text-slate-200 hover:text-white hover:border-white"> <Bars3Icon className="h-5 w-5" /> </button> ) : ( <button onClick={() => setNavbarOpen(false)} className="flex items-center px-3 py-2 border rounded border-slate-200 text-slate-200 hover:text-white hover:border-white"> <XMarkIcon className="h-5 w-5" /> </button> )} </div> <div className="menu hidden md:block md:w-auto" id="navbar"> <ul className="flex p-4 md:p-0 md:flex-row md:space-x-8 mt-0"> {navLinks.map((link, index) => ( <li key={index}> <NavLink href={link.path} title={link.title} /> </li> ))} </ul> </div> </div> {navbarOpen ? <MenuOverlay links={navLinks} /> : null} </nav> ); }; export default Navbar;
#----------------------------------------------------------# # Script to download and view data from GEO database # ---- #----------------------------------------------------------# # Install packages ---- if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") if (!requireNamespace("GEOquery", quietly = TRUE)) BiocManager::install("GEOquery") if (!requireNamespace("car", quietly = TRUE)) install.packages("car") # Load packages ---- library(GEOquery) library(car) # Web to search data: NCBI-GEO ---- browseURL("https://www.ncbi.nlm.nih.gov/sites/GDSbrowser") # Choose a dataset and copy the code GDSXXXX # Inspect samples by clicking on "Sample subsets" # Download, manipulate and save the data ---- code <- "GDS1402" gds <- getGEO(code) str(gds) # observe the content of each slot ## Get the expression matrix from the corresponding slot ---- df <- gds@dataTable@table rownames(df) <- df[,"ID_REF"] # data frame with probes and genes summary(df) df.expr <- na.omit(df)[,c(-1,-2)] # only probes and samples ## Logarithmic scale if necessary ---- ifelse(min(df.expr) <= 0 | max(df.expr) < 20, df.expr <- df.expr, df.expr <- log2(df.expr)) summary(df.expr) ## Save the expression matrix ---- write.table(df.expr,file = paste("expression_data_", code, ".txt", sep = '')) ## Samples subsets ---- names(gds@dataTable@columns) factor <- "cell.type" # change to the desired column groups <- gds@dataTable@columns[,factor]; groups # Data visualization ---- ## Check if they are normalized with boxplot ---- col <- palette(c("blue","red","green","yellow","grey","purple")) title <- paste("Boxplots from the dataset",code,sep = ' ') layout(matrix(c(1,2), nrow = 1), width = c(5,1)) par(mar = c(5,5,4,1)) boxplot(df.expr, palette = col, boxwex = 0.7, notch = T, main = title, las = 2, col = as.factor(groups), outline = F, cex.axis = 0.7) par(mar = c(4,0,4,0)) plot(c(0,1), type = "n", axes = F, xlab = "", ylab = "") legend("center",legend = levels(groups), fill = col, cex = 0.6, title = factor, bty = "n") layout(matrix(1)) ## PCA with 2 components for samples ---- pca <- prcomp(t(df.expr), scale = T, rank = 2) summary(pca) plot(pca) title2 <- paste("PCA for samples of dataset", code, sep = ' ') plot(pca$x, col = groups, main = title2) legend("topright",legend = levels(groups), col = col, cex = 0.6, pch = 1) ## Expression profile of genes chosen by the user ---- sel <- 1:5 # or other selection of rows col2 <- rainbow(length(sel)) layout(matrix(c(1,2), nrow = 1), width = c(5,1)) par(mar = c(5,5,4,1)) matplot(x = 1:length(groups), y = t(df.expr[sel, ]), type = "l", col = col2, lty = 1, main = paste("Expression profile of the",length(sel),"genes (probes) chosen"), xlab = NA, ylab = "Intensity", xaxt = "n") Map(axis, side = 1, at = 1:dim(df.expr)[2], col.axis = groups, labels = colnames(df.expr), lwd = 0, las = 2, cex.axis = 0.7) axis(1, at = 1:dim(df.expr)[2], labels = FALSE) par(mar = c(4,0,4,0)) plot(c(0,1), type = "n", axes = F, xlab = "", ylab = "") legend("center", title = "Gen/Probe", colnames(t(df.expr[sel, ])), col = col2, cex = 0.5, fill = col2, bty = "n") layout(matrix(1)) ## Heatmap with 1000 genes (probes) ---- k <- ifelse(dim(df.expr)[1] >= 1000, 1000, dim(df.expr)[1]); k heatmap(as.matrix(df.expr[1:k,]), Colv = NA, revC = T, ColSideColors = as.character(as.numeric(groups)))
// Paginación de productos let page = 1; // Cantidad de productos let productsCount = 0; // Obtener el formulario de agregar producto const form = document.getElementById("add-product-form"); form.addEventListener("submit", handleSubmit); // Función para manejar el envío del formulario de actualizar producto async function handleUpdateProduct( id, title, description, code, price, stock, category, thumbnail ) { try { if ( !id || !title || !description || !code || !price || !stock || !category ) { return Swal.fire({ icon: "error", title: "Lo siento...", text: "Todos los campos son necesarios!", focusConfirm: true, showClass: { popup: "animate__animated animate__zoomIn", }, }); } else { const product = { title: title, description: description, code: code, price: price, stock: stock, category: category, thumbnail: thumbnail === "" ? { img1: "https://freezedepot.com/wp-content/uploads/2023/05/producto-sin-imagen.png", } : thumbnail.value, }; const response = await fetch( `http://localhost:8080/api/realTimeProducts/${id}`, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("token")}`, }, body: JSON.stringify(product), } ); const result = await response.json(); if (!result.message === "Producto actualizado con éxito") { return Swal.fire({ icon: "error", title: "Oops...", text: "Algo salió mal! Vuelve a intentarlo", showConfirmButton: true, confirmButtonText: "Aceptar", showClass: { popup: "animate__animated animate__zoomIn", }, }); } Swal.fire({ title: "¿Estás seguro?", text: "¡No podrás revertir esto!", icon: "warning", showCancelButton: true, confirmButtonColor: "#d33", cancelButtonColor: "#3085d6", confirmButtonText: "Sí, actualizar producto!", cancelButtonText: "Cancelar", showClass: { popup: "animate__animated animate__zoomIn", }, }).then((result) => { if (result.isConfirmed) { Swal.fire({ title: "¡Producto actualizado con éxito!", icon: "success", confirmButtonColor: "#3085d6", confirmButtonText: "Aceptar", showClass: { popup: "animate__animated animate__zoomIn", }, }).then((result) => { if (result.isConfirmed) { setTimeout(function () { window.location.reload(); }, 500); } }); } }); } } catch (error) { console.log(error); } } //Quiero que este codigo capture los datos del producto y los muestre en el formulario const getProductToUpdate = async (id) => { const updateProductForm = document.getElementById("update-product-container"); const response = await fetch( `http://localhost:8080/api/realTimeProducts/${id}`, { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("token")}`, }, } ); const result = await response.json(); const product = result.data; updateProductForm.innerHTML = ` <h3 class="text-center mt-5 mb-5 text-decoration-underline"> Actualizar producto </h3> <form action="" class="form-container" id="update-product-form"> <div class="mb-3"> <label for="title" class="form-label"> Nombre del producto: </label> <input type="text" class="form-control" id="title" value = "${product.title}" /> </div> <div class="mb-3"> <label for="description" class="form-label"> Descripción: </label> <textarea class="form-control" id="description" style="height: 80px" >${product.description}</textarea> </div> <div class="mb-3"> <label for="code" class="form-label"> Código de producto: </label> <input type="text" class="form-control" id="code" value = "${product.code}" /> </div> <div class="mb-3"> <label for="price" class="form-label"> Precio: </label> <input type="number" class="form-control" id="price" value = "${product.price}" /> </div> <div class="mb-3"> <label for="stock" class="form-label"> Stock: </label> <input type="number" class="form-control" id="stock" value = "${product.stock}" /> </div> <div class="mb-3"> <label for="category" class="form-label"> Categoría: </label> <input type="text" class="form-control" id="category" value = "${product.category}" /> </div> <div class="mb-3"> <label for="thumbnail" class="form-label"> Imagen: </label> <input type="text" class="form-control" id="thumbnail" value = "${product.thumbnail[0]["img1"]}" /> </div> <button type="submit" class="btn btn-primary" id="submit" > Actualizar </button> </form> `; const updateProductData = document.getElementById("update-product-form"); updateProductData.addEventListener("submit", (e) => { e.preventDefault(); const { title, description, code, price, stock, category, thumbnail } = updateProductData.elements; handleUpdateProduct( product._id, title.value, description.value, code.value, price.value, stock.value, category.value, thumbnail.value ); }); window.scrollTo(0, 0); }; // Función para manejar el envío del formulario async function handleSubmit(e) { e.preventDefault(); const { title, description, code, price, stock, category, thumbnail } = form.elements; if ( !title.value || !description.value || !code.value || !price.value || !stock.value || !category.value ) { return Swal.fire({ icon: "error", title: "Lo siento...", text: "Todos los campos son necesarios!", focusConfirm: true, showClass: { popup: "animate__animated animate__zoomIn", }, }); } else { const product = { title: title.value, description: description.value, code: code.value, price: price.value, stock: stock.value, category: category.value, thumbnail: thumbnail.value === "" ? { img1: "https://freezedepot.com/wp-content/uploads/2023/05/producto-sin-imagen.png", } : thumbnail.value, }; const response = await fetch("http://localhost:8080/api/realTimeProducts", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("token")}`, }, body: JSON.stringify(product), }); if (!response.ok) { return Swal.fire({ icon: "error", title: "Oops...", text: "Algo salió mal! Vuelve a intentarlo", showConfirmButton: true, confirmButtonText: "Aceptar", showClass: { popup: "animate__animated animate__zoomIn", }, }); } else { Swal.fire({ icon: "success", title: "Producto agregado con exito!", showConfirmButton: true, showClass: { popup: "animate__animated animate__zoomIn", }, }); } } // Limpiar todos los campos del formulario for (let i = 0; i < form.elements.length; i++) { form.elements[i].value = ""; } updateProductList(); } const getProducts = async () => { try { const result = await fetch("http://localhost:8080/api/realTimeProducts", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("token")}`, }, }); if (result.status === 404) { return Swal.fire({ icon: "error", title: "Oops...", text: "Algo salió mal! Vuelve a intentarlo", showConfirmButton: true, confirmButtonText: "Aceptar", }); } const products = await result.json(); return products; } catch (error) { console.log(error); } }; // Función que obtiene la cantidad de productos const getProductsData = async () => { const data = await getProducts(); const productsData = Math.ceil(data.data.length / 10); return productsData; }; getProductsData().then((data) => { productsCount = data; }); // Función para agregar productos const addProductBtn = () => { const btnAddProduct = document.getElementById("add-product-btn"); if (page === productsCount) { btnAddProduct.classList.add("disabled"); } else { page++; } updateProductList(); }; // Función que pagina los productos const paginatedProducts = async (page) => { const productsData = await getProducts(); const orderedProducts = productsData.data.reverse(); const products = orderedProducts.slice(0, page * 10); return products; }; // Función para actualizar la lista de productos async function updateProductList() { const productList = document.getElementById("products-list"); productList.innerHTML = ""; try { const products = await paginatedProducts(page); const container = document.createElement("div"); products.forEach((product) => { //Capturar la url de la imagen const imageUrl = product.thumbnail[0]["img1"]; const item = document.createElement("div"); item.classList.add("list-group-item"); item.innerHTML = ` <div class="d-flex w-100 justify-content-between flex-column"> <h2 class="mb-1 subtitle">${product.title}</h2> <p class="mb-1"><strong>Descripción:</strong> ${product.description}</p> <p class="mb-1"><strong>Codigo:</strong> ${product.code}</p> <p class="mb-1"><strong>Precio:</strong> ${product.price}</p> <p class="mb-1"><strong>Status:</strong> ${product.status}</p> <p class="mb-1"><strong>Stock:</strong> ${product.stock}</p> <p class="mb-1"><strong>Categoria:</strong> ${product.category}</p> </div> <img src="${imageUrl}" alt="img" width="150" class="thumbnail position-absolute me-5 mt-5 end-0 top-0"> <button type="button" class="btn btn-primary update-product-btn" onclick="getProductToUpdate('${product._id}')">Actualizar</button> <button type="button" class="btn btn-primary delete-product-btn">Eliminar</button> `; const btnEliminar = item.querySelector(".delete-product-btn"); btnEliminar.addEventListener("click", () => { eliminarProducto(product._id); }); container.appendChild(item); }); productList.appendChild(container); } catch (error) { console.log(error); } } updateProductList(); // Eliminar un producto de la lista de productos function eliminarProducto(id) { Swal.fire({ title: "¿Estás seguro?", text: "No podrás revertir esta acción!", icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", showClass: { popup: "animate__animated animate__zoomIn", }, }).then(async (result) => { if (result.isConfirmed) { const response = await fetch( `http://localhost:8080/api/realTimeProducts/${id}`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("token")}`, }, } ); if (!response.ok) { return Swal.fire({ icon: "error", title: "Oops...", text: "Algo salió mal! Vuelve a intentarlo", showConfirmButton: true, confirmButtonText: "Aceptar", showClass: { popup: "animate__animated animate__zoomIn", }, }); } updateProductList(); Swal.fire({ icon: "success", title: "Producto eliminado con exito!", showConfirmButton: true, showClass: { popup: "animate__animated animate__zoomIn", }, }); } }); }
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** @fileoverview Test suite for app-manageemnt-permission-item. */ import 'chrome://os-settings/lazy_load.js'; import {AppManagementPermissionItemElement} from 'chrome://os-settings/lazy_load.js'; import {AppManagementStore, updateSelectedAppId} from 'chrome://os-settings/os_settings.js'; import {App, Permission, PermissionType, TriState} from 'chrome://resources/cr_components/app_management/app_management.mojom-webui.js'; import {AppManagementUserAction} from 'chrome://resources/cr_components/app_management/constants.js'; import {PermissionTypeIndex} from 'chrome://resources/cr_components/app_management/permission_constants.js'; import {createTriStatePermission} from 'chrome://resources/cr_components/app_management/permission_util.js'; import {getPermissionValueBool} from 'chrome://resources/cr_components/app_management/util.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals, assertFalse, assertNull, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; import {FakePageHandler} from '../../app_management/fake_page_handler.js'; import {fakeComponentBrowserProxy, replaceStore, setupFakeHandler} from '../../app_management/test_util.js'; import {clearBody} from '../../utils.js'; type PermissionMap = Partial<Record<PermissionType, Permission>>; suite('AppManagementPermissionItemTest', function() { let permissionItem: AppManagementPermissionItemElement; let fakeHandler: FakePageHandler; const app_id: string = 'app_id'; const permissionType: PermissionTypeIndex = 'kLocation'; function createPermissionItem(): void { clearBody(); document.body.innerHTML = window.trustedTypes!.emptyHTML; permissionItem = document.createElement('app-management-permission-item'); permissionItem.app = getApp(); permissionItem.permissionType = permissionType; document.body.appendChild(permissionItem); flush(); } setup(async function() { const permissions: PermissionMap = {}; permissions[PermissionType[permissionType]] = createTriStatePermission( PermissionType[permissionType], TriState.kAsk, false); fakeHandler = setupFakeHandler(); replaceStore(); await fakeHandler.addApp(app_id, {permissions: permissions}); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app_id)); createPermissionItem(); }); // Fetches the app state from the `AppManagementStore`. function getApp(): App { const app = AppManagementStore.getInstance().data.apps[app_id]; assertTrue(!!app); return app; } test('Toggle permission', async function() { assertFalse(getPermissionValueBool( permissionItem.app, permissionItem.permissionType)); permissionItem.click(); const data = await fakeHandler.whenCalled('setPermission'); assertEquals(data[1].value.tristateValue, TriState.kAllow); assertTrue(!!fakeComponentBrowserProxy); const metricData = await fakeComponentBrowserProxy.whenCalled('recordEnumerationValue'); assertEquals(metricData[1], AppManagementUserAction.LOCATION_TURNED_ON); }); test('Permission item has no description', async function() { assertNull(permissionItem.shadowRoot!.querySelector<HTMLElement>( '#permissionDescription')); }); suite('Permission item with description', () => { setup(() => { loadTimeData.overrideValues({'privacyHubAppPermissionsV2Enabled': true}); createPermissionItem(); }); teardown(() => { loadTimeData.overrideValues({'privacyHubAppPermissionsV2Enabled': false}); }); function getPermissionDescriptionString(): string { return permissionItem.shadowRoot! .querySelector<HTMLElement>( '#permissionDescription')!.innerText.trim(); } async function togglePermission(): Promise<void> { permissionItem.click(); await flushTasks(); permissionItem.set('app', getApp()); } test('Toggle permission', async () => { assertEquals( loadTimeData.getString('appManagementPermissionAsk'), getPermissionDescriptionString()); await togglePermission(); assertEquals( loadTimeData.getString('appManagementPermissionAllowed'), getPermissionDescriptionString()); await togglePermission(); assertEquals( loadTimeData.getString('appManagementPermissionDenied'), getPermissionDescriptionString()); }); }); });
#include<iostream> using namespace std; class demo{ string s; public: void getdata(){ cout<<"Enter string:"; cin>>s; } void putdata(){ cout<<s; } /*cc = aa + bb; cc,aa,bb all are objects. operator overloading operate on objects of class cc -> return type aa -> reference of first object of class demo which works with + -> operator over loading. bb -> argument passed as a object in operator overloading. */ demo operator+(demo bb){//demo itself is aa object and bb is argument in operator overloading demo cc;//return type cc.s=s+bb.s; //a is itself variable in object aa return cc; } }; int main(){ demo aa,bb,cc; aa.getdata(); bb.getdata(); cc=aa+bb;//due to operator overloading works on objects it adds the variable of both aa and bb objects. cc.putdata(); return 0; }
from pydantic import BaseModel, Field, validator, root_validator import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from enum import Enum, IntEnum from typing import Dict, List, Optional, Union from datetime import date # Aqueon Models to parameters as json file # Aqueon Model class RunModeEnum(str, Enum): """ Enum for the type of run. """ fit = "fit" class MultList(BaseModel): APIs: List[str] = Field([]) mults: List[float] = Field([]) @validator('APIs',each_item=True) def check_length(cls,v): assert len(v) == 14, 'API must be 14 characters long' return v class ReservesData(BaseModel): Reservoir: List[str] = Field(..., description='Reservoirs name') SoInitMin: List[float] = Field(..., description='Initial Oil Sat') SoInitMax: List[float] = Field(..., description='Initial Oil Sat') SgInitMin: List[float] = Field(..., description='Initial Gas Sat') SgInitMax: List[float] = Field(..., description='Initial Gas Sat') NetPay: List[float] = Field(..., description='Net Pay') @validator('SoInitMax') def check_so_min(cls,v, values): if values['SoInitMin'] >= v: raise ValueError('SoInitMin must be less than SoInitMax') return v @validator('SgInitMax') def check_sg_min(cls,v, values): if values['SgInitMin'] >= v: raise ValueError('SgInitMin must be less than SgInitMax') return v @validator('NetPay', each_item=True) def check_netpay(cls,v): assert v >= 0, 'NetPay must be greater than 0' @root_validator def check_length_fields(cls,values): list_lengths = [] for i in values: l = len(values[i]) list_lengths.append(l) assert all(i == list_lengths[0] for i in list_lengths), 'All fields must have the same length' return values class FlowUnits(BaseModel): wellGuid: List[str] = Field([]) unitName: List[str] = Field([""]) class ResBounds(BaseModel): xMin: float xMax: float yMin: float yMax: float @validator('xMax') def check_xmax_min(cls,v, values): if values['xMin'] >= v: raise ValueError('xMax must be greater than xMin') return v @validator('yMax') def check_ymax_min(cls,v, values): if values['yMin'] >= v: raise ValueError('yMax must be greater than yMin') return v class Enkf(BaseModel): fitType: int = Field(2, ge=0, le=3) qpFitMode: int = Field(0, ge=0, le=2) Nc: int = Field(20, ge=1, le=100000) Ne: int = Field(96, ge=32, le=192) NhPct: int = Field(95, ge=1, le=100) beta: float = Field(0.05, ge=0.01, le=0.1) dataType: int = Field(0, ge=0, le=1) #? Check if this is correct isIntInjW: bool = Field(True) isIntProd: bool = Field(True) prodBHPSource: int = Field(3, ge=0, le=3) isFilter: bool = Field(True) infFact : float = Field(0.05, ge=0.01, le=0.1) isPerturb: bool = Field(True) wSmooth: float = Field(0.05, ge=0.01) smoothType: int = Field(0, ge=0, le=3) minResponsivity: float = Field(0.001, gt=0) maxResponsivity: float = Field(5, gt=0) histControlMode: int = Field(0, ge=0, le=1) nBHPCont: int = Field(10, ge=10, le=10000000) nTCorr: int = Field(6, ge=1, le=60) nTCorrEnd: int = Field(2, ge=1, le=60) isPar: bool = Field(True) sd : List[List[float]] = Field([[0.15],[0.15],[0.3],[0.15],[0.4]]) startDate: date = Field(None) endDate: date = Field(None) btEndDate: date = Field(None) isDB: int = Field(1, ge=0, le=2) #? Check if this is correct fitMode: int = Field(0, ge=0, le=1) #? Check if this is correct stepOutput: int = Field(0, ge=0, le=1) #? Check if this is correct maxExtrapolate: int = Field(0, ge=0) nMovingMeanBHP: int = Field(0, ge=0) allowConversions: bool = Field(False) @validator('sd', each_item=True) def check_sd(cls,v): assert len(v) == 1, 'sd must be a list of length 1' assert v[0] > 0, 'sd must be greater than 0' assert v[0] < 1, 'sd must be less than 1' class Config: json_encoders = { date: lambda d: d.strftime('%Y-%m-%d'), bool: lambda b: int(b) } class gHKernelModel(IntEnum): each_resmap = 0 continuous_resmap = 1 class BoundaryType(IntEnum): closed = 0 edge = 1 bottom = 2 class ReserveMode(IntEnum): constant_netpay = 0 layer_netpay = 1 well_netpay = 2 class FlowUnitType(IntEnum): no_separation = 0 compartments = 1 fault_blocks = 2 custom = 3 class GsFacDeclineMode(IntEnum): linear = 1 hyperbolic = 2 class GsFacType(IntEnum): dp_lift = 3 pressure_gradient = 4 class ReservoirHorizonSource(IntEnum): constant_dip = 0 horizon_from_db = 1 class DipEffectMode(IntEnum): no_gravity = 0 gravity = 1 class ContProps(BaseModel): dt: int = Field(30, ge=30, le=150, multiple_of=30,) injWBHPCont: bool = Field(False) overrideInjWBHP: float = Field(0, ge=0) overrideProdBHP: float = Field(0, ge=0) overrideInjWMaxP: float = Field(0, ge=0) overrideInjWH: float = Field(0, ge=0) maximumProdBHP: float = Field(0, ge=0) minimumInjWBHP: float = Field(0, ge=0) minimumCompLProd: float = Field(0, ge=0) minimumCompLInjW: float = Field(0, ge=0) loadCompletions: bool = Field(False) multiplierMode: bool = Field(False) injWRateLoss: float = Field(0, ge=0, le=1) useCVSolver: bool = Field(True) useDomainsSolver: bool = Field(False) gHKernelMode: gHKernelModel = Field(gHKernelModel.each_resmap) boundaryType: BoundaryType = Field(BoundaryType.closed) reserveMode: ReserveMode = Field(ReserveMode.constant_netpay) completionMode: int = Field(2) dSol: float = Field(1500, ge=10, le=50000) lmda: float = Field(5, ge=0.1, le=100) minIter: int = Field(2, ge=2, le=10) maxIter: int = Field(10, ge=5, le=30) ATol: float = Field(1e-5, ge=1e-6, le=1e-3) convTolB: float = Field(1e-5, ge=1e-6, le=1e-2) convTolG: float = Field(1e-5, ge=1e-6, le=1e-2) convTolO: float = Field(1e-5, ge=1e-6, le=1e-2) convTolW: float = Field(1e-5, ge=1e-6, le=1e-2) timeOut: int = Field(3600, ge=120, le=6000) boundaryDistance: int = Field(3000, ge=10, le=10000) interiorPointClearanceDistance: int = Field(1, ge=1, le=1000) removeInactiveWells: bool = Field(False) minDist: int = Field(500, ge=10, le=10000) maxCondNum: int = Field(1e10, ge=1e3, le=1e15) cutEndTS: int = Field(0, ge=0) cutStartTS: int = Field(0, ge=0) dryRunSteps: int = Field(0, ge=0) flowUnitType: FlowUnitType = Field(FlowUnitType.no_separation) dSProd: float = Field(5, ge=2, le=10000) dSInjW: float = Field(5, ge=2, le=10000) debug: bool = Field(False) gsFacDeclineMode: GsFacDeclineMode = Field(GsFacDeclineMode.hyperbolic) decExponent: float = Field(0.0, ge=0.0, le=1.0) gsFacType: GsFacType = Field(GsFacType.dp_lift) krOBegDeclineMode: int = Field(2) #? Check if this is correct isSaveWksp: bool = Field(False) nIntPoints: int = Field(300, ge=50, le=500) writeState: int = Field(0) #? Check if this is correct reservoirHorizonSource: ReservoirHorizonSource = Field(ReservoirHorizonSource.constant_dip) dipEffectMode: DipEffectMode = Field(DipEffectMode.no_gravity) #? Check if this is boolean nAvgSteps: int = Field(1, ge=1, le=60) initMode: int = Field(0) explicitInjW: int = Field(0) saveMonthTable: int = Field(1) class Config: json_encoders = { bool: lambda b: int(b) } class StateBounds(BaseModel): PoMax: float = Field(7000, gt=0) PoMin: float = Field(100, gt=0) SwMax: float = Field(0.6, ge=0, lt=1) SwMin: float = Field(0.3, ge=0, lt=1) SgMax: float = Field(0.3, ge=0, lt=1) SgMin: float = Field(0.1, ge=0, lt=1) @validator('PoMin') def check_po_min(cls,v, values): if values['PoMax'] <= v: raise ValueError('PoMax must be greater than PoMin') return v @validator('SwMin') def check_sw_min(cls,v, values): if values['SwMax'] <= v: raise ValueError('SwMax must be greater than SwMin') return v @validator('SgMin') def check_sg_min(cls,v, values): if values['SgMax'] <= v: raise ValueError('SgMax must be greater than SgMin') return v class Ranges(BaseModel): PoInit: List[float] = Field([2000,4000], min_items=2, max_items=2) SwInit: List[float] = Field([0.3,0.5], min_items=2, max_items=2) SgInit: List[float] = Field([0.1,0.2], min_items=2, max_items=2) phi: List[float] = Field([0.1,0.3], min_items=2, max_items=2) K: List[float] = Field([100,400], min_items=2, max_items=2) Cr: List[float] = Field([0.000001,0.00001], min_items=2, max_items=2) WIMultInjw: List[float] = Field([0.1,0.3], min_items=2, max_items=2) alphaSw: List[float] = Field([0.00002,0.00015], min_items=2, max_items=2) dPLift: List[float] = Field([0,4], min_items=2, max_items=2) alphaDP: List[float] = Field([0.00001,0.00005], min_items=2, max_items=2) muORef: List[float] = Field([5,40], min_items=2, max_items=2) muOMin: List[float] = Field([1,2], min_items=2, max_items=2) bO: List[float] = Field([-0.001,-0.0001], min_items=2, max_items=2) muGRef: List[float] = Field([1,5], min_items=2, max_items=2) muGMin: List[float] = Field([0.1,0.2], min_items=2, max_items=2) bG: List[float] = Field([-0.001,-0.0001], min_items=2, max_items=2) krOEnd: List[float] = Field([0.3,0.7], min_items=2, max_items=2) alphaKrO: List[float] = Field([0.000005,0.00001], min_items=2, max_items=2) krGEnd: List[float] = Field([0.5,1.0], min_items=2, max_items=2) krWEnd: List[float] = Field([0.4,0.7], min_items=2, max_items=2) DSg: List[float] = Field([0.001,0.005], min_items=2, max_items=2) DSw: List[float] = Field([0.001,0.005], min_items=2, max_items=2) kvAq: List[float] = Field([0,0], min_items=2, max_items=2) qh: List[float] = Field([-1e-7,1e7], min_items=2, max_items=2) class ConstProps(BaseModel): Co: float = Field(1e-5, ge=0.0) muWRef: float = Field(1, gt=0.0) muWMin: float = Field(0.1, gt=0.0) bW: float = Field(-0.00001) Cw: float = Field(1e-5, ge=0.0) rhoO: float = Field(60, ge=0.0) rhoW: float = Field(62.4, ge=0.0) molG: float = Field(16) nG: float = Field(2,gt=0) nW: float = Field(2,gt=0) krOBeg: float = Field(0.2) Pb: float = Field(500, gt=0.0) RsoPb: float = Field(0.5, gt=0.0) BoPb: float = Field(1.0, gt=0.0) Sgc: float = Field(0.0, ge=0.0, lt=1.0) Sor: float = Field(0.2, ge=0.0, lt=1.0) SwInjW: float = Field(0.8, ge=0.0, lt=1.0) Swc: float = Field(0.25, ge=0.0, lt=1.0) TRef: float = Field(100) pRef: float = Field(14.7, ge=14.7) omega: float = Field(1) zeta: float = Field(1) gasMult: float = Field(1) NetPay: float = Field(100, gt=0.0) WOC: float = Field(0.0) GOC: float = Field(0.0) zRef: float = Field(0.0) poAq: float = Field(0.0) topDip: float = Field(0.0) topAzimuth: float = Field(0.0) topXRef: float = Field(0.0) topYRef: float = Field(0.0) topZRef: float = Field(0.0) class AqueonModel(BaseModel): caseName: str = Field(..., description="Case Name") runMode: RunModeEnum = Field(RunModeEnum.fit, description="Run Mode") companyName: str = Field(" ", description="Company Name") #? Model level integers meaning modelLevel: int = Field(1, description="Model Level") #? BadWellIndx Dict Schema badWellIndx: Dict = Field({}, description="Bad Well Indx") wellGuidList: List[List[str]] = Field(..., description="Well Guid List") multList: MultList = Field(MultList(), description="Multipliers") reservesData: Union[Dict, ReservesData] = Field({}, description="Reserves Data") flowUnit: FlowUnits = Field(FlowUnits(), description="Flow Units") isMultiReservoir: bool = Field(False, description="Is Multi Reservoir") resBnds: ResBounds = Field(ResBounds, description="Reservoir Bounds") enkf: Enkf = Field(Enkf(), description="EnKF") contProps: ContProps = Field(ContProps(), description="Continuous Properties") stateBnds: StateBounds = Field(StateBounds(), description="State Bounds") Rng: Ranges = Field(Ranges(), description="Random Number Generator") constProps: ConstProps = Field(ConstProps(), description="Constants Properties") @validator('wellGuidList', always=True, each_item=True) def check_wellis_list(cls,v): assert isinstance(v, list), "wellGuidList must be a list" assert len(v) == 3, "wellGuidList must be a list of 3 elements" assert all(isinstance(i,str) for i in v), "wellGuidList must be a list of 3 strings" lenght_chars = [10,2,2] for i,s in enumerate(v): assert len(s) == lenght_chars[i], f"wellGuidList[{i}] must be {lenght_chars[i]} characters long" return v class Config: json_encoders = { date: lambda d: d.strftime('%Y-%m-%d'), bool: lambda b: int(b) }
function fs = tz_imnbdens(img,wndlength) %TZ_IMNBDENS Total intensities between every pixel pair in an image. % FS = TZ_IMNBDENS(IMG,WNDLENGTH) returns a 4-D matrix with dimension row X col X W X W. % to access the value at (50,20), use squeeze(edgepot(50,20,:,:)) % edge potential is calculated as sum of intensities along the line between % the center nodes and the neighbor node % FS(i,j,u,v) is the total intensity between pixel IMG(i,j) and % IMG(i+u-wndlength,j+v-wndlength). The neighbor window for each pixel % is (2*wndlength+1)x(2*wndlength+1) % edgepot is a 4-D matrix with dimension row X col X W X W % See also % Copyright (C) 2006 Murphy Lab % Carnegie Mellon University % % 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. % % For additional information visit http://murphylab.web.cmu.edu or % send email to murphy@cmu.edu % 25-Oct-2005 Initial write T. Zhao % Copyright (c) Murphy Lab, Carnegie Mellon University if nargin < 2 error('Exactly 2 arguments are required') end img = double(img); wndSize = [2*wndlength+1,2*wndlength+1]; [filters,offsets]=tz_makelinefilters(wndlength); fs = zeros(size(img,1),size(img,2),wndSize(1),wndSize(2)); for k=1:length(filters) fs(:,:,offsets(k,1)+wndlength+1,offsets(k,2)+wndlength+1) = ... imfilter(img,filters{k},'same'); end
... This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. ... If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. (.require [library [lux (.except) ["$" documentation] [data [collection ["[0]" list]]]]] [\\library ["[0]" /]]) (def math (.List $.Documentation) (list ($.definition /.cos) ($.definition /.sin) ($.definition /.tan) ($.definition /.acos) ($.definition /.asin) ($.definition /.atan) ($.definition /.exp) ($.definition /.log) ($.definition /.ceil) ($.definition /.floor) ($.definition /.root_2) ($.definition /.root_3) ($.definition /.round) ($.definition /.factorial) ($.definition /.hypotenuse) ($.definition /.sinh) ($.definition /.csch) ($.definition /.cosh) ($.definition /.sech) ($.definition /.tanh) ($.definition /.coth) ($.definition /.asinh) ($.definition /.acosh) ($.definition /.atanh) ($.definition /.acoth) ($.definition /.asech) ($.definition /.acsch) ($.definition /.e "The base of the natural logarithm.") ($.definition /.pi "The ratio of a circle's circumference to its diameter.") ($.definition /.tau "The ratio of a circle's circumference to its radius.") ($.definition /.pow "" ($.example (pow param subject))) ($.definition /.atan_2 "" ($.example (atan_2 x y))) ($.definition /.log_by "" ($.example (log_by base it))) )) (`` (def .public documentation (.List $.Documentation) (list.partial ($.module /._ "") ($.definition /.positive?) ($.definition /.negative?) ($.definition /.zero?) ($.definition /.opposite) ($.definition /.abs) ($.definition /.signum) ($.definition /.nat) ($.definition /.int) ($.definition /.rev) ($.definition /.equivalence) ($.definition /.order) ($.definition /.smallest) ($.definition /.biggest) ($.definition /.addition) ($.definition /.multiplication) ($.definition /.minimum) ($.definition /.maximum) ($.definition /.number?) ($.definition /.decimal) ($.definition /.bits) ($.definition /.of_bits) ($.definition /.binary) ($.definition /.octal) ($.definition /.hex) ($.definition /.hash) ($.definition /.= "Frac(tion) equivalence." ($.example (= reference sample))) ($.definition /.< "Frac(tion) less-than." ($.example (< reference sample))) ($.definition /.<= "Frac(tion) less-than or equal." ($.example (<= reference sample))) ($.definition /.> "Frac(tion) greater-than." ($.example (> reference sample))) ($.definition /.>= "Frac(tion) greater-than or equal." ($.example (>= reference sample))) (,, (with_template [<name> <doc>] [($.definition <name> <doc>)] [/.+ "Frac(tion) addition."] [/.- "Frac(tion) substraction."] [/.* "Frac(tion) multiplication."] [/./ "Frac(tion) division."] [/.% "Frac(tion) remainder."] )) ($.definition /./% "" ($.example (/% param subject))) (,, (with_template [<name> <doc>] [($.definition <name> <doc>)] [/.min "Frac(tion) minimum."] [/.max "Frac(tion) minimum."] )) (,, (with_template [<name> <doc>] [($.definition <name> <doc>)] [/.not_a_number "Not a number."] [/.positive_infinity "Positive infinity."] [/.negative_infinity "Negative infinity."] )) ($.definition /.not_a_number? "Tests whether a frac is actually not-a-number." ($.example (not_a_number? it))) ($.definition /.approximately? "" ($.example (approximately? margin_of_error standard value))) ($.definition /.mod "" ($.example (mod divisor dividend))) ..math )))
import { Injectable, NgZone } from '@angular/core'; import { TreeGridComponent } from '@syncfusion/ej2-angular-treegrid'; import { GenericTask } from '../models/generic-task.model'; import { Row } from '../models/types'; import { GridEventService } from '../services/grid-event.service'; export const V_KEY_CODE = 86; export const MIDDLE_CELL_CLASS = 'middle-cell-selection'; export const BOTTOM_CELL_CLASS = 'bottom-cell-selection'; export const TOP_CELL_CLASS = 'top-cell-selection'; export const DEFAULT_CELL_CLASS = 'default-cell-selection'; export const SELECTION_BACKGROUND_CLASS = 'e-selectionbackground'; export const GROUP_PREFIX = 'Group_'; export const COLUMN_HEADER_TEXT_LENGTH = 20; export const CHILD_GRID_PREFIX = 'childGrid_'; export const ROW_INDEX_ATTR = 'aria-rowindex'; export const CTRL_KEY_CODE = 17; export const C_KEY_CODE = 67; export const X_KEY_CODE = 88; export const ENTER_KEY_CODE = 13; export const ESCAPE_KEY_CODE = 27; @Injectable() export class TreeGridUtilityService { constructor( private readonly ngZone: NgZone, private readonly gridEventService: GridEventService ) {} getRowIndex(grid: TreeGridComponent, taskId: string, groupId: string) { const rowSelectedData: any = grid.element.querySelector( `[data-row-id="${groupId}_ROW_${taskId}"]` ); return parseInt(rowSelectedData?.ariaRowIndex, 10); } getRow(grid: TreeGridComponent, taskId: string, groupId: string) { return grid.element.querySelector( `[data-row-id="${groupId}_ROW_${taskId}"]` ); } getTreeGridIndex(grid: TreeGridComponent, taskId: string) { const rowSelectedData = grid .getCurrentViewRecords() .find((x: any) => x.id === taskId); if (rowSelectedData) { return parseInt((rowSelectedData as any).index, 10); } return undefined; } getActualRowIndex(grid: TreeGridComponent, taskId: string) { return grid.getCurrentViewRecords().findIndex((x: any) => x.id === taskId); } toggleExpand(rowData: Row, grid: TreeGridComponent, expand: boolean) { const id = rowData.id; const index = this.getRowIndex(grid, id, rowData.groupId as string); const row = grid.getRowByIndex(index) as HTMLTableRowElement; if (!row) { return; } if (expand) { grid.expandRow(row); } else { grid.collapseRow(row); } // now update the actual object in grid-datasource const ds = grid.dataSource as GenericTask[]; const toggledRow = ds?.find((task) => task.id === rowData.id); if (toggledRow) { toggledRow.expanded = expand; } } addCustomCellClass( cells: NodeListOf<HTMLTableDataCellElement>, className: string ) { cells.forEach((cell) => cell?.classList?.add(className)); } removeHighlightedRow(rows: HTMLTableRowElement[]) { rows.forEach((row) => { const cells = row?.querySelectorAll('td'); if (cells?.length) { cells.forEach((cell) => cell?.classList?.remove( MIDDLE_CELL_CLASS, BOTTOM_CELL_CLASS, TOP_CELL_CLASS, DEFAULT_CELL_CLASS ) ); } }); } displayHighlightedRow(rows: HTMLTableRowElement[]) { rows.forEach((row) => { const cells = row?.querySelectorAll('td'); if (cells?.length) { const prev = row?.previousElementSibling; const next = row?.nextElementSibling; const isPrevRowSelected = rows.some((r) => r === prev); const isNextRowSelected = rows.some((r) => r === next); if (isPrevRowSelected && isNextRowSelected) { this.addCustomCellClass(cells, MIDDLE_CELL_CLASS); } else if (isPrevRowSelected) { this.addCustomCellClass(cells, BOTTOM_CELL_CLASS); } else if (isNextRowSelected) { this.addCustomCellClass(cells, TOP_CELL_CLASS); } else { this.addCustomCellClass(cells, DEFAULT_CELL_CLASS); } } }); } handleKeyPressed(args: any, grid: TreeGridComponent) { const keyCode = args.which || args.keyCode; // sonarignore:start const isCtrlKey = args.ctrlKey || args.metaKey ? true : keyCode === CTRL_KEY_CODE ? true : false; // sonarignore:end if (keyCode === ENTER_KEY_CODE) { // overriding default enter behaviour this.handleEnterKey(args, grid); return false; } else { return false; } } handleEnterKey(args: any, grid?: TreeGridComponent) { args.cancel = true; this.ngZone.run(() => { if (!grid) { return this.gridEventService.callGridEditSave(); } if ((grid as any).isEdit) { grid.saveCell(); } return null; }); } editColumnHeader(flag: boolean, grid: TreeGridComponent) { if (flag) { grid?.startEdit(); (grid as any).isEdit = true; } else { grid?.endEdit(); } } navigateToTask(grid: TreeGridComponent, taskId: string, rows: Row[]) { const index = rows?.findIndex((row) => row.id === taskId); if (index >= 0) { grid.selectRow(index); } } }
<template> <div id="article" class="container"> <section class="categoryList"> <div class="list"> <div class="item"> <span @click="selectChange('')" :class="category?'':'active'">全部</span> </div> <div class="item" v-for="(item,index) in categoryData" :key="index"> <span @click="selectChange(index)" :class="index===category?'active':''">{{item.name}}</span> </div> </div> </section> <section class="pageList"> <el-pagination v-cloak :page-size="page.pageSize" :pager-count="5" :total="page.total" :hide-on-single-page="true" layout="prev, pager, next" @current-change="currentChange" > </el-pagination> </section> <div class="articlelist"> <div class="item" v-for="(item,index) in list.data" :key="item.id" @click="navToDetails(item.id)"> <img :src="item.url" alt=""> <div class="textBox"> <p class="title">{{item.title}}</p> <p class="desc">{{item.desc}}</p> <div class="date"> <div> <i class="el-icon-view"></i> {{item.visits}} </div> <div> <i class="el-icon-time"></i> {{item.date}} </div> </div> </div> </div> <empty v-show="list.data.length<=0"></empty> </div> </div> </template> <script> import articleAPI from '@/api/modul/article'; import Empty from '@/components/Empty'; export default { components:{ "empty":Empty }, data(){ return{ value:'', value1:'', page:{}, list:[], categoryData:[], category:'', } }, head () { return { title:'文章 | 天小天', } }, async asyncData(context){ let page = { pageSize:5, currentPage:1, total:6, }; let listGetData = { pageSize:page.pageSize, currentPage:page.currentPage, category:'', }; let listData = await articleAPI.list(listGetData); let categoryData = await articleAPI.category({}); page.total = listData.total; return { page:page, list:listData, categoryData:categoryData, } }, methods:{ currentChange(e){ this.page.currentPage = e; this.getList(); }, selectChange(e){ this.category = e; this.page.currentPage = 1; this.page.total = 6; this.getList(); }, navToDetails(e){ this.$router.push({ path:'/article/details', query:{ id:e } }); }, async getList(){ let listPostData = { pageSize:this.page.pageSize, currentPage:this.page.currentPage, category:this.category, }; let listData = await articleAPI.list(listPostData); this.page.total = listData.total; this.list=listData; }, }, created() { }, mounted() { }, } </script> <style lang="scss" scoped> @import "@/assets/css/page/article/index"; </style>
import acm.graphics.GRect; import acm.program.GraphicsProgram; import java.awt.*; /** * Created by Bennet on 19.11.2016. */ public class MethodicalPyramid extends GraphicsProgram { //the scale based on which this will be drawn public static final int SCALE = 1600; //run forest run public void run() { //get the amount of layers from the user int layers = getLayers(); //draw each layer for (int i = 0; i < layers; i++) { drawLayer(i, layers, layerColor(i, layers)); } } /** * get the input form the user */ public int getLayers() { return readInt("How many Layers would you like? "); } /** * Returns the color to be used for bricks in the given layer. * * * * @param layerIndex index of the layer whose color to return. {@code 0} is the * bottom layer, {@code numberOfLayers - 1} is the top layer. * @param numberOfLayers the number of layers in the pyramid. * @return the color to be used for the given layer, or {@code null}if * {@code layerIndex} is invalid. */ public Color layerColor(int layerIndex, int numberOfLayers) { if(layerIndex<0||layerIndex>=numberOfLayers){ return null; } int c = 220; if(numberOfLayers>1) { c = 220 * layerIndex / (numberOfLayers - 1);//calculate the green and blue value for the current step } return new Color(255, c, c); //return the color for the current step } /** * Draws the given layer with bricks filled with the given color. If * {@code layerIndex} is invalid, no bricks at all should be drawn. * * * * @param layerIndex index of the layer to draw. {@code 0} is the bottom layer, * {@code numberOfLayers - 1} is the top layer. * @param numberOfLayers the number of layers in the pyramid. * @param layerColor color the layer's bricks should be filled with. */ public void drawLayer(int layerIndex, int numberOfLayers, Color layerColor) { if(layerIndex<0||layerIndex>=numberOfLayers){ return; } //the names of the variables should be self-explanatory int bricksInLayer = numberOfLayers - layerIndex; int brickLength = SCALE / numberOfLayers; int brickHight = SCALE / numberOfLayers / 2; int offsetX = brickLength / 2 * layerIndex+10; int offsetY = SCALE / 2 - brickHight * (layerIndex+1)+10; GRect rect; //draw the bricks in the layer for (int i = 0; i < bricksInLayer; i++) { rect = new GRect(offsetX + brickLength * i, offsetY, brickLength, brickHight); rect.setFilled(true); rect.setFillColor(layerColor); //rect.setColor(layerColor); add(rect); } } }
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="viewModel" type="com.pajaga.ui.autentikasi.login.LoginViewModel" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.autentikasi.login.LoginFragment"> <com.google.android.material.card.MaterialCardView android:id="@+id/progressDialog" android:layout_width="@dimen/_200dp" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:visibility="gone" app:cardElevation="@dimen/_8dp" app:cardCornerRadius="@dimen/_8dp" android:padding="@dimen/_8dp"> <androidx.appcompat.widget.LinearLayoutCompat android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.github.ybq.android.spinkit.SpinKitView android:id="@+id/spin_kit" style="@style/SpinKitView.Large.Circle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" app:SpinKit_Color="@color/black" android:layout_margin="@dimen/_16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <com.google.android.material.textview.MaterialTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Please wait..." android:layout_gravity="center" android:layout_margin="@dimen/_16dp" android:textSize="@dimen/_18sp" android:textStyle="bold" /> </androidx.appcompat.widget.LinearLayoutCompat> </com.google.android.material.card.MaterialCardView> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.05" /> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.4" /> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" style="@style/TitleBlue" android:text="Welcome" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/guideline" /> <TextView android:id="@+id/subtitle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="4dp" android:layout_marginEnd="16dp" android:text="@string/tes" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/title" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="30dp" android:layout_marginBottom="@dimen/_8dp" style="@style/TitleInput" android:text="Email" app:layout_constraintBottom_toTopOf="@id/IL_email" app:layout_constraintStart_toStartOf="parent" /> <com.google.android.material.textfield.TextInputLayout android:id="@+id/IL_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="@dimen/_16dp" android:layout_marginEnd="@dimen/_16dp" app:layout_constraintBottom_toTopOf="@id/guideline1"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/etmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/white" android:fontFamily="@font/poppins_medium" android:text="@={viewModel.email}" android:imeOptions="actionNext" android:inputType="text" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:id="@+id/teepass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="@dimen/_16dp" android:layout_marginBottom="@dimen/_8dp" style="@style/TitleInput" android:text="Password" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/guideline1" /> <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="@dimen/_16dp" android:layout_marginTop="@dimen/_5dp" android:layout_marginEnd="@dimen/_16dp" app:layout_constraintTop_toBottomOf="@id/teepass" app:passwordToggleDrawable="@drawable/show_password_selector" app:passwordToggleEnabled="true" app:passwordToggleTint="@color/blackTrans50"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/white" android:fontFamily="@font/poppins_medium" android:text="@={viewModel.password}" android:imeOptions="actionDone" android:inputType="textPassword" android:paddingHorizontal="@dimen/_10dp" android:textColor="@color/blackTrans50"/> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.button.MaterialButton android:id="@+id/mbLogin" android:layout_width="0dp" android:layout_height="@dimen/_50dp" android:layout_marginStart="@dimen/_16dp" android:layout_marginEnd="@dimen/_16dp" android:layout_marginBottom="@dimen/_16dp" android:background="@drawable/bg_input" app:layout_constraintBottom_toTopOf="@id/parentsignup" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" android:text="Login" android:textSize="@dimen/_12sp"/> <LinearLayout android:id="@+id/parentsignup" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginBottom="@dimen/_20dp" android:gravity="center_horizontal" android:orientation="horizontal" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/poppins_medium" android:text="Don't have an account ? " android:textSize="@dimen/_16sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/poppins_medium" android:text="Sign Up" android:onClick="@{(view) -> viewModel.onMoveToRegister(view)}" android:textColor="@color/primary" android:textSize="@dimen/_16sp" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasFactory, Notifiable, HasApiTokens; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'email', 'first_name', 'last_name', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password' ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function passwordResetOTPs() { return $this->hasMany(PasswordResetOtp::class, "user_id"); } public function Settings() { return $this->hasOne(Settings::class, "user_id"); } public function Subjects() { return $this->hasMany(Subject::class, "user_id"); } public function ScheduleSlots() { return $this->hasMany(ScheduleSlot::class, "user_id"); } public function Modules(){ return $this->hasManyThrough(Module::class, Subject::class, "user_id", "subject_id"); } }
import { FC } from "react"; interface FormInputProps { type: string; name?: string; id?: string; value?: string; placeholder?: string; className?: string; } const FormInput: FC<FormInputProps> = ({ type, name, id, value, placeholder, className, }) => { return ( <> <input type={type} name={name !== "" ? name : ""} id={id !== "" ? id : ""} value={value !== "" ? value : ""} placeholder={placeholder !== "" ? placeholder : ""} className={`${ className ? className : "border-2 border-mrk-chambray text-mrk-chambray p-5 rounded-lg focus:bg-slate-200 text-2xl" }`} required /> </> ); }; export default FormInput;
''' Modified example from https://developers.google.com/mediapipe/solutions/vision/face_landmarker/python https://developers.google.com/mediapipe/solutions/vision/face_landmarker#configurations_options https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/latest/face_landmarker.task ''' import mediapipe as mp import json from mediapipe.tasks import python from mediapipe.tasks.python import vision from typing import Tuple, Union import math import cv2 import numpy as np import mediapipe as mp import time import socket import time import signal host = '127.0.0.1' port = 0 targetip = '127.0.0.1' targetport = 9000 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_socket.bind((host, 0)) # gets free port from OS port = udp_socket.getsockname()[1] def to_array_string(arr): return json.dumps(arr, separators=(',', ':'))[1:-1] # [1,2,3,4,5] => "1,2,3,4,5" def on_mp_facelandmarker_result(result: mp.tasks.vision.FaceLandmarkerResult, output_image: mp.Image, timestamp_ms: int): global udp_socket protocol = "facepipe" source = "mediapipe" scene = 0 camera = 0 time = float(timestamp_ms)/1000.0 for subject in range(0, len(result.face_landmarks)): values = np.array([(lm.x, lm.y, lm.z) for lm in result.face_landmarks[subject]]).flatten().tolist() # each array is a set of landmark objects { 'x': 0, 'y': 0, 'z': 0, ... } - this unpacks it to a continuous list values = to_array_string(values) content = f"l3d|{output_image.width},{output_image.height}|{values}" udp_socket.sendto(f"a|{protocol}|{source}|{scene},{camera},{subject}|{time}|{content}".encode('ascii'), (targetip, targetport)) for subject in range(0, len(result.face_blendshapes)): # bs|name=0|other=0.5|smile=0.8 content = "bs" for i in range(0, len(result.face_blendshapes[subject])): bs = result.face_blendshapes[subject][i] content += f"|{bs.category_name}={bs.score}" udp_socket.sendto(f"a|{protocol}|{source}|{scene},{camera},{subject}|{time}|{content}".encode('ascii'), (targetip, targetport)) # TODO: mesh (even though mediapipe technically does not have one) #message['data'] = { # 'type': 'mesh' #} for subject in range(0, len(result.facial_transformation_matrixes)): values = result.facial_transformation_matrixes[subject].flatten().tolist() values = to_array_string(values) content = f"mat44|face={values}" udp_socket.sendto(f"a|{protocol}|{source}|{scene},{camera},{subject}|{time}|{content}".encode('ascii'), (targetip, targetport)) options = mp.tasks.vision.FaceLandmarkerOptions( base_options = mp.tasks.BaseOptions(model_asset_path='content/thirdparty/mediapipe/face_landmarker.task'), running_mode = mp.tasks.vision.RunningMode.LIVE_STREAM, num_faces = 1, min_face_detection_confidence = 0.1, min_face_presence_confidence = 0.1, min_tracking_confidence = 0.1, output_face_blendshapes = True, output_facial_transformation_matrixes = True, result_callback = on_mp_facelandmarker_result) run_program = True def handler(signum, frame): global run_program run_program = False print("\nExit command received") signal.signal(signal.SIGINT, handler) with mp.tasks.vision.FaceLandmarker.create_from_options(options) as landmarker: cv2_webcam_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) # 0: first webcam in device list cv2_webcam_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cv2_webcam_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) time_start = time.time() while cv2_webcam_capture.isOpened() and run_program: success, cv2_webcam_image = cv2_webcam_capture.read() # TODO: Flip variable cv2_webcam_image = cv2.flip(cv2_webcam_image, 1) # Convert the frame received from OpenCV to a MediaPipe’s Image object. mp_webcam_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=cv2_webcam_image) # This is async and method returns immediately. If another webcam frame is requested before the detector is finished it will ignore the new image. frame_timestamp_ms = round((time.time()-time_start)*1000) landmarker.detect_async(mp_webcam_image, frame_timestamp_ms) # returns to on_mp_facelandmarker_result when done cv2.imshow('image', cv2_webcam_image) if cv2.waitKey(1) == 27: break # esc to quit udp_socket.close() print("\nDone")
import 'package:flutter/material.dart'; import 'dart:io' as io; import 'dart:convert'; import 'package:image_picker/image_picker.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:integradora/src/model/response_api.dart'; import 'package:integradora/src/model/user.dart'; import 'package:integradora/src/provider/users_provider.dart'; import 'package:integradora/src/utils/my_snackbar.dart'; import 'package:integradora/src/utils/mycolors.dart'; import 'package:integradora/src/utils/shared_pref.dart'; import 'package:sn_progress_dialog/progress_dialog.dart'; class PerfilController { BuildContext context; TextEditingController nameController = new TextEditingController(); TextEditingController lastnameController = new TextEditingController(); TextEditingController phoneController = new TextEditingController(); UsersProvider usersProvider = new UsersProvider(); PickedFile pickedFile; io.File imageFile; Function refresh; ProgressDialog _progressDialog; bool isEnabled = true; User user; SharedPref _sharedPref = new SharedPref(); Future init(BuildContext context, Function refresh) async { this.context = context; this.refresh = refresh; _progressDialog = ProgressDialog(context: context); user = User.fromJson(await _sharedPref.read('user')); usersProvider.init(context, sessionUser: user); nameController.text = user.name; lastnameController.text = user.lastname; phoneController.text = user.phone; refresh(); } void update() async { String name = nameController.text; String lastname = lastnameController.text; String phone = phoneController.text.trim(); if (name.isEmpty || lastname.isEmpty || phone.isEmpty) { MySnackbar.show(context, 'Por favor llene todos los campos'); return; } _progressDialog.show(max: 100, msg: 'Actualizando tu información...'); isEnabled = false; User myUser = new User( id: user.id, name: name, lastname: lastname, phone: phone, image: user.image); Stream stream = await usersProvider.update(myUser, imageFile); stream.listen((res) async { _progressDialog.close(); //ResponseApi responseApi = await usersProvider.create(user); ResponseApi responseApi = ResponseApi.fromJson(json.decode(res)); Fluttertoast.showToast(msg: responseApi.message); if (responseApi.success) { user = await usersProvider .getById(myUser.id); //OBTENIENDO EL USUARIO DE LA BD print('Usuario obetnido: ${user.toJson()}'); _sharedPref.save('user', user.toJson()); Navigator.pushNamedAndRemoveUntil( context, 'usuario/inicio', (route) => false); } else { isEnabled = true; } }); } Future selectImage(ImageSource imageSource) async { pickedFile = await ImagePicker().getImage(source: imageSource); if (pickedFile != null) { imageFile = io.File(pickedFile.path); } Navigator.pop(context); refresh(); } void showAlertDialog() { Widget galleryButton = ElevatedButton( style: ElevatedButton.styleFrom(primary: MyColors.primaryColor), onPressed: () { selectImage(ImageSource.gallery); }, child: Text('Galeria'), ); Widget cameraButton = ElevatedButton( style: ElevatedButton.styleFrom(primary: MyColors.primaryColor), onPressed: () { selectImage(ImageSource.camera); }, child: Text( 'Camara', ), ); AlertDialog alertDialog = AlertDialog( title: Text('Selecciona tu imagen'), actions: [galleryButton, cameraButton], ); showDialog( context: context, builder: (BuildContext context) { return alertDialog; }); } void back() { Navigator.pop(context); } }
= Camel-Quarkus Demo == How to Prepare the Demo [source,shell] ---- # Provision "OpenShift 4 Serverless Foundations Lab" cluster and login, for instance: cd ~/dev/demos/camel-quarkus-demos/integration-in-the-cloud-era-with-camel-quarkus openshift-configs/connect # Create knative-serving namespace oc create namespace knative-serving # Install OpenShift ServerLess Operator from the UI (https://docs.openshift.com/container-platform/4.6/serverless/installing_serverless/installing-openshift-serverless.html) + Operators/Operator Hub/Filter (OpenShift ServerLess) + Click Install / Subscribe + Click "Installed Operators" / "OpenShift Serverless" / "KNative Serving - Create Instance " + In the YAML view, set namespace to knative-serving + Click create + watch oc get pods -n knative-serving (wait all pods to be Running/Completed) # Deploy jvm and native projects to the cluster main_upstream mvn clean package -Dquarkus.kubernetes.deploy=true # Finalize openshift configuration ./openshift-configs/installing-demo.sh # Open terminator and configure for knative demo cd ~/dev/demos/camel-quarkus-demos/integration-in-the-cloud-era-with-camel-quarkus # Split window horizontally, and run each command in its own shell . openshift-configs/before-running-demo.sh watch "oc describe quota mem-quota && echo '' && oc get pods | grep -v build" # Tune the zoom (CTRL + scroll 9x) in all shell # Open terminator and configure the local rest demo cd ~/dev/demos/camel-quarkus-demos/integration-in-the-cloud-era-with-camel-quarkus/rest-to-nats-demo/ git checkout -- . # Split window horizontally, then horizontally, and run below command in each shell main_upstream # Then run each command below in its own shell ./start-nats.sh http localhost:8080/steps mvn quarkus:dev (can kill it before demo) # Tune the zoom in each shell (CTRL + scroll as necessary) # In eclipse Open rest-to-nats-demo/CamelRoutes,Step2Bean,StepsRouteTest,Configurations,application.properties # In eclipse Open by-cq-knative-jvm-mode/MyRoutBuilder.java # Execute StepsRouteTest Junit test once, at this stage it should fail with ACTUAL="STEP 1" # Zoom in eclipse editor (CTRL/SHIFT/+ 5 times so that we have ~85 chars per line) # In openshift console, prepare Serverless/Services with namespace default (we should see the 4 knative services) # Configure audio input/output to headset # Copy paste tiny urls so that we can send it very early # Configure display on a single screen (like for Apache CON @Home & JavaLand) # In workspace 2: CTRL+ALT+DOWN/UP to change workspace, Open slides: # ~/dev/demos/camel-quarkus-demos/integration-in-the-cloud-era-with-camel-quarkus/Integration\ In\ The\ Cloud\ Era\ With\ Camel\ Quarkus.odp ---- == How to Run the Demo [source,shell] ---- # Take care of possible lags = audio/video shift, it's worth waiting few seconds so that everyone could see commands output # Copy paste tiny urls in chat/browser/presentation system https://tinyurl.com/vpyfr9xb (Camel Quarkus website) https://tinyurl.com/wpa7wvp9 (Quarkus website) https://tinyurl.com/2cm7886s (Building a native executable) https://tinyurl.com/38yyrx84 (GraalVM Native Image) https://tinyurl.com/7hruukyd (Demo with sources on github) # Speech: Slides about Presenter, Plan, Camel Reminder, Quarkus reminder # Show the rest DSL in Java # In a first shell mvn quarkus:dev # Invoke the service from the middle shell output "STEP 1" http localhost:8080/steps # Uncomment bean in route definition, mention the EndpointRouteBuilder syntax # Invoke the service from the middle shell output "STEP 1 - STEP 2" http localhost:8080/steps # Show in StepsRouteTest how to override the bean in a test # Run the JUnit test from quarkus:dev (by pressing 'r' in the quarkus:dev console) # Uncomment log in route definition # Invoke the service from the middle shell output logs with MEP and body type http localhost:8080/steps # Uncomment @Named on Configurations.log() (camel component tuning via java code) # Invoke the service from the middle shell output logs without MEP and body type http localhost:8080/steps # Uncomment the nats line in route definition, notice that type safe endpoint dsl # quarkus:dev can't start # Uncomment nats.servers line in application.properties (camel component tuning via properties) # Invoke, and show the logs from nats server http localhost:8080/steps # Now let's try in native mode mvn clean package -P native # Speech: Pave the 3 minutes with the slide comparing JVM vs native # Speech: Mention that quarkus is already doing fine in JVM # Speech: Mention that the 3s long configuration is done at build time target/rest-to-nats-demo-1.0.0-SNAPSHOT-runner # Oops not running, we need to explicitly embed some resources # So uncomment 'quarkus.camel.native.resources.include-patterns' in application.properties mvn clean package -P native # Speech: Pave the 3 minutes with slides Native mode (how great), Native mode (how complex) target/rest-to-nats-demo-1.0.0-SNAPSHOT-runner # Move to knative terminator and present the environment # Speech: Show a knative service in eclipse, mention kubernetes extension # Speech: OpenShift cluster = kubernetes with goodies # Speech: Goodies like serverless tab => 4 services in default namespace # Speech: bottom shell, quota expand later, and no pods => knative scales to zero hello-jvm # On demand provisioning, first request served in ~6s hello-native # Speech: We save the 3s from the static initializer, so we have seen the boot time effect # Speech: Wait for knative to scale to zero # Speech: Explain mem quota, then hello-jvm, at 30s launch bye-jvm, oh needs to wait (it's either delay or dollar) # Speech: hello-native, bye-native => we have a better densification # Speech: Slides about conclusion, it's all about, thanks ---------------------------------------------------------------------------------------------------------------------- Raw notes for demo/improvements: Check how to simply deploy on openshift (https://developers.redhat.com/blog/2020/04/24/ramp-up-on-quarkus-a-kubernetes-native-java-framework/) @TODO: Fake the native compilation (it disturbs the demo, for instance it competes with resources from the conferencing system, could be slower) TODO in another demo: Find below how to show resources consumption for containers: watch oc exec hello-cq-knative-native-mode-lswdr-3-deployment-fc89bdd8-9jlc5 cat /sys/fs/cgroup/memory/memory.usage_in_bytes 50999808 ( 48.64 MiB) in native 613645120 (585.22 MiB) in jvm To get the sidecar usage, you need to add "-c queue-proxy" watch oc exec hello-cq-knative-native-mode-yylnv-3-deployment-7fdd977b8f2x2bx -c queue-proxy cat /sys/fs/cgroup/memory/memory.usage_in_bytes TIPS to create a gif file from images: ffmpeg -framerate 0.5 -pattern_type glob -i "Screenshot from 2021-05-07-15h-Getting Further With Camel on Quarkus.mkv - *.png" -s 960x540 demo.gif
package com.swarna.collegeapi.entity; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Entity @Data @AllArgsConstructor @NoArgsConstructor @Builder @ToString(exclude = "course") public class CourseMaterial { @Id @SequenceGenerator( name = "course_material_sequence", sequenceName = "course_material_sequence", allocationSize = 1 ) @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "course_material_sequence" ) private Long courseMaterialId; private String url; // courseMaterial cant exist without course and for one course, there will be one Course Material and vice versa. @OneToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false ) @JoinColumn( // foreign key name = "course_id", // it will save with this name in course_material table. referencedColumnName = "courseId" // courseId is coming from course.courseId ) private Course course; }
<template> <q-page class="q-mx-md-lg q-my-md-xl q-ma-sm-lg q-ma-xs-md"> <div class="text-nightRider q-px-sm text-h5 text-weight-medium"> My Blooprints <q-separator width="120px" class="q-mt-xs" color="primary" size="2px" /> </div> <BlooprintSkeletonCardWeb requestFrom="blooprint" v-if="loading" /> <div v-else-if="!loading && errorInGettingMyBlooprints.length" class="absolute-center text-center text-subtitle1" > {{ errorInGettingMyBlooprints }} </div> <div v-if="!loading && errorInGettingMyBlooprints.length == 0"> <div v-if="myBlooprintList.length == 0"> <NoDataMessageDisplay /> </div> <q-infinite-scroll :offset="250" @load="loadMoreRecords" ref="infiniteScroll" > <template v-slot:loading> <div class="row justify-center q-my-md"> <q-spinner-dots color="primary" size="40px" /> </div> </template> <div class="row"> <div class="col-md-6 col-sm-12 col-xs-12 q-mt-md q-px-sm" v-for="(list, index) in myBlooprintList" :key="index" > <DesktopBlooprintListCard requestFrom="blooprint" :key="index" :thumbnailImage="list.attributes.thumbnail" :authorName="list.attributes.authorName" :price="list.attributes.price" :currency="list.attributes.currency" :blooprintName="list.attributes.name" :blooprintDescription="list.attributes.description" :rating="list.attributes.rating" :blooprint="list" /> </div> </div> <div class="no-more-results-msg border-bottom-secondary text-body1 text-h5 text-center text-manatee" v-if="noMoreResults && myBlooprintList.length != 0" > <span class="bg-whiteSmoke q-px-sm">No more results</span> </div> </q-infinite-scroll> </div> </q-page> </template> <script> import DesktopBlooprintListCard from 'components/DesktopBlooprintListCard.vue' import BlooprintSkeletonCardWeb from 'components/BlooprintSkeletonCardWeb.vue' import NoDataMessageDisplay from 'components/Desktop/NoDataMessageDisplay.vue' import { mapActions, mapGetters } from 'vuex' const BLOOPRINT_SHOW_LIMIT = 10 export default { meta() { return { title: this.$route.meta.title } }, data() { return { loading: true, noMoreResults: false, myBlooprintList: [] } }, components: { DesktopBlooprintListCard, BlooprintSkeletonCardWeb, NoDataMessageDisplay }, mounted() { this.getMyBlooprintsData() }, computed: { ...mapGetters(['errorInGettingMyBlooprints']) }, methods: { ...mapActions(['fetchMyBlooprintsList']), // **************** Method to Fetch My-Blooprints List *********************** async getMyBlooprintsData() { let params = { limit: BLOOPRINT_SHOW_LIMIT, offset: 0 } this.loading = true let data = await this.fetchMyBlooprintsList(params) if (data['data']) { this.myBlooprintList = data['data'] } this.loading = false }, // ************ On Scroll Pagination Load Blooprint Records ***************************** async loadMoreRecords(index, done) { let myBlooprintsLengthBeforeLoad = this.myBlooprintList.length let params = { limit: BLOOPRINT_SHOW_LIMIT, offset: index * BLOOPRINT_SHOW_LIMIT } if (myBlooprintsLengthBeforeLoad > BLOOPRINT_SHOW_LIMIT) { let data = await this.fetchMyBlooprintsList(params) if (data['data'].length > 0) { this.myBlooprintList = this.myBlooprintList.concat(data['data']) } let myBlooprintsLengthAfterLoad = this.myBlooprintList.length if (myBlooprintsLengthBeforeLoad == myBlooprintsLengthAfterLoad) { if (myBlooprintsLengthBeforeLoad > 0) { this.noMoreResults = true } this.$refs.infiniteScroll.stop() } } done() } } } </script>
import BlockchainBackedItem from 0xf8d6e0586b0a20c7 pub struct NFTResult { pub(set) var name: String pub(set) var description: String pub(set) var thumbnail: String pub(set) var owner: Address pub(set) var type: String pub(set) var isLostOrStolen: Bool pub(set) var message: String init() { self.name = "" self.description = "" self.thumbnail = "" self.owner = 0x0 self.type = "" self.isLostOrStolen = false self.message = "" } } pub fun main(address: Address, id: UInt64): NFTResult { let account = getAccount(address) let collection = account .getCapability(BlockchainBackedItem.CollectionPublicPath) .borrow<&{BlockchainBackedItem.BlockchainBackedItemCollectionPublic}>() ?? panic("Could not borrow a reference to the collection") let nft = collection.borrowBlockchainBackedItem(id: id)! var data = NFTResult() // Get the basic display information for this Blockchain Backed Item if let view = nft.resolveView(Type<BlockchainBackedItem.MetadataDisplay>()) { let display = view as! BlockchainBackedItem.MetadataDisplay data.name = display.name data.description = display.description data.thumbnail = display.thumbnail data.isLostOrStolen = display.isLostOrStolen data.message = display.ownerMessage } // The owner is stored directly on the NFT object let owner: Address = nft.owner!.address! data.owner = owner // Inspect the type of this NFT to verify its origin let nftType = nft.getType() data.type = nftType.identifier return data }
import 'package:flutter/material.dart'; import 'package:muzahir_fyp/assets/spacing.dart'; import 'package:muzahir_fyp/components/auth_widgets.dart'; import 'package:muzahir_fyp/components/build_button.dart'; import 'package:muzahir_fyp/components/textfield.dart'; import 'package:muzahir_fyp/view/auth%20screens/sign_up_screen.dart'; import 'package:muzahir_fyp/view/dashboard%20screens/dashboard.dart'; import 'package:nb_utils/nb_utils.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { var emailController = TextEditingController(); var passController = TextEditingController(); var active1 = true; @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: CustomScrollView( slivers: [ SliverFillRemaining( hasScrollBody: false, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), child: Column( children: [ Align( alignment: Alignment.topLeft, child: IconButton( onPressed: () { finish(context); }, icon: const Icon(Icons.arrow_back)) .paddingBottom(size20), ), const Spacer(), text("Login into your account", fontWeight: FontWeight.w500, fontSize: size18) .paddingBottom(size30), textField( hint: "Email", maxline: 1, labell: text("Email"), controller: emailController, ), textField( hint: "Password", controller: passController, maxline: 1, labell: text("Password"), obscures: active1, suffix: IconButton( onPressed: () { setState(() { active1 == true ? active1 = false : active1 = true; }); }, icon: active1 == true ? const Icon(Icons.visibility) : const Icon(Icons.visibility_off)), ), const Spacer(), BuildButton( onPressed: () { if (emailController.text.isEmpty || passController.text.isEmpty) { toast("email or password is empty", bgColor: redColor); } else { const Dashboard().launch(context); toast("login successfully", bgColor: greenColor); } }, text: "Login") .paddingBottom(size20), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ text( "Didn't have an account?", textColor: grey, fontSize: size13, ), textButton( text: "Sign Up", ontap: () { const SignUpScreen().launch(context); }, ) ], ) ], ), ), ), ], ), ), ); } }
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/03/a/RAM8.hdl /** * Memory of 8 registers, each 16 bit-wide. Out holds the value * stored at the memory location specified by address. If load==1, then * the in value is loaded into the memory location specified by address * (the loaded value will be emitted to out from the next time step onward). */ CHIP RAM8 { IN in[16], load, address[3]; OUT out[16]; PARTS: // Put your code here: DMux8Way(in=load, sel=address, a=a1, b=a2, c=a3, d=a4, e=a5, f=a6, g=a7, h=a8); Register(in=in, load=a1, out=out1); Register(in=in, load=a2, out=out2); Register(in=in, load=a3, out=out3); Register(in=in, load=a4, out=out4); Register(in=in, load=a5, out=out5); Register(in=in, load=a6, out=out6); Register(in=in, load=a7, out=out7); Register(in=in, load=a8, out=out8); Mux8Way16(a=out1, b=out2, c=out3, d=out4, e=out5, f=out6, g=out7, h=out8, sel=address, out=out); }
import React, {Component} from "react"; import './table.css'; import store from "../../../app/store"; import {Navigate} from "react-router-dom"; class Table extends Component { constructor(props) { super(props); this.state = {data: []}; } componentDidMount() { store.subscribe(() => { this.setState({reduxState: store.getState()}); }) } handleSubmit = (e) => { console.log(e) } render() { if (!this.props.checks || this.props.checks.length === 0) return ( <div className={"no-results"}> Нет подходящих результатов по запросу </div> ) const handleClick = (e) => { this.setState({redirect: "/details/?id=" + e.target.name}) } if (this.state.redirect) { return ( <Navigate to={this.state.redirect} replace={true}/> ) } return ( <div className={"table-wrapper"}> <table className="table is-bordered is-hoverable is-fullwidth has-text-centered"> <thead> <tr> <th> {this.props.photo} </th> <th className={"name-column"} name="name"> {this.props.name} </th> <th name="price"> {this.props.price} </th> <th> {this.props.submit} </th> </tr> </thead> <tbody> {(this.props.checks) ? this.props.checks.map(function (check) { return ( <tr key={check.id}> <td><img src={check.imageUrl} /></td> <td>{check.name}</td> <td>{check.price + ' рублей'}</td> <td> <button className={"item_button"} name={check.id} onClick={handleClick}>Смотреть</button> </td> </tr> ); }) : <tr> <td colSpan={5}>Loading...</td> </tr>} </tbody> </table> </div>) } } export default Table
// https://leetcode.com/problems/permutation-in-string/description/ public class PermutationInString { /* public static boolean checkInclusion(String s1, String s2) { if(s1.length() > s2.length()) return false; // Initialize both the arrays int[] charCountS1 = new int[26]; int[] charCountS2 = new int[26]; for(int i = 0; i < s1.length(); i++) { charCountS1[s1.charAt(i) - 'a']++; charCountS2[s2.charAt(i) - 'a']++; } // Find the count of equal characters int countOfEqualCharacters = 0; for(int i = 0; i < 26; i++) { if(charCountS1[i] == charCountS2[i]) countOfEqualCharacters++; } // Check the remaining string s2. int low = 0; for(int high = s1.length(); high < s2.length(); high++) { if(countOfEqualCharacters == 26) return true; int charIndex = s2.charAt(low) - 'a'; charCountS2[charIndex]--; if(charCountS1[charIndex] == charCountS2[charIndex]) countOfEqualCharacters++; else if(charCountS1[charIndex] == charCountS2[charIndex] + 1) countOfEqualCharacters--; low++; charIndex = s2.charAt(high) - 'a'; charCountS2[charIndex]++; if(charCountS1[charIndex] == charCountS2[charIndex]) countOfEqualCharacters++; else if(charCountS1[charIndex] == charCountS2[charIndex] - 1) countOfEqualCharacters--; } return (countOfEqualCharacters == 26); } */ // One HashMap only, decrementing the s1 characters and counting the number of zero count characters instead of equal characters in two hashmap public boolean checkInclusion(String s1, String s2) { if(s1.length() > s2.length()) return false; // Initialize both the arrays int[] charCount = new int[26]; for(int i = 0; i < s1.length(); i++) { charCount[s1.charAt(i) - 'a']--; charCount[s2.charAt(i) - 'a']++; } // Find the count of zero count characters int countOfZeroCharacters = 0; for(int i = 0; i < 26; i++) { if(charCount[i] == 0) countOfZeroCharacters++; } // Check the remaining string s2. int low = 0; for(int high = s1.length(); high < s2.length(); high++) { if(countOfZeroCharacters == 26) return true; int charIndex = s2.charAt(low) - 'a'; charCount[charIndex]--; if(charCount[charIndex] == 0) countOfZeroCharacters++; else if(charCount[charIndex] + 1 == 0) countOfZeroCharacters--; low++; charIndex = s2.charAt(high) - 'a'; charCount[charIndex]++; if(charCount[charIndex] == 0) countOfZeroCharacters++; else if(charCount[charIndex] - 1 == 0) countOfZeroCharacters--; } return (countOfZeroCharacters == 26); } }
class Api::V1::AnswersController < Api::V1::BaseController before_action :set_question, only: [:index, :create] before_action :set_answer, only: [:show] authorize_resource def index respond_with @question.answers end def show respond_with @answer end def create @answer = @question.answers.create(answer_params.merge(user: current_resource_owner)) respond_with @answer, each_serializer: AnswerSerializer end private def set_question @question = Question.find(params[:question_id]) end def set_answer @answer = Answer.find(params[:id]) end def answer_params params.require(:answer).permit(:body) end end
<template> <div class="dwc-editor"> <div class="fds-m-b--m fds-m-t--s fds-m-r--s"> <!-- <p class="dwc-editor-header">{{ EDITOR_TITLE }}</p> --> <span class="fds-m-l--s"> <!-- <button @click="saveCode()" class="fds-btn fds-btn--secondary fds-btn--small fds-m-r--xs" type="button"> <svg class="fds-icon fds-icon--size-2" aria-hidden="true" focusable="false" role="img" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg> Save </button> --> <button @click="remove()" :disabled="isDeleteEnabled ? 0:1" class="fds-btn fds-btn--secondary fds-btn--small fds-m-r--xs" type="button"> <svg class="fsa-icon fsa-icon--size-2" aria-hidden="true" focusable="false" role="img" fill="#205493" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"></path></svg> </button> <button @click="undo()" :disabled="isUndoEnabled ? 0:1" class="fds-btn fds-btn--secondary fds-btn--small fds-m-r--xs" type="button"> <svg class="fds-icon fds-icon--size-2" aria-hidden="true" focusable="false" role="img" fill="#205493" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"></path> </svg> </button> <button @click="redo()" :disabled="isRedoEnabled ? 0:1" class="fds-btn fds-btn--secondary fds-btn--small fds-m-r--xs" type="button"> <svg class="fds-icon fds-icon--size-2" aria-hidden="true" focusable="false" role="img" fill="#205493" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M18.4 10.6C16.55 8.99 14.15 8 11.5 8c-4.65 0-8.58 3.03-9.96 7.22L3.9 16c1.05-3.19 4.05-5.5 7.6-5.5 1.95 0 3.73.72 5.12 1.88L13 16h9V7l-3.6 3.6z"></path> </svg> </button> </span> </div> <content-tabs :TABS_DATA="tabsData" TABS_CLASS="fds-content-tabs--justified-equal fds-border--primary-300" TABS_CONTAINER_CLASS="fds-m-t--none" @emitTabSelection="handleTabSelected"> <template v-slot:containers> <div class="fds-m-t--m"> <editor-ui :CONTAINER_ID="uiContainerId + '-container'" CONTAINER_CLASS="" @emitEditorAction="updateCanvas"> </editor-ui> <editor-templates :CONTAINER_ID="templatesContainerId + '-container'" CONTAINER_CLASS="" @emitEditorAction="updateCanvas"> </editor-templates> <!--<editor-code :CONTAINER_ID="codeContainerId + '-container'" CONTAINER_CLASS="" @emitEditorAction="updateCanvas" @interface="getChildInterface"> </editor-code>--> </div> </template> </content-tabs> </div> </template> <script> import { defineAsyncComponent, ref, onMounted, computed, watch } from "vue"; import { useStore } from "vuex"; import { v4 as uuidv4 } from "uuid"; const contentTabs = defineAsyncComponent(() => import('@/_components/content-tabs/content-tabs.vue')); //import editorTemplates from '@/Design/_views/Editor/EditorTemplates.vue'; const editorTemplates = defineAsyncComponent(() => import('@/Design/_views/Editor/EditorTemplates.vue')); const editorUi = defineAsyncComponent(() => import('@/Design/_views/Editor/EditorUi.vue')); const editorCode = defineAsyncComponent(() => import('@/Design/_views/Editor/EditorCode.vue')); export default { props: { EDITOR_TITLE: String }, components: { contentTabs, editorTemplates, editorUi, editorCode }, setup(props, {emit}) { const store = useStore(); const templatesContainerId = ref(uuidv4()); const uiContainerId = ref(uuidv4()); const codeContainerId = ref(uuidv4()); const codeContainerRef = ref(null); const tabsData = ref([ { id: uiContainerId.value, label: 'UI', iconSize: '2', iconPath: 'M20 13H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-6c0-.55-.45-1-1-1zM7 19c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM20 3H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1zM7 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z', iconFillHex: '#494440', isSelected: true, containerId: uiContainerId.value +'-container' }, { id: templatesContainerId.value, label: 'Templates', iconSize: '2', iconPath: 'M10 18h5v-6h-5v6zm-6 0h5V5H4v13zm12 0h5v-6h-5v6zM10 5v6h11V5H10z', iconFillHex: '#494440', isSelected: false, containerId: templatesContainerId.value +'-container' } /* { id: codeContainerId.value, label: 'Code', iconSize: '2', iconPath: 'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z', iconFillHex: '#494440', isSelected: false, containerId: codeContainerId.value +'-container' } */ ]); const deleteEnabled = computed(()=>{ return store.getters['design/getDeleteEnabled'] }); const isDeleteEnabled = ref(); const undoEnabled = computed(()=>{ return store.getters['design/getUndoEnabled'] }); const isUndoEnabled = ref(); const redoEnabled = computed(()=>{ return store.getters['design/getRedoEnabled'] }); const isRedoEnabled = ref(); let childInterface = () => {}; const getChildInterface = (_interface) => childInterface = _interface; const saveCode = () => { childInterface.saveCode(); } const updateCanvas =(_data) => { emit('emitOnUpdate', _data); } const undo = () => { let undoTM = setTimeout(()=>{ emit('emitOnUndo') }, 300); return () => clearTimeout(undoTM); } const redo = () => { let redoTM = setTimeout(()=>{ emit('emitOnRedo') }, 300); return () => clearTimeout(redoTM); } const remove = () => { updateCanvas({ action: 'onComponentUpdate', methodName: 'remove', obj: {placementLocation: 'remove'} }); } const handleTabSelected = (_obj) => { // Do something in Parent Component when Tab Selected //console.log('_obj.id',_obj.id) } watch([deleteEnabled, undoEnabled, redoEnabled], ( curr, prev)=>{ isDeleteEnabled.value = curr[0], isUndoEnabled.value = curr[1], isRedoEnabled.value = curr[2] }) onMounted(()=>{ store.dispatch('design/setDeleteEnabled', false); store.dispatch('design/setUndoEnabled', false); store.dispatch('design/setRedoEnabled', false); }); return { saveCode, remove, undo, redo, handleTabSelected, tabsData, templatesContainerId, uiContainerId, codeContainerId, codeContainerRef, getChildInterface, updateCanvas, isDeleteEnabled, isUndoEnabled, isRedoEnabled }; } }; </script>
// import React from 'react' // import { FlatList, Text, TouchableOpacity, View } from 'react-native' // import { connect } from 'react-redux' // import { Navigation } from 'react-native-navigation' // import { subCategoryTypeEntityDetailScreen, subCategoryTypeEntityEditScreen } from '../../../navigation/layouts' // import SearchBar from '../../../shared/components/search-bar/search-bar' // import SubCategoryTypeActions from './sub-category-type.reducer' // import styles from './sub-category-type-entity-screen-style' // import AlertMessage from '../../../shared/components/alert-message/alert-message' // // More info here: https://facebook.github.io/react-native/docs/flatlist.html // class SubCategoryTypeEntityScreen extends React.PureComponent { // constructor(props) { // super(props) // Navigation.events().bindComponent(this) // /* *********************************************************** // * STEP 1 // * This is an array of objects with the properties you desire // * Usually this should come from Redux mapStateToProps // *************************************************************/ // this.state = { // page: 0, // sort: 'id,asc', // size: 20, // done: false, // searchTerm: '', // dataObjects: [], // } // this.fetchSubCategoryTypes() // } // navigationButtonPressed({ buttonId }) { // subCategoryTypeEntityEditScreen({ entityId: null }) // } // /* *********************************************************** // * STEP 2 // * `renderRow` function. How each cell/row should be rendered // * It's our best practice to place a single component here: // * // * e.g. // return <MyCustomCell title={item.title} description={item.description} /> // *************************************************************/ // renderRow({ item }) { // return ( // <TouchableOpacity onPress={subCategoryTypeEntityDetailScreen.bind(this, { entityId: item.id })}> // <View style={styles.row}> // <Text style={styles.boldLabel}>{item.id}</Text> // {/* <Text style={styles.label}>{item.description}</Text> */} // </View> // </TouchableOpacity> // ) // } // /* *********************************************************** // * STEP 3 // * Consider the configurations we've set below. Customize them // * to your liking! Each with some friendly advice. // *************************************************************/ // // Render a header? // renderHeader = () => <SearchBar onSearch={this.performSearch} searchTerm={this.state.searchTerm} onCancel={this.cancelSearch} /> // // Render a footer? // // renderFooter = () => // // <Text style={[styles.label, styles.sectionHeader]}> - Footer - </Text> // // Show this when data is empty // renderEmpty = () => <AlertMessage title="No SubCategoryTypes Found" show={!this.props.fetching} /> // // renderSeparator = () => // // <Text style={styles.label}> - ~~~~~ - </Text> // // The default function if no Key is provided is index // // an identifiable key is important if you plan on // // item reordering. Otherwise index is fine // keyExtractor = (item, index) => `${index}` // // How many items should be kept im memory as we scroll? // oneScreensWorth = 20 // // extraData is for anything that is not indicated in data // // for instance, if you kept "favorites" in `this.state.favs` // // pass that in, so changes in favorites will cause a re-render // // and your renderItem will have access to change depending on state // // e.g. `extraData`={this.state.favs} // // Optimize your list if the height of each item can be calculated // // by supplying a constant height, there is no need to measure each // // item after it renders. This can save significant time for lists // // of a size 100+ // // e.g. itemLayout={(data, index) => ( // // {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index} // // )} // cancelSearch = () => { // this.setState({ // searchTerm: '', // }) // this.fetchSubCategoryTypes() // } // performSearch = query => { // if (query === '') { // this.cancelSearch() // return // } // this.setState({ // searchTerm: query, // }) // this.props.performSearch(query) // } // fetchSubCategoryTypes = () => { // this.props.getAllSubCategoryTypes({ page: this.state.page, sort: this.state.sort, size: this.state.size }) // } // handleLoadMore = () => { // if (this.state.done || this.props.fetching) { // return // } // this.setState( // { // page: this.state.page + 1, // }, // () => { // this.fetchSubCategoryTypes() // }, // ) // } // static getDerivedStateFromProps(nextProps, prevState) { // if (nextProps.subCategoryTypes) { // return { // done: nextProps.subCategoryTypes.length < prevState.size, // dataObjects: [...prevState.dataObjects, ...nextProps.subCategoryTypes], // } // } // return null // } // render() { // return ( // <View style={styles.container} testID="subCategoryTypeScreen"> // <FlatList // contentContainerStyle={styles.listContent} // data={this.state.dataObjects} // renderItem={this.renderRow} // keyExtractor={this.keyExtractor} // initialNumToRender={this.oneScreensWorth} // onEndReached={this.handleLoadMore} // ListHeaderComponent={this.renderHeader} // /* ListFooterComponent={this.renderFooter} */ // ListEmptyComponent={this.renderEmpty} // ItemSeparatorComponent={this.renderSeparator} // /> // </View> // ) // } // } // const mapStateToProps = state => { // return { // // ...redux state to props here // subCategoryTypes: state.subCategoryTypes.subCategoryTypes, // fetching: state.subCategoryTypes.fetchingAll, // error: state.subCategoryTypes.errorAll, // } // } // const mapDispatchToProps = dispatch => { // return { // performSearch: query => dispatch(SubCategoryTypeActions.subCategoryTypeSearchRequest(query)), // getAllSubCategoryTypes: options => dispatch(SubCategoryTypeActions.subCategoryTypeAllRequest(options)), // } // } // export default connect( // mapStateToProps, // mapDispatchToProps, // )(SubCategoryTypeEntityScreen)
<?php use App\Http\Controllers\HomeController; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Route::post('/submit/data/ajax', [HomeController::class, 'submit'])->name('submit.form'); Route::get('/get/data/ajax', [HomeController::class, 'getData'])->name('data.get.getData'); Route::get('/get/data/ajax/edit/edit/{id}', [HomeController::class, 'editId'])->name('data.edit.data.data'); Route::get('/get/data/ajax/delete/delete/{id}', [HomeController::class, 'deleteId'])->name('data.delete.data.data');
Task = require("./task").Task class Command constructor: (name, aliases..., needsUser, logic) -> @name = name @aliases = aliases @logic = logic @needsUser = needsUser processHelp: (req) -> if req.commandRequest?.name in [':help', ':h', ':describe', ':desc'] req.commandRequest.help ?= [] unless req.commandRequest.value req.commandRequest.help.push usage: @usage(), desc: @desc(), needsUser: @needsUser else if req.commandRequest.value is @name req.commandRequest.help.push usage: @usage(), desc: @desc(), needsUser: @needsUser canRunCommand: (req) -> name = req.commandRequest?.name if (@name is name) or (@aliases.indexOf(name) isnt -1) if @needsUser then req.commandRequest.user? else yes else no middleware: -> self = this (req, res, next) -> self.processHelp(req) if self.canRunCommand(req) console.log req.commandRequest try self.logic(req, res, next) catch error res.send status: 'failure' error: 'exception raised' commandData: req.commandRequest errorData: error else next() notifyBucketUpdate: (name, updatedTask) -> global.io.sockets.emit 'update bucket', bucket: name, updatedTask: updatedTask class InvalidCommand @middleware: -> (req, res, next) -> if req.commandRequest res.send status: 'failure' error: 'unknown command' else next() class NewTaskCommand extends Command constructor: -> self = this super ':new', ':n', yes, (req, res, next) -> task = new Task description: req.commandRequest.value bucket: req.commandRequest.bucket createdAt: Date.now() _owner: req.commandRequest.user._id task.save (err) -> if err next err else self.notifyBucketUpdate req.commandRequest.bucket, task._id res.send status: 'success' usage: -> ":new|:n [bucket] <description>" desc: -> "Create a new task. Unless the optional parameter [bucket] is given, the new task is created inside the currently selected bucket" class ChangeTaskCommand extends Command constructor: -> self = this super ':change', ':ch', yes, (req, res, next) -> Task.findOneAndUpdate { _id: req.commandRequest.taskId }, { description: req.commandRequest.value, updatedAt: Date.now() }, (err, task) -> if err next err else self.notifyBucketUpdate req.commandRequest.bucket, req.commandRequest.taskId res.send status: 'success' usage: -> ":change|:ch <description>" desc: -> "Change the description of the currently selected task" class CloseTaskCommand extends Command constructor: -> self = this super ':close', ':cl', ':check', ':ck', yes, (req, res, next) -> Task.findOneAndUpdate { _id: req.commandRequest.taskId }, { bucket: 'done', updatedAt: Date.now() }, (err, task) -> if err next err else self.notifyBucketUpdate req.commandRequest.bucket, req.commandRequest.taskId res.send status: 'success' usage: -> ":close|:cl|:check|:ck" desc: -> "Mark the current tasks as done. The task is then hidden from the bucket" class MoveTaskToBucketCommand extends Command constructor: -> self = this super ':moveTo', ':mt', yes, (req, res, next) -> Task.findOne _id: req.commandRequest.taskId, (err, task) -> if err next err else if req.commandRequest.bucket oldBucket = task.bucket if oldBucket isnt req.commandRequest.bucket task.update bucket: req.commandRequest.bucket, updatedAt: Date.now(), (err, task) -> if err next err else self.notifyBucketUpdate oldBucket, req.commandRequest.taskId self.notifyBucketUpdate req.commandRequest.bucket, req.commandRequest.taskId res.send status: 'success' else res.send status: 'success' else next() usage: -> ":moveTo|:mt <bucket>" desc: -> "Move the currently selected task to the given bucket" class EmptyBucketCommand extends Command constructor: -> self = this super ':empty!', ':trash!', yes, (req, res, next) -> Task.update { bucket: req.commandRequest.bucket, _owner: req.commandRequest.user._id }, { bucket: 'trash', updatedAt: Date.now() }, { multi: true }, (err) -> if err next err else self.notifyBucketUpdate req.commandRequest.bucket, req.commandRequest.taskId res.send status: 'success' usage: -> ":empty!|:trash! [bucket]" desc: -> "Delete all the tasks inside a bucket. unless the optional [bucket] parameter is given, this command runs on the currently selected bucket" class EmptyAllBucketsCommand extends Command constructor: -> self = this super ':emptyAll!', ':trashAll!', yes, (req, res, next) -> Task.update { bucket: { $nin: ['done', 'trash'] }, _owner: req.commandRequest.user._id }, { bucket: 'trash', updatedAt: Date.now() }, { multi: true }, (err) -> if err next err else self.notifyBucketUpdate 'today', null self.notifyBucketUpdate 'tomorrow', null self.notifyBucketUpdate 'twoDaysFromNow', null self.notifyBucketUpdate 'future', null res.send status: 'success' usage: -> ":emptyAll!|:trashAll!" desc: -> "Apply the :delete command to all the buckets" class DeleteTaskCommand extends Command constructor: -> self = this super ':delete', ':del', ':remove', ':rm', yes, (req, res, next) -> Task.findOneAndUpdate { _id: req.commandRequest.taskId }, { bucket: 'trash', updatedAt: Date.now() }, (err) -> if err next err else self.notifyBucketUpdate req.commandRequest.bucket, req.commandRequest.taskId res.send status: 'success' usage: -> ":delete|:del|:remove|:rm" desc: -> "Delete the currently selected task" class ShiftCommand @shift: (req, res, next, from, to) -> console.log next self = this Task.update { bucket: from, _owner: req.commandRequest.user._id }, { bucket: to, updatedAt: Date.now() }, { multi: true }, (err) -> if err next err else self.notifyBucketUpdate from, null self.notifyBucketUpdate to, null class ShiftBucketCommand extends Command constructor: -> self = this super ':shift!', ':sh!', yes, (req, res, next) -> switch req.commandRequest.bucket when 'tomorrow' ShiftCommand.shift.apply this, [req, res, next, 'tomorrow', 'today'] when 'twoDaysFromNow' ShiftCommand.shift.apply this, [req, res, next, 'twoDaysFromNow', 'tomorrow'] when 'future' ShiftCommand.shift.apply this, [req, res, next, 'future', 'twoDaysFromNow'] res.send status: 'success' usage: -> ":shift!|:sh! [bucket]" desc: -> "Move all the tasks from a bucket to its immediate successor (@2 -> @1, @3 -@2, @4 -> @5). unless the optional [bucket] parameter is given, this command runs on the currently selected bucket" class ShiftAllBucketsCommand extends Command constructor: -> super ':shiftAll!', ':sha!', yes, (req, res, next) -> ShiftCommand.shift.apply this, [req, res, next, 'tomorrow', 'today'] ShiftCommand.shift.apply this, [req, res, next, 'twoDaysFromNow', 'tomorrow'] ShiftCommand.shift.apply this, [req, res, next, 'future', 'twoDaysFromNow'] res.send status: 'success' usage: -> ":shiftAll|:sha!" desc: -> "Apply the :shift command to all the buckets" class LogoutCommand extends Command constructor: -> super ':logout!', ':signout!', yes, (req, res, next) -> req.session.destroy -> res.send status: 'success' redirect: '/' usage: -> ":logout!|:signout!" desc: -> "Close the current user session" class LoginCommand extends Command constructor: -> super ':login', ':signin', no, (req, res, next) -> if req.commandRequest.user res.send status: 'failure' error: 'already logged in' else res.send status: 'success' redirect: '/login' usage: -> ":login|:signin" desc: -> "Redirect to the new user session form" class RegisterCommand extends Command constructor: -> super ':register', ':signup', no, (req, res, next) -> if req.commandRequest.user res.send status: 'failure' error: 'already logged in' else res.send status: 'success' redirect: '/register' usage: -> ":register|:signup" desc: -> "Redirect to the new user registration form" class HelpCommand extends Command constructor: -> super ':help', ':h', ':describe', ':desc', no, (req, res, next) -> res.send status: 'success' help: req.commandRequest.help usage: -> ":help|:h|:describe|:desc [command]" desc: -> "Display the help. if the optional [command] parameter is given then only the help available for it will be displayed" exports.watch = (app) -> commands = [ new NewTaskCommand(), new ChangeTaskCommand(), new CloseTaskCommand(), new MoveTaskToBucketCommand(), new EmptyBucketCommand(), new EmptyAllBucketsCommand(), new DeleteTaskCommand(), new ShiftBucketCommand(), new ShiftAllBucketsCommand(), new LogoutCommand(), new LoginCommand(), new RegisterCommand() ] for command in commands app.use command.middleware() app.use new HelpCommand().middleware() app.use InvalidCommand.middleware()
import { useEffect, useState } from 'react'; import axios from 'axios'; import send from './assets/send.svg'; import bot from './assets/bot.png'; import user from './assets/user.png'; import loaderIcon from './assets/loader.svg'; function App() { const [input, setInput] = useState(); const [posts, setPosts] = useState([]); useEffect(()=>{ document.querySelector(".layout").scrollTop = document.querySelector(".layout").scrollHeight; },[posts]); const fetchBotResp = async () =>{ const data = await axios.post( "https://chatgpt-app-gsa3.onrender.com", { input }, { headers: { "Content-Type":"application/json" } } ); return data; }; const onSubmit = () =>{ if(input.trim() == '') return; updatePosts(input); updatePosts("loading...", false, true); fetchBotResp().then((resp) => { updatePosts(resp.bot.trim(), true); }); }; const autoTypingBot = (text) => { let index = 0; let interval = setInterval(() =>{ if(index < text.length){ setPosts((prevState) => { let LastItem = prevState.pop(); if(LastItem.type !== "bot"){ prevState.push({ type: "bot", post: text.charAt(index-1) }); }else{ prevState.push({ type: "bot", post: LastItem.post + text.charAt(index-1) }); } return [...prevState]; }); }else{ clearInterval(interval); } }); }; const updatePosts = (post, isBot, isLoading) => { if(isBot){ autoTypingBot(post); }else{ setPosts(prevState => { return [ ...prevState, { type: isLoading ? "loading": "user", post } ] }); } }; const onKeyUp = (e) => { if(e.key == "Enter" || e.which === 13){ onSubmit(); } }; return ( <main className='chatGPT-app'> <section className='chat-container'> <div className='layout'> {posts.map((post,index)=> ( <div key = {index} className={`chat-bubble ${post.type === 'bot' || post.type === 'loading' ? "bot" : "" }`}> <div className='avatar'> <img src={post.type === 'bot' || post.type === 'loading' ? bot : user } /> </div> {post.type === "loading" ? ( <div className='loader'> <img src={loaderIcon} /> </div> ) : ( <div className='post'>{post.post}</div> )} </div> )) } </div> </section> <footer> <input value={input} type="text" className="composebar" autoFocus placeholder='Ask Anything!' onChange={(e)=>{ setInput(e.target.value) }} onKeyUp={onKeyUp} /> <div className='send-button' onClick={onSubmit}> <img src={send} /> </div> </footer> </main> ) } export default App
import { useParams } from "react-router-dom" import { request, gql } from "graphql-request" import { useEffect, useState } from "react" const GameHeader = ({ id, name, achievements = [], }: { id: number name: string image: string achievements?: Achievement[] }) => { const min = achievements.reduce<number | undefined>( (min, achievement) => achievement.globalPercentage !== undefined ? min && min < achievement.globalPercentage ? min : achievement.globalPercentage : 0, 0 ) const max = achievements.reduce( (max, achievement) => achievement.globalPercentage !== undefined ? max < achievement.globalPercentage ? achievement.globalPercentage : max : 0, 0 ) return ( <div style={{ display: "flex", alignItems: "center" }}> <div style={{ flexGrow: 1, textAlign: "left" }}> <h3 style={{ margin: 4 }}>{name}</h3> <p style={{ margin: 4 }}> Total Achievements {achievements.length} </p> <p style={{ margin: 4 }}> Difficulty: {min?.toFixed(2)}% to {max.toFixed(2)}% </p> </div> <div style={{ margin: 8, fontSize: "small", alignContent: "flex-start", }} > <a href={`http://store.steampowered.com/app/${id}`} target="_blank" rel="noopener" > View on Steam </a> </div> <div> <img src={`https://media.steampowered.com/steam/apps/${id}/capsule_184x69.jpg`} /> </div> </div> ) } const AchievementItem = ({ displayName, description, iconUrl, globalPercentage, }: Achievement) => { return ( <li style={{ display: "flex", margin: "0.25em" }}> <img src={iconUrl} style={{ width: 64, height: 64 }} /> <div style={{ display: "flex", flexGrow: 1, border: "1px solid white", borderRadius: 5, marginLeft: "0.5em", }} > <div style={{ flexGrow: 1, textAlign: "left", position: "relative", }} > <div style={{ position: "absolute", top: 0, bottom: 0, zIndex: -1, backgroundColor: "#607d8b", margin: "4px", height: "54px", borderRadius: "3px", width: `${globalPercentage ?? 0}%`, }} ></div> <h4 style={{ margin: "0.125em 0 0 0.5em" }}> {displayName} </h4> <p style={{ margin: "0.125em 0 0 0.5em" }}>{description}</p> </div> <div> <span>{globalPercentage?.toFixed(2)}%</span> </div> </div> </li> ) } const GameDetails = ({ game }: { game: Game }) => { return ( <> <GameHeader id={game.id} name={game.name ?? "<noname>"} achievements={game.achievementSet} image={game.iconUrl ?? ""} /> <hr /> <ul style={{ listStyle: "none", padding: 0, margin: 0 }}> {game.achievementSet?.map((achievement) => ( <AchievementItem key={achievement.name} {...achievement} /> ))} </ul> </> ) } const PlayerGameScreen = () => { // const { id } = useParams() const { gameId } = useParams() const [game, setGame] = useState<Game>() const [loading, setLoading] = useState(true) const [error, setError] = useState<string>() useEffect(() => { request<GameResponse>( "/graphql/", gql` { game(id: ${gameId}) { id name imgIconUrl achievementSet { name displayName description iconUrl globalPercentage } } } ` ) .then((resp) => { setLoading(false) setGame(resp.game) }) .catch(() => { setLoading(false) setError("Failed") }) }, [gameId]) let content if (loading) { content = <div>Loading...</div> } else if (game) { content = <GameDetails game={game} /> } else if (error) { content = <div>Error.</div> } return <div>{content}</div> } export default PlayerGameScreen
import gsap from "gsap"; import { ScrollTrigger } from "gsap/ScrollTrigger"; import { MotionPathPlugin } from "gsap/MotionPathPlugin"; import imagesLoaded from "imagesloaded"; gsap.registerPlugin(ScrollTrigger, MotionPathPlugin); const svgs = document.querySelectorAll(".svg-parent"); function initMotionPath() { // Register MotionPathPlugin here to avoid multiple registrations gsap.registerPlugin(MotionPathPlugin, ScrollTrigger); ScrollTrigger.normalizeScroll(true); // declare an array to store tweens let tweens = []; // function to create and manage tweens function createTweens(svgs) { // destroy existing tweens tweens.forEach((tween) => { tween && tween.kill(); }); tweens = []; // iterate over each SVG svgs.forEach((svg, i) => { let startPosition = "0%"; i > 0 ? (startPosition = "60%") : (startPosition = "0%"); const movingIcon = svg.querySelector("#moving-icon"); let svgPath = null; if (window.innerWidth >= 480) { // Desktop svgPath = svg.querySelector(".path-container.is-desktop path"); } else { // Mobile svgPath = svg.querySelector(".path-container.is-mobile path"); } // Set the transform origin and offsets before animating gsap.set(movingIcon, { xPercent: -50, // Center horizontally yPercent: -50, // Center vertically transformOrigin: "50% 50%", // Set the transform origin to the center }); const tween = gsap.to(movingIcon, { motionPath: { path: svgPath, align: svgPath, autoRotate: true, alignOrigin: [0.5, 0.5], offsetX: 0, offsetY: 0, start: 0, //end: 1, }, ease: "none", scrollTrigger: { trigger: svg, start: `top ${startPosition}`, end: "bottom 80%", scrub: 2.5, }, }); tweens.push(tween); }); } // Call createTweens on DOMContentLoaded document.addEventListener("DOMContentLoaded", function () { imagesLoaded(".page-wrapper", () => { createTweens(svgs); }); }); function debounce(func, delay) { let timeoutId; return function () { const context = this; const args = arguments; clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(context, args); }, delay); }; } // Create a debounced version of the resize function const debouncedResize = debounce(function () { createTweens(svgs); }, 200); // Adjust the delay as needed // Update tweens on window resize, using the debounced version window.addEventListener("resize", debouncedResize); } // Call initMotionPath to initialize motion paths initMotionPath();
import { useState, useEffect, createContext } from 'react'; // const addCartItems = (cartItems, productsToAdd) => { // // find if cartItems contains productsToAdd, basically to check if it's already in cart // const existingCartItem = cartItems.find( // (cartItem) => cartItem.id === productsToAdd.id, // ); // // If found increment quantity, basically add items to cart // if (existingCartItem) { // return cartItems.map((cartItem) => // cartItem.id === productsToAdd.id // ? { ...cartItem, quantity: cartItem.quantity + 1 } // : cartItem, // ); // } // // return new array with modified cart items/ new array with items added // return [...cartItems, { ...productsToAdd, quantity: 1 }]; // }; const addCartItems = (cartItems, productsToAdd) => { const existingItems = cartItems.find( (cartItem) => cartItem.id === productsToAdd.id, ); if (existingItems) { return cartItems.map((cartItem) => cartItem.id === productsToAdd.id ? { ...cartItem, quantity: cartItem.quantity + 1 } : { cartItem }, ); } return [...cartItems, { ...productsToAdd, quantity: 1 }]; }; export const CartContext = createContext({ isCartOpen: false, setIsCartOpen: () => {}, cartItems: [], addItemsToCart: () => {}, cartCount: 0, }); export const CartProvider = ({ children }) => { const [isCartOpen, setIsCartOpen] = useState(false); const [cartItems, setCartItems] = useState([]); const [cartCount, setCartCount] = useState(0); useEffect(() => { const newCartCount = cartItems.reduce( (total, cartItem) => total + cartItem.quantity, 0, ); setCartCount(newCartCount); }, [cartItems]); const addItemsToCart = (productsToAdd) => { setCartItems(addCartItems(cartItems, productsToAdd)); }; const value = { isCartOpen, setIsCartOpen, addItemsToCart, cartItems, cartCount }; return ( <CartContext.Provider value={value}> {children} </CartContext.Provider> ); };
import 'package:dio/dio.dart'; import 'dart:developer' as developer; /// 请求方法 enum DioMethod { get, post, put, delete, patch, head, } class DioUtil { /// 单例模式 static DioUtil? _instance; factory DioUtil() => _instance ?? DioUtil._internal(); static DioUtil? get instance => _instance ?? DioUtil._internal(); /// 连接超时时间 static const Duration connectTimeout = Duration(seconds: 60000); /// 响应超时时间 static const Duration receiveTimeout = Duration(seconds: 60000); /// Dio实例 static Dio _dio = Dio(); /// 初始化 DioUtil._internal() { // 初始化基本选项 BaseOptions options = BaseOptions( baseUrl: 'https://m.douban.com/', connectTimeout: connectTimeout, receiveTimeout: receiveTimeout, headers: {'mobile': true, 'appverion': '1111', 'appname': 'flutter'}); _instance = this; // 初始化dio _dio = Dio(options); openLog(); // 添加拦截器 _dio.interceptors.add(InterceptorsWrapper( onRequest: _onRequest, onResponse: _onResponse, onError: _onError)); } /// 请求拦截器 void _onRequest(RequestOptions options, RequestInterceptorHandler handler) { developer.log('请求拦截'); // 头部添加token options.headers["token"] = "xxx"; // 更多业务需求 handler.next(options); // super.onRequest(options, handler); } /// 相应拦截器 void _onResponse( Response response, ResponseInterceptorHandler handler) async { // 请求成功是对数据做基本处理 if (response.statusCode == 200) { // .... } else { // .... } if (response.requestOptions.baseUrl.contains("???????")) { // 对某些单独的url返回数据做特殊处理 } handler.next(response); } /// 错误处理 void _onError(DioError error, ErrorInterceptorHandler handler) { handler.next(error); } /// 请求类 Future<T> request<T>( String path, { DioMethod method = DioMethod.get, Map<String, dynamic>? params, data, CancelToken? cancelToken, Options? options, ProgressCallback? onSendProgress, ProgressCallback? onReceiveProgress, }) async { const methodValues = { DioMethod.get: 'get', DioMethod.post: 'post', DioMethod.put: 'put', DioMethod.delete: 'delete', DioMethod.patch: 'patch', DioMethod.head: 'head' }; options ??= Options(method: methodValues[method]); try { Response response; response = await _dio.request(path, data: data, queryParameters: params, cancelToken: cancelToken, options: options, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress); return response.data; } on DioError catch (e) { rethrow; } } /// 开启日志打印 /// 需要打印日志的接口在接口请求前 DioUtil.instance?.openLog(); void openLog() { _dio.interceptors .add(LogInterceptor(responseHeader: false, responseBody: true)); } }
import random import numpy as np import time class Network: def __init__(self, sizes): """Initializes the network. "sizes" is a list with number of neurons per layer.""" self.sizes = sizes self.num_layers = len(sizes) # The whole network has a list of np vectors as biases (vecotr per layer) self.biases = [np.random.randn(y, 1) for y in sizes[1:]] # The whole network has a list of np matrices as weights (matrix per layer) self.weights = [np.random.randn(x, y) for x, y in zip(sizes[1:], sizes[:-1])] def __repr__(self): return f"Network({self.sizes})" def correct_input(self, input): '''Cheks if the input vecotr is the correct type and dim.''' if len(input) != self.sizes[0]: # Check the length return False if not isinstance(input, np.ndarray): # Check if it a NP vector (array) input = np.array(input) return True def feedforward(self, input, correct=None): """Runs the input a through the whole network.""" if (correct is None) or (correct is False): if not self.correct_input(input): return f"Your vector size is {len(input)}, instead of {len(self.sizes[0])}." layer_value = input for W, b in zip(self.weights, self.biases): layer_value = sigma_fun(W.dot(layer_value) + b) return layer_value def SGD(self, training_data, epochs, mini_batch_size, learning_rate, test_data=None, num=None): '''The learning algorythm for the network.''' training_data_size = len(training_data) if test_data is not None: num = len(test_data) accuracy_progression = [] # Batch the data and run through all the epochs for epoch in range(epochs): if test_data is not None: start_time = time.time() random.shuffle(training_data) for i in range(training_data_size // mini_batch_size): batch = training_data[i*mini_batch_size : (i+1)*mini_batch_size] self.update_mini_batch(batch, learning_rate) if test_data is not None: accuracy = self.evaluate(test_data, num) epoch_time = time.time() - start_time print(f'Epoch {epoch + 1}/{epochs} complete, accuracy is {accuracy}') accuracy_progression.append((accuracy, epoch, epoch_time)) else: print(f'Epoch {epoch + 1}/{epochs} complete.') if test_data is not None: self.accuracy = accuracy_progression def update_mini_batch(self, mini_batch, learning_rate): '''Applies gradient descent to the given batch.''' gradient_b = [np.zeros(b.shape) for b in self.biases] gradient_W = [np.zeros(W.shape) for W in self.weights] for x, y in mini_batch: delta_gradient_b, delta_gradient_W = self.backprop(x, y) # Update the weights and biases for i, delta_grad in enumerate(delta_gradient_b): gradient_b[i] += delta_grad for i, delta_grad in enumerate(delta_gradient_W): gradient_W[i] += delta_grad # Apply the gradient descent to the network for i, elt in enumerate(self.biases): self.biases[i] = elt - ((learning_rate / len(mini_batch)) * gradient_b[i]) for i, elt in enumerate(self.weights): self.weights[i] = elt - ((learning_rate / len(mini_batch)) * gradient_W[i]) def backprop(self, x, y): '''Calculates the gradient of the cost function with the backpropagation algorythm.''' gradient_b = [np.zeros(b.shape) for b in self.biases] gradient_W = [np.zeros(W.shape) for W in self.weights] # Feedforward (different to the method because we need more information) activation = x activations = [x] # Each layer stores its activations pre_sigmoid_act = [] for W, b in zip(self.weights, self.biases): activation = W.dot(activation) + b pre_sigmoid_act.append(activation) activation = sigma_fun(activation) activations.append(activation) # Output layer error delta = self.cost_fun_derivative(activations[-1], y) * sigma_fun_derivative(pre_sigmoid_act[-1]) gradient_W[-1] = delta.dot(activations[-2].transpose()) gradient_b[-1] = delta # Backpropagation through the layers for l in range(2, self.num_layers): z = pre_sigmoid_act[-l] a = sigma_fun_derivative(z) W_T = self.weights[-l+1].transpose() delta = W_T.dot(delta) * a gradient_W[-l] = delta.dot(activations[-l-1].transpose()) gradient_b[-l] = delta return gradient_b, gradient_W def cost_fun_derivative(self, out_activations, y): '''Derivative of the standard cost function for a single training example.''' return out_activations - y def evaluate(self, test_data, num): '''Evaluates the performace of the neural network.''' random.shuffle(test_data) test_batch = test_data[0:num] # The 'guess' of the network is the highes activation in the last layer result = [(np.argmax(self.feedforward(x)), y) for x, y in test_batch] return list(sum([y[x] == 1 for x, y in result]) / len(test_batch))[0] # Other functions def sigma_fun(x): x = np.clip(x, -100, 100) return 1 / (1 + np.exp(-x)) def sigma_fun_derivative(x): # Not stable if the derivate is calculated by hand return sigma_fun(x) * (1 - sigma_fun(x)) # Works on vectors
import { createCustomElement } from "./sw/custom-element.js"; import MDParser from "./sw/md.js"; import { warning } from "./sw/parser.js"; /** * @typedef {Object} ElementDescriptor * @property {string} template * @property {string} name * @property {Object.<string, any> & HTMLElement } props * @property {boolean} markdown * @property {Array<string>} watched */ /** * * @param {string} name */ const checkNameValidity = ( name )=>{ return name.match(/[-.\d_a-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]+-[-.\d_a-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]+/) } /**@param {ElementDescriptor} descriptor */ export const define = ( descriptor )=>{ if( !checkNameValidity( descriptor.name ) ){ warning(` name ${descriptor.name} is not a valid name. See https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name for the correct specifications`); return; } if( descriptor.markdown ){ descriptor.template = new MDParser(descriptor.template).toHTML(); } createCustomElement( descriptor.name, descriptor.template, descriptor.props, descriptor.watched ); } /** * create new component * @param {string} name * @returns {HTMLCustomElement} */ export const create = (name)=>{ return CustomElementRegistry.create(name); } /** * create and append new component * @param {string} name * @param {Record<string,string>} props * @param {HTMLElement} node * @returns {HTMLCustomElement | undefined} */ export const append = (name, props = {}, node = document.body)=>{ const el = CustomElementRegistry.create(name); if( !el ) return; node.appendChild(el); for( let [k,v] of Object.entries(props) ){ if( v instanceof Array ) el.setArray(k,v); else el.setAttribute(k,v); } return el; }
#para descomponer una serie de tiempo graficamente se utiliza #una funcion que se llama decompose, por lo que primero #es importante reconocer la serie de tiempo y despues aplicarle la funcion #graficamente desoc<-sample (3:8, 44, replace=T) tdesoc<-ts(desoc, frequency = 4, start=2005) #muestra tendencia, temporalidad.. plot(decompose(tdesoc)) plot(tdesoc) #llamamos la base tiie<-(read.csv(("C:\\Users\\SalaD-10\\Downloads\\TIIE2015.csv"))) View(tiie) ttiie<-ts(tiie, frequency = 52, start=2005) #muestra tendencia, temporalidad.. plot(decompose(ttiie)) plot(ttiie) #llamamos la base pib<-read.csv(("C:\\Users\\SalaD-10\\Downloads\\PIB México1.csv")) View(pib) #serie de tiempo spib<-ts(pib, frequency = 4, start=2007) plot(spib) ##muestra tendencia, temporalidad..suaviza la tendencia plot(decompose(spib)) View(spib) summary(spib) names(spib$trend) #descomponemos la serie y le ponemos un nombre depibst<-decompose(spib) names(depibst) depibst$trend depibst$seasonal depibst$random ***************** #Ejercicio descomponer una serie de tiempo #1)graficamente y 2)mandar llamar cada uno ##de los componentes de la serie de tiempo #realizar una interpretacion sobre los datos #observados de la serie de tiempo #serie 1=consumo de bienes y servicios de #mx anuales [renglon 9:43, columna k] #1)graficamente bienes<-read.csv(("C:\\Users\\SalaD-10\\Downloads\\bienes.csv")) View(bienes) sbien<-ts(bienes, frequency = 12, start=2014) plot(sbien) #1)graficamente plot(decompose(sbien)) View(spib) summary(spib) names(spib$trend) #descomponemos la serie y le ponemos un nombre depibst<-decompose(spib) names(depibst) depibst$trend depibst$seasonal depibst$random #Ejercicio descomponer una serie de tiempo #1)graficamente y 2)mandar llamar cada uno #de los componentes de la serie de tiempo #realizar una interpretacion sobre los datos #observados de la serie de tiempo #serie 1=consumo de bienes y servicios de #mx anuales [renglon 9:43, columna k] #1)graficamente bienes<-read.csv(("C:\\Users\\SalaD-10\\Downloads\\bienes.csv")) View(bienes) sbien<-ts(bienes, frequency = 12, start=2014) plot(sbien) #1)graficamente plot(decompose(sbien))
import { useEffect, useLayoutEffect, useMemo } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import styled from 'styled-components'; import withLoader from 'hoc/withloader'; import Prospectus from './Prospectus'; import Curriculum from './Curriculum'; import BoardofSchool from './BoardofSchool'; import { LoaderProps } from 'typings'; import ImageSlider from './ImageSlider'; import Video from './Video'; import { fetchHomePageData } from 'store/actions/home.actions'; import homeContainerStyles from 'styles/home/home.styles'; import { RootState } from 'store'; const HomeContainer = styled.div` ${homeContainerStyles} `; const Home: React.FC<LoaderProps> = ({ setLoading }) => { const rootState = useSelector((state: RootState) => state); const { home, common } = rootState; const hideLoader = useMemo( () => Object.keys(home).length && Object.keys(common).length ? true : false, [home, common] ); const dispatch = useDispatch(); useEffect( () => { dispatch(fetchHomePageData()); }, //eslint-disable-next-line [] ); useLayoutEffect( () => { if (hideLoader) setLoading(false); }, //eslint-disable-next-line [hideLoader] ); return hideLoader ? ( <HomeContainer className='w-screen min-h-screen'> <ImageSlider /> <Prospectus /> <Video /> <Curriculum /> <BoardofSchool /> </HomeContainer> ) : null; }; export default withLoader(Home);
import { MigrationInterface, QueryRunner, TableColumn, TableForeignKey, } from 'typeorm'; export default class AlterProviderFieldToProviderId1598528415267 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.dropColumn('appointments', 'provider'); await queryRunner.addColumn( 'appointments', new TableColumn({ name: 'provider_id', type: 'uuid', isNullable: true, }) ); await queryRunner.createForeignKey( 'appointments', new TableForeignKey({ name: 'appointment_provider', columnNames: ['provider_id'], referencedColumnNames: ['id'], referencedTableName: 'users', onDelete: 'SET NULL', onUpdate: 'CASCADE', }) ); } public async down(queryRunner: QueryRunner): Promise<void> { // As alterações precisam ser desfeitas no sentido reverso, pois se a coluna de provider_id // for deletada antes da foreignKey, não há mais como deletar essa foreignKey await queryRunner.dropForeignKey('appointments', 'appointment_provider'); await queryRunner.dropColumn('appointments', 'provider_id'); await queryRunner.dropColumn( 'appointments', new TableColumn({ name: 'provider', type: 'varchar', }) ); } }
<?php namespace App\Http\Controllers; use App\Models\Course; use App\Models\Course_User; use App\Models\Requirement; use App\Models\Curriculum; use App\Models\Outcome; use Illuminate\Http\Request; use Illuminate\Support\Str; use DB; use Alert; use Redirect; class CourseAdminController extends Controller { // Use Tabel Course public function __construct() { $this->middleware('admin'); } // Tampil Admin public function index(){ return view('admin.course_course',[ "title" => "Courses - Manage Course", "data" => Course::with('kategori')->get(), "nama" => auth()->user()->name, ]); } // Tampilan Tambah Course public function create(){ return view('admin.course_tambahcourse',[ "title" => "Courses - Tambah Course", "nama" => auth()->user()->name, "kategori" => DB::table('categories')->get(), ]); } // Simpan Data Course public function store(Request $request){ $validatedData=$request->validate([ 'title' => 'required', 'short_description' => 'required', 'category' => 'required', 'description' => 'required', 'level' => 'required', 'requirements' => 'required', 'outcomes' => 'required', 'gambar' => 'required', ]); // return redirect("/course/create"); $c = new Course; $c->title = $request->title; $c->short_description = $request->short_description; $c->description = $request->description; $c->category = $request->category; $c->level = $request->level; $c->instructor = 0; // STORE GAMBAR // $name = $request->file('gambar')->getClientOriginalName(); $name=Str::random(15).'.'.$request->file('gambar')->extension(); $path = $request->file('gambar')->storeAs('public/uploads/course',$name); $c->gambar = $name; // // TOP COURSE if($request->is_topcourse == 1) $c->is_topcourse = 1; else $c->is_topcourse = 0; // // ALLOW ENROLL if($request->allow_enroll == 1) $c->allow_enroll = 1; else $c->allow_enroll = 0; // // FREE if($request->is_free == 1) $c->price = 0; else if($request->discount == 1){ if($request->discount_price === null) $request->discount_price=0; $c->price = $request->price - $request->discount_price; } else $c->price = $request->price; // INSERT $c->save(); // BEDA TABEL // REQUIREMENTS foreach($request->requirements as $req){ Requirement::create([ 'name' => $req, 'course' => $c->id ]); } // OUTOMES foreach($request->outcomes as $out){ Outcome::create([ 'name' => $out, 'course' => $c->id ]); } toast('Your data has been submited!','success'); // dd($request->all()); return redirect("/course"); // untuk diarahkan kemana } // Tampilan Edit public function edit($id){ return view("admin.course_editcourse",[ 'title' => 'Courses - Edit Course', 'item' => Course::find($id), "nama" => auth()->user()->name, "kategori" => DB::table('categories')->get(), "instructor" => DB::table('users')->where('is_admin', '=', 2)->get(), "req" => DB::table('requirements')->where('course', '=', $id)->get(), "out" => DB::table('outcomes')->where('course', '=', $id)->get(), "cur" => DB::table('curricula')->where('course', '=', $id)->get(), "pertemuan" => Curriculum::select('pertemuan', DB::raw('count(*) as total'))->where('course', '=', $id) ->groupBy('pertemuan')->get(), ]); } // Simpan Hasil Edit public function update(Request $request, $id){ $validatedData=$request->validate([ 'title' => 'required', 'short_description' => 'required', 'category' => 'required', 'description' => 'required', 'level' => 'required', 'requirements' => 'required', 'outcomes' => 'required', ]); Requirement::where('course', '=', $id)->delete(); Outcome::where('course', '=', $id)->delete(); // return redirect("/course/create"); $c = Course::find($id); $c->title = $request->title; $c->short_description = $request->short_description; $c->description = $request->description; $c->category = $request->category; $c->level = $request->level; $c->instructor = $request->instructor; // STORE GAMBAR if ($request->hasFile('gambar')) { $name=$c->gambar; $path = $request->file('gambar')->storeAs('public/uploads/course',$name); $c->gambar = $name; } // // TOP COURSE if($request->is_topcourse == 1) $c->is_topcourse = 1; else $c->is_topcourse = 0; // // ALLOW ENROLL if($request->allow_enroll == 1) $c->allow_enroll = 1; else $c->allow_enroll = 0; // // FREE if($request->is_free == 1) $c->price = 0; else if($request->discount == 1){ if($request->discount_price === null) $request->discount_price=0; $c->price = $request->price - $request->discount_price; } else $c->price = $request->price; // INSERT $c->save(); // BEDA TABEL // REQUIREMENTS foreach($request->requirements as $req){ Requirement::create([ 'name' => $req, 'course' => $c->id ]); } // OUTOMES foreach($request->outcomes as $out){ Outcome::create([ 'name' => $out, 'course' => $c->id ]); } toast('Your data has been updated!','success'); // dd($request->all()); return redirect("/course"); // untuk diarahkan kemana } // Hapus Data Course public function destroy(Request $request, $id){ Course::destroy($id); // Session::flash('hapussuccess', 'Data berhasil dihapus!'); toast('Your data has been deleted!','success'); return redirect("/course"); // untuk diarahkan kemana } // Add Section // Simpan Hasil Edit public function addsection(Request $request, $id){ $validatedData=$request->validate([ 'section' => 'required|min:5', ]); // Menyimpan update $user = User::find($id); $user->name = $request->name; $user->email = $request->email; $user->save(); toast('Your data has been saved!','success'); return redirect("/course"); // untuk diarahkan kemana } // ADD LESSON public function addLesson(Request $request, $id){ $validatedData=$request->validate([ 'pertemuan' => 'required', 'materi' => 'required', 'jenis' => 'required', ]); $validatedData['course']=$id; if($validatedData['jenis'] !== 'Youtube Video'){ // STORE MATERI $name=Str::random(15).'.'.$request->file('materi')->extension(); $path = $request->file('materi')->storeAs('public/uploads/materi',$name); $validatedData['materi'] = $name; } // dd($request->all()); Curriculum::create($validatedData); //untuk menyimpan data toast('Your data has been added!','success'); return \Redirect::back(); } public function detailCourseAdmin($id) { return view('admin.course_detailcourse', [ "course" => Course::with('instruktur')->find($id), "title" => 'Courses - Detail Course', "nama" => auth()->user()->name, ]); } }
<template> <el-card style="width: 500px; margin: 100px auto"> <el-form label-width="80px" size="small"> <el-form-item label="用户名"> <el-input v-model="form.username" disabled autocomplete="off"></el-input> </el-form-item> <el-form-item label="昵称"> <el-input v-model="form.nickname" autocomplete="off"></el-input> </el-form-item> <el-form-item label="邮箱"> <el-input v-model="form.email" autocomplete="off"></el-input> </el-form-item> <el-form-item label="电话"> <el-input v-model="form.phone" autocomplete="off"></el-input> </el-form-item> <el-form-item label="地址"> <el-input type="textarea" v-model="form.address" autocomplete="off"></el-input> </el-form-item> <el-form-item style="text-align: center"> <el-button type="primary" @click="save">确 定</el-button> </el-form-item> </el-form> </el-card> </template> <script> import request from "@/utils/request"; export default { name: "Person", data(){ return{ form: {}, user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {} } }, created() { // this.request.get("/user/username/"+this.user.username).then(res => { // if(res.code === '200'){ // this.form = res.data // } // }) this.getUser().then(res => { this.form = res }) }, methods: { // ---------- async getUser(){ return (await this.request.get("/user/username/"+this.user.username)).data }, save(){ request.post("/user", this.form).then(res=>{ if(res.data){ this.$message.success("保存成功") //触发父级更新User的方法 this.$emit("refreshUser") //更新浏览器存储的用户信息--------------------- this.getUser().then(res => { res.token = JSON.parse(localStorage.getItem("user")).token localStorage.setItem("user", JSON.stringify(res)) }) }else{ this.$message.error("保存失败") } }) }, } } </script> <style scoped> </style>
function ExperienceSurveyForm(props) { const { title, consumptionMethod, dose, description } = props.data; return ( <div className="container"> <div> <hr></hr> <h6> <i> *Please complete your <a href="https://www.opencann.net/#/opencann.near/widget/profile.edit" target="_blank" rel="noopener noreferrer" > profile </a>{" "} and <a href="https://www.opencann.net/#/opencann.near/widget/profile.demographics" target="_blank" rel="noopener noreferrer" > demographics </a> before starting. </i> </h6> <hr></hr> <h4>Cannabis Experience Report</h4> <p> Instructions: describe one (1) experience you had with cannabis.{" "} <b>OpenCann is designed to support anonymity</b>. Only include as much detail as you feel comfortable having associated with your{" "} <a href="https://www.opencann.net/#/opencann.near/widget/profile.edit" target="_blank" rel="noopener noreferrer" > profile </a>{" "} . </p> <div className="mb-3"> <label class="form-label" for="title"> Title Your Report </label> <input class="form-control" id="title" value={props.data.title} onChange={onTitleChange} placeholder="e.g. My First Cannnabis Experience" /> </div> <div className="mb-3"> <Widget src="nearhorizon.near/widget/Inputs.MultiSelect" props={{ data: props.data.consumptionMethod, onChange: onConsumptionMethodChange, height: "250px", options: substance.consumptionMethod, label: "How did you consume cannabis?", placeholder: "Select all methods that apply.", }} /> </div> <div className="mb-3"> <label class="form-label" for="dose"> Estimated Dose </label> <input class="form-control" id="dose" value={props.data.dose} onChange={onDoseChange} placeholder="Describe as best as possible" /> </div> <div className="mb-3"> <label class="form-label" for="otherSubstances"> Other Substances Taken </label> <input class="form-control" id="otherSubstances" value={props.data.otherSubstances} onChange={onOtherSubstancesChange} placeholder="Other Substances Taken" /> </div> <div className="mb-3"> <label class="form-label" for="description"> Describe Your Experience </label> <Widget src="efiz.near/widget/every.markdown.create" props={{ data: props.data.description, onChange: onDescriptionChange, height: "250px", }} /> </div> <div className="mb-3"> <label class="form-label" for="setSetting"> Set and Setting </label> <Widget src="efiz.near/widget/every.markdown.create" props={{ data: props.data.setSetting, onChange: onSetSettingChange, height: "250px", }} /> </div> <div className="row mb-3"> <div className="col"> <label for="start">Experience Start Date</label> <input class="form-control" id="start" type="date" value={props.data.start} onChange={onStartChange} /> </div> <div className="col"> <label for="startTime">Experience Start Time</label> <input class="form-control" id="startTime" type="time" value={props.data.startTime} onChange={onStartTimeChange} /> </div> </div> <div className="row mb-3"> <div className="col"> <label for="end">Experience End Date</label> <input class="form-control" id="end" type="date" value={props.data.end} onChange={onEndChange} /> </div> <div className="col"> <label for="endTime">Experience End Time</label> <input class="form-control" id="endTime" type="time" value={props.data.endTime} onChange={onEndTimeChange} /> </div> </div> <div className="mb-3"> <label class="form-label" for="location"> Geographic Region </label> <input class="form-control" id="location" value={props.data.location} onChange={onLocationChange} placeholder="Where did your experience take place?" /> </div> <hr></hr> <h5>Perceived Effects</h5> <p></p> <div className="mb-3"> <Widget src="nearhorizon.near/widget/Inputs.MultiSelect" props={{ data: props.data.physicalEffects, onChange: onPhysicalEffectsChange, height: "250px", options: props.cannabis.physicalEffects, label: "Physical Effects", placeholder: "Select all that apply.", }} /> </div> <div className="mb-3"> <Widget src="nearhorizon.near/widget/Inputs.MultiSelect" props={{ data: props.data.visualEffects, onChange: onVisuallEffectsChange, height: "250px", options: props.cannabis.visualEffects, label: "Visual Effects", placeholder: "Select all methods that apply.", }} /> </div> <div className="mb-3"> <Widget src="nearhorizon.near/widget/Inputs.MultiSelect" props={{ data: props.data.auditoryEffects, onChange: onAuditoryEffectsChange, height: "250px", options: props.substance.auditoryEffects, label: "Auditory Effects", placeholder: "Select all methods that apply.", }} /> </div> <div className="mb-3"> <Widget src="nearhorizon.near/widget/Inputs.MultiSelect" props={{ data: props.data.cognitiveEffects, onChange: onCognitiveEffectsChange, height: "250px", options: props.substance.cognitiveEffects, label: "Cognitive Effects", placeholder: "Select all methods that apply.", }} /> </div> <div className="mb-3"> <Widget src="nearhorizon.near/widget/Inputs.MultiSelect" props={{ data: props.data.multisensoryEffects, onChange: onMultiSensoryEffectsChange, height: "250px", options: props.substance.multisensoryEffects, label: "Multi-sensory Effects", placeholder: "Select all methods that apply.", }} /> </div> <hr></hr> <h5>Product Information</h5> <p></p> <div className="mb-3"> <label class="form-label" for="productName"> Product Name/Description </label> <input class="form-control" id="productName" value={props.data.productName} onChange={onProductNameChange} placeholder="Product Name/Description" /> </div> <div className="mb-3"> <label class="form-label" for="brandName"> Brand Name (if available) </label> <input class="form-control" id="brandName" value={props.data.brandName} onChange={onBrandNameChange} placeholder="Brand Name (if available)" /> </div> <div></div> <div className="mb-3"> <label class="form-label" for="batchNumber"> Batch Number </label> <input class="form-control" id="batchNumber" value={props.data.batchNumber} onChange={onBatchNumberChange} placeholder="Batch Number" /> </div> <div className="mb-3"> <label class="form-label" for="link"> Link to Product/Strain </label> <input class="form-control" id="link" type="url" value={props.data.link} onChange={onLinkChange} placeholder="Link to Product/Strain" /> </div> <div className="mb-3 row "> <div className="col"> <label>Photo of Product(s) Consumed</label> <Widget src="near/widget/ImageEditorTabs" props={{ image: props.data.logo, onChange: onLogoChange }} /> </div> <div className="col"> <label>Product Manufacturer Logo</label> <Widget src="near/widget/ImageEditorTabs" props={{ image: props.data.background, onChange: onBackgroundChange }} /> </div> </div> <hr></hr> <div className="mb-3"> <label for="hashtags"> <p> Hashtags:{" "} {props.data.hashTags.length !== 0 && props.data.hashTags.map((item) => ( <> <span className="badge text-bg-primary"> {item}{" "} <i className="bi bi-x ms-2 p-1" onClick={() => onHashTagRemove(item)} ></i> </span>{" "} </> ))} </p> </label> <div className="mb-3 d-flex gap-3"> <input id="hashtags" value={props.data.tempHash} onChange={onTempHashChange} placeholder="New Response Tags" /> <button onClick={onHashTagAdd}>Add</button> </div> <div className="mb-3"> <label for="organizer">Form Creator: </label> <a href="https://opencann.near.social" target="_blank" rel="noopener noreferrer" > opencann.near </a> </div> <div className="mb-3"> <label for="daoId">DAO ID: </label> <a href="https://explorer.near.org/accounts/cannabis-genome.sputnik-dao.near" target="_blank" rel="noopener noreferrer" > cannabis-genome.sputnik-dao.near </a> </div> </div> <div className="mb-3"> <button onClick={handleNewResponse}>Submit Response</button> <button onClick={clearFields}>Clear Fields</button> </div> </div> </div> ); } //return <ExperienceSurveyForm />; return { ExperienceSurveyForm };
/** * Created by Hussain on 2/4/2023 * */ package com.hsn.pianotiles.handler import android.graphics.Canvas import android.os.CountDownTimer import com.hsn.pianotiles.core.Tile import com.hsn.pianotiles.core.TileType import com.hsn.pianotiles.utils.Constants import com.hsn.pianotiles.utils.Util import com.hsn.pianotiles.utils.ViewPortHandler import java.util.Timer import java.util.TimerTask import kotlin.math.roundToInt import kotlin.random.Random class ClassicTilesBoardHandler( private val iTileCallback: ITileCallback, private val gameType: GameType ) : ITile { private var tiles = ArrayList<ArrayList<Tile>>() private val rows = 4 private val cols = 4 private var viewPortHandler: ViewPortHandler = ViewPortHandler(0, 0) private var isStart = true private var gameOver: Boolean = false private var score: Float = 0f private var timer = Timer() private val rowMax: Int get() { return when (gameType) { GameType.CLASSIC -> 50 GameType.ARCADE -> Int.MAX_VALUE GameType.ZEN -> Int.MAX_VALUE GameType.RELAY -> Int.MAX_VALUE GameType.RUSH -> Int.MAX_VALUE GameType.COLOR -> 50 } } private var rowCreated = rows private val gameOverTimer: CountDownTimer? get() { return when (gameType) { GameType.ZEN -> object : CountDownTimer(Constants.ZEN_TIME * 1000L, 150L) { override fun onTick(time: Long) { score = (time / 1000f) iTileCallback.updateScore(getScore()) if (gameOver) { cancel() } } override fun onFinish() { setGameOver() } } GameType.RELAY -> object : CountDownTimer(Constants.RELAY_TIME * 1000L, 150L) { override fun onTick(time: Long) { score = (time / 1000f) iTileCallback.updateScore(getScore()) if (gameOver) { cancel() } } override fun onFinish() { setGameOver() } } else -> null } } private val scoreUpdateTask: TimerTask get() = object : TimerTask() { override fun run() { score += 1 iTileCallback.updateScore(getScore()) } } override fun initializeTiles() { tiles.clear() for (i in 0 until rows) { val newTiles = ArrayList<Tile>() val r = Random.nextInt(0, rows) for (j in 0 until cols) { val type = if (r == j) TileType.BLACK else TileType.WHITE val tile = Tile(type, viewPortHandler, rows, cols) newTiles.add(tile) tile.setFirstTile(i == rows - 1 && type == TileType.BLACK) } tiles.add(newTiles) } } override fun setViewPortHandler(viewPortHandler: ViewPortHandler) { this.viewPortHandler = viewPortHandler initializeTiles() } override fun getTiles(): ArrayList<ArrayList<Tile>> { return tiles } override fun getRows(): Int { return rows } override fun getCols(): Int { return cols } override fun isBegin(): Boolean { return isStart } override fun checkTilesClicked(x: Int, y: Int) { if (gameOver) return val yMax = if (isBegin()) cols - 1 else cols - 2 if (y < yMax) return if (tiles[y][x].tileType == TileType.BLACK) { tiles[y][x].clicked() if (isBegin()) { isStart = false iTileCallback.setGameBegin() beginScoreUpdateTask() } } } private fun beginScoreUpdateTask() { when (gameType) { GameType.ZEN, GameType.RELAY -> gameOverTimer?.start() else -> { timer.scheduleAtFixedRate(scoreUpdateTask, 0, 1) } } } override fun checkWhiteTileClicked(x: Int, y: Int): Boolean { if (gameOver) return false if (tiles[y][x].tileType == TileType.WHITE) { tiles[y][x].clicked() return true } else { return false } } override fun getScore(): String { return when (gameType) { GameType.ZEN, GameType.RELAY -> { score.toString() } else -> { String.format("%.3f", score / 1000) } } } override fun setGameOver() { gameOver = true iTileCallback.setGameOver() timer.cancel() scoreUpdateTask.cancel() } override fun isGameOver(): Boolean = gameOver private fun removeLastRowAddAtTop() { if (gameOver) return tiles.removeAt(rows - 1) val newTiles = ArrayList<Tile>() if (rowCreated < rowMax) { val r = Random.nextInt(0, 4) for (i in 0 until 4) { val type = if (i == r) TileType.BLACK else TileType.WHITE newTiles.add(Tile(type, viewPortHandler, rows, cols)) } tiles.add(0, newTiles) rowCreated++ } else { for (i in 0 until 4) { val type = TileType.EMPTY newTiles.add(Tile(type, viewPortHandler, rows, cols)) } tiles.add(0, newTiles) } } override fun next() { if (!isGameOver()) { var twoTilesClicked = 0 for (r in tiles.size - 2 until tiles.size) { for (tile in getTiles()[r]) { if (tile.tileType == TileType.BLACK && tile.isClicked()) { twoTilesClicked++ } } } if (twoTilesClicked == 2) { removeLastRowAddAtTop() } } } override fun reset() { isStart = true gameOver = false score = 0f rowCreated = 0 scoreUpdateTask.cancel() timer.cancel() timer.purge() timer = Timer() initializeTiles() iTileCallback.updateScore(getScore()) } override fun draw(canvas: Canvas) { val tiles = getTiles() val rows = tiles.size val cols = tiles[0].size var xpos = 0 for (i in 0 until rows) { var ypos = 0 for (j in 0 until cols) { tiles[i][j].drawTile(canvas, ypos, xpos) ypos += (viewPortHandler.width / cols) } xpos += (viewPortHandler.height / rows) } } override fun onClick(x: Float, y: Float) { val dx = Util.map(x.roundToInt(), IntRange(0, viewPortHandler.width - 1), IntRange(0, 4)) val dy = Util.map(y.roundToInt(), IntRange(0, viewPortHandler.height - 1), IntRange(0, 4)) if (isBegin()) { checkTilesClicked(dx, dy) } else { if (checkWhiteTileClicked(dx, dy)) { setGameOver() } else { checkTilesClicked(dx, dy) } } } override fun getViewPortHandler(): ViewPortHandler { return viewPortHandler } override fun isFinished(): Boolean { // check first n - 1 rows contains Empty Tiles var finished = true for (i in 0 until rows - 1) { for (j in 0 until cols) { if (tiles[i][j].tileType == TileType.WHITE || tiles[i][j].tileType == TileType.BLACK) { finished = false } } } if (finished) { removeLastRowAddAtTop() setGameOver() } return finished } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * @author yefuwang@microsoft.com */ import { FxError, Inputs, Result, ok, err, ManifestUtil, devPreview, Context, } from "@microsoft/teamsfx-api"; import { join } from "path"; import { HelperMethods } from "./helperMethods"; import { OfficeAddinManifest } from "office-addin-manifest"; import projectsJsonData from "./config/projectsJsonData"; import * as childProcess from "child_process"; import { promisify } from "util"; import { CopyFileError } from "../../../core/error"; import _ from "lodash"; import { hooks } from "@feathersjs/hooks/lib"; import { ActionExecutionMW } from "../../middleware/actionExecutionMW"; import { Generator } from "../generator"; import { convertProject } from "office-addin-project"; import { QuestionNames } from "../../../question/questionNames"; import { getTemplate } from "../../../question/create"; import { getLocalizedString } from "../../../common/localizeUtils"; const componentName = "office-addin"; const telemetryEvent = "generate"; const templateName = "office-addin"; export class OfficeAddinGenerator { @hooks([ ActionExecutionMW({ enableTelemetry: true, telemetryComponentName: componentName, telemetryEventName: telemetryEvent, errorSource: componentName, }), ]) static async generate( context: Context, inputs: Inputs, destinationPath: string ): Promise<Result<undefined, FxError>> { const result = await OfficeAddinGenerator.doScaffolding(context, inputs, destinationPath); if (result.isErr()) { return err(result.error); } // If lang is undefined, it means the project is created from a folder. const lang = inputs[QuestionNames.ProgrammingLanguage]; const templateRes = await Generator.generateTemplate( context, destinationPath, templateName, lang != "No Options" ? (lang === "TypeScript" ? "ts" : "js") : undefined ); if (templateRes.isErr()) return err(templateRes.error); return ok(undefined); } public static async childProcessExec(cmdLine: string) { return promisify(childProcess.exec)(cmdLine); } public static async doScaffolding( context: Context, inputs: Inputs, destinationPath: string ): Promise<Result<undefined, FxError>> { const template = getTemplate(inputs); const name = inputs[QuestionNames.AppName] as string; const addinRoot = destinationPath; const fromFolder = inputs[QuestionNames.OfficeAddinFolder]; const language = inputs[QuestionNames.ProgrammingLanguage]; const host = inputs[QuestionNames.OfficeAddinHost]; const workingDir = process.cwd(); const importProgress = context.userInteraction.createProgressBar( getLocalizedString("core.generator.officeAddin.importProject.title"), 3 ); process.chdir(addinRoot); try { if (!fromFolder) { // from template const jsonData = new projectsJsonData(); const projectRepoBranchInfo = jsonData.getProjectRepoAndBranch(template, language, true); // Copy project template files from project repository if (projectRepoBranchInfo.repo) { await HelperMethods.downloadProjectTemplateZipFile( addinRoot, projectRepoBranchInfo.repo, projectRepoBranchInfo.branch ); // Call 'convert-to-single-host' npm script in generated project, passing in host parameter const cmdLine = `npm run convert-to-single-host --if-present -- ${_.toLower(host)}`; await OfficeAddinGenerator.childProcessExec(cmdLine); const manifestPath = jsonData.getManifestPath(template) as string; // modify manifest guid and DisplayName await OfficeAddinManifest.modifyManifestFile( `${join(addinRoot, manifestPath)}`, "random", `${name}` ); await HelperMethods.moveManifestLocation(addinRoot, manifestPath); } } else { await importProgress.start(); // from existing project await importProgress.next( getLocalizedString("core.generator.officeAddin.importProject.copyFiles") ); HelperMethods.copyAddinFiles(fromFolder, addinRoot); const sourceManifestFile: string = inputs[QuestionNames.OfficeAddinManifest]; let manifestFile: string = sourceManifestFile.replace(fromFolder, addinRoot); await importProgress.next( getLocalizedString("core.generator.officeAddin.importProject.convertProject") ); if (manifestFile.endsWith(".xml")) { // Need to convert to json project first await convertProject(manifestFile); manifestFile = manifestFile.replace(/\.xml$/, ".json"); } inputs[QuestionNames.OfficeAddinHost] = await getHost(manifestFile); await importProgress.next( getLocalizedString("core.generator.officeAddin.importProject.updateManifest") ); await HelperMethods.updateManifest(destinationPath, manifestFile); } process.chdir(workingDir); await importProgress.end(true, true); return ok(undefined); } catch (e) { process.chdir(workingDir); await importProgress.end(false, true); return err(CopyFileError(e as Error)); } } } // TODO: update to handle different hosts when support for them is implemented // TODO: handle multiple scopes type OfficeHost = "Outlook"; // | "Word" | "OneNote" | "PowerPoint" | "Project" | "Excel" async function getHost(addinManifestPath: string): Promise<OfficeHost> { // Read add-in manifest file const addinManifest: devPreview.DevPreviewSchema = await ManifestUtil.loadFromPath( addinManifestPath ); let host: OfficeHost = "Outlook"; switch (addinManifest.extensions?.[0].requirements?.scopes?.[0]) { // case "document": // host = "Word"; case "mail": host = "Outlook"; // case "notebook": // host = "OneNote"; // case "presentation": // host = "PowerPoint"; // case "project": // host = "Project"; // case "workbook": // host = "Excel"; } return host; }
import React, { Fragment } from "react"; import CharacterCard from "../../components/card/character/CharacterCard"; import { Container, Row, Col } from "react-bootstrap"; function Home(props) { const [loading, setLoading] = React.useState(true); const [data, setData] = React.useState({}); const [search, setSearch] = React.useState(""); if (search !== props.search) { setSearch(props.search); } React.useEffect(() => { try { setLoading(true); window .fetch("https://rickandmortyapi.com/api/character") .then((res) => res.json()) .then((response) => { setData(response); setLoading(false); }); } catch (error) { console.log( "Se produjo un error realizando la peticion al api. " + error ); } }, []); return ( <Fragment> <Container> <Row className="justify-content-md-center animated fadeIn slow"> {loading ? ( <p>Cargando...</p> ) : search !== null && search !== "" ? ( data.results .filter((filterItem) => filterItem.name.toLowerCase().includes(search.toLowerCase()) ) .map((item) => ( <Col xs={6} sm={4} md={3} key={item.id}> <CharacterCard {...item} /> </Col> )) ) : ( data.results.map((item) => ( <Col xs={6} sm={4} md={3} key={item.id}> <CharacterCard {...item} /> </Col> )) )} </Row> </Container> </Fragment> ); } export default Home;
import { Box, Button, Grid, Typography } from "@mui/material"; import React, { useEffect, useState } from "react"; import Typist from "react-typist"; import logo from "../../assets/remove.png"; import { TypeAnimation } from "react-type-animation"; import { useNavigate } from "react-router-dom"; import ReactLoading from "react-loading"; import { animated, useSpring } from "@react-spring/web"; const DefaultPage = () => { const navigate = useNavigate(); const [load, setLoad] = useState(true); const [isVisible, setIsVisible] = useState(false); const styles = useSpring({ opacity: isVisible ? 1 : 0, y: isVisible ? 0 : 24, }); useEffect(() => { setTimeout(() => { setLoad(false); setIsVisible(true); }, 1000); }, []); return ( <Box sx={{ height: "100vh", color: "#F7F7F7", display: "flex", flexDirection: "column", padding: "2rem", background: "#141E30", background: "-webkit-linear-gradient(to right, #243B55, #141E30)", background: "linear-gradient(to right, #243B55, #141E30)", }} > <Grid container sx={{ width: "90%", }} > <Grid item xs={12} sm={12} md={6}> <Typography variant="h4" sx={{ fontSize: "2rem", fontFamily: "Bebas Neue, Roboto", color: "#F7F7F7", }} > Devs Channel </Typography> </Grid> </Grid> {load && ( <Box sx={{ marginTop: "10rem", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", }} > <ReactLoading type={"cylon"} color={"darkGray"} height={"40px"} width={"70px"} /> </Box> )} {!load && ( <> <Box sx={{ marginTop: "5rem", width: "100%", display: "flex", flexDirection: "column", alignItems: "center", gap: "1rem", }} > <Box sx={{ width: "200px", height: "70px", }} > <img src={logo} alt="" style={{ width: "200px", height: "70px", objectFit: "cover", }} /> </Box> <Typography variant="button" sx={{ fontSize: { xs: "1.5rem", sm: "1.5rem", md: "2rem", }, fontFamily: "Bebas Neue, Roboto", letterSpacing: "3px", }} > Greetings!! Dev </Typography> <Box sx={{ width: { xs: "100%", sm: "100%", md: "60%", }, fontSize: { xs: "16px", sm: "16px", md: "1.5rem", }, height: "100px", }} > <TypeAnimation sequence={[ "Chat with the Chad Developers.", // Types 'One' 1000, // Waits 1s "Exchange knowledge and experience.", 2000, "Get inspired and be inspired.", 3000, "Chat and share ideas.", () => { // console.log("Done typing!"); // Place optional callbacks anywhere in the array }, ]} wrapper="div" cursor={true} repeat={Infinity} style={{ width: "100%", textAlign: "center", fontFamily: "Courier Prime, monospace", }} /> </Box> </Box> <animated.div style={styles}> <Grid spacing={2} container // justifyContent={"center"} // alignItems={"center"} sx={{ padding: { xs: "0", sm: "0", md: " 0 32rem", }, }} > <Grid item xs={12} sm={12} md={6}> <Button variant="contained" fullWidth sx={{ background: "#272a37", "&:hover": { background: "transparent", }, }} onClick={() => navigate("/login")} > Login </Button> </Grid> <Grid item xs={12} sm={12} md={6}> <Button variant="contained" fullWidth sx={{ background: "#414555", "&:hover": { background: "transparent", }, }} onClick={() => navigate("/register")} > Register </Button> </Grid> </Grid> </animated.div> </> )} <Box sx={{ marginTop: "auto", }} > <Typography variant="body1" fontSize={"12px"}> @Devs-Channel, 2023 - By Mafiz </Typography> </Box> </Box> ); }; export default DefaultPage;
"""* EJERCICIO: * - Muestra ejemplos de creación de todas las estructuras soportadas por defecto en tu lenguaje. * - Utiliza operaciones de inserción, borrado, actualización y ordenación. * * DIFICULTAD EXTRA (opcional): * Crea una agenda de contactos por terminal. * - Debes implementar funcionalidades de búsqueda, inserción, actualización y eliminación de contactos. * - Cada contacto debe tener un nombre y un número de teléfono. * - El programa solicita en primer lugar cuál es la operación que se quiere realizar, y a continuación * los datos necesarios para llevarla a cabo. * - El programa no puede dejar introducir números de teléfono no númericos y con más de 11 dígitos. * (o el número de dígitos que quieras) * - También se debe proponer una operación de finalización del programa. """ import re # Tuplas - Son inmutables, se pueden iterar print("TUPLAS") tupla = (1, 2, 3, 4, 1) # tupla = tuple([1, 2, 3]) print(type(tupla)) print(tupla) # Iterar tuplas print("ITERAR TUPLAS") for dato in tupla: print(dato) print(len(tupla)) # Muestra la cantidad de elementos # Metodos tuplas print("METODOS TUPLAS") print(tupla.count(1)) # cuenta los elementos que son 1 print(tupla.index(4)) # imprime el el indice del valor 4 # Listas - Son mutables, se pueden iterar print("LISTAS") lista = [1, 2, 3, 4] # lista = list("123") print(type(lista)) print(lista) a, b, c, d = lista print(f"{a} - {b} - {c} - {d}") # Iterar listas print("ITERAR LISTAS") for dato in lista: print(dato) print(len(lista)) # Muestra la cantidad de elementos # Metodos print("METODOS LISTAS") lista.remove(3) # Remueve el elemento 3 print(lista) lista.extend([5, 6]) # Se extiende la lsita con uno o varios elementos print(lista) lista.append(7) # Se agrega un valor al final de la lista print(lista) lista.insert(2, 3) # Se inserta un 3 en la posicion 2 print(lista) lista.pop() # Se elimina el ultimo valor print(lista) lista.reverse() # La oredena en sentido inverso print(lista) lista.sort() # La ordena de menor a mayor print(lista) print( lista[3] ) # Imprime el valor de la lista en la posicion 3 (comienza a contar desde 0) print(lista.index(4)) # Imprime la posicion del elemento 4 # Set - Son inmutables, se pueden iterar, no permite datos repetidos y desordenados print("SETS") s = set([2, 1, 4, 2, 3, 1]) print(type(s)) print(s) # Iterar sets print("ITERAR SETS") for dato in s: print(dato) print(len(s)) # Muestra la cantidad de elementos print("METODOS DE SETS") s.add(5) # Agrega el valor 5 print(s) s.remove(3) # Remueve el valor 3 print(s) s.pop() # Remueve un valor al azar print(s) s.clear() # Vacia el set print(s) # Diccionarios - Son mutables, se pueden iterar print("DICCIONARIOS") diccionario = {"Juan": "juan@mail.com", "Maria": "maria@mail.com"} # diccionario = dict([("Juan", "juan@mail.com"), ("Maria", "maria@mail.com")]) print(type(diccionario)) print(diccionario) print("ITERAR DICCIONARIOS") for x, y in diccionario.items(): print(f"clave: {x}, valor: {y}") print("METODOS DE DICCIONARIOS") print( diccionario.get("Juan", "No existe") ) # Muestra el valor para la clave, si no existe muestra el segundo parametro print(diccionario.items()) # Muestra todos los items del diccionario print(diccionario.keys()) # Muestra todos los keys del diccionario print(diccionario.values()) # Muestra todos los valores del diccionario diccionario.pop("Juan") # Elimina el item con esa key print(diccionario) d = {"Jose": "jose@mail.com"} diccionario.update(d) # Agrega un item o si existe lo modifica print(diccionario) diccionario.clear() # Vacia el diccionario print(diccionario) """ DIFICULTAD EXTRA """ # Funcion de menu de opciones def menu(): opciones = "1234" print("\nBIENVENIDO A LA AGENDA:") print("1 - Dar de alta") print("2 - Dar de baja") print("3 - Consultar") print("4 - Modificar") print("\n0 - Salir\n") global seleccion global decision seleccion = input("seleccione una opcion: ") if seleccion in opciones: decision = True else: decision = False # Funcion para dar de alta def alta(posicion: dict, contador: int): patron = "^\d{13}$" name = input("Ingrese el nombre: ") phone = input("Ingrese el telefono (debe tener 13 digitos): ") if re.match(patron, phone): prov = {str(contador): [name, phone]} posicion.update(prov) contador += 1 else: print("El telefono ingresado es incorrecto") print("Debe tener 13 digitos") alta(posicion, contador) return posicion, contador # Funcion para dar de baja def baja(posicion: dict): mostrar(posicion) x = input("\nIngrese que ID quiere dar de baja: ") if posicion.get(x, "no") == "no": print("El item no existe") return baja(posicion) posicion.pop(x) return posicion # Funcion de consulta def consulta(posicion: dict): mostrar(posicion) x = input("\nPresione una tecla para continuar") if x != "": return # Funcion para modificar def modificar(posicion: dict): mostrar(posicion) x = input("\nIngrese que ID quiere modificar: ") if posicion.get(x, "no") == "no": print("El item no existe") return modificar(posicion) name = input("Ingrese el nombre a modificar: ") phone = input("Ingrese el telefono a modificar: ") prov = {str(x): [name, phone]} posicion.update(prov) return posicion # Funcion para mostrar la agenda def mostrar(posicion: dict): print("-" * 43) print(f'{"ID":4} {"NOMBRE":25} {"TELEFONO":17}') for i in posicion: print(f"{i:4} {posicion[i][0]:25} {posicion[i][1]:12}") print("-" * 43) # Inicia mostrando un menu de opciones posicion = {} contador = 0 menu() while decision: if seleccion == "1": posicion, contador = alta(posicion, contador) menu() elif seleccion == "2": posicion = baja(posicion) menu() elif seleccion == "3": consulta(posicion) menu() elif seleccion == "4": posicion = modificar(posicion) menu() print("Ha salido de la agenda!!")
import {BaseRequestJson} from "@entities/base.requestJson"; import { getRandomFirstName, getRandomLastName, getRandomRequestId, getRandomSessionId } from "@utils/randomUtils"; import {RequestSource} from "@libs/requestSource"; import userTestData from "@data/user.json"; import {SportExperience} from "@libs/sportExperience"; export interface UserDataRequestJson { email: string; name: string; last_name: string; middle_name: string; sex: string; password: string | null; phone: string; birthday: string; lang: string; user_foto_id: number; home_club_id: number; club_access: boolean; admin_panel_access: boolean; class_registration_access: boolean; sport_experience: string; } export const getUserRequestJson = async (clubId: number, email: string, phoneNumber: string): Promise<BaseRequestJson<UserDataRequestJson>> => { return { session_id: await getRandomSessionId(), request_id: await getRandomRequestId(), request_source: RequestSource.CRM, data: { email: email, name: await getRandomFirstName(), last_name: await getRandomLastName(), middle_name: userTestData.middleName, sex: userTestData.sex.male, password: userTestData.password, phone: phoneNumber, birthday: userTestData.birthday, lang: userTestData.lang, user_foto_id: userTestData.userPhotoId, home_club_id: clubId, club_access: false, admin_panel_access: false, class_registration_access: false, sport_experience: SportExperience.WITHOUT_EXPERIENCE } }; }
package dev.plex.medina.storage; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import dev.plex.medina.MedinaBase; import lombok.Getter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @Getter public class SQLConnection implements MedinaBase { private HikariDataSource dataSource; public SQLConnection() { String host = plugin.config.getString("database.hostname"); int port = plugin.config.getInt("database.port"); String username = plugin.config.getString("database.username"); String password = plugin.config.getString("database.password"); String database = plugin.config.getString("database.name"); HikariConfig config = new HikariConfig(); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); this.dataSource = new HikariDataSource(); dataSource.setMaxLifetime(15000); dataSource.setIdleTimeout(15000 * 2); dataSource.setConnectionTimeout(15000 * 4); dataSource.setMinimumIdle(2); dataSource.setMaximumPoolSize(10); try { Class.forName("org.mariadb.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + database); dataSource.setUsername(username); dataSource.setPassword(password); } catch (ClassNotFoundException throwables) { throwables.printStackTrace(); } try (Connection con = getCon()) { con.prepareStatement("CREATE TABLE IF NOT EXISTS `reports` (" + "`reportId` INT NOT NULL AUTO_INCREMENT, " + "`reporterUUID` VARCHAR(46) NOT NULL, " + "`reporterName` VARCHAR(18), " + "`reportedUUID` VARCHAR(46) NOT NULL, " + "`reportedName` VARCHAR(18), " + "`timestamp` BIGINT, " + "`reason` VARCHAR(2000), " + "`resolved` BOOLEAN, " + "`deleted` BOOLEAN, " + "PRIMARY KEY (`reportId`));").execute(); } catch (SQLException throwables) { throwables.printStackTrace(); } } private boolean tableExistsSQL(String tableName) throws SQLException { try (Connection connection = getCon()) { PreparedStatement preparedStatement = connection.prepareStatement("SELECT count(*) " + "FROM information_schema.tables " + "WHERE table_name = ?" + "LIMIT 1;"); preparedStatement.setString(1, tableName); ResultSet resultSet = preparedStatement.executeQuery(); resultSet.next(); return resultSet.getInt(1) != 0; } catch (SQLException ignored) { return false; } } public Connection getCon() { if (this.dataSource == null) { return null; } try { return dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; } }
import { Resolver, Mutation, Args, Parent, ResolveField, Query, } from '@nestjs/graphql'; import { GameResultService } from './game-result.service'; import { GameResultEntity } from 'src/game-result/entities/game-result.entity'; import { GameResultCreateDTO } from 'src/game-result/dtos/create-game-result.input'; import { GameEntity } from 'src/game/entities/game.entity'; import { PlayerEntity } from 'src/player/entities/player.entity'; @Resolver(() => GameResultEntity) export class GameResultResolver { constructor(private readonly gameResultService: GameResultService) {} @Query(() => [GameResultEntity]) getAllGameResults() { return this.gameResultService.findAllResults(); } @Query(() => GameResultEntity) getOneGameResult(@Args('id') id: number) { return this.gameResultService.findOneResult(id); } @Mutation(() => GameResultEntity) createGameResult(@Args('gameResult') gameResult: GameResultCreateDTO) { return this.gameResultService.createGameResult(gameResult); } @ResolveField(() => PlayerEntity) player(@Parent() gameResult: GameResultEntity) { return this.gameResultService.getPlayer(gameResult.playerId); } @ResolveField(() => GameEntity) game(@Parent() gameResult: GameResultEntity) { return this.gameResultService.getGame(gameResult.gameId); } }
"use client" import { User } from "@prisma/client" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { signOut } from "next-auth/react" import Link from "next/link" import Image from "next/image" interface UserNavigationProps { user: User } // ユーザーナビゲーション const UserNavigation = ({ user }: UserNavigationProps) => { return ( <DropdownMenu> <DropdownMenuTrigger> <div className="relative w-10 h-10 flex-shrink-0"> <Image src={user.image || "/default.png"} className="rounded-full object-cover" alt={user.name || "avatar"} fill sizes="40px" /> </div> </DropdownMenuTrigger> <DropdownMenuContent className="bg-white p-2 w-[300px]" align="end"> <Link href={`/author/${user.id}`}> <DropdownMenuItem className="cursor-pointer"> <div className="break-words min-w-0"> <div className="mb-2">{user.name || ""}</div> <div className="text-gray-500">{user.email || ""}</div> </div> </DropdownMenuItem> </Link> <DropdownMenuSeparator /> {user.isAdmin && ( <Link href="/event/new"> <DropdownMenuItem className="cursor-pointer"> イベント新規作成 </DropdownMenuItem> </Link> )} <Link href="/settings/profile"> <DropdownMenuItem className="cursor-pointer"> アカウント設定 </DropdownMenuItem> </Link> <DropdownMenuItem onSelect={async (event) => { event.preventDefault() await signOut({ callbackUrl: "/" }) }} className="text-red-600 cursor-pointer" > ログアウト </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) } export default UserNavigation
import { HandlerContext } from "$fresh/server.ts"; import { getJson } from "../../shared/file.ts"; import { Category } from "./categories.ts"; export type Product = { // id: string; name: string; url: string; image?: string; preview?: string; price?: number; annotation: string; description: string; brand: string | null; featured: boolean | null; category?: Category; features: { id: number; value: string }[]; articleNumber?: string; isExists?: boolean; metaTitle: string; metaKeywords: string; metaDescription: string; }; export const handler = async (req: Request, _ctx: HandlerContext) => { try { const reqUrl = new URL(req.url); const url = new URL("https://tehmet.su/ajax/products.php"); url.search = reqUrl.search; const config = (await getJson("./db/config.json")) as { categoriesWithPrice: string[]; showPrice: boolean; }; const response = await fetch(url.toString()); const json = await response.json(); const data = (json.data ?? {}) as Record<string, Product>; const products = Object.entries(data).map(([id, p]) => ({ ...p, id: Number(id), isExists: true, price: ((p.category && config.categoriesWithPrice.includes(p.category.url)) || config.showPrice) && p.price ? Number(p.price) : undefined, })) as Product[]; // try { // const decoder = new TextDecoder("utf-8"); // const ostatki = await Deno.readFile("./db/ostatki.csv"); // const content = await parse(decoder.decode(ostatki), { // lazyQuotes: true, // separator: ";", // skipFirstRow: true, // }); // console.log(content); // } catch (error) { // console.error("Error when load ostatki.csv", error.message); // } return new Response(JSON.stringify(products), { headers: { "Content-Type": "application/json", }, }); } catch (error) { // console.error(error); return new Response(JSON.stringify([]), { headers: { "Content-Type": "application/json", }, }); } };
## message_textview.py ## ## Contributors for this file: ## - Yann Le Boulanger <asterix@lagaule.org> ## - Nikos Kouremenos <kourem@gmail.com> ## ## Copyright (C) 2003-2004 Yann Le Boulanger <asterix@lagaule.org> ## Vincent Hanquez <tab@snarc.org> ## Copyright (C) 2005 Yann Le Boulanger <asterix@lagaule.org> ## Vincent Hanquez <tab@snarc.org> ## Nikos Kouremenos <nkour@jabber.org> ## Dimitur Kirov <dkirov@gmail.com> ## Travis Shirk <travis@pobox.com> ## Norman Rasmussen <norman@rasmussen.co.za> ## ## 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; version 2 only. ## ## 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. ## import gtk import gobject class MessageTextView(gtk.TextView): '''Class for the message textview (where user writes new messages) for chat/groupchat windows''' __gsignals__ = dict( mykeypress = (gobject.SIGNAL_RUN_LAST | gobject.SIGNAL_ACTION, None, # return value (int, gtk.gdk.ModifierType ) # arguments ) ) def __init__(self): gtk.TextView.__init__(self) # set properties self.set_border_width(1) self.set_accepts_tab(True) self.set_editable(True) self.set_cursor_visible(True) self.set_wrap_mode(gtk.WRAP_WORD) self.set_left_margin(2) self.set_right_margin(2) self.set_pixels_above_lines(2) self.set_pixels_below_lines(2) if gobject.pygtk_version < (2, 8, 0): gobject.type_register(MessageTextView) # We register depending on keysym and modifier some bindings # but we also pass those as param so we can construct fake Event # Here we register bindings for those combinations that there is NO DEFAULT # action to be done by gtk TextView. In such case we should not add a binding # as the default action comes first and our bindings is useless. In that case # we catch and do stuff before default action in normal key_press_event # and we also return True there to stop the default action from running # CTRL + SHIFT + TAB gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.ISO_Left_Tab, gtk.gdk.CONTROL_MASK, 'mykeypress', int, gtk.keysyms.ISO_Left_Tab, gtk.gdk.ModifierType, gtk.gdk.CONTROL_MASK) # CTRL + TAB gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.Tab, gtk.gdk.CONTROL_MASK, 'mykeypress', int, gtk.keysyms.Tab, gtk.gdk.ModifierType, gtk.gdk.CONTROL_MASK) # TAB gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.Tab, 0, 'mykeypress', int, gtk.keysyms.Tab, gtk.gdk.ModifierType, 0) # CTRL + UP gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.Up, gtk.gdk.CONTROL_MASK, 'mykeypress', int, gtk.keysyms.Up, gtk.gdk.ModifierType, gtk.gdk.CONTROL_MASK) # CTRL + DOWN gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.Down, gtk.gdk.CONTROL_MASK, 'mykeypress', int, gtk.keysyms.Down, gtk.gdk.ModifierType, gtk.gdk.CONTROL_MASK) # ENTER gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.Return, 0, 'mykeypress', int, gtk.keysyms.Return, gtk.gdk.ModifierType, 0) # Ctrl + Enter gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.Return, gtk.gdk.CONTROL_MASK, 'mykeypress', int, gtk.keysyms.Return, gtk.gdk.ModifierType, gtk.gdk.CONTROL_MASK) # Keypad Enter gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.KP_Enter, 0, 'mykeypress', int, gtk.keysyms.KP_Enter, gtk.gdk.ModifierType, 0) # Ctrl + Keypad Enter gtk.binding_entry_add_signal(MessageTextView, gtk.keysyms.KP_Enter, gtk.gdk.CONTROL_MASK, 'mykeypress', int, gtk.keysyms.KP_Enter, gtk.gdk.ModifierType, gtk.gdk.CONTROL_MASK)
import React, { forwardRef } from "react"; export type InputSize = "medium" | "large"; export type InputType = "text" | "email" | "password" | "number"; export type InputProps = { id: string; name: string; label: string; type?: InputType; size?: InputSize; className?: string; }; const CustomInput: React.FC<InputProps> = forwardRef< HTMLInputElement, InputProps >( ( { id, name, label, type = "text", size = "medium", className = "", ...props }, ref ) => { return ( <div className='mt-2 md:mt-4' aria-live='polite'> <label htmlFor='' className='text-md font-bold text-gray-600 block capitalize' > {label} <span className='text-red-500'>*</span> <input id={id} ref={ref} name={name} type={type} aria-label={label} className={`w-full p-2 border border-gray-300 rounded mt-1 text-md font-normal ${className}`} {...props} /> </label> </div> ); } ); export default CustomInput;
import { Component, OnInit, OnDestroy } from '@angular/core'; import { HttpHeaders, HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { JhiEventManager, JhiParseLinks } from 'ng-jhipster'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { IResource } from 'app/shared/model/resource.model'; import { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants'; import { ResourceService } from './resource.service'; import { ResourceDeleteDialogComponent } from './resource-delete-dialog.component'; @Component({ selector: 'jhi-resource', templateUrl: './resource.component.html' }) export class ResourceComponent implements OnInit, OnDestroy { resources: IResource[]; eventSubscriber?: Subscription; itemsPerPage: number; links: any; page: number; predicate: string; ascending: boolean; constructor( protected resourceService: ResourceService, protected eventManager: JhiEventManager, protected modalService: NgbModal, protected parseLinks: JhiParseLinks ) { this.resources = []; this.itemsPerPage = ITEMS_PER_PAGE; this.page = 0; this.links = { last: 0 }; this.predicate = 'id'; this.ascending = true; } loadAll(): void { this.resourceService .query({ page: this.page, size: this.itemsPerPage, sort: this.sort() }) .subscribe((res: HttpResponse<IResource[]>) => this.paginateResources(res.body, res.headers)); } reset(): void { this.page = 0; this.resources = []; this.loadAll(); } loadPage(page: number): void { this.page = page; this.loadAll(); } ngOnInit(): void { this.loadAll(); this.registerChangeInResources(); } ngOnDestroy(): void { if (this.eventSubscriber) { this.eventManager.destroy(this.eventSubscriber); } } trackId(index: number, item: IResource): number { // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion return item.id!; } registerChangeInResources(): void { this.eventSubscriber = this.eventManager.subscribe('resourceListModification', () => this.reset()); } delete(resource: IResource): void { const modalRef = this.modalService.open(ResourceDeleteDialogComponent, { size: 'lg', backdrop: 'static' }); modalRef.componentInstance.resource = resource; } sort(): string[] { const result = [this.predicate + ',' + (this.ascending ? 'asc' : 'desc')]; if (this.predicate !== 'id') { result.push('id'); } return result; } protected paginateResources(data: IResource[] | null, headers: HttpHeaders): void { const headersLink = headers.get('link'); this.links = this.parseLinks.parse(headersLink ? headersLink : ''); if (data) { for (let i = 0; i < data.length; i++) { this.resources.push(data[i]); } } } }
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:composite="http://xmlns.jcp.org/jsf/composite" xmlns:zlb="http://xmlns.jcp.org/jsf/composite/composites" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:x="http://myfaces.apache.org/tomahawk" xmlns:pt="http://xmlns.jcp.org/jsf/passthrough" xmlns:jsf="http://xmlns.jcp.org/jsf"> <composite:interface> <composite:attribute name="inputDuplicate" default="false" /> <composite:attribute name="showHelpBtn" default="true" /> <composite:attribute name="helpTitle" default="default help Title (field.xhtml)" /> <composite:attribute name="helpText" default="default help text" /> <composite:attribute name="identifier" /> <!-- #{field.label} --> <composite:attribute name="labelText" /> <!-- #{field.helpMessage} --> <composite:attribute name="labelHelpText" /> <!-- #{field.required} --> <composite:attribute name="fieldRequired" default="false" /> <!-- #{field.value} --> <composite:attribute name="value" /> <!-- #{field.booleanValue} --> <composite:attribute name="booleanValue" /> <!-- #{field.displayType} --> <composite:attribute name="fieldType" default="input" /> <!-- #{field.validationError} --> <composite:attribute name="propertyValid" default="true" /> <!-- #{field.validationErrorMessage} --> <composite:attribute name="errorMessageText" /> <!-- #{field.selectItemList} --> <composite:attribute name="selectItems" /> <!-- #{field.subValue} --> <composite:attribute name="subValue" /> <!-- #{field.helpMessage} ? --> <composite:attribute name="placeholderText" default="" /> <!-- styling options --> <composite:attribute name="mainClass" default="" /> <composite:attribute name="subClass" default="" /> <composite:attribute name="fieldStyle" default="" /> <composite:attribute name="displayDuplicateButton" default="false" /> <composite:attribute name="displayRemoveButton" default="false" /> <composite:attribute name="render" default="@form" /> </composite:interface> <composite:implementation> <h:panelGroup id="#{cc.attrs.identifier}" layout="block" styleClass="form-group #{cc.attrs.mainClass}"> <!-- Checkbox needs slightly different markup --> <ui:fragment rendered="#{cc.attrs.fieldType=='checkbox' or cc.attrs.fieldType=='combo'}"> <div class="form-check #{!cc.attrs.propertyValid ? 'validate--danger' : ''}"> <div class="form-check-wrapper"> <h:selectBooleanCheckbox id="#{cc.attrs.identifier}_checkbox" rendered="#{cc.attrs.fieldType=='checkbox' or cc.attrs.fieldType=='combo'}" pt:aria-label="#{cc.attrs.labelText}" styleClass="form-check-input" value="#{cc.attrs.booleanValue}" onfocus="focusField(this);"> <f:ajax event="valueChange" render="#{cc.attrs.render}" execute="@this" /> </h:selectBooleanCheckbox> <zlb:label labelFor="activation" labelText="#{cc.attrs.labelText}" labelHelpText="Lorem ipsum dolor sit amet, consetetur sadipscing elitr" labelRequired="#{cc.attrs.fieldRequired}" /> <h:selectOneRadio id="#{cc.attrs.identifier}_radio" rendered="#{cc.attrs.fieldType=='combo' and cc.attrs.booleanValue}" styleClass="form-control" value="#{cc.attrs.subValue}" onfocus="focusField(this);"> <f:ajax event="valueChange" render="#{cc.attrs.render}" execute="@this" /> <f:selectItems value="#{cc.attrs.selectItems}" var="#{cc.attrs.var}" itemLabel="#{cc.attrs.itemLabel}" itemValue="#{cc.attrs.itemValue}" /> </h:selectOneRadio> </div> <!-- end form-check-wraper --> <h:panelGroup rendered="#{cc.attrs.showHelpBtn}"> <button jsf:id="showHelp2" jsf:onfocus="focusField(this);" type="button" class="form-icons__button form-icons__button--help" aria-label="#{msgs.plugin_rest_usercreation_ariaLabel_elementHelp}" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-body="#{cc.attrs.helpText}" data-bs-title="#{cc.attrs.helpTitle}"> <ui:include src="/uii/includes/icon-help.xhtml" /> </button> </h:panelGroup> </div> <!-- end form-check --> <!-- Help text / danger text --> <h:panelGroup layout="block" rendered="#{!cc.attrs.propertyValid}" styleClass="font-danger validation-message"> <h:outputText value="#{cc.attrs.errorMessageText}" /> </h:panelGroup> <h:outputText styleClass="help-block font-light" rendered="#{NavigationForm.showHelp}" value="#{cc.attrs.labelHelpText}" /> </ui:fragment> <ui:fragment rendered="#{cc.attrs.fieldType!='checkbox' and cc.attrs.fieldType!='combo'}"> <label for="#{cc.attrs.identifier}_input" class="zlb-label"> <h:outputText escape="false" value="#{cc.attrs.labelText}" /> <h:panelGroup styleClass="input-required" rendered="#{cc.attrs.fieldRequired}"> <i class="fa fa-asterisk" /> </h:panelGroup> </label> <div class="form form-field #{cc.attrs.subClass} #{!cc.attrs.propertyValid ? 'validate--danger' : ''}"> <x:inputText id="#{cc.attrs.identifier}_input" rendered="#{cc.attrs.fieldType=='input'}" pt:aria-label="#{cc.attrs.labelText}" styleClass="form-control #{cc.attrs.fieldStyle}" value="#{cc.attrs.value}" validator="#{field.validateField}" onfocus="focusField(this);"> <f:ajax event="valueChange" render="#{cc.attrs.render}" execute="@this focusField" /> <f:passThroughAttribute name="placeholder" value="#{cc.attrs.placeholderText}" /> </x:inputText> <x:inputTextarea id="#{cc.attrs.identifier}_textare" rendered="#{cc.attrs.fieldType=='textarea'}" pt:aria-label="#{cc.attrs.labelText}" styleClass="form-control #{cc.attrs.fieldStyle}" value="#{cc.attrs.value}" validator="#{field.validateField}" onfocus="focusField(this);"> <f:ajax event="valueChange" render="#{cc.attrs.render}" execute="@this" /> <f:passThroughAttribute name="placeholder" value="#{cc.attrs.placeholderText}" /> </x:inputTextarea> <h:selectOneMenu id="#{cc.attrs.identifier}_select" rendered="#{cc.attrs.fieldType=='dropdown' or cc.attrs.fieldType=='journaltitles'}" styleClass="form-select #{cc.attrs.fieldStyle}" value="#{cc.attrs.value}" pt:aria-label="#{cc.attrs.labelText}" validator="#{field.validateField}" onfocus="focusField(this);"> <f:selectItem itemValue="" itemLabel="#{msgs.bitteAuswaehlen}" /> <f:ajax event="valueChange" render="#{cc.attrs.render}" execute="@this" /> <f:selectItems value="#{cc.attrs.selectItems}" var="#{cc.attrs.var}" itemLabel="#{cc.attrs.itemLabel}" itemValue="#{cc.attrs.itemValue}" /> </h:selectOneMenu> <h:outputText rendered="#{cc.attrs.fieldType=='output'}" styleClass="form-control #{cc.attrs.fieldStyle}" value="#{cc.attrs.value}"> </h:outputText> <div class="form-icons"> <h:panelGroup rendered="#{cc.attrs.displayDuplicateButton}"> <button jsf:id="button" jsf:action="#{DashboardForm.plugin.duplicateMetadataField}" class="form-icons__button form-icons__button--duplicate" aria-label="#{msgs.plugin_rest_usercreation_ariaLabel_elementDuplicate}" onfocus="focusField(this);"> <ui:include src="/uii/includes/icon-plus.xhtml" /> <f:setPropertyActionListener value="#{field}" target="#{DashboardForm.plugin.currentField}" /> <f:ajax render="@form" execute="@this" /> </button> </h:panelGroup> <h:panelGroup rendered="#{cc.attrs.displayRemoveButton}"> <button jsf:id="removeButton" jsf:action="#{DashboardForm.plugin.removeMetadataField}" class="form-icons__button form-icons__button--duplicate" aria-label="#{msgs.plugin_rest_usercreation_ariaLabel_elementDeletion}" onfocus="focusField(this);"> <ui:include src="/uii/includes/icon-minus.xhtml" /> <f:setPropertyActionListener value="#{field}" target="#{DashboardForm.plugin.currentField}" /> <f:ajax render="@form" execute="@this" /> </button> </h:panelGroup> <h:panelGroup rendered="#{cc.attrs.showHelpBtn}"> <button jsf:id="showHelpField" jsf:onfocus="focusField(this);" type="button" class="form-icons__button form-icons__button--help" aria-label="#{msgs.plugin_rest_usercreation_ariaLabel_elementHelp}" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-body="#{cc.attrs.helpText}" data-bs-title="#{cc.attrs.helpTitle}"> <ui:include src="/uii/includes/icon-help.xhtml" /> </button> </h:panelGroup> </div> <!-- Help text / danger text --> <h:panelGroup layout="block" rendered="#{!cc.attrs.propertyValid}" styleClass="font-danger validation-message"> <h:outputText value="#{msgs[cc.attrs.errorMessageText]}" /> </h:panelGroup> <h:outputText styleClass="help-block font-light" rendered="#{NavigationForm.showHelp}" value="#{cc.attrs.labelHelpText}" /> </div> </ui:fragment> </h:panelGroup> </composite:implementation> </ui:composition>
import Image from 'next/image'; import Link from 'next/link'; import { cn } from '@/lib/utils'; import { ClerkLoaded, ClerkLoading, UserButton } from '@clerk/nextjs'; import { Loader } from './loader'; import { SidebarItem } from './sidebar-item'; type Props = { className?: string; }; const SidebarItems = [ { name: 'Learn', href: '/learn', imagePath: '/learn.svg' }, { name: 'Leaderboard', href: '/leaderboard', imagePath: '/leaderboard.svg' }, { name: 'Quests', href: '/quests', imagePath: '/quests.svg' }, { name: 'Shop', href: '/shop', imagePath: '/shop.svg' }, ]; export const Sidebar = ({ className }: Props) => { return ( <aside className={cn( 'left-0 top-0 flex h-full flex-col border-r-2 px-4 lg:fixed lg:w-[256px]', className, )} > <Link href="/learn"> <div className="flex items-center gap-x-3 pb-7 pl-4 pt-8"> <Image src="/mascot.svg" height={40} width={40} alt="Mascot" /> <h1 className="trackin-wide text-2xl font-extrabold text-green-600">Lingo</h1> </div> </Link> <div className="flex flex-1 flex-col gap-y-2"> {SidebarItems.map((item) => ( <SidebarItem key={item.name} href={item.href} imagePath={item.imagePath} label={item.name} /> ))} </div> <div className="p-4"> <ClerkLoading> <Loader /> </ClerkLoading> <UserButton afterSignOutUrl="/" /> <ClerkLoaded /> </div> </aside> ); };
\documentclass{book} \usepackage{tikz} \usetikzlibrary{positioning,chains,fit,shapes,calc} \begin{document} \definecolor{myblue}{RGB}{80,80,160} \definecolor{mygreen}{RGB}{80,160,80} \begin{tikzpicture}[thick, every node/.style={draw,circle}, fsnode/.style={fill=myblue}, ssnode/.style={fill=mygreen}, every fit/.style={ellipse,draw,inner sep=-2pt,text width=2cm}, ->,shorten >= 3pt,shorten <= 3pt ] % the vertices of Partner \begin{scope}[start chain=going below,node distance=7mm] \node[fsnode,on chain] (p11) [label=left: $P11$] {}; \node[fsnode,on chain] (p12) [label=left: $P12$] {}; \node[fsnode,on chain] (p13) [label=left: $P13$] {}; \node[fsnode,on chain] (p14) [label=left: $P14$] {}; \node[fsnode,on chain] (p15) [label=left: $P15$] {}; \end{scope} % the vertices of Partner \begin{scope}[xshift=4cm,yshift=-0.5cm,start chain=going below,node distance=7mm] \node[ssnode,on chain] (p21) [label=right: $P21$] {}; \node[ssnode,on chain] (p22) [label=right: $P22$] {}; \node[ssnode,on chain] (p23) [label=right: $P23$] {}; \node[ssnode,on chain] (p24) [label=right: $P24$] {}; \node[ssnode,on chain] (p25) [label=right: $P25$] {}; \end{scope} % the set U \node [myblue,fit=(p11) (p15),label=above:$Partner$] {}; % the set V \node [mygreen,fit=(p21) (p25),label=above:$Partner$] {}; % the edges \draw (p11) -- (p25); \draw (p11) -- (p23); \draw (p12) -- (p24); \draw (p13) -- (p22); \draw (p14) -- (p21); \draw (p14) -- (p25); \draw (p15) -- (p21); \draw (p15) -- (p25); \end{tikzpicture} \end{document}
import React, { useEffect, useState } from "react"; import { Button, Divider, Form, Input, Modal, Radio, Select, Table, } from "antd"; import { MINIMUMSKILLS } from "../const"; import { deleteData, getData, putData } from "../server/common"; import { Loading1 } from "../loading/Loading1"; import "./style.css"; import TextArea from "antd/lib/input/TextArea"; const columns = [ { title: "Title", dataIndex: "title", }, { title: "Description", dataIndex: "description", }, { title: "Minimum Skill", dataIndex: "minimumSkill", }, { title: "Tuition", dataIndex: "tuition", }, { title: "Weeks", dataIndex: "weeks", }, ]; const layout = { labelCol: { span: 24, }, wrapperCol: { span: 24, }, }; const Courses = () => { const [form] = Form.useForm(); const [selected, setSelected] = useState([]); const [isModalVisible, setIsModalVisible] = useState(false); const [data, setData] = useState([]); const rowSelection = { onChange: (_, selectedRows) => { setSelected(selectedRows); }, }; useEffect(() => { getCourses(); }, []); const getCourses = () => { getData("courses").then((res) => { setData(res.data.data); }); }; const showModal = () => { setIsModalVisible(true); }; const handleCancel = () => { setIsModalVisible(false); }; const handleOk = () => { setIsModalVisible(false); let values = form.getFieldsValue(); if (selected.length === 0) { } else { putData(`courses/${selected[0]._id}`, values).then(() => { getCourses(); setSelected([]); form.resetFields(); }); } }; const edit = () => { form.setFieldsValue(selected[0]); showModal(); }; const Delete = () => { selected.map((cour) => { deleteData(`courses/${cour._id}`).then(() => { getCourses(); setSelected([]); }); }); }; return ( <div> <div className="d-flex justify-content-between align-items-center"> <h3>Courses</h3> {selected.length !== 0 && ( <div id="actions"> {selected.length === 1 && ( <Button className="me-2" type="primary" onClick={edit}> Edit </Button> )} <Button type="danger" onClick={Delete}> Delete </Button> </div> )} <Button type="primary" onClick={showModal}> Add </Button> </div> <Divider /> <Table rowSelection={{ type: "chackbox", ...rowSelection, selectedRowKeys: selected.map((item) => item._id), }} rowKey="_id" columns={columns} dataSource={data} loading={data.length === 0 ? Loading1 : false} /> <Modal title="Basic Modal" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} maskClosable={false} > <Form {...layout} form={form} name="user" initialValues={{ scholarshipAvailable: false }} > <Form.Item name="title" label="Title" rules={[{ required: true, message: "Not filled" }]} > <Input /> </Form.Item> <Form.Item name="minimumSkill" label="Minimum Skill" rules={[{ required: true, message: "Not filled" }]} > <Select mode="multiple" allowClear style={{ width: "100%" }} placeholder="Please select careers" > {MINIMUMSKILLS.map((minimumSkill, index) => ( <Select.Option key={index} value={minimumSkill}> {minimumSkill} </Select.Option> ))} </Select> </Form.Item> <Form.Item name="tuition" label="Tuition" rules={[{ required: true, message: "Not filled" }]} > <Input /> </Form.Item> <Form.Item name="weeks" label="Weeks" rules={[{ required: true, message: "Not filled" }]} > <Input type="number" /> </Form.Item> <Form.Item name="description" label="Descreption" rules={[{ required: true, message: "Not filled" }]} > <TextArea /> </Form.Item> <Form.Item name="scholarshipAvailable" label="Scholar ship Available"> <Radio.Group> <Radio value="true">Yes</Radio> <Radio value="false">No</Radio> </Radio.Group> </Form.Item> </Form> </Modal> </div> ); }; export default Courses;
<form (ngSubmit)="onSubmit()" [formGroup]="formGroup"> <div class="d-flex justify-content-center"> <h4 class="mt-5">Todos los campos son obligatorios</h4> </div> <div class="vertical-center"> <mat-form-field> <mat-label>Tipo de documento</mat-label> <mat-select formControlName="typeId"> <mat-option value="Cédula de ciudadanía">Cédula de ciudadanía</mat-option> <mat-option value="Pasaporte">Pasaporte</mat-option> </mat-select> <mat-error *ngIf="formGroup.get('typeId')?.hasError('required')"> Este campo es obligatorio. </mat-error> </mat-form-field> </div> <div class="vertical-center"> <mat-form-field> <mat-label>Número de documento</mat-label> <input type="number" matInput formControlName="idNumber" placeholder="Escriba su número de documento"> <mat-error *ngIf="formGroup.get('idNumber')?.hasError('required')"> Este campo es obligatorio. </mat-error> <mat-error *ngIf="formGroup.get('idNumber')?.hasError('pattern')"> El valor debe tener entre 8 y 11 dígitos numéricos. </mat-error> </mat-form-field> </div> <div class="vertical-center"> <mat-form-field> <mat-label>País</mat-label> <mat-select formControlName="country"> <mat-option *ngFor="let countrie of countries" [value]="countrie.name.common">{{countrie.name.common}}</mat-option> </mat-select> <mat-error *ngIf="formGroup.get('country')?.hasError('required')"> Este campo es obligatorio. </mat-error> </mat-form-field> </div> <div class="vertical-center"> <button class="btn btn-primary rounded" [disabled]="formGroup.invalid">Buscar</button> </div> </form>
#pragma once #include "identifier.h" class Environment { public: Environment() {} inline IdentifierList getIdList() const noexcept { return idList; } inline StringList getIdNameList() const noexcept{ StringList nameList; for (const Identifier& id : idList) nameList.push_back(id.getName()); return nameList; } inline Identifier* getId(std::string idName) noexcept { checkIdName(idName); for (size_t i = 0; i < idList.size(); i++) if (idList[i].getName() == idName) return &idList[i]; return nullptr; } inline void addId(const Identifier& id) { if (exists(id.getName())) getId(id.getName())->setValue(id.getValue()); // modify value if already exists else idList.push_back(id); } inline void delId(std::string idName) { checkIdName(idName); for (size_t i = 0; i < idList.size(); i++) if (idList[i].getName() == idName) idList.erase(idList.begin() + i); } inline bool exists(std::string idName) const { checkIdName(idName); for (const Identifier& id : idList) if (id.getName() == idName) return true; return false; } inline bool isSysId(std::string idName) { checkIdName(idName); for (const Identifier& id : idList) if (id.getName() == idName && id.isSysId()) return true; return false; } private: static inline void checkIdName(std::string& name) { while (name[0] == '$') name = name.substr(1); } IdentifierList idList; };
#include <stdio.h> #include <stdarg.h> #include "variadic_functions.h" /** * print_all - Print a variable number of values based on a format string. * @format: A format string containing format specifiers. * @...: The values to be printed. * * Description: This function prints a variable number of values based on the * format string provided. The format string can contain the following * specifiers: * - 'c': Character * - 'i': Integer * - 'f': Float * - 's': String (if NULL, prints "(nil)") * * The values are retrieved from the variable argument list and printed * according to the format string. Values are separated by commas and a * newline character is printed at the end. */ void print_all(const char * const format, ...) { va_list args; int j = 0; const char *str = NULL; va_start(args, format); while (format && format[j]) { switch (format[j]) { case 'i': printf("%d", va_arg(args, int)); break; case 's': str = va_arg(args, char*); if (str == NULL) str = "(nil)"; printf("%s", str); break; case 'c': printf("%c", (char)va_arg(args, int)); break; case 'f': printf("%f", (float)va_arg(args, double)); break; default: j++; continue; } if (format[j + 1]) printf(", "); j++; } printf("\n"); va_end(args); }
"use client"; import React, { useState } from "react"; const NewTransaction = () => { const [formInput, setFormInput] = useState({ name: "", description: "", date: "", price: "", }); const handleNameInputChange = (event) => { setFormInput({ ...formInput, name: event.target.value, }); }; const handleDescriptionInputChange = (event) => { setFormInput({ ...formInput, description: event.target.value, }); }; const handleDateInputChange = (event) => { setFormInput({ ...formInput, date: event.target.value, }); }; const handlePriceInputChange = (event) => { setFormInput({ ...formInput, price: event.target.value, }); }; const submitHandler = async (event) => { event.preventDefault(); const url = process.env.NEXT_PUBLIC_API_URL + "transaction"; try { const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name: formInput.name, price: formInput.price, description: formInput.description, date: formInput.date, }), }); if (!response.ok) { throw new Error("Erro ao enviar transação."); } const json = await response.json(); console.log("result", json); setFormInput({ name: "", price: "", description: "", date: "", }); } catch (error) { console.error("Erro ao processar a transação:", error.message); } }; return ( <> <form className="flex flex-col " onSubmit={submitHandler}> <div className="grid grid-cols-2 grid-rows-2 gap-3 "> <div> <input type="text" placeholder="Movimentação" onChange={handleNameInputChange} value={formInput.name} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg block w-full p-2.5 outline-none text-center" /> </div> <div> <input type="text" onChange={handleDescriptionInputChange} value={formInput.description} placeholder="Descrição" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg block w-full p-2.5 outline-none text-center" /> </div> <div> <input type="number" placeholder="Valor" onChange={handlePriceInputChange} value={formInput.price} className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg block w-full p-2.5 outline-none text-center" /> </div> <div> <input type="date" onChange={handleDateInputChange} value={formInput.date} className="bg-gray-50 border border-gray-300 text-gray-400 text-sm rounded-lg block w-full p-2.5 outline-none text-center" /> </div> </div> <button className="bg-[#1F1F1F] rounded-xl py-2 my-9 text-white hover:scale-[1.02] duration-300 dark:bg-gray-700 dark:text-gray/70" type="submit" > Adicionar nova Transação </button> </form> </> ); }; export default NewTransaction;