text
stringlengths
184
4.48M
import { Component, OnInit } from '@angular/core'; import { UserService } from './user.service'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private _userService: UserService) {} subscription: Subscription; userActivated = false; ngOnInit() { this.subscription = this._userService.activatedEmitter.subscribe( didActivate => { this.userActivated = didActivate; } ); } ngOnDestroy() { this.subscription.unsubscribe(); } }
<template> <component :is="component" class="Navigation__NavigationItem NavigationItem"> <i v-if="icon" class="NavigationItem__icon" :class="[icon]" /> <span class="NavigationItem__text"> <slot /> </span> </component> </template> <script setup lang="ts"> type Props = { icon?: string; component?: string; }; withDefaults(defineProps<Props>(), { component: 'router-link', }); </script> <style lang="postcss" scoped> .NavigationItem.router-link-active, .NavigationItem.router-link-exact-active { @apply text-blue-500; } .NavigationItem { @apply text-black cursor-pointer hover:text-blue-500 flex items-center justify-start space-x-4 duration-200 transition-colors ease-in; } .NavigationItem__icon { @apply inline; } .NavigationItem__text { @apply font-semibold; } </style>
const sequelize = require('../db') const {DataTypes} = require('sequelize') const User = sequelize.define('user', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, email: {type: DataTypes.STRING, unique: true,}, password: {type: DataTypes.STRING}, role: {type: DataTypes.STRING, defaultValue: "USER"}, }) const Basket = sequelize.define('basket', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, }) const BasketMaterial = sequelize.define('basket_material', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, }) const Material = sequelize.define('material', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, name: {type: DataTypes.STRING, unique: true, allowNull: false}, price: {type: DataTypes.INTEGER, allowNull: false}, rating: {type: DataTypes.INTEGER, defaultValue: 0}, img: {type: DataTypes.STRING, allowNull: false}, }) const Type = sequelize.define('type', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, name: {type: DataTypes.STRING, unique: true, allowNull: false}, }) const Manufacturer = sequelize.define('manufacturer', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, name: {type: DataTypes.STRING, unique: true, allowNull: false}, }) const Rating = sequelize.define('rating', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, rate: {type: DataTypes.INTEGER, allowNull: false}, }) const MaterialInfo = sequelize.define('material_info', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, title: {type: DataTypes.STRING, allowNull: false}, description: {type: DataTypes.STRING, allowNull: false}, }) const TypeManufacturer = sequelize.define('type_manufacturer', { id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, }) User.hasOne(Basket) Basket.belongsTo(User) User.hasMany(Rating) Rating.belongsTo(User) Basket.hasMany(MaterialInfo) MaterialInfo.belongsTo(Basket) Type.hasMany(Material) Material.belongsTo(Type) Manufacturer.hasMany(Material) Material.belongsTo(Manufacturer) Material.hasMany(Rating) Rating.belongsTo(Material) Material.hasMany(BasketMaterial) BasketMaterial.belongsTo(Material) Material.hasMany(MaterialInfo, {as: 'info'}); MaterialInfo.belongsTo(Material) Type.belongsToMany(Manufacturer, {through: TypeManufacturer }) Manufacturer.belongsToMany(Type, {through: TypeManufacturer }) module.exports = { User, Basket, BasketMaterial, Material, Type, Manufacturer, Rating, TypeManufacturer, MaterialInfo }
package valueobject import ( "testing" vo "github.com/hcsouza/fiap-tech-fast-food/src/core/valueObject" "github.com/stretchr/testify/assert" ) func TestCategory(t *testing.T) { t.Run("should return true when category is Lanche", func(t *testing.T) { isValid := vo.Category("Lanche").IsValid() assert.True(t, isValid) }) t.Run("should return true when category is Bebida", func(t *testing.T) { isValid := vo.Category("Bebida").IsValid() assert.True(t, isValid) }) t.Run("should return true when category is Acompanhamento", func(t *testing.T) { isValid := vo.Category("Acompanhamento").IsValid() assert.True(t, isValid) }) t.Run("should return true when category is Sobremesa", func(t *testing.T) { isValid := vo.Category("Sobremesa").IsValid() assert.True(t, isValid) }) t.Run("should return false when category is unkown", func(t *testing.T) { isValid := vo.Category("Não mapeada").IsValid() assert.False(t, isValid) }) }
#ifndef _UPGRADEPATH_BACKUP_H_ #define _UPGRADEPATH_BACKUP_H_ // The "memory" structure for the upgrade methods typedef std::map<const std::string, std::string> MemoryMap; // The "memory" as used by the upgrade methods MemoryMap _memory; /* Copies a whole node (and all its children) from source/fromXPath to * the base registry/toXPath * * @returns: true, if the copy action was successful */ bool copyNode(xml::Document& source, const std::string& fromXPath, const std::string& toXPath) { // Try to load the node from the user.xml xml::NodeList from = source.findXPath(fromXPath); if (from.size() > 0) { // Make sure the target path exists xmlNodePtr toNode = createKey(toXPath); // Cycle through all the results and insert them into the registry for (unsigned int i = 0; i<from.size(); i++) { if (toNode != NULL && toNode->children != NULL) { globalOutputStream() << "XMLRegistry: Importing nodes matching " << fromXPath.c_str() << "\n"; // Insert the data here xmlAddPrevSibling(toNode->children, from[i].getNodePtr()); } else { globalOutputStream() << "XMLRegistry: Error: Could not create/find key: " << toXPath.c_str() << "\n"; return false; } } return true; } else { globalOutputStream() << "XMLRegistry: Error: Could not find fromXPath: " << fromXPath.c_str() << "\n"; return false; } } /* Deletes a node (and all its children) from source/fromXPath * * @returns: true, if the copy action was successful */ bool deleteNode(xml::Document& source, const std::string& xPath) { // Try to load the node from the user.xml xml::NodeList nodeList = source.findXPath(xPath); if (nodeList.size() > 0) { globalOutputStream() << "XMLRegistry: Deleting nodes matching " << xPath.c_str() << "\n"; for (unsigned int i = 0; i < nodeList.size(); i++) { // Delete the node nodeList[i].erase(); } } // Return true, no matter if the node was found or not return true; } /* Copies a value from source/fromXPath to the base registry/toXPath * * @returns: true, if the copy value action was successful */ bool copyValue(xml::Document& source, const std::string& fromXPath, const std::string& toXPath) { // Try to load the source node, return an empty string if nothing is found xml::NodeList nodeList = source.findXPath(fromXPath); // Does it even exist? if (nodeList.size() > 0) { // Load the node from the user's xml and get the value xml::Node node = nodeList[0]; const std::string valueToCopy = node.getAttributeValue("value"); globalOutputStream() << "XMLRegistry: Importing value: " << fromXPath.c_str() << "\n"; // Copy the value into the base registry set(toXPath, valueToCopy); return true; } else { globalOutputStream() << "XMLRegistry: copy_value not possible: " << fromXPath.c_str() << " not found, action skipped!\n"; return false; } } /* Adds the element <nodeName> as child to all nodes that match <toXPath> * with the name attribute set to <name>. The target document is <doc>. * * Note: This can and is intended to affect multiple nodes as well * * @returns: true, if everything went fine, false otherwise */ bool addNode(xml::Document& doc, const std::string& toXPath, const std::string& nodeName, const std::string& name) { xmlNodePtr insertPoint; bool returnValue = true; // Obtain a list of the nodes the child nodeName will be added to xml::NodeList nodeList = doc.findXPath(toXPath); for (unsigned int i = 0; i<nodeList.size(); i++) { insertPoint = nodeList[i].getNodePtr(); // Add the <nodeName> to the insert point xmlNodePtr createdNode = xmlNewChild(insertPoint, NULL, xmlCharStrdup(nodeName.c_str()), NULL); if (createdNode != NULL) { // Create an xml::Node out of the xmlNodePtr createdNode and set the name attribute xml::Node node(createdNode); node.addText("\n"); node.setAttributeValue("name", name); returnValue &= true; } else { globalOutputStream() << "XMLRegistry: Critical: Could not create insert point.\n"; returnValue = false; } } return returnValue; } /* Sets the attribute <attrName> of all nodes matching <xPath> to <attrValue> * and creates the attributes, if they are non-existant * * Note: This can and is intended to affect multiple nodes as well * * @returns: true */ bool setAttribute(xml::Document& doc, const std::string& xPath, const std::string& attrName, const std::string& attrValue) { globalOutputStream() << "XMLRegistry: Setting attribute " << attrName.c_str() << " of nodes matching XPath: " << xPath.c_str() << "..."; // Obtain a list of the nodes whose attributes should be altered xml::NodeList nodeList = doc.findXPath(xPath); for (unsigned int i = 0; i<nodeList.size(); i++) { nodeList[i].setAttributeValue(attrName, attrValue); } globalOutputStream() << nodeList.size() << " nodes affected.\n"; return true; } /* Finds the attribute <attrName> of the node matching <xPath> * and stores its value under the memory <memoryIndex> * * @returns: true, if everything went fine, false otherwise */ bool saveAttribute(xml::Document& doc, const std::string& xPath, const std::string& attrName, const std::string& memoryIndex) { // Obtain a list of the nodes that match the xPath criterion xml::NodeList nodeList = doc.findXPath(xPath); if (nodeList.size() > 0) { // Store the string into the specified memory location _memory[memoryIndex] = nodeList[0].getAttributeValue(attrName); return true; } else { globalOutputStream() << "XMLRegistry: Could not save attribute value " << attrName.c_str() << " located at " << xPath.c_str() << "\n"; return false; } } /* Retrieves the memory string _memory[memoryIndex] with a small existence check */ const std::string getMemory(const std::string& memoryIndex) { MemoryMap::iterator it = _memory.find(memoryIndex); return (it != _memory.end()) ? _memory[memoryIndex] : ""; } /* Replaces all the memory references in a string with the respective content from the memory */ std::string parseMemoryVars(const std::string& input) { // output = input for the moment std::string output = input; // Initialise the boost::regex, not the double escapes // (this should be "\{\$\d\}" and matches something like {$1} or {$23} boost::regex expr("\\{\\$(\\d)+\\}"); boost::match_results<std::string::iterator> results; // The iterators for wading through the string std::string::iterator start, end; start = output.begin(); end = output.end(); // Loop through the matches and replace the occurrences with the respective memory vars while (boost::regex_search(start, end, results, expr, boost::match_default)) { // Obtain the replacement string via the getMemory method const std::string replacement = getMemory(std::string(results[1].first, results[1].second)); // Replace the entire regex match results[0] with the replacement string output.replace(results[0].first, results[0].second, replacement); // Set the iterator to right after the match start = results[0].second; } // Now replace the {$ROOT} occurence with the XMLRegistry root key // The regex would be \{\$ROOT\}, but the backslashes have to be escaped for C++, hence the double expr = "\\{\\$ROOT\\}"; start = output.begin(); end = output.end(); while (boost::regex_search(start, end, results, expr, boost::match_default)) { const std::string replacement = std::string("/") + _topLevelNode; // Replace the entire regex match results[0] with the replacement string output.replace(results[0].first, results[0].second, replacement); // Set the iterator to right after the match start = results[0].second; } return output; } /* Performs the action defined in the actionNode * * @returns: true if everything went fine, false otherwise */ bool performAction(xml::Document& userDoc, xml::Node& actionNode) { // Determine what action is to be performed const std::string actionName = actionNode.getName(); // Determine which registry is the target for this operation const std::string target = actionNode.getAttributeValue("target"); xml::Document& targetDoc = (target == "base") ? _registry : userDoc; // Copy a whole node (as specified by an xpath) into the base registry if (actionName == "copyNode") { const std::string fromXPath = parseMemoryVars(actionNode.getAttributeValue("fromXPath")); const std::string toXPath = parseMemoryVars(actionNode.getAttributeValue("toXPath")); // Copy the node from userDoc>fromXPath to the base registry>toXPath return copyNode(targetDoc, fromXPath, toXPath); } // Copy an attribute value from the user xml into the base registry else if (actionName == "copyValue") { const std::string fromXPath = parseMemoryVars(actionNode.getAttributeValue("fromXPath")); const std::string toXPath = parseMemoryVars(actionNode.getAttributeValue("toXPath")); // Copy the value from userDoc>fromXPath to the base registry>toXPath return copyValue(targetDoc, fromXPath, toXPath); } // Delete a whole node from the user xml (useful to clean things up before copying them) else if (actionName == "deleteNode") { const std::string xPath = parseMemoryVars(actionNode.getAttributeValue("xPath")); // Delete the value from userDoc>xPath return deleteNode(targetDoc, xPath); } // Add an element to a all nodes matching toXPath else if (actionName == "addNode") { const std::string toXPath = parseMemoryVars(actionNode.getAttributeValue("toXPath")); const std::string nodeName = parseMemoryVars(actionNode.getAttributeValue("nodeName")); const std::string name = parseMemoryVars(actionNode.getAttributeValue("name")); return addNode(targetDoc, toXPath, nodeName, name); } // Set the attribute of all nodes matching xPath else if (actionName == "setAttribute") { const std::string xPath = parseMemoryVars(actionNode.getAttributeValue("xPath")); const std::string attrName = parseMemoryVars(actionNode.getAttributeValue("name")); const std::string attrValue = parseMemoryVars(actionNode.getAttributeValue("value")); return setAttribute(targetDoc, xPath, attrName, attrValue); } // Find the attribute of the node matching xPath and save it under memoryIndex else if (actionName == "saveAttribute") { const std::string xPath = parseMemoryVars(actionNode.getAttributeValue("xPath")); const std::string attrName = parseMemoryVars(actionNode.getAttributeValue("name")); const std::string memoryIndex = parseMemoryVars(actionNode.getAttributeValue("memoryIndex")); return saveAttribute(targetDoc, xPath, attrName, memoryIndex); } // No action taken, that was kind of a success :) return true; } /* Imports the values from userDoc into the base registry according * to the defined upgrade paths * * @returns: true if everything went well, and false, if one or more actions * failed during the import process */ bool performUpgrade(xml::Document& userDoc, const std::string& version) { // Load the upgrade information from the base registry std::string upgradePathXPath = std::string("user/upgradePaths/upgradePath"); upgradePathXPath += "[@fromVersion='" + version + "']"; xml::NodeList upgradePaths = findXPath(upgradePathXPath); // Up to now everything went fine... bool returnValue = true; // Any upgrade paths found? if (upgradePaths.size() > 0) { globalOutputStream() << "Upgrade path information found, upgrading...\n"; // Load the upgradeItems from the registry xml::NodeList upgradeItems = upgradePaths[0].getChildren(); // Execute the actions defined in this upgradepath for (unsigned int i = 0; i < upgradeItems.size(); i++) { // returnValue can only be true if both values are true returnValue &= performAction(userDoc, upgradeItems[i]); } return returnValue; } else { // Bail out globalOutputStream() << "XMLRegistry: Error: Could not load upgrade path information!\n"; return false; } } // Imports the specified file and checks if an upgrade has to be made void importUserXML(const std::string& pathToUserXML) { std::string filename = pathToUserXML; std::string userVersion = "0.5.0"; globalOutputStream() << "XMLRegistry: Importing user.xml from " << filename.c_str() << "\n"; // Load the user xml to check if it can be upgraded file xmlDocPtr pUserDoc = xmlParseFile(filename.c_str()); // Could the document be parsed or is it bogus? if (pUserDoc) { // Convert it into xml::Document and load the top-level node(s) (there should only be one) xml::Document userDoc(pUserDoc); xml::NodeList versionNode = userDoc.findXPath("/user/version"); // Check if the version tag exists if (versionNode.size() > 0) { // It exists, load it and compare it to the base version userVersion = versionNode[0].getAttributeValue("value"); } else { // No version tag, this definitely has to be upgraded... globalOutputStream() << "XMLRegistry: No version tag found, assuming version 0.5.0" << "\n"; } std::string baseVersion = get("user/version"); // Check if the upgrade is necessary if (baseVersion > userVersion) { // Yes it is necessary, userVersion < baseVersion globalOutputStream() << "XMLRegistry: Upgrading " << filename.c_str() << " from version: " << userVersion.c_str() << " to " << baseVersion.c_str() << "\n"; // Create a backup of the old file std::string backupFileName = filename; boost::algorithm::replace_last(backupFileName, ".xml", std::string(".") + userVersion + ".xml"); userDoc.saveToFile(backupFileName); // Everything is loaded and backed up, call the upgrade method performUpgrade(userDoc, userVersion); } else { // Version is up to date, no upgrade necessary, import the file as it is importFromFile(filename, ""); } } else { globalOutputStream() << "XMLRegistry: Critical: Could not parse " << filename.c_str() << "\n"; globalOutputStream() << "XMLRegistry: Critical: File does not exist or is not valid XML!\n"; } } #endif /*_UPGRADEPATH_BACKUP_H_*/
import React from "react"; import { Link } from "gatsby"; import "../styles/footer.scss"; const Logo = () => { return ( <Link className="footer-logo" to="/"> <img className="footer-logo__image" src="https://global-uploads.webflow.com/5deea2e254c6bb904cf59c96/5e45e151f236a82c108b5b68_logo10.svg" alt="" /> <img className="footer-logo__text" src="https://global-uploads.webflow.com/5deea2e254c6bb904cf59c96/5e45cc9946e3c4dd2aaf3a86_logo9.svg" alt="" /> </Link> ); }; const Copyright = () => { return ( <span className="footer-copyright"> {"Copyright © "} {new Date().getFullYear()}{" "} <a className="footer-copyright__link" href="https://www.finicast.com/"> Finicast, Inc </a> {"."} </span> ); }; const CTA = () => { return ( <div className="footer-cta"> <button className="footer-cta__button">Lets Get in Touch</button> </div> ); }; const Navbar = () => { return ( <nav className="footer-navbar"> <span className="footer-navbar__heading">About Us</span> <ul className="footer-navbar__list"> <li className="footer-navbar__item"> <Link className="footer-navbar__link" to="/about"> Who We Are </Link> </li> <li className="footer-navbar__item"> <a className="footer-navbar__link" href="https://www.linkedin.com/company/finicast/jobs/" target="_blank" rel="noopener noreferrer" > Careers </a> </li> <li className="footer-navbar__item"> <Link className="footer-navbar__link" to="/contact"> Contact Us </Link> </li> </ul> </nav> ); }; const Footer = () => { return ( <footer className="footer"> <div className="footer__content"> <CTA /> <Navbar /> <div className="footer-logo-group"> <Logo /> <Copyright /> </div> </div> </footer> ); }; export default Footer;
import { useState, useEffect } from 'react' import './App.css' import axios from 'axios'; //Functions function useTodo(){ const [todos, setTodos] = useState([]); useEffect(() => { setInterval(()=>{ axios.get("http://localhost:3000/todos").then((response) => { setTodos(response.data); })}, 1000); },[]) return todos; } function App() { // fetch all todos from server const todos = useTodo(); const [newTodo, setNewTodo] = useState({title : "", description: ""}); // Event handler for title input const handleTitleChange = (event) => { setNewTodo({ ...newTodo, title: event.target.value }); }; // Event handler for description input const handleDescriptionChange = (event) => { setNewTodo({ ...newTodo, description: event.target.value }); }; return ( <> <div> <h1>Easy Todo App</h1> <br /> <h2>Title</h2> <input type="text" onChange = {handleTitleChange}/> <h3>Description</h3> <input type="text" onChange = {handleDescriptionChange}/> <br/> <br/> <button onClick={() => { axios.post("http://localhost:3000/todos", newTodo); } }>Create Todo</button> <br/> {todos.map((item) => { return <Todo title = {item.title} description = {item.description} id = {item.id} ></Todo>; })} </div> </> ) } function Todo(props) { // Add a delete button here so user can delete a TODO. return <div> {props.title} {props.description} <button onClick = {() => { axios.delete(`http://localhost:3000/todos/${props.id}`); }}> DELETE </button> </div> } export default App
package jpabook.jpashop.api; import jakarta.validation.constraints.NotEmpty; import jpabook.jpashop.domain.Member; import jpabook.jpashop.service.MemberService; import lombok.AllArgsConstructor; import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; @RestController @RequiredArgsConstructor @Slf4j public class MemberApiController { private final MemberService memberService; @GetMapping("/api/v1/members") public List<Member> memberV1() { return memberService.findMembers(); } @GetMapping("/api/v2/members") public Result memberV2() { List<Member> findMembers = memberService.findMembers(); List<MemberDto> collect = findMembers.stream() .map(m -> new MemberDto(m.getName())) .collect(Collectors.toList()); return new Result(collect.size(), collect); } @Data @AllArgsConstructor static class Result<T> { private int count; private T data; } @Data @AllArgsConstructor static class MemberDto { private String name; } @PostMapping ("/api/v1/members") public CreateMemberResponse saveMemberV1(@RequestBody @Validated Member member) { Long id = memberService.join(member); return new CreateMemberResponse(id); } @DeleteMapping("/api/v1/deleteMember") public Long deleteMemberV1(@RequestBody deleteMemberRequest request) { return memberService.deleteMember(request.getName()); } @PostMapping("/api/v2/members") public CreateMemberResponse saveMemberV2(@RequestBody @Validated CreateMemberRequest request) { Member member = new Member(); member.setName(request.getName()); Long id = memberService.join(member); return new CreateMemberResponse(id); } @PutMapping("/api/v2/members/{id}") public UpdateMemberResponse updateMemberV2(@PathVariable("id") Long id, @RequestBody @Validated updateMemberRequest request) { memberService.update(id, request.getName()); Member findMember = memberService.findOne(id); return new UpdateMemberResponse(findMember.getId(), findMember.getName()); } @Data static class CreateMemberResponse { private Long id; public CreateMemberResponse(Long id) { this.id = id; } } @Data static class CreateMemberRequest { @NotEmpty(message = "회원 명을 입력하세요.") private String name; } @Data static class updateMemberRequest { private String name; } @Data @AllArgsConstructor static class UpdateMemberResponse { private Long id; private String name; } @Data static class deleteMemberRequest { private String name; } }
/** * Copyright 2010-2022 interactive instruments GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.interactive_instruments.etf.testdriver; import static de.interactive_instruments.etf.testdriver.AbstractTestResultCollector.ResultCollectorState.*; /** * * @author Jon Herrmann ( herrmann aT interactive-instruments doT de ) */ public abstract class AbstractTestResultCollector extends AbstractTestCollector implements TestResultCollector { protected enum ResultCollectorState { READY, WRITING_TEST_TASK_RESULT, WRITING_TEST_MODULE_RESULT, WRITING_TEST_CASE_RESULT, WRITING_TEST_STEP_RESULT, WRITING_CALLED_TEST_CASE_RESULT, CALLED_TEST_CASE_RESULT_FINISHED, WRITING_CALLED_TEST_STEP_RESULT, CALLED_TEST_STEP_RESULT_FINISHED, WRITING_TEST_ASSERTION_RESULT, TEST_ASSERTION_RESULT_FINISHED, TEST_STEP_RESULT_FINISHED, TEST_CASE_RESULT_FINISHED, TEST_MODULE_RESULT_FINISHED, TEST_TASK_RESULT_FINISHED, } private ResultCollectorState currentState = ResultCollectorState.READY; private AbstractTestTaskProgress taskProgress; private String testTaskResultId; private void setState(final ResultCollectorState newState) { logger.trace("Switching from state {} to state {} ", this.currentState, newState); this.currentState = newState; } void setTaskProgress(final AbstractTestTaskProgress taskProgress) { this.taskProgress = taskProgress; } abstract protected String startTestTaskResult(final String resultedFrom, final long startTimestamp) throws Exception; @Override public String getTestTaskResultId() { return testTaskResultId; } @Override final public String doStartTestTask(final String testModelItemId, final long startTimestamp) throws IllegalArgumentException, IllegalStateException { if (currentState != READY) { throw new IllegalStateException( "Illegal state transition: cannot start writing Test Task result when in " + currentState + " state"); } setState(WRITING_TEST_TASK_RESULT); try { testTaskResultId = startTestTaskResult(testModelItemId, startTimestamp); return testTaskResultId; } catch (Exception e) { throw new IllegalArgumentException(e); } } abstract protected String startTestModuleResult(final String resultedFrom, final long startTimestamp) throws Exception; @Override final public String doStartTestModule(final String testModelItemId, final long startTimestamp) throws IllegalArgumentException, IllegalStateException { if (currentState != WRITING_TEST_TASK_RESULT && currentState != TEST_MODULE_RESULT_FINISHED) { throw new IllegalStateException( "Illegal state transition: cannot start writing Test Module result when in " + currentState + " state"); } setState(WRITING_TEST_MODULE_RESULT); try { return startTestModuleResult(testModelItemId, startTimestamp); } catch (Exception e) { throw new IllegalArgumentException(e); } } @Override final public String startTestCase(final String testModelItemId, final long startTimestamp) throws IllegalArgumentException, IllegalStateException { try { switch (currentState) { case WRITING_TEST_MODULE_RESULT: case TEST_CASE_RESULT_FINISHED: setState(WRITING_TEST_CASE_RESULT); return startTestCaseResult(testModelItemId, startTimestamp); case WRITING_TEST_STEP_RESULT: startInvokedTests(); case CALLED_TEST_CASE_RESULT_FINISHED: case CALLED_TEST_STEP_RESULT_FINISHED: setState(WRITING_CALLED_TEST_CASE_RESULT); subCollector = createCalledTestCaseResultCollector(this, testModelItemId, startTimestamp); return subCollector.currentResultItemId(); case WRITING_CALLED_TEST_CASE_RESULT: case WRITING_CALLED_TEST_STEP_RESULT: return subCollector.startTestCase(testModelItemId, startTimestamp); } throw new IllegalStateException( "Illegal state transition: cannot start writing Test Case result when in " + currentState + " state"); } catch (Exception e) { throw new IllegalArgumentException(e); } } @Override final public String startTestStep(final String testModelItemId, final long startTimestamp) throws IllegalArgumentException, IllegalStateException { try { switch (currentState) { case WRITING_TEST_CASE_RESULT: case TEST_STEP_RESULT_FINISHED: setState(WRITING_TEST_STEP_RESULT); return startTestStepResult(testModelItemId, startTimestamp); case WRITING_TEST_STEP_RESULT: startInvokedTests(); case CALLED_TEST_CASE_RESULT_FINISHED: case CALLED_TEST_STEP_RESULT_FINISHED: setState(WRITING_CALLED_TEST_STEP_RESULT); subCollector = createCalledTestStepResultCollector(this, testModelItemId, startTimestamp); return subCollector.currentResultItemId(); case WRITING_CALLED_TEST_CASE_RESULT: case WRITING_CALLED_TEST_STEP_RESULT: return subCollector.startTestStep(testModelItemId, startTimestamp); } throw new IllegalStateException( "Illegal state transition: cannot start writing Test Step result when in " + currentState + " state"); } catch (Exception e) { throw new IllegalArgumentException(e); } } @Override final public String startTestAssertion(final String testModelItemId, final long startTimestamp) throws IllegalArgumentException, IllegalStateException { try { switch (currentState) { case CALLED_TEST_CASE_RESULT_FINISHED: case CALLED_TEST_STEP_RESULT_FINISHED: endInvokedTests(); case WRITING_TEST_STEP_RESULT: startTestAssertionResults(); case TEST_ASSERTION_RESULT_FINISHED: setState(WRITING_TEST_ASSERTION_RESULT); return startTestAssertionResult(testModelItemId, startTimestamp); case WRITING_CALLED_TEST_CASE_RESULT: case WRITING_CALLED_TEST_STEP_RESULT: return subCollector.startTestAssertion(testModelItemId, startTimestamp); } throw new IllegalStateException( "Illegal state transition: cannot start writing Test Assertion result when in " + currentState + " state"); } catch (Exception e) { throw new IllegalArgumentException(e); } } abstract protected String endTestTaskResult(final String testModelItemId, final int status, final long stopTimestamp) throws Exception; abstract protected String endTestModuleResult(final String testModelItemId, final int status, final long stopTimestamp) throws Exception; @Override final public String doEnd(final String testModelItemId, final int status, final long stopTimestamp) throws IllegalArgumentException, IllegalStateException { try { switch (currentState) { case TEST_MODULE_RESULT_FINISHED: setState(TEST_TASK_RESULT_FINISHED); return endTestTaskResult(testModelItemId, status, stopTimestamp); case TEST_CASE_RESULT_FINISHED: setState(TEST_MODULE_RESULT_FINISHED); return endTestModuleResult(testModelItemId, status, stopTimestamp); case TEST_STEP_RESULT_FINISHED: case WRITING_TEST_CASE_RESULT: setState(TEST_CASE_RESULT_FINISHED); return endTestCaseResult(testModelItemId, status, stopTimestamp); case CALLED_TEST_CASE_RESULT_FINISHED: case CALLED_TEST_STEP_RESULT_FINISHED: endInvokedTests(); setState(TEST_STEP_RESULT_FINISHED); return endTestStepResult(testModelItemId, status, stopTimestamp); case TEST_ASSERTION_RESULT_FINISHED: endTestAssertionResults(); case WRITING_TEST_STEP_RESULT: // no assertions or invoked tests added setState(TEST_STEP_RESULT_FINISHED); return endTestStepResult(testModelItemId, status, stopTimestamp); case WRITING_TEST_ASSERTION_RESULT: setState(TEST_ASSERTION_RESULT_FINISHED); if (taskProgress != null) { taskProgress.advance(); } return endTestAssertionResult(testModelItemId, status, stopTimestamp); case WRITING_CALLED_TEST_CASE_RESULT: case WRITING_CALLED_TEST_STEP_RESULT: return subCollector.end(testModelItemId, status, stopTimestamp); } throw new IllegalStateException( "Illegal state transition: cannot end result structure when in " + currentState + " state"); } catch (final Exception e) { logger.error("An internal error occurred finishing result {} ", testModelItemId, e); notifyError(); throw new IllegalStateException(e); } } /** * Called by a SubCollector */ public void prepareSubCollectorRelease() { if (currentState == WRITING_CALLED_TEST_CASE_RESULT) { setState(CALLED_TEST_CASE_RESULT_FINISHED); } else if (currentState == WRITING_CALLED_TEST_STEP_RESULT) { setState(CALLED_TEST_STEP_RESULT_FINISHED); } else { throw new IllegalStateException( "Illegal state transition: cannot release sub collector when in " + currentState + " state"); } } @Override public int currentModelType() { switch (currentState) { case WRITING_TEST_TASK_RESULT: case TEST_MODULE_RESULT_FINISHED: return 1; case WRITING_TEST_MODULE_RESULT: case TEST_CASE_RESULT_FINISHED: return 2; case WRITING_TEST_CASE_RESULT: case TEST_STEP_RESULT_FINISHED: return 3; case WRITING_TEST_STEP_RESULT: case CALLED_TEST_CASE_RESULT_FINISHED: case CALLED_TEST_STEP_RESULT_FINISHED: case TEST_ASSERTION_RESULT_FINISHED: return 4; case WRITING_TEST_ASSERTION_RESULT: return 5; case WRITING_CALLED_TEST_CASE_RESULT: return subCollector.currentModelType(); case WRITING_CALLED_TEST_STEP_RESULT: return subCollector.currentModelType(); } return -1; } @Override public String toString() { final StringBuffer sb = new StringBuffer("TestResultCollector {"); sb.append("currentState=").append(currentState).append(", "); sb.append("aggregatedSubStatus=").append(getContextStatus()).append(", "); sb.append("subCollector=").append(subCollector != null ? subCollector.toString() : "none"); sb.append('}'); return sb.toString(); } }
<h1 align="center">GeoAuxNet: Towards Universal 3D Representation Learning for Multi-sensor Point Clouds</h1> <div align='center'> Shengjun Zhang, Xin Fei, <a href='https://duanyueqi.github.io/'>Yueqi Duan</a> </div> <div align='center'> Department of Electronic Engineering, Tsinghua University </div> <div align='center'> Department of Automation, Tsinghua University </div> <div align='center'> <a href="https://arxiv.org/pdf/2403.19220.pdf">View CVPR 2024 Paper Here</a> </div> <div id='result image' style='margin-top: 10px'> <img src='result.png'> <p align='center'>Semantic segmentation results on S3DIS and ScanNet from RGB-D cameras and SemanticKITTI from LiDAR. For all methods, we trained collectively on three datasets. Our method outperforms other methods with better detailed structures.</p> </div> <div style="width: 100%; text-align: center;" align='center'> <table style="margin: 0 auto;"> <thead> <tr> <th style="text-align: center;">Model</th> <th style="text-align: center;">Params</th> <th style="text-align: center;">S3DIS mIoU</th> <th style="text-align: center;">ScanNet mIoU</th> <th style="text-align: center;">SemanticKITTI mIoU</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">GeoAuxNet (joint)</td> <td style="text-align: center;">64.7M</td> <td style="text-align: center;">69.5</td> <td style="text-align: center;">71.3</td> <td style="text-align: center;">63.8</td> </tr> </tbody> </table> </div> ## Overview - [Installation](#installation) - [Data Preparation](#data-preparation) - [Quick Start](#quick-start) ## Installation ### Requirements - Ubuntu: 18.04 or higher - CUDA: 11.3 or higher - PyTorch: 1.10.0 or higher ### Conda Environment - Tested on Ubuntu 20.04.1, CUDA 11.6, pytorch==1.13.1 - See requirement.yaml for tested environment ```bash conda create -n geo-aux python=3.8 -y conda activate geo-aux conda install ninja -y # Choose version you want here: https://pytorch.org/get-started/previous-versions/ conda install pytorch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 pytorch-cuda=11.7 -c pytorch -c nvidia conda install h5py pyyaml -c anaconda -y conda install sharedarray tensorboard tensorboardx yapf addict einops scipy plyfile termcolor timm -c conda-forge -y conda install pytorch-cluster pytorch-scatter pytorch-sparse -c pyg -y pip install torch-geometric pip install faiss-gpu # spconv (SparseUNet) # refer GitHub - traveller59/spconv: Spatial Sparse Convolution Library pip install spconv-cu117 # PTv1 & PTv2 or precise eval cd libs/pointops python setup.py install # docker & multi GPU arch TORCH_CUDA_ARCH_LIST="ARCH LIST" python setup.py install # e.g. 7.5: RTX 3000; 8.0: a100 More available in: https://developer.nvidia.com/cuda-gpus TORCH_CUDA_ARCH_LIST="7.5 8.0" python setup.py install cd ../.. # Open3D (visualization, optional) pip install open3d ``` ## Data Preparation ### S3DIS - Run preprocessing code for S3DIS as follows: ```bash # S3DIS_DIR: the directory of downloaded Stanford3dDataset_v1.2 dataset. # RAW_S3DIS_DIR: the directory of Stanford2d3dDataset_noXYZ dataset. (optional, for parsing normal) # PROCESSED_S3DIS_DIR: the directory of processed S3DIS dataset (output dir). # S3DIS without aligned angle python pointcept/datasets/preprocessing/s3dis/preprocess_s3dis.py --dataset_root ${S3DIS_DIR} --output_root ${PROCESSED_S3DIS_DIR} ``` - The processed s3dis dir should be organized as follow ```bash s3dis │── Area_1 │── conferenceRoom_1.pth │── conferenceRoom_2.pth ... │── Area_2 ... │── Area_6 ``` ### ScanNet The preprocessing support semantic and instance segmentation for both `ScanNet20`, `ScanNet200` and `ScanNet Data Efficient`. - Download the [ScanNet](http://www.scan-net.org/) v2 dataset. - Run preprocessing code for raw ScanNet as follows: ```bash # RAW_SCANNET_DIR: the directory of downloaded ScanNet v2 raw dataset. # PROCESSED_SCANNET_DIR: the directory of processed ScanNet dataset (output dir). python pointcept/datasets/preprocessing/scannet/preprocess_scannet.py --dataset_root ${RAW_SCANNET_DIR} --output_root ${PROCESSED_SCANNET_DIR} ``` - The processed scannet dir should be organized as follow ```bash scannet │── train │── scene0000_00.pth │── scene0000_01.pth ... │── val ... │── test ... ``` ### SemanticKITTI - Download [SemanticKITTI](http://www.semantic-kitti.org/dataset.html#download) dataset. - Link dataset to codebase. - The processed semanticKITTI dir should be organized as follow - ```bash |- semantic_kitti |- dataset |- sequences |- 00 |- 01 |- ... |- poses |- 00.txt ... ``` ### nuScenes - Download the official [NuScene](https://www.nuscenes.org/nuscenes#download) dataset (with Lidar Segmentation) and organize the downloaded files as follows: ```bash NUSCENES_DIR │── samples │── sweeps │── lidarseg ... │── v1.0-trainval │── v1.0-test ``` - Run information preprocessing code (modified from OpenPCDet) for nuScenes as follows: ```bash # NUSCENES_DIR: the directory of downloaded nuScenes dataset. # PROCESSED_NUSCENES_DIR: the directory of processed nuScenes dataset (output dir). # MAX_SWEEPS: Max number of sweeps. Default: 10. pip install nuscenes-devkit pyquaternion python pointcept/datasets/preprocessing/nuscenes/preprocess_nuscenes_info.py --dataset_root ${NUSCENES_DIR} --output_root ${PROCESSED_NUSCENES_DIR} --max_sweeps ${MAX_SWEEPS} --with_camera python pointcept/datasets/preprocessing/nuscenes/preprocess_nuscenes_info.py --dataset_root data/nuscenes --output_root data/preprocess_nuscenes --max_sweeps 10 --with_camera ``` - Link raw dataset to processed NuScene dataset folder: ```bash # NUSCENES_DIR: the directory of downloaded nuScenes dataset. # PROCESSED_NUSCENES_DIR: the directory of processed nuScenes dataset (output dir). ln -s ${NUSCENES_DIR} {PROCESSED_NUSCENES_DIR}/raw ``` then the processed nuscenes folder is organized as follows: ```bash nuscene |── raw │── samples │── sweeps │── lidarseg ... │── v1.0-trainval │── v1.0-test |── info ``` ## Quick Start ### Training **Train from scratch.** The training processing is based on configs in `configs` folder. The training script will generate an experiment folder in `exp` folder and backup essential code in the experiment folder. Training config, log, tensorboard and checkpoints will also be saved into the experiment folder during the training process. ```bash export CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES} # Script (Recommended) sh scripts/train.sh -p ${INTERPRETER_PATH} -g ${NUM_GPU} -d ${DATASET_NAME} -c ${CONFIG_NAME} -n ${EXP_NAME} # Direct export PYTHONPATH=./ python tools/train.py --config-file ${CONFIG_PATH} --num-gpus ${NUM_GPU} --options save_path=${SAVE_PATH} ``` For example: ```bash # By script export CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES} sh scripts/train.sh -p python -d s3dis -c semseg-geo-s3-sc-sk -n semseg-geo-s3-sc-sk -g 4 # Direct export PYTHONPATH=./ python tools/train.py --config-file configs/s3dis/semseg-geo-s3-sc-sk.py --num-gpus 4 --options save_path=exp/s3dis/semseg-geo-s3-sc-sk resume=True ``` **Resume training from checkpoint.** If the training process is interrupted by accident, the following script can resume training from a given checkpoint. ```bash # Script (Recommended) # simply add "-r true" sh scripts/train.sh -p ${INTERPRETER_PATH} -g ${NUM_GPU} -d ${DATASET_NAME} -c ${CONFIG_NAME} -n ${EXP_NAME} -r true # Direct export PYTHONPATH=./ python tools/train.py --config-file ${CONFIG_PATH} --num-gpus ${NUM_GPU} --options save_path=${SAVE_PATH} resume=True weight=${CHECKPOINT_PATH} ``` ### Testing ```bash # By script (Based on experiment folder created by training script) sh scripts/test.sh -p ${INTERPRETER_PATH} -g ${NUM_GPU} -d ${DATASET_NAME} -n ${EXP_NAME} -w ${CHECKPOINT_NAME} # Direct export PYTHONPATH=./ python tools/test.py --config-file ${CONFIG_PATH} --num-gpus ${NUM_GPU} --options save_path=${SAVE_PATH} weight=${CHECKPOINT_PATH} ``` For example: ```bash sh scripts/test.sh -p python -d s3dis -n semseg-geo-s3-sc-sk -w model_best -g 1 # Direct export PYTHONPATH=./ python tools/test.py --config-file configs/s3dis/semseg-geo-s3-sc-sk.py --options save_path=exp/s3dis/semseg-geo-s3-sc-sk weight=exp/s3dis/semseg-geo-s3-sc-sk/model/model_best.pth --num-gpus 1 ```
## AWS C MQTT C99 implementation of the MQTT 3.1.1 specification. ## License This library is licensed under the Apache 2.0 License. ## Usage ### Building CMake 3.1+ is required to build. `<install-path>` must be an absolute path in the following instructions. #### Linux-Only Dependencies If you are building on Linux, you will need to build aws-lc and s2n-tls first. ``` git clone [email protected]:awslabs/aws-lc.git cmake -S aws-lc -B aws-lc/build -DCMAKE_INSTALL_PREFIX=<install-path> cmake --build aws-lc/build --target install git clone [email protected]:aws/s2n-tls.git cmake -S s2n-tls -B s2n-tls/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path> cmake --build s2n-tls/build --target install ``` #### Building aws-c-mqtt and Remaining Dependencies ``` git clone [email protected]:awslabs/aws-c-common.git cmake -S aws-c-common -B aws-c-common/build -DCMAKE_INSTALL_PREFIX=<install-path> cmake --build aws-c-common/build --target install git clone [email protected]:awslabs/aws-c-cal.git cmake -S aws-c-cal -B aws-c-cal/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path> cmake --build aws-c-cal/build --target install git clone [email protected]:awslabs/aws-c-io.git cmake -S aws-c-io -B aws-c-io/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path> cmake --build aws-c-io/build --target install git clone [email protected]:awslabs/aws-c-compression.git cmake -S aws-c-compression -B aws-c-compression/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path> cmake --build aws-c-compression/build --target install git clone [email protected]:awslabs/aws-c-http.git cmake -S aws-c-http -B aws-c-http/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path> cmake --build aws-c-http/build --target install git clone [email protected]:awslabs/aws-c-mqtt.git cmake -S aws-c-mqtt -B aws-c-mqtt/build -DCMAKE_INSTALL_PREFIX=<install-path> -DCMAKE_PREFIX_PATH=<install-path> cmake --build aws-c-mqtt/build --target install ``` ### Overview This library contains an MQTT implementation that is simple and easy to use, but also quite powerful and low on unnecessary copies. Here is a general overview of the API: ### `struct aws_mqtt_client;` `aws_mqtt_client` is meant to be created once per application to pool common resources required for opening MQTT connections. The instance does not need to be allocated, and may be managed by the user. ```c int aws_mqtt_client_init( struct aws_mqtt_client *client, struct aws_allocator *allocator, struct aws_event_loop_group *elg); ``` Initializes an instance of `aws_mqtt_client` with the required parameters. * `client` is effectively the `this` parameter. * `allocator` will be used to initialize the client (note that the client itself is NOT allocated). *This resource must outlive `client`*. * `bootstrap` will be used to initiate new socket connections MQTT. *This resource must outlive `client`*. See [aws-c-io][aws-c-io] for more information about `aws_client_bootstrap`. ```c void aws_mqtt_client_clean_up(struct aws_mqtt_client *client); ``` Cleans up a client and frees all owned resources. **NOTE**: DO NOT CALL THIS FUNCTION UNTIL ALL OUTSTANDING CONNECTIONS ARE CLOSED. ### `struct aws_mqtt_client_connection;` ```c struct aws_mqtt_client_connection *aws_mqtt_client_connection_new( struct aws_mqtt_client *client, struct aws_mqtt_client_connection_callbacks callbacks, const struct aws_byte_cursor *host_name, uint16_t port, struct aws_socket_options *socket_options, struct aws_tls_ctx_options *tls_options); ``` Allocates and initializes a new connection object (does NOT actually connect). You may use the returned object to configure connection parameters, and then call `aws_mqtt_client_connection_connect` to actually open the connection. * `client` is required in order to use an existing DNS resolver, event loop group, and allocator. * `callbacks` provides the connection-level (not operation level) callbacks and the userdata to be given back. * `host_name` lists the end point to connect to. This may be a DNS address or an IP address. *This resource may be freed immediately after return.* * `port` the port to connect to on `host_name`. * `socket_options` describes how to open the connection. See [aws-c-io][aws-c-io] for more information about `aws_socket_options`. * `tls_options` provides TLS credentials to connect with. Pass `NULL` to not use TLS (**NOT RECOMMENDED**). See [aws-c-io][aws-c-io] for more information about `aws_tls_ctx_options`. ```c void aws_mqtt_client_connection_destroy(struct aws_mqtt_client_connection *connection); ``` Destroys a connection and frees all outstanding resources. **NOTE**: DO NOT CALL THIS FUNCTION UNTIL THE CONNECTION IS CLOSED. ```c int aws_mqtt_client_connection_set_will( struct aws_mqtt_client_connection *connection, const struct aws_byte_cursor *topic, enum aws_mqtt_qos qos, bool retain, const struct aws_byte_cursor *payload); ``` Sets the last will and testament to be distributed by the server upon client disconnection. Must be called before `aws_mqtt_client_connection_connect`. See `aws_mqtt_client_connection_publish` for information on the parameters. `topic` and `payload` must persist past the call to `aws_mqtt_client_connection_connect`. ```c int aws_mqtt_client_connection_set_login( struct aws_mqtt_client_connection *connection, const struct aws_byte_cursor *username, const struct aws_byte_cursor *password); ``` Sets the username and password to be sent to the server on connection. Must be called before `aws_mqtt_client_connection_connect`. `username` and `password` must persist past the call to `aws_mqtt_client_connection_connect`. ```c int aws_mqtt_client_connection_set_reconnect_timeout( struct aws_mqtt_client_connection *connection, uint64_t min_timeout, uint64_t max_timeout); ``` Sets the minimum and maximum reconnect timeouts. The time between reconnect attempts will start at min and multipy by 2 until max is reached. ```c int aws_mqtt_client_connection_connect( struct aws_mqtt_client_connection *connection, const struct aws_byte_cursor *client_id, bool clean_session, uint16_t keep_alive_time); ``` Connects to the remote endpoint. The parameters here are set in the MQTT CONNECT packet directly. `client_id` must persist until the `on_connack` connection callback is called. ```c int aws_mqtt_client_connection_disconnect(struct aws_mqtt_client_connection *connection); ``` Closes an open connection. Does not clean up any resources, that's to be done by `aws_mqtt_client_connection_destroy`, probably from the `on_disconnected` connection callback. ```c uint16_t aws_mqtt_client_connection_subscribe_single( struct aws_mqtt_client_connection *connection, const struct aws_byte_cursor *topic_filter, enum aws_mqtt_qos qos, aws_mqtt_client_publish_received_fn *on_publish, void *on_publish_ud, aws_mqtt_suback_single_fn *on_suback, void *on_suback_ud); ``` Subscribes to the topic filter given with the given QoS. `on_publish` will be called whenever a packet matching `topic_filter` arrives. `on_suback` will be called when the SUBACK packet has been received. `topic_filter` must persist until `on_suback` is called. The packet_id of the SUBSCRIBE packet will be returned, or 0 on error. ```c uint16_t aws_mqtt_client_connection_unsubscribe( struct aws_mqtt_client_connection *connection, const struct aws_byte_cursor *topic_filter, aws_mqtt_op_complete_fn *on_unsuback, void *on_unsuback_ud); ``` Unsubscribes from the topic filter given. `topic_filter` must persist until `on_unsuback` is called. The packet_id of the UNSUBSCRIBE packet will be returned, or 0 on error. ```c uint16_t aws_mqtt_client_connection_publish( struct aws_mqtt_client_connection *connection, const struct aws_byte_cursor *topic, enum aws_mqtt_qos qos, bool retain, const struct aws_byte_cursor *payload, aws_mqtt_op_complete_fn *on_complete, void *userdata); ``` Publish a payload to the topic specified. For QoS 0, `on_complete` will be called as soon as the packet is sent over the wire. For QoS 1, as soon as PUBACK comes back. For QoS 2, PUBCOMP. `topic` and `payload` must persist until `on_complete`. ```c int aws_mqtt_client_connection_ping(struct aws_mqtt_client_connection *connection); ``` Sends a PINGREQ packet to the server. [aws-c-io]: https://github.com/awslabs/aws-c-io
% function textBar(labels, y, [ax], [col], [lb], [ub]) % % Generates a bar diagram with text labels. % % labels cell array of labels % y bar height % col color % lb lower bound of the figure % ub upper bound of the figure function textBar(labels, y, ax, col, lb, ub) clamp = @(x)max(min([1,1,1], x), [0,0,0]); if ( ~exist( 'ax', 'var' ) || isempty(ax) ) ax = axes; end if ( ~exist( 'col', 'var' ) || isempty(col) ) col = [.2 0 .8]; end if ( size( col, 1 ) == 1 ) col = repmat( col, numel(y), 1 ); end badIdx = isinf(y) | isnan(y); for i = 1 : numel(y) b = barh( ax, i, y(i) ); hold on; set( b, 'EdgeColor', col(i,:) ); set( b, 'FaceColor', clamp(col(i,:) + 0.9) ); set( b, 'LineWidth', 1.05 ); if ( exist('ub', 'var' ) ) line( [lb(i), ub(i)], [i, i], 'LineWidth', 1.05, 'Color', col(i,:) ); line( [lb(i), lb(i)], [i-.2, i+.2], 'LineWidth', 1.05, 'Color', col(i,:) ); line( [ub(i), ub(i)], [i-.2, i+.2], 'LineWidth', 1.05, 'Color', col(i,:) ); end end set( ax, 'YTick', 1 : numel(y) ) set( ax, 'YTickLabel', labels, 'fontsize', 9 ); ys = y(~badIdx); xlims = [ min([0, min(ys) - 0.1 * abs(min(ys))]), max(ys) + 0.1 * abs(max(min(ys))) ]; if ( exist('ub', 'var' ) ) xlims = [ min([0, min(lb) - 0.1 * abs(min(lb))]), max(ub) + 0.1 * abs(max(min(ub))) ]; end if ( xlims(2) == xlims(1) ) xlims(2) = xlims(1)+0.1; end xlim(xlims); ylim( [ 0.5, numel(y) + 0.5 ] ); hold on; plot( repmat( xlims(1) + 0.05 * ( xlims(2) - xlims(1) ), 1, sum(badIdx) ), find(badIdx), 'xr', 'MarkerSize', 10 ); set(gca, 'YDir', 'Reverse' ); grid off; set(gca, 'XGrid', 'on'); end
import { deleteUser, followUser, getUser, getUserFriends, getUserProfile, unfollowUser, updateProfilePicture, updateUser, } from "../services/user.service.js"; export const updateUserController = async (req, res) => { if (req.body.userId === req.params.id || req.body.isAdmin) { try { const user = await updateUser(req.params.id, req.body); res.status(200).json({ user, message: "Account has been updated Successfully", }); } catch (err) { console.log(err); res.status(500).json(err); } } else { res.status(500).json("you can only update your account"); } }; export const updateProfilePictureController = async (req, res) => { try { const user = await updateProfilePicture(req.params.id, req.file.path); //console.log(req.body); res.status(200).json({ user, message: "Profile Picture has been updated Successfully", }); } catch (err) { console.log(err); res.status(500).json(err); } }; export const deleteUserController = async (req, res) => { if (req.body.userId === req.params.id || req.body.isAdmin) { try { await deleteUser(req.params.id); res.status(200).json({ message: "Account has been deleted Successfully", }); } catch (err) { console.log(err); res.status(500).json(err); } } else { res.status(500).json("you can only delete your account"); } }; export const getUserController = async (req, res) => { try { const user = await getUser(req.params.id); const { password, ...data } = user._doc; res.status(200).json({ userInfo: data, message: "Account has been fetched Successfully", }); } catch (err) { console.log(err); res.status(500).json(err); } }; export const getUserProfileController = async (req, res) => { try { const user = await getUserProfile(req.query); const { password, ...data } = user._doc; res.status(200).json({ userInfo: data, message: "Account has been fetched Successfully", }); } catch (err) { console.log(err); res.status(500).json(err); } }; export const followUserController = async (req, res) => { try { const data = await followUser(req.body, req.params); res.status(200).json({ data, message: "Follow User Successfully", }); } catch (err) { console.log(err); res.status(500).json(err); } }; export const unfollowUserController = async (req, res) => { try { const data = await unfollowUser(req.body, req.params); res.status(200).json({ data, message: "UnFollow User Successfully", }); } catch (err) { console.log(err); res.status(500).json(err); } }; export const getUserFriendsController = async (req, res) => { try { const friends = await getUserFriends(req.params); res.status(200).json({ friends, message: "Friends have fetched Successfully!", }); } catch (err) { console.log(err); res.status(500).json(err); } };
using MainApp.Models.User; using Microsoft.AspNetCore.Identity; namespace MainApp.Data { // Init first identity data (roles + admin) public static class IdentityInitializer { public static async Task InitializeAsync(UserManager<UserModel> userManager, RoleManager<IdentityRole> roleManager, IConfiguration configuration) { // get credentials from configuration var name = configuration["Admin:Name"]; var password = configuration["Admin:Password"]; // Adding users roles if (await roleManager.FindByNameAsync(UserRoles.User) == null) { await roleManager.CreateAsync(new IdentityRole(UserRoles.User)); } if (await roleManager.FindByNameAsync(UserRoles.Moderator) == null) { await roleManager.CreateAsync(new IdentityRole(UserRoles.Moderator)); } if (await roleManager.FindByNameAsync(UserRoles.Admin) == null) { await roleManager.CreateAsync(new IdentityRole(UserRoles.Admin)); } // Adding initial admin if (await userManager.FindByNameAsync(name) == null) { var admin = new UserModel { UserName = name }; var result = await userManager.CreateAsync(admin, password); if (result.Succeeded) { // Add all roles for admin await userManager.AddToRolesAsync(admin, new List<string>() { UserRoles.User, UserRoles.Moderator, UserRoles.Admin }); } } } } }
<template> <div class="tab"> <input v-model="selectedTab" type="radio" :id="value" :name="groupName" :value="value" class="tab__input" /> <label class="tab__label" :for="value"> <span class="tab__labelText">{{ label }}</span> <span class="tab__label--overlay" /> </label> </div> </template> <script lang="ts"> import { inject, defineComponent, Ref, ref } from "vue"; export default defineComponent({ name: "Tab", props: { value: { type: String, required: true }, label: { type: String, required: true }, }, setup() { const groupName = inject("groupName") as string; const selectedTab: Ref<string> = inject("selectedTab", ref("")); return { groupName, selectedTab }; }, }); </script> <style scoped> .tab { flex: 1 1 auto; height: 58px; outline: none; } .tab__input { position: absolute; overflow: hidden; clip: rect(0 0 0 0); width: 1px; height: 1px; margin: -1px; padding: 0; border: 0; } .tab__input:checked + .tab__label .tab__label--overlay { background: rgba(19, 0, 128, 0.363); } .tab__label { position: relative; height: 100%; cursor: pointer; text-align: center; letter-spacing: 1px; text-transform: uppercase; font-size: 13px; font-weight: 600; font-style: normal; line-height: 42px; display: flex; justify-content: center; flex-direction: column; } .tab__labelText { z-index: 2; } .tab__label--overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transform: skewX(-20deg); } </style>
package pl.project.plannerapp.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import pl.project.plannerapp.DTO.ToDoDTO; import pl.project.plannerapp.domain.ToDoEntity; import pl.project.plannerapp.model.ToDo; import pl.project.plannerapp.repo.PersonalDataRepo; import pl.project.plannerapp.repo.ToDoRepo; import pl.project.plannerapp.utils.ToDoConventerUtils; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class ToDoServiceImpl implements ToDoService { private final ToDoRepo toDoRepo; private final PersonalDataRepo personalDataRepo; @Autowired public ToDoServiceImpl(ToDoRepo toDoRepo, PersonalDataRepo personalDataRepo) { this.toDoRepo = toDoRepo; this.personalDataRepo = personalDataRepo; } @Override public List<ToDo> getAllTasks() { return toDoRepo.findAll() .stream() .map(ToDoConventerUtils::convert) .collect(Collectors.toList()); } @Override public ToDo addTask(ToDo toDo) { toDoRepo.save(toDo); return toDo; } @Override public boolean deleteTask(Long id) { ToDoEntity toDoEntity = toDoRepo.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); toDoRepo.delete(toDoEntity); return true; } @Override public Optional<ToDoDTO> getById(Long id) { return toDoRepo.findById(id) .map(ToDoConventerUtils::convert); } @Override public ToDo markTaskAsCompleted(Long id) { return null; } }
# NeuroExplainer: Fine-Grained Attention Decoding to Uncover Cortical Development Patterns of Preterm Infants ## Description NeuroExplainer is an explainable geometric deep network adopting a hierarchical attention-decoding framework to learn fine-grained attention and discriminative representations in a spherical space to accurately recognize preterm infants from term-born infants. NeuroExplainer learns the hierarchical attention-decoding modules under subject-level weak supervision coupled with targeted regularizers deduced from domain knowledge regarding brain development. These prior-guided constraints implicitly maximize the explainability metrics (i.e., fidelity, sparsity, and stability) in network training, driving the learned network to output detailed explanations and accurate classifications. ### The schematic diagram of our NeuroExplainer architecture and Spherical attention mechanism: ![](https://github.com/qianyuhou/NeuroExplainer/blob/main/images/architecture.png) ### Typical examples of the explanation factors captured by different methods: ![](https://github.com/qianyuhou/NeuroExplainer/blob/main/images/attention-comparison.png) ## Package Dependency - python (3.10) - pytorch (2.1.0) - torchvision (1.16.0) - tensorboardx (2.6.2.2) - NumPy (1.22.4) - SciPy (1.11.3) - pyvista (0.42.3) ## Step 0. Environment setup ``` git clone https://github.com/ladderlab-xjtu/NeuroExplainer.git ``` You can use conda to easily create an environment for the experiment using following command: ``` conda create -n neuroexplainer python=3.10 conda activate neuroexplainer conda install pytorch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 pytorch-cuda=12.1 -c pytorch -c nvidia conda install pyvista ``` To install the required packages, run: ``` pip install . ``` ## Step 1. Data preparation We provide processed and curated dataset from the [Developing Human Connectome Project (dHCP)](https://biomedia.github.io/dHCP-release-notes/index.html). Note that the data repository is private and only visible to those who have access. The input spherical surfaces contain 10, 242 vertices, and three features, i.e., cortical thickness, mean curvature, and convexity, are required for the classfication. ## Step 2. Training After data prepration, modify the [main.py](https://github.com/qianyuhou/NeuroExplainer/blob/main/main.py) file to match the training data in your own path. To save the coresponding models and results, the save directories must be manually changed. Then, run: ``` python main.py ``` If successful, you will see ``` 6952268 paramerters in total learning rate = [0:0/247] LOSS= LOSS_1= LOSS_2= LOSS_3= LOSS_4= LOSS_5= [0:1/247] LOSS= LOSS_1= LOSS_2= LOSS_3= LOSS_4= LOSS_5= Train_arr= Val_acc= ,Val_auc= save max acc or auc model Val_max_auc= ,Val_max_arr= ,save_epoch= ,save_num= last five train Dice: All complete in ... ``` In our implementation, the feature representations produced by EB-1 to EB-4 in [architecture](https://github.com/qianyuhou/NeuroExplainer/blob/main/images/architecture.png) have 32, 64, 128, and 256 channels, respectively. Correspondingly, DB-1 to DB-3, and the final classification layer have 256, 128, 64, and 32 channels, respectively. The GPU memory consumption may vary depending on CUDA kernels. ### Step 3. Test In this step, you can calculate the accuracy of classification for preterm and term-born infants and obtain the output attention maps on surface and sphere. To predict a single surface’ attention map, you need to modify the [test.py](https://github.com/qianyuhou/NeuroExplainer/blob/main/test.py) file to match the data in your own path. To save the attention maps of the left and right brain at the sphere and surface, the save directories must be manually changed or created. In this step, you can use the saved model `./muilt_view_10242_ori_$epoch_max_acc.pkl` in Step 2. ### Visualization You can use [Paraview](https://www.paraview.org/) software to visualize the attention map in VTK format. An example of the coarse-grained attention map and the fine-grained attention map of preterm infant are shown below. More usages about Paraview please refer to [Paraview](https://www.paraview.org/). ![paraview](https://github.com/qianyuhou/NeuroExplainer/blob/main/images/attention%20map.png) ## Citation Please cite the following paper if you use (part of) our code in your research: ``` Xue, C., Wang, F., Zhu, Y., Li, H., Meng, D., Shen, D., & Lian, C.(2023). NeuroExplainer: Fine-Grained Attention Decoding to Uncover Cortical Development Patterns of Preterm Infants. In: Greenspan, H., et al. Medical Image Computing and Computer Assisted Intervention – MICCAI 2023. MICCAI 2023. Lecture Notes in Computer Science, vol 14221. Springer, Cham. ```
Mining Closed Episodes from Event Sequences Efficiently Wenzhi Zhou1, Hongyan Liu1, and Hong Cheng2 1 Department of Management Science and Engineering Tsinghua University, Beijing, China, 100084 {zhouwzh.05,liuhy}@sem.tsinghua.edu.cn 2 Department of Systems Engineering and Engineering Management, The Chinese University of Hong Kong, Shatin, N. T., Hong Kong [email protected] Abstract. Recent studies have proposed different methods for mining frequent episodes. In this work, we study the problem of mining closed episodes based on minimal occurrences. We study the properties of minimal occurrences and design effective pruning techniques to prune non-closed episodes. An efficient mining algorithm Clo_episode is proposed to mine all closed episodes follow- ing a breadth-first search order and integrating the pruning techniques. Experi- mental results demonstrate the efficiency of our mining algorithm and the compactness of the mining result set. Keywords: Episode, closed episode, frequent pattern, sequence. 1 Introduction Frequent episode mining in event sequences is an important mining task with broad applications such as alarm sequence analysis in telecommunication networks [1], financial events and stock trend relationship analysis [4], web access pattern analysis and protein family relationship analysis [5]. An event sequence is a long sequence of events. Each event is described by its type and a time of occurrence. A frequent epi- sode is a frequently recurring short subsequence of the event sequence. Previous studies on frequent itemset mining and sequential pattern mining show that mining closed itemsets [10] or closed sequential patterns [11] is not only an in- formation lossless compression of all frequent patterns, but also an effective way to improve the mining efficiency. A frequent itemset (or sequence) is closed if there is no super itemset (or super sequence) with the same support. To the best of our knowl- edge, there are some research work on frequent episode or generalized frequent epi- sode mining [2, 3, 7-9], but there is no existing method for mining closed episodes. Therefore, it is natural to raise two questions: (1) what is a closed episode? and (2) how to find closed episodes efficiently? Following the definitions of closed itemset and closed sequence, we can define closed episode similarly. For example, in Table 1, as event B always co-occurs with event A, we say event B is not closed (the formal definition is given in Section 2) M.J. Zaki et al. (Eds.): PAKDD 2010, Part I, LNAI 6118, pp. 310–318, 2010. © Springer-Verlag Berlin Heidelberg 2010 Mining Closed Episodes from Event Sequences Efficiently 311 given a time span constraint of 4 (i.e., the maximum window size threshold) and a frequency constraint of 2 (i.e., the minimum support threshold). Table 1. An example sequence of events 1 5 6 Time 10 11 12 13 14 15 16 17 18 19 Event A B C A B D F E F C E D F A B C E A B 2 7 3 4 8 9 Though the concept of closed episode is similar with that of closed itemset and closed sequence, mining closed episode efficiently is much more challenging. The challenge is caused by two properties in frequent episode mining: (1) there is tempo- ral order among different events in an episode; and (2) we take into account repeated occurrences of an episode in the event sequence. In this paper, we define a concept of minimal occurrence (a similar concept was defined in [1]) and use minimal occurrence to model the occurrences of an episode in the event sequence. Based on this model, we will develop several pruning techniques to reduce the search space on closed episodes. We propose an efficient algorithm to mine all closed episodes by exploiting the pruning techniques. The remainder of this paper is organized as follows. We give the problem defini- tion in Section 2. Section 3 presents the novel mining algorithm and our proposed pruning techniques. We demonstrate the performance of our algorithm through exten- sive experiments in Section 4. Section 5 concludes the paper. 2 Problem Definition The framework of mining frequent episode was first proposed by Mannila et al. [1]. In [1], two kinds of episodes, serial and parallel episodes, were formally defined. In this paper, we focus on serial episode mining, and we call it episode for simplicity. Given a set E of event types (or elements), E={e1, e2, …, em}, an event sequence (or event stream) S is an ordered sequence of events, denoted by S=<(A1, t1), (A2, t2), …, (AN, tN)>, where Ai∈E is the event that happens at time ti (we call it the occurrence time of Ai), and Ts≤ti≤ti+1<Te for i=1, 2, …, N-1. Ts is called the starting time of S, and Te the ending time. Thus an event sequence can be denoted by (S, Ts, Te). An episode α is an ordered collection of event types, α=<B1, B2, …, Bn>, where Bi∈E (i=1, 2, …, n) and n<N. An episode with n events is called an n-length episode, or n-episode. A window on an event sequence (S, Ts, Te) is an event sequence (w, ts, te), where ts>Te and te<Ts. Window w consists of those events (A, t) from S where ts≤t<te. The time span te−ts is called the size of the window w. Definition 1 (Minimal occurrence). Given an event sequence S and an episode α, a minimal occurrence of α is such a time interval [ts, te) that (1) α occurs in [ts, te); (2) there exists no smaller time interval [t’s, t’e)⊂[ts, te) that α occurs in it. ts is the start- ing time of this occurrence and te the ending time; and (3) te−ts<win, where win is a user-defined maximum window size threshold, and te−ts is called the time span of this minimal occurrence. That is, each occurrence of an episode must be within a window no larger than win. 312 W. Zhou, H. Liu, and H. Cheng For an episode α, all of its minimal occurrences are denoted as a set MO(α)={[ts, te)| [ts, te) is a minimal occurrence of α}. The support of an episode is the number of its minimal occurrences, i.e., sup(α)=|MO(α)|. Given a minimum support threshold minsup, if sup(α)≥minsup, α is called a frequent episode, or α is frequent. Definition 2 (Sub-episode and super episode). An episode β=<B1, B2, …, Bm> where m<n is called a sub-episode of another episode α=<A1, A2, …, An>, if there are m integers 1≤i1<i2<…<im≤n such that B1= Ai1, B2= Ai2, …, Bm= Aim. Episode α is called the super episode of episode β. If we have i1=1, i2=2, …, im=m, then α is called the forward-extension super episode of β. If we have i1=n−m+1, i2 = n−m+2, …, im=n, then α is called the backward-extension super episode of β. If α is a super episode of β but is neither a forward-extension nor backward-extension super episode of β, α is called the middle-extension super episode of β. Definition 3 (Closed episode). Given an event sequence S, an episode α is closed if (1) α is frequent; and (2) there exists no super episode β⊃α with the same support as it. Definition 4 (Forward-closed episode). Episode α is forward-closed if (1) α is fre- quent; and (2) there is no forward-extension super episode of α with the same support as α. Similarly we can define another two kinds of closed episodes. Definition 5 (Backward-closed episode). Episode α is backward-closed if (1) α is frequent; and (2) there is no backward-extension super episode of α with the same support as α. Definition 6 (Middle-closed episode). Episode α is middle-closed if (1) α is frequent; and (2) there is no middle-extension super episode of α with the same support as α. A closed episode should be forward-closed, backward-closed and middle-closed simultaneously. Mining Task: Given an event sequence S, a minimum support threshold minsup, and a maximum window size threshold win, the mining task is to find the complete set of closed episodes from S. 3 Mining Closed Episodes To enumerate potential closed episodes, we perform a search in a prefix tree as shown in Figure 1. We assume that there is a predefined order, denoted by ≺, among the set of distinct event types. In our example sequence, we use the lexicographical order, i.e., A ≺B ≺C ≺D ≺E ≺F. The mining process follows a breadth-first search order. Starting from the root node with the empty episode α= ∅ , we can generate length−1 episodes at level 1 by adding one event to α. Similarly we can grow an episode at level k by adding one event to get length−(k+1) episodes at level k+1. For each candidate episode, we com- pute its minimal occurrence set from the minimal occurrence sets of its sub-episodes through a “join” operation. Since the episode mining and checking are based on minimal occurrences of episodes, we will first give some properties of minimal occur- rences and show how they can be used for pruning search space. Mining Closed Episodes from Event Sequences Efficiently 313 ∅ A B C D AA AB AC AD BA BB BC BD … ABA ABB ABC ABD BAB BAC Fig. 1. A tree of episode (sequence) enumeration Property 1. In an event sequence S, if [ts, te) is a minimal occurrence of episode α=<A1, A2,…, An>, then there must exist two events, (A1, ts) and (An, te−1) in S. Property 2. Assume [ts, te) and [us, ue) are two minimal occurrences of episode α. If ts < us, then we have te < ue; if te < ue, then we have ts < us. Based on Property 2, minimal occurrences in MO(α) can be sorted in the ascending order of their starting time. Then the order among an episode’s minimal occurrences is strict. If one occurrence starts ahead of another, then it must end earlier. According to Definition 1, the time span of an episode’s minimal occurrence is bounded by the window size threshold win. Therefore, given a minimal occurrence [ts, te), if te−ts=win, the episode cannot be extended forward or backward in the time win- dow [ts, ts+win), although some events might be inserted in the middle of it. We de- fine such minimal occurrences as saturated minimal occurrences. Definition 7 (Saturation and expansion). A minimal occurrence [ts, te) of an episode α is saturated if the time span te−ts=win, the user-specified maximum window size threshold. Otherwise, it is an unsaturated minimal occurrence. An episode α’s satura- tion, denoted as α.saturation, is defined as the number of saturated minimal occur- rences, and its expansion, denoted as α.expansion, is the number of unsaturated minimal occurrences. Apparently, α.saturation+α.expansion=sup(α) holds. For a saturated minimal occur- rence of an episode, no additional events can be inserted before the first event or after the last event; otherwise, the maximum window size constraint will be violated. This means, for an episode α we can find its forward-extension or backward-extension super episode γ only in the unsaturated minimal occurrences. The upper bound of γ’s support is the number of α’s unsaturated minimal occurrences. Therefore, if γ is fre- quent, the number of unsaturated minimal occurrences in MO(α) must be no smaller than minsup. If one episode has less than minsup unsaturated minimal occurrences, then none of its forward-extension or backward-extension super episodes is frequent. In this case, it is unnecessary to generate and check its super episodes. Therefore, we have following two lemmas. Lemma 1: If the expansion of an episode α is smaller than the minimum frequency threshold minsup, i.e., α.expansion<minsup, then all forward-extension and backward- extension super episodes of α are infrequent. 314 W. Zhou, H. Liu, and H. Cheng Lemma 2: Given a frequent episode α and its minimal occurrence set MO(α), if (1) α.saturation>0, and (2) there is a saturated minimal occurrence ω∈MO(α) that cannot be extended in the middle, then α must be closed. The algorithm, Clo_episode, is developed to find all closed episodes in an event se- quence. Its major steps are given in Figure 2. The algorithm structure is as follows. It first generates the set of length-1 frequent episodes F1 (lines 1-4). The event sequence S is scanned and all distinct single events are generated as their minimal occurrences. Then, Clo_episode generates closed episodes level by level in an iterative way through the while loop (lines 5-19). length−1 episodes with Each iteration in the while loop generates the set of candidate episodes Ck and the set of frequent episodes Fk. This process iterates until Fk is empty. For a non-empty set Fk, it produces Fk+1 which is the frequent episode set of length−(k+1) and CFk which is the set of length−k closed episodes. Episodes in Fk are processed in a prede- fined order as we explained above. scan S and compute MO(α) for all α∈C1 ; k=1; Algorithm Clo_episode Input: Event sequences S, maximum window size threshold win, minimum support threshold minsup; Output: the set of closed episodes CF Method: 1. C1= the set of length−1 episodes in S 2. 3. 4. F1={α∈C1 | α is frequent} 5. while Fk != Φ do for each episode α∈Fk such that α.forward!=0 do 6. Ck+1=Gen_candiate(α, Fk); 7. 8. Ck+1=Prune(Ck+1); 9. Ck+1=Gen_MO(Ck+1); for each candidate episode γ∈Ck+1 do 10. if sup(γ)≥minsup, put γ into Fk+1 11. if there is length−k subepisode β of γ such that β.closed=-1 and sup(γ)=sup(β) do 12. set β.closed=0 13. if γ is a middle-extension super episode of β, call Clo_prune(α, β, γ); 14. 15. end for 16. end for CFk={α∈Fk |α.closed!= 0} 17. 18. k=k+1; 19. end while 20. CF={α |α∈CFi (1≤i<k) and there is no super episode β of α such that sup(β)=sup(α)}; Output CF Fig. 2. Major steps of Algorithm Clo_episode For each episode α∈Fk which can be extended forward (line 6), function Gen_candiate(α, Fk) is called to generate α’s candidate super episodes of length−(k+1) (line 7). A super episode is generated by combining α and another length−k episode in Fk that shares the first (k−1) events with α. Then function Prune(Ck+1) is called to prune those candidates that cannot be frequent (line 8). Next Gen_MO(Ck+1) is invoked to generate the minimal occurrences for each candidate episode. It also computes saturation and expansion of Mining Closed Episodes from Event Sequences Efficiently 315 each candidate episode and checks whether they can be extended forward or back- ward and whether they are closed. Due to space limitation, we omit the details of the two functions. Based on the computed information, each frequent episode γ is added into Fk+1 (line 11); the sub-episodes of γ that have the same support as γ will be marked not closed (lines 12-13). For those sub-episodes β of γ that share the first and last events with γ, function Clo_prune(α, β, γ) is invoked to see if it can be pruned (line 14). The details of function Clo_prune are given in Figure 3. Clo_prune(α, β, γ) 1 Sort minimal occurrences in MO(β) and MO(γ) respectively by starting time ascendingly 2 Initialize flag=true 3 for i=1 to |MO(β)| do 4 if MO(γ)[i].ts!=MO(β)[i].ts or MO(γ)[i].te!=MO(β)[i].te do 5 flag=false 6 break 7 end for 8 if flag=true do 9 Remove β from Fk; 10 if (β≺α) remove all β’s forward-extension super episodes from Fk+1; 11 return Fig. 3. Major steps of Function Clo_prune Function Clo_prune compares the minimal occurrences of episode β and that of its middle-extension super episode γ. If MO(γ)=MO(β), then β is not closed. All of β’s forward-extension super episodes are not closed either. Due to space limitation, we omit the detail of proof. 4 Experiments In this section we will present experimental results on synthetic datasets. We also conducted experiments on a real dataset. But due to space limitation, we will only report the results of synthetic datasets. We evaluate the efficiency of our proposed algorithm as well as the reduction in the number of episodes generated, comparing with MINEPI proposed by Mannila et al. [1] for frequent episode mining. To test the effectiveness of the pruning techniques for pruning non-closed episodes, we disable the function Clo_prune and get another algorithm called Clo_episode_NP without the pruning techniques. All of our experiments were performed on a PC with 3Ghz CPU, 2GB RAM, and 300GB hard disk running windows XP. We design a synthetic dataset generator, by which we can evaluate the perform- ance of different algorithms with different data characteristics. The generator takes five parameters. The parameter NumOfPatterns is the number of potentially closed episodes in the final sequence, MaxLength and MinLength are the maximum and minimum length of potential episodes respectively, NumOfWindows is used to control the length of the whole sequence, and win is the size of a window. Due to space limi- tation, we omit the detail of the generator. 316 W. Zhou, H. Liu, and H. Cheng To generate event sequences, we fix the value of MinLength, and vary the other five parameters: NumOfPatterns(P), MaxLength(L), NumOfWindows(N), win(W) and minsup. Thus we create five groups of datasets, each of which is generated by varying one parameter and fixing the other four parameters as shown in Table 2. Table 2. Five groups of synthetic datasets Group Datasets 1 2 3 4 5 PxL12N4000W14 P200L12NxW14 P200LxN4000W16 P200L12N4000Wx P200L12N4000W14 P 100-200 200 200 200 200 L 12 12 9-14 12 12 N 4000 3200-4800 4000 4000 4000 W 14 14 16 10-16 14 Minsup 15 20 15 20 10-35 For each group of datasets, we plot the running time and the number of frequent/closed episodes in two figures. The results are shown in Figures 4 to 13. The y-axes are in logarithmic scales in Figures 5, 7, 9, 11 and 13. From Figure 4 we can see that Clo_episode significantly outperforms MINEPI and Clo_episode_NP. This shows that the pruning techniques in Clo_episode are very effective. In addition, the running time of Clo_episode is not affected much as P in- creases, but that of the other two algorithms increases dramatically. Figure 5 shows that the number of closed episodes found by Clo_episode is much smaller than the number of frequent episodes output by MINEPI. Figures 6 and 7 show a similar result. As N increases, the sequence becomes longer. For a fixed minsup threshold, the number of frequent episodes by MINEPI increases a lot, but the number of closed episodes does not increase as much. Figures 8 and 9 show that the number of frequent episodes output by MINEPI in- creases significantly with L. Accordingly the running time increases. Figure 8 shows that Clo_episode is much more efficient than MINEPI and Clo_episode_NP. Figures 10 and 11 show that when win increases from 10 to 14, the running time becomes longer, the number of frequent episodes becomes larger, but the number of closed episodes does not increase much. When win is greater than 14, the running time of all three algorithms does not increase. This is because the average length of potential closed episodes is fixed at 12 in the sequence. Figures 12 and 13 show that, as minsup increases, the number of frequent and closed episodes decreases. The running time decreases accordingly. Fig. 4. Running time vs P Fig. 5. No. frequent/closed episodes vs P Mining Closed Episodes from Event Sequences Efficiently 317 Fig. 6. Running time vs N Fig. 7. No. frequent/closed episodes vs N Fig. 8. Running time vs L Fig. 9. No. frequent/closed episodes vs L Fig. 10. Running time vs W Fig. 11. No. frequent/closed episodes vs W Fig. 12. Running time vs minsup Fig.13. No. frequent/closed episodes vs minsup Overall, from these five groups of experiments we can see that our algorithm Clo_episode performs much better than MINEPI and Clo_episode_NP. 5 Conclusion Frequent episode mining is an important mining task in data mining. In this paper, we study how to mine closed episodes efficiently. We proposed a novel algorithm 318 W. Zhou, H. Liu, and H. Cheng Clo_episode, which incorporates several effective pruning strategies and a minimal occurrence-based support counting method. Experiments demonstrate the effective- ness and efficiency of these methods. Acknowledgments. This work was supported in part by the National Natural Science Foundation of China under Grant No. 70871068, 70621061 and 70890083. References [1] Mannila, H., Toivonen, H., Verkamo, A.I.: Discovery of Frequent Episodes in Event Se- quences. Data Mining and Knowledge Discovery 1(3), 259–289 (1997) [2] Mannila, H., Toivonen, H.: Discovering generalized episodes using minimal occurrences. In: KDD 1996, Portland, OR (1996) [3] Laxman, S., Sastry, P.S., Unnikrishnan, K.P.: A Fast Algorithm For Finding Frequent Episodes In Event Streams. In: KDD 2007, SanJose, CA (2007) [4] Ng, A., Fu, A.: Mining Frequent Episodes for Relating Financial Events and Stock Trend. In: PAKDD 2003, Seoul, Korea (2003) [5] Baixeries, J., Casas-Garriga, G., Balcázar, J.L.: Mining unbounded episodes from sequential data [6] Meger, N., Rigotti, C.: Constraint-based mining of episode rules and optimal window sizes. In: Boulicaut, J.-F., Esposito, F., Giannotti, F., Pedreschi, D. (eds.) PKDD 2004. LNCS (LNAI), vol. 3202, pp. 313–324. Springer, Heidelberg (2004) [7] Gwadera, R., Atallah, M.J., Szpankowski, W.: Reliable detection of episodes in event sequences. In: ICDM 2003, Melbourne, FL (2003) [8] Gwadera, R., Atallah, M.J., Szpankowski, W.: Markov models for identification of sig- nificant episodes. In: SDM 2005, Newport Beach, CA (2005) [9] Laxman, S., Sastry, P.S., Unnikrishnan, K.P.: Discovering frequent episodes and learning Hidden Markov Models: A formal connection. IEEE TKDE 17(11), 1505–1517 (2005) [10] Wang, J., Han, J., Pei, J.: CLOSET+: Searching for the Best Strategies for Mining Fre- quent Closed Itemsets. In: KDD 2003, Washington, DC (2003) [11] Yan, X., Han, J., Afshar, R.: CloSpan: Mining Closed Sequential Patterns in Large Data- bases. In: SDM 2003, San Francisco, CA (2003)
import { Biometrics } from "@metriport/api-sdk"; import { PROVIDER_FITBIT } from "../../shared/constants"; import { Util } from "../../shared/util"; // import { findMinMaxHeartRate } from "./activity"; import { FitbitBreathingRate } from "./models/breathing-rate"; import { FitbitCardioScore } from "./models/cardio-score"; import { FitbitHeartRate } from "./models/heart-rate"; import { FitbitHeartVariability } from "./models/heart-variability"; import { FitbitSpo2 } from "./models/spo2"; import { FitbitTempCore } from "./models/temperature-core"; import { FitbitTempSkin } from "./models/temperature-skin"; export const mapToBiometrics = ( date: string, breathing?: FitbitBreathingRate, cardio?: FitbitCardioScore, hr?: FitbitHeartRate, hrv?: FitbitHeartVariability, spo?: FitbitSpo2, tempCore?: FitbitTempCore, tempSkin?: FitbitTempSkin ): Biometrics => { const metadata = { date: date, source: PROVIDER_FITBIT, }; const biometrics: Biometrics = { metadata: metadata, heart_rate: {}, hrv: {}, respiration: {}, temperature: {}, }; if (breathing) { biometrics.respiration = { ...biometrics.respiration, ...Util.addDataToObject("avg_breaths_per_minute", breathing.breathingRate), }; } if (cardio && cardio.value) { biometrics.respiration = { ...biometrics.respiration, ...Util.addDataToObject("vo2_max", extractVo2(cardio.value.vo2Max)), }; } if (hr) { biometrics.heart_rate = { ...biometrics.heart_rate, ...Util.addDataToObject("resting_bpm", hr.value.restingHeartRate), }; // if (hr.value.heartRateZones && hr.value.heartRateZones.length) { // const heartZones = hr?.value.heartRateZones; // TODO #805: Include a more thorough breakdown of the heart rate data to get the actual min and max bpm, instead of relying on heartRateZones // https://github.com/metriport/metriport/issues/805 // const { min_item, max_item } = findMinMaxHeartRate(heartZones); // biometrics.heart_rate = { // ...biometrics.heart_rate, // min_bpm: min_item, // max_bpm: max_item, // }; // } } if (hrv) { biometrics.hrv = { rmssd: { ...Util.addDataToObject("avg_millis", hrv.value.dailyRmssd), }, }; } if (spo) { biometrics.respiration = { ...biometrics.respiration, spo2: { ...Util.addDataToObject("min_pct", spo.value?.min), ...Util.addDataToObject("max_pct", spo.value?.max), ...Util.addDataToObject("avg_pct", spo.value?.avg), }, }; } if (tempCore) { biometrics.temperature = { ...biometrics.temperature, core: { ...Util.addDataToObject("avg_celcius", tempCore.value), }, }; } if (tempSkin) { biometrics.temperature = { ...biometrics.temperature, ...Util.addDataToObject("delta_celcius", tempSkin.value.nightlyRelative), }; } return biometrics; }; const extractVo2 = (range: string): number => { if (range.includes("-")) { const number = range.split("-")[1]; return parseInt(number); } return parseInt(range); };
package apps.cradle.quests.utils import androidx.preference.PreferenceManager import apps.cradle.quests.App import apps.cradle.quests.R import apps.cradle.quests.database.entities.DbAction import apps.cradle.quests.database.entities.DbCategory import apps.cradle.quests.database.entities.DbNote import apps.cradle.quests.database.entities.DbQuest import apps.cradle.quests.database.entities.DbTask import apps.cradle.quests.ui.fragments.moveTask.MoveTaskViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import java.util.Date import java.util.UUID object TutorialsUtils { fun addTutorials() = runBlocking(Dispatchers.IO) { val prefs = PreferenceManager.getDefaultSharedPreferences(App.instance) if (!prefs.getBoolean(PREF_TUTORIALS_INITIALIZED, false)) { val categoryId = addTutorialCategories() addTutorialQuests(categoryId) addTutorialTasks() addTutorialNotes() prefs.edit().putBoolean(PREF_TUTORIALS_INITIALIZED, true).apply() } } private fun addTutorialCategories(): String { val categoryId = UUID.randomUUID().toString() App.db.categoriesDao().insert( DbCategory( id = categoryId, title = App.instance.getString(R.string.categoriesDifferentTitle) ) ) return categoryId } private fun addTutorialQuests(categoryId: String) { App.db.questsDao().insert( DbQuest( id = USER_MANUAL_QUEST_ID, categoryId = categoryId, title = App.instance.getString(R.string.userManualQuestTitle) ) ) } private fun addTutorialTasks() { App.db.tasksDao().run { insert(transferTasksTutorialTask()) insert(taskWithActionsTutorialTask()) insert(finishTasksTutorialTask()) insert(moveTasksTutorialTask()) insert(feedbackTutorialTask()) } } private fun transferTasksTutorialTask(): DbTask { return DbTask( id = UUID.randomUUID().toString(), questId = USER_MANUAL_QUEST_ID, title = App.instance.getString(R.string.transferTasksTutorialTaskTitle), date = resetTimeInMillis(Date().time), time = DbTask.NO_TIME, reminder = DbTask.REMINDER_DEFAULT, state = DbTask.STATE_ACTIVE, deadline = DbTask.NO_DEADLINE ) } private fun moveTasksTutorialTask(): DbTask { return DbTask( id = UUID.randomUUID().toString(), questId = USER_MANUAL_QUEST_ID, title = App.instance.getString(R.string.moveTasksTutorialTaskTitle), date = resetTimeInMillis(Date().time), time = DbTask.NO_TIME, reminder = DbTask.REMINDER_DEFAULT, state = DbTask.STATE_ACTIVE, deadline = DbTask.NO_DEADLINE ) } private fun finishTasksTutorialTask(): DbTask { return DbTask( id = UUID.randomUUID().toString(), questId = USER_MANUAL_QUEST_ID, title = App.instance.getString(R.string.finishTasksTutorialTaskTitle), date = resetTimeInMillis(Date().time), time = DbTask.NO_TIME, reminder = DbTask.REMINDER_DEFAULT, state = DbTask.STATE_ACTIVE, deadline = DbTask.NO_DEADLINE ) } private fun taskWithActionsTutorialTask(): DbTask { val taskId = UUID.randomUUID().toString() App.db.actionsDao().run { insert( DbAction( id = UUID.randomUUID().toString(), taskId = taskId, title = App.instance.getString(R.string.taskWithActionsTutorialFirstActionTitle), state = DbAction.STATE_ACTIVE ) ) insert( DbAction( id = UUID.randomUUID().toString(), taskId = taskId, title = App.instance.getString(R.string.taskWithActionsTutorialSecondActionTitle), state = DbAction.STATE_ACTIVE ) ) insert( DbAction( id = UUID.randomUUID().toString(), taskId = taskId, title = App.instance.getString(R.string.taskWithActionsTutorialThirdActionTitle), state = DbAction.STATE_ACTIVE ) ) } return DbTask( id = taskId, questId = USER_MANUAL_QUEST_ID, title = App.instance.getString(R.string.taskWithActionsTutorialTaskTitle), date = resetTimeInMillis(Date().time), time = DbTask.NO_TIME, reminder = DbTask.REMINDER_DEFAULT, state = DbTask.STATE_ACTIVE, deadline = DbTask.NO_DEADLINE ) } private fun feedbackTutorialTask(): DbTask { return DbTask( id = UUID.randomUUID().toString(), questId = USER_MANUAL_QUEST_ID, title = App.instance.getString(R.string.feedbackTutorialTask), date = MoveTaskViewModel.getNextMonth(), time = DbTask.NO_TIME, reminder = DbTask.REMINDER_DEFAULT, state = DbTask.STATE_ACTIVE, deadline = DbTask.NO_DEADLINE ) } private fun addTutorialNotes() { App.db.notesDao().insert( DbNote( id = UUID.randomUUID().toString(), questId = USER_MANUAL_QUEST_ID, title = App.instance.getString(R.string.tutorialNoteAboutTitle), content = App.instance.getString(R.string.tutorialNoteAboutContent), created = System.currentTimeMillis() ) ) } private const val PREF_TUTORIALS_INITIALIZED = "pref_tutorials_initialized" private const val USER_MANUAL_QUEST_ID = "user_manual_quest_id" }
use crate::domain::devices::device::Device; use crate::domain::enums::RemoveEnum; pub struct Room { name: String, devices: Vec<Box<dyn Device>>, } impl Room { pub fn new(name: String) -> Room { Room { name, devices: Vec::new(), } } pub fn get_name(&self) -> &str { &self.name } pub fn add_device(&mut self, device: Box<dyn Device>) { self.devices.push(device); } pub fn get_device_by_name(&self, name: &str) -> Option<&dyn Device> { self.devices .iter() .find(|device| device.get_name() == name) .map(|device| device.as_ref()) } pub fn delete_device_by_name(&mut self, name: &str) -> RemoveEnum { if let Some(index) = self .devices .iter() .position(|device| device.get_name() == name) { let removed_device = self.devices.remove(index); let message = format!("Device {} successfully deleted", removed_device.get_name()); RemoveEnum::Success(message) } else { let message = format!("Device with name {} not found", name); RemoveEnum::NotFound(message) } } } #[cfg(test)] mod tests { use super::*; struct MockDevice { name: String, } impl Device for MockDevice { fn get_name(&self) -> &str { &self.name } fn get_info(&self) -> String { String::from("Mock Device") } } #[test] fn test_new_room() { let room = Room::new(String::from("Test Room")); assert_eq!(room.name, "Test Room"); assert!(room.devices.is_empty()); } #[test] fn test_get_name() { let room = Room::new(String::from("Test Room")); assert_eq!(room.get_name(), "Test Room"); } #[test] fn test_add_device() { let mut room = Room::new(String::from("Test Room")); let mock_device = MockDevice { name: String::from("Mock Device"), }; room.add_device(Box::new(mock_device)); assert_eq!(room.devices.len(), 1); } #[test] fn test_get_device_by_name() { let mut room = Room::new(String::from("Test Room")); let mock_device = MockDevice { name: String::from("Mock Device"), }; room.add_device(Box::new(mock_device)); let device = room.get_device_by_name("Mock Device"); assert!(device.is_some()); let device_name = device.unwrap().get_name(); assert_eq!(device_name, "Mock Device"); } #[test] fn test_delete_device_by_name_success() { let mut room = Room::new(String::from("Test Room")); let mock_device = MockDevice { name: String::from("Mock Device"), }; room.add_device(Box::new(mock_device)); match room.delete_device_by_name("Mock Device") { RemoveEnum::Success(message) => { assert_eq!(message, "Device Mock Device successfully deleted") } _ => panic!("Expected Success, got something else"), } assert_eq!(room.devices.len(), 0); } #[test] fn test_delete_device_by_name_not_found() { let mut room = Room::new(String::from("Test Room")); let mock_device = MockDevice { name: String::from("Mock Device"), }; room.add_device(Box::new(mock_device)); match room.delete_device_by_name("Nonexistent Device") { RemoveEnum::NotFound(message) => { assert_eq!(message, "Device with name Nonexistent Device not found") } _ => panic!("Expected NotFound, got something else"), } assert_eq!(room.devices.len(), 1); } }
import UIKit import SnapKit import Then import RxCocoa import RxSwift class LoginViewController: UIViewController { private var disposeBag = DisposeBag() //MARK: - UI private let emailText = UILabel().then { $0.text = "E-mail" $0.font = .notoSansFont(ofSize: 18, family: .regular) } private let emailTextField = UITextField().then { $0.placeholder = "이메일을 입력해주세요." $0.clearButtonMode = .always $0.returnKeyType = .next $0.layer.borderColor = UIColor.black.cgColor $0.layer.borderWidth = 1 $0.layer.cornerRadius = 10 $0.addLeftPadding() } private let passwordText = UILabel().then { $0.text = "Password" $0.font = .notoSansFont(ofSize: 18, family: .regular) } private let passwordTextField = UITextField().then { $0.placeholder = "비밀번호를 입력해주세요." $0.clearButtonMode = .always $0.returnKeyType = .next $0.layer.borderColor = UIColor.black.cgColor $0.layer.borderWidth = 1 $0.layer.cornerRadius = 10 $0.isSecureTextEntry = true $0.addLeftPadding() } private let loginFailedText = UILabel().then { $0.font = .notoSansFont(ofSize: 15, family: .regular) $0.textColor = .red } private let loginButton = UIButton(type: .system).then { $0.backgroundColor = .black $0.setTitleColor(.white, for: .normal) $0.setTitle("로그인", for: .normal) $0.titleLabel?.font = .notoSansFont(ofSize: 25, family: .medium) $0.contentHorizontalAlignment = .center $0.layer.cornerRadius = 10 } //MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white self.hideKeyboard() setButton() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = true } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() addSubviews() makeSubviewConstraints() } private func setButton() { loginButton.rx.tap .subscribe(onNext: { if self.emailTextField.text == "[email protected]" && self.passwordTextField.text == "qwer1234" { self.navigationController?.pushViewController(MainViewController(), animated: true) } else { self.passwordTextField.text = "" self.loginFailedText.text = "일치하지 않습니다." print("일치하지 않습니다.") } }) .disposed(by: disposeBag) } } //MARK: - Layout extension LoginViewController { func addSubviews() { [emailText, emailTextField, passwordText, passwordTextField, loginFailedText, loginButton].forEach { view.addSubview($0) } } func makeSubviewConstraints() { emailText.snp.makeConstraints { $0.top.equalToSuperview().inset(127) $0.left.equalToSuperview().inset(30) } emailTextField.snp.makeConstraints { $0.top.equalTo(emailText.snp.bottom).offset(13) $0.centerX.equalToSuperview() $0.leading.trailing.equalToSuperview().inset(30) $0.height.equalTo(50) } passwordText.snp.makeConstraints { $0.top.equalTo(emailTextField.snp.bottom).offset(25) $0.left.equalToSuperview().inset(30) } passwordTextField.snp.makeConstraints { $0.top.equalTo(passwordText.snp.bottom).offset(13) $0.centerX.equalToSuperview() $0.leading.trailing.equalToSuperview().inset(30) $0.height.equalTo(50) } loginFailedText.snp.makeConstraints { $0.top.equalTo(passwordTextField.snp.bottom).offset(8) $0.left.equalToSuperview().inset(34) } loginButton.snp.makeConstraints { $0.top.equalTo(loginFailedText.snp.bottom).offset(405) $0.centerX.equalToSuperview() $0.leading.trailing.equalToSuperview().inset(30) $0.height.equalTo(50) } } }
// config-utils.go - provide utility methods for handling and manipulating data provided // in the AppConfig struct instance package config import ( "strings" "github.com/google/go-github/github" "github.com/mgmaster24/go-gh-scanner/utils" ) // Returns the Language object associated with the provided string func (config *AppConfig) GetLanguage(lang string) *Language { for _, l := range config.Languages { if l.Name == lang { return &l } } return nil } // Gets a list of file extensions associated with each defined language in the config // // Example Language Definition: // // Language { Name: "HTML", Extension: ".html" } func (config *AppConfig) GetLanguageExts() []string { exts := make([]string, len(config.Languages)) for i, l := range config.Languages { exts[i] = l.Extension } return exts } // Converts the PerPage ScanConfig value to a githubListOptions pointer func (config *AppConfig) ToListOptions() *github.ListOptions { return &github.ListOptions{PerPage: config.ScanConfig.PerPage} } // Gets the short relative value of a dependency // // npm deps are generally split by a backslash. I.E. @angular/material func (config *AppConfig) GetShortDepName() string { depParts := strings.Split(config.CurrentDep, "/") return depParts[len(depParts)-1] } // Determines whether the repo value is in the ignore repos slice func (config *AppConfig) ShouldIgnoreRepo(repoName string) bool { return isInStrArray(config.ReposToIgnore, repoName) } // Determines whether the team value is in the ignore repos slice func (teamsToIgnore TeamsToIgnore) ShouldIgnoreTeam(teamName string) bool { return isInStrArray(teamsToIgnore, teamName) } func isInStrArray(vals []string, strToCheck string) bool { for _, val := range vals { if strings.Contains(val, "*") { if utils.StringsMatch(val, strToCheck) { return true } } else if val == strToCheck { return true } } return false }
<template> <div ref="orderDetailRef" class="order-detail"> <div class="header"> <img alt="" class="mytrolLogo" src="@assets/images/mytrolLogo.png" /> <icon-svg class="icon" icon="icon-a-bianzu101" @click="handleHideClick"></icon-svg> </div> <div class="avator"> <img :src="messageDetail.avatar" alt="" /> <span>{{ messageDetail.nickname }}</span> </div> <p class="des"> {{ messageDetail.name }} </p> <div class="ikon"> <img :src="joinPreviewUrl(messageDetail.file)" alt="" /> </div> <div class="works-desc"> <h3>作品介绍</h3> <p>Introduction of works</p> </div> <p class="des">{{ messageDetail.description }}</p> <div class="ikon"> <img :src="joinPreviewUrl(messageDetail.file_background)" alt="" /> </div> <div class="audit-box"> <div @click="handleAuditClick(true)"> <icon-svg class="icon" icon="icon-a-bianzu33"></icon-svg> <span>通过</span> </div> <div @click="handleAuditClick(false)"> <icon-svg class="icon" icon="icon-x-circle-bold"></icon-svg> <span>不通过</span> </div> </div> </div> </template> <script> import { getCurrentInstance, onUpdated, ref } from "vue"; import { auditPassedApi, reviewBindBoxApi } from "@api"; import { errorNotify, successNotify } from "@/utils"; export default { emits: ["clonse"], props: { messageDetail: Object, auditStatus: String, }, setup(props, { emit }) { const { proxy } = getCurrentInstance(); const orderDetailRef = ref(null); onUpdated(() => { orderDetailRef.value.style.animation = "sliding-show 0.5s linear 0s"; }); const handleHideClick = () => { orderDetailRef.value.style.animation = "sliding-hiden 0.5s linear 0s"; setTimeout(() => { emit("clonse"); }, 400); }; const handleAuditClick = (bol) => { const status = bol ? "success" : "failed"; if (props.auditStatus === "a") { auditPassed(String(props.messageDetail.id), status); } else { auditBindBox(String(props.messageDetail.id), status); } }; const auditBindBox = async (denom_id, status) => { const { err_code } = await reviewBindBoxApi({ denom_id: String(denom_id), status, }); if (err_code === "0") { emit("clonse", "refresh", props.messageDetail.id); successNotify("审核成功"); } else { errorNotify("审核失败,区块上链中..."); } }; const auditPassed = async (denom_id, status) => { const { err_code } = await auditPassedApi({ denom_id: String(denom_id), status, }); if (err_code === "0") { successNotify("审核成功"); emit("clonse", "refresh", props.messageDetail.id); } else { errorNotify("审核失败,区块上链中..."); } }; return { orderDetailRef, joinPreviewUrl: proxy.joinPreviewUrl, handleAuditClick, handleHideClick, }; }, }; </script> <style lang="scss" scoped> .order-detail { position: absolute; right: 10px; top: 17px; width: 390px; height: calc(100% - 60px); background: #ffffff; overflow-y: auto; box-shadow: -6px 0px 18px 0px rgba(107, 107, 107, 0.16); border-radius: 12px; box-sizing: border-box; padding: 0 21px; animation: sliding-show 0.5s linear 0s; .header { display: flex; align-items: center; justify-content: flex-end !important; position: sticky; top: 0; left: 0; background: #fff; height: 50px; width: 105%; .mytrolLogo { margin-right: 80px; } .icon { font-size: 1.4rem; cursor: pointer; } } .avator { margin-top: 18px; display: flex; justify-content: flex-start; align-items: center; img { display: inline-block; width: 38px; height: 38px; border-radius: 50%; } span { font-size: 16px; font-weight: 600; color: #000000; margin-left: 10px; } } .des { margin: 0; padding: 0; margin-top: 10px; font-weight: 400; color: #434343; font-size: 16px; text-align: left; color: #434343; } .ikon { width: 348px; height: 261px; overflow: hidden; border-radius: 5px; margin-top: 10px; img { width: 100%; height: 100%; object-fit: cover; object-position: 50% 50%; } } .works-desc { display: flex; flex-direction: column; justify-content: center; align-items: center; margin-top: 22px; h3 { color: #434343; font-weight: 600; font-size: 20px; } p { margin: 0; padding: 0; font-weight: 600; color: #434343; font-size: 15px; } } .audit-box { position: sticky; bottom: 5px; right: 0; transform: translateX(0); display: flex; justify-content: center; div { width: 154px; height: 48px; background: #54a44b; border-radius: 8px; text-align: center; line-height: 48px; margin-left: 12px; color: #fff; border: none; cursor: pointer; color: #ffffff; border-radius: 8px; .icon { font-size: 1.2rem; margin-right: 10px; } &:first-child { background-color: #54a44b; } &:last-child { background-color: #ff451d; } } } } @keyframes sliding-show { from { transform: translateX(500px); } to { transform: translateX(0); } } @keyframes sliding-hiden { from { transform: translateX(0); } to { transform: translateX(500px); } } </style>
/******************************************************************************* File: packetgen.h Project: OpenSonATA Authors: The OpenSonATA code is the result of many programmers over many years Copyright 2011 The SETI Institute OpenSonATA 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. OpenSonATA 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 OpenSonATA. If not, see<http://www.gnu.org/licenses/>. Implementers of this code are requested to include the caption "Licensed through SETI" with a link to setiQuest.org. For alternate licensing arrangements, please contact The SETI Institute at www.seti.org or setiquest.org. *******************************************************************************/ /** * Packet generator program. */ #ifndef _PacketGenH #define _PacketGenH #include <unistd.h> #include <errno.h> #include <stdio.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <stdint.h> #include <vector> #include <alarm.h> #include <sseInterface.h> #include "BeamPacket.h" #include "ChannelPacket.h" #include "Gaussian.h" using namespace gauss; using namespace sonata_lib; using namespace std; /** * Signal inserted into the sample stream. */ struct PacketSig { SigType type; // signal type float64_t freq; // signal frequency float64_t drift; // signal drift (Hz/sec) float64_t snr; // signal snr float64_t tStart; // signal Pulse Signal Start Time float64_t tOn; // signal Pulse Signal On Time float64_t tOff; // signal Pulse Signal Off Time uint8_t pol; // signal polarization PacketSig(): type(CwSignal), freq(0.0), drift(0.0), snr(0.0), tStart(0.0), tOn(1.0), tOff(0.0), pol(ATADataPacketHeader::BOTH) {} PacketSig(SigType type_, float64_t freq_, float64_t drift_, float64_t snr_, float64_t tStart_, float64_t tOn_, float64_t tOff_, uint8_t pol_): type(type_), freq(freq_), drift(drift_), snr(snr_), tStart(tStart_), tOn(tOn_), tOff(tOff_), pol(pol_) {} }; typedef vector<PacketSig> PacketSigList; // function declarations void usage(); void parseArgs(int argc, char **argv); void alarmHandler(int signal); void fullThrottle(); void openFile(const string& file); void createPackets(Gaussian& xGen, Gaussian& yGen, ATAPacket& xPkt, ATAPacket& yPkt); void sendPackets(ATAPacket& xPkt, ATAPacket& yPkt); void printSummary(ComplexInt8 *data, int n); void fPrintSummary(ComplexFloat32 *data, int n); void printStatistics(); //--------------------------------------------------------------------- // in-line class under test //--------------------------------------------------------------------- #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <linux/sockios.h> class MCSend { public: MCSend(int, uint32_t, string); void send(const void *, size_t); int getSendHWM() { return sendHWM; } private: int sockFd; sockaddr_in mcastAddr; int sendHWM; }; #endif
import axios from 'axios' export async function redirectToAuthCodeFlow(clientId: string) { const verifier = generateCodeVerifier(128) const challenge = await generateCodeChallenge(verifier) localStorage.setItem('verifier', verifier) const params = new URLSearchParams() params.append('client_id', clientId) params.append('response_type', 'code') params.append('redirect_uri', import.meta.env.VITE_SPOTIFY_REDIRECT_URI) params.append( 'scope', 'user-read-private user-read-email playlist-read-private playlist-read-collaborative playlist-modify-public playlist-modify-private' ) params.append('code_challenge_method', 'S256') params.append('code_challenge', challenge) document.location = `https://accounts.spotify.com/authorize?${params.toString()}` } export async function getAccessToken(clientId: string, code: string) { console.log('getAccessToken') const verifier = localStorage.getItem('verifier') const params = new URLSearchParams() params.append('client_id', clientId) params.append('grant_type', 'authorization_code') params.append('code', code) params.append('redirect_uri', import.meta.env.VITE_SPOTIFY_REDIRECT_URI) params.append('code_verifier', verifier!) const { data } = await axios.post('https://accounts.spotify.com/api/token', params, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) // const { access_token } = data return data } function generateCodeVerifier(length: number) { let text = '' const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for (let i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)) } return text } async function generateCodeChallenge(codeVerifier: string) { const data = new TextEncoder().encode(codeVerifier) const digest = await window.crypto.subtle.digest('SHA-256', data) return btoa(String.fromCharCode.apply(null, [...new Uint8Array(digest)])) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, '') }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Naux\Mail\SendCloudTemplate; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','avatar','confirmation_token','api_token' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function owns(Model $model){ return $this->id == $model->user_id; } public function answers(){ return $this->hasMany(Answer::class); } public function questions(){ return $this->hasMany(Question::class); } public function followers(){ return $this->belongsToMany(Question::class,'user_question')->withTimestamps(); } public function followThis($question){ return $this->followers()->toggle($question); } public function followed($question){ return !! $this->followers()->where('question_id',$question)->count(); } public function sendPasswordResetNotification($token) { $data = [ 'url' => url('password/reset', $token) ]; $template = new SendCloudTemplate('laravideo_password_rest', $data); \Mail::raw($template, function ($message) { $message->from('[email protected]', 'xiaohai'); $message->to($this->email); }); } }
import { Dispatch } from "redux"; import * as L from '../loading' import * as E from '../errorMessage' import * as D from '../../data' import { setUser, changeEmail, changeName, changePicture } from "./actions"; export const getRemoteUser = () => (dispatch: Dispatch) => { dispatch(L.setLoading(true)) dispatch(E.setErrorMessage('')) D.fetchRandomUser() .then(user => dispatch(setUser(user))) .catch((e:Error) => E.setErrorMessage(e.message)) .finally(() => dispatch(L.setLoading(false))) } export const changeNameByFetching = () => (dispatch: Dispatch) => { dispatch(L.setLoading(true)) dispatch(E.setErrorMessage('')) D.fetchRandomUser() .then(user => dispatch(changeName(user.name))) .catch((e:Error) => E.setErrorMessage(e.message)) .finally(() => dispatch(L.setLoading(false))) } export const changeEmailByFetching = () => (dispatch: Dispatch) => { dispatch(L.setLoading(true)) dispatch(E.setErrorMessage('')) D.fetchRandomUser() .then(user => dispatch(changeEmail(user.email))) .catch((e:Error) => E.setErrorMessage(e.message)) .finally(() => dispatch(L.setLoading(false))) } export const changePictureByFetching = () => (dispatch: Dispatch) => { dispatch(L.setLoading(true)) dispatch(E.setErrorMessage('')) D.fetchRandomUser() .then(user => dispatch(changePicture(user.picture))) .catch((e:Error) => E.setErrorMessage(e.message)) .finally(() => dispatch(L.setLoading(false))) }
 #include <iostream> #include <vector> using namespace std; class Heap { public: vector<int> v; int s = 0; Heap() { v.push_back(-1); } void insert(int e) { s++; v.push_back(e); upheap(s); } void upheap(int child) { int parent = (child / 2); if (parent >= 1) { if (v[child] > v[parent]) { int tmp; tmp = v[child]; v[child] = v[parent]; v[parent] = tmp; upheap(parent); } else { return; } } else { return; } } void downheap(int parent) { int leftchild = parent * 2; int rightchild = parent * 2 + 1; if (rightchild <= s) { if (v[leftchild] > v[rightchild]) { if (v[parent] < v[leftchild]) { int tmp; tmp = v[leftchild]; v[leftchild] = v[parent]; v[parent] = tmp; downheap(leftchild); } } else { if (v[parent] < v[rightchild]) { int tmp; tmp = v[rightchild]; v[rightchild] = v[parent]; v[parent] = tmp; downheap(rightchild); } } } else if (leftchild <= s) { if (v[parent] < v[leftchild]) { int tmp; tmp = v[leftchild]; v[leftchild] = v[parent]; v[parent] = tmp; } return; } else { return; } } void size() { cout << s << endl; } bool isEmpty() { if (s == 0) return true; else return false; } void pop() { if (this->isEmpty()==false) { cout << v[1] << endl; v[1] = v[s]; v.pop_back(); s--; downheap(1); } else { cout << -1 << endl; } } void top() { if (this->isEmpty() == false) { cout << v[1] << endl; } else { cout << -1 << endl; } } void print() { if (this->isEmpty() == false) { for (int i = 1; i <= s; i++) { cout << v[i] << " "; } } else { cout << -1 << endl; } } }; int main() { int N; cin >> N; Heap h; while (N--) { string cmd; cin >> cmd; if (cmd == "insert") { int e; cin >> e; h.insert(e); } else if (cmd == "size") { h.size(); } else if (cmd == "isEmpty") { cout << h.isEmpty() << endl; } else if (cmd == "pop") { h.pop(); } else if (cmd == "top") { h.top(); } else if (cmd == "print") { h.print(); } } }
import * as fb_helper from './fb_helper' import type { FirebaseApp } from 'firebase/app' import type { User } from 'firebase/auth' import type { User as UserType } from 'firebase/auth' import { OrganizationUser } from './OrganizationUsers' import { Location } from './Locations' import { getDocs, getFirestore, connectFirestoreEmulator, collection, query, where, setDoc, doc, addDoc, WithFieldValue, DocumentData, QueryDocumentSnapshot, SnapshotOptions, getDoc, DocumentSnapshot, FieldValue, DocumentReference, updateDoc, deleteDoc} from 'firebase/firestore' export const orgConverter = { toFirestore(org: WithFieldValue<Organization>): DocumentData { return {name: org.Name}; }, fromFirestore( snapshot: QueryDocumentSnapshot, options: SnapshotOptions ): Organization { const data = snapshot.data(options)!; let o = new Organization(null) o.ID = snapshot.id o.Name = data.name return o } } const app : FirebaseApp = fb_helper.get_app() const db = getFirestore(app) connectFirestoreEmulator(db,'localhost',8088) const orgRef = collection(db,'organization').withConverter(orgConverter) export class Organization { ID: string Name: string Owners: Array<string> = [] Members: Array<string> = [] Locations: Array<Location> DomainSuffix: string private CurrentUser : User constructor(user: User, org_doc? : DocumentSnapshot) { this.CurrentUser = user if (org_doc) { this.ID = org_doc.id let data = org_doc.data() this.Name = data.name } } // Public methods save = async (ou: OrganizationUser) => { if (!this.Owners) this.Owners = [] if (!this.Members) this.Members = [] if (!this.Locations) this.Locations = [] if (this.Locations == undefined) this.Locations = [] if (this.Owners.length == 0) this.Owners.push(ou.ID) // force ownership if (!this.ID) { // new Org. Force user to be member, add default location let loc = new Location(null) loc.Name = 'Headquarters' this.Locations.push(loc) this.Members.push(ou.ID) } console.warn(this.Owners) if ( this.Owners.filter(owner => owner == ou.ID).length == 0) this.Owners.push(ou.ID) if ( this.Members.filter(member => member == ou.ID).length == 0) this.Members.push(ou.ID) //save organization doc let org_doc : DocumentReference if (this.ID) { org_doc = doc(db,'organization',this.ID) await setDoc(org_doc.withConverter(orgConverter), this) } else { org_doc = await addDoc(orgRef.withConverter(orgConverter), this) this.ID = org_doc.id } //save locations this.Locations.forEach(loc => loc.save(this)) //save ownership to user doc(s) let user_snap : DocumentSnapshot let user_data : DocumentData for (let i = 0; i < this.Owners.length; i ++) { let owner_id = this.Owners[i] // get the document from firestore user_snap = await OrganizationUser.get_raw(owner_id) user_data = await user_snap.data() //update the ownership if this is a new addition let existing = user_data.ownership.filter(owned_group => owned_group.id == this.ID) console.debug('owner exists?',existing,user_data.ownership) if (existing.length == 0) { user_data.ownership.push(org_doc) updateDoc(user_snap.ref,{ ownership:user_data.ownership }) } } // todo remove owners that have been removed //save membership to user doc(s) for (let i = 0; i < this.Members.length; i ++) { let member_id = this.Members[i] // get the document from firestore user_snap = await OrganizationUser.get_raw(member_id) user_data = await user_snap.data() // update document if this is a new addition if (user_data.membership.filter(member_of => member_of.id == this.ID).length == 0) { user_data.membership.push(org_doc) updateDoc(user_snap.ref,{ membership:user_data.membership }) } } //todo remove members that have been removed // save location doc(s) this.Locations.forEach(loc => loc.save(this)) } delete = async () => { deleteDoc(doc(db,'organization',this.ID)) } static async from_doc_id (user: User, id: string): Promise<Organization> { return this.doc_to_org(user,await this.get_doc(null,`organization/${id}`)) } static async from_doc_ref(user: User, dr: DocumentReference): Promise<Organization> { console.debug('getting document for ref',dr) return this.doc_to_org(user,await this.get_doc(dr,null)) } static async from_doc_path(user: User, path: string): Promise<Organization> { console.debug('getting document for path',path) return this.doc_to_org(user,await this.get_doc(null,path)) } private static doc_to_org(user: User, d: DocumentSnapshot) : Organization { let o : Organization = new Organization(user) const data = d.data() o.ID = d.id o.Locations = data.locations o.Name = data.name return o } private static async get_doc(dr? : DocumentReference, path?: string) : Promise<DocumentSnapshot> { console.log( dr) if (dr) return await getDoc(dr) else return await getDoc(doc(db,path)) } } export class Organizations extends Array<Organization> { private CurrentUser : User constructor(user?: User, orgs? : Array<Organization>) { if (!orgs) orgs = [] super(...orgs) this.CurrentUser = user } // Public methods }
import { createPortal } from "react-dom"; type Props = { element?: JSX.Element; isOpen: boolean; onClose?: (data: any) => void; }; const Modal = ({ element, isOpen, onClose }: Props) => { return isOpen ? createPortal( <div className="h-full absolute top-0 left-0 right-0 bottom-0 flex items-center justify-center z-10"> <div className="z-10" tabIndex={10}> {element} </div> <div onClick={onClose} className="opacity-25 bg-black absolute top-0 left-0 bottom-0 right-0" ></div> </div>, document.body ) : null; }; export default Modal;
import 'package:flutter/material.dart'; import '../../controllers/MovieController.dart'; import '../../models/Movie.dart'; import 'package:get/get.dart'; class MovieCard extends StatelessWidget { MovieCard({ Key? key, required this.movie, required this.titleSize, required this.ratingSize, }) : super(key: key); MovieController controller = Get.put(MovieController()); final Movie movie; final double titleSize; final double ratingSize; @override Widget build(BuildContext context) { final isFavorite = false; // Get the favorite status using GetX return GestureDetector( onTap: () { controller.goToMovieDetails(movie); }, child: Padding( padding: EdgeInsets.only(right: 8.0), child: Card( elevation: 1, shadowColor: Colors.purple, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), side: BorderSide( color: Theme.of(context).primaryColor, // Replace with your desired primary color width: 2.0, ), ), child: Stack( children: [ AspectRatio( aspectRatio: 0.5, // Height is double than width child: Column( children: [ Expanded( child: ClipRRect( borderRadius: BorderRadius.vertical( top: Radius.circular(10.0), ), child: Hero( tag: 'movieImage_${movie.id}', child: Image.network( movie.imageUrl, fit: BoxFit.cover, ), ), ), ), Padding( padding: EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _getTruncatedTitle(movie.title), style: TextStyle( fontSize: titleSize, ), overflow: TextOverflow.ellipsis, softWrap: false, ), SizedBox(height: 4), Row( children: [ Text( movie.rating.toStringAsFixed(1), style: TextStyle( fontSize: ratingSize, ), ), SizedBox(width: 4), Icon(Icons.star, color: Colors.yellow, size: 12), ], ), ], ), ), ], ), ), ], ), ), ), ); } String _getTruncatedTitle(String title) { final int maxLength = 25; // Set the maximum length of the title if (title.length > maxLength) { return title.substring(0, maxLength - 3) + "..."; } else { return title; } } }
package com.example.userbacked.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.example.userbacked.common.BaseResponse; import com.example.userbacked.common.ErrorCode; import com.example.userbacked.common.ResultUtil; import com.example.userbacked.model.domain.User; import com.example.userbacked.model.domain.request.UserLoginRequest; import com.example.userbacked.model.domain.request.UserRegisterRequest; import com.example.userbacked.service.UserService; import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; import static com.example.userbacked.contant.UserConstant.ADMIN_ROLE; import static com.example.userbacked.contant.UserConstant.USER_LOGIN_STATUS; /** * 用户接口 * * @author 韩凯翔 */ @RestController @Slf4j @RequestMapping("/user") public class UserController { @Resource private UserService userService; @PostMapping("/register") public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) { if (userRegisterRequest == null) { return ResultUtil.error(ErrorCode.NOT_LOGIN); } String userAccount = userRegisterRequest.getUserAccount(); String userPassword = userRegisterRequest.getUserPassword(); String checkPassword = userRegisterRequest.getCheckPassword(); if (userAccount == null || userPassword == null || checkPassword == null) { return ResultUtil.error(ErrorCode.PARAM_ERROR); } long result = userService.userRegister(userAccount, userPassword, checkPassword); return ResultUtil.success(result); } @PostMapping("/login") public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) { if (userLoginRequest == null) { return ResultUtil.error(ErrorCode.NOT_LOGIN); } String userAccount = userLoginRequest.getUserAccount(); String userPassword = userLoginRequest.getUserPassword(); if (userAccount == null || userPassword == null) { return ResultUtil.error(ErrorCode.PARAM_ERROR); } User user1 = userService.dologin(userAccount, userPassword, request); return ResultUtil.success(user1); } //查找用户 @GetMapping("/search") public BaseResponse<List<User>> searchUser(String username, HttpServletRequest request) { //仅管理员可以查询 if (!isadmin(request)) { return ResultUtil.error(ErrorCode.NO_AUTH); } QueryWrapper<User> queryWrapper = new QueryWrapper<>(); if (StringUtils.isNotBlank(username)) { queryWrapper.like("username", username); } List<User> list = userService.list(queryWrapper); List<User> collect = list.stream().map(user -> userService.getSafierUser(user)).collect(Collectors.toList()); return ResultUtil.success(collect); } @PostMapping("/delete") public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) { //仅管理员可以查询 if (!isadmin(request)){ return ResultUtil.error(ErrorCode.NO_AUTH); } if (id <= 0) { return ResultUtil.error(ErrorCode.NULL_ERROR); } boolean b = userService.removeById(id); return ResultUtil.success(b); } @GetMapping("/current") public BaseResponse<User> getCurrentUser(HttpServletRequest request) { Object userLoginStatus = request.getSession().getAttribute(USER_LOGIN_STATUS); if (userLoginStatus == null) { return ResultUtil.error(ErrorCode.NOT_LOGIN); } User currentUser = (User) userLoginStatus; User userNow = userService.getById(currentUser.getId()); User safierUser = userService.getSafierUser(userNow); return ResultUtil.success(safierUser); } /** * 用户退出登录 */ @PostMapping("/logout") public BaseResponse<Integer> userlogout(HttpServletRequest request) { if (request == null) { return ResultUtil.error(ErrorCode.NULL_ERROR); } int userlogout = userService.userlogout(request); return ResultUtil.success(userlogout); } /** * 是否为管理员 * * @param request * @return */ private boolean isadmin(HttpServletRequest request) { //仅管理员可以查询 Object userLoginStatus = request.getSession().getAttribute(USER_LOGIN_STATUS); User user = (User) userLoginStatus; if (user == null || (user.getUserRole() != ADMIN_ROLE)) { return false; } return true; } }
class Solution { public int[] nextGreaterElements(int[] nums) { int[] result = new int[nums.length]; Stack<Integer> stack = new Stack<>(); for (int i = nums.length -1; i >= 0; i--) { stack.push(i); } for (int i = nums.length - 1; i >= 0; i--) { result[i] = -1; //The item that can't find larger one should equal to -1 as default. while (!stack.isEmpty() && nums[stack.peek()] <= nums[i]) { stack.pop(); // pop the stack until we meet the index of larger one of the item } if (!stack.isEmpty()) { result[i] = nums[stack.peek()]; // now the item's value is the larger one. stack.peek() is the index } stack.push(i); // i can be the larger one of the next item } return result; } }
#pragma once #include <string> #include <glm/glm.hpp> #include <vector> #include <fstream> #include <iostream> #include <memory> #include "ISerializable.h" template<typename ResponseT> class Array3D : public ISerializable{ private: ResponseT* _ptr; size_t _w=0, _h=0, _d=0; bool _copied = false; public: class xySlice { public: xySlice(int x, int y, const Array3D* array3d) :m_array3D(array3d), m_x(x), m_y(y){} ResponseT& operator[](size_t z) { return m_array3D->At(m_x, m_y, z); } private: const Array3D* m_array3D; int m_x; int m_y; }; class xSlice { public: xSlice(int x, const Array3D* array3d) :m_array3D(array3d), m_x(x) {} xySlice operator[](int y) { return xySlice(m_x, y, m_array3D); } private: const Array3D* m_array3D; int m_x; }; Array3D() {} Array3D(const Array3D& old_obj) { _w = old_obj._w; _h = old_obj._h; _d = old_obj._d; _ptr = old_obj._ptr; old_obj._copied = true; } Array3D(AUTOLIST_CTOR_OPTIONS options) :ISerializable(options) {} Array3D(size_t w, size_t h, size_t d); ~Array3D(); void allocate(size_t w, size_t h, size_t d); ResponseT* getPtr() const { return _ptr; } size_t getW() const { return _w; } size_t getH() const { return _h; } size_t getD() const { return _d; } ResponseT& At(size_t x, size_t y, size_t z) const; ResponseT& At(const glm::ivec3& at) const { return At(at.x, at.y, at.z); } ResponseT& operator [](const glm::ivec3& at) const { return At(at.x, at.y, at.z);} xSlice operator[](int xCoord) const { return xSlice(xCoord, this); } void free(); virtual void SaveToFile(std::string filePath)const override; virtual void LoadFromFile(std::string filePath) override; virtual char* SaveToBuffer(char* destination)const override; virtual const char* LoadFromBuffer(const char* source) override; virtual bool SetSerializableProperty(const SerializableProperty& p) override; virtual int GetNumSerializableProperties() const override; virtual const std::vector<SerializableProperty>& GetSerializableProperties() const; virtual std::string GetSerializableNodeName() const override; virtual size_t GetBinaryFileNumBytes() const override; /* * pass an opened file stream that is set to the start of a saved array3d. * */ void StreamAlreadyAllocatedArrayFromFile(std::ifstream& stream, const glm::ivec3& originAt, unsigned int offsetOfArrayFromStartOfFile = 0); }; template<typename ResponseT> inline Array3D<ResponseT>::Array3D(size_t w, size_t h, size_t d) { allocate(w, h, d); } template<typename ResponseT> inline Array3D<ResponseT>::~Array3D() { if(_ptr != nullptr && !_copied) free(); } template<typename ResponseT> inline void Array3D<ResponseT>::allocate(size_t w, size_t h, size_t d) { if (_ptr != nullptr) free(); _w = w; _h = h; _d = d; _ptr = new ResponseT[w * h * d]; memset(_ptr, 0x00, w * h * d * sizeof(ResponseT)); } template<typename ResponseT> inline ResponseT& Array3D<ResponseT>::At(size_t x, size_t y, size_t z) const { size_t index = x * _h * _d + y * _d + z; return _ptr[index]; } template<typename ResponseT> inline void Array3D<ResponseT>::free() { delete[] _ptr; } template<typename ResponseT> inline void Array3D<ResponseT>::SaveToFile(std::string filePath) const { // allocate buffer to be written to file, layed out as follows: // width, height, depth, array data const auto outputBufferSize = (sizeof(size_t) * 3) + (sizeof(ResponseT) * _w * _d * _h); auto outputBuffer = std::make_unique<char>(outputBufferSize); SaveToBuffer(outputBuffer.get()); // write to file std::ofstream file(filePath, std::ios::out | std::ios::binary); file.write(outputBuffer.get(), outputBufferSize); } template<typename ResponseT> inline void Array3D<ResponseT>::LoadFromFile(std::string filePath) { // open file std::ifstream is(filePath, std::ios::in | std::ios::binary); // get length is.seekg(0, is.end); int fileLength = is.tellg(); is.seekg(0, is.beg); // allocate buffer for the entire files contents and write files contents into it auto inputBuf = std::make_unique<char[]>(fileLength); is.read(inputBuf.get(), fileLength); LoadFromBuffer(inputBuf.get()); } #define ARRAY3D_NUM_SERIALIZABLE_PROPERTIES 4 template<typename ResponseT> inline const std::vector<SerializableProperty>& Array3D<ResponseT>::GetSerializableProperties() const { static std::vector<SerializableProperty> props(ARRAY3D_NUM_SERIALIZABLE_PROPERTIES); props[0].name = "Data"; props[0].type = SerializablePropertyType::Bytes; props[0].data.SizeIfApplicable = sizeof(ResponseT) * _w * _d * _h; props[0].data.dataUnion.Bytes = (char*)_ptr; props[1].name = "Width"; props[1].type = SerializablePropertyType::Uint32; props[1].data.dataUnion.Uint32 = _w; props[2].name = "Height"; props[2].type = SerializablePropertyType::Uint32; props[2].data.dataUnion.Uint32 = _h; props[3].name = "Depth"; props[3].type = SerializablePropertyType::Uint32; props[3].data.dataUnion.Uint32 = _d; return props; } template<typename ResponseT> inline bool Array3D<ResponseT>::SetSerializableProperty(const SerializableProperty& p) { if (p.name == "Data") { _ptr = (ResponseT*)p.data.dataUnion.Bytes; return true; } else if (p.name == "Width") { _w = p.data.dataUnion.Uint32; return true; } else if (p.name == "Height") { _h = p.data.dataUnion.Uint32; return true; } else if (p.name == "Depth") { _d = p.data.dataUnion.Uint32; return true; } return false; } template<typename ResponseT> inline int Array3D<ResponseT>::GetNumSerializableProperties() const { return ARRAY3D_NUM_SERIALIZABLE_PROPERTIES; } template<typename ResponseT> std::string Array3D<ResponseT>::GetSerializableNodeName() const { return "Array3D"; } template<typename ResponseT> inline char* Array3D<ResponseT>::SaveToBuffer(char* destination) const { // copy class data to the staging buffer memcpy(destination, &_w, sizeof(size_t)); memcpy(destination + sizeof(size_t), &_h, sizeof(size_t)); memcpy(destination + sizeof(size_t) * 2, &_d, sizeof(size_t)); memcpy(destination + sizeof(size_t) * 3, _ptr, sizeof(ResponseT) * _w * _d * _h); return destination + sizeof(size_t) * 3 + sizeof(ResponseT) * _w * _d * _h; } template<typename ResponseT> inline const char* Array3D<ResponseT>::LoadFromBuffer(const char* source) { // read width, height and depth, from the file into local vars size_t w, h, d; memcpy(&w, source, sizeof(size_t)); memcpy(&h, source + sizeof(size_t), sizeof(size_t)); memcpy(&d, source + sizeof(size_t) * 2, sizeof(size_t)); // allocate using the w, h and d obtained from the file allocate(w, h, d); // copy array data into newly allocated array memcpy(_ptr, source + sizeof(size_t) * 3, sizeof(ResponseT) * w * h * d); return source + sizeof(size_t) * 3 + sizeof(ResponseT) * w * h * d; } template<typename ResponseT> inline size_t Array3D<ResponseT>::GetBinaryFileNumBytes() const { return sizeof(size_t) * 3 + sizeof(ResponseT) * _w * _d * _h; } template<typename ResponseT> void Array3D<ResponseT>::StreamAlreadyAllocatedArrayFromFile(std::ifstream& stream, const glm::ivec3& originAt, unsigned int offsetOfArrayFromStartOfFile) { size_t originIndex = originAt.x * _h * _d + originAt.y * _d + originAt.z; auto onVoxel = glm::ivec3(); for (int z = 0; z < _d; z++) { for (int y = 0; y < _h; y++) { for (int x = 0; x < _w; x++) { onVoxel = originAt + glm::ivec3{ x,y,z }; size_t index = onVoxel.x * _h * _d + onVoxel.y * _d + onVoxel.z; stream.seekg( offsetOfArrayFromStartOfFile + sizeof(size_t) * 3 + // the three fields are saved first see save to buffer function index * sizeof(ResponseT), std::ios::beg ); stream.read((char*)&At(x, y, z), sizeof(ResponseT)); } } } }
using System; using System.Linq; using BeastRescue.Models; using System.Threading.Tasks; using Microsoft.OpenApi.Models; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace BeastRescue { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<BeastRescueContext>(opt => opt.UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"]))); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "BeastRescue", Version = "v1", Description = "Beast Rescue Rescues Beasts", Contact = new OpenApiContact { Name = "Beast Rescue of the Pacific Northwest", Email = string.Empty, Url = new Uri("https://unsplash.com/photos/V5pZ9F0M4vU"), } }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "BeastRescue v1"); c.RoutePrefix = string.Empty; }); // app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
import random import pycountry import pytest from faker import Faker from sqlmodel import Session, select from ibg.api.controllers.user import UserController from ibg.api.models.error import UserAlreadyExistsError, UserNotFoundError from ibg.api.models.table import User from ibg.api.models.user import UserCreate, UserUpdate @pytest.mark.asyncio async def test_creates_new_user_with_valid_input(user_controller: UserController, session: Session, faker: Faker): # Arrange user_create = UserCreate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), password=faker.password(), ) # Act result = await user_controller.create_user(user_create) db_user = session.exec(select(User).where(User.id == result.id)).one() # Assert assert result.username == user_create.username == db_user.username assert result.email_address == user_create.email_address == db_user.email_address assert result.country == user_create.country == db_user.country assert result.password == user_create.password == db_user.password assert db_user.id == result.id @pytest.mark.asyncio async def test_create_two_users_with_same_email_address(user_controller: UserController, faker: Faker): # Arrange user_create = UserCreate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), password=faker.password(), ) # Act await user_controller.create_user(user_create) # Assert with pytest.raises(UserAlreadyExistsError): await user_controller.create_user(user_create) @pytest.mark.asyncio async def test_raises_exception_if_user_create_is_none(user_controller: UserController): with pytest.raises(Exception): await user_controller.create_user(None) @pytest.mark.asyncio async def test_empty_list_when_no_users(user_controller: UserController): # Arrange # Act result = await user_controller.get_users() # Assert assert result == [] @pytest.mark.asyncio async def test_list_few_users(user_controller: UserController, faker: Faker): # Arrange users = [ UserCreate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), password=faker.password(), ) for _ in range(5) ] # Act created_users = [await user_controller.create_user(user) for user in users] db_users = await user_controller.get_users() # Assert assert len(db_users) == 5 for user, created_user, db_user in zip(users, created_users, db_users): assert user.username == created_user.username == db_user.username assert user.email_address == created_user.email_address == db_user.email_address assert user.country == created_user.country == db_user.country assert user.password == created_user.password == db_user.password @pytest.mark.asyncio async def test_returns_user_with_valid_uuid(user_controller: UserController, faker: Faker): # Arrange user_create = UserCreate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), password=faker.password(), ) new_user = await user_controller.create_user(user_create) # Act result = await user_controller.get_user_by_id(new_user.id) # Assert assert result.id == new_user.id assert result.username == user_create.username == new_user.username assert result.email_address == user_create.email_address == new_user.email_address assert result.country == user_create.country == new_user.country assert result.password == user_create.password == new_user.password @pytest.mark.asyncio async def test_update_user_with_valid_input(user_controller: UserController, faker: Faker): # Arrange user_create = UserCreate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), password=faker.password(), ) new_user = await user_controller.create_user(user_create) user_update = UserUpdate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), ) # Act updated_user = await user_controller.update_user_by_id(new_user.id, user_update) # Assert assert updated_user.id == new_user.id assert updated_user.username == user_update.username assert updated_user.email_address == user_update.email_address assert updated_user.country == user_update.country @pytest.mark.asyncio async def test_update_user_with_invalid_user_id(user_controller: UserController, faker: Faker): # Arrange user_update = UserUpdate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), ) # Act & Assert with pytest.raises(UserNotFoundError, match="User with id .* not found"): await user_controller.update_user_by_id(faker.uuid4(), user_update) @pytest.mark.asyncio async def test_delete_user(user_controller: UserController, session: Session, faker: Faker): # Arrange user_create = UserCreate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), password=faker.password(), ) new_user = await user_controller.create_user(user_create) # Act await user_controller.delete_user(new_user.id) # Assert with pytest.raises(UserNotFoundError, match="User with id .* not found"): await user_controller.get_user_by_id(new_user.id) @pytest.mark.asyncio async def test_delete_user_bad_behavior(user_controller: UserController, faker: Faker): # Arrange non_existent_id = faker.uuid4() # Act & Assert with pytest.raises(UserNotFoundError, match="User with id .* not found"): await user_controller.delete_user(non_existent_id) @pytest.mark.asyncio async def test_update_user_password(user_controller: UserController, session: Session, faker: Faker): # Arrange user_create = UserCreate( username=faker.user_name(), email_address=faker.email(), country=random.choice([country.alpha_3 for country in pycountry.countries]), password=faker.password(), ) new_user = await user_controller.create_user(user_create) new_password = faker.password() # Act updated_user = await user_controller.update_user_password(new_user.id, new_password) # Assert assert updated_user.id == new_user.id assert updated_user.username == new_user.username assert updated_user.email_address == new_user.email_address assert updated_user.country == new_user.country assert updated_user.password == new_password @pytest.mark.asyncio async def test_update_user_password_that_doesnt_exist(user_controller: UserController, faker: Faker): # Arrange non_existent_id = faker.uuid4() new_password = faker.password() # Act & Assert with pytest.raises(UserNotFoundError, match="User with id .* not found"): await user_controller.update_user_password(non_existent_id, new_password)
import spacy def get_movie_suggestions(movie_description, movies): """Returns the most similar movie to the movie description Parameters movie_description: str # The description of the movie movies: dict # A dictionary of movie names and descriptions""" nlp = spacy.load("en_core_web_md") nlp_movie_description = nlp(movie_description) highest_similarity = 0 most_similar_movie = "" for movie_name, movie in movies.items(): similarity = nlp_movie_description.similarity(nlp(movie)) if similarity > highest_similarity: highest_similarity = similarity most_similar_movie = movie_name return most_similar_movie def main(): """Reads movies.txt to a dictionary, splits the line by colon to get the movie name and description, removing trailing whitespace. and then calls get_movie_suggestions to get the most similar movie""" movies = {} with open("movies.txt", "r") as f: for line in f: movie_name, movie_description = line.split(":") movies[movie_name] = movie_description.strip() test_movie = """Will he save their world or destroy it? When the Hulk becomes too dangerous for the Earth, the Illuminati trick Hulk into a shuttle and launch him into space to a planet where the Hulk can live in peace. Unfortunately, Hulk land on the planet Sakaar where he is sold into slavery and trained as a gladiator.""" print(get_movie_suggestions(test_movie, movies)) if __name__ == '__main__': main()
\documentclass[11pt]{exam} \newcommand{\myname}{Sihao Yin, Yuxuan Jiang} %Write your name in here \newcommand{\myUCO}{0028234022, 0028440468} %write your UCO in here \newcommand{\myhwtype}{Homework} \newcommand{\myhwnum}{12} %Homework set number \newcommand{\myclass}{CS580} \newcommand{\mylecture}{} \newcommand{\mysection}{} \usepackage{listings} % Prefix for numedquestion's \newcommand{\questiontype}{Question} % Use this if your "written" questions are all under one section % For example, if the homework handout has Section 5: Written Questions % and all questions are 5.1, 5.2, 5.3, etc. set this to 5 % Use for 0 no prefix. Redefine as needed per-question. \newcommand{\writtensection}{0} \usepackage{amsmath, amsfonts, amsthm, amssymb} % Some math symbols \usepackage{enumerate} \usepackage{graphicx} \usepackage{hyperref} \usepackage[all]{xy} \usepackage{wrapfig} \usepackage{fancyvrb} \usepackage[T1]{fontenc} \usepackage{listings} \usepackage[shortlabels]{enumitem} \usepackage{centernot} \usepackage{mathtools} \DeclarePairedDelimiter{\ceil}{\lceil}{\rceil} \DeclarePairedDelimiter{\floor}{\lfloor}{\rfloor} \DeclarePairedDelimiter{\card}{\vert}{\vert} \setlength{\parindent}{0pt} \setlength{\parskip}{5pt plus 1pt} \pagestyle{empty} \def\indented#1{\list{}{}\item[]} \let\indented=\endlist \newcounter{questionCounter} \newcounter{partCounter}[questionCounter] \newenvironment{namedquestion}[1][\arabic{questionCounter}]{% \addtocounter{questionCounter}{1}% \setcounter{partCounter}{0}% \vspace{.2in}% \noindent{\bf #1}% \vspace{0.3em} \hrule \vspace{.1in}% }{} \newenvironment{numedquestion}[0]{% \stepcounter{questionCounter}% \vspace{.2in}% \ifx\writtensection\undefined \noindent{\bf \questiontype \; \arabic{questionCounter}. }% \else \if\writtensection0 \noindent{\bf \questiontype \; \arabic{questionCounter}. }% \else \noindent{\bf \questiontype \; \writtensection.\arabic{questionCounter} }% \fi \vspace{0.3em} \hrule \vspace{.1in}% }{} \newenvironment{alphaparts}[0]{% \begin{enumerate}[label=\textbf{(\alph*)}] }{\end{enumerate}} \newenvironment{arabicparts}[0]{% \begin{enumerate}[label=\textbf{\arabic{questionCounter}.\arabic*})] }{\end{enumerate}} \newenvironment{questionpart}[0]{% \item }{} \newcommand{\answerbox}[1]{ \begin{framed} \vspace{#1} \end{framed}} \pagestyle{head} \headrule \header{\textbf{\myclass\ \mylecture\mysection}}% {\textbf{\myname\ (\myUCO)}}% {\textbf{\myhwtype\ \myhwnum}} \begin{document} \thispagestyle{plain} \begin{center} {\Large \myclass{} \myhwtype{} \myhwnum} \\ \myname{} (\myUCO{}) \\ \today \end{center} %Here you can enter answers to homework questions \begin{numedquestion} \begin{enumerate}[a] \item Suppose we have a graph G, we can construct a graph G' by adding a vertex v, which has edges to all vertices in G. Hence, as long as there is a s-t Hamiltonian path in G, there will be a Hamiltonian circle in G', because with the help of v, we can reach back at s via v from t. This can be done in polynomial time since there are only N edges and 1 vertex that need to be added \item Given a undirected graph G, we can construct a directed graph G' as follows: for each edge in G, we construct two edges in G' that go in the opposite direction. Hence, if there is an undirected Hamiltonian cycle in G, there will also be a Hamiltonian cycle in G'. If there is a directed Hamiltonian cycle in G', there will also be a undirected Hamiltonian cycle in G. The construction of G' can be done in polynomial time because there are only N edges \item Given a directed graph G, we can construct a undirected graph G as follows: for each vertex v in G, we create 3 vertices v',v'',v''' in G' and there will be edges (v',v'') and (v'',v'''). For each edge u$\rightarrow$v in G, we create an edge (u''',v') to G'. This can be done in polynomial time. If there is a Hamiltonian cycle in G, a Hamilton cycle in G' will look like v1',v1'',v1''',v2',v2'',v2'''...... If there is a Hamiltonian cycle in G', the Hamiltonian cycle in G is determined by the positions of vi'' in G'. Since vi'' in G' is preceded by vi' and succeeded by vi''', if the Hamiltonian cycle in G' looks like v1'',v2'',v3'',...., then the Hamiltonian cycle in G will look like v1,v2,v3.... \item First, we can use a) to deduce directed Hamiltonian path to directed Hamiltonian cycle. Then we can use c) to deduce directed Hamiltonian cycle to undirected Hamiltonian cycle. If we can deduce undirected Hamiltonian cycle to undirected Hamiltonian path in polynomial time, we can find a polynomial time reduction from directed Hamiltonian path to undirected Hamiltonian path since all the aforementioned reductions are in polynomial time. We give the polynomial time reduction from undirected Hamiltonian cycle to undirected Hamiltonian path. Given a undirected graph G, we can construct a graph G' as follows: First we copy all vertices to G', then for one random vertex v in G, we create a copy v' of it in G'. v' in G' has all the edges v has in G.Then in G', we add two vertices u and u'. We also add two edges u-v and u'-v' in G' This can be done in polynomial time If there is a Hamiltonian cycle in G, there will be a Hamiltonian path u-u' in G'. If there is a Hamiltonian path u-u' in G', we can also see that there must be a Hamiltonian cycle in G. Note the only Hamiltonian path in G' must be the path u-u', since u is only connected to v and u' is only connected to v'. Hence, with the above, we have found a polynomial time reduction from directed Hamiltonian path to undirected Hamiltonian path. \end{enumerate} \end{numedquestion} \pagebreak \begin{numedquestion} To prove a problem is at least hard as SAT, we can try to prove they are NP-hard, since SAT is a NP. \begin{enumerate}[a] \item A spanning tree visits every node. We can see that a spanning tree with only 2 leaves is exactly a Hamiltonian path problem. If we can find a Hamiltonian path from one leaf to the other, we found a spanning tree with two leaves. Hence, we can reduct the problem of finding a spanning tree with two leaves in G from finding a Hamiltonian path in G'. Since finding a Hamiltonian path is at least hard as SAT, finding a spanning tree with 2 leaves is also as hard as SAT. \item A spanning tree with a degree at most 2 is also a Hamiltonian path problem. We can reduct the problem of finding a spanning tree with a degree at most 2 from the Hamiltonian path problem, since the source and destination would have a degree of 1 while all other nodes have a degree of 2. Same as above, since finding a Hamiltonian path is at least hard as SAT, finding a spanning tree with degree at most 2 is also as hard as SAT. \item We reduct this problem from the undirected Hamiltonian path problem. Given a undirected G, we construct a undirected graph G' as follows: \begin{enumerate} \item First copy G to G' \item In G', we add a vertex v that is connected to all other vertices. \item In G', we add 41 vertices u1,u2,...u41, each with an edge to v \end{enumerate} G' can be constructed in polynomial time If G has a Hamiltonian path s-t, then in G' t is also connected to v and v is connected to u1 to u41. The spanning tree in G' will be formed by all vertices in G and the 41 added vertices. This spanning tree has 42 leaf vertices, namely s and the 41 added vertices If there is a spanning tree in G' with 42 leaves, we know s is the leaf vertex that is not a ui. We also know t is the only neighbour of v in the spanning tree that is not a leaf vertex. A path from s to t must visit all the vertices in G. As before, since we can reduct this problem from the Hamiltonian path problem, this problem as at least as hard as SAT \item We reduct this problem from the undirected Hamiltonian path problem. Given a undirected G with a s-t Hamiltonian path, we construct a undirected graph G' as follows: \begin{enumerate} \item First copy G to G' \item In G', we add 40 edges to each vertex, each of these 42 edges connect a vertex in G to a newly created vertex, thus each vertex in G' has a degree at most 42 \end{enumerate} G' can be constructed in polynomial time If G has a Hamiltonian path s-t, we can find a spanning tree in G' by simply applying step 2 in the above construction of G'. Then, each vertex in G' can be either a leaf, which is the newly created vertex, or it could be a vertex on the Hamiltonian path. If it is a vertex on the path, it has a degree at most 42. If there is a spanning tree in G', the vertices that form a Hamiltonian path in G will be those vertices in the spanning tree in G' that is not a leaf node. Since we can use the algorithm of this problem to solve the problem of Hamiltonian path, This problem is at least as hard as Hamiltonian path, which is as hard as SAT. \end{enumerate} \end{numedquestion} \pagebreak \begin{numedquestion} \begin{enumerate}[a] \item read it \item Given a undirected graph G, we construct a graph G' as follows: for any inter-connected 3 vertices, we add k-3 vertices, so that these k vertices are connected to each other. We can do this in polynomial time If G is 3-colourable, then in G', we can assign each of the added k-3 vertices with a new colour that is not one of the original 3 colours If G' is k-colourable, then we know G is 3-colourable. \item We give the algorithm as follows \\ \\ \textbf{Introduction:} We use the idea of a "gadget" as introduced by Jeff. The different is, instead of a gadget with 3 vertices, we use a gadget with k vertices. These k vertices are connected to each other, each of a different colour. We incorporate the gadget in the original graph. We call the new graph G'. Note, at the beginning, the gadget is not connected to any vertex in G. For each vertex v in G, we do the following \begin{enumerate} \item we connect it to k-1 vertices in the gadget, so when colouring, v has the colour of the one un-connected vertex in the gadget. \item We feed G' to the subroutine. \begin{enumerate} \item If G' turns out to be k-colourable, we keep the v-1 edges in G', which symbolising us remembering the colour choice for v. \item If G' turns out not to be k-colourable, we try to connect v with another k-1 vertices in the gadget and redo the test. \end{enumerate} \item It is guaranteed for at least one test to pass, since we know the original graph is k-colourable. \end{enumerate} We perform the aforementioned transformation to each vertex in the original graph, one by one. In the end, we will get a k-coloring\\ \\ \textbf{Algorithm:} \begin{lstlisting} function kColour(G): G' = incorporate the gadget into G //this is the mapping of colour and vertices in G colour = new Map for each vertex v in G: for each vertex u in gadget: G' = connect v with vertices in the gadget other than u if subroutine(G') == 'TRUE': keep the k-1 edges in G' colour[v] = colour[u] break else: delete the k-1 edges in G' continue \end{lstlisting} \\ \textbf{Correctness:} At each step we assign the colour of a vertex to be the colour of the unselected vertex in the gadget. We use the subroutine to guarantee after this assignment, graph G is still k-colourable. Therefore, after each successful assignment, graph G will always remain k-colourable, until we found a mapping for all vertices.\\ \\ \textbf{Analysis:} We traverse each vertex in G. For each vertex, at most we need to try all vertices in the gadget. For each try, we call the subroutine, which has polynomial time. Suppose we can represent the runtime of the routine as f(n), the total time needed is O(f(n)+k*n*f(n)). As we can see, this time is polynomial. \item Since 2-coloring is the same as determining if the graph is bipartite or not, we can solve 2-coloring in polynomial time. We give the pseudocode below \begin{lstlisting} function 2Color(G): randomly colour a vertex with red colour neighbours of red vertex blue colour neighbours of blue vertex red while there still exists un-coloured vertices: if its neighbours are all red: colour it blue if its neighbours are all blue: colour it red if some neighbour blue and some neighbour red: return "Not 2-colourable" \end{lstlisting} The above algorithm will find a 2-coloring if the graph is indeed 2-colourable. It will return not 2-colourable otherwise.// The above algorithm is also polynomial, since it colours each vertex exactly once. \end{enumerate} \end{numedquestion} % if you do not solve some of the questions use this command to increment counter %\setcounter{questionCounter}{4} %\begin{numedquestion} % Questions 2 and 3 were not solved, this is an answer to question 5. %\end{numedquestion} % if questions have subparts, use this command %\pagebreak %\begin{numedquestion} % Use the alphaparts environment to for letters. % \begin{alphaparts} % \item Part a % \item Part b % \item Part c % \end{alphaparts} %\end{numedquestion} %\begin{numedquestion} % Using the \texttt{description} environment is a great way to typeset induction proofs! % \begin{description} % \item[Base Case:] % Here I have my base case. % \item[Induction Hypothesis:] % Assume things to make proof work. % \item[Induction Step:] % Prove all the things. % \end{description} % Therefore, we have proven the claim by induction on in the \texttt{description} environment. %\end{numedquestion} \end{document}
//------------------------------------------------------------ACOUNT------------------------------------------------------------ /** * @swagger * /Account: * get: * tags: * - Account * description: Get all Users * responses: * '200': * description: Success ! */ /** /** * @swagger * /Account/Login: * post: * consumes: * - application/json * tags: * - Account * parameters: * - in: body * name: user * description: The user to create. * schema: * type: object * properties: * UserName: * type: string * Password: * type: string * responses: * '200': * description: Success ! */ /** * @swagger * /Account/Register: * post: * consumes: * - application/json * tags: * - Account * parameters: * - in: body * name: user * description: The user to create. * schema: * type: object * properties: * UserName: * type: string * Password: * type: string * FullName: * type: string * Email: * type: string * Role: * type: array * responses: * '200': * description: Success ! */ /** * @swagger * /Account/{id}: * put: * consumes: * - application/json * tags: * - Account * parameters: * - in: path * name: id * - in: body * name: user * description: The user to create. * schema: * type: object * properties: * UserName: * type: string * Password: * type: string * FullName: * type: string * Email: * type: string * Role: * type: array * responses: * '200': * description: Success ! */ /** * @swagger * /Account/{id}: * delete: * consumes: * - application/json * tags: * - Account * parameters: * - in: path * name: id * responses: * '200': * description: Success ! */
import { useToast } from "@chakra-ui/react" import {useContext,createContext,useState} from "react" import {api} from "../services/api" export const LoanContext = createContext({}) export const useLoan = () => { const context = useContext(LoanContext); if (!context) { throw new Error("userAuth must be used within an AuthProvider"); } return context; } export const LoanProvider = ({children}) => { const [loan,setLoan] = useState({}) const [installments,setInstallments] = useState([]) const toast = useToast() const simulateLoan = async (data) => { api.post("/loans",data ).then((loanResponse) => { setLoan(loanResponse.data) setInstallments(loanResponse.data.installments) }).catch((err) => toast({ title:"Aumente o valor da parcela.", description:"O valor mínimo da parcela deve ser 1% do valor total do empréstimo.", status:"error", duration:6000, position:"top-right", isClosable:true }))} return ( <LoanContext.Provider value={{loan, installments,simulateLoan}}>{children}</LoanContext.Provider> ) }
import { Input, HostBinding, Component } from "@angular/core"; import { ButtonLikeAbstraction } from "../shared/button-like.abstraction"; export type ButtonTypes = "primary" | "secondary" | "danger"; const buttonStyles: Record<ButtonTypes, string[]> = { primary: [ "tw-border-primary-500", "tw-bg-primary-500", "!tw-text-contrast", "hover:tw-bg-primary-700", "hover:tw-border-primary-700", "disabled:tw-bg-primary-500/60", "disabled:tw-border-primary-500/60", "disabled:!tw-text-contrast/60", "disabled:tw-bg-clip-padding", ], secondary: [ "tw-bg-transparent", "tw-border-text-muted", "!tw-text-muted", "hover:tw-bg-text-muted", "hover:tw-border-text-muted", "hover:!tw-text-contrast", "disabled:tw-bg-transparent", "disabled:tw-border-text-muted/60", "disabled:!tw-text-muted/60", ], danger: [ "tw-bg-transparent", "tw-border-danger-500", "!tw-text-danger", "hover:tw-bg-danger-500", "hover:tw-border-danger-500", "hover:!tw-text-contrast", "disabled:tw-bg-transparent", "disabled:tw-border-danger-500/60", "disabled:!tw-text-danger/60", ], }; @Component({ selector: "button[bitButton], a[bitButton]", templateUrl: "button.component.html", providers: [{ provide: ButtonLikeAbstraction, useExisting: ButtonComponent }], }) export class ButtonComponent implements ButtonLikeAbstraction { @HostBinding("class") get classList() { return [ "tw-font-semibold", "tw-py-1.5", "tw-px-3", "tw-rounded", "tw-transition", "tw-border", "tw-border-solid", "tw-text-center", "hover:tw-no-underline", "focus:tw-outline-none", "focus-visible:tw-ring", "focus-visible:tw-ring-offset-2", "focus-visible:tw-ring-primary-700", "focus-visible:tw-z-10", ] .concat( this.block == null || this.block === false ? ["tw-inline-block"] : ["tw-w-full", "tw-block"] ) .concat(buttonStyles[this.buttonType ?? "secondary"]); } @HostBinding("attr.disabled") get disabledAttr() { const disabled = this.disabled != null && this.disabled !== false; return disabled || this.loading ? true : null; } @Input() buttonType: ButtonTypes = null; @Input() block?: boolean; @Input() loading = false; @Input() disabled = false; @Input("bitIconButton") icon: string; get iconClass() { return [this.icon, "!tw-m-0"]; } }
<template> <div class="container"> <div> <Logo /> <h6 class="title">三种路由配置</h6> <ul> <li>page页面自动配置</li> <li>@nuxtjs/router 模块配置</li> <li>nuxt.config.js 中配置 router>extendRouters</li> </ul> <div class="links"> <nuxt-link to="/item" class="button--grey" alt=" 自动路由 /item"> 自动路由静态的 /item </nuxt-link> <nuxt-link to="/some/my-component-page" class="button--grey" alt=" 自定路由到 /some/my-component-page" > 自定义路由/some/my-component-page </nuxt-link> </div> <div class="links"> <nuxt-link :to="'/item-' + parseInt(Math.random() * 1000)" class="button--grey" alt=" 自动路由 /item" > 自动路由+自定义路由 成为动态的 /item-${id} </nuxt-link> <nuxt-link :to="'/item/' + parseInt(Math.random() * 1000)" class="button--grey" alt=" 自动路由 /item" > 自动路由动态 /item/${id} </nuxt-link> <nuxt-link :to="'/extend/test'" class="button--grey"> nuxt.config.js 配置的拓展路由 /extend/test</nuxt-link > </div> <p>.</p> <p>.</p> <p>.</p> <div> <nuxt-link to="/qiantao" class="button--grey">嵌套路由</nuxt-link> </div> </div> </div> </template> <script> export default {}; </script> <style> .container { margin: 0 auto; min-height: 100vh; display: flex; justify-content: center; align-items: center; text-align: center; flex-wrap:wrap; } .title { font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; display: block; font-weight: 900; font-size: 25px; color: #35495e; background: #ffcc33; letter-spacing: 1px; } .subtitle { font-weight: 300; font-size: 42px; color: #526488; word-spacing: 5px; padding-bottom: 15px; } .links { padding-top: 15px; } </style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> </style> </head> <body> <div id="app"> <div> {{msg_num/20}} </div> <div> {{msg_bullon?"是啊":"不是"}} </div> <div> {{msg_arr.split("/")}} </div> <div> <!-- 知识点【1】:1.0中的的小写转大写过滤符在2.0中被废弃 --> {{msg_small | toUpperCase }} </div> <div> {{msg_filter | fileter_fun}} <!-- 知识点【2】:过滤器中传参语法不是这样的 --> <!-- {{msg_filter | fileter_fun "sky" "moon"}} --> </div> </div> </body> <script type="text/javascript" src="../../../../commonJS/vue.js"></script> <script type="text/javascript" src="../../../../commonJS/zepto-1.2.0.js"></script> <!-- <script type="text/javascript" src="../../../../commonJS/moment.js"></script> --> <!-- <script type="text/javascript" src="../../../../commonJS/common.js"></script> --> <script> 'use strict'; Vue.prototype.$ = $; var app = new Vue({ el: "#app", data: function() { return { msg_num: 100, msg_bullon: true, msg_arr: "2019/11/02", msg_small: "abc", msg_filter: "ok" } }, filters: { fileter_fun: function fileter_fun(value, param1, param2) { var this_ = this; debugger var a = param1; var b = param2; if ("ok") { return "过滤生效" } } } }) </script> </html>
const { Task } = require('klasa'); const { DateTime } = require('luxon'); const fetch = require('node-fetch'); module.exports = class extends Task { constructor(...args) { super(...args, { enabled: true }); } async run(metadata) { const today = DateTime.local().minus({ months: 1 }); const count_by_users = await fetch(`${process.env.WEBSITEURL}/api/graphql`, { method: "post", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ query: `{ allQuestions(filter: {validated: {isNull: false}, createdAt: {greaterThanOrEqualTo: "${today.toFormat('yyyy-LL-01')}"}}) { nodes { userByUserId { discordId } } } }` }) }) .then(response => response.json()) .then(response => { const count_by_users = {}; for (let i = 0, imax = response.data.allQuestions.nodes.length ; i < imax ; i++) { const question = response.data.allQuestions.nodes[i]; count_by_users[question.userByUserId.discordId] = (count_by_users[question.userByUserId.discordId] || 0) + 1; } console.log(count_by_users); return count_by_users; }); const guilds = [...this.client.guilds.cache.values()]; for (let i = 0, imax = guilds.length ; i < imax ; i++) { const guild = guilds[i]; const role_id = guild.settings.permissions.monthly_contributor; const news_channel = guild.channels.resolve(guild.settings.channels.news); if (!role_id) continue; // fetch the role const role = guild.roles.resolve(role_id); if (!role) continue; // reset previous monthly contributor const previous = [...role.members.values()]; for (let j = 0, jmax = previous.length ; j < jmax ; j++) { previous[j].roles.remove(role); } const list = Object.keys(count_by_users).sort((a, b) => count_by_users[b] - count_by_users[a]); // check first user present in list for (let j = 0, jmax = list.length ; j < jmax ; j++) { const user = guild.members.resolve(list[j]); if (user) { // give it the role news_channel.send(`Félicitations à <@${list[j]}> qui a obtenu le rôle de ${role} avec ${count_by_users[list[j]]} questions postées ce mois-ci.`); user.roles.add(role); break; } } } } async init() { if (!this.client.schedule._tasks.some(t => t.id === 'monthly_contributor')) { this.client.schedule.create('monthly_contributor', '5 0 1 * *', { data: {}, catchUp: true, id: 'monthly_contributor' }); } } };
import express from 'express'; import * as http from 'http'; import 'dotenv/config'; import * as winston from 'winston'; import * as expressWinston from 'express-winston'; import cors from 'cors'; import debug from 'debug'; import { CommonRoutesConfig } from '../../adapters/apis/routes/common/common.routes.config'; import logger from '../logs/winston.logs'; import { ProductsRoutes } from '../../adapters/apis/routes/products/products.routes.config'; import { TablesRoutes } from '../../adapters/apis/routes/tables/tables.routes.config'; import handleError from '../config/handle.error'; const app: express.Application = express(); const server: http.Server = http.createServer(app); const port = process.env.PORT; const routes : CommonRoutesConfig[] = []; const debugLog: debug.IDebugger = debug('app'); app.use(express.json()); app.use(cors()); const loggerOptions: expressWinston.LoggerOptions = { transports: [new winston.transports.Console()], format: winston.format.combine( winston.format.json(), winston.format.prettyPrint(), winston.format.colorize({ all: true }) ), }; if(!process.env.DEBUG) { loggerOptions.meta = false; }; app.use(expressWinston.logger(loggerOptions)); routes.push(new ProductsRoutes(app)); routes.push(new TablesRoutes(app)); app.use(handleError.hasError); const runningMessage = `Server running on port ${port}`; app.get('/', (req: express.Request, res: express.Response) => { res.status(200).send(runningMessage); }); server.listen(port, () => { routes.forEach((route: CommonRoutesConfig) => { debugLog(`Configured routes for ${route.getName()}`); }); logger.info(runningMessage); }); export default app;
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <form:form method="POST" commandName="signUpForm" class="form-horizontal" name="addUserForm"> <div class="form-group"> <label class="control-label col-sm-2">login</label> <div class="col-sm-8"> <form:input path="username" type="text" class="form-control" /> <form:errors path="username" cssClass="alert-danger danger" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">email</label> <div class="col-sm-8"> <form:input path="email" type="email" class="form-control" /> <form:errors path="email" cssClass="alert-danger danger" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">password</label> <div class="col-sm-8"> <form:input path="password" type="password" class="form-control" /> <form:errors path="password" cssClass="alert-danger danger" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">confirm password</label> <div class="col-sm-8"> <form:input path="confirmPassword" type="password" class="form-control" /> <form:errors path="confirmPassword" cssClass="alert-danger danger" /> </div> </div> <div class="form-group"> <label class="col-sm-8 col-sm-offset-2"> <form:checkbox path="grantAdminAuthorities" /> grant admin authorities </label> </div> <c:if test="${ formActionMsg ne null }"> <div class="form-group col-sm-12"> <c:if test="${ formActionMsg.type eq errorMsg }"> <div class="alert alert-danger text-center">${formActionMsg.body}</div> </c:if> <c:if test="${ formActionMsg.type eq successMsg }"> <div class="alert alert-success text-center">${formActionMsg.body}</div> </c:if> </div> </c:if> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> <div class="form-group"> <div class="col-sm-offset-2 col-sm-8"> <input class="btn btn-success btn-block" type="submit" value="add account" /> </div> </div> </form:form>
<template> <el-aside width="200px"> <el-scrollbar> <el-menu router :default-active="defaultActive" background-color="transparent" > <template v-for="val in menuList"> <el-sub-menu :index="val.path" v-if="val.children && val.children.length > 0" :key="val.path" > <template #title> <!-- <SvgIcon :name="val.meta.icon" /> --> <span>{{ val.meta.title }}</span> </template> <SubItem :chil="val.children" /> </el-sub-menu> <el-menu-item :index="val.path" :key="val.path" v-else> <!-- <SvgIcon :name="val.meta.icon" /> --> <template #title> <span>{{ val.meta.title }}</span> </template> </el-menu-item> </template> </el-menu> </el-scrollbar> </el-aside> </template> <script lang="ts"> import { defineComponent, onBeforeMount, reactive, toRefs, watch } from "vue"; import { Location, Document, Menu as IconMenu, Setting, } from "@element-plus/icons-vue"; import { useStore } from "vuex"; import { useRoute } from "vue-router"; import SubItem from "./subMenu.vue"; export default defineComponent({ name: "Aside", components: { Location, Document, Setting, IconMenu, SubItem, }, setup() { const store = useStore(); const route = useRoute(); const state: any = reactive({ menuList: [], defaultActive: route.path, isCollapse: false, }); // 设置/过滤路由(非静态路由/是否显示在菜单中) const setFilterRoutes = () => { state.menuList = filterRoutesFun(store.state.routesList); }; // 路由过滤递归函数 const filterRoutesFun = (arr: Array<object>) => { return arr .filter((item: any) => !item.meta.isHide) .map((item: any) => { item = Object.assign({}, item); if (item.children) item.children = filterRoutesFun(item.children); return item; }); }; /** * @description 监听路由变化,切换菜单选中 */ watch( () => route.path, () => { state.defaultActive = route.path; } ); /** * @description 加载前设置路由菜单 */ onBeforeMount(() => { setFilterRoutes(); }); return { ...toRefs(state) }; }, }); </script> <style lang="scss" scoped> .el-aside { background-color: var(--el-color-white); box-shadow: var(--box-shadow); .el-menu { border-right: 0; background-color: var(--el-color-white); } } </style>
from django.db import models from garagem.models import Acessorio, Cor, Modelo from uploader.models import Image class Veiculo(models.Model): id = models.BigAutoField(primary_key=True) descricao = models.CharField(max_length=100) cor = models.ForeignKey(Cor, on_delete=models.PROTECT, related_name="veiculos") ano = models.IntegerField(null=True, default=0) preco = models.DecimalField(max_digits=10, decimal_places=2, null=True, default=0) modelo = models.ForeignKey(Modelo, on_delete=models.PROTECT, related_name="veiculos") acessorios = models.ManyToManyField(Acessorio, related_name="veiculos") capa = models.ManyToManyField( Image, related_name="+", ) def __str__(self): return f"{self.modelo} ({self.ano}), {self.cor}"
# Week 3: Introduction to React ## Thursday - Project Walkthrough: Personal Portfolio Website ### Instructor Guide --- ### Objective To build a personal portfolio website using React, showcasing various components that represent different sections like About, Projects, Skills, and Contact. ### Project Setup - **Task**: Initialize the React project. - **Instructions**: - Use `create-react-app` to bootstrap the portfolio project. - Create a new folder `portfolio` and navigate into it: ```bash npx create-react-app portfolio cd portfolio npm start ``` - Structure the project with components for each portfolio section. ### Building React Components - **About Component**: - Create an `About` component to display personal information. - **Code Snippet**: ```javascript function About() { return ( <div> <h2>About Me</h2> <p>Short bio or personal statement.</p> </div> ); } ``` - **Projects Component**: - Develop a `Projects` component to showcase project works. - Use state to manage project list. - **Code Snippet**: ```javascript function Projects() { const projects = [{ name: 'Project 1', description: 'Description...' }]; return ( <div> <h2>Projects</h2> {projects.map((project, index) => ( <div key={index}> <h3>{project.name}</h3> <p>{project.description}</p> </div> ))} </div> ); } ``` - **Skills and Contact Components**: - Similarly, create `Skills` and `Contact` components. ### Styling the Components - **Task**: Apply CSS to style each component. - **Instructions**: - Create separate CSS files for each component or use inline styling. - Focus on a clean and professional layout. - **Code Snippet (for example, in About.css)**: ```css .about { margin: 20px; padding: 20px; border: 1px solid #ddd; } ``` ### Assembling the Portfolio - **Task**: Assemble all components in the `App` component. - **Instructions**: - Import each section component into `App.js`. - Layout the components to form a complete portfolio. - **Code Snippet**: ```javascript import About from './About'; import Projects from './Projects'; // Import other components function App() { return ( <div> <About /> <Projects /> {/* Include other components */} </div> ); } ``` ### Adding Interactivity - **Optional Tasks**: - Implement a lightbox for project images. - Add a form in the Contact component with form handling. ### Testing and Debugging - **Task**: Test the portfolio website. - **Instructions**: - Ensure all components render correctly. - Check responsive design and fix any styling issues. --- This walkthrough provides a foundation for building a personal portfolio site with React, offering a practical application of React components, state management, and props.
require "rails_helper" feature "Editing a user" do let!(:admin_user) { FactoryGirl.create :admin_user } let!(:user) { FactoryGirl.create :user } before do sign_in_as! admin_user visit "/" click_link "Admin" click_link "Users" click_link user.email click_link "Edit User" end scenario "Updating a user's details" do fill_in "Email", with: "[email protected]" click_button "Update User" expect(page).to have_content("User has been updated.") within "#users" do expect(page).to have_content("[email protected]") expect(page).to_not have_content(user.email) end end scenario "Toggling user's admin ability" do check "Is an admin?" click_button "Update User" expect(page).to have_content("User has been updated.") within "#users" do expect(page).to have_content("#{user.email} (Admin)") end end end
import { ContactProps } from "@/pages/contact"; export const getMains = async () => { const response = await fetch("https://sabberdeveloper.hasura.app/v1/graphql", { method: "POST", headers: { "Content-Type": "application/json", "X-Hasura-Role": "public", }, body: JSON.stringify({ query: ` query GetPortfolio { portfolio(limit: 3, order_by: {id: desc}) { id content desc media title } } ` }), }); const json = await response.json(); return json?.data?.portfolio; }; export const getFoods = async () => { const response = await fetch("https://sabberdeveloper.hasura.app/v1/graphql", { method: "POST", headers: { "Content-Type": "application/json", "X-Hasura-Role": "public", }, body: JSON.stringify({ query: ` query GetFood { food { id media title } } ` }), }); const json = await response.json(); return json?.data?.food; }; export const getFoodsById = async (id: number) => { const response = await fetch("https://sabberdeveloper.hasura.app/v1/graphql", { method: "POST", headers: { "Content-Type": "application/json", "X-Hasura-Role": "public", }, body: JSON.stringify({ query: ` query GetFood($id: Int) { food(where: {id: {_eq: $id}}) { id desc title content ingredients recipes time media media1 created_at updated_at type } } `, variables: { id, }, }), }); const json = await response.json(); return json?.data?.food[0]; }; export const getArticles = async () => { const response = await fetch("https://sabberdeveloper.hasura.app/v1/graphql", { method: "POST", headers: { "Content-Type": "application/json", "X-Hasura-Role": "public", }, body: JSON.stringify({ query: ` query GetPortfolio { portfolio { id content desc media slug title } } ` }), }); const json = await response.json(); return json?.data?.portfolio; }; export const getَArticleById = async (id: number) => { const response = await fetch("https://sabberdeveloper.hasura.app/v1/graphql", { method: "POST", headers: { "Content-Type": "application/json", "X-Hasura-Role": "public", }, body: JSON.stringify({ query: ` query GetPortfolio($id: Int) { portfolio(where: {id: {_eq: $id}}) { id content content1 content2 content3 desc media media1 media2 slug title title1 title2 title3 } } `, variables: { id, }, }), }); const json = await response.json(); return json?.data?.portfolio[0]; }; export const postContact = async (data: ContactProps) => { const response = await fetch(`https://sabberdeveloper.hasura.app/v1/graphql`, { method: "POST", headers: { "Content-Type": "application/json", "X-Hasura-Role": "public", }, body: JSON.stringify({ query: ` mutation InsertMessage($name: String, $phone: String, $text: String) { insert_message(objects: {name: $name, phone: $phone, text: $text}) { affected_rows returning { id name phone text } } } `, variables: { name: data.name, phone: data.phone, text: data.text }, }), }); const json = await response.json(); return json; };
import React,{useEffect} from 'react' import { connect } from 'react-redux' import { getCourse } from '../../redux/actionCreators' import store from '../../redux/store' import Banner from '../Organisms/Banner' import {Link} from 'react-router-dom' const Course = ({course}) => { useEffect(()=>{ store.dispatch(getCourse(1)) },[]) return( <> { course && <> <Banner color='dark-color' title={course.name} subtitle={course.subtitle} image={{ src: course.picture, alt: course.name }} courseBanner poster={course.picture} especialidad={course.data.specialities[0].name} /> <main className="ed-grid lg-grid-10"> <div className="lg-cols-7"> <div className="course-features ed-grid lg-grid-3 s-border s-pxy-2 s-radius s-bg-white l-block s-shadow-bottom row-gap"> <div> <h3 className="t4">¿Qué aprenderás?</h3> <ul dangerouslySetInnerHTML={{__html: course.you_learn}}/> </div> <div> <h3 className="t4">Conocimientos previos</h3> <ul dangerouslySetInnerHTML={{__html: course.requirements}}/> </div> <div> <h3 className="t4">Nivel</h3> <p>{course.level}</p> </div> </div> <h2>Temario del curso</h2> <div className="s-border s-px-2 lg-pxy-4 s-radius s-bg-white l-block l-section s-shadow-bottom"> { course.data.classes.map(cl=>( <div className='course-class l-section' key={cl.class.id}> <h3>{cl.class.title}</h3> <p>{cl.class.description}</p> <ul className="data-list"> { cl.subjects.map(s=>( <li key={s.subject.id}><Link to={`/clase/${s.subject.id}`} className="color dark-color">{s.subject.title}</Link></li> )) } </ul> </div> )) } </div> </div> <div className="lg-cols-3"> <h2 className="t3">Profesor</h2> <p>Roberto Quintero</p> </div> </main> </> } </> )} const mapStateToProps = state =>({ course: state.courseReducer.course }) export default connect(mapStateToProps,{})(Course)
import { Scene, Vector3, Group, PlaneGeometry, TextureLoader, MeshBasicMaterial, Mesh, Raycaster, Object3D, Audio, Quaternion, AxesHelper, } from "three"; import { Tween, Easing } from "@tweenjs/tween.js"; import { EnemyModel } from "./enemy"; import PointerLockControls from "./utils/PointerLockControls"; import State from "./state"; import WeaponLoader, { weaponConfig } from "./utils/weaponLoader"; import BulletHoleMesh from "./utils/BulletHoleMesh"; import BulletStore from "./utils/BulletStore"; import AudioLoader from "./utils/AudioLoader"; class Weapon { model?: Group; group; swayingGroup; swayingAnimationFinished = true; swayingAnimation: Tween<Vector3> | null = null; isShooting = false; recoilGroup; recoilAnimation: Tween<{ x: number; y: number; z: number; rotation: number; }> | null = null; recoilAnimationFinished = true; swayingNewPosition = new Vector3(-0.005, 0.005, 0); swayingDuration = 1000; isMoving = false; isAiming = false; aimingStartAnimation: Tween<Vector3> | null = null; aimingEndAnimation: Tween<Vector3> | null = null; flashAnimation: Tween<{ opacity: number }> | null = null; flashMesh; currentIndex = 1; loader = new WeaponLoader(); bulletHole = new BulletHoleMesh("decal"); scene: Scene; audioLoader; aimElement; bulletRay; tipsElement; constructor(scene: Scene, controls: PointerLockControls) { this.audioLoader = new AudioLoader(controls); this.group = new Group(); this.swayingGroup = new Group(); this.recoilGroup = new Group(); this.scene = scene; BulletStore.init(); const texLoader = new TextureLoader(); const geometry = new PlaneGeometry(0.2, 0.2); const texture = texLoader.load("./img/flash_shoot.png"); const material = new MeshBasicMaterial({ map: texture, transparent: true, opacity: 0, }); this.flashMesh = new Mesh(geometry, material); this.flashMesh.rotateY(Math.PI); this.aimElement = document.getElementById("aim"); this.bulletRay = new Raycaster(new Vector3(), new Vector3(), 0, 100); this.tipsElement = document.getElementById("tips"); } load() { return new Promise(async (resolve) => { const weapons = await this.loader.load(); const defaultWeapon = weapons[weaponConfig[this.currentIndex].name]; this.model = defaultWeapon.model; // const axesHelper = new AxesHelper(150); // this.model.add(axesHelper); const flashPosition = defaultWeapon.config.flashPosition; this.flashMesh.position.set( flashPosition[0], flashPosition[1], flashPosition[2] ); this.recoilGroup.add(this.flashMesh); this.recoilGroup.add(this.model); this.swayingGroup.add(this.recoilGroup); this.group.add(this.swayingGroup); this.scene.add(this.group); await this.audioLoader.load("shooting", "./audio/single-shoot-ak47.wav"); await this.audioLoader.load("empty", "./audio/shoot-without-bullet.wav"); // this.initSwayingAnimation(); this.initRecoilAnimation(); this.initAimingAnimation(); this.initFlashAnimation(); resolve(1); }); } reload() { BulletStore.reload(); this.tipsElement!.innerHTML = ""; } findEnemyId = (model: Object3D): number => { if (model.name === "enemy") { return model.id; } if (model.parent) { return this.findEnemyId(model.parent); } return 0; }; beginAiming = () => { this.isAiming = true; this.aimElement?.classList.add("aiming"); // if (State.firstPerson) { // // this.swayingAnimation!.stop(); // this.aimingStartAnimation!.start(); // } }; endAiming = () => { this.isAiming = false; this.aimElement?.classList.remove("aiming"); // if (State.firstPerson) { // this.aimingEndAnimation!.start(); // } }; beginShooting = () => { this.isShooting = true; }; endShooting = () => { this.isShooting = false; }; generateRecoilPosition() { const amount = 0.01; return { x: -Math.random() * amount, y: Math.random() * amount, z: -Math.random() * amount, rotation: 7, }; } initFlashAnimation() { const currentFlash = { opacity: 0 }; this.flashAnimation = new Tween(currentFlash) .to({ opacity: 1 }, 40) .easing(Easing.Quadratic.Out) .onUpdate(() => { this.flashMesh.material.opacity = currentFlash.opacity; }) .onComplete(() => { this.flashMesh.material.opacity = 0; }); } initAimingAnimation() { const currentPosition = this.swayingGroup.position; const finalPosition = new Vector3(0.1, 0.05, 0); this.aimingStartAnimation = new Tween(currentPosition) .to(finalPosition, 200) .easing(Easing.Quadratic.Out); this.aimingEndAnimation = new Tween(finalPosition.clone()) .to(new Vector3(0, 0, 0), 200) .easing(Easing.Quadratic.Out) .onUpdate((position) => { this.swayingGroup.position.copy(position); }) .onComplete(() => { this.updateSwayingAnimation(); }); } initRecoilAnimation() { const currentPosition = { x: 0, y: 0, z: 0, rotation: 0 }; const newPosition = this.generateRecoilPosition(); const duration = 80; this.recoilAnimation = new Tween(currentPosition) .to(newPosition, duration) .easing(Easing.Quadratic.Out) .repeat(1) .yoyo(true) // .onUpdate(() => { // this.recoilGroup.rotation.x = // -(currentPosition.rotation * Math.PI) / 180; // this.recoilGroup.position.copy( // new Vector3(currentPosition.x, currentPosition.y, currentPosition.z) // ); // }) .onStart(() => { this.recoilAnimationFinished = false; }) .onComplete(() => { this.recoilAnimationFinished = true; }); } initSwayingAnimation() { const currentPosition = new Vector3(0, 0, 0); const initialPosition = new Vector3(0, 0, 0); const newPosition = this.swayingNewPosition; const duration = this.swayingDuration; this.swayingAnimation = new Tween(currentPosition) .to(newPosition, duration) .easing(Easing.Quadratic.Out) .onUpdate(() => { this.swayingGroup.position.copy(currentPosition); }); const swayingBackAnimation = new Tween(currentPosition) .to(initialPosition, duration) .easing(Easing.Quadratic.Out) .onUpdate(() => { this.swayingGroup.position.copy(currentPosition); }) .onComplete(() => { this.swayingAnimationFinished = true; }); this.swayingAnimation.chain(swayingBackAnimation); } updateSwayingAnimation() { if (!this.swayingAnimation || this.isAiming) { return; } this.swayingAnimation.stop(); this.swayingAnimationFinished = true; if (this.isMoving) { this.swayingDuration = 300; this.swayingNewPosition = new Vector3(-0.015, 0, 0); } else { this.swayingDuration = 1000; this.swayingNewPosition = new Vector3(-0.005, 0.005, 0); } this.initSwayingAnimation(); } switchWeapon(index: number) { if (index === this.currentIndex + 1) { return; } this.currentIndex = index - 1; this.recoilGroup.remove(this.model!); const weapon = this.loader.weapons[weaponConfig[this.currentIndex].name]; this.model = weapon.model; this.recoilGroup.add(this.model); const flashPosition = weapon.config.flashPosition; this.flashMesh.position.set( flashPosition[0], flashPosition[1], flashPosition[2] ); } bulletCollision(controls: PointerLockControls, enemyArray: EnemyModel[]) { this.bulletRay.set( controls.camera.getWorldPosition(new Vector3()), controls.getDirection() ); const intersectsEnemy = this.bulletRay.intersectObjects( enemyArray.map((item) => item.model.model!) ); if (intersectsEnemy.length > 0) { // shoot enemy const id = this.findEnemyId(intersectsEnemy[0].object); const enemy = enemyArray.find((item) => item.id === id); enemy?.model.getShot(); } else { const intersectsWorld = this.bulletRay.intersectObjects( State.worldMapMeshes, false ); if (intersectsWorld.length > 0) { // 击中world this.bulletHole.create(intersectsWorld[0], this.scene!); } } } render( controls: PointerLockControls, enemyArray: EnemyModel[], moveVelocity: Vector3, rightHand: Object3D ) { if (this.model) { // if (!this.isMoving && moveVelocity.length() > 0) { // this.isMoving = true; // this.updateSwayingAnimation(); // } else if (this.isMoving && moveVelocity.length() === 0) { // this.isMoving = false; // this.updateSwayingAnimation(); // } // if (this.swayingAnimation && this.swayingAnimationFinished) { // this.swayingAnimationFinished = false; // this.swayingAnimation.start(); // } if (this.isShooting && this.recoilAnimationFinished) { if (BulletStore.count === 0) { this.audioLoader.play("empty"); this.tipsElement!.innerText = "按 R 键更换弹夹"; } else { this.audioLoader.play("shooting"); BulletStore.decrease(); this.recoilAnimation!.start(); this.flashAnimation!.start(); this.bulletCollision(controls, enemyArray); } } const handPosition = new Vector3(); const handQuaternion = new Quaternion(); rightHand.getWorldPosition(handPosition); rightHand.getWorldQuaternion(handQuaternion); // this.group.rotation.copy(controls.cameraGroup.rotation); this.group.position.copy(handPosition); // 枪跟随手(tps) this.group.quaternion.copy(handQuaternion); this.group.rotateX(-Math.PI / 2).rotateZ(-Math.PI / 2); } } } export default Weapon;
import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { UserEntity } from 'src/entities'; import { UserService } from 'src/modules/user/user.service'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private readonly userService: UserService, private readonly config: ConfigService, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: config.get('JWT_SECRET'), }); } async validate(payload: any): Promise<UserEntity> { Logger.log('Validate JwtStrategy init'); const { sub: id } = payload; return await this.userService.getUserById(id); } }
import * as fs from 'fs'; import * as process from 'process'; import lodash from 'lodash'; // let schedule1 = process.env.SCHEDULE1; let schedule2 = process.env.SCHEDULE2; let currentPath = process.cwd() let filePath = currentPath + '/' + process.env.SCHEDULE_FILE; filePath export interface Schedule { requestId: string; took: number; RateLimitState: string; RateLimitReason: string; RateLimitPeriod: string; RetryCount: number; _parent: Parent; description: string; ownerTeam: BaseTimeline; startDate: string; endDate: string; finalTimeline: FinalTimeline; baseTimeline: BaseTimeline; overrideTimeline: BaseTimeline; forwardingTimeline: BaseTimeline; } export interface Parent { id: string; name: string; enabled: boolean; } export interface BaseTimeline { } export interface FinalTimeline { rotations: Rotation[]; } export interface Rotation { id: string; name: string; order: number; periods: Period[]; } export interface Period { startDate: string; endDate: string; type: PeriodType; recipient: Recipient; } export interface Recipient { type: RecipientType; name: string; id: string; username: string; } export enum RecipientType { User = "user", } export enum PeriodType { Historical = "historical", } export interface CoveredPeriod { startDate: Date endDate: Date dayRate: number engineer: string dayOfWeek: string duration: number } function timeConvert(n: number): number { var num = n; var hours = (num / 60); var rhours = Math.floor(hours); var minutes = (hours - rhours) * 60; var rminutes = Math.round(minutes); //return num + " minutes = " + rhours + " hour(s) and " + rminutes + " minute(s)."; return hours } function loadSchedule(filePath: string): Schedule { const file = fs.readFileSync(filePath, 'utf8'); return JSON.parse(file); } function saveRate(filePath: string, data: string) { fs.writeFileSync(filePath, data); } let schedule = loadSchedule(filePath) schedule // extract rotations let rotations = schedule.finalTimeline.rotations //filter out required schedules let filtered = rotations.filter((r) => r.name === schedule1 || r.name === schedule2) filtered // merge two schedules together let periods: Array<Period> = [].concat(filtered[0].periods, filtered[1].periods) //periods let len = periods.length len const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] let covered: Array<CoveredPeriod> = [] periods.map((p) => { let startDate = Date.parse(p.startDate) let endDate = Date.parse(p.endDate) let dayOfWeek = days[new Date(startDate).getDay()] let duration = timeConvert((endDate - startDate) / 1000 / 60) let rate = 0 let endDay = new Date(Date.parse(p.endDate)).getDay() let startDay = new Date(Date.parse(p.startDate)).getDay() let dateDiff = Math.abs((endDay + 1) - (startDay + 1)) dateDiff if (dateDiff == 0) { // if less than 8am it's classed as overnight if (new Date(startDate).getHours() < 8) { rate = 1 } } else { // if diff is 1 it's classed as overnight if (dateDiff == 1) { rate = 1 } else { let date = new Date(startDate) for (let i = 0; i < dateDiff; i++) { // saturday and sunday if (date.getDay() === 0 || date.getDay() === 6) { rate+=2 } else { rate+=1 } date.setDate(date.getDate() + i) } } } let dayRate = rate let cover: CoveredPeriod = { startDate: new Date(startDate), endDate: new Date(endDate), dayRate: dayRate, engineer: p.recipient.name, dayOfWeek: dayOfWeek, duration: duration } covered.push(cover) }) covered var result = covered.reduce(function(r, e) { let s = { rates: 0, ranges: [] } if (r[e.engineer]) { s = r[e.engineer] } s.rates += e.dayRate s.ranges.push({ startDate: e.startDate, endDate: e.endDate, dayOfWeek: e.dayOfWeek }) r[e.engineer] = s; return r; }, {}); //result // stringify json pretty let aggregated = JSON.stringify(result, null, 2) console.log(aggregated) saveRate(currentPath + '/rates.json', aggregated)
--- title: In 2024, How to Change Lock Screen Wallpaper on Nubia Z50 Ultra date: 2024-05-19T09:20:27.485Z updated: 2024-05-20T09:20:27.485Z tags: - unlock - remove screen lock categories: - android description: This article describes How to Change Lock Screen Wallpaper on Nubia Z50 Ultra excerpt: This article describes How to Change Lock Screen Wallpaper on Nubia Z50 Ultra keywords: Nubia Z50 Ultra unlock with google assistant,unlock android phone password without factory reset,pattern unlock without password,Nubia Z50 Ultra lock screen wallpaper on android,Nubia Z50 Ultra android emergency call bypass,Nubia Z50 Ultra best sim location trackers,Nubia Z50 Ultra unlock bootloader,forgot pattern lock,how to use oem unlocking,forgot android password,Nubia Z50 Ultra fingerprint not working,Nubia Z50 Ultra android password reset thumbnail: https://www.lifewire.com/thmb/xk4sG4I9EUDVvTCEXSRMmg2yPjw=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/superbowl_dmytroAksonov_Getty-5a775189119fa8003752b313.jpg --- ## How to Change Lock Screen Wallpaper on Nubia Z50 Ultra Every smartphone user wants their lock screen wallpapers to be the finest quality. Since the Nubia Z50 Ultra device comes with a generic lock screen wallpaper on itself, changing it is necessary. Regardless of your Android device, the need to change the ****lock screen wallpaper on Android**** is significant. If so, the article will provide two diverse techniques familiar to any Android device. Along with the basic methods, the article will redirect its discussion to changing the lock screen wallpaper for different brands. Find more about ****how to change the lock screen wallpaper on Android**** with the available methods and techniques to bring aesthetics to your device. ## Part 1: How To Change Lock Screen Picture on Android Phone With 2 Common Methods Every Android smartphone has its interface to follow while changing the lock screen wallpaper or screen saver of the Nubia Z50 Ultra device. However, before we dive into the Nubia Z50 Ultra device-specific details, let's dissect the two common methods to change ****the lock screen wallpaper on Android:**** ### Method 1: Pressing Home Screen Method The first thing to try for changing the lock screen wallpaper includes the long press technique. This technique is available for almost all Android devices, a basic approach to changing lock screen wallpapers. To know how it is done, follow the steps provided below: ****Step 1:**** As you unlock your Android smartphone, press the clear region until the home-screen options appear on the front. ****Step 2:**** Select the “Wallpaper” option in the available buttons to lead to another window showing different wallpapers. ![tap on wallpaper icon](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-1.jpg) ****Step 3:**** Out of all the wallpapers, select any of them and tap on the “Apply” button to set it as your lock screen wallpaper. ![select the required wallpaper](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-2.jpg) ### Method 2: Using Your Gallery You can also set your favorite picture as the ****Android lock screen wallpaper**** from the settings provided in your gallery. To know how you can utilize your device’s Gallery, look into the steps provided next: ****Step 1:**** Access the menu of your Android device and locate the “Gallery” app in the available options. Continue to locate your respective photo in the “Albums.” ![access the gallery](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-3.jpg) ****Image name: lock-screen-wallpaper-on-android-3.jpg**** ****Image alt: access the gallery**** ****Step 2:**** Choose and open the image on the screen, and continue to select the “Three-Dotted” icon on the bottom-right of the screen. ![tap on three dots](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-4.jpg) ****Step 3:**** On selecting the option of “Set as wallpaper,” you will apply the particular image from the Gallery as your lock screen wallpaper. ![choose set as wallpaper option](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-5.jpg) ## Part 2: How to Change Lock Screen Wallpaper on Different Brands of Android Phones The provided methods in the above part are comprehensive in changing the lock screen wallpaper of any Android smartphone. This, however, is not the same and is true for every Android device in the market. Since the difference in operation brings a clash for many users, the need for an idea for different smartphone brands is essential. For this part, we will bring a guide explaining ****how to change the lock screen wallpaper on Android**** of different brands: ### For Samsung Users ****Step 1:**** On unlocking your Samsung, hold the empty space on your home screen to open a set of options. Select "Wallpapers" from the available list and continue to the next screen. ![tap on wallpaper icon](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-6.jpg) ****Step 2:**** Choose the option of “My wallpapers” or “Gallery” from the available list and select the wallpaper of your choice. As you select one, you will have to set it as your “Home screen,” “Lock screen,” or wallpaper for both screens. ![select the option for wallpaper](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-7.jpg) ****Step 3:**** Once you observe the image on the preview window, tap on the button on the bottom to set it as your lock screen wallpaper. ![apply the wallpaper](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-8.jpg) ****Step 1:**** As you access the home screen of your Google Pixel, continue to hold the space. This will open a list of options where you must tap on "Wallpaper & style." Continue to select the "Change wallpaper" option to bring new colors to your Google Pixel. ![tap on change wallpaper](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-9.jpg) ****Step 2:**** On the next screen, select any particular category you want to set the lock screen wallpaper. For instance, if you selected "My photos," choose your image and preview it on the following screen. ![choose your favorite wallpaper](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-10.jpg) ****Step 3:**** To proceed, specify where you wish to set it as your wallpaper. As the options appear on the front, select the "Lock screen" option and continue to set your wallpaper. ![select the lock screen option](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-11.jpg) ### For Motorola Users ****Step 1:**** Lead into the “Settings” of your Motorola device and look for the “Wallpaper & style” option in the list. ![tap on wallpaper and style](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-12.jpg) ****Step 2:**** Select any options appearing on the next screen that defines the location from where you will add the new wallpaper. Selecting a particular wallpaper from the available options leads to the "Preview" screen. ![select wallapaper source option](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-13.jpg) ****Step 3:**** Continue to select the "Lock Screen" option on the preview screen and tap on the "Tick" icon at the bottom. To confirm, tap "Lock screen" to change the wallpaper on the lock screen of your Motorola. ![confirm the lock screen wallpaper](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-14.jpg) ****Step 1:**** Launch the “Settings” application on your OnePlus smartphone and continue to the “Personalizations” option. ![choose personalization option](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-15.jpg) ****Step 2:**** On the next screen, continue to the "Wallpapers" section and go through the available media to select a new wallpaper. ![select the wallpapers option](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-16.jpg) ****Step 3:**** As you select a particular wallpaper and continue to the preview screen, select the “Apply” button and proceed to choose “Lock Screen” from the pop-up menu. ![tap on lock screen option](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-17.jpg) ## Part 3: Top 10 Download Sites About Cool Screen Wallpaper on Android What if you feel that you do not have the coolest screen wallpaper that you can change on your Android device? Before changing your ****Android lock screen wallpaper**** on your device, find a unique option that can be easily replaced. Instead of limiting yourselves to the options available on the Nubia Z50 Ultra device, you can consider moving to different download sites for downloading the coolest lock screen wallpaper: ### 1. [<u>Zedge</u>](https://www.zedge.net/wallpapers) Zedge is one of the most premium websites for accessing wallpapers for Android devices. With accessibility to content from exclusive artists, Zedge presents the best personalization options to its users. For effective wallpaper creation, you can add your creativity to bring in the best results for your device. ![zedge android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-18.jpg) ### 2. [<u>Interfacelift</u>](https://interfacelift.com/wallpaper/downloads/downloads/any/) For exclusive access to free wallpapers of multiple categories, Interfacelift provides some impressive and high-quality results. This intuitive wallpaper site provides some captivating options. Along with that, it asserts a special force on photographs of landscapes, which makes it a great site. ![interfacelift android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-19.jpg) ### 3. [<u>Unsplash</u>](https://unsplash.com/s/photos/Android-wallpapers) Known for keeping royalty-free, high-quality content, Unsplash can be a great Android wallpaper site. Download your favorite wallpapers that will perfectly suit your Android device. Along with its smooth interface, Unsplash offers diversity with its dedicated Unsplash+ plan. ![unsplash android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-20.jpg) ### 4. [<u>Mobile9</u>](https://www.mobile9.com/) For variety, you can always go for Mobile9. This unique, expressive, and productive wallpaper site provides the best Android wallpapers. Following this, it offers multiple diversity of content, including ringtones and books. However, to get your hands on the finest quality wallpaper, do consider trying the site. ![mobile9 android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-21.jpg) ### 5. [<u>Dribbble</u>](https://dribbble.com/) If you seek the best design for your Android lock screen, Dribbble provides the finest quality. Out of the 10,000+ designs, you can find your choice. Along with that, the site service also presents the wallpapers in dedicated categories. Searching for the right ****Android lock screen wallpaper**** gets easy in such an environment. ![dribbble android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-22.jpg) ### 6\. [<u>Wallpapers.com</u>](https://wallpapers.com/android) For a service that provides dedicated Android lock screen wallpapers, Wallpapers.com holds a good position. With the finest wallpapers to use on the Android device, you can also customize the available wallpapers. Dedicated categories make it easy for users to select their favorite wallpaper from the 1000+ options. ![wallpapers.com android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-23.jpg) ### 7\. [<u>Pexels</u>](https://www.pexels.com/search/android%20wallpaper/) There are very few websites that offer the finest quality wallpapers for free. Pexels, being one of them, displays a great interface for users with sub-categorization. With descriptions for every wallpaper, you can select the best one for your device. Find a categorized section of more than 70,000 wallpapers on this platform. ![pexels android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-24.jpg) ### 8\. [<u>Pixabay</u>](https://pixabay.com/images/search/android%20wallpaper/?manual_search=1) Who won’t have heard of Pixabay as a haven for lock screen wallpapers? This platform provides a different perspective on wallpaper search. To find the best option, you can diversify your search according to orientation, size, and color. This makes your search much easier and swift for changing the Android lock screen. ![pixabay android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-25.jpg) ### 9\. [<u>500px</u>](https://500px.com/) To access the best wallpapers in the world, 500px is a good platform to keep in mind. While it helps a wide community fulfill their tasks, it can be a purposeful option. For diverse operability in the site, users can also sell their work into a global marketplace. ![500px android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-26.jpg) ### 10\. [<u>Wallpaperswide</u>](http://wallpaperswide.com/) From desktop to Android wallpapers, Wallpaperswide holds a diverse set of options. This platform is designed to provide a diversity of categories to its users. With a simple interface, it is a great option for gathering content. ![wallpaperswide android wallpapers](https://images.wondershare.com/drfone/article/2023/03/lock-screen-wallpaper-on-android-27.jpg) ## Bonus Part: How To Unlock Android Screen if Forgotten the Password Although you have learned ****how to change the lock screen wallpaper on Android,**** multiple complications can arise. One such problem that can occur on your device involves it getting locked. If the Nubia Z50 Ultra device gets locked, you cannot use it. For an Android whose password is locked, you will require a platform to amend the problem. [<u>Dr.Fone – Screen Unlock (Android)</u>](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) provides a complete platform to unlock the Android device. This is the right place to go if you seek to remove such locks from your device within minutes. With the option of bypassing any screen lock, it can protect your device's data. Such options make it the finest platform to resolve issues with the Android device. To know how one can unlock their Android device with Dr.Fone, look through the provided steps: ****Step 1: Open Screen Unlock Tool**** You need to download and launch Dr.Fone on your computer and continue to the “Screen Unlock” tool. On accessing the tool, connect your Android device with a cable. ![choose the screen unlock tool](https://images.wondershare.com/drfone/guide/drfone-home.png) ****Step 2: Start Unlocking the Android**** Proceed to select the "Unlock Android Screen/FRP" option and continue into the "Unlock Android Screen" option. ![proceed with unlock android screen](https://images.wondershare.com/drfone/guide/android-screen-unlock-3.png) ****Step 3: Select Mode and Device Details**** If you intend not to lose data, continue to the "Remove without data loss" option. You will have to select the details of the connected Android device. ![select the unlock mode](https://images.wondershare.com/drfone/guide/screen-unlock-any-android-device-1.png) ****Step 4: Access Download Mode**** Put your Android device in Download Mode by powering it off. Continue to press the "Volume Down," "Home," and "Power" buttons simultaneously. After a few seconds, press the "Volume Up" button to enter the Download Mode. ![activate the download mode](https://images.wondershare.com/drfone/guide/android-screen-unlock-without-data-loss-4.png) ****Step 5: Unlock Android Successfully**** The package starts downloading as the Nubia Z50 Ultra device gets into Download Mode. It will take a while until it completes. Once the download process gets completed, press the “Remove Now” button to remove the Android screen lock. ![start removing screen lock](https://images.wondershare.com/drfone/guide/android-unlock-07.png) ****Image name: lock-screen-wallpaper-on-android-32.jpg**** ****Image link:**** [<u>https://images.wondershare.com/drfone/guide/android-unlock-07.png</u>](https://images.wondershare.com/drfone/guide/android-unlock-07.png) ****Image alt: start removing screen lock**** ## Conclusion The details provided are comprehensive in helping you change ****the lockscreen wallpaper on Android****. While learning unique ways, along with dedicated techniques for smartphones, we are sure that you are clear about how to change lock screen picture on Android phone.Why not take a try now? This article has also introduced some of the best sites to download Android wallpapers. For effective results and to save your locked device from getting useless, use Dr.Fone – Screen Unlock. ## 10 Easy-to-Use FRP Bypass Tools for Unlocking Google Accounts On Nubia Z50 Ultra FRP, popularly known as the Factory Reset Protection program, is an additional data protection feature for all Android users. As per the FRP feature, in any unfortunate event wherein you lose the Nubia Z50 Ultra device or if any unauthorized person tries to reset it, the Nubia Z50 Ultra device will require the Google Account ID and password to be fed in. So, this program is designed to curb the chances of theft and other fraudulent activities. However, it was found that the FRP feature comes out as trouble for those who somehow forget their Google Account ID/ password, or who have purchased a second-hand phone either online or via some third-party source. Hence, it is important to know how to bypass a Google Account. Below mentioned are the Top 10 FRP tools to bypass Google accounts. ## Tool 1: Android FRP Bypass Helper - Dr.Fone - Screen Unlock (Android OS 2.1 or later) Dr.Fone - Screen Unlock can help you bypass your Google account and enter into your device's home screen with ease. No matter whether you can't get the Google account from previous sellers, or just forgot the PIN. In just 5 minutes, your Google FRP lock can be removed. <iframe allowfullscreen="allowfullscreen" frameborder="0" src="https://www.youtube.com/embed/MU8fYmLJBXg" id="video-iframe-t"></iframe> ![Safe download](https://mobiletrans.wondershare.com/images/security.svg)safe & secure ### Features - Available for Samsung/Xiaomi/Readmi/OPPO/Realme/Vivo devices. - It provides a useful guide. - Dr.Fone - Screen Unlock can reactivate the lock removers **Price**: $39.95/year, Go and check [Dr.Fone –Screen Unlock.](https://download.wondershare.com/drfone_unlock_full3372.exe) **Pros**: - a. Easy to use with detailed guide including video guide. - b. Only need a few minutes to complete. - c. It is also useful for users who do not know their mobile phone model. - d. It is safe and convenient. **Cons**: A little pricey, but worth it. You can easily download it from Dr.Fone's official website within one minute and use it with our detailed instructions. Even if you don't know the specific model of your Samsung device, Dr.Fone - Screen Unlock will provide you with quality service and assistance. Check [the bypass FRP lock guide](https://drfone.wondershare.com/guide/google-frp-bypass.html) in detail to help you disable your Google account on your Android smartphone. ### [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) Bypass Android FRP Lock without Google Account or a PIN Code. - It is helpful even though you don't know the OS version of your Samsung. - Only remove the lock screen, no data loss at all. - No tech knowledge asked, everybody, can handle it. - Work also for Xiaomi, Redmi, Oppo, Realme, Vivo devices. **4,926,978** people have downloaded it ## Tool 2: Samsung Reactivation/FRP Lock Removal Service [Samsung Reactivation/FRP unlocking service](http://directunlocks.com/lock-protection.php?aff=wondershare) can solve your FRP issue through an online service. With this, you only need to enter your phone details to get the unique user ID and password. The staff will contact and help you to bypass the Google FRP lock on your Samsung devices within 24-72 hours. ![frp bypass tools-samsung-frp-lock-removal](https://images.wondershare.com/drfone/article/2018/03/samsung-frp-lock-removal.jpg "Tool 2") ### Features - Unlock most Samsung FRP locks, not limited to the version of Android. - Huaman service only, solve the problem with the help of staff.  Go and check  [Samsung Reactivation/FRP unlocking service](http://directunlocks.com/lock-protection.php?aff=wondershare) **Pros**: - It provides online service - no confusing video tutorials and no risky software to download. - No tech knowledge is required. Everybody can handle it. - Issues will be solved within 24-72 hours. **Cons**: - It supports Samsung phones only now. - It takes a long time to wait. ## Tool 3: FRP/Google Account Bypass and Flashing Tool One of the best tools that cover almost all the latest versions of Android phones. This tool is quite easy to use. ![frp bypass tools-Tool 4](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-4.jpg "Tool 4") ### Features - Works for Samsung, HTC, MTK, MI, QUALCOMM, SPD, and many more devices. - This tool is for all the latest device versions. - The old version of SP Flash is also covered by this tool.  Go and check  [FRP/Google Account Bypass and Flashing Tool](http://devoloperxda.blogspot.in/2017/05/a-new-frpgoogle-account-bypass-and.html) **Price**: Free **Pros**: Work for almost all the versions of Android phones. **Cons**: Currently not tested with Android versions 5.1.1 and 6.0.1. ## Tool 4: FRP Bypass Solutions FRP Bypass Solutions is tested and updated for the process of bypassing Google verification if you forget the credentials of your account. ![frp bypass tools-Tool 5](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-5.jpg "Tool 5") ### Features - It works with all Android devices such as Moto series, LG, ZTE, HUAWEI, Vodafone, Samsung, Lenovo, HISENSE, XPERIA, and lots more. - It covers the latest versions and the team keeps it updated. - It is a useful tool for Samsung Galaxy S8.  Go and check  [FRP Bypass Solutions](https://www.cashsite.tk/) **Price**: $7.00 **Pros**: The tool has been tested and verified to work for Android 7.0 and 7.1. **Cons**: You need to purchase the tool to use all its features. ## Tool 5: D&G Password Unlocker D&G unlocker tool assists you in step by step and comprehensive way to unlock your Android phones. It can help Android users to remove FRP restrictions from their mobiles and tablets in a few seconds. The program will work for major brands including Samsung, Lenovo, Motorola, Xiaomi, Huawei, HTC, and Yuphoria. ![frp bypass tools-Tool 6](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-6.jpg "Tool 6") ### Features - It is compatible with Windows 7, 8, 10, XP, and Vista. - It supports Samsung, Motorola, Huawei, HTC, Lenovo, Xiaomi, and Euphoria.  Go and check  [D&G Password Unlocker](http://www.freemobiletools.com/2017/04/d-password-unlocker-tools-all-frp.html) **Price**: Free **Pros**: Provides free setup for Windows. **Cons**: There are no details available for LG devices. ## Tool 6: Pangu FRP Bypass tool for Remove 2017 The processing time is just about 10 minutes. This facility is for the Authorized Google account owner. With this tool, the FRP lock will get removed. ![frp bypass tools-Tool 7](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-7.jpg "Tool 7") ### Features - This tool works for All Samsung, Motorola, Micromax, Lenovo, MTK, and SPD devices. -  Lollipop 5.1, Marshmallow 6.1, Nougat 7.0 and 7.1.2, and Oreo 8.0.  Go and check  [D&G Password Unlocker](http://pangu.in/bypass-samsung-google-account-verification-reset-remove-frp-lock) **Price**: Free **Pros**: Works well with all Samsung and other devices. **Cons**: The tool requires you to use an OTG cable with a pen drive or a computer. ## Tool 7: FRP lock Google Verification Bypass Tool Software This is a kind of software program that is innovative and through this unlocker tool, additional protection for the Android devices can get bypassed. ![frp bypass tools-Tool 8](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-8.jpg "Tool 8") ### Features It works for HTC, Samsung devices, Motorola, Huawei, Lenovo, OPPO, LG, Alcatel, Xiaomi, Sony, and other Android devices.  Go and check  [FRP lock Google Verification Bypass](http://www.allmobitools.com/2016/11/frp-lock-google-verification-bypass.html) **Price**: Free Pros: - Works well for almost all Android devices and unblocks any Android phone with a Reactivation Lock error. - It is 100% free. - Also, it works for higher Android versions from 5.1.1 – 6.0 to 7.1. **Cons**: To Apply this method you need a Wi-Fi connection or a micro USB cable. ## Tool 8: Samsung FRP Helper V.0.2 FRP Removal Tools Samsung FRP tool uses the ADB feature to Bypass the FRP verification process. ![frp bypass tools-Tool 9](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-9.jpg "Tool 9") ### Features - This tool has an easy and interactive GUI. - It comes with a detailed guide.  Go and check  [Samsung FRP Helper V.0.2 FRP Removal](http://www.gsmfavor.com/2017/01/samsung-frp-helper-v02-frp-removal.html) **Price**: Free **Pros**: Easy to use and comes with a guide. **Cons**: - It does not work with other models besides Samsung. - Combination firmware is required to run this software. ## Tool 9: GSM Flasher ADB Bypass FRP Tool GSM flasher uses an easy and accessible way to bypass an Android device's lock through a USB cable. The downloading, as well as the complete setup, takes a few minutes. Also, ADB (Android debug bridge) helps you to have to communicate with your device. ![frp bypass tools-Tool 10](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-10.jpg "Tool 10") ### Features - a. GSM flasher software setup is easy to use. - It works with all OS types. - A pattern lock removal facility is also available. - This file can be used for the reactivation of lock removers.  Go and check  [GSM Flasher ADB Bypass FRP](http://www.allflashfiles.net/2017/06/gsm-flasher-adb-bypass-frp-latest-setup.html) **Price**: Free **Pros**: It can be used for all types of Android devices. **Cons**: Can also act as a reactivator for lock removers. ## Tool 10: FRP Bypass APK Download Samsung for Android FRP Bypass helps to overcome the security feature of the Nubia Z50 Ultra device so that you can easily bypass the Google Account verification process. As per user ratings, FRP Bypass APK has 4.1 Stars. ![frp bypass tools-Tool 3](https://images.wondershare.com/drfone/article/2017/07/factory-reset-protection-5-3.jpg "Tool 3") ### Features - A useful tool for Samsung Galaxy devices. - Download and use it for free. - You can also share this tool with your friends and family.  Go and check  [FRP Bypass APK Download Samsung for Android](https://apkoftheday.co/frp-bypass-apk-download/) **Price**: Free **Pros**: If you have forgotten your Google Account ID/ password, this tool will come in handy. **Cons**: - You cannot access this tool directly through the local market or resources. - Play Store users cannot access this tool. ## The Comparison of the 10 FRP Bypass Tools | **Bypass FRP Tools** | **Unique Feature** | **Price** | **Cons** | | --- | --- | --- | --- | | [Dr.Fone - Screen Unlock](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/)![hot icon](https://images.wondershare.com/drfone/article/2022/05/hot-tip.png) | Bypass most Android FRP remotely | $39.95 per year for 1-5 mobile devices | Only available for Samsung/Xiaomi/Readmi/OPPO/Realme/Vivo at present | | Samsung Online Removal Service | Huaman service only, solve the problem with the help of staff | $15-$50 per time for 1 device | It takes a long time to wait | | FRP/Google Account Bypass and Flashing | Works for Samsung, HTC, MTK, MI, QUALCOMM, SPD, and many more devices | Free | Currently not tested with Android versions 5.1.1 and 6.0.1, and not always functional. | | FRP Bypass Solutions | Works with all Android devices such as Moto series, LG, ZTE, HUAWEI, Vodafone, Samsung, Lenovo, HISENSE, XPERIA, etc. | $7 | You need to purchase the tool to use all its features | | D&G Password Unlocker | Compatible with Windows 7, 8, 10, XP, and Vista | Free | Unavailable for LG devices | | Pangu FRP Bypass tool for Remove 2017 | Lollipop 5.1, Marshmallow 6.1, Nougat 7.0 and 7.1.2, and Oreo 8.0. | Free | Requires you to use an OTG cable with a pen drive or a computer. | | FRP lock Google Verification Bypass Tool Software | Additional protection for Android devices can get bypassed. | Free | A Wi-Fi connection or a micro USB cable is needed | | Samsung FRP Helper V.0.2 FRP Removal Tools | With an easy and interactive Guide. | Free | Combination firmware is required to run this software | | GSM Flasher ADB Bypass FRP Tool | Works with all OS types | Free | Can also act as a reactivator for lock removers | | FRP Bypass APK Download Samsung for Android | Effective on Samsung devices | Free | Play Store users cannot access this tool | ## The Bottom Line The article above gives useful information on some of the important tools for the FRP bypass process. The information available is to assist the original users only who have somehow forgotten their user GoogleID/password. We hope that using any of the above methods will definitely resolve your FRP bypass issue with ease. If you also want to bypass the iCloud activation lock, Dr.Fone is of help. ## 6 Solutions to Unlock Nubia Phones If You Forgot Password, PIN, Pattern Too many times, we forget the passcode of our smartphones, only to regret it later. Don't worry if you are facing the same issue. It happens to all of us at times. Fortunately, there are many ways to unlock an Android device even when you have **forgotten its password/pin/pattern lock**. This guide will teach you how to unlock Nubia phones if you forgot the password in five different ways. Read on and choose your preferred option if you forgot the password on your Nubia phone and move past every setback you face. <iframe width="560" height="315" src="https://www.youtube.com/embed/68FqgS6Ym8E" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="allowfullscreen"></iframe> ## Solution 1: Unlock Nubia Phone using Dr.Fone - Screen Unlock (5 mins solution) Among all the solutions we are going to introduce in this article, this is the easiest one. [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) can help you remove the lock screen of [some Nubia and Samsung devices](https://drfone.wondershare.com/reference/android-lock-screen-removal.html) without any data loss. After the lock screen is removed, the phone will work like it's never been locked before, and all your data are there. Besides, you can use this tool to bypass the passcode on other Android phones, such as Huawei, Lenovo, Oneplus, etc. The only defect of Dr.Fone is that it will erase all the data beyond Samsung and Nubia after unlocking. ![arrow](https://drfone.wondershare.com/style/images/arrow_up.png) ### [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) Get into the Locked Nubia Phone within Minutes - Available for most Nubia series, like LG/LG2/LG3/G4, etc. - Except for Nubia phones, it unlocks 20,000+ models of Android phones & tablets. - Everybody can handle it without any technical background. - Offer customized removal solutions to promise good success rate. **4,008,669** people have downloaded it ### How to unlock an Nubia phone with Dr.Fone - Screen Unlock (Android)? Step 1. Launch Dr.Fone. Download Dr.Fone from the download buttons above. Install and launch it on your computer. Then select the "**Screen Unlock**" function. ![unlock lg phone - launch drfone](https://images.wondershare.com/drfone/guide/drfone-home.png) Step 2. Connect your phone. Connect your Nubia phone to the computer using a USB cable. Click on **Unlock Android Screen** on Dr.Fone. ![unlock lg phone - connect phone](https://images.wondershare.com/drfone/guide/android-screen-unlock-3.png) Step 3. Select the phone model. Currently, Dr.Fone supports removing lock screens on some Nubia and Samsung devices without data loss. Select the correct phone model information from the dropdown list. ![unlock lg phone - select phone model](https://images.wondershare.com/drfone/guide/screen-unlock-any-android-device-2.png) Step 4. Boot the phone in download mode. - Disconnect your Nubia phone and power it off. - Press the Power Up button. While you are holding the Power Up button, plug in the USB cable. - Keep pressing the Power Up button until the Download Mode appears. ![unlock lg phone - boot in download mode](https://images.wondershare.com/drfone/guide/android-screen-unlock-without-data-loss-4.png) Step 5. Remove the lock screen. After your phone boot in download mode, click on Remove to start to remove the lock screen. This process only takes a few minutes. Then your phone will restart in normal mode without any lock screen. ![unlock lg phone - remove lock screen](https://images.wondershare.com/drfone/guide/screen-unlock-any-android-device-6.png) For more detailed steps, please go to our guide on [unlocking Android phones with/without data loss](https://drfone.wondershare.com/guide/android-lock-screen-removal.html). ## Solution 2: Unlock the Nubia Phone Using Android Device Manager (Need a Google account) This is probably the most convenient solution to set up a new lock for your Nubia device. With Android Device Manager, you can locate your device, ring it, erase its data, and even change its lock remotely. All you got to do is log in to the Nubia Z50 Ultra device Manager account using the credentials of your Google Account. Needless to say, your Nubia phone should be linked to your Google Account. Learn how to unlock the Nubia phone if forgot your password using Android Device Manager. - **Step 1.** Start by logging in to [Android Device Manager](https://www.google.co.in/android/devicemanager) by entering the credentials of your respective Google Account that is configured with your phone. ![unlock lg forgot password - login android device manager](https://images.wondershare.com/drfone/article/2017/03/14892201986480.jpg) - **Step 2.** Select your device's icon to get access to various features like ring, lock, erase, and more. Out of all the provided options, click on “**lock**” to change the security lock of your device. ![unlock lg forgot password - select device](https://images.wondershare.com/drfone/article/2017/03/14892202439511.jpg) - **Step 3.** Now, a new pop-up window will open. Here, provide the new password for your device, confirm it, and click on the “lock” button again to save these changes. ![unlock lg forgot password - lock with new password](https://images.wondershare.com/drfone/article/2017/03/14892202692339.jpg) That's it! Your phone will reset its password, and you would be able to move past any problem related to forgetting the password on the Nubia phone using [Android Device Manager unlock](https://drfone.wondershare.com/unlock/android-device-manager-unlock.html). ## Solution 3: Unlock the Nubia Phone Using Google Login (only Android 4.4 and below) If your Nubia device runs on Android 4.4 and previous versions, then you can easily move past the password/pattern lock without any trouble. The provision is not available on devices, which run on newer versions of Android. Nevertheless, for all the Nubia Z50 Ultra devices running on older versions than Android 4.4, this is undoubtedly the easiest way to set a new passcode. Follow these steps to learn how to unlock your Nubia phone if you forgot your password using your Google credentials. - **Step 1.** Try bypassing the pattern lock at least 5 times. After all the failed attempts, you will get the option to either make an emergency call or choose the option of “**Forget pattern**”. ![unlock lg forgot password - forgot pattern](https://images.wondershare.com/drfone/article/2017/03/14892203178747.jpg) - **Step 2.** Select the “Forget pattern” option and provide the correct credentials of your Google account to unlock your phone. ![unlock lg forgot password - log in google account](https://images.wondershare.com/drfone/article/2017/03/14892203377058.jpg) ## Solution 4: Unlock the Nubia Phone Using Custom Recovery (SD card needed) If your phone has a removable SD card, you can also try this technique to disable the pattern/password on your device. Though, you need to have some custom recovery installed on your device for this method. You can always go for TWRP (Team Win Recovery Project) and flash it on your device. TWRP: <https://twrp.me/> Also, since you can't move anything to your device when it is locked, you need to do the same using its SD card. After ensuring that you have met all the basic prerequisites, follow these steps and learn how to unlock the Nubia phone's forgotten password using a custom recovery. - **Step 1.** Download a [Pattern Password Disable](http://forum.xda-developers.com/attachment.php?attachmentid=2532214&d=1390399283) application and save its ZIP file on your computer. Now, insert your SD card into your system and move the recently downloaded file to it. - **Step 2.** Reboot your phone into recovery mode. For instance, the TWRP recovery mode can be turned on by simultaneously pressing the Power, Home, and Volume Up button. You would get different options on your screen after entering the custom recovery mode. Tap on “Install” and browse the Pattern Password Disable application file. ![unlock lg forgot password - team win recovery project](https://images.wondershare.com/drfone/article/2017/03/14892204165153.jpg) - **Step 3.** Install the above-mentioned application and wait for a few minutes. Afterward, restart your Nubia phone. Ideally, your phone will be restarted without any lock screen. If you get a lock screen, you can bypass it by entering any random digits. ## Solution 5: Factory Reset Nubia Phone in Recovery Mode (erases all phone data) If none of the above-mentioned alternatives work, then you can also try to factory reset your device. This will erase every kind of data from your device and make it look brand new by resetting it. Though, you can easily resolve the forgot password on the Nubia phone with it. Therefore, before proceeding, you need to be familiar with all the repercussions of performing a factory reset. All you got to do is follow these steps. - **Step 1.** Put your Nubia phone on its recovery mode with correct key combinations. To do this, firstly, turn your device off and let it rest for a few seconds. Now, press the Power and Volume Down key at the same time. Keep pressing them until you see LG's logo on the screen. Release the buttons for a few seconds and press them again at the same time. Again, keep pressing the buttons until you see the recovery mode menu. This technique works with most Nubia devices, but it can differ slightly from one model to another. - **Step 2.** Choose “Wipe Data/Factory Reset.” You can use the Volume up and down key to navigate the options and the power/home key to select anything. Use these keys and select the “Wipe Data/Factory Reset” option. You might get another pop-up asking to delete all user data. Just agree it reset your device. Sit back and relax as your device will perform a hard reset. ![unlock lg forgot password - enter in recovery mode](https://images.wondershare.com/drfone/article/2017/03/14892204518630.jpg) - **Step 3.** Select the “Reboot system now” option to restart it. Your phone will be restarted without any lock screen. ![unlock lg forgot password - reboot system](https://images.wondershare.com/drfone/article/2017/03/14892204671940.jpg) After following these steps, you can easily overcome how to unlock the Nubia phone forgot password issue. ## Solution 6: Unlock Nubia Phone Using ADB Command (need USB debugging enabled) This might be a little complicated initially, but if you don't want to follow either of the above-mentioned techniques to unlock your device, you can go with this alternative. Before proceeding, make sure that you have ADB (Android Debug Bridge) installed on your computer. If you don't have it, then you can download Android SDK right [here](https://developer.android.com/studio/index.html). Additionally, it would help if you turned on the USB Debugging feature on your phone before you forgot the password. If USB debugging is not turned on before, then this method will not work for you. After making your device ready and downloading all the essential software on your computer, follow these steps to learn how to unlock your Nubia phone if you forgot the password. - **Step 1.** Connect your device to the computer with a USB cable and open the command prompt when it is successfully connected. If you get a pop-up message regarding USB Debugging permission on your device, simply agree to it and continue. - **Step 2.** Now, please provide the following code on the command prompt and reboot your device when it is processed. If you want, you can also tweak the code a little and provide a new lock pin. - _ADB_ _shell_ - _cd /data/data/com.android.providers.settings/databases_ - _sqlite3 settings.__db_ - _update system set value=0 where name='lock\_pattern\_autolock';_ - _update system set value=0 where name='lockscreen__.lockedoutpermanently';_ - _.quit_ ![unlock lg forgot password - command code](https://images.wondershare.com/drfone/article/2017/03/14892205231542.jpg) - **Step 3.** If the above code doesn't work, try providing the code “ADB _shell rm /data/system/gesture. the key_” to it and follow the same drill. ![unlock lg forgot password - code](https://images.wondershare.com/drfone/article/2017/03/14892205424871.jpg) - **Step 4.** After restarting your device, if you still get a lock screen, then give a random password to bypass it. ## Conclusion You can choose a preferred option and rectify the issue whenever you [forgot the password on the Nubia phone](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/). Make sure that you meet all the requirements and go through the respective tutorial to attain fruitful results. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-mastering-android-device-manager-the-ultimate-guide-to-unlocking-your-realme-device-by-drfone-android/"><u>In 2024, Mastering Android Device Manager The Ultimate Guide to Unlocking Your Realme Device</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/a-perfect-guide-to-remove-or-disable-google-smart-lock-on-poco-by-drfone-android/"><u>A Perfect Guide To Remove or Disable Google Smart Lock On Poco</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-unlock-nokia-c32-phone-without-any-data-loss-by-drfone-android/"><u>In 2024, How to Unlock Nokia C32 Phone without Any Data Loss</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/full-guide-to-unlock-your-nokia-c12-by-drfone-android/"><u>Full Guide to Unlock Your Nokia C12</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-7-ways-to-unlock-a-locked-honor-x9b-phone-by-drfone-android/"><u>In 2024, 7 Ways to Unlock a Locked Honor X9b Phone</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-unlock-a-network-locked-poco-x6-pro-phone-by-drfone-android/"><u>How to Unlock a Network Locked Poco X6 Pro Phone?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/mastering-android-device-manager-the-ultimate-guide-to-unlocking-your-honor-magic-6-pro-device-by-drfone-android/"><u>Mastering Android Device Manager The Ultimate Guide to Unlocking Your Honor Magic 6 Pro Device</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/the-ultimate-guide-how-to-bypass-swipe-screen-to-unlock-on-poco-m6-5g-device-by-drfone-android/"><u>The Ultimate Guide How to Bypass Swipe Screen to Unlock on Poco M6 5G Device</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-can-i-bypass-a-forgotten-phone-password-of-realme-narzo-n53-by-drfone-android/"><u>In 2024, Can I Bypass a Forgotten Phone Password Of Realme Narzo N53?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-unlock-poco-c55-phone-password-without-factory-reset-by-drfone-android/"><u>How to Unlock Poco C55 Phone Password Without Factory Reset?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-tips-and-tricks-for-setting-up-your-realme-12-pro-5g-phone-pattern-lock-by-drfone-android/"><u>In 2024, Tips and Tricks for Setting Up your Realme 12 Pro 5G Phone Pattern Lock</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-forgot-pattern-lock-heres-how-you-can-unlock-nubia-red-magic-8s-proplus-pattern-lock-screen-by-drfone-android/"><u>In 2024, Forgot Pattern Lock? Heres How You Can Unlock Nubia Red Magic 8S Pro+ Pattern Lock Screen</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-7-ways-to-unlock-a-locked-realme-v30-phone-by-drfone-android/"><u>In 2024, 7 Ways to Unlock a Locked Realme V30 Phone</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-remove-forgotten-pin-of-your-realme-v30-by-drfone-android/"><u>How to Remove Forgotten PIN Of Your Realme V30</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/top-10-password-cracking-tools-for-nubia-red-magic-8s-proplus-by-drfone-android/"><u>Top 10 Password Cracking Tools For Nubia Red Magic 8S Pro+</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/best-poco-x6-pattern-lock-removal-tools-remove-android-pattern-lock-without-losing-data-by-drfone-android/"><u>Best Poco X6 Pattern Lock Removal Tools Remove Android Pattern Lock Without Losing Data</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-unlock-a-network-locked-realme-11-5g-phone-by-drfone-android/"><u>How to Unlock a Network Locked Realme 11 5G Phone?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-bypassing-google-account-with-vnrom-bypass-for-poco-by-drfone-android/"><u>In 2024, Bypassing Google Account With vnROM Bypass For Poco</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/the-top-5-android-apps-that-use-fingerprint-sensor-to-lock-your-apps-on-poco-by-drfone-android/"><u>The Top 5 Android Apps That Use Fingerprint Sensor to Lock Your Apps On Poco</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-full-tutorial-to-bypass-your-realme-10t-5g-face-lock-by-drfone-android/"><u>In 2024, Full Tutorial to Bypass Your Realme 10T 5G Face Lock?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-change-poco-c50-lock-screen-password-by-drfone-android/"><u>In 2024, How To Change Poco C50 Lock Screen Password?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-can-i-bypass-a-forgotten-phone-password-of-motorola-edge-40-neo-by-drfone-android/"><u>In 2024, Can I Bypass a Forgotten Phone Password Of Motorola Edge 40 Neo?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-unlock-any-poco-c55-phone-password-using-emergency-call-by-drfone-android/"><u>In 2024, How To Unlock Any Poco C55 Phone Password Using Emergency Call</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-enable-usb-debugging-on-a-locked-poco-c65-phone-by-drfone-android/"><u>In 2024, How To Enable USB Debugging on a Locked Poco C65 Phone</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-remove-a-previously-synced-google-account-from-your-motorola-moto-g24-by-drfone-android/"><u>In 2024, How to Remove a Previously Synced Google Account from Your Motorola Moto G24</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-top-apps-and-online-tools-to-track-realme-11-proplus-phone-withwithout-imei-number-by-drfone-android/"><u>In 2024, Top Apps and Online Tools To Track Realme 11 Pro+ Phone With/Without IMEI Number</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/unlock-nokia-c12-pro-phone-password-without-factory-reset-full-guide-here-by-drfone-android/"><u>Unlock Nokia C12 Pro Phone Password Without Factory Reset Full Guide Here</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-unlock-nubia-z50-ultra-phone-without-google-account-by-drfone-android/"><u>How to Unlock Nubia Z50 Ultra Phone without Google Account?</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-unlock-poco-c50-phone-password-without-factory-reset-full-guide-here-by-drfone-android/"><u>In 2024, Unlock Poco C50 Phone Password Without Factory Reset Full Guide Here</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/best-ways-on-how-to-unlockbypassswiperemove-oneplus-nord-3-5g-fingerprint-lock-by-drfone-android/"><u>Best Ways on How to Unlock/Bypass/Swipe/Remove OnePlus Nord 3 5G Fingerprint Lock</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-unlock-realme-c67-5g-phone-without-pin-by-drfone-android/"><u>How to Unlock Realme C67 5G Phone without PIN</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/best-oppo-a78-5g-pattern-lock-removal-tools-remove-android-pattern-lock-without-losing-data-by-drfone-android/"><u>Best Oppo A78 5G Pattern Lock Removal Tools Remove Android Pattern Lock Without Losing Data</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-enable-usb-debugging-on-a-locked-oppo-a56s-5g-phone-by-drfone-android/"><u>How To Enable USB Debugging on a Locked Oppo A56s 5G Phone</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-unlock-your-realme-c33-2023-phone-with-ease-the-3-best-lock-screen-removal-tools-by-drfone-android/"><u>In 2024, Unlock Your Realme C33 2023 Phone with Ease The 3 Best Lock Screen Removal Tools</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/how-to-unlock-any-honor-magic-6-pro-phone-password-using-emergency-call-by-drfone-android/"><u>How To Unlock Any Honor Magic 6 Pro Phone Password Using Emergency Call</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/in-2024-how-to-lock-apps-on-poco-m6-pro-5g-to-protect-your-individual-information-by-drfone-android/"><u>In 2024, How to Lock Apps on Poco M6 Pro 5G to Protect Your Individual Information</u></a></li> <li><a href="https://easy-unlock-android.techidaily.com/unlock-your-realme-12-proplus-5g-phone-with-ease-the-3-best-lock-screen-removal-tools-by-drfone-android/"><u>Unlock Your Realme 12 Pro+ 5G Phone with Ease The 3 Best Lock Screen Removal Tools</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-how-to-remove-a-previously-synced-google-account-from-your-samsung-galaxy-a54-5g-by-drfone-android/"><u>In 2024, How to Remove a Previously Synced Google Account from Your Samsung Galaxy A54 5G</u></a></li> <li><a href="https://activate-lock.techidaily.com/icloud-unlocker-download-unlock-icloud-lock-for-your-iphone-14-pro-by-drfone-ios/"><u>iCloud Unlocker Download Unlock iCloud Lock for your iPhone 14 Pro</u></a></li> <li><a href="https://activate-lock.techidaily.com/in-2024-new-guide-how-to-check-icloud-activation-lock-status-from-your-iphone-14-plus-by-drfone-ios/"><u>In 2024, New Guide How To Check iCloud Activation Lock Status From Your iPhone 14 Plus</u></a></li> <li><a href="https://fix-guide.techidaily.com/restore-missing-app-icon-on-infinix-zero-30-5g-step-by-step-solutions-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Restore Missing App Icon on Infinix Zero 30 5G Step-by-Step Solutions | Dr.fone</u></a></li> <li><a href="https://android-transfer.techidaily.com/how-to-transfer-data-from-xiaomi-14-to-other-android-devices-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>How to Transfer Data from Xiaomi 14 to Other Android Devices? | Dr.fone</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/how-to-make-a-jaw-dropping-time-lapse-video-in-2024/"><u>How to Make A Jaw-Dropping Time Lapse Video, In 2024</u></a></li> <li><a href="https://unlock-android.techidaily.com/best-honor-90-lite-pattern-lock-removal-tools-remove-android-pattern-lock-without-losing-data-by-drfone-android/"><u>Best Honor 90 Lite Pattern Lock Removal Tools Remove Android Pattern Lock Without Losing Data</u></a></li> <li><a href="https://bypass-frp.techidaily.com/in-2024-step-by-step-tutorial-how-to-bypass-vivo-y77t-frp-by-drfone-android/"><u>In 2024, Step-by-Step Tutorial How To Bypass Vivo Y77t FRP</u></a></li> <li><a href="https://howto.techidaily.com/calls-on-tecno-phantom-v-flip-go-straight-to-voicemail-12-fixes-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Calls on Tecno Phantom V Flip Go Straight to Voicemail? 12 Fixes | Dr.fone</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-how-to-transfer-data-from-samsung-galaxy-m14-5g-to-samsung-phone-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, How to Transfer Data from Samsung Galaxy M14 5G to Samsung Phone | Dr.fone</u></a></li> <li><a href="https://howto.techidaily.com/9-solutions-to-fix-realme-12-5g-system-crash-issue-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>9 Solutions to Fix Realme 12 5G System Crash Issue | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/8-best-apps-for-screen-mirroring-xiaomi-14-pc-drfone-by-drfone-android/"><u>8 Best Apps for Screen Mirroring Xiaomi 14 PC | Dr.fone</u></a></li> <li><a href="https://techidaily.com/use-device-manager-to-identify-missing-or-malfunctioning-hardware-drivers-with-windows-device-manager-in-windows-11-by-drivereasy-guide/"><u>Use Device Manager to identify missing or malfunctioning hardware drivers with Windows Device Manager in Windows 11</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/new-2024-approved-the-ultimate-iphone-video-editing-roundup-top-5-apps/"><u>New 2024 Approved The Ultimate iPhone Video Editing Roundup Top 5 Apps</u></a></li> <li><a href="https://howto.techidaily.com/fix-unfortunately-settings-has-stopped-on-oppo-a78-5g-quickly-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Fix Unfortunately Settings Has Stopped on Oppo A78 5G Quickly | Dr.fone</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/new-2024-approved-the-10-best-free-android-video-editors-without-watermarks-or-subscriptions/"><u>New 2024 Approved The 10 Best Free Android Video Editors Without Watermarks or Subscriptions</u></a></li> <li><a href="https://fix-guide.techidaily.com/reasons-for-motorola-moto-g14-stuck-on-startup-screen-and-ways-to-fix-them-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Reasons for Motorola Moto G14 Stuck on Startup Screen and Ways To Fix Them | Dr.fone</u></a></li> <li><a href="https://unlock-android.techidaily.com/in-2024-7-ways-to-unlock-a-locked-itel-p40-phone-by-drfone-android/"><u>In 2024, 7 Ways to Unlock a Locked Itel P40 Phone</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-unlock-vivo-v27e-phone-pattern-lock-without-factory-reset-by-drfone-android/"><u>How to Unlock Vivo V27e Phone Pattern Lock without Factory Reset</u></a></li> <li><a href="https://android-location.techidaily.com/in-2024-for-people-wanting-to-mock-gps-on-xiaomi-redmi-a2-devices-drfone-by-drfone-virtual/"><u>In 2024, For People Wanting to Mock GPS on Xiaomi Redmi A2 Devices | Dr.fone</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-fix-error-1015-while-restoring-iphone-12-pro-max-stellar-by-stellar-data-recovery-ios-iphone-data-recovery/"><u>How to fix error 1015 while restoring iPhone 12 Pro Max | Stellar</u></a></li> <li><a href="https://bypass-frp.techidaily.com/addrom-bypass-an-android-tool-to-unlock-frp-lock-screen-for-your-vivo-t2-5g-by-drfone-android/"><u>AddROM Bypass An Android Tool to Unlock FRP Lock Screen For your Vivo T2 5G</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-how-can-we-unlock-our-samsung-galaxy-a14-5g-phone-screen-by-drfone-android/"><u>In 2024, How Can We Unlock Our Samsung Galaxy A14 5G Phone Screen?</u></a></li> <li><a href="https://meme-emoji.techidaily.com/10-best-work-memes-to-have-fun-in-work-days-for-2024/"><u>10 Best Work Memes to Have Fun in Work Days for 2024</u></a></li> <li><a href="https://ai-video-apps.techidaily.com/new-s-top-avchd-video-editing-tools-compared/"><u>New S Top AVCHD Video Editing Tools Compared</u></a></li> <li><a href="https://ai-vdieo-software.techidaily.com/2024-approved-videopad-video-editor-is-it-worth-the-investment-a-2023-review/"><u>2024 Approved Videopad Video Editor Is It Worth the Investment? A 2023 Review</u></a></li> <li><a href="https://howto.techidaily.com/calls-on-vivo-y36-go-straight-to-voicemail-12-fixes-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Calls on Vivo Y36 Go Straight to Voicemail? 12 Fixes | Dr.fone</u></a></li> <li><a href="https://android-location-track.techidaily.com/in-2024-how-to-detect-and-remove-spyware-on-huawei-p60-drfone-by-drfone-virtual-android/"><u>In 2024, How to Detect and Remove Spyware on Huawei P60? | Dr.fone</u></a></li> <li><a href="https://blog-min.techidaily.com/4-ways-to-transfer-music-from-xiaomi-redmi-note-12-5g-to-iphone-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>4 Ways to Transfer Music from Xiaomi Redmi Note 12 5G to iPhone | Dr.fone</u></a></li> <li><a href="https://ios-unlock.techidaily.com/in-2024-everything-you-need-to-know-about-unlocked-iphone-6s-plus-by-drfone-ios/"><u>In 2024, Everything You Need To Know About Unlocked iPhone 6s Plus</u></a></li> <li><a href="https://techidaily.com/how-do-i-reset-my-samsung-galaxy-m14-5g-phone-without-technical-knowledge-drfone-by-drfone-reset-android-reset-android/"><u>How do I reset my Samsung Galaxy M14 5G Phone without technical knowledge? | Dr.fone</u></a></li> <li><a href="https://fix-guide.techidaily.com/how-to-fix-unresponsive-touch-screen-on-lava-yuva-2-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>How To Fix Unresponsive Touch Screen on Lava Yuva 2 | Dr.fone</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-5-easy-ways-to-copy-contacts-from-poco-c55-to-iphone-14-and-15-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, 5 Easy Ways to Copy Contacts from Poco C55 to iPhone 14 and 15 | Dr.fone</u></a></li> </ul></div>
"use client"; import { Card, CardBody, Checkbox, Pagination, User, cn, } from "@nextui-org/react"; import { type User as Profile, type Rattings } from "@prisma/client"; import { Star } from "lucide-react"; import React, { useState } from "react"; type Props = { rattings: Array< Rattings & { user: Profile; } >; }; const Ratings = ({ rattings }: Props) => { const [value, setValue] = useState(5); const [page, setPage] = React.useState(1); const num = [1, 2, 3, 4, 5]; const calculateAverageRating = () => { const totalRating = rattings.reduce( (total, current) => total + current.value, 0, ); const averageRating = totalRating / rattings.length; return averageRating; }; const rataRata = calculateAverageRating(); const filteredRating = rattings.filter((item) => item.value === value); function calPercen(nilai: number) { const totalRating = rattings.length; const jumlahKemunculan = rattings.filter( (rating) => rating.value === nilai, ).length; const persentase = (jumlahKemunculan / totalRating) * 100; return persentase; } const items = React.useMemo(() => { const start = (page - 1) * 5; const end = start + 5; return filteredRating.slice(start, end); }, [page, filteredRating]); const pages = Math.ceil(filteredRating.length / 5); return ( <div className="my-10"> <p className="py-3 text-xl font-semibold">Rattings</p> <div className="grid grid-cols-1 gap-10 sm:grid-cols-2 lg:grid-cols-5"> <div className="col-span-2"> <div className="relative order-1"> <div className="sticky top-24"> <Card className="h-fit w-full px-5"> <CardBody className="flex flex-col gap-2"> <div className="my-3 flex flex-row items-center justify-center gap-1"> <Star className="fill-yellow-400 stroke-default-100 stroke-1" size={50} /> <p className="text-3xl"> {rataRata.toFixed(1)} <span>/</span> <span>5</span> </p> </div> {num.reverse().map((item) => { const percen = calPercen(item); return ( <div key={item} className="flex w-full space-x-4"> <Checkbox key={item} isSelected={value === item} onChange={() => { setValue(item); }} > <div className="flex flex-row items-center gap-2" key={item} > <Star className="fill-yellow-400 stroke-default-100 stroke-1" /> {item} </div> </Checkbox> <span className="relative w-full overflow-hidden rounded-large border"> <span className="absolute inset-0 bg-primary" style={{ width: `${percen}%` }} ></span> </span> </div> ); })} </CardBody> </Card> </div> </div> </div> <div className="col-span-2 lg:col-span-3"> <div className={cn( "grid min-h-full grid-cols-1 gap-10 md:grid-cols-2 lg:grid-cols-1", { "h-full": items.length < 1, }, )} > {items.map((item) => ( <div className="flex flex-col gap-2 border-b border-default-100 py-3" key={item.id} > <div className="flex items-center justify-between lg:flex-1"> <User classNames={{ base: "justify-start", }} name={item.user.name} description={item.createdAt.toLocaleString()} avatarProps={{ src: item.user.image ?? "/Logo.png", }} /> <p className="inline-flex"> <Star className="fill-yellow-400 stroke-default-100 stroke-1" /> {item.value} </p> </div> <p>{item.comment}</p> </div> ))} {items.length < 1 && ( <div className="inline-flex h-full w-full items-center justify-center"> <p className="text-lg font-semibold">No rating yet</p> </div> )} </div> <div className="mt-5 flex justify-center"> <Pagination isCompact showControls showShadow color="primary" page={page} total={pages} onChange={setPage} /> </div> </div> </div> </div> ); }; export default Ratings;
package tournament import ( "bufio" "fmt" "io" "sort" "strings" ) type ( matchResult string position uint8 ) const ( MATCH_WIN matchResult = "win" MATCH_LOSS matchResult = "loss" MATCH_DRAW matchResult = "draw" POSITION_FIRST position = 1 POSITION_SECOND position = 2 TEAM_COL_WIDTH = 31 ) func NewMatchResultByPosition(matchResultStr string, position position) (matchResult, error) { if matchResultStr == "draw" { return MATCH_DRAW, nil } switch position { case POSITION_FIRST: switch matchResultStr { case "win": return MATCH_WIN, nil case "loss": return MATCH_LOSS, nil default: return "", fmt.Errorf("invalid match result") } case POSITION_SECOND: switch matchResultStr { case "win": return MATCH_LOSS, nil case "loss": return MATCH_WIN, nil default: return "", fmt.Errorf("invalid match result") } default: return "", fmt.Errorf("invalid position") } } type teamSummary struct { MatchesPlayed uint32 Wins uint32 Draws uint32 Losses uint32 Points uint32 TeamName string } func (ts teamSummary) Print(writer io.Writer) { fmt.Fprintf( writer, "%s| %d | %d | %d | %d | %d\n", prepareTeamString(ts.TeamName, TEAM_COL_WIDTH), ts.MatchesPlayed, ts.Wins, ts.Draws, ts.Losses, ts.Points, ) } func NewTeamSummary(teamName string, mRes matchResult) *teamSummary { switch mRes { case MATCH_WIN: return &teamSummary{TeamName: teamName, MatchesPlayed: 1, Wins: 1, Points: 3} case MATCH_DRAW: return &teamSummary{TeamName: teamName, MatchesPlayed: 1, Draws: 1, Points: 1} case MATCH_LOSS: return &teamSummary{TeamName: teamName, MatchesPlayed: 1, Losses: 1} default: panic("invalid match result") } } func (ts *teamSummary) Update(matchResult matchResult, position position) { ts.MatchesPlayed += 1 switch matchResult { case MATCH_WIN: ts.Wins += 1 ts.Points += 3 case MATCH_DRAW: ts.Draws += 1 ts.Points += 1 case MATCH_LOSS: ts.Losses += 1 } } type teamSummaryMap map[string]*teamSummary func (tsMap teamSummaryMap) Update(teamName string, matchResultStr string, position position) error { matchResult, err := NewMatchResultByPosition(matchResultStr, position) if err != nil { return err } if team, ok := tsMap[teamName]; ok { team.Update(matchResult, position) return nil } tsMap[teamName] = NewTeamSummary(teamName, matchResult) return nil } func (tsMap teamSummaryMap) Print(writer io.Writer) { fmt.Fprintf( writer, "%s| %s | %s | %s | %s | %s\n", prepareTeamString("Team", TEAM_COL_WIDTH), "MP", "W", "D", "L", "P", ) for _, ts := range tsMap.toList() { ts.Print(writer) } } func (tsMap teamSummaryMap) toList() []*teamSummary { summaryList := make([]*teamSummary, 0, len(tsMap)) for _, summaryRow := range tsMap { summaryList = append(summaryList, summaryRow) } sort.Slice(summaryList, func(i, j int) bool { if summaryList[i].Points == summaryList[j].Points { return summaryList[i].TeamName < summaryList[j].TeamName } else { return summaryList[i].Points > summaryList[j].Points } }) return summaryList } func Tally(reader io.Reader, writer io.Writer) error { summaryMap := teamSummaryMap{} scanner := bufio.NewScanner(reader) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if line == "" || strings.HasPrefix(line, "#") { continue } parts := strings.Split(line, ";") if len(parts) != 3 { return fmt.Errorf("invalid line: %s", line) } team1Name, team2Name, matchResultStr := parts[0], parts[1], parts[2] if err := summaryMap.Update(team1Name, matchResultStr, POSITION_FIRST); err != nil { return err } if err := summaryMap.Update(team2Name, matchResultStr, POSITION_SECOND); err != nil { return err } } summaryMap.Print(writer) return nil } func prepareTeamString(teamName string, teamColWidth int) string { teamColPaddingLen := teamColWidth - len(teamName) return fmt.Sprintf("%s%s", teamName, strings.Repeat(" ", teamColPaddingLen)) }
#include "f_util.h" #include "ff.h" #include "hardware/i2c.h" #include "hardware/pwm.h" #include "hw_config.h" #include "pico/stdlib.h" #include "rtc.h" #include <stdbool.h> #include <stdio.h> #include <string.h> #define FILENAME "log.txt" #define I2C_PORT i2c1 #define I2C_SDA 2 #define I2C_SCL 3 #define NFC_ADDR 0x24 #define SERVO_PIN 15 #define PN532_MIFARE_ISO14443A (0x00) #define PN532_PREAMBLE (0x00) #define PN532_STARTCODE1 (0x00) #define PN532_STARTCODE2 (0xFF) #define PN532_POSTAMBLE (0x00) #define PN532_HOSTTOPN532 (0xD4) #define PN532_I2C_READY (0x01) #define PN532_COMMAND_INLISTPASSIVETARGET (0x4A) #define PN532_COMMAND_SAMCONFIGURATION (0x14) #define PN532_PACKBUFFSIZ 64 uint8_t pn532_packetbuffer[PN532_PACKBUFFSIZ]; uint8_t pn532ack[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00}; /**************************************************************************/ /*! @brief Writes a command to the PN532, automatically inserting the preamble and required frame details (checksum, len, etc.) @param cmd Pointer to the command buffer @param cmdlen Command length in bytes */ /**************************************************************************/ void writecommand(uint8_t *cmd, uint8_t cmdlen) { // I2C or Serial command write. uint8_t packet[8 + cmdlen]; uint8_t LEN = cmdlen + 1; packet[0] = PN532_PREAMBLE; packet[1] = PN532_STARTCODE1; packet[2] = PN532_STARTCODE2; packet[3] = LEN; packet[4] = ~LEN + 1; packet[5] = PN532_HOSTTOPN532; uint8_t sum = 0; for (uint8_t i = 0; i < cmdlen; i++) { packet[6 + i] = cmd[i]; sum += cmd[i]; } packet[6 + cmdlen] = ~(PN532_HOSTTOPN532 + sum) + 1; packet[7 + cmdlen] = PN532_POSTAMBLE; int ret = i2c_write_blocking(I2C_PORT, NFC_ADDR, packet, 8 + cmdlen, false); if (ret != 8 + cmdlen) { printf("Error in writecommand function: %d\n", ret); } } /**************************************************************************/ /*! @brief Return true if the PN532 is ready with a response. */ /**************************************************************************/ bool isready() { // I2C ready check via reading RDY byte uint8_t rdy[1]; int ret = i2c_read_blocking(I2C_PORT, NFC_ADDR, rdy, 1, false); if (ret != 1) { printf("Error in isready function: %d\n", ret); } return rdy[0] == PN532_I2C_READY; } /**************************************************************************/ /*! @brief Waits until the PN532 is ready. @param timeout Timeout before giving up */ /**************************************************************************/ bool waitready(uint16_t timeout) { uint16_t timer = 0; while (!isready()) { if (timeout != 0) { timer += 10; if (timer > timeout) { return false; } } sleep_ms(10); } return true; } /**************************************************************************/ /*! @brief Reads n bytes of data from the PN532 via SPI or I2C. @param buff Pointer to the buffer where data will be written @param n Number of bytes to be read */ /**************************************************************************/ void readdata(uint8_t *buff, uint8_t n) { // I2C read uint8_t rbuff[n + 1]; // +1 for leading RDY byte int ret = i2c_read_blocking(I2C_PORT, NFC_ADDR, rbuff, n + 1, false); if (ret < 0) { printf("Error in readdata function: %d\n", ret); } for (uint8_t i = 0; i < n; i++) { buff[i] = rbuff[i + 1]; } } /**************************************************************************/ /*! @brief Tries to read the SPI or I2C ACK signal */ /**************************************************************************/ bool readack() { uint8_t ackbuff[6]; readdata(ackbuff, 6); return (0 == memcmp(ackbuff, pn532ack, 6)); } /**************************************************************************/ /*! @brief Sends a command and waits a specified period for the ACK @param cmd Pointer to the command buffer @param cmdlen The size of the command in bytes @param timeout timeout before giving up @returns 1 if everything is OK, 0 if timeout occured before an ACK was recieved */ /**************************************************************************/ bool sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen, uint16_t timeout) { // I2C works without using IRQ pin by polling for RDY byte // seems to work best with some delays between transactions // write the command writecommand(cmd, cmdlen); // I2C TUNING sleep_ms(1); // Wait for chip to say it's ready! if (!waitready(timeout)) { return false; } // read acknowledgement if (!readack()) { printf("No ACK frame received!"); return false; } // I2C TUNING sleep_ms(1); // Wait for chip to say it's ready! if (!waitready(timeout)) { return false; } return true; // ack'd command } /**************************************************************************/ /*! Reads the ID of the passive target the reader has deteceted. @param uid Pointer to the array that will be populated with the card's UID (up to 7 bytes) @param uidLength Pointer to the variable that will hold the length of the card's UID. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool readDetectedPassiveTargetID(uint8_t *uid, uint8_t *uidLength) { // read data packet readdata(pn532_packetbuffer, 20); // check some basic stuff /* ISO14443A card response should be in the following format: byte Description ------------- ------------------------------------------ b0..6 Frame header and preamble b7 Tags Found b8 Tag Number (only one used in this example) b9..10 SENS_RES b11 SEL_RES b12 NFCID Length b13..NFCIDLen NFCID */ if (pn532_packetbuffer[7] != 1) return 0; uint16_t sens_res = pn532_packetbuffer[9]; sens_res <<= 8; sens_res |= pn532_packetbuffer[10]; /* Card appears to be Mifare Classic */ *uidLength = pn532_packetbuffer[12]; for (uint8_t i = 0; i < pn532_packetbuffer[12]; i++) { uid[i] = pn532_packetbuffer[13 + i]; } return 1; } /**************************************************************************/ /*! @brief Waits for an ISO14443A target to enter the field and reads its ID. @param cardbaudrate Baud rate of the card @param uid Pointer to the array that will be populated with the card's UID (up to 7 bytes) @param uidLength Pointer to the variable that will hold the length of the card's UID. @param timeout Timeout in milliseconds. @return 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool readPassiveTargetID(uint8_t cardbaudrate, uint8_t *uid, uint8_t *uidLength, uint16_t timeout) { pn532_packetbuffer[0] = PN532_COMMAND_INLISTPASSIVETARGET; pn532_packetbuffer[1] = 1; // max 1 cards at once (we can set this to 2 later) pn532_packetbuffer[2] = cardbaudrate; if (!sendCommandCheckAck(pn532_packetbuffer, 3, timeout)) { return 0x0; // no cards read } return readDetectedPassiveTargetID(uid, uidLength); } /**************************************************************************/ /*! @brief Configures the SAM (Secure Access Module) @return true on success, false otherwise. */ /**************************************************************************/ bool SAMConfig(void) { pn532_packetbuffer[0] = PN532_COMMAND_SAMCONFIGURATION; pn532_packetbuffer[1] = 0x01; // normal mode; pn532_packetbuffer[2] = 0x14; // timeout 50ms * 20 = 1 second pn532_packetbuffer[3] = 0x01; // use IRQ pin! if (!sendCommandCheckAck(pn532_packetbuffer, 4, 1000)) return false; // read data packet readdata(pn532_packetbuffer, 9); int offset = 6; return (pn532_packetbuffer[offset] == 0x15); } int main() { stdio_init_all(); time_init(); // Wait for the USB Debug port // while (!stdio_usb_connected()) tight_loop_contents(); sleep_ms(3000); printf("Starting\n"); sd_card_t *pSD = sd_get_by_num(0); gpio_set_function(SERVO_PIN, GPIO_FUNC_PWM); pwm_config config = pwm_get_default_config(); // Set the PWM frequency (50 Hz is common for servos) pwm_config_set_clkdiv(&config, 100.0f); uint slice_num = pwm_gpio_to_slice_num(SERVO_PIN); pwm_init(slice_num, &config, true); i2c_init(I2C_PORT, 400 * 1000); gpio_set_function(I2C_SDA, GPIO_FUNC_I2C); gpio_set_function(I2C_SCL, GPIO_FUNC_I2C); gpio_pull_up(I2C_SDA); gpio_pull_up(I2C_SCL); SAMConfig(); uint8_t lastUid[] = {0, 0, 0, 0, 0, 0, 0}; while (1) { pwm_set_gpio_level(SERVO_PIN, 0); uint8_t success; uint8_t uid[] = {0, 0, 0, 0, 0, 0, 0}; // Buffer to store the returned UID uint8_t uidLength = 0; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) // Wait for an NTAG203 card. When one is found 'uid' will be populated with // the UID, and uidLength will indicate the size of the UUID (normally 7) success = readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength, 1000); if (success && memcmp(lastUid, uid, uidLength) != 0) { FRESULT fr = f_mount(&pSD->fatfs, pSD->pcName, 1); if (FR_OK != fr) { panic("f_mount error: %s (%d)\n", FRESULT_str(fr), fr); } FIL fil; fr = f_open(&fil, FILENAME, FA_OPEN_APPEND | FA_WRITE); if (FR_OK != fr && FR_EXIST != fr) { panic("f_open(%s) error: %s (%d)\n", FILENAME, FRESULT_str(fr), fr); } printf("UID: "); for (int i = 0; i < uidLength; i++) { printf("%x", uid[i]); f_printf(&fil, "%x", uid[i]); // prints to the log file } printf("\n"); f_printf(&fil, "\n"); fr = f_close(&fil); if (FR_OK != fr) { printf("f_close error: %s (%d)\n", FRESULT_str(fr), fr); } f_unmount(pSD->pcName); pwm_set_gpio_level(SERVO_PIN, 500); sleep_ms(500); } memcpy(lastUid, uid, 7); } return 0; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="images/icons8-h-16.png" type="image/x-icon"> <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/remixicon/3.4.0/remixicon.css" crossorigin=""> --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css" rel="stylesheet"> <link rel="stylesheet" href="styles/styles.css"> <title>Himanshu Chauhan portfolio website</title> </head> <body> <header class="header" id="header"> <nav class="nav container"> <a href="#" class="nav__logo"> <span class="nav__logo-circle">H</span> <span class="nav__logo-name">Chauhan.</span> </a> <div class="nav__menu" id="nav-menu"> <span class="nav__title">Menu</span> <h3 class="nav__name">Himanshu Chauhan</h3> <ul class="nav__list"> <li class="nav__item"> <a href="#home" class="nav__link">Home.</a> </li> <li class="nav__item"> <a href="#about" class="nav__link">About Me.</a> </li> <li class="nav__item"> <a href="#services" class="nav__link">Services.</a> </li> <li class="nav__item"> <a href="#projects" class="nav__link">Projects.</a> </li> <li class="nav__item"> <a href="#contact" class="nav__link nav__link-button">Contact Me.</a> </li> </ul> <!-- Close button --> <div class="nav__close" id="nav-close"> <i class="ri-close-line"></i> </div> </div> <div class="nav__buttons"> <!-- Theme button --> <i class="ri-moon-line change-theme" id="theme-button"></i> <!-- Toggle button --> <div class="nav__toggle" id="nav-toggle"> <i class="ri-menu-4-line"></i> </div> </div> </nav> </header> <main class="main"> <section class="home section" id="home"> <div class="home__container container grid"> <h1 class="home__name">Himanshu.</h1> <div class="home__perfil"> <div class="home__image"> <img src="images/Himanshu_Chauhan.jpeg" alt="image" class="home__img"> <div class="home__shadow"></div> <img src="images/curved-arrow.svg" alt="home__arrow" class="home__arrow"> <img src="images/random-lines.svg" alt="home__line" class="home__line"> <div class="geometric-box"></div> <div class="home__social"> <a href="https://www.instagram.com/himanshuch8055/" target="_blank" class="home__social-link"> <i class="ri-instagram-line"></i> </a> <a href="https://www.linkedin.com/in/himanshuch8055/" target="_blank" class="home__social-link"> <i class="ri-linkedin-box-line"></i> </a> <a href="https://github.com/Himanshuch8055" target="_blank" class="home__social-link"> <i class="ri-github-line"></i> </a> </div> </div> </div> <div class="home__info"> <p class="home__description"> <b>Full Stack Developer 🙂</b>, with knowledge in web development and design, Passionate programmer in love with JavaScript ❤️, Contributing to open source 🚀 </p> <a href="#about" class="home__scroll"> <div class="home__scroll-box"> <i class="ri-arrow-down-s-line"></i> </div> <span class="home__scroll-text">Scroll Down</span> </a> </div> </div> </section> <section class="about section" id="about"> <div class="about__container container grid"> <h2 class="section__title-1"> <span>About Me.</span> </h2> <div class="about__perfil"> <div class="about__image"> <img src="images/Himanshuch8055.png" alt="Himanshuch8055" class="about__img"> <div class="about__shadow"></div> <div class="geometric-box"></div> <img src="images/random-lines.svg" alt="about__line" class="about__line"> <div class="about__box"></div> </div> </div> <div class="about__info"> <p class="about__description"> Passionate about creating <b>Web Pages</b> with <b>UI/UX</b> User Interface. </p> <ul class="about__list"> <li class="about__item"> <b>My Skills Are:</b> HTML, CSS, JavaScript, ReactJs, NodeJs, NextJs, Git & GitHub, Bootstrap, Tailwind CSS & Figma. </li> </ul> <div class="about__buttons"> <a href="#contact" class="button"> <i class="ri-send-plane-line"></i>Contact Me </a> <a href="https://www.linkedin.com/in/himanshuch8055/" target="_blank" class="button__ghost"> <i class="ri-linkedin-box-line"></i> </a> </div> </div> </div> </section> <section class="services section" id="services"> <h2 class="section__title-2"> <span>Services.</span> </h2> <div class="services__container container grid"> <article class="services__card"> <div class="services__border"></div> <div class="services__content"> <div class="services__icon"> <div class="services__box"></div> <i class="ri-layout-4-line"></i> </div> <h2 class="services__title">Web Design</h2> <p class="services__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> </article> <article class="services__card"> <div class="services__border"></div> <div class="services__content"> <div class="services__icon"> <div class="services__box"></div> <i class="ri-code-box-line"></i> </div> <h2 class="services__title">Development</h2> <p class="services__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> </article> <article class="services__card"> <div class="services__border"></div> <div class="services__content"> <div class="services__icon"> <div class="services__box"></div> <i class="ri-smartphone-line"></i> </div> <h2 class="services__title">Mobile App</h2> <p class="services__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> </article> </div> </section> <section class="projects section" id="projects"> <h2 class="section__title-1"> <span>Projects.</span> </h2> <div class="projects__container container grid"> <article class="projects__card"> <div class="projects__image"> <img src="images/landing-page-1.png" alt="" class="projects__img"> <a href="#projects" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Landing Page 1</h2> <p class="projects__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> <div class="projects__buttons"> <a href="https://github.com/Himanshuch8055" target="_blank" class="projects__link"> <i class="ri-github-line"></i>View </a> <a href="#" target="_blank" class="projects__link"> <!-- <i class="ri-dribbble-line"></i>View --> </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="images/landing-page-2.png" alt="" class="projects__img"> <a href="#projects" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Landing Page 2</h2> <p class="projects__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> <div class="projects__buttons"> <a href="https://github.com/Himanshuch8055" target="_blank" class="projects__link"> <i class="ri-github-line"></i>View </a> <a href="#" target="_blank" class="projects__link"> <!-- <i class="ri-dribbble-line"></i>View --> </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="images/landing-page-3.png" alt="" class="projects__img"> <a href="#projects" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Landing Page 3</h2> <p class="projects__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> <div class="projects__buttons"> <a href="https://github.com/Himanshuch8055" target="_blank" class="projects__link"> <i class="ri-github-line"></i>View </a> <a href="#" target="_blank" class="projects__link"> <!-- <i class="ri-dribbble-line"></i>View --> </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="images/landing-page-4.png" alt="" class="projects__img"> <a href="#projects" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Landing Page 4</h2> <p class="projects__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> <div class="projects__buttons"> <a href="https://github.com/Himanshuch8055" target="_blank" class="projects__link"> <i class="ri-github-line"></i>View </a> <a href="#" target="_blank" class="projects__link"> <!-- <i class="ri-dribbble-line"></i>View --> </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="images/landing-page-4.png" alt="" class="projects__img"> <a href="#projects" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Landing Page 4</h2> <p class="projects__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> <div class="projects__buttons"> <a href="https://github.com/Himanshuch8055" target="_blank" class="projects__link"> <i class="ri-github-line"></i>View </a> <a href="#" target="_blank" class="projects__link"> <!-- <i class="ri-dribbble-line"></i>View --> </a> </div> </article> <article class="projects__card"> <div class="projects__image"> <img src="images/landing-page-4.png" alt="" class="projects__img"> <a href="#projects" class="projects__button button"> <i class="ri-arrow-right-up-line"></i> </a> </div> <div class="projects__content"> <h3 class="projects__subtitle">Website</h3> <h2 class="projects__title">Landing Page 4</h2> <p class="projects__description"> Beautiful and elegant designs with interfaces that are intuitive, efficient and pleasant to use for the user. </p> </div> <div class="projects__buttons"> <a href="https://github.com/Himanshuch8055" target="_blank" class="projects__link"> <i class="ri-github-line"></i>View </a> <a href="#" target="_blank" class="projects__link"> <!-- <i class="ri-dribbble-line"></i>View --> </a> </div> </article> </div> </section> <section class="contact section" id="contact"> <div class="contact__container grid"> <div class="contact__data"> <h2 class="section__title-2"> <span>Contact Me.</span> </h2> <p class="contact__description-1"> I will read all emails. Send me any message you want and I'll get back to you. </p> <p class="contact__description-2"> I need your <b>Name</b> and <b>Email Address</b> , but you won't receive anything other than your reply. </p> <div class="geometric-box"></div> </div> <div class="contact__mail"> <h2 class="contact__title"> Send Me A Message </h2> <form action="" class="contact__form" id="contact-form"> <div class="contact__group"> <div class="contact__box"> <input type="text" name="user_name" class="contact__input" id="name" required placeholder="Name"> <label for="name" class="contact__label">Name</label> </div> <div class="contact__box"> <input type="email" name="user_email" class="contact__input" id="email" required placeholder="Email"> <label for="email" class="contact__label">Email</label> </div> </div> <div class="contact__box"> <input type="text" name="user_Subject" class="contact__input" id="Subject" required placeholder="Subject"> <label for="Subject" class="contact__label">Subject</label> </div> <div class="contact__box contact__area"> <textarea name="user_massage" id="massage" class="contact__input" required placeholder="Massage"></textarea> <label for="massage" class="contact__label">Massage</label> </div> <p class="contact__message" id="contact-message"></p> <button type="submit" class="contact__button button"> <i class="ri-send-plane-line"></i>Send Message </button> </form> </div> <div class="contact__social"> <img src="images/curved-arrow.svg" alt="image" class="contact__social-arrow"> <div class="contact__social-data"> <div> <p class="contact__social-description-1"> Does not send emails </p> <p class="contact__social-description-2"> Write me on my social networks </p> </div> <div class="contact__social-links"> <a href="https://twitter.com/himanshuch8055" target="_blank" class="contact__social-link"> <i class="ri-twitter-x-line"></i> </a> <a href="https://www.instagram.com/himanshuch8055/" target="_blank" class="contact__social-link"> <i class="ri-instagram-line"></i> </a> <a href="https://www.linkedin.com/in/himanshuch8055/" target="_blank" class="contact__social-link"> <i class="ri-linkedin-box-line"></i> </a> </div> </div> </div> </div> </section> </main> <footer class="footer"> <div class="footer__container container grid"> <ul class="footer__links"> <li> <a href="#about" class="footer__link">About</a> </li> <li> <a href="#services" class="footer__link">Services</a> </li> <li> <a href="#projects" class="footer__link">Projects</a> </li> </ul> <span class="footer__copy"> &#169; All Rights Reserved By <a href="">Himanshu Chauhan.</a> </span> </div> </footer> <!--========== SCROLL UP ==========--> <a href="#" class="scroll__up" id="scroll-up"> <i class="ri-arrow-up-s-line"></i> </a> <script src="scripts/scrollreveal.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js"></script> <script src="scripts/script.js"></script> </body> </html>
package io.github.hillelmed.ogm.starter.config; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import java.util.List; import java.util.Map; @ExtendWith(MockitoExtension.class) @ExtendWith(SpringExtension.class) class GeneralBeanConfigTest { @Mock private OgmProperties properties; @Mock private ApplicationContext applicationContext; private GeneralBeanConfig config; @BeforeEach void setUp() { config = new GeneralBeanConfig(properties, applicationContext); } @Test void testJsonMapper() { ObjectMapper jsonMapper = config.jsonMapper(); assertThat(jsonMapper).isNotNull(); assertThat(jsonMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); assertThat(jsonMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test void testXmlMapper() { XmlMapper xmlMapper = config.xmlMapper(); assertThat(xmlMapper).isNotNull(); assertThat(xmlMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); assertThat(xmlMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test void testYamlMapper() { YAMLMapper yamlMapper = config.yamlMapper(); assertThat(yamlMapper).isNotNull(); assertThat(yamlMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); assertThat(yamlMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test void testOgmConfig() { when(properties.getUrl()).thenReturn("http://example.com"); when(properties.getUsername()).thenReturn("user"); when(properties.getPassword()).thenReturn("pass"); OgmConfig ogmConfig = config.ogmConfig(); assertThat(ogmConfig).isNotNull(); assertThat(ogmConfig.getUrl()).isEqualTo("http://example.com"); } @Test void testListOfRepositoriesClass() { // Mocking the scanning process and the ApplicationContext when(applicationContext.getBeansWithAnnotation(SpringBootApplication.class)).thenReturn(Map.of()); // This part is tricky to test since it involves classpath scanning. // You would need to simulate or mock the provider's behavior // This is just a basic example without actual scanning List<String> repositoryClasses = config.listOfRepositoriesClass(); assertThat(repositoryClasses).isNotNull(); } }
import { currentProfile } from "@/lib/currentProfile"; import { db } from "@/lib/db"; import { MessageSchema } from "@/lib/validators/message"; import { NextApiResponseServerIO } from "@/types"; import { NextApiRequest } from "next"; import { z } from "zod"; const handler = async (req: NextApiRequest, res: NextApiResponseServerIO) => { if (req.method !== "POST") { return res.status(405).json({ message: "Method not allowed" }); } try { const profile = await currentProfile(req); if (!profile) { return new Response("Unauthorized", { status: 401 }); } const { serverId, channelId } = req.query; if (!serverId) { return res.status(422).json({ message: "Server Id is required", }); } if (!channelId) { return res.status(422).json({ message: "Channel Id is required", }); } const { body } = req; const { fileUrl } = req.body; const { content } = MessageSchema.parse(body); if (!content) { return res.status(422).json({ message: "Content is required", }); } const server = await db.server.findFirst({ where: { id: serverId as string, members: { some: { profileId: profile.id, }, }, }, include: { members: true, }, }); if (!server) { return res.status(404).json({ message: "Server not found", }); } const channel = await db.channel.findFirst({ where: { id: channelId as string, serverId: server.id, }, }); if (!channel) { return res.status(404).json({ message: "Channel not found", }); } const member = server.members.find( (member) => member.profileId === profile.id ); if (!member) { return res.status(404).json({ message: "Member not found", }); } const message = await db.message.create({ data: { content, fileUrl, channelId: channel.id, memberId: member.id, }, include: { member: { include: { profile: true, }, }, }, }); const channelKey = `chat:${channel.id}:messages`; res?.socket?.server?.io?.emit(channelKey, message); return res.status(200).json(message); } catch (error) { console.log("[CHANNEL_UPDATE]", error); if (error instanceof z.ZodError) { return res.status(422).json({ message: error.message, }); } return res.status(500).json({ message: "Internal Error", }); } }; export default handler;
import { useEffect, useState } from 'react'; const usePointerPos = () => { const [pos, setPos] = useState({ x: 0, y: 0 }); useEffect(() => { const handleMouseMove = (e: MouseEvent) => { setPos({ x: e.clientX, y: e.clientY }); }; globalThis.addEventListener('mousemove', (e) => handleMouseMove(e)); return () => globalThis.removeEventListener('mousemove', (e) => handleMouseMove(e)); }); return { x: pos.x, y: pos.y, }; }; export default usePointerPos;
@file:Suppress("LeakingThis", "unused", "JpaDataSourceORMInspection") package com.linecorp.kotlinjdsl.example.eclipselink.javax.entity.employee import java.util.* import javax.persistence.Column import javax.persistence.DiscriminatorColumn import javax.persistence.Embedded import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Inheritance import javax.persistence.InheritanceType import javax.persistence.OneToMany import javax.persistence.Table @Entity @Table(name = "employee") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "employee_type") class Employee( @Id @Column(name = "employee_id") val employeeId: Long, @Column(name = "name") var name: String, @Column(name = "nickname") var nickname: String?, @Column(name = "phone") var phone: String, @Embedded val address: EmployeeAddress, @OneToMany(mappedBy = "employee") val departments: MutableSet<EmployeeDepartment>, ) { init { departments.forEach { it.employee = this } } override fun equals(other: Any?): Boolean = Objects.equals(employeeId, (other as? Employee)?.employeeId) override fun hashCode(): Int = Objects.hashCode(employeeId) override fun toString(): String = "Employee(employeeId=$employeeId)" }
import React, { useState } from "react"; import { Box, Card, CardContent, Slide, Typography } from "@mui/material"; interface Props { image: string; message: string; details: string; } const CardComponent = ({ image, message, details }: Props) => { const [cardHover, setCardHover] = useState(false); const handleMouseEnter = () => { setCardHover(true); }; const handleMouseOut = () => { setCardHover(false); }; return ( <Card onMouseOver={handleMouseEnter} onMouseOut={handleMouseOut} sx={{ display: "flex", alignItems: "flex-end", justifyContent: "left", backgroundImage: image, backgroundPosition: "center", backgroundSize: "cover", borderRadius: "1rem", boxShadow: "none", width: 300, height: 500, transition: "0.5s", "&:hover": { transform: " scale(1.05)", transition: "0.3s", }, }} > <CardContent> <Box> <Typography sx={{ color: "#FFF", fontFamily: "Dosis", fontSize: { xs: "30px", md: "40px" }, fontWeight: "600", paddingBottom: "0.25rem", }} > {message} </Typography> </Box> <Slide direction="up" in={cardHover} mountOnEnter unmountOnExit> <Typography sx={{ textAlign: "left", color: "#FFF", fontFamily: "Dosis", fontSize: { xs: "14px", md: "20px" }, fontWeight: "600", paddingBottom: "0.25rem", }} > {details} </Typography> </Slide> </CardContent> </Card> ); }; export default CardComponent;
import template from "./change_password.hbs"; import Block from "../../utils/Block"; import {addFocus, addBlur} from "../../utils/addFocusBlurEvents"; import Input from "../../partials/input" import Button from "../button"; import Router from "../../utils/Router"; import { inputChangeInfo } from "../inputChangeInfo/inputChangeInfo"; import UserController from "../../controllers/UserController"; export default class FormChangePassword extends Block { init() { this.children.inputPassword = [ new inputChangeInfo({ messageErrorInform: "Неверный пароль", description: "Старый пароль:", input: new Input({ name: "oldPassword", type:"password", class: "profile-input__change-data", events: { focus: function(e: HTMLFormElement) { addFocus(e) }, blur: function(e: HTMLFormElement) { addBlur(e) } } }) }), new inputChangeInfo({ messageErrorInform: "Неверный пароль", description: "Новый пароль:", input: new Input({ name:"newPassword", type:"password", class:"profile-input__change-data", events: { focus: function(e: HTMLFormElement) { addFocus(e) }, blur: function(e: HTMLFormElement) { addBlur(e) } } }) }), new inputChangeInfo({ messageErrorInform: "Пароли не совпадают", description: "Повторить новый пароль:", input: new Input({ name:"password", type:"password", class:"profile-input__change-data", events: { focus: function(e: HTMLFormElement) { addFocus(e) }, blur: function(e: HTMLFormElement) { addBlur(e) } } }) }) ] this.children.buttons = [ new Button({ class: "size_h25_w180 bg_color_50AF8A", label: "Сохранить", events: { click: () => this.onSubmit() } }), new Button({ class: "size_h25_w180 bg_color_8c8c8c", label: "Отмена", events: { click: () => { Router.go("/settings") } } }) ] } onSubmit() { const value = (this.children.inputPassword as inputChangeInfo[]) .filter(el => (el.children.input as Input).getName() !== "repit_password") .map(el => { if((el.children.input as Input).getBlock()) { return [(el.children.input as Input).getName(), (el.children.input as Input).getValue()] } else { alert("Поля не должны быть пустыми") throw new Error() } }) const data = Object.fromEntries(value) UserController.changePassword(data) } render() { return this.compile(template, {...this.props}) } }
package com.mendozamatias.presentation.controller; import com.mendozamatias.bussines.services.IPacienteService; import com.mendozamatias.domain.dto.paciente.CrearPacienteDto; import com.mendozamatias.domain.dto.paciente.PacienteDto; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.annotation.security.PermitAll; import org.apache.coyote.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List; @Tag(name = "2. Pacientes ", description = "API para la gestión de Pacientes atendidos en la clinica") @RestController @RequestMapping("/api/pacientes") public class PacienteController { @Autowired private IPacienteService pacienteService; @Operation(summary = "Listar a todos los pacientes", description = "Lista todos los pacientes que se atienden en la clinica") @ApiResponse(responseCode = "200", description = "Paciente") @PreAuthorize("hasRole('PROFESIONAL')") @GetMapping public ResponseEntity<List<PacienteDto>> listarTodosLosPacientes(){ return ResponseEntity.status(HttpStatus.OK).body(pacienteService.listarTodosLosPaciente()); } @Operation(summary = "Crear un paciente", description = "Crea un paciente") @ApiResponse(responseCode = "200", description = "Paciente") @PermitAll @PostMapping public ResponseEntity<PacienteDto> crearUnPaciente(@RequestBody CrearPacienteDto crearPacienteDto){ return ResponseEntity.status(HttpStatus.CREATED).body(pacienteService.crearUnPaciente(crearPacienteDto)); } }
package egecoskun121.com.crm.security; import egecoskun121.com.crm.model.entity.Role; import egecoskun121.com.crm.model.entity.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.Collections; public class MyUserDetails implements UserDetails { private User user; public MyUserDetails(User user) { this.user = user; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { Role a = user.getRole(); SimpleGrantedAuthority authority = new SimpleGrantedAuthority(a.toString()); return Collections.singleton(authority); } public Long getId(){ return user.getId(); } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUserName(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
import { Navigate } from 'react-router-dom'; import React, { memo, useEffect } from 'react'; import { useDispatch } from 'react-redux'; import { Grid, Button, Alert, CircularProgress, Pagination, Card, CardContent, CardMedia, Typography, } from '@mui/material'; import Post from '../../components/Post/Post'; import toggleModal from '../../redux/actions/modal'; import { myFetchPosts } from '../../redux/actions/posts'; import { useTypedSelector } from '../../hooks/useTypedSelector'; import classes from './UserPage.module.css'; import { MAX_POSTS_ON_PAGE } from '../../utils/constants'; import { filterCategories, paginatePosts } from '../../utils/filterArray'; import takeImage from '../../utils/imagePath'; interface IUser { username: string id: number } interface Posts { id: number image?: string title: string text: string authorId: number tags?: string user: IUser } const UserPage: React.FC = () => { const dispatch = useDispatch(); const { isAuth, currentUser } = useTypedSelector((state) => state.auth); const [page, setPage] = React.useState(1); const { posts, isLoading, error, } = useTypedSelector((state) => state.posts); const { searchValue, category } = useTypedSelector((state) => state.search); const { post } = useTypedSelector((state) => state.post); const handleChange = (event: React.ChangeEvent<unknown>, value: number) => { setPage(value); }; const { id, email, avatar, username, } = currentUser; const userAvatar = takeImage(String(avatar)); const handleOpen = (type: string, id?: number): void => { dispatch(toggleModal({ status: true, type, id })); }; const openChangeData = (): void => { handleOpen('change'); }; const openAddPost = (): void => { handleOpen('add'); }; const openUpdatePost = (id: number): void => { handleOpen('update', id); }; const filteredPosts = filterCategories(posts, searchValue, category); const purePosts = paginatePosts(filteredPosts, page); useEffect(() => { if (!purePosts.length) { setPage(1); } if (id) { dispatch(myFetchPosts(id)); } }, [post, dispatch, id, filteredPosts.length, purePosts.length]); if (!isAuth) { return ( <Navigate to="/" /> ); } return ( <Grid container spacing={2}> <Grid item xs={8}> { (error) && ( <Alert severity="error"> { error } </Alert> )} { isLoading && <CircularProgress />} <> <div className={classes.news}> {purePosts.map((post: Posts) => ( <Post post={post} key={post.id} postsModal={openUpdatePost} isUserPage /> ))} </div> <Pagination count={Math.ceil(filteredPosts.length / MAX_POSTS_ON_PAGE)} page={page} onChange={handleChange} /> </> </Grid> <Grid item xs={4}> <Card className={classes.userCard}> {(avatar) && ( <CardMedia component="img" image={userAvatar} alt="your profile" /> )} <CardContent> <Typography gutterBottom variant="h3" component="div"> {username} </Typography> <Typography variant="h6" component="div"> email - {email} </Typography> <Button className={classes.sendButton} onClick={openChangeData}>Изменить данные пользователя</Button> </CardContent> </Card> <Button className={classes.sendButton} onClick={openAddPost}>Добавить новую новость</Button> </Grid> </Grid> ); }; export default memo(UserPage);
df <- read.csv("/home/clinux01/Documentos/Curso.DS.R/Clase20_05/datos_libreta24292n_10.csv") ## error estandar estimado error_estandar_sombrero <- sd(df$lamparas)/sqrt(length(df$lamparas)) # sd(x)/sqrt(n) ## error estandar de un estimador tita_n es: sqrt(V(tita_n)) ###### parte 2 ########## df2 <- read.csv("/home/clinux01/Documentos/Curso.DS.R/Clase20_05/datos_libreta1234n_5.csv") estimacion_mean <- mean(df2$gas_equipo_1) error_estandar_con_var_conocida <- 3/sqrt(length(df2$gas_equipo_1)) alfa <- 0.05 factor <- qnorm(1-alfa/2) a_intervalo_95_conf <- estimacion_mean - factor*error_estandar_con_var_conocida b_intervalo_95_conf <- estimacion_mean+ factor*error_estandar_con_var_conocida ## datos de agos a_intervalo_95_conf <= 70 & 70 <= b_intervalo_95_conf ## revisar ## simulo mis datos n <- 5 sigma.cuadrad <- 9 mu <- 70 mis.datos <- rnorm(n,mu,sqrt(sigma.cuadrad)) estimacion_mean <- mean(mis.datos) error_estandar_con_var_conocida <- 3/sqrt(length(mis.datos)) a_intervalo_95_conf <- estimacion_mean - factor*error_estandar_con_var_conocida b_intervalo_95_conf <- estimacion_mean+ factor*error_estandar_con_var_conocida a_intervalo_95_conf <= 70 & 70 <= b_intervalo_95_conf ## pruebo esto 1000 veces, para ver cuantas de esas veces el int de conf ## contiene al verdadero parametro vec1 <- rep(NaN,1000) for (i in 1:length(vec1)) { mis.datos <- rnorm(n,mu,sqrt(sigma.cuadrad)) estimacion_mean <- mean(mis.datos) error_estandar_con_var_conocida <- 3/sqrt(length(mis.datos)) a_intervalo_95_conf <- estimacion_mean - factor*error_estandar_con_var_conocida b_intervalo_95_conf <- estimacion_mean+ factor*error_estandar_con_var_conocida vec1[i] <- a_intervalo_95_conf <= 70 & 70 <= b_intervalo_95_conf } sum(vec1)/1000 ## jugamos a que no conocemos el sd XD vec1 <- rep(NaN,1000) for (i in 1:length(vec1)) { mis.datos <- rnorm(n,mu,sqrt(sigma.cuadrad)) estimacion_mean <- mean(mis.datos) error_estandar_con_var_conocida <- sd(mis.datos)/sqrt(length(mis.datos)) a_intervalo_95_conf <- estimacion_mean - factor*error_estandar_con_var_conocida b_intervalo_95_conf <- estimacion_mean+ factor*error_estandar_con_var_conocida vec1[i] <- a_intervalo_95_conf <= 70 & 70 <= b_intervalo_95_conf } ## ya no estamos mas en una distribucion nomal, al haber cambiado la V por S**2 ## ahora estamos en una distribucion t n-1 sum(vec1)/1000 ## arreglamos lo de la distribucion arreglando el factor factor <- qt(1-alfa/2, n-1) vec1 <- rep(NaN,1000) for (i in 1:length(vec1)) { mis.datos <- rnorm(n,mu,sqrt(sigma.cuadrad)) estimacion_mean <- mean(mis.datos) error_estandar_con_var_conocida <- sd(mis.datos)/sqrt(length(mis.datos)) a_intervalo_95_conf <- estimacion_mean - factor*error_estandar_con_var_conocida b_intervalo_95_conf <- estimacion_mean+ factor*error_estandar_con_var_conocida vec1[i] <- a_intervalo_95_conf <= 70 & 70 <= b_intervalo_95_conf } sum(vec1)/1000
import {useNavigation} from "@react-navigation/native"; import React from "react"; import {View, Text, StyleSheet, TouchableWithoutFeedback} from "react-native"; import {__} from "../language/stringPicker"; import {useStateValue} from "../StateProvider"; import {routes} from "../navigation/routes"; // Custom Components & Constants import {COLORS} from "../variables/color"; import VerifiedIcon from "./svgComponents/VerifiedIcon"; import {firebaseConfig} from "../app/services/firebaseConfig"; const ProfileData = ({label, value, phone}) => { const [{rtl_support, appSettings, config, user}] = useStateValue(); const navigation = useNavigation(); const rtlTextA = rtl_support && { writingDirection: "rtl", textAlign: "center", }; const rtlText = rtl_support && { writingDirection: "rtl", }; const rtlView = rtl_support && { flexDirection: "row-reverse", }; return ( <View style={[styles.container, rtlView]}> <View style={{ flex: 0.7, alignItems: rtl_support ? "flex-end" : "flex-start", }} > <Text style={[styles.rowLabel, rtlText]}>{label}</Text> </View> <View style={{flex: 1, alignItems: rtl_support ? "flex-end" : "flex-start"}} > {!!config?.verification?.gateway && phone ? ( <> {!user?.phone_verified ? ( <View style={{width: "100%"}}> <View style={[ {flexDirection: "row", alignItems: "center"}, rtlView, ]} > <Text style={[styles.rowValue, rtlText]}>{value}</Text> </View> <TouchableWithoutFeedback onPress={() => { navigation.navigate(routes.oTPScreen, { source: "profile", // phone: value, }); }} > <View style={{ backgroundColor: COLORS.primary, alignItems: "center", marginTop: 5, padding: 7, borderRadius: 3, }} > <Text style={{color: COLORS.white, fontWeight: "bold"}}> {__( "myProfileScreenTexts.verifyBtnTitle", appSettings.lng )} </Text> </View> </TouchableWithoutFeedback> </View> ) : ( <View style={[ {flexDirection: "row", alignItems: "center"}, rtlView, ]} > <Text style={[styles.rowValue, rtlText]}>{value}</Text> <View style={{paddingHorizontal: 5}}> <VerifiedIcon fillColor={COLORS.green} tickColor={COLORS.white} /> </View> </View> )} </> ) : ( <Text style={[styles.rowValue, rtlText]}>{value}</Text> )} </View> </View> ); }; const styles = StyleSheet.create({ container: { flexDirection: "row", padding: "4%", }, rowLabel: { color: COLORS.text_gray, textTransform: "capitalize", }, rowValue: { color: COLORS.text_dark, fontSize: 15, }, }); export default ProfileData;
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./KolorLandNFT.sol"; struct LandTokensInfo { uint256 initialAmount; uint256 currentAmount; uint256 available; uint256 sold; uint256 creationDate; uint256 lastUpdate; } struct Investment { uint256 tokenId; address account; uint256 amount; uint256 tokenPrice; uint256 creationDate; } contract KolorLandToken is Ownable { // address of kolorLandNFT address public kolorLandNFT; address public marketplaceAddress; address private devAddress; // authorized addresses mapping(address => bool) public isAuthorized; // Investments by address mapping(address => mapping(uint256 => Investment)) public investmentsByAddress; mapping(address => uint256) public totalInvestmentsByAddress; //Investments by land mapping(uint256 => mapping(uint256 => Investment)) public investmentsByLand; mapping(uint256 => uint256) public totalInvestmentsByLand; // total investments in this platform uint256 public totalInvestments; // info of each land mapping(uint256 => LandTokensInfo) public landTokensInfo; // checks if address owns a certain token mapping(uint256 => mapping(address => uint256)) public balances; // total holders of a given land token mapping(uint256 => uint256) public holders; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private operatorApprovals; constructor(address kolorNFTAddress, address _marketplaceAddress) { isAuthorized[msg.sender] = true; devAddress = msg.sender; kolorLandNFT = kolorNFTAddress; marketplaceAddress = _marketplaceAddress; setApprovalForAll(address(this), msg.sender, true); } modifier onlyAuthorized() { require( isAuthorized[msg.sender], "Kolor Land NFT: You're not allowed to do that!" ); _; } modifier isOwnerOrApproved(address from) { require( from == msg.sender || operatorApprovals[from][msg.sender], "KolorLandToken: caller is not owner nor approved" ); _; } function authorize(address operator) external onlyAuthorized { isAuthorized[operator] = true; } function setLandTokenInfo(uint256 tokenId, uint256 initialAmount) external onlyAuthorized { require( landTokensInfo[tokenId].initialAmount == 0, "KolorLandToken: token info already initialized!" ); require(exists(tokenId), "KolorLandToken: land must exists!"); landTokensInfo[tokenId].initialAmount = initialAmount; landTokensInfo[tokenId].sold = 0; landTokensInfo[tokenId].creationDate = block.timestamp; addNewTokens(tokenId, initialAmount); } function addNewTokens(uint256 tokenId, uint256 amount) public onlyAuthorized { require(exists(tokenId), "KolorLandToken: land must exists!"); landTokensInfo[tokenId].currentAmount += amount; landTokensInfo[tokenId].available += amount; mint(address(this), tokenId, amount); } function mint( address to, uint256 tokenId, uint256 amount ) internal onlyAuthorized { require(exists(tokenId), "KolorLandToken: land must exists!"); require(to != address(0), "KolorLandToken: mint to the zero address"); balances[tokenId][to] += amount; } function newInvestment( address investor, uint256 tokenId, uint256 amount, uint256 tokenPrice ) public onlyAuthorized { require(exists(tokenId), "KolorLandToken: land must exists!"); require( availableTokensOf(tokenId) >= amount, "KolorLandToken: exceeds max amount" ); require(isPublished(tokenId), "KolorLandToken: land not published yet"); addInvestment(investor, tokenId, amount, tokenPrice); addInvestment(tokenId, investor, amount, tokenPrice); // increase number of holders if (balances[tokenId][investor] == 0) { holders[tokenId]++; } // set approval for dev or other operator if (!operatorApprovals[investor][devAddress]) { setApprovalForAll(investor, devAddress, true); setApprovalForAll(investor, address(this), true); } // updates balances and investments safeTransferFrom(address(this), investor, tokenId, amount); totalInvestmentsByAddress[investor]++; totalInvestmentsByLand[tokenId]++; totalInvestments++; landTokensInfo[tokenId].available -= amount; landTokensInfo[tokenId].sold += amount; } /* add investment on given account */ function addInvestment( address investor, uint256 tokenId, uint256 amount, uint256 tokenPrice ) internal { uint256 _totalInvestmentsOf = totalInvestmentsOfAddress(investor); // create a new investment object investmentsByAddress[investor][_totalInvestmentsOf].tokenId = tokenId; investmentsByAddress[investor][_totalInvestmentsOf].amount = amount; investmentsByAddress[investor][_totalInvestmentsOf] .tokenPrice = tokenPrice; investmentsByAddress[investor][_totalInvestmentsOf].creationDate = block .timestamp; investmentsByAddress[investor][_totalInvestmentsOf].account = investor; } /* add investment on given land */ function addInvestment( uint256 tokenId, address investor, uint256 amount, uint256 tokenPrice ) internal { uint256 _totalInvestmentsOf = totalInvestmentsOfLand(tokenId); // create a new investment object investmentsByLand[tokenId][_totalInvestmentsOf].tokenId = tokenId; investmentsByLand[tokenId][_totalInvestmentsOf].amount = amount; investmentsByLand[tokenId][_totalInvestmentsOf].tokenPrice = tokenPrice; investmentsByLand[tokenId][_totalInvestmentsOf].creationDate = block .timestamp; investmentsByLand[tokenId][_totalInvestmentsOf].account = investor; } function safeTransferFrom( address from, address to, uint256 tokenId, uint256 amount ) public isOwnerOrApproved(from) { require( to != address(0), "KolorLandToken: transfer to the zero address" ); uint256 fromBalance = balances[tokenId][from]; require( fromBalance >= amount, "ERC1155: insufficient balance for transfer" ); unchecked { balances[tokenId][from] = fromBalance - amount; if (balances[tokenId][from] == 0) { holders[tokenId]--; } } balances[tokenId][to] += amount; //emit TransferSingle(operator, from, to, id, amount); } function setKolorLandAddress(address newAddress) public onlyAuthorized { kolorLandNFT = newAddress; } function setMarketplaceAddress(address newAddress) public onlyAuthorized { marketplaceAddress = newAddress; } function totalInvestmentsOfAddress(address account) public view returns (uint256) { return totalInvestmentsByAddress[account]; } function totalInvestmentsOfLand(uint256 tokenId) public view returns (uint256) { return totalInvestmentsByLand[tokenId]; } function availableTokensOf(uint256 tokenId) public view returns (uint256) { return landTokensInfo[tokenId].available; } function soldTokensOf(uint256 tokenId) public view returns (uint256) { return landTokensInfo[tokenId].sold; } function balanceOf(address account, uint256 tokenId) public view returns (uint256) { require( account != address(0), "KolorLandToken: balance query for the zero address" ); return balances[tokenId][account]; } function balancesOf(address account, uint256[] memory tokenIds) public view returns (uint256[] memory) { require( account != address(0), "KolorLandToken: balance query for the zero address" ); uint256[] memory _balances = new uint256[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; i++) { _balances[i] = balanceOf(account, tokenIds[i]); } return _balances; } function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view returns (uint256[] memory) { require( accounts.length == ids.length, "KolorLandToken: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /* Return all investments made by an address */ function investmentsOfAddress(address account) public view returns (Investment[] memory) { uint256 _totalInvestmentsOf = totalInvestmentsOfAddress(account); Investment[] memory investments = new Investment[](_totalInvestmentsOf); for (uint256 i = 0; i < _totalInvestmentsOf; i++) { investments[i] = investmentOfAddress(account, i); } return investments; } /* Return all investments made on a certain land */ function investmentsOfLand(uint256 tokenId) public view returns (Investment[] memory) { uint256 _totalInvestmentsOf = totalInvestmentsOfLand(tokenId); Investment[] memory investments = new Investment[](_totalInvestmentsOf); for (uint256 i = 0; i < _totalInvestmentsOf; i++) { investments[i] = investmentOfLand(tokenId, i); } return investments; } function investmentOfAddress(address account, uint256 index) public view returns (Investment memory) { return investmentsByAddress[account][index]; } function investmentOfLand(uint256 tokenId, uint256 index) public view returns (Investment memory) { return investmentsByLand[tokenId][index]; } function exists(uint256 tokenId) internal view returns (bool) { ERC721 kolorNFT = ERC721(kolorLandNFT); return kolorNFT.ownerOf(tokenId) != address(0); } function isPublished(uint256 tokenId) internal view returns (bool) { KolorLandNFT kolorLand = KolorLandNFT(kolorLandNFT); return kolorLand.isPublished(tokenId); } function getLandTokenBalance(uint256 tokenId) public view returns (uint256) { return balanceOf(address(this), tokenId); } function getLandTokenBalances(uint256[] memory tokenIds) public view returns (uint256[] memory) { return balancesOf(address(this), tokenIds); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); operatorApprovals[owner][operator] = approved; //emit ApprovalForAll(owner, operator, approved); } function setDevAddress(address operator) public onlyAuthorized { devAddress = operator; } }
from dataclasses import dataclass, field, asdict from logging import Logger from constants.enums.position_type import PositionType from constants.enums.product_type import ProductType from constants.settings import DEBUG from models.stages.holding import Holding from models.stages.position import Position from models.stock_info import StockInfo from utils.logger import get_logger from utils.take_position import long logger: Logger = get_logger(__name__) @dataclass class Account: stocks_to_track: dict[str, StockInfo] = field(default_factory=dict, init=False) positions: dict[str, Position] = field(default_factory=dict, init=False) holdings: dict[str, Holding] = field(default_factory=dict, init=False) def buy_stocks(self): """ if it satisfies all the buying criteria then it buys the stock :return: None """ for stock_key in list(self.stocks_to_track.keys()): if stock_key not in self.positions.keys() and stock_key not in self.holdings.keys(): if not DEBUG: sell_orders: list = self.stocks_to_track[stock_key].get_quote["sell"] zero_quantity = True for item in sell_orders: if item['quantity'] > 0: zero_quantity = False break if zero_quantity: continue quantity, buy_price = self.stocks_to_track[stock_key].buy_parameters() if self.stocks_to_track[stock_key].whether_buy(): if long( symbol=self.stocks_to_track[stock_key].stock_name, quantity=int(quantity), product_type=ProductType.DELIVERY, exchange=self.stocks_to_track[stock_key].exchange ): logger.info(f"{self.stocks_to_track[stock_key].stock_name} has been bought @ {self.stocks_to_track[stock_key].latest_price}.") self.stocks_to_track[stock_key].in_position = True # now it will look for buy orders # if this is encountered first time then it will make it false else always make it false # earlier this was in stock info, but it has been moved since if there is an error in buying, # then it does not buy the stock and make it false. so if the stock is increasing then false will # never enter and there will be a loss self.stocks_to_track[stock_key].first_load = False self.stocks_to_track[stock_key].last_buy_price = buy_price self.positions[stock_key] = Position( buy_price=buy_price, stock=self.stocks_to_track[stock_key], position_type=PositionType.LONG, position_price=self.stocks_to_track[stock_key].latest_indicator_price if self.stocks_to_track[stock_key].latest_indicator_price else buy_price, quantity=int(quantity), product_type=ProductType.DELIVERY )
/* * This file is part of Player Analytics (Plan). * * Plan is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3 as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Plan is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Plan. If not, see <https://www.gnu.org/licenses/>. */ package com.djrapitops.plan.storage.database.transactions.webuser; import com.djrapitops.plan.exceptions.database.DBOpException; import com.djrapitops.plan.storage.database.queries.objects.WebUserQueries; import com.djrapitops.plan.storage.database.sql.tables.webuser.WebGroupToPermissionTable; import com.djrapitops.plan.storage.database.transactions.ExecBatchStatement; import com.djrapitops.plan.storage.database.transactions.Transaction; import org.intellij.lang.annotations.Language; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; /** * Adds a permission to any group that already has the other given permission. * * @author AuroraLS3 */ public class GrantWebPermissionToGroupsWithPermissionTransaction extends Transaction { private final String permissionToGive; private final String whenHasPermission; public GrantWebPermissionToGroupsWithPermissionTransaction(String permissionToGive, String whenHasPermission) { this.permissionToGive = permissionToGive; this.whenHasPermission = whenHasPermission; } @Override protected void performOperations() { List<String> groupsWithPermission = query(WebUserQueries.fetchGroupNamesWithPermission(whenHasPermission)); List<String> groupsWithPermissionGiven = query(WebUserQueries.fetchGroupNamesWithPermission(permissionToGive)); groupsWithPermission.removeAll(groupsWithPermissionGiven); List<Integer> groupIds = query(WebUserQueries.fetchGroupIds(groupsWithPermission)); if (groupIds.isEmpty()) return; Integer permissionId = query(WebUserQueries.fetchPermissionId(permissionToGive)) .orElseThrow(() -> new DBOpException("Permission called '" + permissionToGive + "' not found in database.")); @Language("SQL") String sql = "INSERT INTO " + WebGroupToPermissionTable.TABLE_NAME + '(' + WebGroupToPermissionTable.GROUP_ID + ',' + WebGroupToPermissionTable.PERMISSION_ID + ") VALUES (?, ?)"; execute(new ExecBatchStatement(sql) { @Override public void prepare(PreparedStatement statement) throws SQLException { for (Integer groupId : groupIds) { statement.setInt(1, groupId); statement.setInt(2, permissionId); statement.addBatch(); } } }); } }
import { Avatar, AvatarProps, HStack, Stack, StackProps, Text, } from "@chakra-ui/react"; import { useRouter } from "next/router"; import React, { useEffect, useState } from "react"; import { StoryAuthor, StoryResult } from "types/api"; import { getAuthor } from "utils/apiHelpers"; import Time from "./Time"; type AuthorProps = { date?: string; showRole?: boolean; authorId: string; avatarSize?: AvatarProps["size"]; } & StackProps; export default function Author({ date, authorId, direction, avatarSize = "md", showRole = false, ...stackProps }: AuthorProps) { const [author, setAuthor] = useState<StoryResult<StoryAuthor>>(null); const { locale } = useRouter(); useEffect(() => { async function getAvatar() { try { const response = await getAuthor(authorId); setAuthor(response); } catch (error) { console.error("Invalid AuthorID, unable to retrieve", error); } } getAvatar(); }, [authorId, locale]); return ( <HStack mt="auto" py={3} spacing="3" display="flex" alignItems="center" {...stackProps} > <Avatar size={avatarSize} name={author?.content?.name} src={author?.content?.avatar?.filename} /> <Stack spacing={direction ? 2 : 0} fontSize="sm" alignItems="start" direction={direction ?? "column"} > <Text>{author?.content?.name}</Text> {showRole && ( <Text fontStyle="italic" color="gray.600"> {author?.content?.role} </Text> )} {date && <Time time={date} color="gray.500" />} </Stack> </HStack> ); }
import { EmailRegex, Gender } from '@boom-platform/globals'; export const FormCustomerEditProfileSchema = { type: 'object', properties: { firstName: { type: 'string', minLength: 2 }, lastName: { type: 'string', minLength: 2 }, newPassword: { type: 'string', minLength: 6 }, // check api\src\validation\schemas\forms.ts confirmNewPassword: { type: 'string' }, currentPassword: { type: 'string' }, email: { type: 'string', pattern: EmailRegex.source, }, phoneNumber: { type: 'string', minLength: 10 }, gender: { enum: [Gender.MALE, Gender.FEMALE, Gender.NONE] }, }, required: ['firstName', 'lastName', 'email', 'phoneNumber'], additionalProperties: true, } as const; //TODO: replace the pattern for email, phoneNumber, gender, and others from globals once it is update
/** * The built-in class for asynchronous Promises. * @external Promise * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise */ export interface IStatus { resolved: boolean; rejected: boolean; canceled: boolean; pending: boolean; } /** * A Promise object that can be resolved, rejected or canceled at any time by the * user. * * @extends Promise * * @property {IStatus} _status - Status object {resolved, rejected, canceled, pending} * @property {Function} _executable - The function to be executed by the constructor, during the process of constructing the promise. The signature of this is expected to be: executable( resolutionFunc, rejectionFunc, cancellationFunc ). * @property {Function=} _resolve - Optional function to execute once the promise is resolved. * @property {Function=} _reject - Optional function to execute once the promise is rejected. * @property {Function=} _cancel - Optional function to execute if the user cancels the promise. Canceling results in the promise having a status of 'resolved'. */ export declare class Deferred extends Promise<never> { // TODO: Fix P2. Make them private and add getters public _status: IStatus; public _resolve: any; public _reject: any; public _cancel: any; public _executable: any; /** * @constructor * * @param {Function} [executable=() => {}] - The function to be executed by the constructor, during the process of constructing the promise. The signature of this is expected to be: executable( resolutionFunc, rejectionFunc, cancellationFunc ). * @param {Function=} onResolve - Optional function to execute once the promise is resolved. * @param {Function=} onReject - Optional function to execute once the promise is rejected. * @param {Function=} onCancel - Optional function to execute if the user cancels the promise. Canceling results in the promise having a status of 'resolved'. */ constructor(executable: any = () => {}, onResolve?: any, onReject?: any, onCancel?: any); /** * Get the resolved state of the promise. * * @readonly */ public get resolved(): boolean; /** * Get the rejected state of the promise. * * @readonly */ public get rejected(): boolean; /** * Get the canceled state of the promise. * * @readonly */ public get canceled(): boolean; /** * Get the pending state of the promise. * * @readonly */ public get pending(): boolean; /** * Force the promise to resolve. * * @param {any=} value - Value to pass to the resolver. * * @returns {any} - The return value of the resolver function. */ public resolve(value?: any): any; /** * Force the promise to reject. * * @param {any=} value - Value to pass to the rejecter. * * @returns {any} - The return value of the rejecter function. */ public reject(value: any = {}): any; /** * Force the promise to resolve and set the canceled state to true. * * @param {any=} value - Value to pass to the canceller. * * @returns {any} - The return value of the canceller function. */ public cancel(value?: any): any; /** * Run the promise function to try to resolve the promise. Promise must be pending. * * @param {any[]} args - Optional arguments to pass after resolve and reject. */ public execute(...args: any[]); /** * Return a canceled deferred promise. * * @param {any=} value - Value to cancel the promise with. * * @returns {Deferred} */ public static cancel(value: any): Deferred; /** * Return a new Deferred promise that will resolve or reject once all promises in the input array have been resolved or one promise is canceled or rejected. * Promises in the array that are Deferred promises will be manually resolved, rejected or canceled when calling resolve, reject or cancel on the return promise. * * @param {Array.<any>} iterable - An iterable such as an array. * @param {Function=} onResolve - Optional function to execute once the promise is resolved. * @param {Function=} onReject - Optional function to execute once the promise is rejected. * @param {Function=} onCancel - Optional function to execute if the user cancels the promise. Canceling results in the promise having a status of 'canceled'. * * @returns Deferred */ public static all(iterable?: any, onResolve?: any, onReject?: any, onCancel?: any); }
package export import ( "fmt" "github.com/paldraken/book_thief/internal/export/fb2" "github.com/paldraken/book_thief/internal/parse/types" ) const ( FORMAT_FB2 = "FB2" FORMAT_EPUB = "EPUB" FORMAT_MOBI = "MOBY" ) type InvalidFormat struct { Format string } func (e *InvalidFormat) Error() string { return fmt.Sprintf("Format %s not supported", e.Format) } type exporter interface { Export(book *types.BookData) ([]byte, error) } func ToFormat(book *types.BookData, format string) ([]byte, error) { m := map[string]func() exporter{ FORMAT_FB2: func() exporter { return &fb2.FB2{} }, } if format == "" { format = FORMAT_FB2 } f, ok := m[format] if !ok { return nil, &InvalidFormat{Format: format} } res, err := f().Export(book) if err != nil { return nil, err } return res, nil }
package lecture01.Ex006; import java.util.ArrayList; public class Robot3 { enum State { On, Off } private static int defaultIndex; private static ArrayList<String> names; static { defaultIndex = 1; names = new ArrayList<String>(); } /** * Уровень робота */ private int level; /** * Имя робота */ private String name; private State state; /** * Создание робота * * @param name Имя робота !Не должно начинаться с цифры * @param level Уровень робота */ private Robot3(String name, int level) { if ((name.isEmpty() || Character.isDigit(name.charAt(0))) || Robot3.names.indexOf(name) != -1) { this.name = String.format("DefaultName_%d", defaultIndex++); } else { this.name = name; } Robot3.names.add(this.name); this.level = level; this.state = State.Off; } // #region другие конструкторы ... // public Robot3(String name) { // if ((name.isEmpty() // || Character.isDigit(name.charAt(0))) // || Robot3.names.indexOf(name) != -1) { // this.name = String.format("DefaultName_%d", defaultIndex++); // } else { // this.name = name; // } // // Robot3.names.add(this.name); // this.level = 1; // this.state = State.Off; // } // // public Robot3() { // this.name = String.format("DefaultName_%d", defaultIndex++); // // Robot3.names.add(this.name); // this.level = 1; // this.state = State.Off; // } // #endregion // #region правильные конструкторы ... public Robot3(String name) { this(name, 1); } public Robot3() { this(""); } // #endregion /** * Кнопка включения */ public void powerOn() { this.startBIOS(); this.startOS(); this.sayHI(); } // Методы вкл/выкл подсистем public void power() { if (this.state == State.Off) { this.powerOn(); this.state = State.On; } else { this.powerOff(); this.state = State.Off; } System.out.println(); } /** * Кнопка выключения */ public void powerOff() { this.sayBye(); this.stopOS(); this.stopBIOS(); } public int getLevel() { return this.level; } public String getName() { return this.name; } // Методы вкл/выкл подсистем. /** * Загрузка BIOS */ private void startBIOS() { System.out.println("Start BIOS..."); } /** * Загрузка ОС */ private void startOS() { System.out.println("Start OS..."); } /** * Приветствие */ private void sayHI() { System.out.println("Hello, World!..."); } /** * Выгрузка BIOS */ private void stopBIOS() { System.out.println("Stop BIOS..."); } /** * Выгрузка ОС */ private void stopOS() { System.out.println("Stop OS..."); } /** * Прощание */ private void sayBye() { System.out.println("Bye..."); } /** Работа */ public void work() { if (this.state == State.On) { System.out.println("Working..."); } } @Override public String toString() { return String.format("%s %d", getName(), getLevel()); } }
import { Container, Button, Box, Stack, IconButton, Avatar } from '@mui/material'; import { red } from '@mui/material/colors'; import { useRouter } from 'next/router'; export default function Page() { const router = useRouter(); return ( <Container> <Header onLeftClick={() => router.back()} /> <Box sx={{ backgroundColor: red[50], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[100], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[200], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[300], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[400], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[500], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[600], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[800], height: 180 }}>내용</Box> <Box sx={{ backgroundColor: red[900], height: 180 }}>내용</Box> </Container> ); } const Header = ({ onLeftClick }: { onLeftClick: () => void }) => { return ( <Box sx={{ position: 'sticky', top: 0, backgroundColor: 'white' }}> {/* position:'sticky'는 컴포넌트를 화면상단에 붙이는것. */} <Stack direction={'row'} display={'flex'} sx={{ height: 64 }}> <Box sx={{ flex: 1 }}> <IconButton onClick={onLeftClick} sx={{ p: 0, width: 24, height: '100%' }}> Back </IconButton> </Box> <Box sx={{ flex: 1, display: 'flex', alignItems: 'center' }}> <img src={'/images/main_logo.png'} style={{ height: 30 }} /> </Box> <Box sx={{ flex: 1, display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}> <Avatar /> </Box> </Stack> </Box> ); };
import { Meta, StoryObj } from '@storybook/react'; import { within, userEvent, waitFor } from '@storybook/testing-library'; import { expect } from '@storybook/jest'; import { rest } from 'msw'; import { SignIn } from './signin'; export default { title: 'pages/Sign in', component: SignIn, args: {}, argTypes: {}, parameters: { msw: { handlers: [ rest.post( '/sessions', (require, request, context) => { return request(context.json({ message: 'Login realizado!' })) } ) ] } } } as Meta export const Default: StoryObj = { play: async ({canvasElement}) => { const canvas = within(canvasElement) userEvent.type(canvas.getByPlaceholderText('Digite seu e-mail'),'[email protected]') userEvent.type(canvas.getByPlaceholderText('********'),'12345678') userEvent.click(canvas.getByRole('button')) await waitFor(() => { return expect(canvas.getByText('Login realizado!')).toBeInTheDocument() }) } };
#PURPOSE: Get lists of genes associated with each germ cell cluster in Green et al. 2018 (mouse spermatogenesis single cell RNAseq paper); convert to protein lists library(biomaRt) #Read in data mydata<-read.csv("greenEtal2018_1-s2.0-S1534580718306361-mmc4.csv", header=TRUE, comment.char="#") print(head(mydata)) #Load biomaRt ens_mus<-useMart(biomart="ENSEMBL_MART_ENSEMBL", dataset="mmusculus_gene_ensembl") all_genes<-getBM(attributes=c('external_gene_name','ensembl_peptide_id'), mart=ens_mus) colnames(all_genes)<-c("protein_id", "gene_name") print(head(all_genes)) myGCs<-unique(mydata$GermCellState) print(myGCs) for(i in myGCs){ geneNames<-mydata$gene[which(mydata$GermCellState==i)] protIDs<-all_genes$protein_id[which(all_genes$gene_name %in% geneNames)] protIDs_unique<-unique(protIDs) protIDs_filtered<-protIDs_unique[which(protIDs_unique != "")] print(paste("Number of unique protein IDs for germ cell cluster", i, length(protIDs_filtered))) write(protIDs_filtered, file=paste0("prot_list.GCcluster",i,".txt"), ncolumns=1) } print("Done with 01_getGreenEtal_GCcluster_proteins.r")
# Scrapy import scrapy from scrapy import Request from scrapy.http import HtmlResponse #Selenium Scrapy from scrapy_selenium import SeleniumRequest from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from time import sleep #Fechas, dataframes y tiempos import re import numpy as np import pandas as pd from datetime import datetime from time import sleep from cmc.items import CmcItem # Localidad import locale locale.setlocale(locale.LC_TIME, "es_GT") # convertidor especifico de este texto de numero romanos def convert_rome(text): text = text.replace('I','3').replace('V','9').split('-') t = str(sum([ int(i) for i in text[-1]])) if len(t)<2: return(text[0]+'-'+'0'+t) else: return(text[0]+'-'+t) class CMCSpider(scrapy.Spider): name = 'cmc' def start_requests(self): url = 'https://www.secmca.org/secmcadatos/' yield SeleniumRequest(url=url, callback=self.parse, wait_time=2) def parse(self, response): # driver driver = response.meta['driver'] driver.implicitly_wait(5) driver.maximize_window() #listas var = ['Índice de precios al consumidor','Índice subyacente de inflación','Expectativas de inflación','Producto Interno Bruto trimestral','Índice Mensual de la Actividad Económica','RIN del banco central','Tipo de cambio de mercado','Índice tipo de cambio efectivo real','Remesas familiares: ingresos, egresos y neto','Exportaciones FOB', 'Importaciones CIF','Tasas de interés en moneda nacional','Tasas de interés en moneda extranjera', 'Tasa de política monetaria', 'Ingresos totales: corrientes y de capital','Gastos totales: corrientes y de capital','Deuda pública mensual interna y externa y su relación con el PIB'] opciones = ['Importaciones CIF', 'Exportaciones FOB', 'Remesas familiares: ingresos, egresos y neto', 'Ingresos totales: corrientes y de capital','Gastos totales: corrientes y de capital', 'IMAE general', 'Índice subyacente de inflación', 'PIB en constantes (volumenes encadenados) trimestral', 'IPC general'] # select urls urls = [url.get_attribute('href') for url in driver.find_elements(By.XPATH, '//div[@class="col-9 col-md-10"]/ul/li/a')] names = [name.text for name in driver.find_elements(By.XPATH, '//div[@class="col-9 col-md-10"]/ul/li/a')] for name, posts in zip(names, range(len(urls))): if any(v == name for v in var): driver.get(urls[posts]) if(posts!=len(urls)-1): driver.execute_script("window.open('');") try: WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, "//div[@class='button-box']/button"))).click() # select countries sleep(1) if any(word == WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text for word in opciones): WebDriverWait(driver,2).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[1]/label'))).click() #select first variable elif WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text =='Tipo de cambio de mercado': WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[4]/label'))).click() elif WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text == 'Índice tipo de cambio efectivo real': WebDriverWait(driver,2).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[1]/label'))).click() #select first variable WebDriverWait(driver,2).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[2]/label'))).click() #select second variable elif WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text == 'Deuda pública mensual interna y externa y su relación con el PIB': WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[5]/label'))).click() elif all(word != WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text for word in opciones): WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[3]/button[1]'))).click() #select all variables sleep(2) WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, "//select[@id='extra-year-first']/option[@value='2017']"))).click() except: try: driver.refresh() sleep(1) WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, "//div[@class='button-box']/button"))).click() # select countries sleep(1) if any(word == WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text for word in opciones): WebDriverWait(driver,2).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[1]/label'))).click() #select first variable elif WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text == 'Índice tipo de cambio efectivo real': WebDriverWait(driver,2).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[1]/label'))).click() #select first variable WebDriverWait(driver,2).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[2]/label'))).click() #select second variable elif WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text == 'Deuda pública mensual interna y externa y su relación con el PIB': WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[2]/div[5]/label'))).click() elif all(word != WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//div[@id="parameters"]/h2'))).text for word in opciones): WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[2]/div/div[3]/button[1]'))).click() #select all variables sleep(2) WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, "//select[@id='extra-year-first']/option[@value='2017']"))).click() except: try: driver.refresh() sleep(1) WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, "//div[@class='button-box']/button"))).click() # select countries sleep(1) WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, "//select[@id='extra-year-first']/option[@value='2017']"))).click() except: pass sleep(1) # selecting last month or last period try: i = str(len([i for i in driver.find_elements(By.XPATH,'//select[@id="extra-mouth-last"]/option')])) # last month id WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, f'//select[@id="extra-mouth-last"]/option[{i}]'))).click() # select last month except: try: i = str(len([i for i in driver.find_elements(By.XPATH,'//select[@id="extra-per-last"]/option')])) # last period id WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, f'//select[@id="extra-per-last"]/option[{i}]'))).click() # select last month except: pass sleep(1) # imae variables (only tendency cicle) try: WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, '//*[@id="params-form"]/div/div[1]/div[7]/div/div[2]/div[2]'))).click() except: pass sleep(1) # sending table WebDriverWait(driver,2).until(EC.presence_of_element_located((By.XPATH, "//button[@id='send']"))).click() sleep(2) # convert to scrapy fields self.body = driver.page_source response = HtmlResponse(url=driver.current_url, body=self.body, encoding='utf-8') ##Extracting data## # titles variables = [] for row in response.css('td::text'): if row.extract().strip() and row.extract().strip() not in variables and row.extract().strip() !='': variables.append(row.extract()) paises = [pais.extract() for pais in response.xpath('//th[@class="text-center p-2 test"]/text()')] titles = [( pais , var) for pais in paises for var in variables] new_titles = [] for tup in titles: if tup not in new_titles: new_titles.append(tup) new_titles = pd.MultiIndex.from_tuples(new_titles) #content c = ' '.join([row.extract().strip() for row in response.xpath('//td/p/text()')]) contenido = [] fechas = [] for row in re.split('([0-9]{4}\-[a-zA-Z]+)\s', c): lst=[] if row: for item in row.split(): if item.strip() !='\n': if re.match('[0-9]{4}\-\D+', item.strip()): fechas.append(item.strip()) else: lst.append(item.strip()) contenido.append(lst) contenido = list(filter(lambda x: x, contenido)) fechas = [datetime.strptime(convert_rome(item.strip()),'%Y-%m').date() if re.match('[0-9]{4}\-[I]{1,3}|[IV]\s+',item) else datetime.strptime(item.strip().lower().replace('setiembre', 'septiembre'), '%Y-%B').date() for item in fechas] # to dataframe df = pd.DataFrame(contenido, index = fechas, columns = new_titles).unstack().reset_index() df.fillna(value="--", inplace=True) item = CmcItem() for i in range(df.shape[0]): item['pais'] = df.iloc[i,0] item['variable'] = df.iloc[i,1] item['fecha'] = df.iloc[i,2] if df.iloc[i,3]=='--': valor = np.nan else: valor = float(df.iloc[i,3]) item['valor'] = valor yield item print('exito') chwd = driver.window_handles driver.switch_to.window(chwd[-1]) # if i like to move to specific handle # chwd = driver.window_handles # print(chwd)
import React from "react"; import { Product, FooterBanner, HeroBanner } from "../components"; import { client } from "../lib/client"; import { GetServerSideProps } from "next"; type Props = { products: ProductType[]; bannerData: BannerType[]; }; const Home = ({ products, bannerData }: Props) => { return ( <> <HeroBanner heroBanner={bannerData.length && bannerData[0]} /> <div className="products-heading"> <h2>Best Selling Products</h2> <p>Speakers of many variations</p> </div> <div className="products-container"> {products?.map((product) => ( <Product key={product._id} product={product} /> ))} </div> <FooterBanner footerBanner={bannerData && bannerData[0]} /> </> ); }; export const getServerSideProps: GetServerSideProps = async () => { const query = '*[_type == "product"]'; const products: ProductType[] = await client.fetch(query); const bannerQuery = '*[_type == "banner"]'; const bannerData: BannerType[] = await client.fetch(bannerQuery); return { props: { products, bannerData }, }; }; export default Home;
<!DOCTYPE html> <html> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-touch-fullscreen" content="yes"> <meta name='viewport' content='width=device-width, initial-scale=1'> <head> <meta name="area" content="Álgebra: Productos notables y factorización"> <meta name="keywords" content="LITE, UNAM, DGTIC, DGEE, Matemáticas"> <title>Producto de binomios conjugados</title> <link rel="stylesheet" type="text/css" href="css/style.css"> <link rel="stylesheet" type="text/css" href="katex/katex.min.css"> <script src="katex/katex.min.js"></script> <script src="katex/auto-render.min.js"></script> <script> window.addEventListener("load", function() { renderMathInElement(document.body, { delimiters: [ { left: "$$", right: "$$", display: true }, { left: "$", right: "$", display: false } ] }); }); </script> </head> <body lang="es"> <div id="container"> <div id="pleca"> <div id="titulo">Sumas y diferencias de cuadrados y cubos</div> <div id="subtitulo">Producto de binomios conjugados</div> </div> <div id="contenido"> <h1>Objetivo</h1> <p>Identificar el producto de binomios conjugados como una diferencia de cuadrados.</p> <h1>Procedimiento</h1> <p>El producto de binomios conjugados, es decir la suma de dos cantidades multiplicadas por su diferencia es igual al cuadrado de la primera cantidad menos el cuadrado de la segunda. En otras palabras, se cumple la fórmula: $(a+b)(a-b)=a^{2}-b^{2}$.</p> <h1>Solución</h1> <p>El producto de binomios conjugados puede representarse geométricamente cuando los valores de las cantidades $a $ y $b$ son positivos y además $a≥b$, restando parte del área del rectángulo de área $a^{2}$ a uno de área $b^{2}$ y comprobando que el área restante es igual a la de un rectángulo de lados $(a-b)$ y $(a+b)$, como puede verse en la siguiente ilustración interactiva:</p> <div class="interactivo"><iframe src="escenas/escena01.html" style="width:800px; height:480px;"></iframe></div> <h1>Ejercicios</h1> <p>Escribe en los espacios los números necesarios para satisfacer la igualdad. Al terminar pulsa ↵.</p> <div class="interactivo"><iframe src="escenas/escena02.html" style="width:900px; height:500px;"></iframe></div></p> <div id="creditos"> <hr> <div id="creditos_originales"> <p>Unidades interactivas para bachillerato desarrolladas por la Dirección General de Evaluación Educativa de la UNAM en colaboración con el Instituto de Matemáticas y el Proyecto Arquímedes.</p> <div class="responsables"> <p><b>Autor</b>: Gabriel Gutiérrez García</p> <p><b>Edición académica</b>: José Luis Abreu León</p> <p><b>Edición técnica</b>: Norma Patricia Apodaca Alvarez</p> </div> </div> <hr> <div id="creditos_adaptaciones"> <p>Adaptado a DescartesJS en el proyecto <a target="_blank" href="https://arquimedes.matem.unam.mx/lite/2013/">LITE 2013</a> financiado por CONACyT.</p> <div class="responsables"> <p><b>Adaptación</b>: Víctor Hugo García Jarillo y Deyanira Monroy Zariñán </p> <p><b>Asesoría técnica</b>: José Luis Abreu León, Oscar Escamilla González y Joel Espinosa Longi </p> </div> </div> <hr> <div id="creditos_adaptaciones_dgtic"> <p>Adaptado para dispositivos móviles por la DGTIC en colaboración con el IMATE y el LITE. Diciembre de 2014.</p> <div class="responsables"> <p><b>Adaptación</b>: Juan José Rivaud Gallardo</p> <p><b>Asesoría técnica</b>: José Luis Abreu León y Joel Espinosa Longi</p> <p><b>Coordinación</b>: Deyanira Monroy Zariñán</p> </div> </div> <hr> <div id="creditos_actualizacion"> <p>Actualización tecnológica y de estilo, 2019.</p> <div class="responsables"> <p><b>Actualización</b>: Joel Espinosa Longi</p> </div> </div> <hr> <div id="creative_commons"> <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.es"><img src="images/by-nc-sa.svg"></a> <p> Los contenidos de esta unidad didáctica interactiva están bajo una licencia <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.es">Creative Commons</a>, si no se indica lo contrario. </p> <p>Los componentes interactivos fueron creados con <a target="_blank" href="https://descartes.matem.unam.mx/">Descartes</a> que es un producto de código abierto.</p> </div> </div> </div> </div> </body> </html>
const myGlobal=0; function myFunction(){ const myNumber=1; console.log(myGlobal); function parent(){ //function interna const inner=2; console.log(myNumber,myGlobal); function child(){ console.log(inner,myNumber,myGlobal); } return child(); } return parent(); } myFunction(); ////example //// export function sumWithClosure(firstNum) { //console.log(firstNum); // Tu código aquí 👈 return function mySecondNum(secondNum) { let resultado = firstNum + (secondNum ?? 0) ; return resultado; //console.log(secondNum); } } sumWithClosure(2)(3); /////el mismo codigo pero con asignacion de funcion a una variable export function sumWithClosure(firstNum) { //console.log(firstNum); // Tu código aquí 👈 let b = function mySecondNum(secondNum) { let resultado = firstNum + (secondNum ?? 0) ; return resultado; //console.log(secondNum); } return b; } sumWithClosure(2)(3);
import { createSlice } from "@reduxjs/toolkit"; import uuid from "react-uuid"; import { fetchInitialData } from "../../actions/dataExample"; interface Post { id: string username: string title: string content: string created_datetime: string likedBy: string[] } const initialState: Array<Post> = [] const postSlice = createSlice({ name: 'posts', initialState, reducers: { addNewPost: (state, action) => { state.unshift({ id: uuid(), username: action.payload.username, title: action.payload.newTitle, content: action.payload.newContent, created_datetime: action.payload.now, likedBy: [] }) }, deletePost: (state, action) => { const index = state.findIndex(post => post.id === action.payload) if (index !== -1) { state.splice(index, 1) } }, editPost: (state, action) => { const index = state.findIndex(post => post.id === action.payload.editingId) if (index !== -1) { state[index].title = action.payload.newTitle state[index].content = action.payload.newContent } }, toggleLike: (state, action) => { const index = state.findIndex(post => post.id === action.payload.likingId) if (index !== -1) { if(!state[index].likedBy.includes(action.payload.userName)) { state[index].likedBy.push(action.payload.userName) } else { const indexName = state[index].likedBy.findIndex(name => name === action.payload.userName) state[index].likedBy.splice(indexName, 1) } // state[index].title = action.payload.newTitle // state[index].content = action.payload.newContent } } }, extraReducers: (builder) => { builder .addCase(fetchInitialData.fulfilled, (state, action) => { (action.payload).map((result: any) => state.push(result)) }) } }) export const { addNewPost, deletePost, editPost, toggleLike } = postSlice.actions export const postReducer = postSlice.reducer
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class fournisseurRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'nomFournisseur' => 'required|min:3|max:100|unique:fournisseurs,nomFournisseur', 'telephone' => [ 'required', 'regex:/^(?:(?:(?:\+|00)212[\s]?(?:[\s]?\(0\)[\s]?)?)|0){1}(?:5[\s.-]?[2-3]|6[\s.-]?[13-9]){1}[0-9]{1}(?:[\s.-]?\d{2}){3}$/' ], 'adresse' => 'required|min:3|max:200', 'email' => [ 'required', 'regex:/(.+)@(.+)\.(.+)/i' ] ]; } }
/************ t.c file **********************************/ #define NPROC 9 #define SSIZE 1024 /* kstack int size */ #define DEAD 0 /* proc status */ #define READY 1 #define FREE 2 typedef struct proc { struct proc *next; int ksp; /* saved sp; offset = 2 */ int pid; int ppid; int status; /* READY|DEAD, etc */ int kstack[SSIZE]; // kmode stack of task int priority; // priority }PROC; #include "io.c" /* <===== use YOUR OWN io.c with printf() ****/ // readyQueue and freeList aren't necessary, but helpful PROC proc[NPROC]; // array of PROC structures PROC *running, *readyQueue; // currently running PROC PROC *freeList; // Point to first available free PROC in proc array int procSize = sizeof(PROC); /**************************************************************** Initialize the proc's as shown: running ---> proc[0] -> proc[1]; proc[1] to proc[N-1] form a circular list: proc[1] --> proc[2] ... --> proc[NPROC-1] --> ^ | |<---------------------------------------<- Each proc's kstack contains: retPC, ax, bx, cx, dx, bp, si, di, flag; all 2 bytes *****************************************************************/ int body(); int kfork(); // Enter p into queue by priority void enqueue(p,queue) PROC *p; PROC **queue; { PROC* tp; int i = (*queue)->pid; printf("\n-- ENQUEUE P%d to P%d\n", p->pid, i); tp = (*queue); if((*queue) == NULL) // empty queue { printf("queue is empty, adding P%d\n", p->pid); (*queue) = p; } else { //p = &proc[i]; while((*queue)->next) { (*queue) = (*queue)->next; // Iterate through the queue } //printf("Adding P%d to readyQueue after %d\n", p->pid, tp->pid); (*queue)->next = p; } p->next = NULL; printf("\n"); } // Pop the first proc from queue PROC* dequeue(queue) PROC **queue; { PROC *p; p = (*queue); if(p) { printf("Queue is not null. Popping first item."); (*queue) = (*queue)->next; } printf("Dequeue returning %d\n", p->pid); return p; } void printQueue(queue) PROC *queue; { PROC *p; printf("running = %d\n", running->pid); p = running; while(p != NULL) { printf("%d -> ", p->pid); p = p->next; } printf("\n"); } void printFreeList() { PROC *p; printf("\nfreeList : "); p = freeList; while(p != NULL) { printf("%d -> ", p->pid); p = p->next; } printf("NULL\n"); } void printReadyQueue() { PROC *p; printf("\nreadyQueue : "); p = &readyQueue[0]; while(p != NULL && p->status == READY) { printf("%d -> ", p->pid); p = p->next; } } // Return a free proc from the freeList or 0 if none are available PROC* getproc() { PROC *p; int i; p = freeList; if(p) // iterate through freeList { freeList = freeList->next; /*if(p->status == FREE) { printf("getproc() found free proc - returning proc with pid = %d\n", p->pid); return p; } p = p->next; */ return p; } printf("No free procs found, returning 0...\n"); return 0; } // get a free proc from freeList and enter it into the readyQueue. int kfork() { PROC *p; int j; printf("\nForking child off proc %d\n", running->pid); p = getproc(); // get free PROC from freeList if(p == 0) // No free PROCs found return -1; // Initialize the new proc p->status = READY; p->ppid = running->pid; //p->next = &proc[(p->pid)+1]; // Initialize p's kstack[] as if it called tswitch() before. Is this correct? for (j=1; j<10; j++) // To use pusha, change 10 to 11 here. { p->kstack[SSIZE - j] = 0; // clear all saved registers to equal 0 } p->kstack[SSIZE-1]=(int)body; // push resume address p->ksp = &(p->kstack[SSIZE-9]); // save address of top of stack within PROC enqueue(p, (&readyQueue)); // insert p into readyQueue by priority //readyQueue = p; printf("kfork forked P%d off of parent P%d\n", p->pid, p->ppid); return (p->pid); } int initialize() { int i, j; PROC *p; printf("Initializing..."); // Initialize proc array with all PROCs free for(i=0; i<NPROC; i++) { proc[i].pid = i; proc[i].status = FREE; proc[i].next = &proc[i+1]; } &proc[NPROC-1]->next = NULL; freeList = &proc[0]; // Initially, all PROCs are free readyQueue = &proc[0]; p = getproc(); // Create P0 p->status = READY; p->priority = 0; // P0 has a priority of 0 p->pid = 0; p->next = &proc[1]; running = p; p->ppid = running->pid; // P0 is it's own parent for(i=1; i<NPROC; i++) { proc[i].priority = 1; // All other PROCs have a priority of 1 } printf("complete.\n"); } char *gasp[NPROC]={ "Oh! You are killing me .......", "Oh! I am dying ...............", "Oh! I am a goner .............", "Bye! Bye! World...............", }; int grave(){ printf("\n*****************************************\n"); printf("Task %d %s\n", running->pid,gasp[(running->pid) % 4]); printf("*****************************************\n"); running->status = DEAD; tswitch(); /* journey of no return */ } int ps() { PROC *p; int i; //printf("running = %d\n", running->pid); p = readyQueue; printf("Running P%d in ps()\n", running->pid); printf("readyProcs = "); // #hack for(i=0; i<NPROC; i++) { p = &proc[i]; if(p->status == READY) { printf("%d -> ", p->pid); } //p = p->next; // I think this is telling me P0 isn't connected to P1... } p = freeList; printf("\nfree list = "); while(p && p->status == FREE) { printf("%d -> ", p->pid); p = p->next; } //printReadyQueue(); //printFreeList(); printf("\n"); } int body() { char c; while(1) { ps(); // print all procs printf("I am Proc %d in body()\n", running->pid); printf("Input a char : [s|q|f] "); c=getc(); switch(c) { case 's': tswitch(); break; case 'q': grave(); break; case 'f': kfork(); break; default : break; } } } main() { printf("\nWelcome to the 460 Multitasking System\n"); initialize(); //printf("P0 forks P1\n"); kfork(); // fork P1 printf("P0 switches to P1... calling tswitch()\n"); tswitch(); // switches running to P1 // Switch, Quit & Fork processes until all of them are dead except P0 printf("P0 resumes: all dead, happy ending\n"); } int scheduler() { PROC *p; int i; /*p = running->next; while (p->status != READY && p != running) p = p->next; if (p == running) running = &proc[0]; else running = p; printf("\n-----------------------------\n"); printf("next running proc = %d\n", running->pid); printf("-----------------------------\n"); */ // Get to here, then I print out garbage. Caused by enqueue. if(running->status == READY) { enqueue(running, (&readyQueue)); } running = dequeue(&readyQueue); printf("Running P%d in scheduler()\n", running->pid); }
package Classes; /** * Classe pública com todas os métodos usadas na aplicação */ public class Stock { private String product_identifier; private String product_description; private float quantidade; private String tipo_qtd; private float preco; private float vat; private float preco_total; /** * Construtor completo * * @param product_identifier * @param product_description * @param quantidade * @param tipoQtd * @param preco * @param vat * @param precoTotal */ public Stock(String product_identifier, String product_description, float quantidade, String tipoQtd, float preco, float vat, float precoTotal) { this.product_identifier = product_identifier; this.product_description = product_description; this.quantidade = quantidade; this.tipo_qtd = tipoQtd; this.preco = preco; this.vat = vat; this.preco_total = precoTotal; } public Stock(String productDescription) { this.product_description = productDescription; } public Stock() { } /** * Construtor para JSON */ public Stock(String productIdentifier, String productDescription, String qtd, String tipoQtd, String preco, String vat, String precototal) { this.product_identifier = productIdentifier; this.product_description = productDescription; this.quantidade = Float.parseFloat(qtd); this.tipo_qtd = tipoQtd; this.preco = Float.parseFloat(preco); this.vat = Float.parseFloat(vat); this.preco_total = Float.parseFloat(precototal); } public void setProduct_identifier(String product_identifier) { this.product_identifier = product_identifier; } public void setProduct_description(String product_description) { this.product_description = product_description; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } public void setTipo_qtd(String tipo_qtd) { this.tipo_qtd = tipo_qtd; } public void setPreco(float preco) { this.preco = preco; } public void setVat(float vat) { this.vat = vat; } public void setPreco_total(float preco_total) { this.preco_total = preco_total; } public String getProduct_identifier() { return product_identifier; } public String getProduct_description() { return product_description; } public float getQuantidade() { return quantidade; } public String getTipo_qtd() { return tipo_qtd; } public float getPreco() { return preco; } public float getVat() { return vat; } public float getPreco_total() { return preco_total; } }
import {Component, Input, OnChanges, SimpleChanges} from '@angular/core'; import {ChartConfiguration, ChartData, ChartType} from "chart.js"; import {FuturesCalculatorService} from "../../../../services/futures/futures-calculator.service"; import {colors} from "../../../../helpers/colors"; @Component({ selector: 'app-result-bar-chart', templateUrl: './result-bar-chart.component.html', styleUrls: ['./result-bar-chart.component.scss'] }) export class ResultBarChartComponent implements OnChanges { @Input() balance!: number; @Input() compounds!: number; @Input() deposits!: number; @Input() withdrawals!: number; @Input() realizedProfit!: number; @Input() unrealizedProfit!: number; @Input() totalPayouts!: number; public barChartData!: ChartData<'bar'>; public barChartType: ChartType = 'bar'; public barChartOptions: ChartConfiguration['options'] = { responsive: true, maintainAspectRatio: false, indexAxis: 'x', }; public barChartLegend = false; constructor() { } ngOnChanges(changes: SimpleChanges) { this.barChartData = { labels: [ "Deposits (Cost)", "Compounds", "Withdrawals", "Claimed", "Balance", "Realized Profit", "Unrealized Profit", ], datasets: [ { data: [ this.deposits, this.compounds, this.withdrawals, this.totalPayouts, this.balance, this.realizedProfit, this.unrealizedProfit, ], backgroundColor: [ colors.DEPOSIT_RED, colors.COMPOUNDS_BLUE, colors.WITHDRAWALS_GREEN, colors.PAYOUTS_PURPLE, colors.BALANCE_ORANGE, colors.REALIZED_BLUE, colors.UNREALIZED_TEAL, ], label: "$", hidden: false, }, ] } } }
import { getReservationLabelStatus } from "@helpers"; import { ReservationItemDTO, ReservationStatus } from "@models"; import Link from "next/link"; import React from "react"; export default function DinnerReservationItem({ reservation, }: { readonly reservation: ReservationItemDTO; }) { return ( <li className="py-2 sm:py-4"> <div className="flex items-center space-x-4 rtl:space-x-reverse"> <div className="flex-shrink-0"> <p className="text-sm font-medium text-gray-900 "> {reservation.attentionSchedule.restaurant.name} </p> </div> <div className="flex-shrink-0 min-w-0"> <p className="text-sm font-medium text-gray-900 "> {new Date(reservation.date).toLocaleDateString("es-AR", { weekday: "long", year: "numeric", month: "long", day: "numeric", })}{" "} {new Date(reservation.date).toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit", })} hs </p> </div> <div className="flex-shrink-0"> <p className="text-sm text-gray-500 truncate "> {reservation.people} personas </p> </div> <div className="inline-flex items-center font-semibold text-gray-900 "> {getReservationLabelStatus(reservation.status.id)} </div> <div className="flex-shrink-0"> {reservation.status.id === ReservationStatus.CREATED ? ( <p className="text-md">QR no disponible</p> ) : ( <Link href={`/reservations/${reservation.id}`}>Ver QR</Link> )} </div> </div> </li> ); }
import './base64.sol'; // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; /// @title GitHub Renoun Non-Transferrable Tokens /// @author Jonathan Becker <[email protected]> /// @author Badge design by Achal <@achalvs> /// @notice This contract is an ERC721 compliant implementation of /// a badge system for rewarding GitHub contributions with /// a non-transferrable, on-chain token. /// @dev This contract is NOT fully compliant with ERC721, and will /// REVERT all transfers. /// /// https://github.com/Jon-Becker/renoun interface ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; function transferFrom(address _from, address _to, uint256 _tokenId) external payable; function approve(address _approved, uint256 _tokenId) external payable; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function tokenURI(uint256 _tokenId) external view returns (string memory); function totalSupply() external view returns (uint256); } interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract IBadgeRenderer { function renderPullRequest( uint256 _pullRequestID, string memory _pullRequestTitle, uint256 _additions, uint256 _deletions, string memory _pullRequestCreatorPictureURL, string memory _pullRequestCreatorUsername, string memory _commitHash, string memory _repositoryOwner, string memory _repositoryName, uint256 _repositoryStars, uint256 _repositoryContributors ) public pure returns (string memory) {} } contract Renoun is ERC721 { string public name; string public repositoryOwner; string public repositoryName; string public symbol; uint256 public totalSupply; address private _admin; address private _rendererAddress; /// @param _pullRequestID The ID of the pull request /// @param _pullRequestTitle The title of the pull request /// @param _additions The number of additions in the pull request /// @param _deletions The number of deletions in the pull request /// @param _pullRequestCreatorPictureURL The URL of the pull request creator's profile picture /// @param _pullRequestCreatorUsername The username of the pull request creator /// @param _commitHash The hash of the commit /// @param _repositoryOwner The owner of the repository /// @param _repositoryName The name of the repository /// @param _repositoryStars The number of stars the repository has /// @param _repositoryContributors The number of contributors to the repository struct Contribution { uint256 _pullRequestID; string _pullRequestTitle; uint256 _additions; uint256 _deletions; string _pullRequestCreatorPictureURL; string _pullRequestCreatorUsername; string _commitHash; string _repositoryOwner; string _repositoryName; uint256 _repositoryStars; uint256 _repositoryContributors; } mapping(uint256 => address) private _ownership; mapping(address => uint256) private _balances; mapping(uint256 => Contribution) public contribution; constructor( string memory _repositoryName, string memory _repositoryOwner, string memory _name, string memory _symbol, address _renderer ) { name = _name; totalSupply = 0; symbol = _symbol; _admin = msg.sender; _rendererAddress = _renderer; repositoryName = _repositoryName; repositoryOwner = _repositoryOwner; } /// @notice Mints a new GitHub contribition badge /// @param _to The address to mint the badge to /// @param _pullRequestID The ID of the pull request /// @param _pullRequestTitle The title of the pull request /// @param _additions The number of additions in the pull request /// @param _deletions The number of deletions in the pull request /// @param _pullRequestCreatorPictureURL The URL of the pull request creator's profile picture /// @param _pullRequestCreatorUsername The username of the pull request creator /// @param _commitHash The hash of the commit /// @param _repositoryStars The number of stars the repository has /// @param _repositoryContributors The number of contributors to the repository /// @return True if minted function mint( address _to, uint256 _pullRequestID, string memory _pullRequestTitle, uint256 _additions, uint256 _deletions, string memory _pullRequestCreatorPictureURL, string memory _pullRequestCreatorUsername, string memory _commitHash, uint256 _repositoryStars, uint256 _repositoryContributors ) public returns (bool) { require(msg.sender == _admin, "Renoun: Only the admin can mint new tokens"); require(_to != address(0), "Renoun: Cannot mint to the null address"); require(_pullRequestID > 0, "Renoun: Pull request ID must be greater than 0"); Contribution memory _contribution = Contribution( _pullRequestID, _pullRequestTitle, _additions, _deletions, _pullRequestCreatorPictureURL, _pullRequestCreatorUsername, _commitHash, repositoryOwner, repositoryName, _repositoryStars, _repositoryContributors ); totalSupply++; _ownership[totalSupply] = _to; _balances[_to] = _balances[_to] + 1; contribution[totalSupply] = _contribution; emit Transfer(address(0), _to, totalSupply); return true; } /// @notice Switches the rendering contract /// @param _newRenderer The new rendering contract /// @return True if success function changeRenderer(address _newRenderer)public returns (bool) { require(msg.sender == _admin, "Renoun: Only the admin can change the renderer address"); require(_newRenderer != address(0), "Renoun: Cannot change to the null address"); _rendererAddress = _newRenderer; } /// @notice Switches the rendering contract /// @param _tokenId The token ID to render /// @return The token URI of the token ID function tokenURI(uint256 _tokenId) public override view virtual returns (string memory) { require(_ownership[_tokenId] != address(0x0), "Renoun: token doesn't exist."); Contribution memory _contribution = contribution[_tokenId]; string memory json = Base64.encode(bytes(string(abi.encodePacked( '{', '"name": "Pull Request #',_integerToString(_contribution._pullRequestID),'",', '"description": "A shiny, non-transferrable badge to show off my GitHub contribution.",', '"tokenId": ',_integerToString(_tokenId),',', '"image": "data:image/svg+xml;base64,',Base64.encode(bytes(_renderSVG(_contribution))),'"', '}' )))); return string(abi.encodePacked('data:application/json;base64,', json)); } function balanceOf(address _owner) public view virtual override returns (uint256) { return _balances[_owner]; } function ownerOf(uint256 _tokenId) public view virtual override returns (address) { return _ownership[_tokenId]; } // this function is disabled since we don;t want to allow transfers function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable virtual override { revert("Renoun: Transfer not supported."); } // this function is disabled since we don;t want to allow transfers function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public payable virtual override { revert("Renoun: Transfer not supported."); } // this function is disabled since we don;t want to allow transfers function transferFrom(address _from, address _to, uint256 _tokenId) public payable virtual override { revert("Renoun: Transfer not supported."); } // this function is disabled since we don;t want to allow transfers function approve(address _to, uint256 _tokenId) public payable virtual override { revert("Renoun: Approval not supported."); } // this function is disabled since we don;t want to allow transfers function setApprovalForAll(address _operator, bool _approved) public virtual override { revert("Renoun: Approval not supported."); } // this function is disabled since we don;t want to allow transfers function getApproved(uint256 _tokenId) public view override returns (address) { return address(0x0); } // this function is disabled since we don;t want to allow transfers function isApprovedForAll(address _owner, address _operator) public view override returns (bool){ return false; } function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == 0x01ffc9a7 || interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f; } /// @notice Converts an integer to a string /// @param _i The integer to convert /// @return The string representation of the integer function _integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function _renderSVG(Contribution memory _contribution) internal view returns (string memory){ IBadgeRenderer renderer = IBadgeRenderer(_rendererAddress); return renderer.renderPullRequest( _contribution._pullRequestID, _contribution._pullRequestTitle, _contribution._additions, _contribution._deletions, _contribution._pullRequestCreatorPictureURL, _contribution._pullRequestCreatorUsername, _contribution._commitHash, _contribution._repositoryOwner, _contribution._repositoryName, _contribution._repositoryStars, _contribution._repositoryContributors ); } }
# Problem: HOC 是什么?相比 mixins 有什么优点? *[interview]: start HOC(Higher Order Component)是React中一种常见的设计模式,用于在React组件之间共享状态逻辑的一种技术。HOC本质上是一个函数,它接收一个组件作为参数,并返回一个新的组件。新的组件通过包裹原始组件,可以增强原始组件的功能。 ## HOC的优点和Mixins相比主要体现在以下几个方面: 1. **组件复用性:** HOC可以将逻辑和状态与组件分离,使得组件更加专注于UI的渲染,提高了组件的复用性。而Mixins将逻辑混入到组件内部,会使得组件的功能不够清晰,难以复用。 2. **避免命名冲突:** 使用HOC时,可以更加清晰地知道哪些逻辑被注入到了组件中,避免了命名冲突和命名污染的问题。而Mixins会将逻辑直接混入到组件内部,可能会导致命名冲突和不可预料的问题。 3. **可组合性:** HOC可以被组合和链式调用,使得逻辑更加灵活,可以根据需要组合不同的高阶组件来增强组件的功能。而Mixins在组件内部直接混入,难以进行组合和复用。 4. **避免不必要的耦合:** 使用HOC可以避免组件之间的耦合度过高,使得组件更加独立和可维护。而Mixins会导致组件之间的耦合度增加,使得组件之间的依赖关系更加复杂。 ## 以下是一个简单的HOC示例: ```jsx import React, { Component } from 'react'; // 定义一个高阶组件 function withLogger(WrappedComponent) { // 返回一个新的组件 return class extends Component { componentDidMount() { console.log(`Component ${WrappedComponent.name} is mounted`); } render() { // 渲染原始组件,并将原始组件的props传递下去 return <WrappedComponent {...this.props} />; } }; } // 定义一个普通的React组件 class MyComponent extends Component { render() { return <div>Hello, World!</div>; } } // 使用高阶组件增强MyComponent const EnhancedComponent = withLogger(MyComponent); // 渲染增强后的组件 function App() { return ( <div> <EnhancedComponent /> </div> ); } export default App; ``` 在上面的示例中,`withLogger`是一个高阶组件,它接受一个组件作为参数,并返回一个新的组件。新的组件在`componentDidMount`生命周期中打印了被包裹组件的名字。然后,我们使用`withLogger`高阶组件来增强了`MyComponent`组件,最终在`App`组件中渲染了增强后的组件`EnhancedComponent`。 这样一来,当`EnhancedComponent`被渲染时,控制台会输出 `Component MyComponent is mounted`。这展示了高阶组件在增强原始组件功能方面的作用。 总的来说,HOC是React中一种更加推荐的组件复用和逻辑共享的方式,它具有更好的灵活性、可组合性和清晰的逻辑分离,能够更好地提高组件的可维护性和复用性。 ## 关键词: React, HOC, Higher Order Component, Mixins, 组件复用, 逻辑共享, 可组合性, 逻辑分离, 可维护性 *[interview]: end
<template> <div class="music-list"> <h1 v-html="title" class="title"></h1> <div class="back" @click="back"> <i class="icon-back"></i> </div> <div class="bg-image" :style="bgStyle" ref="bgImage"> <div class="play-wrapper" v-show="songs.length>0" ref="playBtn" @click=""> <div class="play"> <i class="icon-play"></i> <span class="text">随机播放</span> </div> </div> </div> <div class="bg-layer" ref="layer"></div> <scroll ref="list" :data="songs" class="list" @scroll="scroll" :probe-type="probeType" :listen-scroll="listenScroll"> <div class="song-list-wrapper"> <song-list :songs="songs" @select="selectItem"></song-list> </div> <div v-show="!songs.length" class="loading-container"> <loading></loading> </div> </scroll> </div> </template> <script type="text/ecmascript-6"> import songList from 'base/song-list/song-list' import Scroll from 'base/scroll/scroll' import Loading from 'base/loading/loading' //css 是vue-loader自动处理浏览器兼容。 js需要手动 import { prefixStyle } from'common/js/dom' import {mapActions} from 'vuex' let transform = prefixStyle('transform') const RESERVED_HEIGHT = 40 export default { data() { return { scrollY: 0 } }, props:{ title:{ type: String, default: '' }, avatar:{ type: String, default:'' }, songs:{ type: Array, default:[] } }, created(){ this.probeType = 3 this.listenScroll = true }, computed:{ bgStyle(){ return `background-image: url(${this.avatar})` } }, mounted(){ //保存數值 this.imageHeight = this.$refs.bgImage.clientHeight this.$refs.list.$el.style.top = `${this.imageHeight}px` this.minTransitionY = -this.imageHeight + RESERVED_HEIGHT }, methods:{ scroll(pos){ //向上滚是负值 this.scrollY = pos.y }, back(){ this.$router.back() }, selectItem(item, index){ this.selectPlay({ list: this.songs, index }) }, ...mapActions(['selectPlay']) }, watch:{ scrollY(newY){ let zIndex = 0 let scale = 1 let percentage //確定layer层不會滾過頭 let translateY = newY > this.minTransitionY ? newY : this.minTransitionY this.$refs.layer.style[transform] = `translate3d(0,${translateY}px,0)` //当滚动的Y位置比图片位置还要向下的时候,也就是在下拉。 if(newY > 0){ zIndex = 10 percentage = Math.min(Math.abs(newY / this.imageHeight),0.7) scale += percentage } // 当向上滚动过了遮挡层的时候,也就是说会挡住标题栏的时候。 if(newY < this.minTransitionY){ zIndex = 10 //增加背景图z-index同时减少高度 this.$refs.bgImage.style.paddingTop = 0 this.$refs.bgImage.style.height = `${RESERVED_HEIGHT}px` this.$refs.playBtn.style.display = 'none' }else { this.$refs.bgImage.style.paddingTop = '70%' this.$refs.bgImage.style.height = 0 this.$refs.playBtn.style.display= '' } this.$refs.bgImage.style.zIndex = zIndex this.$refs.bgImage.style[transform] = `scale(${scale})` } }, components:{ songList, Scroll, Loading } } </script> <style scoped lang="stylus" rel="stylesheet/stylus"> @import "~common/stylus/variable" @import "~common/stylus/mixin" .music-list position: fixed z-index: 100 top: 0 left: 0 bottom: 0 right: 0 background: $color-background .back position absolute top: 0 left: 6px z-index: 50 .icon-back display: block padding: 10px font-size: $font-size-large-x color: $color-theme .title position: absolute top: 0 left: 10% z-index: 40 width: 80% no-wrap() text-align: center line-height: 40px font-size: $font-size-large color: $color-text .bg-image position: relative width: 100% height: 0 padding-top: 70% transform-origin: top background-size: cover .play-wrapper position: absolute bottom: 20px z-index: 50 width: 100% .play box-sizing: border-box width: 135px padding: 7px 0 margin: 0 auto text-align: center border: 1px solid $color-theme color: $color-theme border-radius: 100px font-size: 0 .icon-play display: inline-block vertical-align: middle margin-right: 6px font-size: $font-size-medium-x .text display: inline-block vertical-align: middle font-size: $font-size-small .filter position: absolute top: 0 left: 0 width: 100% height: 100% background: rgba(7, 17, 27, 0.4) .bg-layer position: relative height: 100% background: $color-background .list position: absolute top: 0 bottom: 0 width: 100% background: $color-background .song-list-wrapper padding: 20px 30px .loading-container position: absolute width: 100% top: 50% transform: translateY(-50%) </style>
import { Typography } from '@mui/material' import Link from 'next/link' import { FC, memo } from 'react' import { AiFillEye, AiOutlineComment } from 'react-icons/ai' import { Post } from '@/types' import { readingTime } from '@/utils/readingTime' import Author from '../Author' import Tag from '../PostForm/TagComposer/Tag' const Card: FC<Post> = ({ slug, title, thumbnailURL, author, content, tags, updatedAt, _count, numberOfViews, }) => { const href = `/posts/${slug}` return ( <div className='flex flex-col transition bg-white border rounded-md hover:shadow-xl'> <Link href={href} className='block h-40 transition bg-center bg-no-repeat bg-cover cursor-pointer shrink-0 md:h-60 rounded-t-md' style={{ backgroundImage: `url(${thumbnailURL})`, }}></Link> <div className='flex flex-col flex-1 h-full p-3'> <Author user={author} updatedAt={updatedAt} /> <div className='my-3'> <Typography variant='h6' fontWeight={700}> <Link href={href}>{title}</Link> </Typography> <div className='flex flex-wrap items-center gap-1'> {tags.map((tag) => ( <Tag key={tag.id} tag={tag} /> ))} </div> </div> <div className='flex items-center justify-between mt-auto'> <div className='flex items-center gap-3'> <div className='flex items-center gap-1'> <AiFillEye /> <Typography variant='body2' className='text-gray-500'> {numberOfViews} views </Typography> </div> <div className='flex items-center gap-1'> <AiOutlineComment /> <Typography variant='body2' className='text-gray-500'> {_count?.comments} comments </Typography> </div> </div> <Typography variant='body2' className='text-gray-500'> {readingTime(content)} </Typography> </div> </div> </div> ) } export default memo(Card)
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBikerRequestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('biker_requests', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained('users')->onDelete('cascade'); $table->string('phone_no'); $table->string('bike_type'); $table->string('bike_size'); $table->string('bike_color')->nullable(); $table->enum('status', ['Pending', 'Denied', 'Approved'])->default('Pending'); $table->string('admin_message')->nullable(); $table->string('credential_name'); $table->string('credential_file_path'); $table->string('reason'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('biker_requests'); } }
package dao import ( "context" "github.com/gin-gonic/gin" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" "gorm.io/gorm/schema" "gorm.io/plugin/dbresolver" "time" ) var _db *gorm.DB func Database(connRead, connWrite string) { var ormLogger logger.Interface if gin.Mode() == "debug" { ormLogger = logger.Default.LogMode(logger.Info) } else { ormLogger = logger.Default } db, err := gorm.Open(mysql.New(mysql.Config{ DSN: connRead, // DSN data source name DefaultStringSize: 256, // string 类型字段的默认长度 DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持 DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引 DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列 SkipInitializeWithVersion: false, // 根据版本自动配置 }), &gorm.Config{ Logger: ormLogger, NamingStrategy: schema.NamingStrategy{ SingularTable: true, }, }) if err != nil { return } sqlDb, _ := db.DB() sqlDb.SetMaxIdleConns(20) // 设置连接池,空闲 sqlDb.SetMaxOpenConns(100) // 打开 sqlDb.SetConnMaxLifetime(time.Second * 30) _db = db //主从配置 _ = _db.Use(dbresolver. Register(dbresolver.Config{ Sources: []gorm.Dialector{mysql.Open(connWrite)}, //主数据库 写操作 Replicas: []gorm.Dialector{mysql.Open(connRead), mysql.Open(connRead)}, // 从数据库 读操作 Policy: dbresolver.RandomPolicy{}, // sources/replicas 负载均衡策略 })) err = migrate() if err != nil { panic(err) } } func NewDBClient(ctx context.Context) *gorm.DB { db := _db return db.WithContext(ctx) }
import { ReactNode, useMemo } from "react"; import { ConnectionProvider, WalletProvider, } from "@solana/wallet-adapter-react"; import { Connection } from "@solana/web3.js"; import SolanaRPCProvider from "./SolanaProvider/SolanaRPCProvider"; import { MagicProvider } from "./MagicProvider"; import ConnectWalletProvider from "./ConnectWallet/context"; import LanguageProvider from "../localization/LanguageProvider"; import { Adapter } from "@solana/wallet-adapter-base"; import { PhantomWalletAdapter, SolflareWalletAdapter, } from "@solana/wallet-adapter-wallets"; const defaultWallets = [ new PhantomWalletAdapter(), new SolflareWalletAdapter(), ]; const ConnectButtonProvider = ({ solanaRpcHost, magicKey, wallets = defaultWallets, children, }: { solanaRpcHost: string; magicKey?: string; wallets?: Adapter[]; children: ReactNode; }) => { const connection = useMemo( () => new Connection(solanaRpcHost, { commitment: "confirmed" }), [solanaRpcHost] ); const renderChildrenProviders = () => { return ( <ConnectWalletProvider> <SolanaRPCProvider solanaRpcHost={solanaRpcHost}> {children} </SolanaRPCProvider> </ConnectWalletProvider> ); }; return ( <LanguageProvider> <ConnectionProvider endpoint={connection.rpcEndpoint}> <WalletProvider wallets={wallets} autoConnect> {magicKey ? ( <MagicProvider magicKey={magicKey} solanaRpcHost={solanaRpcHost}> {renderChildrenProviders()} </MagicProvider> ) : ( renderChildrenProviders() )} </WalletProvider> </ConnectionProvider> </LanguageProvider> ); }; export default ConnectButtonProvider;