text
stringlengths
184
4.48M
/** * @file capteurs.h * * @author GOURDON Arnaud * PREVOST Theophile * * @brief Fonctions permettant la lecture des donnees des capteurs. */ #ifndef __CAPTEURS_H__ #define __CAPTEURS_H__ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #ifndef ADC_CHANNEL #define ADC_CHANNEL 0x500 #endif #ifndef I2C_SLAVE #define I2C_SLAVE 0x0703 #endif // Fichier correspondant aux peripheriques de la carte #define ADC_DEVICE "/dev/adc" #define I2C_DEVICE "/dev/i2c0" // Bit de configuration du registre de temperature #define CONFIG_TEMP_OS 0x80 #define CONFIG_TEMP_R0 0x40 #define CONFIG_TEMP_R1 0x20 #define CONFIG_TEMP_F0 0x10 #define CONFIG_TEMP_F1 0x08 #define CONFIG_TEMP_POL 0x04 #define CONFIG_TEMP_TM 0x02 #define CONFIG_TEMP_SD 0x01 /** * @struct t_captors_data * @brief Structure comprenant les valeurs physiques des differents capteurs * (Temperature, pression et humidite) */ typedef struct s_captors_data { double T; /**< Temperature (en C) */ double P; /**< Pression (en hPA) */ double RH; /**< Humidite (en %) */ } t_captors_data, * t_ptr_captors_data; /** * @struct t_tendances * @brief Structure comprenant les tendances des differents capteurs * (Temperature, pression et humidite). * Croissant si > 0 / Decroissant si < 0 */ typedef struct s_tendances { int T; /**< Temperature (en C) */ int P; /**< Pression (en hPA) */ int RH; /**< Humidite (en %) */ } t_tendances, * t_ptr_tendances; /** * @brief Permet de modifier le registre de configuration * de la sonde de temperature. * @param fd Descripteur de fichier du peripherique (bus I2C). * @param mask Masque de bits de configuration de la forme : OS R1 R0 F1 F0 POL TM S avec : - OS : OS/ALERT - F1/F0 : Fault queue mode - POL : Polarity mode - TM : Thermostat mode - SD : Shutdown mode * @return EXIT_SUCCESS ou EXIT_FAILURE */ extern int config_temperature(int fd, unsigned char mask); /** * @brief Lecture de la temperature. * @param fd Descripteur de fichier du peripherique (bus I2C). * @param T Parametre de sortie. Valeur de la temperature mesuree (en C). * @return EXIT_SUCCESS ou EXIT_FAILURE */ extern int lire_temperature(int fd, double * T); /** * @brief Lecture du niveau d'humidite. * @param fd Descripteur de fichier du peripherique (CAN). * @param T Valeur de la temperature ambiante. * @param RH Parametre de sortie. Valeur de l'humidite mesuree (en pourcent). * @return EXIT_SUCCESS ou EXIT_FAILURE */ extern int lire_humidite(int fd, double T, double * RH); /** * @brief Lecture du niveau de pression. * @param fd Descripteur de fichier du peripherique (CAN). * @param P Parametre de sortie. Valeur de la pression mesuree (en hPA). * @return EXIT_SUCCESS ou EXIT_FAILURE */ extern int lire_pression(int fd, double * P); /** * @brief Lectures des donnees de tous les capteurs. * @param p Parametre de sortie. Valeurs des differentes sondes. * @return EXIT_SUCCESS ou EXIT_FAILURE */ extern int lire_donnees_capteurs(t_ptr_captors_data p); #endif /* __CAPTEURS_H__ */
using DomainLayer.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; using RepositoryLayer; using RepositoryLayer.implimentation; using RepositoryLayer.Interfaces; using ServiceLayer.Services.Contract; using ServiceLayer.Services.Implimentations; using System.Net.NetworkInformation; using System.Web.Helpers; using UserManger.Models; using UserManger.Service; var builder = WebApplication.CreateBuilder(args); var configuration = builder.Configuration; // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext<RecipeDbContext>(option=> { option.UseSqlServer(builder.Configuration.GetConnectionString("ConnString")); option.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); builder.Services.AddScoped<IRecipe, RecipeService>(); builder.Services.AddScoped<IIngredients, IngredientsService>(); builder.Services.AddScoped(typeof(IRepository<>),typeof(RepositoryImplementation<>)); builder.Services.AddScoped<Iuser, userServices>(); builder.Services.AddScoped<IRateAndReview, RateAndReviewService>(); builder.Services.AddScoped<ICategory,CategoryServicecs>(); builder.Services.AddScoped<IFavorite, FavoriteService>(); builder.Services.AddScoped<IPlanner, PlannerService>(); builder.Services.AddScoped<IShoppingList,ShoppingListService>(); builder.Services.AddScoped<IFollow,FollowerService>(); builder.Services.AddScoped<IComment, CommentService>(); builder.Services.Configure<FormOptions>(o => { o.ValueLengthLimit = int.MaxValue; o.MultipartBodyLengthLimit = int.MaxValue; o.MemoryBufferThreshold = int.MaxValue; }); builder.Services.Configure<DataProtectionTokenProviderOptions>(option => option.TokenLifespan = TimeSpan.FromHours(10)); //configuration email var emailConfig = configuration .GetSection("EmailConfiguration") .Get<EmailConfigration>(); builder.Services.AddSingleton(emailConfig); builder.Services.AddScoped<IEmail, EmailService>(); //identy builder.Services.AddIdentity<IdentityUser, IdentityRole>(). AddEntityFrameworkStores<RecipeDbContext>(). AddDefaultTokenProviders(); //authentication builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }); //cahe builder.Services.AddMemoryCache(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Resourcess")), RequestPath = new PathString("/Resourcess") }); app.UseCors(policy=>policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); app.UseAuthorization(); app.MapControllers(); app.Run();
import React, { useEffect } from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; /* Components */ import { FlexContainer } from "./FlexContainer"; import Spinner from "./Spinner"; import Image from "./Image"; /* Data */ import Interactive_Interface from "../../assets/illustration/Interactive_Interface.svg" // import MainLogoSrc from "../../assets/logo-rmit.png"; import learning_English from "../../assets/illustration/learning_English.svg"; import Quiz from "../../assets/illustration/Quiz.svg"; /* Styled Components */ const MainCont = styled(FlexContainer)` width: 80vw; height: 90vh; margin: 5vh auto; background-color: ${props => props.theme.screenColor}; @media (max-width: 820px) { width: 70vw; flex-direction: column; } `; const SideCont = styled(FlexContainer)` width: 90%; flex-direction: column; justify-content: space-between; margin-right: 5vw; `; const InputCont = styled(FlexContainer)` flex-direction: column; width: ${props => (props.isCreateAccount ? "100%" : "70%")}; height: ${props => (props.isCreateAccount ? "100%" : "90%")}; padding: 3%; background-color: lightblue; border-radius: 30px; `; const StyledTitle = styled.p` color: ${props => props.theme.fontColorWhite}; font-weight: 700; font-size: 2.5vw; margin: 2vw; `; /* AutoSlideshow*/ const SlideShow = styled.div` margin: 0 auto; overflow: hidden; width: 35vw; max-width: 600px; @media (max-width: 820px) { display: none; } `; const SlideShowSlider = styled.div` white-space: nowrap; transition: ease 1000ms; `; const Slide = styled.div` display: inline-block; position: relative; height: 40vh; width: 100%; `; const SlideShowDots = styled.div` text-align: center; `; const SlideShowDot = styled.div` display: inline-block; height: 15px; width: 15px; border-radius: 50%; cursor: pointer; margin: 0 5px; background-color: ${props => props.isCurrentSlide ? props.theme.mainBlue : props.theme.darkGrey}; `; const Desc = styled.p` position: absolute; width: auto; height: 0; left: 0; right: 0; top: 0; bottom: 0; margin: auto; text-align: center; font-weight: 700; font-size: 2vw; color: ${props => props.theme.slideMsg}; `; const AutoSlideshow = ({ images, delayTime }) => { const [currentIdx, setCurrentIdx] = React.useState(0); const timeoutRef = React.useRef(null); const ImgStyle = { width: "100%", height: "100%", filter: "brightness(40%)" }; const resetTimeout = () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; const handleChangeIdx = () => { const numOfImg = images.length; resetTimeout(); timeoutRef.current = setTimeout( () => setCurrentIdx(prevIndex => prevIndex === numOfImg - 1 ? 0 : prevIndex + 1 ), delayTime ); }; useEffect(() => { handleChangeIdx(); return () => { resetTimeout(); }; }, [currentIdx]); return ( <SlideShow> <SlideShowSlider style={{ transform: `translate3d(${-currentIdx * 100}%, 0, 0)` }}> {images.map((item, index) => ( <Slide key={index}> <Image src={item.src} style={ImgStyle} /> <Desc>{item.desc}</Desc> </Slide> ))} </SlideShowSlider> <SlideShowDots> {images.map((item, index) => ( <SlideShowDot key={index} isCurrentSlide={currentIdx === index} onClick={() => { setCurrentIdx(index); }}></SlideShowDot> ))} </SlideShowDots> </SlideShow> ); }; /* Data */ const imagesData = [ { src: learning_English, desc: "Choose from different courses!" }, { src: Interactive_Interface, desc: "Different UI\nfor visual and text learners" }, { src: Quiz, desc: "Test your knowledge!", }, ]; const AccPageTemplate = ({ children, pageTitle, isCreateAccount, isSpinnerVisible, }) => { return ( <MainCont> <SideCont> {/* <Image src={MainLogoSrc} alt={"Particeps Main Logo Image"} style={{ width: "30vw", height: "30vh", }} /> */} <AutoSlideshow images={imagesData} delayTime={4000} /> </SideCont> <InputCont isCreateAccount={isCreateAccount}> <StyledTitle>{pageTitle}</StyledTitle> {children} </InputCont> <Spinner isVisible={isSpinnerVisible} isFullSize /> </MainCont> ); }; AccPageTemplate.propTypes = { pageTitle: PropTypes.string.isRequired, isCreateAccount: PropTypes.bool, isSpinnerVisible: PropTypes.bool, }; export default AccPageTemplate;
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GenericPlatform/HttpRequestImpl.h" #include "Interfaces/IHttpResponse.h" #include "PlatformHttp.h" /** * Apple implementation of an Http request */ class FAppleHttpNSUrlSessionRequest : public FHttpRequestImpl { public: // implementation friends friend class FAppleHttpNSUrlSessionResponse; //~ Begin IHttpBase Interface virtual FString GetURL() const override; virtual FString GetURLParameter(const FString& ParameterName) const override; virtual FString GetHeader(const FString& HeaderName) const override; virtual TArray<FString> GetAllHeaders() const override; virtual FString GetContentType() const override; virtual int32 GetContentLength() const override; virtual const TArray<uint8>& GetContent() const override; //~ End IHttpBase Interface //~ Begin IHttpRequest Interface virtual FString GetVerb() const override; virtual void SetVerb(const FString& Verb) override; virtual void SetURL(const FString& URL) override; virtual void SetContent(const TArray<uint8>& ContentPayload) override; virtual void SetContent(TArray<uint8>&& ContentPayload) override; virtual void SetContentAsString(const FString& ContentString) override; virtual bool SetContentAsStreamedFile(const FString& Filename) override; virtual bool SetContentFromStream(TSharedRef<FArchive, ESPMode::ThreadSafe> Stream) override; virtual void SetHeader(const FString& HeaderName, const FString& HeaderValue) override; virtual void AppendToHeader(const FString& HeaderName, const FString& AdditionalHeaderValue) override; virtual void SetTimeout(float InTimeoutSecs) override; virtual void ClearTimeout() override; virtual TOptional<float> GetTimeout() const override; virtual bool ProcessRequest() override; virtual void CancelRequest() override; virtual EHttpRequestStatus::Type GetStatus() const override; virtual const FHttpResponsePtr GetResponse() const override; virtual void Tick(float DeltaSeconds) override; virtual float GetElapsedTime() const override; //~ End IHttpRequest Interface /** * Constructor * * @param InSession - NSURLSession session used to create NSURLSessionTask to retrieve the response */ explicit FAppleHttpNSUrlSessionRequest(NSURLSession* InSession); /** * Destructor. Clean up any connection/request handles */ virtual ~FAppleHttpNSUrlSessionRequest(); private: /** * Create the session connection and initiate the web request * * @return true if the request was started */ bool StartRequest(); /** * Process state for a finished request that no longer needs to be ticked * Calls the completion delegate */ void FinishedRequest(); /** * Close session/request handles and unregister callbacks */ void CleanupRequest(); private: /** This is the NSMutableURLRequest, all our Apple functionality will deal with this. */ NSMutableURLRequest* Request; /** This is the session our request belongs to */ NSURLSession* Session; /** This is the Task associated to the sessionin charge of our request */ NSURLSessionTask* Task; /** Flag whether the request payload source is a file */ bool bIsPayloadFile; /** The request payload length in bytes. This must be tracked separately for a file stream */ int32 ContentBytesLength; /** The response object which we will use to pair with this request */ TSharedPtr<class FAppleHttpNSUrlSessionResponse,ESPMode::ThreadSafe> Response; /** Array used to retrieve back content set on the ObjC request when calling GetContent*/ mutable TArray<uint8> StorageForGetContent; /** Current status of request being processed */ EHttpRequestStatus::Type CompletionStatus; /** Start of the request */ double StartRequestTime; /** Time taken to complete/cancel the request. */ float ElapsedTime; }; @class FAppleHttpNSUrlSessionResponseDelegate; /** * Apple implementation of an Http response */ class FAppleHttpNSUrlSessionResponse : public IHttpResponse { private: // Delegate implementation. Keeps the response state and data FAppleHttpNSUrlSessionResponseDelegate* ResponseDelegate; /** Request that owns this response */ const FAppleHttpNSUrlSessionRequest& Request; public: // implementation friends friend class FAppleHttpNSUrlSessionRequest; //~ Begin IHttpBase Interface virtual FString GetURL() const override; virtual FString GetURLParameter(const FString& ParameterName) const override; virtual FString GetHeader(const FString& HeaderName) const override; virtual TArray<FString> GetAllHeaders() const override; virtual FString GetContentType() const override; virtual int32 GetContentLength() const override; virtual const TArray<uint8>& GetContent() const override; //~ End IHttpBase Interface //~ Begin IHttpResponse Interface virtual int32 GetResponseCode() const override; virtual FString GetContentAsString() const override; //~ End IHttpResponse Interface /** * Check whether headers are available. */ bool AreHeadersAvailable() const; /** * Check whether a response is ready or not. */ bool IsReady() const; /** * Check whether a response had an error. */ bool HadError() const; /** * Check whether a response had a connection error. */ bool HadConnectionError() const; /** * Get the number of bytes received so far */ const int32 GetNumBytesReceived() const; /** * Get the number of bytes sent so far */ const int32 GetNumBytesWritten() const; /** * Constructor * * @param InRequest - original request that created this response */ FAppleHttpNSUrlSessionResponse(const FAppleHttpNSUrlSessionRequest& InRequest); /** * Destructor */ virtual ~FAppleHttpNSUrlSessionResponse(); };
package eth_test import ( "encoding/json" "os" "path/filepath" "reflect" "testing" "github.com/stretchr/testify/require" "github.com/ethereum-optimism/optimism/op-service/eth" ) type dataJson struct { Data map[string]any `json:"data"` } // TestAPIGenesisResponse tests that json unmarshaling a json response from a // eth/v1/beacon/genesis beacon node call into a APIGenesisResponse object // fills all existing fields with the expected values, thereby confirming that // APIGenesisResponse is compatible with the current beacon node API. // This also confirms that the [sources.L1BeaconClient] correctly parses // responses from a real beacon node. func TestAPIGenesisResponse(t *testing.T) { require := require.New(t) var resp eth.APIGenesisResponse require.Equal(1, reflect.TypeOf(resp.Data).NumField(), "APIGenesisResponse changed, adjust test") path := filepath.Join("testdata", "eth_v1_beacon_genesis_goerli.json") jsonStr, err := os.ReadFile(path) require.NoError(err) require.NoError(json.Unmarshal(jsonStr, &resp)) require.NotZero(resp.Data.GenesisTime) jsonMap := &dataJson{Data: make(map[string]any)} require.NoError(json.Unmarshal(jsonStr, jsonMap)) genesisTime, err := resp.Data.GenesisTime.MarshalText() require.NoError(err) require.Equal(jsonMap.Data["genesis_time"].(string), string(genesisTime)) } // TestAPIConfigResponse tests that json unmarshaling a json response from a // eth/v1/config/spec beacon node call into a APIConfigResponse object // fills all existing fields with the expected values, thereby confirming that // APIGenesisResponse is compatible with the current beacon node API. // This also confirms that the [sources.L1BeaconClient] correctly parses // responses from a real beacon node. func TestAPIConfigResponse(t *testing.T) { require := require.New(t) var resp eth.APIConfigResponse require.Equal(1, reflect.TypeOf(resp.Data).NumField(), "APIConfigResponse changed, adjust test") path := filepath.Join("testdata", "eth_v1_config_spec_goerli.json") jsonStr, err := os.ReadFile(path) require.NoError(err) require.NoError(json.Unmarshal(jsonStr, &resp)) require.NotZero(resp.Data.SecondsPerSlot) jsonMap := &dataJson{Data: make(map[string]any)} require.NoError(json.Unmarshal(jsonStr, jsonMap)) secPerSlot, err := resp.Data.SecondsPerSlot.MarshalText() require.NoError(err) require.Equal(jsonMap.Data["SECONDS_PER_SLOT"].(string), string(secPerSlot)) } // TestAPIGetBlobSidecarsResponse tests that json unmarshaling a json response from a // eth/v1/beacon/blob_sidecars/<X> beacon node call into a APIGetBlobSidecarsResponse object // fills all existing fields with the expected values, thereby confirming that // APIGenesisResponse is compatible with the current beacon node API. // This also confirms that the [sources.L1BeaconClient] correctly parses // responses from a real beacon node. func TestAPIGetBlobSidecarsResponse(t *testing.T) { require := require.New(t) path := filepath.Join("testdata", "eth_v1_beacon_blob_sidecars_7422094_goerli.json") jsonStr, err := os.ReadFile(path) require.NoError(err) var resp eth.APIGetBlobSidecarsResponse require.NoError(json.Unmarshal(jsonStr, &resp)) require.NotEmpty(resp.Data) require.Equal(5, reflect.TypeOf(*resp.Data[0]).NumField(), "APIBlobSidecar changed, adjust test") require.Equal(1, reflect.TypeOf(resp.Data[0].SignedBlockHeader).NumField(), "SignedBeaconBlockHeader changed, adjust test") require.Equal(5, reflect.TypeOf(resp.Data[0].SignedBlockHeader.Message).NumField(), "BeaconBlockHeader changed, adjust test") require.NotZero(resp.Data[0].Blob) require.NotZero(resp.Data[1].Index) require.NotZero(resp.Data[0].KZGCommitment) require.NotZero(resp.Data[0].KZGProof) require.NotZero(resp.Data[0].SignedBlockHeader.Message.Slot) require.NotZero(resp.Data[0].SignedBlockHeader.Message.ParentRoot) require.NotZero(resp.Data[0].SignedBlockHeader.Message.BodyRoot) require.NotZero(resp.Data[0].SignedBlockHeader.Message.ProposerIndex) require.NotZero(resp.Data[0].SignedBlockHeader.Message.StateRoot) }
// MovieItem.tsx import React from "react"; import { FaStar } from "react-icons/fa"; // import { useNavigate } from 'react-router-dom'; // interface MovieItemProps { // movie: Movie; // handleMovieClick: (movieId: number) => void; // } interface Movie { id: number; // url: string; title: string; year: number; rating: number; genres: string[]; large_cover_image: string; } interface Props{ movie: Movie; } const MovieItem: React.FC<Props> = ({ movie }) => { // const navigate = useNavigate(); const { id, title, year, rating, genres, large_cover_image } = movie; console.log(genres) // const handleViewDetail = () => { // navigate(`/details${id}`); // }; return ( <div className="group"> <div className="relative border-4 border-white m-3 p-3 w-48 h-auto rounded-md hover:cursor-pointer hover:border-ytsthemecolor hover:transition duration-700" key={id}> <img src={large_cover_image} alt={title} className="w-48 h-auto" /> <div className="hidden group-hover:block text-white"> <a className=" hover:bg-black hover:bg-opacity-65 hover:transition duration-1000 absolute top-0 left-0 h-full w-full flex flex-col gap-7 justify-center items-center" href={`details/${id}`}> <h1 className="text-3xl"><FaStar /></h1> <p className="font-bold text-3xl">{rating}/10</p> <p className="font-bold">{genres?.slice(0,3).map(genre=>( <h4>{genre}</h4> ))}</p> <button className="group-hover:bg-ytsthemecolor p-2 m-3 hover:transition duration-1000 rounded-md" >View Detail</button> </a> </div> </div> <h2 className="mx-3 px-3 font-bold">{title.slice(0, 20)}</h2> <p className="mx-3 px-3 text-gray-400">{year}</p> </div> ); }; export default MovieItem;
//@version=5 // @description Methods associated with Pitchfork and Pitchfork Drawing. Depends on the library PitchforkTypes for Pitchfork/PitchforkDrawing objects which in turn use DrawingTypes for basic objects Point/Line/LineProperties. Also depends on DrawingMethods for related methods library("PitchforkMethods", overlay = true) import HeWhoMustNotBeNamed/DrawingTypes/2 as dr import HeWhoMustNotBeNamed/DrawingMethods/2 import HeWhoMustNotBeNamed/PitchforkTypes/2 as p method get(p.Fork this, string key)=>key== "ratio"? str.tostring(this.ratio) : key == "include"? str.tostring(this.include) : na // @function Converts PitchforkTypes/Fork object to string representation // @param this PitchforkTypes/Fork object // @returns string representation of PitchforkTypes/Fork export method tostring(p.Fork this)=> str = '' if(not na(this)) keys = array.from("ratio", "include") keyValues = array.new<string>() for key in keys keyValues.push('"'+key+'":'+'"'+this.get(key)+'"') str := '{'+array.join(keyValues, ",")+'}' str // @function Converts Array of PitchforkTypes/Fork object to string representation // @param this Array of PitchforkTypes/Fork object // @returns string representation of PitchforkTypes/Fork array export method tostring(array<p.Fork> this)=> str = '' if(not na(this)) values = array.new<string>() for fork in this values.push(fork.tostring()) str := '['+array.join(values, ",")+']' str method get(p.PitchforkProperties this, string key)=>key == "forks"? str.tostring(this.forks.tostring()) : key == "type"? this.type : key == "inside"? (this.inside? 'true': 'false'): na // @function Converts PitchforkTypes/PitchforkProperties object to string representation // @param this PitchforkTypes/PitchforkProperties object // @param sortKeys If set to true, string output is sorted by keys. // @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys // @returns string representation of PitchforkTypes/PitchforkProperties export method tostring(p.PitchforkProperties this, bool sortKeys = false, int sortOrder = 1)=> str = '' if(not na(this)) keys = array.from("ratios", "type", "inside") keyValues = array.new<string>() if(sortKeys and not na(sortOrder) and sortOrder!=0) keys.sort(sortOrder>0? order.ascending : order.descending) for key in keys keyValues.push('"'+key+'":'+'"'+this.get(key)+'"') str := '{'+array.join(keyValues, ",")+'}' str method get(p.PitchforkDrawingProperties this, string key)=>key == "extend"? (this.extend?'true':'false') : key == "fillTransparency"? str.tostring(this.fillTransparency) : key == "fill"? (this.fill? 'true': 'false'): na // @function Converts PitchforkTypes/PitchforkDrawingProperties object to string representation // @param this PitchforkTypes/PitchforkDrawingProperties object // @param sortKeys If set to true, string output is sorted by keys. // @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys // @returns string representation of PitchforkTypes/PitchforkDrawingProperties export method tostring(p.PitchforkDrawingProperties this, bool sortKeys = false, int sortOrder = 1)=> str = '' if(not na(this)) keys = array.from("extend", "fill", "fillTransparency") keyValues = array.new<string>() if(sortKeys and not na(sortOrder) and sortOrder!=0) keys.sort(sortOrder>0? order.ascending : order.descending) for key in keys keyValues.push('"'+key+'":'+'"'+this.get(key)+'"') str := '{'+array.join(keyValues, ",")+'}' str method get(p.Pitchfork this, string key)=>key == "a"? this.a.tostring() : key == "b"? this.b.tostring() : key == "c"? this.c.tostring() : key == "properties"? this.properties.tostring(): key == "dProperties"? this.dProperties.tostring() : na // @function Converts PitchforkTypes/Pitchfork object to string representation // @param this PitchforkTypes/Pitchfork object // @param sortKeys If set to true, string output is sorted by keys. // @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys // @returns string representation of PitchforkTypes/Pitchfork export method tostring(p.Pitchfork this, bool sortKeys = false, int sortOrder = 1)=> str = '' if(not na(this)) keys = array.from("a", "b", "c", "properties", "dProperties") keyValues = array.new<string>() if(sortKeys and not na(sortOrder) and sortOrder!=0) keys.sort(sortOrder>0? order.ascending : order.descending) for key in keys keyValues.push('"'+key+'":'+'"'+this.get(key)+'"') str := '{'+array.join(keyValues, ",")+'}' str getParrallelPoint(p1Start, p1End, p2Start)=> priceDiff = p1Start.price-p2Start.price barDiff = p1Start.bar - p2Start.bar barTimeDiff = p1Start.bartime - p2Start.bartime dr.Point.new(p1End.price-priceDiff, p1End.bar-barDiff, p1End.bartime - barTimeDiff) // @function Creates PitchforkTypes/PitchforkDrawing from PitchforkTypes/Pitchfork object // @param this PitchforkTypes/Pitchfork object // @returns PitchforkTypes/PitchforkDrawing object created export method createDrawing(p.Pitchfork this)=> this.lProperties := na(this.lProperties)? dr.LineProperties.new() : this.lProperties this.properties := na(this.properties)? p.PitchforkProperties.new() : this.properties this.dProperties := na(this.dProperties)? p.PitchforkDrawingProperties.new(commonColor = this.lProperties.color) : this.dProperties if(na(this.properties.forks)) this.properties.forks := array.new<p.Fork>() if(this.properties.forks.size()==0) this.properties.forks.push(p.Fork.new(0.5, this.lProperties.color, true)) this.properties.forks.push(p.Fork.new(1.0, this.lProperties.color, true)) if(na(this.dProperties.commonColor)) this.dProperties.commonColor := this.lProperties.color dr.Point p1 = this.properties.type == "schiff"? dr.Point.new((this.a.price+this.b.price)/2, this.a.bar, this.a.bartime) : this.properties.type == "mschiff"? dr.Point.new((this.a.price+this.b.price)/2, int((this.a.bar+this.b.bar)/2), int((this.a.bartime+this.b.bartime)/2)): this.a dr.Point p2 = this.properties.inside? this.c : dr.Point.new((this.b.price+this.c.price)/2, int((this.b.bar+this.c.bar)/2), int((this.a.bartime+this.b.bartime)/2)) dr.Point p3 = dr.Point.new(2*p2.price-p1.price, 2*p2.bar-p1.bar, 2*p2.bartime-p1.bartime) baseLineProperties = dr.LineProperties.copy(this.lProperties) baseLineProperties.extend := this.dProperties.extend? extend.right : extend.none medianLine = dr.Line.new(p1, p2, this.lProperties) array<dr.Line> forkLines = array.new<dr.Line>() array<dr.Linefill> fills = array.new<dr.Linefill>() forkLines.push(dr.Line.new(p2, p3, baseLineProperties)) array<color> fillColors = array.new<color>() for [i, fork] in this.properties.forks if(fork.include) forkColor = na(fork.forkColor) or fork.forkColor == color(na) or this.dProperties.forceCommonColor? this.dProperties.commonColor : fork.forkColor diffPriceB = (this.b.price-p2.price)*fork.ratio diffBarB = int((this.b.bar-p2.bar)*fork.ratio) diffBarTimeB = int((this.b.bartime-p2.bar)*fork.ratio) forkLineProperties = dr.LineProperties.copy(baseLineProperties) forkLineProperties.color := forkColor dr.Point p1Edgeb = dr.Point.new(p2.price+diffPriceB, p2.bar+diffBarB, p2.bartime+diffBarTimeB) dr.Point p2Edgeb = getParrallelPoint(p2, p3, p1Edgeb) dr.Line forkLineEdgeB = dr.Line.new(p1Edgeb, p2Edgeb, forkLineProperties) forkLines.push(forkLineEdgeB) fillColors.push(forkColor) if(not this.properties.inside) dr.Point p1Edgec = dr.Point.new(p2.price-diffPriceB, p2.bar-diffBarB, p2.bartime-diffBarTimeB) dr.Point p2Edgec = getParrallelPoint(p2, p3, p1Edgec) dr.Line forkLineEdgeC = dr.Line.new(p1Edgec, p2Edgec, forkLineProperties) forkLines.unshift(forkLineEdgeC) fillColors.unshift(forkColor) if(this.dProperties.fill) for [index, forkColor] in fillColors fills.push(dr.Linefill.new(forkLines.get(index), forkLines.get(index+1), forkColor, this.dProperties.fillTransparency)) baseLine = dr.Line.new(array.first(forkLines).start, array.last(forkLines).start, this.lProperties) this.drawing := p.PitchforkDrawing.new(medianLine, baseLine, forkLines, fills) this.drawing // @function Creates PitchforkTypes/PitchforkDrawing array from PitchforkTypes/Pitchfork array of objects // @param this array of PitchforkTypes/Pitchfork object // @returns array of PitchforkTypes/PitchforkDrawing object created export method createDrawing(array<p.Pitchfork> this)=> array<p.PitchforkDrawing> drawings = array.new<p.PitchforkDrawing>() if(not na(this)) for pitchfork in this drawings.push(pitchfork.createDrawing()) drawings // @function draws from PitchforkTypes/PitchforkDrawing object // @param this PitchforkTypes/PitchforkDrawing object // @returns PitchforkTypes/PitchforkDrawing object drawn export method draw(p.PitchforkDrawing this)=> this.medianLine.draw() this.baseLine.draw() this.forkLines.draw() this.linefills.draw() this // @function deletes PitchforkTypes/PitchforkDrawing object // @param this PitchforkTypes/PitchforkDrawing object // @returns PitchforkTypes/PitchforkDrawing object deleted export method delete(p.PitchforkDrawing this)=> this.medianLine.delete() this.baseLine.delete() this.linefills.delete() this.forkLines.delete() this // @function deletes underlying drawing of PitchforkTypes/Pitchfork object // @param this PitchforkTypes/Pitchfork object // @returns PitchforkTypes/Pitchfork object deleted export method delete(p.Pitchfork this)=> if(not na(this)) this.drawing.delete() this // @function deletes array of PitchforkTypes/PitchforkDrawing objects // @param this Array of PitchforkTypes/PitchforkDrawing object // @returns Array of PitchforkTypes/PitchforkDrawing object deleted export method delete(array<p.PitchforkDrawing> this)=> if not na(this) for drawing in this drawing.delete() this // @function deletes underlying drawing in array of PitchforkTypes/Pitchfork objects // @param this Array of PitchforkTypes/Pitchfork object // @returns Array of PitchforkTypes/Pitchfork object deleted export method delete(array<p.Pitchfork> this)=> if not na(this) for pitchfork in this pitchfork.delete() this // @function deletes array of PitchforkTypes/PitchforkDrawing objects and clears the array // @param this Array of PitchforkTypes/PitchforkDrawing object // @returns void export method clear(array<p.PitchforkDrawing> this)=> if not na(this) while(this.size()!=0) this.pop().delete() // @function deletes array of PitchforkTypes/Pitchfork objects and clears the array // @param this Array of Pitchfork/Pitchfork object // @returns void export method clear(array<p.Pitchfork> this)=> if(not na(this)) while(this.size()!=0) this.pop().delete() // ###################################################################### Tests ############################################################# // import HeWhoMustNotBeNamed/ZigzagTypes/1 as zg // import HeWhoMustNotBeNamed/ZigzagMethods/1 // import HeWhoMustNotBeNamed/utils/1 as ut // import HeWhoMustNotBeNamed/Logger/1 as l // var logger = l.Logger.new(minimumLevel = 'DEBUG') // logger.init() // theme = input.string('Dark', title='Theme', options=['Light', 'Dark'], group='Generic Settings', // tooltip='Chart theme settings. Line and label colors are generted based on the theme settings. If dark theme is selected, '+ // 'lighter colors are used and if light theme is selected, darker colors are used.') // zigzagLength = input.int(13, step=5, minval=3, title='Length', group='Zigzag', tooltip='Zigzag length for level 0 zigzag') // depth = input.int(50, "Depth", step=25, maxval=500, group='Zigzag', tooltip='Zigzag depth refers to max number of pivots to show on chart') // useRealTimeBars = input.bool(true, 'Use Real Time Bars', group='Zigzag', tooltip = 'If enabled real time bars are used for calculation. Otherwise, only confirmed bars are used') // typeTooltip = 'Handle Type' + // '\n\tregular - Pivot A' + // '\n\tschiff - X of Pivot A and y from median of Pivot A and B' + // '\n\tmschiff - X and Y are median of Pivot A and Pivot B' + // '\n\nNeck Type' + // '\n\tmedian - median of Pivot B and Pivot C' + // '\n\tinside - Pivot C' // pitchforkType = input.string("regular", "Type", ["regular", "schiff", "mschiff"], group="Pitchfork", inline="t") // neckType = input.string('median', '', ['median', 'inside'], group="Pitchfork", inline="t", tooltip=typeTooltip) // inside = neckType == 'inside' // ratioFrom = input.float(0.25, 'Ratio', minval=0.0, maxval=0.5, group='Pitchfork', inline='r') // ratioTo = input.float(1, '', minval=0.5, maxval=1.618, group='Pitchfork', inline='r', tooltip='Range of ratio for which drawing pitchfork is allowed') // useConfirmedPivot = input.bool(true, 'Use Confirmed Pivots', group="Pitchfork", tooltip="If set to true, uses last confirmed pivot and ignores the current moving pivot") // includeRatio1 = input.bool(false, '', inline='r1', group='Forks') // ratio1 = input.float(0.236, '', inline='r1', group='Forks') // color1 = input.color(#f77c80, '', inline='r1', group='Forks') // includeRatio2 = input.bool(false, '', inline='r1', group='Forks') // ratio2 = input.float(0.382, '', inline='r1', group='Forks') // color2 = input.color(#ffb74d, '', inline='r1', group='Forks') // includeRatio3 = input.bool(true, '', inline='r2', group='Forks') // ratio3 = input.float(0.500, '', inline='r2', group='Forks') // color3 = input.color(#fff176, '', inline='r2', group='Forks') // includeRatio4 = input.bool(false, '', inline='r2', group='Forks') // ratio4 = input.float(0.618, '', inline='r2', group='Forks') // color4 = input.color(#81c784, '', inline='r2', group='Forks') // includeRatio5 = input.bool(false, '', inline='r3', group='Forks') // ratio5 = input.float(0.786, '', inline='r3', group='Forks') // color5 = input.color(#42bda8, '', inline='r3', group='Forks') // includeRatio6 = input.bool(false, '', inline='r3', group='Forks') // ratio6 = input.float(0.886, '', inline='r3', group='Forks') // color6 = input.color(#4dd0e1, '', inline='r3', group='Forks') // includeRatio7 = input.bool(true, '', inline='r4', group='Forks') // ratio7 = input.float(1.000, '', inline='r4', group='Forks') // color7 = input.color(#5b9cf6, '', inline='r4', group='Forks') // includeRatio8 = input.bool(false, '', inline='r4', group='Forks') // ratio8 = input.float(1.130, '', inline='r4', group='Forks') // color8 = input.color(#9575cd, '', inline='r4', group='Forks') // includeRatio9 = input.bool(false, '', inline='r5', group='Forks') // ratio9 = input.float(1.272, '', inline='r5', group='Forks') // color9 = input.color(#ba68c8, '', inline='r5', group='Forks') // includeRatio10 = input.bool(false, '', inline='r5', group='Forks') // ratio10 = input.float(1.382, '', inline='r5', group='Forks') // color10 = input.color(#f06292, '', inline='r5', group='Forks') // includeRatio11 = input.bool(false, '', inline='r6', group='Forks') // ratio11 = input.float(1.618, '', inline='r6', group='Forks') // color11 = input.color(#faa1a4, '', inline='r6', group='Forks') // includeRatio12 = input.bool(false, '', inline='r6', group='Forks') // ratio12 = input.float(2.000, '', inline='r6', group='Forks') // color12 = input.color(#4caf50, '', inline='r6', group='Forks') // extend = input.bool(true, "Extend", group="Display", tooltip = "Extend fork lines to right") // fill = input.bool(true, "Fill", group="Display", inline='f') // transparency = input.int(95, "Transparency", group="Display", inline='f', tooltip = "Fill Forkline with background color") // offset = useRealTimeBars? 0 : 1 // indicators = matrix.new<float>() // indicatorNames = array.new<string>() // themeColors = ut.getColors(theme) // var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, depth, offset) // zigzag.calculate(array.from(high, low), indicators, indicatorNames) // startIndex = useConfirmedPivot? 1:0 // includes = array.from(includeRatio1, includeRatio2, includeRatio3, includeRatio4, includeRatio5, includeRatio6, // includeRatio7, includeRatio8, includeRatio9, includeRatio10, includeRatio11, includeRatio12) // ratios = array.from(ratio1, ratio2, ratio3, ratio4, ratio5, ratio6, ratio7, ratio8, ratio9, ratio10, ratio11, ratio12) // colors = array.from(color1, color2, color3, color4, color5, color6, color7, color8, color9, color10, color11, color12) // array<p.Fork> forks = array.new<p.Fork>() // for [i, include] in includes // if(include) // forks.push(p.Fork.new(ratios.get(i), colors.get(i), include)) // p.PitchforkProperties properties = p.PitchforkProperties.new(forks, pitchforkType, inside) // p.PitchforkDrawingProperties dProperties = p.PitchforkDrawingProperties.new(extend, fill, transparency) // if(barstate.islast) // var array<p.Pitchfork> pitchforks = array.new<p.Pitchfork>() // pitchforks.clear() // mlzigzag = zigzag // while(array.size(mlzigzag.zigzagPivots) >= 3+startIndex) // lineColor = themeColors.pop() // themeColors.unshift(lineColor) // p3 = array.get(mlzigzag.zigzagPivots, startIndex) // p3Point = p3.point // p2Point = array.get(mlzigzag.zigzagPivots, startIndex+1).point // p1Point = array.get(mlzigzag.zigzagPivots, startIndex+2).point // if (p3.ratio >= ratioFrom and p3.ratio <= ratioTo and p3Point.bar - p1Point.bar <500) // dr.LineProperties lProperties = dr.LineProperties.new(color=lineColor) // p.Pitchfork pitchFork = p.Pitchfork.new(p1Point, p2Point, p3Point, properties, dProperties, lProperties) // drawing = pitchFork.createDrawing() // drawing.draw() // pitchforks.push(pitchFork) // mlzigzag := mlzigzag.nextlevel()
'use server' import process from 'node:process' import { Buffer } from 'node:buffer' import z from 'zod' import { cookies, headers } from 'next/headers' import { isoBase64URL } from '@simplewebauthn/server/helpers' import { revalidatePath } from 'next/cache' import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse, } from '@simplewebauthn/server' import type { AuthenticationResponseJSON, AuthenticatorTransportFuture, RegistrationResponseJSON, } from '@simplewebauthn/types' import { ERROR_MESSAGE, SUCCEED_MESSAGE, resMessageError, resMessageSuccess, } from '~/server/message' import { dbCreateAuthSession, dbCreateAuthenticatorForUser, dbCreateSession, dbCreateUser, dbReadAuthSessionData, dbReadAuthenticatorById, dbReadAuthenticatorsByUserId, dbReadLoggedInUserInfoBySession, dbRemoveAuthenticatorCounter, dbUpdateAuthenticatorCounter, } from '~/server/db/user' const host = headers().get('host')! const [domain] = host.split(':') // Human-readable title for your website const rpName = 'Cotton Blog' // A unique identifier for your website const rpID = domain! // The URL at which registrations and authentications should occur const origin = process.env.NODE_ENV !== 'production' ? `http://${host}` : `https://${host}` function setCookie(key: string, value: string) { cookies().set(key, value, { httpOnly: true, secure: true, maxAge: 2592000, }) } // LOGOUT export async function LogoutAction() { await Promise.resolve(cookies().delete('session-id')) } // REG interface AuthenticatorInfoCreAndTrans { credentialID: string createAt?: Date transports?: string | null } export interface AuthenticatorInfo extends AuthenticatorInfoCreAndTrans { credentialPublicKey: Buffer counter: number aaguid: string } async function getCurrentAuthSession() { const sessionId = cookies().get('auth-session-id')?.value if (!sessionId) return resMessageError('AUTH_SESSION_NOT_FOND') let currentSession try { currentSession = await dbReadAuthSessionData(sessionId) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } if (!currentSession) return resMessageError('AUTH_SESSION_EXPIRE') return currentSession } async function generateRegistrationOpt( userName: string, userId?: string, userAuthenticators?: AuthenticatorInfoCreAndTrans[], ) { let options try { options = await generateRegistrationOptions({ rpName, rpID, userID: userId !== undefined ? isoBase64URL.toBuffer(userId) : userId, userDisplayName: userName, userName, excludeCredentials: userAuthenticators?.map((authenticator) => ({ id: authenticator.credentialID, type: 'public-key', // Optional transports: authenticator.transports ? (JSON.parse(authenticator.transports) as AuthenticatorTransportFuture[]) : undefined, })), authenticatorSelection: { // Defaults residentKey: 'preferred', userVerification: 'preferred', }, }) } catch (e) { console.error(e) return resMessageError('GENERATE_REG_OPTIONS_FAILED') } let session try { session = await dbCreateAuthSession(options.challenge, options.user.id, options.user.name) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } setCookie('auth-session-id', session.id) return resMessageSuccess('OPTION_GENERATE', options) } export async function RegOptAction(formData: FormData) { const schema = z.object({ userName: z.string(), }) let data try { data = schema.parse({ userName: formData.get('username'), }) } catch { return resMessageError('ZOD_FORM_DATA_TYPE_ERROR') } if (data.userName === '') return resMessageError('USER_ID_CAN_NOT_BE_EMPTY') return await generateRegistrationOpt(data.userName) } async function verifyRegistrationRes( localResponse: RegistrationResponseJSON, currentSession: { currentChallenge: string }, ) { let verification try { verification = await verifyRegistrationResponse({ response: localResponse, expectedChallenge: currentSession.currentChallenge, expectedOrigin: origin, expectedRPID: rpID, requireUserVerification: false, }) } catch (e) { console.error(e) return resMessageError('VERIFY_REG_RESPONSE_PROCESS_FAILED') } const { verified, registrationInfo } = verification if (!verified || !registrationInfo) return resMessageError('VERIFY_REG_RESPONSE_FAILED') const { credentialPublicKey, credentialID, counter, aaguid } = registrationInfo const newAuthenticator = { credentialID, credentialPublicKey: Buffer.from(credentialPublicKey), counter, transports: JSON.stringify(localResponse.response.transports), aaguid, } return newAuthenticator } export async function vRegResAction(localResponse: RegistrationResponseJSON) { const currentSession = await getCurrentAuthSession() if ('message' in currentSession) return currentSession const newAuthenticator = await verifyRegistrationRes(localResponse, currentSession) if ('message' in newAuthenticator) return newAuthenticator let user try { user = await dbCreateUser(currentSession.userId!, currentSession.userName!, newAuthenticator) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } try { cookies().delete('auth-session-id') const session = await dbCreateSession(user.id) setCookie('session-id', session.id) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } return resMessageSuccess('REGISTER_FINISH') } // Auth export async function AuthOptAction() { let options try { options = await generateAuthenticationOptions({ rpID, userVerification: 'required', }) } catch (e) { console.error(e) return resMessageError('GENERATE_AUTH_OPTIONS_FAILED') } let session try { session = await dbCreateAuthSession(options.challenge) } catch (e) { console.error(e) return resMessageError('GENERATE_NEW_AUTH_SESSION_FAILED') } setCookie('auth-session-id', session.id) return resMessageSuccess('OPTION_GENERATE', options) } export async function vAuthResAction(options: AuthenticationResponseJSON) { const currentSession = await getCurrentAuthSession() if ('message' in currentSession) return currentSession let authenticator try { authenticator = await dbReadAuthenticatorById(options.rawId) } catch (e) { return resMessageError('DB_ERROR') } if (!authenticator) return resMessageError('AUTHENTICATOR_NOT_FOUND') let verification try { verification = await verifyAuthenticationResponse({ response: options, expectedChallenge: currentSession.currentChallenge, expectedOrigin: origin, expectedRPID: rpID, authenticator: { ...authenticator, credentialID: authenticator.credentialID, credentialPublicKey: new Uint8Array(authenticator.credentialPublicKey), transports: authenticator.transports ? (JSON.parse(authenticator.transports) as AuthenticatorTransportFuture[]) : undefined, }, }) } catch (e) { console.error(e) return resMessageError('VERIFY_AUTH_RESPONSE_PROCESS_FAILED') } if (!verification.verified) return resMessageError('VERIFY_AUTH_RESPONSE_FAILED') try { await dbUpdateAuthenticatorCounter( authenticator.credentialID, verification.authenticationInfo.newCounter, ) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } try { cookies().delete('auth-session-id') const session = await dbCreateSession(authenticator.userId) setCookie('session-id', session.id) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } return resMessageSuccess('AUTH_FINISH') } // ADD DEVICE export async function addDeviceOptAction() { // SESSION CHECK const sessionId = cookies().get('session-id')?.value if (!sessionId) return resMessageError('SESSION_NOT_FOUND') // USER CHECK let userInfo try { userInfo = await dbReadLoggedInUserInfoBySession(sessionId) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } if (!userInfo) return resMessageError('SESSION_EXPIRE') let authenticators try { authenticators = await dbReadAuthenticatorsByUserId(userInfo.id) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } if (!authenticators) return resMessageError('NO_DEVICE_REGISTER_BEFORE') return await generateRegistrationOpt(userInfo.name, userInfo.id, authenticators) } export async function addDeviceVResAction(localResponse: RegistrationResponseJSON) { const currentSession = await getCurrentAuthSession() if ('message' in currentSession) return currentSession const newAuthenticator = await verifyRegistrationRes(localResponse, currentSession) if ('message' in newAuthenticator) return newAuthenticator try { await dbCreateAuthenticatorForUser(currentSession.userId!, newAuthenticator) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } revalidatePath('/posts/[slug]', 'page') revalidatePath('/about') return resMessageSuccess('ADD_DEVICE_SUCCEED') } export async function removeUserDeviceAction(credentialID: string) { // SESSION CHECK const sessionId = cookies().get('session-id')?.value if (!sessionId) return resMessageError('SESSION_NOT_FOUND') // USER CHECK let userInfo try { userInfo = await dbReadLoggedInUserInfoBySession(sessionId) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } if (!userInfo) return resMessageError('SESSION_EXPIRE') let authenticators try { authenticators = await dbReadAuthenticatorsByUserId(userInfo.id) } catch (e) { console.error(e) return resMessageError('DB_ERROR') } if (authenticators.length === 1) return resMessageError('ONLY_ONE_DEVICE_REMAIN') try { await dbRemoveAuthenticatorCounter(userInfo.id, credentialID) revalidatePath('/posts/[slug]', 'page') revalidatePath('/about') return { message: SUCCEED_MESSAGE.REMOVE_DEVICE_SUCCEED } } catch (e) { return { message: ERROR_MESSAGE.REMOVE_DEVICE_SQL_ERROR } } }
.row .col-md-6 h1 Timesheet - #{@user.department&.name} .col-md-6 button.btn.btn-primary.float-right.mr-1 data-target="#newEventUploads" data-toggle="modal" type="button" i.material-icons-outlined.text-white publish span.ml-2 Upload #newEventUploads.modal.fade aria-hidden="true" aria-labelledby="newEventUploads" role="dialog" tabindex="-1" .modal-dialog role="document" .modal-content .modal-header h5.modal-title Upload Documents button.close aria-label="Close" data-dismiss="modal" type="button" span aria-hidden="true" &times; .modal-body .row.mt-3 .col-md-12 = form_tag import_conductor_events_path, multipart: true do .custom-file label.custom-file-label Choose file = file_field_tag :file, class: "custom-file-input" = submit_tag "Import", class: "btn btn-primary form-control mt-5" - if @user.has_role?(:admin, @company) or @user.has_role?(:staffer, @company) = button_to export_conductor_allocations_path, params: { events: @events_all }, method: :post, class: 'btn btn-warning float-right mr-2' do i.material-icons-outlined get_app span.ml-2 Download = link_to "Edit Categories", edit_tags_conductor_events_path, class: 'btn btn-secondary float-right mr-2' a.float-right.mr-5.mt-2 data-target="#checkUsers" data-toggle="modal" type="button" i.material-icons-outlined groups #checkUsers.modal.fade aria-hidden="true" aria-labelledby="checkUsers" role="dialog" tabindex="-1" .modal-dialog role="document" .modal-content .modal-header h5.modal-title Timesheet submitted button.close aria-label="Close" data-dismiss="modal" type="button" span aria-hidden="true" &times; .modal-body .row.mt-3 .col-md-12 table.table th Name th No. of days th No. of hours - @user_event_count.each do |key, value| tr td = key.to_s td = value[0].to_s td = value[1].to_s .row.mt-5 .col-md-12.m-2 .col-md-1.float-left.mt-3.px-0 span FILTER BY .col-md-2.float-left.px-1.select2-multiple = select_tag('allocation_user', options_for_select(@users.map {|k,v| [k.full_name, k.id] }, selected: (params[:allocation_users].split(",") if params[:allocation_users].present?)), class: 'select2 allocation-users', multiple: true, data: {"placeholder": 'Choose user...'}) .col-md-2.float-left.px-1 = text_field_tag :start_date, params[:start_date], {class: 'col-md-12 form-control datepicker', 'data-toggle': 'datetimepicker', id: 'startDate', 'data-target': '#startDate', placeholder: "Start date..."} .col-md-2.float-left.px-1 = text_field_tag :end_date, params[:end_date], {class: 'col-md-12 form-control datepicker', 'data-toggle': 'datetimepicker', id: 'endDate', 'data-target': '#endDate', placeholder: "End date..."} .col-md-2.float-left.px-1.select2-multiple = select_tag('project_client', options_for_select(@clients.map {|k,v| [k.name, k.id]}, selected: (params[:project_clients].split(",") if params[:project_clients].present?)), class: 'select2 project-clients', multiple: true, data: {"placeholder": 'Choose client...'}) .col-md-2.float-left.px-1.select2-multiple = select_tag('service_line_filter', options_for_select(@service_lines.map {|k,v| [k.name, k.id]}, selected: (params[:service_line].split(",") if params[:service_line].present?)), class: 'select2 service-line', multiple: true, data: {"placeholder": 'Choose job function...'}) .col-md-1.float-left.px-1 = button_tag 'Filter', type: 'button', class: 'btn btn-sm btn-primary timesheet-filter-button' hr .row .col-sm-12 h1 Create new task = form_for @event, url: conductor_events_path do |f| .row.mx-2 .form-inline.col-md-12 - if current_user.has_role? :staffer, @company or current_user.has_role? :admin, @company .col.pl-0.pr-2 = select_tag :user, options_from_collection_for_select(@users, "id", "full_name", @event.allocations.last&.user&.id), {class: 'select2 select2-width', include_blank: true, data: {"placeholder": 'Allocate someone...'}} .col.pl-0.pr-2 = f.date_field :start_time, class: 'form-control w-100', required: true .col.pl-0.pr-2 = select_tag :client, options_for_select(@clients.map {|k,v| [k.name, k.id]}, selected: @event.categories.where(category_type: "client").name), {include_blank: true, required: true, class: 'select2 select2-width', data: {"placeholder": 'Select client...' }} .col.pl-0.pr-2 = select_tag :service_line, options_for_select(@service_lines.map {|k,v| [k.name, k.id]}, selected: @event.categories.where(category_type: "service_line").name), {include_blank: true, required: true, class: 'select2 select2-width', data: {"placeholder": 'Select job function...' }} .col.pl-0.pr-2 = select_tag :project, options_for_select(@projects.map {|k,v| [k.name, k.id]}, selected: @event.categories.where(category_type: "project").name), {include_blank: true, required: true, class: 'select2 select2-width', data: {"placeholder": 'Select project...' }} .col.pl-0.pr-2 = select_tag :task, options_for_select(@tasks.map {|k,v| [k.name, k.id]}, selected: @event.categories.where(category_type: "task").name), {include_blank: true, required: true, class: 'select2 select2-width', data: {"placeholder": 'Select task...' }} .col-1.pl-0.pr-2 = f.number_field :number_of_hours, {min: 0, step: 0.1, placeholder: 'Hours...', class: 'form-control w-100', required: true} .pl-0.pr-2 = f.submit 'Save', class: 'btn btn-primary' hr .row .col-sm-12 .table-responsive table.table.table-striped thead tr th th Date th Client th Job Function th Project th Task th | Hours a.ml-2 data-container="body" title="An estimation of the number of hours you worked" data-html="true" data-placement="left" data-toggle="tooltip" data-trigger="hover" i.fa.fa-info-circle th th tbody - @events.each do |event| = form_for event, url: conductor_event_path(event.id), remote: true do |f| tr - if event.allocations.present? td.text-center width="3%" .avatar-circle data-container="body" data-placement="bottom" data-toggle="tooltip" title=(event.allocations[0].user.full_name) span.initials = "#{event.allocations[0].user.first_name[0]}#{event.allocations[0].user&.last_name[0]}" - else td td width="10%" = f.date_field :start_time, { class: 'form-control', data: { event_id: event.id }, onchange: "eventsUpdate(this)" } td width="12%" = f.select :client_category, @clients.map { |k,v| [k.name, k.id] }, { selected: event.categories.find_by(category_type: "client")&.id, prompt: 'Select client...' }, { class: 'select2 form-control', id: 'event_' + event.id + '_client', data: { event_id: event.id}, onchange: "eventsUpdate(this);" } td width="20%" = f.select :service_line_category, @service_lines.map { |k,v| [k.name, k.id] }, { selected: event.categories.find_by(category_type: "service_line")&.id, prompt: 'Select job function...' }, { class: 'select2 form-control', id: 'event_' + event.id + '_service_line_list', data: { event_id: event.id }, onchange: "eventsUpdate(this);" } td width="12%" = f.select :project_category, @projects.map { |k,v| [k.name, k.id] }, { selected: event.categories.find_by(category_type: "project")&.id, prompt: 'Select project...' }, { class: 'select2 form-control', id: 'event_' + event.id + '_project', data: { event_id: event.id}, onchange: "eventsUpdate(this);" } td width="20%" = f.select :task_category, @tasks.map { |k,v| [k.name, k.id] }, { selected: event.categories.find_by(category_type: "task")&.id, prompt: 'Select task...' }, { class: 'select2 form-control', id: 'event_' + event.id + '_task', data: { event_id: event.id}, onchange: "eventsUpdate(this);" } td width="15%" = f.number_field :number_of_hours, {min: 0, step: 0.1, class: 'form-control', data: { event_id: event.id }, onchange: "eventsUpdate(this);"} td.p-0 width="5%" .dropdown.dropdown-inline.float-right a.btn.btn-icon.btn-link href="#" aria-expanded="false" aria-haspopup="true" data-toggle="dropdown" i.fa.fa-ellipsis-h.text-secondary .dropdown-menu.dropdown-menu-right .dropdown-item = link_to "Delete", conductor_event_path(event), method: :delete, data: {confirm: "Are you sure you want to delete task?"} td width="3%" = fa_icon "check", class: 'text-success ajax-icons' = fa_icon "times", class: 'text-danger ajax-icons' = paginate @events, views_prefix: 'dashboard'
import argparse import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader import torch.nn as nn import torch.optim as optim from help_code_QNN import ToTensor, ECG_DataSET from models.QNN import Quantum from torchsummary import summary def main(): # Hyperparameters BATCH_SIZE = args.batchsz BATCH_SIZE_TEST = args.batchsz LR = args.lr EPOCH = args.epoch SIZE = args.size path_data = args.path_data path_indices = args.path_indices # Instantiating NN net = Quantum() summary(net, (1, 1250, 1)) net.train() net = net.float().to(device) # Start dataset loading trainset = ECG_DataSET(root_dir=path_data, indice_dir=path_indices, mode='train', size=SIZE, transform=transforms.Compose([ToTensor()])) trainloader = DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=0) testset = ECG_DataSET(root_dir=path_data, indice_dir=path_indices, mode='test', size=SIZE, transform=transforms.Compose([ToTensor()])) testloader = DataLoader(testset, batch_size=BATCH_SIZE_TEST, shuffle=True, num_workers=0) print("Training Dataset loading finish.") criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(net.parameters(), lr=LR) epoch_num = EPOCH Train_loss = [] Train_acc = [] Test_loss = [] Test_acc = [] print("Start training") for epoch in range(epoch_num): # loop over the dataset multiple times (specify the #epoch) running_loss = 0.0 correct = 0.0 accuracy = 0.0 i = 0 for j, data in enumerate(trainloader, 0): # print(j) inputs, labels = data['ECG_seg'], data['label'] inputs = inputs.float().to(device) labels = labels.to(device) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() _, predicted = torch.max(outputs.data, 1) correct += (predicted == labels).sum() accuracy += correct / BATCH_SIZE correct = 0.0 running_loss += loss.item() i += 1 print('[Epoch, Batches] is [%d, %5d] \nTrain Acc: %.5f Train loss: %.5f' % (epoch + 1, i, accuracy / i, running_loss / i)) Train_loss.append(running_loss / i) Train_acc.append((accuracy / i).item()) running_loss = 0.0 accuracy = 0.0 correct = 0.0 total = 0.0 i = 0.0 running_loss_test = 0.0 for data_test in testloader: net.eval() ECG_test, labels_test = data_test['ECG_seg'], data_test['label'] ECG_test = ECG_test.float().to(device) labels_test = labels_test.to(device) outputs_test = net(ECG_test) _, predicted_test = torch.max(outputs_test.data, 1) total += labels_test.size(0) correct += (predicted_test == labels_test).sum() loss_test = criterion(outputs_test, labels_test) running_loss_test += loss_test.item() i += 1 print('Test Acc: %.5f Test Loss: %.5f' % (correct / total, running_loss_test / i)) Test_loss.append(running_loss_test / i) Test_acc.append((correct / total).item()) torch.save(net, f'./saved_models/QNN/ECG_net_{epoch+1}.pkl') torch.save(net.state_dict(), f'./saved_models/QNN/ECG_net_state_dict_{epoch+1}.pkl') file = open('./saved_models/loss_acc.txt', 'w') file.write("Train_loss\n") file.write(str(Train_loss)) file.write('\n\n') file.write("Train_acc\n") file.write(str(Train_acc)) file.write('\n\n') file.write("Test_loss\n") file.write(str(Test_loss)) file.write('\n\n') file.write("Test_acc\n") file.write(str(Test_acc)) file.write('\n\n') print('Finish training') if __name__ == '__main__': argparser = argparse.ArgumentParser() argparser.add_argument('--epoch', type=int, help='epoch number', default=20) argparser.add_argument('--lr', type=float, help='learning rate', default=0.0001) argparser.add_argument('--batchsz', type=int, help='total batchsz for traindb', default=32) argparser.add_argument('--cuda', type=int, default=0) argparser.add_argument('--size', type=int, default=1250) argparser.add_argument('--path_data', type=str, default='../../data/training_dataset/') argparser.add_argument('--path_indices', type=str, default='./data_indices/') args = argparser.parse_args() # change # device = torch.device("cuda:" + str(args.cuda)) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("device is --------------", device) main()
@extends('template_backend.home') @section('sub-judul','Edit Posts') @section('content') @if (count($errors)>0) @foreach ($errors->all() as $error) <div class="alert alert-danger" role="alert"> {{ $error }} </div> @endforeach @endif @if (Session::has('success')) <div class="alert alert-success" role="alert"> {{ Session('success') }} </div> @endif <form action="{{ route('posts.update', $post->id)}}" method="POST" enctype="multipart/form-data"> @csrf @method('patch') <div class="form-group"> <label>Judul Posts</label> <input type="text" class="form-control" name="judul" value="{{$post->judul}}"> </div> <div class="form-group"> <label>Kategori Posts</label> <select name="category_id" class="form-control"> <option value="" holder>Pilih Kategori</option> @foreach ($category as $kategori) <option value="{{ $kategori->id }}" @if ($kategori->id == $post->category_id) selected @endif> {{ $kategori->name }}</option> @endforeach </select> </div> <div class="form-group"> <label>Pilih Tags</label> <select class="form-control select2" multiple="" name="tags[]"> @foreach ($tags as $tag) <option value="{{ $tag -> id}}" @foreach ($post->tags as $value) @if ($tag->id == $value->id) selected @endif @endforeach>{{ $tag-> name }}</option> @endforeach </select> </div> <div class="form-group"> <label>Isi Konten Posts</label> <textarea type="text" class="form-control" name="content">{{ $post->content }}</textarea> </div> <div class="form-group"> <label>Gambar Posts</label> <input type="file" class="form-control" name="gambar"> </div> <div class="form-group"> <button class="btn btn-primary btn-block">Update Posts</button> </div> </form> @endsection
import { json } from '@remix-run/node'; import type { LinksFunction, MetaFunction } from '@remix-run/node'; import { Link, useLoaderData } from '@remix-run/react'; import type { ReactElement } from 'react'; import { getStoredNotes } from '~/data/notes'; import noteDetailsStyles from '~/styles/note-details.css'; import type { DataArgParams, NotesType } from '~/types/types'; // link to the dynamic route for notesId export const links: LinksFunction = () => { return [{ rel: 'stylesheet', href: noteDetailsStyles }]; }; export const meta: MetaFunction = ({ data }) => ({ title: data.title as NotesType['title'], description: 'Manage your notes with ease.', }); function NotesDetailPage(): ReactElement { // accessing the data from the load function const loadedNotesData = useLoaderData(); return ( <main id="note-details"> <header> <nav> <Link to="/notes">Back to all notes</Link> </nav> {/* NOTES-TITLE */} <h1>{loadedNotesData?.title ?? 'NO TITLE'}</h1> <p id="note-details-content">{loadedNotesData?.content ?? 'NO CONTENT'}</p> </header> </main> ); } export default NotesDetailPage; // ######################################################## export async function loader({ params }: DataArgParams): Promise<string> { // fetching all entries from the notes.json // file of with our notes entry list const notes = await getStoredNotes(); // notesId has to be the same name as notes.`$notesId`.tsx // in the dynamic route page name const notesId = params.notesId; // check if the note is === to the id in the dynamic // url when the card is clicked. const selectedNote: string = notes.find((note: NotesType) => { return note.id === notesId; }); // if the note with the proper id is selected then an error: 404 // will be thrown. so like for example going to route localhost:3000/notes/notes-1 // should return the error component with the logic in the if statement if (!selectedNote) { throw json( { message: `COULD NOT FIND NOTE FOR ID: ${notesId}` }, { status: 404 }, ); } // finally then return the selectedNote in your loader return selectedNote; } // ########################################################
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_API_BASE }), endpoints: (builder) => ({ // Create element endpoint createElement: builder.mutation({ query: (payload) => ({ url: "/elements", method: "POST", body: payload, }), }), // Get all elements endpoint getAllElements: builder.query({ query: () => "/elements", }), // Get element by id endpoint getElementById: builder.query({ query: (id) => `/elements/${id}`, }), // Update element endpoint updateElement: builder.mutation({ query: ({ id, item }) => ({ url: `/elements/${id}`, method: "PUT", body: item, }), }), // Delete element endpoint deleteElement: builder.mutation({ query: (id) => ({ url: `/elements/${id}`, method: "DELETE", }), }), // Create element link endpoint createElementLink: builder.mutation({ query: ({ id, payload }) => ({ url: `elements/${id}/elementlinks`, method: "POST", body: payload, }), }), // Get all element links endpoint getAllElementLinks: builder.query({ query: (id) => `elements/${id}/elementlinks`, }), // Get element by id endpoint getElementLinkById: builder.query({ query: ({ id, linkId }) => `elements/${id}/elementlinks/${linkId}`, }), // Update element endpoint updateElementLink: builder.mutation({ query: ({ id, linkId, item }) => ({ url: `elements/${id}/elementlinks/${linkId}`, method: "PUT", body: item, }), }), // Delete element endpoint deleteElementLink: builder.mutation({ query: ({ id, linkId }) => ({ url: `elements/${id}/elementlinks/${linkId}`, method: "DELETE", }), }), // get Element Categories getElementCategories: builder.query({ query: () => "/lookups/1/lookupvalues", }), // get Element Classifications getElementClassifications: builder.query({ query: () => "/lookups/2/lookupvalues", }), // get Element Payruns getElementPayruns: builder.query({ query: () => "/lookups/5/lookupvalues", }), // get suborganizations getSuborganizations: builder.query({ query: () => "/suborganizations", }), // get departments getDepartments: builder.query({ query: (id) => `/suborganizations/${id}/departments`, }), // get Employee Types getEmployeeTypes: builder.query({ query: () => "/lookups/4/lookupvalues", }), // get Unions getUnions: builder.query({ query: () => "/lookups/8/lookupvalues", }), // get job titles getJobTitles: builder.query({ query: () => "/lookups/6/lookupvalues", }), // get location getLocations: builder.query({ query: () => "/lookups/7/lookupvalues", }), // get employee categories getEmployeeCategories: builder.query({ query: () => "/lookups/3/lookupvalues", }), // get grades getGrades: builder.query({ query: () => "/grade", }), // get grade steps getGradeSteps: builder.query({ query: (id) => `/grade/${id}/gradesteps`, }), }), }); export const { useCreateElementMutation, useGetAllElementsQuery, useGetElementByIdQuery, useUpdateElementMutation, useDeleteElementMutation, useGetElementCategoriesQuery, useGetElementClassificationsQuery, useGetElementPayrunsQuery, useGetAllElementLinksQuery, useGetElementLinkByIdQuery, useCreateElementLinkMutation, useDeleteElementLinkMutation, useUpdateElementLinkMutation, useGetSuborganizationsQuery, useGetJobTitlesQuery, useGetLocationsQuery, useGetUnionsQuery, useGetEmployeeCategoriesQuery, useGetEmployeeTypesQuery, useGetGradesQuery, useGetDepartmentsQuery, useGetGradeStepsQuery, } = api; export default api;
# Intel-Unnati-Project-Fake-News-Detection-Using-Python-and-Machine-Learning Our team Machine Minds which includes `Zaid Khan`,`Abhigyan Basak`,`Akshay Singh` from MIT Manipal As a part of the Intel Unnati Industrial Training.This is our project, we have used several machine learning (ML) and deep learning (DL) models to detect fake news. Here is a summary of the models and their corresponding accuracies: Our dataset: https://onlineacademiccommunity.uvic.ca/isot/2022/11/27/fake-news-detection-datasets/ Video Links: ML Model: https://drive.google.com/file/d/1za0RCrffhMxRpk06OxAT5IbvaaA6RKtO/view?usp=drive_link LSTM Model: https://drive.google.com/file/d/1huocyh-LhN7TiHH0G3M8g_vUm2MCLDDL/view?usp=drive_link In our project, we have three main files: a. `ModelsAccuracyTable.xlsx`: - This Excel file contains the accuracy values of various models used for fake news detection. It provides a summary of the model performances, including the ML and DL models we employed. b. `FakeNewsClassifierUsingLSTM.ipynb`: - This Python script focuses on implementing the LSTM deep learning model for fake news detection. The LSTM model leverages its recurrent architecture to capture sequential dependencies in textual data, making it suitable for analyzing news articles. c. `FakeNewsDetection using ML.ipynb`: - This Python script serves as the main file for our fake news detection using ML techniques. It encompasses the implementation of multiple ML models such as Logistic Regression, Multinomial Naive Bayes, Support Vector Classifier, Decision Tree Classifier, Random Forest Classifier, Ensemble Learning, Passive Aggressive Classifier, and AdaBoost Classifier. These models have been trained and evaluated for the task of detecting fake news. 1. LSTM (DL Model): Accuracy - 0.9528 - Long Short-Term Memory (LSTM) is a type of recurrent neural network (RNN) commonly used for sequence classification tasks like text analysis. 2. Logistic Regression (ML Model): Accuracy - 0.9865 - Logistic Regression is a linear classification model that applies the logistic function to predict binary outcomes. 3. Multinomial Naive Bayes (ML Model): Accuracy - 0.9385 - Multinomial Naive Bayes is a probabilistic classifier based on the Bayes' theorem, suitable for text classification tasks. 4. Support Vector Classifier (ML Model): Accuracy - 0.9936 - Support Vector Classifier (SVC) is a supervised learning model that separates classes using hyperplanes in high-dimensional space. 5. Decision Tree Classifier (ML Model): Accuracy - 0.9957 - Decision Tree Classifier builds a tree-like model of decisions and their possible consequences, enabling classification based on feature values. 6. Random Forest Classifier (ML Model): Accuracy - 0.9902 - Random Forest Classifier is an ensemble learning method that combines multiple decision trees to make predictions. 7. Ensemble Learning (ML Model): Accuracy - 0.9957 - Ensemble Learning combines multiple ML models to improve predictive performance and make more accurate predictions. 8. Passive Aggressive Classifier (ML Model): Accuracy - 0.9943 - Passive Aggressive Classifier is an online learning algorithm for binary classification that adapts to misclassified samples aggressively. 9. AdaBoost Classifier (ML Model): Accuracy - 0.9943 - AdaBoost Classifier is an ensemble learning method that iteratively combines weak classifiers to create a strong classifier. These models have been trained and evaluated on our dataset for fake news detection. Each model has achieved a certain level of accuracy, which indicates its performance in classifying news articles as real or fake.
package object import ( "io" "gopkg.in/src-d/go-git.v4/plumbing" "gopkg.in/src-d/go-git.v4/plumbing/storer" ) // NewFilterCommitIter returns a CommitIter that walks the commit history, // starting at the passed commit and visiting its parents in Breadth-first order. // The commits returned by the CommitIter will validate the passed CommitFilter. // The history won't be transversed beyond a commit if isLimit is true for it. // Each commit will be visited only once. // If the commit history can not be traversed, or the Close() method is called, // the CommitIter won't return more commits. // If no isValid is passed, all ancestors of from commit will be valid. // If no isLimit is limmit, all ancestors of all commits will be visited. func NewFilterCommitIter( from *Commit, isValid *CommitFilter, isLimit *CommitFilter, ) CommitIter { var validFilter CommitFilter if isValid == nil { validFilter = func(_ *Commit) bool { return true } } else { validFilter = *isValid } var limitFilter CommitFilter if isLimit == nil { limitFilter = func(_ *Commit) bool { return false } } else { limitFilter = *isLimit } return &filterCommitIter{ isValid: validFilter, isLimit: limitFilter, visited: map[plumbing.Hash]struct{}{}, queue: []*Commit{from}, } } // CommitFilter returns a boolean for the passed Commit type CommitFilter func(*Commit) bool // filterCommitIter implments CommitIter type filterCommitIter struct { isValid CommitFilter isLimit CommitFilter visited map[plumbing.Hash]struct{} queue []*Commit lastErr error } // Next returns the next commit of the CommitIter. // It will return io.EOF if there are no more commits to visit, // or an error if the history could not be traversed. func (w *filterCommitIter) Next() (*Commit, error) { var commit *Commit var err error for { commit, err = w.popNewFromQueue() if err != nil { return nil, w.close(err) } w.visited[commit.Hash] = struct{}{} if !w.isLimit(commit) { err = w.addToQueue(commit.s, commit.ParentHashes...) if err != nil { return nil, w.close(err) } } if w.isValid(commit) { return commit, nil } } } // ForEach runs the passed callback over each Commit returned by the CommitIter // until the callback returns an error or there is no more commits to traverse. func (w *filterCommitIter) ForEach(cb func(*Commit) error) error { for { commit, err := w.Next() if err == io.EOF { break } if err != nil { return err } if err := cb(commit); err == storer.ErrStop { break } else if err != nil { return err } } return nil } // Error returns the error that caused that the CommitIter is no longer returning commits func (w *filterCommitIter) Error() error { return w.lastErr } // Close closes the CommitIter func (w *filterCommitIter) Close() { w.visited = map[plumbing.Hash]struct{}{} w.queue = []*Commit{} w.isLimit = nil w.isValid = nil } // close closes the CommitIter with an error func (w *filterCommitIter) close(err error) error { w.Close() w.lastErr = err return err } // popNewFromQueue returns the first new commit from the internal fifo queue, // or an io.EOF error if the queue is empty func (w *filterCommitIter) popNewFromQueue() (*Commit, error) { var first *Commit for { if len(w.queue) == 0 { if w.lastErr != nil { return nil, w.lastErr } return nil, io.EOF } first = w.queue[0] w.queue = w.queue[1:] if _, ok := w.visited[first.Hash]; ok { continue } return first, nil } } // addToQueue adds the passed commits to the internal fifo queue if they weren't seen // or returns an error if the passed hashes could not be used to get valid commits func (w *filterCommitIter) addToQueue( store storer.EncodedObjectStorer, hashes ...plumbing.Hash, ) error { for _, hash := range hashes { if _, ok := w.visited[hash]; ok { continue } commit, err := GetCommit(store, hash) if err != nil { return err } w.queue = append(w.queue, commit) } return nil }
import getData from "../../utils/api"; import Spinner from "../../components/Spinner/Spinner.jsx"; import { useReducer, useEffect } from "react"; import reducer, { initialState } from "../../Helpers/Reducer/bookableReducer.jsx"; import BookablesList from "../../components/Bookables/List.jsx"; import Bookings from "../../components/Bookings/Bookings.jsx"; import { useParams } from "react-router-dom"; export default function BookingsPage() { const [state, dispatch] = useReducer(reducer, initialState); const { group, bookableIndex, bookables } = state; const { isLoading, error } = state; const bookablesInGroup = bookables.filter((b) => b.group === group); let bookable = bookablesInGroup[bookableIndex]; const { id } = useParams(); if (id) { bookable = bookables.find((b) => b.id === parseInt(id, 10)) || bookables[0]; } useEffect(() => { dispatch({ type: "FETCH_BOOKABLES_REQUEST" }); getData("http://localhost:8080/bookables") .then((bookables) => dispatch({ type: "FETCH_BOOKABLES_SUCCESS", payload: bookables, }) ) .catch((error) => dispatch({ type: "FETCH_BOOKABLES_ERROR", payload: error, }) ); }, []); if (error) { return <p>{error.message}</p>; } if (isLoading) { return ( <p> <Spinner /> Loading bookables... </p> ); } return ( <main className="bookings-page"> <BookablesList group={group} bookableIndex={bookableIndex} bookables={bookables} dispatch={dispatch} /> <Bookings bookable={bookable} /> </main> ); }
/** * SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06 */ package com.liferay.commerce.currency.internal.util; import com.ibm.icu.text.DecimalFormat; import com.ibm.icu.text.DecimalFormatSymbols; import com.liferay.commerce.currency.configuration.RoundingTypeConfiguration; import com.liferay.commerce.currency.constants.CommerceCurrencyConstants; import com.liferay.commerce.currency.model.CommerceCurrency; import com.liferay.commerce.currency.util.CommercePriceFormatter; import com.liferay.petra.string.StringPool; import com.liferay.portal.configuration.metatype.bnd.util.ConfigurableUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.util.Validator; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Locale; import java.util.Map; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; /** * @author Marco Leo * @author Alessio Antonio Rendina * @author Andrea Di Giorgi */ @Component( configurationPid = "com.liferay.commerce.currency.configuration.RoundingTypeConfiguration", service = CommercePriceFormatter.class ) public class CommercePriceFormatterImpl implements CommercePriceFormatter { @Override public String format(BigDecimal price, Locale locale) throws PortalException { DecimalFormat decimalFormat = _getDecimalFormat(null, locale); return decimalFormat.format(price); } @Override public String format( CommerceCurrency commerceCurrency, BigDecimal price, Locale locale) throws PortalException { DecimalFormat decimalFormat = _getDecimalFormat( commerceCurrency, locale); return decimalFormat.format(price); } @Override public String formatAsRelative( CommerceCurrency commerceCurrency, BigDecimal relativePrice, Locale locale) { if (relativePrice.signum() == 0) { return StringPool.BLANK; } DecimalFormat decimalFormat = _getDecimalFormat( commerceCurrency, locale); if (relativePrice.signum() == -1) { return String.format( "%2s %s", StringPool.MINUS, decimalFormat.format(relativePrice.negate())); } return String.format( "%2s %s", StringPool.PLUS, decimalFormat.format(relativePrice)); } @Activate @Modified protected void activate(Map<String, Object> properties) { _roundingTypeConfiguration = ConfigurableUtil.createConfigurable( RoundingTypeConfiguration.class, properties); } @Deactivate protected void deactivate() { _roundingTypeConfiguration = null; } private DecimalFormat _getDecimalFormat( CommerceCurrency commerceCurrency, Locale locale) { String formatPattern = CommerceCurrencyConstants.DECIMAL_FORMAT_PATTERN; int maxFractionDigits = _roundingTypeConfiguration.maximumFractionDigits(); int minFractionDigits = _roundingTypeConfiguration.minimumFractionDigits(); RoundingMode roundingMode = _roundingTypeConfiguration.roundingMode(); if (commerceCurrency != null) { formatPattern = commerceCurrency.getFormatPattern(locale); if (Validator.isNull(formatPattern)) { formatPattern = commerceCurrency.getFormatPattern( commerceCurrency.getDefaultLanguageId()); } maxFractionDigits = commerceCurrency.getMaxFractionDigits(); minFractionDigits = commerceCurrency.getMinFractionDigits(); roundingMode = RoundingMode.valueOf( commerceCurrency.getRoundingMode()); } DecimalFormat decimalFormat = new DecimalFormat( formatPattern, DecimalFormatSymbols.getInstance(locale)); decimalFormat.setMaximumFractionDigits(maxFractionDigits); decimalFormat.setMinimumFractionDigits(minFractionDigits); decimalFormat.setRoundingMode(roundingMode.ordinal()); return decimalFormat; } private volatile RoundingTypeConfiguration _roundingTypeConfiguration; }
package UserInterface.Form; import java.awt.BorderLayout; import java.awt.Container; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import DataAccess.DTO.UsuarioDTO; import UserInterface.GUI.PnlBorrarCuenta; import UserInterface.GUI.PnlCambiarContrasena; import UserInterface.GUI.PnlEstadoCuenta; import UserInterface.GUI.PnlImpresion; import UserInterface.GUI.PnlLogin; import UserInterface.GUI.PnlMain; import UserInterface.GUI.PnlMenu; import UserInterface.GUI.PnlMovimientos; import UserInterface.GUI.PnlRecarga; import UserInterface.GUI.PnlTransferencia; /** * Clase MainForm que representa la ventana principal de la aplicación. */ public class MainForm extends JFrame { Boolean estadoCuentaVisto = false; // Estado del estado de cuenta JPanel pnlMain = new PnlMain(); // Panel principal PnlEstadoCuenta pnlEstadoCuenta; // Panel de estado de cuenta PnlMenu pnlMenu; // Panel de menú UsuarioDTO usuarioDTO; // Objeto que contiene los datos del usuario /** * Constructor de la clase MainForm. * @param tilteApp Título de la aplicación. * @param usuarioDTO Objeto UsuarioDTO que contiene los datos del usuario. * @param login Panel de inicio de sesión. */ @SuppressWarnings("unused") public MainForm(String tilteApp, UsuarioDTO usuarioDTO, PnlLogin login) { this.usuarioDTO = usuarioDTO; customizeComponent(tilteApp); setIconImage( new ImageIcon(getClass().getResource("/UserInterface/Resource/FondoAcciones.png")).getImage()); pnlMenu.btnRecarga.addActionListener(e -> setPanel(new PnlRecarga(usuarioDTO, pnlMenu))); pnlMenu.btnTransferencia.addActionListener(e -> setPanel(new PnlTransferencia(usuarioDTO, pnlMenu))); pnlMenu.btnMovimientos.addActionListener(e -> setPanel(new PnlMovimientos(usuarioDTO))); pnlMenu.btnVerEstado.addActionListener(e -> {setPanel(pnlEstadoCuenta = new PnlEstadoCuenta(usuarioDTO)); estadoCuentaVisto = true;}); pnlMenu.btnImprimirEstado.addActionListener(e -> new PnlImpresion(estadoCuentaVisto, usuarioDTO)); pnlMenu.btnCambiarContrasena.addActionListener(e -> setPanel(new PnlCambiarContrasena(usuarioDTO))); pnlMenu.btnBorrarCuenta.addActionListener(e -> setPanel(new PnlBorrarCuenta(usuarioDTO, login))); pnlMenu.btnCerrarSesion.addActionListener(e -> { dispose(); try { PnlLogin login2 = new PnlLogin(); login2.setVisible(true); login2.addLoginSuccessListener(() -> { try { login2.dispose(); MainForm mainForm = new MainForm("PoliBank", login2.getUsuarioLogeado(), login); } catch (Exception e1) { e1.printStackTrace(); } }); } catch (Exception e1) { e1.printStackTrace(); } }); } /** * Método para cambiar el panel principal en la MainForm. * @param formularioPanel Panel que se establecerá como panel principal. */ private void setPanel(JPanel formularioPanel) { Container container = getContentPane(); container.remove(pnlMain); pnlMain = formularioPanel; container.add(pnlMain, BorderLayout.CENTER); revalidate(); repaint(); } /** * Método para personalizar los componentes de la MainForm. * @param tilteApp Título de la aplicación. */ private void customizeComponent(String tilteApp) { pnlMenu = new PnlMenu(usuarioDTO); setTitle(tilteApp); setSize(930, 800); setResizable(false); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Crear un contenedor para los dos paneles usando BorderLayout Container container = getContentPane(); container.setLayout(new BorderLayout()); // Agregar los paneles al contenedor container.add(pnlMenu, BorderLayout.WEST); container.add(pnlMain, BorderLayout.CENTER); setVisible(true); } }
// You are given an array of n integers, and your task is to find two values (at distinct positions) whose sum is x. // Input // The first input line has two integers n and x: the array size and the target sum. // The second line has n integers a_1,a_2,\dots,a_n: the array values. // Output // Print two integers: the positions of the values. If there are several solutions, you may print any of them. If there are no solutions, print IMPOSSIBLE. // Constraints // 1 \le n \le 2 \cdot 10^5 // 1 \le x,a_i \le 10^9 // Example // Input: // 4 8 // 2 7 5 1 // Output: // 2 4 #include <bits/stdc++.h> using namespace std; #define ll long long int main(){ ll n; cin >> n; ll x; cin >> x; map<ll, ll> indices; // Map to store the indices of elements for (ll i = 0; i < n; i++) { ll ai; cin >> ai; // Check if the complement (x - ai) exists in the map if (indices.find(x - ai) != indices.end()) { cout << indices[x - ai] + 1 << " " << i + 1 << endl; return 0; } // Insert the current element along with its index into the map indices[ai] = i; } cout << "IMPOSSIBLE" << endl; return 0; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef FIPV6FRAME_H #define FIPV6FRAME_H 1 #include <map> #include <inttypes.h> #include <endian.h> #ifndef htobe16 #include "../endian_conversion.h" #endif #include <iostream> #include "../fframe.h" #include "../caddress.h" #include "../cvastring.h" namespace rofl { // error classes class eIPv6FrameBase : public eFrameBase {}; // base error class for cpppoepacket class eIPv6FrameTagNotFound : public eIPv6FrameBase {}; // pppoe tag not found class eIPv6FrameInvalidSyntax : public eIPv6FrameBase {}; // frame has invalid syntax class eIPv6FrameInval : public eIPv6FrameBase {}; // invalid parameter class eIPv6FrameNotFound : public eIPv6FrameBase {}; // element not found class fipv6ext : public fframe { private: std::string info; public: // static // IPv6 generic extension header struct ipv6_ext_hdr_t { uint8_t nxthdr; uint8_t len; uint8_t data[0]; } __attribute__((packed)); public: struct ipv6_ext_hdr_t *exthdr; public: // default constructor fipv6ext() : fframe((size_t)0), exthdr(0) {}; // default constructor fipv6ext(struct ipv6_ext_hdr_t* hdr, size_t hdrlen) throw (eIPv6FrameInval) : fframe((uint8_t*)hdr, hdrlen), exthdr((struct ipv6_ext_hdr_t*)soframe()) { if (hdrlen < 8) { throw eIPv6FrameInval(); } }; // default constructor fipv6ext(uint8_t* hdr, size_t hdrlen) throw (eIPv6FrameInval) : fframe(hdr, hdrlen), exthdr((struct ipv6_ext_hdr_t*)soframe()) { if (hdrlen < 8) { throw eIPv6FrameInval(); } }; // virtual destructor virtual ~fipv6ext() { }; // copy constructor fipv6ext(fipv6ext const& ipv6ext) : fframe(ipv6ext.framelen()) { *this = ipv6ext; }; // assignment operator fipv6ext& operator= (fipv6ext const& ipv6ext) { if (this == &ipv6ext) return *this; fframe::operator= (ipv6ext); exthdr = (struct ipv6_ext_hdr_t*)soframe(); return *this; }; const char* c_str() { cvastring vas(256); info.assign(vas("[IPv6-ext-hdr(%p): nxthdr:%d hdrextlen:%d block-cnt:%d bytes-len:%d]", exthdr, exthdr->nxthdr, exthdr->len, (exthdr->len + 1), (exthdr->len + 1) * 8)); return info.c_str(); }; }; /** pppoe mixin for cpacket * */ class fipv6frame : public fframe { private: // data structures std::string info; //< info string public: // static #define IPV6_ADDR_LEN 16 #define IPV6_VERSION 6 /* ipv6 constants and definitions */ // ipv6 ethernet types enum ipv6_ether_t { IPV6_ETHER = 0x86dd, }; // IPv6 header struct ipv6_hdr_t { uint8_t bytes[4]; // version + tc + flow-label uint16_t payloadlen; uint8_t nxthdr; uint8_t hoplimit; uint8_t src[IPV6_ADDR_LEN]; uint8_t dst[IPV6_ADDR_LEN]; uint8_t data[0]; } __attribute__((packed)); enum ipv6_ext_t { IPPROTO_IPV6_HOPOPT = 0, IPPROTO_ICMP = 1, IPPROTO_TCP = 6, IPPROTO_UDP = 17, IPV6_IP_PROTO = 41, IPPROTO_IPV6_ROUTE = 43, IPPROTO_IPV6_FRAG = 44, IPPROTO_IPV6_ICMP = 58, IPPROTO_IPV6_NONXT = 59, IPPROTO_IPV6_OPTS = 60, IPPROTO_IPV6_MIPV6 = 135, }; /* ipv6 definitions */ public: // data structures struct ipv6_hdr_t *ipv6_hdr; // pointer to pppoe header uint8_t *ipv6data; // payload data size_t ipv6datalen; // ppp data length std::map<enum ipv6_ext_t, fipv6ext> ipv6exts; // IPv6 extensions headers public: // methods /** constructor * */ fipv6frame( uint8_t* data, size_t datalen); /** destructor * */ virtual ~fipv6frame(); /** calculate ipv6 header checksum * */ void ipv6_calc_checksum(); /** * */ fipv6ext& get_ext_hdr(enum ipv6_ext_t type) throw (eIPv6FrameNotFound); public: // overloaded from fframe /** returns boolean value indicating completeness of the packet */ virtual bool complete(); /** returns the number of bytes this packet expects from the socket next */ virtual size_t need_bytes(); /** validate (frame structure) * */ virtual void validate(uint16_t total_len = 0) throw (eFrameInvalidSyntax); /** initialize (set eth_hdr, pppoe_hdr) * */ virtual void initialize() throw (eIPv6FrameInval); /** insert payload * */ virtual void payload_insert( uint8_t *data, size_t datalen) throw (eFrameOutOfRange); /** get payload * */ virtual uint8_t* payload() const throw (eFrameNoPayload); /** get payload length * */ virtual size_t payloadlen() const throw (eFrameNoPayload); /** dump info * */ virtual const char* c_str(); public: /** */ void set_version(uint8_t version = 0x06); /** */ uint8_t get_version(); /** */ void set_traffic_class(uint8_t tc); /** */ void set_dscp(uint8_t dscp); /** */ void set_ecn(uint8_t ecn); /** */ uint8_t get_traffic_class() const; /** */ uint8_t get_dscp() const; /** */ uint8_t get_ecn() const; /** */ void set_flow_label(uint32_t flabel); /** */ uint32_t get_flow_label() const; /** */ void set_payload_length(uint16_t len); /** */ uint16_t get_payload_length(); /** */ void set_next_header(uint8_t nxthdr); /** */ uint8_t get_next_header(); /** */ void set_hop_limit(uint8_t hops); /** */ uint8_t get_hop_limit(); /** */ void dec_hop_limit(); /** src in network-byte-order */ void set_ipv6_src(uint8_t *somem, size_t memlen) throw (eIPv6FrameInval); /** src in network-byte-order */ void set_ipv6_src(cmemory const& src) throw (eIPv6FrameInval); /** */ void set_ipv6_src(caddress const& src) throw (eIPv6FrameInval); /** */ caddress get_ipv6_src() const; /** dst in network-byte-order */ void set_ipv6_dst(uint8_t *somen, size_t memlen) throw (eIPv6FrameInval); /** dst in network-byte-order */ void set_ipv6_dst(cmemory const& dst) throw (eIPv6FrameInval); /** */ void set_ipv6_dst(caddress const& dst) throw (eIPv6FrameInval); /** */ caddress get_ipv6_dst() const; private: // methods public: friend std::ostream& operator<< (std::ostream& os, fipv6frame const& ipv6) { os << "<fipv6frame: "; os << "dst:" << ipv6.get_ipv6_dst() << " "; os << "src:" << ipv6.get_ipv6_src() << " "; os << "tc:" << (unsigned int)ipv6.get_traffic_class() << " "; os << "flowlabel:" << (unsigned int)ipv6.get_flow_label() << " "; os << ">"; return os; }; }; }; // end of namespace #endif
require 'rails_helper' RSpec.describe 'Recipes', type: :system do include Devise::Test::IntegrationHelpers before(:all) do Recipe.delete_all Food.delete_all User.destroy_all @user = User.create!(name: 'yashodhi', email: 'yashodhi@mail.com', password: '123456', password_confirmation: '123456', confirmed_at: Time.now) @food1 = Food.create( user: @user, name: 'Test Food', measurement_unit: 'Gram', price: 9.99, quantity: 10 ) @food2 = Food.create( user: @user, name: 'Test Food', measurement_unit: 'Gram', price: 9.99, quantity: 10 ) @foods = Food.all end before(:each) do sign_in @user end it 'I can see the food names' do visit foods_path @foods.each do |food| expect(page).to have_content(food.name) end end it 'I can see the food measurement_units ' do visit foods_path @foods.each do |food| expect(page).to have_content(food.measurement_unit) end end it 'I can see the food price' do visit foods_path @foods.each do |food| expect(page).to have_content(food.quantity) end end end
/* * ChatPlugin - A complete yet lightweight plugin which handles just too many features! * Copyright 2023 Remigio07 * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * <https://github.com/Remigio07/ChatPlugin> */ package me.remigio07.chatplugin.server.language; import me.remigio07.chatplugin.api.common.ip_lookup.IPLookup; import me.remigio07.chatplugin.api.common.ip_lookup.IPLookupManager; import me.remigio07.chatplugin.api.common.storage.configuration.ConfigurationType; import me.remigio07.chatplugin.api.common.util.manager.LogManager; import me.remigio07.chatplugin.api.server.language.Language; import me.remigio07.chatplugin.api.server.language.LanguageDetector; import me.remigio07.chatplugin.api.server.language.LanguageDetectorMethod; import me.remigio07.chatplugin.api.server.language.LanguageManager; import me.remigio07.chatplugin.api.server.player.ChatPluginServerPlayer; public class LanguageDetectorImpl extends LanguageDetector { @Override public void load() { if (!ConfigurationType.CONFIG.get().getBoolean("languages.detector.enabled")) return; delay = ConfigurationType.CONFIG.get().getLong("languages.detector.delay-ms"); try { method = LanguageDetectorMethod.valueOf(ConfigurationType.CONFIG.get().getString("languages.detector.method")); if (method == LanguageDetectorMethod.GEOLOCALIZATION) { if (!IPLookupManager.getInstance().isEnabled()) { LogManager.log("Language detector method GEOLOCALIZATION specified at \"languages.detector.method\" in config.yml requires the IP lookup module to be enabled. You can enable it at \"ip-lookup.enabled\" in config.yml. The module will be disabled; all new players' languages will be set to the default language, specified at \"languages.main-language-id\" in config.yml.", 2); unload(); return; } if (!IPLookupManager.getInstance().isLoadOnJoin()) { LogManager.log("Language detector method GEOLOCALIZATION specified at \"languages.detector.method\" in config.yml requires the IP lookup module's option specified at \"ip-lookup.load-on-join\" in config.yml to be enabled. The module will be disabled; all new players' languages will be set to the default language, specified at \"languages.main-language-id\" in config.yml.", 2); unload(); return; } } } catch (IllegalArgumentException e) { LogManager.log( "Invalid language detector method (\"{0}\") set at \"languages.detector.method\" in config.yml: only CLIENT_LOCALE and GEOLOCALIZATION are allowed; setting to default value of CLIENT_LOCALE.", 2, ConfigurationType.CONFIG.get().getString("languages.detector.method") ); method = LanguageDetectorMethod.CLIENT_LOCALE; } enabled = true; } @Override public Language detectUsingClientLocale(ChatPluginServerPlayer player) { return detect(player.getLocale().getCountry()); } @Override public Language detectUsingGeolocalization(IPLookup ipLookup) { return detect(ipLookup.getCountryCode()); } private Language detect(String countryCode) { for (Language language : LanguageManager.getInstance().getLanguages()) for (String languageCountryCode : language.getCountryCodes()) if (languageCountryCode.equalsIgnoreCase(countryCode)) return language; return Language.getMainLanguage(); } }
package carleton.sysc4907.controller.element; import carleton.sysc4907.view.DiagramElement; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.layout.Pane; /** * Class responsible for creating and deleting previews when a diagram element is dragged in the diagram. */ public class MovePreviewCreator { /** * Constructs a new MovePreviewCreator. */ public MovePreviewCreator() { } /** * Creates a semi-transparent move preview for a given element and adds it to the diagram editing pane. * @param element the DiagramElement to preview the movement of * @param dragStartX the x coordinate where dragging started * @param dragStartY the y coordinate where dragging started * @return the created preview as an ImageView */ public ImageView createMovePreview(DiagramElement element, double dragStartX, double dragStartY) { // create preview WritableImage img = element.snapshot(null, new WritableImage( (int) element.getBoundsInParent().getWidth(), (int) element.getBoundsInParent().getHeight())); ImageView preview = new ImageView(img); preview.setOpacity(0.5); preview.setLayoutX(element.getLayoutX()); preview.setLayoutY(element.getLayoutY()); ((Pane) element.getParent()).getChildren().add(preview); return preview; } /** * Deletes the specified move preview from the scene. * If the preview is null, does nothing. * @param element the DiagramElement associated with the move preview to delete * @param preview the preview to delete */ public void deleteMovePreview(DiagramElement element, ImageView preview) { if (preview == null) { return; } ((Pane) element.getParent()).getChildren().remove(preview); } }
import axios from "axios"; import { BigcommerceCartMixin } from "@/bigcommerce/vue/mixins"; import { PricingHelper } from "@/core/vue/mixins"; import { makeVM, SubscriptionInterface as subscription, CheckoutInterface, } from "@/core/interfaces"; import { BigcommerceCart } from "@/bigcommerce/utils"; /** * Gets the current BC cart data. * * @returns {Promise<object>} The current cart in BC format. */ async function getCurrentCart() { const opts = { $axios: axios, }; const vm = makeVM(BigcommerceCartMixin, opts); const cart_response = await vm.getCartResponse(); if (cart_response && cart_response.data && cart_response.data.length) { return cart_response.data[0]; } throw Error("No cart found."); } /** * Check if the the current cart or a specified cart has a subscription. * * @param {object} [cart_data=false] A specific BC cart object as returned from the Storefront API. * @returns {Promise<boolean>} Whether the cart has a subscription. */ function hasSubscription(cart_data = false) { const cartHelper = helper(); cartHelper.cartId = cart_data.id; return cartHelper.hasSubscription; } /** * Helper function which returns the total_price field from a checkout payload. * * @returns {Promise<number>} The total_price for the current cart. */ async function helperCurrentCartTotal() { const subscription_iface = subscription; const checkout_iface = CheckoutInterface; const cart_data = await getCurrentCart(); const subscription_data = await subscription_iface.getSubscriptions({ cart_id: cart_data.id, }); const payload = checkout_iface.createPayload(cart_data, subscription_data); return payload.total_price; } /** * Helper function which returns an item price for a cart line item. * * @param {string} line_id A cart line id that exists in the current cart. * @returns {Promise<number>} The item price for the cart line. */ async function helperCurrentCartLineItemPrice(line_id) { const cart_data = await getCurrentCart(); const item_types = ["physicalItems", "digitalItems", "customItems"]; let cart_line = false; for (let i = 0; i < item_types.length; i++) { for (let j = 0; j < cart_data.lineItems[item_types[i]].length; j++) { if (cart_data.lineItems[item_types[i]][j].id === line_id) { cart_line = cart_data.lineItems[item_types[i]][j]; break; } } } if (!cart_line) { throw Error(`Cart line not found in current cart: ${line_id}`); } const subscription_iface = subscription; const subscription_data = await subscription_iface.getSubscriptions(cart_data.id, cart_line.id); if (!subscription_data.length) { return cart_line.salePrice; } return new PricingHelper().calculateItemPrice({ item_price: cart_line.salePrice, ...subscription_data[0], }).value; } /** * @param {string} rechargeDomain The store's domain from recharge. * @param {string} checkoutUrl The Checkout URL. * @returns {object} A bigcommerce cart. */ function helper(rechargeDomain, checkoutUrl) { // const vuex = makeStoreVM({ getters: ["currentSubData"] }); const rca_data = typeof RCA_DATA !== "undefined" ? RCA_DATA : window.RCA_DATA; return new BigcommerceCart({ subscriptionDataGetter: subscription.currentSubscriptionData, rcaProductData: rca_data.RCA_PRODUCT_DATA, domain: rechargeDomain, subscriptionCheckoutURL: checkoutUrl, themeObjectData: window.RCA_store_objects, }); } export default { cartTotal: helperCurrentCartTotal, itemPrice: helperCurrentCartLineItemPrice, hasSubscription: hasSubscription, helper, };
package Snake; import javax.swing.table.AbstractTableModel; import java.io.Serializable; import java.util.*; /** * The Score class. */ class Score implements Serializable, Comparable<Score>{ private final String playerName; private final int scorePoint; private final String date; /** * Instantiates a new Score. * * @param playerName the player name * @param score the score * @param date the date */ public Score(String playerName, int score, String date) { this.playerName = playerName; this.scorePoint = score; this.date = date; } /** * Gets player name. * * @return the player name */ public String getPlayerName() { return playerName; } /** * Gets score. * * @return the score */ public int getScore() { return scorePoint; } /** * Gets date. * * @return the date */ public String getDate() { return date; } /** * Compares this object with the specified object for order. * Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. * * @param other the object to be compared. * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. */ @Override public int compareTo(Score other) { return Integer.compare(other.scorePoint, this.scorePoint); } /** * Indicates whether some other object is "equal to" this one. * * @param obj the reference object with which to compare. * @return true if this object is the same as the obj argument; false otherwise. */ @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Score other)) return false; if(compareTo(other) != 0) return false; return this.playerName.equals(other.playerName) && this.date.equals(other.date); } } /** * The Score data class. * This class represents a collection of scores and implements the Collection interface. */ public class ScoreData extends AbstractTableModel implements Collection<Score> { /** * The constant scores. */ protected static List<Score> scores = new ArrayList<>(); /** * The names of the columns in the JTable. */ private final String[] ColumnNames = {"Player Name", "Score", "Date"}; /** * Add score. * * @param score the score */ public static void addScore(Score score) { scores.add(score); } /** * Gets the number of rows. */ @Override public int getRowCount() { return scores.size(); } /** * Gets the number of columns. */ @Override public int getColumnCount() { return ColumnNames.length; } /** * Gets the value at the specified row and column. */ @Override public Object getValueAt(int rowIndex, int columnIndex) { Score score = scores.get(rowIndex); switch (columnIndex) { case 0: return score.getPlayerName(); case 1: return score.getScore(); case 2: return score.getDate(); default: break; } return null; } /** * Gets the name of the column at the specified index. */ @Override public String getColumnName(int columnIndex) { return ColumnNames[columnIndex]; } /** * Get score. * * @param rowIndex the row index * @return the score */ public Score get(int rowIndex) { return scores.get(rowIndex); } /** * Adds a score to the collection. * * @param score the score to add * @return true if the score was added successfully */ @Override public boolean add(Score score) { return scores.add(score); } /** * Returns the number of scores in the collection. * * @return the number of scores */ @Override public int size() { return scores.size(); } /** * Checks if the collection is empty. * * @return true if the collection is empty, false otherwise */ @Override public boolean isEmpty() { return scores.isEmpty(); } /** * Checks if the collection contains a specific score. * * @param o the score to check for * @return true if the score is in the collection, false otherwise */ @Override public boolean contains(Object o) { return scores.contains(o); } /** * Returns an iterator over the scores in the collection. * * @return an iterator over the scores */ @Override public Iterator<Score> iterator() { return scores.iterator(); } /** * Returns an array containing all the scores in the collection. * * @return an array of scores */ @Override public Object[] toArray() { return scores.toArray(); } /** * Returns an array containing all the scores in the collection; the runtime type of the returned array is that of the specified array. * * @param a the array into which the elements of the collection are to be stored * @return an array of scores */ @Override public <T> T[] toArray(T[] a) { return scores.toArray(a); } /** * Adds all the scores in the specified collection to the collection. * * @param c the collection containing scores to be added * @return true if the collection is modified as a result of this operation */ @Override public boolean addAll(Collection<? extends Score> c) { return scores.addAll(c); } /** * Removes a specific score from the collection. * * @param o the score to be removed * @return true if the score was removed successfully */ @Override public boolean remove(Object o) { return scores.remove(o); } /** * Checks if the collection contains all the scores in the specified collection. * * @param c the collection to be checked for containment in this collection * @return true if this collection contains all the elements of the specified collection */ @Override public boolean containsAll(Collection<?> c) { return new HashSet<>(scores).containsAll(c); } /** * Removes all the scores in the specified collection from the collection. * * @param c the collection containing scores to be removed * @return true if the collection is modified as a result of this operation */ @Override public boolean removeAll(Collection<?> c) { return scores.removeAll(c); } /** * Retains only the scores in the collection that are contained in the specified collection. * * @param c the collection containing scores to be retained * @return true if the collection is modified as a result of this operation */ @Override public boolean retainAll(Collection<?> c) { return scores.retainAll(c); } /** * Removes all the scores from the collection. */ @Override public void clear() { scores.clear(); } }
#include <rclcpp/rclcpp.hpp> #include <sensor_msgs/msg/image.hpp> #include <std_msgs/msg/string.hpp> #include <opencv2/opencv.hpp> #include "atom_logic/FindLines.h" // Replace with your actual message types #include "atom_logic/PID.h" #define PID_KP 2.0f #define PID_KI 0.5f #define PID_KD 0.25f #define PID_TAU 0.02f #define PID_LIM_MIN -90.0f #define PID_LIM_MAX 90.0f #define PID_LIM_MIN_INT -5.0f #define PID_LIM_MAX_INT 5.0f #define SAMPLE_TIME_S 0.01f /* Maximum run-time of simulation */ #define SIMULATION_TIME_MAX 4.0f class WebcamNode : public rclcpp::Node { public: WebcamNode() : Node("atom_core_logic_node") { // Open a webcam for video capture cv::VideoCapture cap(0); PIDController_Init(&pid); if (!cap.isOpened()) { RCLCPP_ERROR(get_logger(), "Error opening video stream or file"); return; } // Create a publisher to publish processed images image_pub_ = create_publisher<sensor_msgs::msg::Image>("processed_image", 10); pid_pub_ = create_publisher<std_msgs::msg::String>("pid_out", 10); // Create a FindLines instance (assuming this class processes images) FindLines lines(m_FrameOut); // You might need to adjust the arguments lines.OnAttach(); while (rclcpp::ok()) { // Use a while loop to continuously process frames cv::Mat frame; cap >> frame; cv::resize(frame, frame, cv::Size(640, 480)); frame.copyTo(m_FrameOut); lines.OnUpdate(); // cv::resize(lines.GetPreprocessed(), m_FrameOut, cv::Size(320, 240)); PIDController_Update(&pid, 0, lines.GetOffsetCenter()); // std::cout<<std::round(pid.out)<<std::endl; if (pid.out <= 0){ sprintf(serialBuffer, "1:%d\n" , 90 + (uint8_t)abs(std::round(pid.out))); } else{ sprintf(serialBuffer, "1:%d\n" , 90 - (uint8_t)abs(std::round(pid.out))); } std::cout<<serialBuffer<<std::endl; //publish pid auto pid_msg = std_msgs::msg::String(); pid_msg.data = serialBuffer; pid_pub_->publish(pid_msg); // // Convert the processed image to a sensor_msgs::msg::Image // sensor_msgs::msg::Image img_msg; // img_msg.header.stamp = this->now(); // img_msg.header.frame_id = "camera_frame"; // Replace with the correct frame_id // img_msg.width = m_FrameOut.cols; // img_msg.height = m_FrameOut.rows; // img_msg.step = m_FrameOut.step; // img_msg.data = std::vector<uint8_t>(m_FrameOut.data, m_FrameOut.data + m_FrameOut.total() * m_FrameOut.elemSize()); // img_msg.encoding = "bgr8"; // Adjust the encoding as needed // image_pub_->publish(img_msg); // Display the processed frame in an OpenCV window cv::imshow("Lines", m_FrameOut); cv::waitKey(5); } } private: rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr image_pub_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pid_pub_; cv::Mat m_FrameOut; char serialBuffer [255]; PIDController pid = {PID_KP, PID_KI, PID_KD, PID_TAU, PID_LIM_MIN, PID_LIM_MAX, PID_LIM_MIN_INT, PID_LIM_MAX_INT, SAMPLE_TIME_S}; }; int main(int argc, char** argv) { rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<WebcamNode>()); rclcpp::shutdown(); return 0; }
import React, { useState } from 'react'; import { TbCalendarCheck } from 'react-icons/tb'; import { IoRemoveOutline } from 'react-icons/io5'; import { TiTicket } from 'react-icons/ti'; import { TbBasketDiscount } from 'react-icons/tb'; import { FaCartArrowDown } from 'react-icons/fa6'; import { LuCheckCircle } from 'react-icons/lu';import Navbar from '../zooAnimalPage/Navbar/Navbar'; import Snowfall from 'react-snowfall'; import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker'; import './TicketsPage.css' import dayjs from 'dayjs'; import { useNavigate } from 'react-router-dom'; const TicketsPage = () => { const today = dayjs(); const startDate = today.startOf('month'); const endDate = today.add(1, 'month').endOf('month'); const [snowFlakeActive, setSnowFlakeActive] = useState(false); const [selectedDate, setSelectedDate] = useState(today); const navigate = useNavigate(); const showSnowFlake = () => { setSnowFlakeActive(!snowFlakeActive); }; const handleDateChange = (newDate) => { setSelectedDate(newDate); const formattedDate = newDate?.format('YYYY-MM-DD'); // Kiểm tra null trước khi format // Chuyển hướng sang trang 'next' và truyền thông tin ngày đã chọn if (formattedDate) { navigate(`/tickets/type/${formattedDate}`); } }; return ( <div className='calendarPage'> {snowFlakeActive && <Snowfall color="white" snowflakeCount={100} style={{ zIndex: 1000 }} />} <Navbar showSnowFlake={showSnowFlake}/> <h1>Online Booking</h1> <div className='calendarProgress'> <TbCalendarCheck size={40} className='bookingIcon1'/> <IoRemoveOutline size={40} className='bookingIcon1'/> <TiTicket size={40} className='bookingIcon2'/> <IoRemoveOutline size={40} className='bookingIcon2'/> <TbBasketDiscount size={40} className='bookingIcon2'/> <IoRemoveOutline size={40} className='bookingIcon2'/> <FaCartArrowDown size={40} className='bookingIcon2'/> <IoRemoveOutline size={40} className='bookingIcon2'/> <LuCheckCircle size={40} className='bookingIcon2'/> </div> <p className='calendarP'><span>STEP 1:</span> Pick a day for your marvelous trip to our Zoo</p> <div className='calendar'> <LocalizationProvider dateAdapter={AdapterDayjs}> <StaticDatePicker orientation="landscape" minDate={startDate} maxDate={endDate} renderInput={() => <input readOnly />} value={selectedDate} onChange={handleDateChange} /> </LocalizationProvider> </div> </div> ); } export default TicketsPage;
<u>NAME</u> <b>Toward an Appleton WI Makerspace...</b> <u>SYNOPSIS</u> <p><b>The Distributed Hacker Maker Network(DHMN) is working towards an Appleton, WI makerspace/hackerspace. </b></p> <u>DESCRIPTION</u> <p><b><strong>What’s a hackerspace or a makerspace?</strong> </b></p> <p><b> <a href="http://www.flickr.com/photos/27276950@N00/7289412522/" title="still_20110122115232 by mikeputnam, on Flickr"><img src="http://farm8.staticflickr.com/7235/7289412522_0fec7833b2.jpg" width="500" height="375" alt="still_20110122115232"></a> </b> </p> <p><b><em><a href="http://madhackerhaus.info/2011/01/the-very-first-madhackerhaus/">MadHackerHaus 1 held at Sector67</a></em> </b></p> <p><b>In my opinion, these are a combination of many things: a garage, workshop, studio, conference room, machine shop, wood shop, office, kitchen table, basement workbench, art space, photography studio, etc, etc. The common threads here are making/fixing/creating and most importantly sharing these experiences with other people. </b></p> <p><b>Most makerspaces are funded by membership fees. Often, full members have 24/7 access to the space to work on their projects. Some spaces allows non-members to visit the space when accompanied by a member. Other membership approaches include discounted student and family membership rates. Some makerspaces even offer desk/office space to local entrepreneurs. Alternate sources of funding come from for-pay classes, things sold on the premises, grants, and donations. Most spaces resemble non-profits whether they have officially obtained non-profit status or not. </b></p> <p><b><strong>What might you see inside a makerspace/hackerspace?</strong> </b></p> <p><b><strong><a title="Adam C. and his Arduino board by geemo88, on Flickr" href="http://www.flickr.com/photos/geemo88/5394320737/"><img src="http://farm6.static.flickr.com/5211/5394320737_dc188314fb.jpg" alt="Adam C. and his Arduino board" width="343" height="257"></a><br></strong> </b></p> <p><b><em><a href="http://milwaukeemakerspace.com/content/project-roundup-127">Arduino development at Milwaukee Makerspace</a></em> </b></p> <p><b>Routers, CNCs, saws, lathes, kilns, oscilloscopes, soldering irons, circuit boards, Arduino, easels, sewing machines, pottery wheels, do-it-yourselfer’s, computer programmers, photographers, artists, mechanics, network administrators, musicians, woodworkers, mechanical engineers, authors, entrepreneurs, web designers, et. al. </b></p> <p><b><strong>What other activities do makerspaces do?</strong> </b></p> <p><b>Contests! Many spaces participate in contests with each other coordinated through http://hackerspaces.org Examples include: <a href="http://hackerspaces.org/wiki/Global_Hackerspace_Cupcake_Challenge">Global Cupcake Challenge</a>, Hackathons (where programmers work in parallel on the same problem), <a href="http://www.555contest.com/">555 contest</a> , <a href="http://www.rpmchallenge.com/">RPM Challenge</a>, <a href="http://blog.makezine.com/archive/2010/02/hackerspaces_in_space_annual_space.html">Space Blimp Contest</a> </b></p> <p><b><a href="http://milwaukeemakerspace.org/content/movie-night-suggestions">Movie nights</a> , <a href="http://www.sector67.org/blog/2011/board-game-night">game days</a> , <a href="http://web414.com/">host meetups</a>, <a href="http://www.buildmadison.org/">community building events</a> <a href="http://bucketworks.org/category/tags/start-anything">incubate startups</a>,etc. </b></p> <p><b><strong>How can I get in on this?</strong> </b></p> <p><b><a href="http://rasterweb.net/raster/2010/11/11/twitter-monkey/" target="_blank"><img src="http://rasterweb.net/raster/wp-content/uploads/2010/11/twittermonkeyarduino.jpg" alt="Twitter Monkey"></a> </b></p> <p><b><em><a href="http://rasterweb.net/raster/2010/11/11/twitter-monkey/">Twitter Monkey by Raster</a></em> </b></p> <p><b>If you enjoy things like <a href="http://makezine.com/">Make Magazine</a>, <a href="http://hackaday.com/">Hack-a-day</a>, <a href="http://lifehacker.com/">Lifehacker</a>, <a href="http://www.popsci.com/">Popular Science</a>, <a href="http://www.popularmechanics.com/">Popular Mechanics</a>, <a href="http://sparkfun.com">Sparkfun</a>, <a href="http://www.adafruit.com">Adafruit Industries</a>, <a href="http://www.radioshack.com/">Radio Shack</a>, <a href="http://www.firstlegoleague.org/">FIRST/Lego Robotics</a>, <a href="http://instructables.com">Instructables</a>, <a href="http://wisconsinlinux.org">Linux</a>, you’ll find lots in common with people at a makerspace. </b></p> <p><b>I encourage you to read up on makerspaces and form your own perceptions about them. Then either join one or start one. You’ll be glad you did. </b></p> <p><b>If you are nearby, <a href="http://dhmn.net">join the DHMN as we work toward an Appleton, WI hackerspace/makerspace</a>. </b></p> <p><b><strong>Other hackerspaces/makerspaces in Wisconsin</strong> </b></p> <p><b><strong><em>Milwaukee, WI</em></strong><br>Bucketworks(hosts <a href="http://barcampmilwaukee.org">BarCampMilwaukee</a> – an unconference, <a href="http://web414.com">Web414</a>, many tech related meetups, co-working, etc)<br><a href="http://milwaukeemakerspace.org/">Milwaukee Makerspace</a> (participates in <a href="http://milwaukeemakerspace.org/?q=taxonomy/term/21">Power Racing Series</a>) </b></p> <p><b><strong><em>Madison, WI</em></strong><br><a href="http://sector67.org">Sector67</a> (hosted first <a href="http://madhackerhaus.info">MadHackerHaus</a>, <a href="http://buildmadison.org">BuildMadison</a>, holds Arduino classes, etc) </b></p> <p><b><strong>Everywhere else</strong><br><a href="http://hackerspaces.org">http://hackerspaces.org</a> </b></p>
import os from typing import List import h5py import matplotlib.pyplot as plt import numpy as np import pandas as pd from beetroots.inversion.results.utils.abstract_util import ResultsUtil from beetroots.inversion.results.utils.mc import histograms class ResultsRegularizationWeights(ResultsUtil): __slots__ = ( "model_name", "list_names", "path_img", "path_data_csv_out_mcmc", "N_MCMC", "T_MC", "T_BI", "freq_save", "effective_T_BI", "effective_T_MC", "D", ) def __init__( self, model_name: str, path_img: str, path_data_csv_out_mcmc: str, N_MCMC: int, T_MC: int, T_BI: int, freq_save: int, D: int, list_names: List[str], ): self.model_name = model_name self.list_names = list_names self.path_img = path_img self.path_data_csv_out_mcmc = path_data_csv_out_mcmc self.N_MCMC = N_MCMC self.T_MC = T_MC self.T_BI = T_BI self.freq_save = freq_save self.effective_T_BI = T_BI // freq_save self.effective_T_MC = T_MC // freq_save self.D = D def read_data(self, list_mcmc_folders: List[str]): list_tau = np.zeros((self.N_MCMC, self.effective_T_MC, self.D)) for seed, mc_path in enumerate(list_mcmc_folders): with h5py.File(mc_path, "r") as f: # try: list_tau[seed] = np.array(f["list_tau"]) # except: # return np.empty((self.D,)), False return list_tau def create_folders(self): folder_path_inter = f"{self.path_img}/regularization_weights" folder_path = f"{folder_path_inter}/{self.model_name}" for path_ in [folder_path_inter, folder_path]: if not os.path.isdir(path_): os.mkdir(path_) return folder_path def estimate_regu_weight(self, list_mcmc_folders: List[str]) -> np.ndarray: for i, mc_path in enumerate(list_mcmc_folders): if i == 0: with h5py.File(mc_path, "r") as f: list_tau = np.array(f["list_tau"][self.effective_T_BI :]) else: with h5py.File(mc_path, "r") as f: list_tau = np.concatenate( [ list_tau, np.array( f["list_tau"][self.effective_T_BI :], ), ] ) estimated_regu_weights = list_tau.mean(0) return estimated_regu_weights def main( self, list_mcmc_folders: List[str], ) -> np.ndarray: folder_path = self.create_folders() list_tau = self.read_data(list_mcmc_folders) print("starting plots of regularization weights") for seed in range(self.N_MCMC): for d in range(self.D): list_tau_sd = list_tau[seed, :, d] * 1 assert list_tau_sd.shape == (self.effective_T_MC,) list_tau_sd_no_BI = list_tau_sd[self.effective_T_BI :] * 1 tau_MMSE = list_tau_sd_no_BI.mean(0) IC_2p5 = np.percentile(list_tau_sd_no_BI, q=2.5, axis=0) IC_97p5 = np.percentile(list_tau_sd_no_BI, q=97.5, axis=0) assert isinstance(tau_MMSE, float), tau_MMSE assert isinstance(IC_2p5, float), IC_2p5 assert isinstance(IC_97p5, float), IC_97p5 title = f"MC {self.list_names[d]} spatial regularization" title += " weight" histograms.plot_1D_chain( list_tau_sd, None, d, folder_path, title, lower_bounds_lin=1e-8 * np.ones((1,)), upper_bounds_lin=1e8 * np.ones((1,)), N_MCMC=self.N_MCMC, T_MC=self.T_MC, T_BI=self.T_BI, ) title = "posterior distribution of spatial regularization" title += f" weight of {self.list_names[d]}" histograms.plot_1D_hist( list_tau_sd_no_BI, None, d, folder_path, title=title, lower_bounds_lin=1e-8 * np.ones((1,)), upper_bounds_lin=1e8 * np.ones((1,)), seed=seed, estimator=tau_MMSE, IC_low=IC_2p5, IC_high=IC_97p5, ) # altogether list_tau_flatter = list_tau.reshape( (self.N_MCMC * self.effective_T_MC, self.D), ) list_tau_flatter_no_BI = list_tau[:, self.effective_T_BI :].reshape( (self.N_MCMC * (self.T_MC - self.T_BI) // self.freq_save, self.D) ) tau_MMSE, _ = list_tau_sd_no_BI.mean(0) # (D,) IC_2p5 = np.percentile(list_tau_sd_no_BI, q=2.5, axis=0) # (D,) IC_97p5 = np.percentile(list_tau_sd_no_BI, q=97.5, axis=0) # (D,) assert tau_MMSE.shape == (self.D,) assert IC_2p5.shape == (self.D,) assert IC_97p5.shape == (self.D,) plt.figure(figsize=(8, 6)) plt.title("regularization weights sampling") for d, name in enumerate(self.list_names): plt.semilogy(list_tau_flatter[:, d], label=name) for seed in range(self.N_MCMC): if seed == 0: plt.axvline( seed * self.effective_T_MC + self.effective_T_BI, c="k", ls="--", label="T_BI", ) elif seed == 1: plt.axvline( seed * self.effective_T_MC, c="k", ls="-", label="new MC", ) plt.axvline( seed * self.effective_T_MC + self.effective_T_BI, c="k", ls="--", ) else: plt.axvline(seed * self.effective_T_MC, c="k", ls="-") plt.axvline( seed * self.effective_T_MC + self.effective_T_BI, c="k", ls="--", ) plt.grid() plt.legend() # plt.tight_layout() plt.savefig( f"{folder_path}/mc_regu_weights.PNG", bbox_inches="tight", ) plt.close() for d in range(self.D): title = "posterior distribution of spatial regularization weight" title = f" of {self.list_names[d]}" histograms.plot_1D_hist( list_tau_flatter_no_BI[:, d], None, d, folder_path, title, self.lower_bounds_lin, self.upper_bounds_lin, None, tau_MMSE[d], IC_2p5[d], IC_97p5[d], ) list_estimation_tau = [] for d in range(self.D): dict_ = { "model_name": self.model_name, "d": d, "MMSE": tau_MMSE[d], } for q in [0.5, 2.5, 5, 95, 97.5, 99]: dict_[f"per_{q}"] = np.percentile( list_tau_flatter_no_BI[:, d], q=q, ) list_estimation_tau.append(dict_) df_estimation_tau = pd.DataFrame(list_estimation_tau) path_file = f"{self.path_data_csv_out_mcmc}/estimation_tau.csv" df_estimation_tau.to_csv( path_file, mode="a", header=not (os.path.exists(path_file)), ) print("plots of regularization weights done") return
"""Financiera_KeniaMoreira URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.urls import path, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from app_seguridad import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), path('fina/', include('app_financiera.urls')), path('login/', views.log_in, name="login_view"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
import React, { useState } from "react" import { useMediaQuery } from "react-responsive" import SearchBar from "./SearchBar" import ResourceCategories from "./ResourceCategories" const AllResources = () => { const isMobile = useMediaQuery({ maxWidth: 767 }) const isTablet = useMediaQuery({ minWidth: 768, maxWidth: 1023 }) const isDesktop = useMediaQuery({ minWidth: 1024, maxWidth: 1823 }) const isBigScreen = useMediaQuery({ minWidth: 1824 }) const [searchQuery, setSearchQuery] = useState("") const [showFavoritesOnly, setShowFavoritesOnly] = useState(false) const [viewMode, setViewMode] = useState("list") const handleSearch = (inputValue) => { setSearchQuery(inputValue) if (inputValue) { setShowFavoritesOnly(false) } } const handleToggleFavorites = () => { setShowFavoritesOnly(!showFavoritesOnly) setSearchQuery("") } const toggleViewMode = () => { setViewMode((prevMode) => (prevMode === "list" ? "grid" : "list")); } const resourceCategories = [ { key: 1, baseName: "SearchEnginesConventional", title: "Search Engines Conventional", }, { key: 2, baseName: "SearchEnginesAI", title: "Search Engines AI", }, { key: 3, baseName: "SearchEnginesMedia", title: "Search Engines Media", }, { key: 4, baseName: "SearchEnginesInt", title: "Search Engines Int", }, { key: 5, baseName: "ImageGenerators", title: "Image Generators", }, { key: 6, baseName: "DesignStudios", title: "Design Studios", }, { key: 7, baseName: "Designers", title: "Designers", }, { key: 8, baseName: "TypeFoundries", title: "Type Foundries", }, { key: 9, baseName: "TypeInspo", title: "Type Inspo", }, { key: 10, baseName: "TypeMarkets", title: "Type Markets", }, { key: 11, baseName: "Indexing", title: "Indexing", }, { key: 12, baseName: "BuildSites", title: "Build Sites", }, { key: 13, baseName: "FileTransfering", title: "File Transfering", }, { key: 14, baseName: "Workflow", title: "Workflow", }, { key: 15, baseName: "WebPractices", title: "Web Practices", }, { key: 16, baseName: "JSLibraries", title: "Creative JS", }, { key: 17, baseName: "CSSMix", title: "CSS Mix", }, { key: 18, baseName: "Critics", title: "Blogs", }, { key: 19, baseName: "ExperimentalPortfolios", title: "Experimental Portfolios", }, { key: 20, baseName: "SiteAwards", title: "Site Awards", }, { key: 21, baseName: "UIInspo", title: "UI Inspo", }, { key: 22, baseName: "FreeAssets", title: "Free Assets", }, { key: 23, baseName: "TypeGames", title: "Type Games", }, { key: 24, baseName: "MiscUtils", title: "Misc Utils", }, { key: 25, baseName: "MiscMisc", title: "Misc Misc", }, { key: 26, baseName: "Extensions", title: "Extensions", }, { key: 27, baseName: "Experimental", title: "Experimental", }, { key: 28, baseName: "Random", title: "Random", } ] return ( <> {(isTablet || isDesktop || isBigScreen) && ( <> <div className="row align-items-center mb-4"> <div className="col-sm-5 col-lg-4 px-0"> {/* Search bar */} <SearchBar onSearch={handleSearch} /> </div> <div className="col-md-auto px-0"> <input id="favoritesInput" type="button" value="Favorites" className={`toggle-button ${showFavoritesOnly ? 'active' : ''}`} onClick={handleToggleFavorites} /> </div > </div > </> )} <ResourceCategories resourceCategories={resourceCategories} searchQuery={searchQuery} showFavoritesOnly={showFavoritesOnly} /> </> ) } export default AllResources
import React, { CSSProperties } from 'react'; export interface InputProps { onChange: (value: string) => void; value: string | number; label?: string; placeHolder?: string; style?: CSSProperties; className?: string; type?: InputType; } export enum InputType { text = 'text', password = 'password', number = 'number', } export const Input = (props: InputProps) => { const { label, onChange, value, placeHolder, style, className } = props; return ( <> <style> {` .WeHub-componentInput { display: flex; flex-direction: column; width: 100%; } .WeHub-componentInput__label { margin-bottom: 8px; font-weight: 600; color: #40454f; font-size: 14px; } .WeHub-componentInput__input { border: 1px solid #d0d6dc; padding: 12px; border-radius: 8px; color: #40454f; font-size: 14px; width: 100%; outline: none; box-sizing: border-box; } `} </style> <div style={style} className={`WeHub-componentInput ${className}`}> {label && ( <label className="WeHub-componentInput__label">{label}</label> )} <input className="WeHub-componentInput__input" placeholder={placeHolder} value={value} onChange={e => onChange(e.target.value)} type={props.type || InputType.text} /> </div> </> ); };
/* * Copyright 2015, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package tub.ods.pch.channel.node; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SignatureException; import java.security.cert.CertificateEncodingException; import java.util.List; import javax.net.ssl.SSLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.event.ContextStartedEvent; import org.springframework.context.event.ContextStoppedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; import org.web3j.abi.datatypes.Address; import org.web3j.crypto.ECKeyPair; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.netty.GrpcSslContexts; import io.grpc.netty.NettyServerBuilder; import io.netty.handler.ssl.SslContextBuilder; import io.netty.util.internal.NativeLibraryLoader; import tub.ods.pch.channel.util.ChannelServerProperties; import tub.ods.pch.channel.node.EthereumConfig; import tub.ods.pch.channel.node.ContractsManager; import tub.ods.pch.channel.node.ContractsManagerFactory; import tub.ods.pch.channel.util.CryptoUtil; import tub.ods.pch.channel.EndpointRegistry; import tub.ods.pch.channel.model.EndpointRegistryContract; @Service @EnableConfigurationProperties(ChannelServerProperties.class) public class NodeServer { private static final Logger log = LoggerFactory.getLogger(NodeServer.class); private final List<BindableService> bindableServices; private Server grpcServer; private ServerSocket healthCheckSocket; private ChannelServerProperties properties; private final EthereumConfig ethereumConfig; private final ContractsManagerFactory factory; private Thread healthChecker; public NodeServer(List<BindableService> bindableServices, ChannelServerProperties properties, EthereumConfig ethereumConfig, ContractsManagerFactory factory) { this.bindableServices = bindableServices; this.properties = properties; this.ethereumConfig = ethereumConfig; this.factory = factory; } @EventListener(ContextStartedEvent.class) public void start() throws Exception { int port = properties.getPort(); NettyServerBuilder builder = NettyServerBuilder.forPort(port); ((Iterable<BindableService>) bindableServices).forEach(builder::addService); if (properties.isSecure()) { configureSsl(builder); } grpcServer = builder.build(); try { grpcServer.start(); } catch (IOException e) { throw new RuntimeException(e); } if (properties.getHealthCheckPort() > 0) { log.info("Starting health check at port {}", properties.getHealthCheckPort()); healthCheckSocket = new ServerSocket(properties.getHealthCheckPort()); healthChecker = new Thread(this::healthCheck, "Health Checker"); healthChecker.setDaemon(true); healthChecker.start(); } log.info("Server started, GRPC API listening on {}", grpcServer.getPort()); String endpointUrl = properties.getEndpointUrl(); if (endpointUrl == null) { log.warn("No endpoint url provided"); } else { for (Address address : ethereumConfig.getAddresses()) { ContractsManager contractManager = factory.getContractManager(address); EndpointRegistry registry = new EndpointRegistry(contractManager.endpointRegistry()); registry.registerEndpoint(address, endpointUrl); } } } private void healthCheck() { while (!Thread.interrupted() && !healthCheckSocket.isClosed()) { try { Socket socket = healthCheckSocket.accept(); socket.getOutputStream().write("OK".getBytes()); socket.close(); } catch (IOException e) { if (Thread.interrupted()) return; log.debug("Health check socket error", e); } } } private void configureSsl(NettyServerBuilder builder) throws NoSuchAlgorithmException, CertificateEncodingException, NoSuchProviderException, InvalidKeyException, SignatureException, SSLException { NativeLibraryLoader.loadFirstAvailable(ClassLoader.getSystemClassLoader(), "netty_tcnative_osx_x86_64", "netty_tcnative_linux_x86_64", "netty_tcnative_windows_x86_64" ); ECKeyPair ecKeyPair = ethereumConfig.getMainCredentials().getEcKeyPair(); KeyPair keyPair = CryptoUtil.decodeKeyPair(ecKeyPair); SslContextBuilder contextBuilder = SslContextBuilder.forServer( keyPair.getPrivate(), CryptoUtil.genCert(keyPair) ); builder.sslContext(GrpcSslContexts.configure(contextBuilder).build()); } @EventListener(ContextStoppedEvent.class) public void stop() throws InterruptedException { if (healthCheckSocket != null) { try { healthCheckSocket.close(); healthCheckSocket = null; } catch (Exception e) { log.warn("Failed to close socket", e); } } if (healthChecker != null) { healthChecker.interrupt(); healthChecker.join(); healthChecker = null; } grpcServer.shutdown(); } public void awaitTermination() throws InterruptedException { if (grpcServer != null) { grpcServer.awaitTermination(); } } }
use cli::get_starting_pile; use cli::paths::*; use handy_core::game::*; use handy_core::solver::*; use handy_core::utils::*; fn format_prefix_result(prefix_result: &PrefixResult) -> String { match prefix_result { PrefixResult::Event(event, pile) => { format!("{} {:?}", format_event_for_cli(event), pile) } PrefixResult::Pile(pile) => format!("Done Activation: {:?}", pile), } } fn card_activation_result_via_choices(pile: &Pile) -> Pile { let state = GameStateWithPileTrackedEventLog::new(pile.clone()); let future_states = resolve_top_card(&state); let mut current_pile = pile.clone(); let mut current_events: Vec<Event> = vec![]; loop { let event_options = find_next_events_matching_prefix(&future_states, &current_events); loop { println!("Current State: {:?}", current_pile); for (i, option) in event_options.iter().enumerate() { println!("{}: {}", i, format_prefix_result(option)); } let maybe_choice: Result<usize, _> = if event_options.len() == 1 { println!("Making only choice"); Ok(0) } else { text_io::try_read!() }; if let Ok(choice) = maybe_choice { if choice < event_options.len() { let prefix_result = &event_options[choice]; match prefix_result { PrefixResult::Event(event, pile) => { current_pile = pile.clone(); current_events.push(event.clone()); } PrefixResult::Pile(pile) => return pile.clone(), } break; } } println!("Invalid row number. Try again"); } } } fn card_activation_result_via_all_outcomes(pile: &Pile) -> Pile { let state = GameStateWithEventLog::new(pile.clone()); //let options = collapse_states(resolve_top_card(&state)); let options = resolve_top_card(&state); let matchup = try_get_matchup_from_pile(pile).unwrap(); let model = try_read_model_for_matchup(matchup).unwrap(); loop { println!("Current State: {:?}", pile); for (i, option) in options.iter().enumerate() { println!( "{}: {:?} via {} ({}) ({})", i, option.pile, format_multiple_events(&option.events), i, model.score_pile(&option.pile) ); } if options.len() == 1 { println!("Making only choice"); return options[0].pile.clone(); } let maybe_choice: Result<usize, _> = text_io::try_read!(); if let Ok(choice) = maybe_choice { if choice < options.len() { return options[choice].pile.clone(); } } println!("Invalid row number. Try again"); } } pub fn start_cli_game(mut active_pile: Pile, is_interactive_mode: bool) { loop { if let Some(winner) = is_game_winner(&active_pile) { println!("Game is over. {:?} wins!", winner); break; } if is_interactive_mode { active_pile = card_activation_result_via_choices(&active_pile); } else { active_pile = card_activation_result_via_all_outcomes(&active_pile); } } } fn main() { let start_pile = get_starting_pile(); start_cli_game(start_pile.into(), false); }
# frozen_string_literal: true module MediaWiktory::Wikipedia module Actions # Receive a bounce email and process it to handle the failing recipient. # # Usage: # # ```ruby # api.bouncehandler.email(value).perform # returns string with raw output # # or # api.bouncehandler.email(value).response # returns output parsed and wrapped into Response object # ``` # # See {Base} for generic explanation of working with MediaWiki actions and # {MediaWiktory::Wikipedia::Response} for working with action responses. # # All action's parameters are documented as its public methods, see below. # class Bouncehandler < MediaWiktory::Wikipedia::Actions::Post # The bounced email. # # @param value [String] # @return [self] def email(value) merge(email: value.to_s) end end end end
@extends('layouts.main') @section('container') <h1 class="mb-3 text-center">{{ $tittle }}</h1> <div class="row justify-content-center"> <div class="col-md-6"> <form action="/posts"> @if(request('category')) <input type="hidden" name="category" value="{{ request('category') }}"> @endif @if(request('author')) <input type="hidden" name="author" value="{{request('author')}}"> @endif <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Search.." name="search" value="{{request('search')}}"> <button class="btn btn-danger" type="submit">Search</button> </div> </form> </div> </div> @if ($posts->count()) <div class="card mb-3"> @if($posts[0]->image) <div style="max-height: 500px; overflow:hidden"> <img src="{{ asset('storage/' . $posts[0]->image)}}" alt="{{ $posts[0]->category->name }}" class="img-fluid"> </div> @else <img src="https://source.unsplash.com/1200x400?{{$posts[0]->category->name }}" class="card-img-top" alt="{{$posts[0]->category->name }}"> @endif <div class="card-body text-center"> <h3 class="card-title"><a href="/posts/{{ $posts[0]->slug }}" class="text-decoration-none text-dark">{{ $posts[0]->tittle }}</a></h3> <p> <small class="text-body-secondary"> BY. <a href="posts?author={{ $posts[0]->author->username }}" class="text-decoration-none">{{ $posts[0]->author->name }}</a>in <a href="/posts?category={{ $posts[0]->category->slug }}" class="text-decoration-none">{{ $posts[0]->category->name }}</a> {{ $posts[0]->created_at->diffForHumans() }} </small> </p> <p class="card-text">{{ $posts[0]->excerpt }}</p> <a href="/posts/{{ $posts[0]->slug }}" class="text-decoration-none btn btn-primary">Read more</a> </div> </div> <div class="container"> <div class="row"> @foreach($posts->skip(1) as $post) <div class="col-md-4 mb-3"> <div class="card"> <div class="position-absolute px-3 py-2 " style="background-color: rgba(0,0,0,0.7)"> <a href="/posts?category={{ $post->category->slug }}" class="text-white text-decoration-none">{{$post->category->name}}</a></div> @if($post->image) <img src="{{ asset('storage/' . $post->image)}}" alt="{{$post->category->name }}" class="img-fluid"> @else <img src="https://source.unsplash.com/500x400?{{$post->category->name }}" class="card-img-top" alt="{{$posts[0]->category->name }}"> @endif <div class="card-body"> <h5 class="card-title">{{$post->title}}</h5> <p> <small class="text-muted"> By. <a href="/posts?author={{$post->author->username}}" class="text-decoration-none">{{$post->author->name}}</a> {{$post->created_at->diffForHumans()}} </small> </p> <p class="card-text">{{$post->excerpt}}</p> <a href="/posts/{{$post->slug}}" class="btn btn-primary">Read more</a> </div> </div> </div> @endforeach </div> </div> @else <p class="text-center fs-4">No Post found.</p> @endif <div class="d-flex justify-content-end"> {{ $posts->links() }} </div> @endsection
import express, { Request, Response } from "express"; import { checkAuth } from "../auth/auth"; import { pool } from "../db/db"; import { User } from "../types/user"; import { fileUpload } from "../utils/fileUpload"; export const appRouter = express.Router(); appRouter.get("/", checkAuth, async (req: Request, res: Response) => { //@ts-ignore const userResult = await pool.query("SELECT * FROM users where email=$1", [ //@ts-ignore req.email, ]); const userRows = userResult.rows; if (!userRows.length) return res.sendStatus(401); const user: User = userResult.rows[0]; const companyId = user.companies_id; const company = await pool.query("SELECT * FROM companies WHERE id=$1", [ companyId, ]); const locations = await pool.query( "SELECT * FROM locations where companies_id=$1 ", [companyId] ); const locationIds = locations.rows.map((row) => row.id); const menuLocations = await pool.query( "SELECT * FROM menus_locations where locations_id = ANY($1::int[])", [locationIds] ); const menuIds = menuLocations.rows.map((row) => row.menus_id); const menus = await pool.query( "SELECT * FROM menus WHERE id= ANY($1::int[])", [menuIds] ); const menusMenuCategoriesResult = await pool.query( "SELECT * FROM menus_menu_categories WHERE menus_id = ANY($1::int[])", [menuIds] ); const menuCategoryIds = menusMenuCategoriesResult.rows.map( (row) => row.menu_categories_id ); const menuCategories = await pool.query( "SELECT * FROM menu_categories WHERE id = ANY($1::int[])", [menuCategoryIds] ); const menusAddonCategories = await pool.query( "SELECT * FROM menus_addon_categories WHERE menus_id= ANY($1::int[])", [menuIds] ); const addonCategoryIds = menusAddonCategories.rows.map( (row) => row.addon_categories_id ); const addonCategories = await pool.query( "SELECT * FROM addon_categories WHERE id=ANY($1::int[])", [addonCategoryIds] ); const addons = await pool.query( "SELECT * FROM addons WHERE addon_categories_id=ANY($1::int[])", [addonCategoryIds] ); res.send({ menus: menus.rows, menuCategories: menuCategories.rows, addons: addons.rows, addonCategories: addonCategories.rows, locations: locations.rows, menusLocations: menuLocations.rows, company: company.rows[0], }); }); appRouter.post("/assets", (req: Request, res: Response) => { try { fileUpload(req, res, (error) => { if (error) { return res.sendStatus(500); } console.log(req.files); const files = req.files as Express.MulterS3.File[]; const file = files[0]; const assetUrl = file.location; return res.send({ assetUrl }); }); } catch (error) { return res.sendStatus(500); } });
import time def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) # Example usage input_array = [80, 400, 180, 500, 20, 320, 120] sorted_array = quicksort(input_array) print("Sorted array:", sorted_array) # Worst-case scenario worst_case_input = list(range(1, 10001)) start_time = time.time() quicksort(worst_case_input) end_time = time.time() execution_time = end_time - start_time print(f"Time taken to sort worst-case input: {execution_time} seconds")
<!-- * The search page * @author: Bo Pang * @since: 2023-04-09 * [...slug].vue --> <template> <Head> <Title>Search: {{ keyword }}</Title> </Head> <div class="main-column"> <div class="catNav-wrapper clearfix"> <div pandatab="" class="pf-catNav" active-class=".current-menu-item,.current-menu-ancestor,.current-cat" sub-class=".sub-menu,.children" prev-text="<i class=pandastudio-icons-left ></i>" next-text="<i class=pandastudio-icons-right ></i>" sub-trigger="" auto-scrolling=""> <!-- <ul class="menu"> <li class="anchor" style="position: absolute; width: 72px; transform: translateX(1.99219px); left: 0px; opacity: 1;"> </li> <li id="menu-item-583" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-574 current_page_item menu-item-583" style=""><a href="https://www.ipangbo.cn/timeline" aria-current="page">时间线</a></li> <li id="menu-item-585" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-585"><a href="https://note.ipangbo.cn">Note站</a></li> <li id="menu-item-586" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-586"><a href="https://www.ipangbo.cn/category/site">网站</a></li> <li id="menu-item-588" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-588"><a href="https://www.ipangbo.cn/category/linux">Linux</a></li> <li id="menu-item-589" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-589"><a href="https://www.ipangbo.cn/category/build">开发 Build</a></li> <li id="menu-item-590" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-590"><a href="https://www.ipangbo.cn/category/game">游戏</a></li> <li id="menu-item-591" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-591"><a href="https://www.ipangbo.cn/category/%e7%95%99%e5%ad%a6">留学</a></li> <li id="menu-item-587" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-587"><a href="https://www.ipangbo.cn/category/uncategorized">未分类</a></li> </ul> --> </div> </div> <div class="main-container archive-list"> <div class="row post-card-row style-blog"> <TimeLineArticleCard v-for="(card, index) in currentPageCards" :card="card" :key="index"> </TimeLineArticleCard> <div>{{ status }}</div> </div> </div> <!-- <div class="pagination-wrapper clearfix"> <ul class="pf-pagination"> <li class="pagenumber" v-for="page in pageAmount" :key="page" :class="currentPage === page ? 'active' : ''"> <a @click="handleTogglePage(page)"> <span class="active">{{ page }}</span> </a> </li> </ul> </div> --> </div> </template> <script setup lang="ts"> import { useCurrentArticleStore } from '~/stores/currentArticle'; import { usePostsStore } from '~/stores/posts'; const route = useRoute(); const keyword = route.params.slug[0]; const status = ref('Searching...'); const currentArticleStore = useCurrentArticleStore(); currentArticleStore.title = `Search: ${keyword}` currentArticleStore.imgAddr = '/search_bg.png'; const postsStore = usePostsStore(); await postsStore.getSearchResult(keyword); const currentPageCards = postsStore.currentTimeLineCards; if (currentPageCards.length === 0) { status.value = 'No such result'; } else { status.value = ''; } </script> <style scoped> .pf-catNav[pandaTab] { visibility: hidden; } </style>
import { useMemo } from "react"; import { Connector } from "wagmi"; import { AvailableCosmosWallets } from "~/config/generated/cosmos-kit-wallet-list"; import { CosmosWalletRegistry } from "~/config/wallet-registry"; import { useConnectEvmWallet } from "~/hooks/evm-wallet"; export const WagmiWalletConnectType = "walletConnect"; export const WagmiMetamaskSdkType = "metaMask"; export const useSelectableWallets = ({ isMobile, includedWallets, }: { isMobile: boolean; includedWallets: ("cosmos" | "evm")[]; }) => { const { connectors } = useConnectEvmWallet(); const evmWallets = useMemo(() => { if (!includedWallets.includes("evm")) return []; return ( connectors .reduce((acc, wallet) => { const walletToAdd = { ...wallet, walletType: "evm" as const }; if (wallet.name === "MetaMask") { walletToAdd.icon = "/logos/metamask.svg"; } if (wallet.type === WagmiMetamaskSdkType) { walletToAdd.name = walletToAdd.name + " (Mobile)"; } if (wallet.name === "WalletConnect") { walletToAdd.icon = "/logos/walletconnect.svg"; } if (wallet.name === "Coinbase Wallet") { walletToAdd.icon = "/logos/coinbase.svg"; } return [...acc, walletToAdd]; }, [] as (Connector & { walletType: "evm" })[]) // type === "injected" should come first .sort((a, b) => { if (a.type === "injected" && b.type !== "injected") return -1; if (a.type !== "injected" && b.type === "injected") return 1; return 0; }) ); }, [connectors, includedWallets]); const cosmosWallets = useMemo(() => { if (!includedWallets.includes("cosmos")) return []; return ( CosmosWalletRegistry // If mobile, filter out browser wallets .reduce((acc, wallet, _index, array) => { if (isMobile) { /** * If an extension wallet is found in mobile, this means that we are inside an app browser. * Therefore, we should only show that compatible extension wallet. * */ if (acc.length > 0 && acc[0].name.endsWith("-extension")) { return acc; } const _window = window as Record<string, any>; const mobileWebModeName = "mobile-web"; /** * If on mobile and `leap` is in `window`, it means that the user enters * the frontend from Leap's app in app browser. So, there is no need * to use wallet connect, as it resembles the extension's usage. */ if (_window?.leap && _window?.leap?.mode === mobileWebModeName) { return array .filter((wallet) => wallet.name === AvailableCosmosWallets.Leap) .map((wallet) => ({ ...wallet, mobileDisabled: false })); } /** * If on mobile and `keplr` is in `window`, it means that the user enters * the frontend from Keplr's app in app browser. So, there is no need * to use wallet connect, as it resembles the extension's usage. */ if (_window?.keplr && _window?.keplr?.mode === mobileWebModeName) { return array .filter( (wallet) => wallet.name === AvailableCosmosWallets.Keplr ) .map((wallet) => ({ ...wallet, mobileDisabled: false })); } /** * If user is in a normal mobile browser, show only wallet connect */ return wallet.name.endsWith("mobile") ? [...acc, wallet] : acc; } return [...acc, wallet]; }, [] as (typeof CosmosWalletRegistry)[number][]) .map((wallet) => ({ ...wallet, walletType: "cosmos" as const, })) ); }, [includedWallets, isMobile]); return { evmWallets, cosmosWallets }; };
#pragma once #include "imgui.h" enum ImGuiToggleFlags_ { ImGuiToggleFlags_None = 0, ImGuiToggleFlags_Animated = 1 << 0, // The toggle should be animated. Mutually exclusive with ImGuiToggleFlags_Static. ImGuiToggleFlags_Static = 1 << 1, // The toggle should not animate. Mutually exclusive with ImGuiToggleFlags_Animated. ImGuiToggleFlags_BorderedFrame = 1 << 2, // The toggle should have a border drawn on the frame. ImGuiToggleFlags_BorderedKnob = 1 << 3, // The toggle should have a border drawn on the knob. ImGuiToggleFlags_HighlightEnabledKnob = 1 << 4, // The toggle's knob should be drawn in a highlight color when enabled. ImGuiToggleFlags_A11yLabels = 1 << 8, // The toggle should draw on and off labels to indicate its state. ImGuiToggleFlags_Bordered = ImGuiToggleFlags_BorderedFrame | ImGuiToggleFlags_BorderedKnob, // Shorthand for bordered frame and knob. ImGuiToggleFlags_Default = ImGuiToggleFlags_Static, // The default flags used when no ImGuiToggleFlags_ are specified. }; typedef int ImGuiToggleFlags; // -> enum ImGuiToggleFlags_ // Flags: for Toggle() modes namespace ImGuiToggleConstants { constexpr float Phi = 1.6180339887498948482045f; constexpr float DiameterToRadiusRatio = 0.5f; constexpr float AnimationSpeedDisabled = 0.0f; constexpr float AnimationSpeedDefault = 1.0f; constexpr float FrameRoundingDefault = 1.0f; constexpr float KnobRoundingDefault = 1.0f; constexpr float WidthRatioDefault = Phi; constexpr float KnobInsetDefault = 1.5f; constexpr float BorderThicknessDefault = 1.0f; constexpr float AnimationSpeedMinimum = 0.0f; constexpr float FrameRoundingMinimum = 0.0f; constexpr float FrameRoundingMaximum = 1.0f; constexpr float KnobRoundingMinimum = 0.0f; constexpr float KnobRoundingMaximum = 1.0f; constexpr float WidthRatioMinimum = 1.1f; constexpr float WidthRatioMaximum = 10.0f; constexpr float KnobInsetMinimum = -100.0f; constexpr float KnobInsetMaximum = 100.0f; } struct ImGuiToggleConfig { ImGuiToggleFlags Flags = ImGuiToggleFlags_Default; float AnimationSpeed = ImGuiToggleConstants::AnimationSpeedDefault; float FrameRounding = ImGuiToggleConstants::FrameRoundingDefault; float KnobRounding = ImGuiToggleConstants::KnobRoundingDefault; float WidthRatio = ImGuiToggleConstants::WidthRatioDefault; float KnobInset = ImGuiToggleConstants::KnobInsetDefault; float FrameBorderThickness = ImGuiToggleConstants::BorderThicknessDefault; float KnobBorderThickness = ImGuiToggleConstants::BorderThicknessDefault; const char* OnLabel = "1"; const char* OffLabel = "0"; ImVec2 Size = ImVec2(0.0f, 0.0f); }; namespace ImGui { // Widgets: Toggle Switches // - Toggles behave similarly to ImGui::Checkbox() // - Sometimes called a toggle switch, see also: https://en.wikipedia.org/wiki/Toggle_switch_(widget) // - They represent two mutually exclusive states, with an optional animation on the UI when toggled. // Optional parameters: // - flags: Values from the ImGuiToggleFlags_ enumeration to set toggle modes. // - speed: Animation speed scalar. (0,...] default: 1.0f (Overloads with this parameter imply ImGuiToggleFlags_Animated) // - frame_rounding: A scalar that controls how rounded the toggle frame is. 0 is square, 1 is round. (0, 1) default 1.0f // - knob_rounding: A scalar that controls how rounded the toggle knob is. 0 is square, 1 is round. (0, 1) default 1.0f IMGUI_API bool Toggle(const char* label, bool* v); IMGUI_API bool Toggle(const char* label, bool* v, ImGuiToggleFlags flags); IMGUI_API bool Toggle(const char* label, bool* v, ImGuiToggleFlags flags, float speed); IMGUI_API bool Toggle(const char* label, bool* v, ImGuiToggleFlags flags, float frame_rounding, float knob_rounding); IMGUI_API bool Toggle(const char* label, bool* v, ImGuiToggleFlags flags, float speed, float frame_rounding, float knob_rounding); IMGUI_API bool Toggle(const char* label, bool* v, const ImGuiToggleConfig& config); } // namespace ImGui
const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); var userSchema = new mongoose.Schema({ fullName: { type: String, required: 'Full name can\'t be empty' }, email: { type: String, required: 'Email can\'t be empty' }, otp: { type: String }, password: { type: String }, status:{ type:Number }, phone:{ type: String, }, address:{ type: String, }, qualification:{ type: String, }, passout:{ type: Number, }, skills:{ type: String, }, employmentStatus:{ type: String, }, techtraining:{ type: String, }, course:{ type: String, }, image:{ type: String, }, exitexammark:{ type: Number, }, studId:{ type: String, }, saltSecret: String }); // Custom validation for email // userSchema.path('email').validate((val) => { // emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; // return emailRegex.test(val); // }, 'Invalid e-mail.'); // Events // userSchema.pre('save', function (next) { // bcrypt.genSalt(10, (err, salt) => { // bcrypt.hash(this.password, salt, (err, hash) => { // this.password = hash; // this.saltSecret = salt; // next(); // }); // }); // }); // Methods userSchema.methods.verifyPassword = function (password) { return bcrypt.compareSync(password, this.password); }; userSchema.methods.generateJwt = function () { return jwt.sign({ _id: this._id}, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXP }); } mongoose.model('User', userSchema);
import React from "react"; import { Box, Typography, Link, Button } from "@mui/material"; import { Avatar } from "src/components/Avatar"; import { DeveloperType } from "src/types/DeveloperType"; import { UserType } from "src/types/RepositoryType"; import { FireIcon } from "src/components/Icons/FireIcon"; import { BranchIcon } from "src/components/Icons/BranchIcon"; import { HeartIcon } from "src/components/Icons/HeartIcon"; interface DeveloperProps { developer: DeveloperType; } export const Developer: React.FC<DeveloperProps> = ({ developer }) => { const user: UserType = { username: developer.username, url: developer.url, avatar: developer.avatar, }; return ( <Box sx={{ padding: "20px", borderWidth: "0 0 1px 0", borderColor: "secondary.main", borderStyle: "solid", display: "flex", flexDirection: "row", alignItems: "flex-start", }} > <Typography sx={{ width: "16px", fontSize: "12px", textAlign: "center" }}> {developer.rank} </Typography> <Box sx={{ marginX: "16px" }}> <Avatar user={user} size={"48px"} /> </Box> <Box sx={{ flexGrow: 1, display: "flex", flexDirection: "row" }}> <Box sx={{ width: "33.33%", display: "flex", flexDirection: "column", paddingRight: "8px", }} > <Link href={developer.url} sx={{ fontSize: "20px", fontWeight: "600", color: "#58a6ff", textDecoration: "none", marginBottom: "4px", ":hover": { textDecoration: "underline", }, }} > {developer.name} </Link> <Link href={developer.url} sx={{ fontSize: "16px", color: "text.secondary", textDecoration: "none", marginBottom: "4px", ":hover": { color: "#58a6ff", textDecoration: "underline", }, }} > {developer.username} </Link> </Box> <Box sx={{ width: "33.33%", paddingRight: "8px", }} > <Box sx={{ display: "flex", flexDirection: "row", alignItems: "center", marginBottom: "4px", }} > <FireIcon /> <Typography sx={{ fontSize: "12px", textTransform: "uppercase", marginLeft: "4px", }} > Popular Repo </Typography> </Box> <Link href={developer.popularRepository.url} sx={{ display: "flex", flexDirection: "row", alignItems: "center", textDecoration: "none", color: "#58a6ff", marginBottom: "4px", ":hover": { textDecoration: "underline", }, }} > <BranchIcon /> <Typography sx={{ fontSize: "16px", fontWeight: 600, marginLeft: "4px" }} > {developer.popularRepository.repositoryName} </Typography> </Link> {developer.popularRepository.description && ( <Typography>{developer.popularRepository.description}</Typography> )} </Box> <Box sx={{ width: "33.33%", display: "flex", flexDirection: "row", alignItems: "flex-start", justifyContent: "flex-end", }} > <Button variant="outlined" sx={{ padding: "3px 12px", borderRadius: "6px", borderColor: "secondary.main", bgcolor: "background.paper", marginRight: "8px", display: "flex", flexDirection: "row", alignItems: "center", ":hover": { borderColor: "text.secondary", }, }} > <HeartIcon /> <Typography sx={{ fontSize: "12px", fontWeight: 600, color: "text.primary", marginLeft: "6px", textTransform: "none", }} > Sponsor </Typography> </Button> <Button variant="outlined" sx={{ padding: "3px 12px", borderRadius: "6px", borderColor: "secondary.main", bgcolor: "background.paper", ":hover": { borderColor: "text.secondary", }, }} > <Typography sx={{ fontSize: "12px", fontWeight: 600, color: "text.primary", textTransform: "none", }} > Follow </Typography> </Button> </Box> </Box> </Box> ); };
from utils.dataset import TilesDatasetFly, TilesDataset from towbintools.towbintools.deep_learning.augmentation import get_mean_and_std, get_training_augmentation, get_validation_augmentation, grayscale_to_rgb, get_prediction_augmentation import os from time import perf_counter from pytorch_toolbelt.inference.tiles import ImageSlicer import pytorch_lightning as pl import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from joblib import Parallel, delayed from pytorch_toolbelt import inference import pytorch_toolbelt.losses as L import re from skimage.filters import threshold_otsu from sklearn.model_selection import train_test_split from torch import nn, optim from torch.utils.data import DataLoader from torch.utils.tensorboard.writer import SummaryWriter from torchmetrics.classification import BinaryF1Score from torchvision.transforms import Compose, Normalize, ToTensor from tqdm import tqdm import albumentations as albu from towbintools.foundation import image_handling, binary_image from utils.loss import FocalTverskyLoss from tqdm import tqdm from tifffile import imwrite from joblib import Parallel, delayed import cv2 from architectures import NestedUNet import pretrained_microscopy_models as pmm raw_dir = "/mnt/towbin.data/shared/btowbin/20230809_wBT23_LIPSI_for_body_mask_training/raw/" mask_dir = "/mnt/towbin.data/shared/btowbin/20230809_wBT23_LIPSI_for_body_mask_training/analysis/ch1_seg/" def extract_seq_number(filename): # Define a regular expression pattern to match the number after "Seq" pattern = r'Seq(\d+)' # Use re.search to find the first occurrence of the pattern in the filename match = re.search(pattern, filename) # Check if a match was found if match: # Extract and return the matched number as an integer seq_number = int(match.group(1)) return seq_number else: # Return None if no match was found return 0 raw_paths = sorted([os.path.join(raw_dir, file) for file in os.listdir(raw_dir)], key=extract_seq_number) mask_paths = sorted([os.path.join(mask_dir, file) for file in os.listdir(mask_dir)], key=extract_seq_number) # Create DataFrames raw_df = pd.DataFrame({'raw_path': raw_paths}) mask_df = pd.DataFrame({'mask_path': mask_paths}) # Assuming the sequence number is the same for both raw and mask files, # we can extract it from the paths and create a common column for merging raw_df['seq_number'] = raw_df['raw_path'].apply(extract_seq_number) mask_df['seq_number'] = mask_df['mask_path'].apply(extract_seq_number) # Merge DataFrames based on the seq_number merged_df = pd.merge(raw_df, mask_df, on='seq_number') merged_df = merged_df.dropna(how='any') raw_paths = merged_df['raw_path'].values.tolist() mask_paths = merged_df['mask_path'].values.tolist() print(raw_paths[-5:]) print(mask_paths[-5:]) cleaned_raw_dir = "/mnt/towbin.data/shared/btowbin/20230809_wBT23_LIPSI_for_body_mask_training/cleaned/raw/" cleaned_mask_dir = "/mnt/towbin.data/shared/btowbin/20230809_wBT23_LIPSI_for_body_mask_training/cleaned/ch1_seg/" os.makedirs(cleaned_raw_dir, exist_ok=True) os.makedirs(cleaned_mask_dir, exist_ok=True) def clean_training_zstack(raw_path, mask_path): try: raw = image_handling.read_tiff_file(raw_path) mask = image_handling.read_tiff_file(mask_path) # look at all the planes of the mask get indexes of completely black planes black_planes = [] for i, plane in enumerate(mask): if np.max(plane) == 0: black_planes.append(i) # if there are black planes, remove them from the raw and mask if len(black_planes) > 0: raw = np.delete(raw, black_planes, axis=0) mask = np.delete(mask, black_planes, axis=0) # look at the remaining planes and remove those with more than 2 connected components print('remaining planes', mask.shape[0]) if mask.shape[0] == 0: return planes_to_remove = [] for i, plane in enumerate(mask): nb_labels, labels = cv2.connectedComponents(plane) if nb_labels > 2: planes_to_remove.append(i) if len(planes_to_remove) > 0: raw = np.delete(raw, planes_to_remove, axis=0) mask = np.delete(mask, planes_to_remove, axis=0) # save all remaining planes into individual tiffs if mask.shape[0] > 0: for i, plane in enumerate(mask): # binary closing fill bright holes and median filter the mask plane = cv2.morphologyEx(plane, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10,10))) plane = binary_image.fill_bright_holes(raw, plane, 1) plane = cv2.medianBlur(plane, 5) imwrite(os.path.join(cleaned_mask_dir, f"{os.path.basename(mask_path)[:-5]}_{i}.tiff"), plane.astype(np.uint8), compression="zlib") imwrite(os.path.join(cleaned_raw_dir, f"{os.path.basename(raw_path)[:-5]}_{i}.tiff"), raw[i], compression="zlib") except IndexError: pass Parallel(n_jobs=32, prefer='processes')(delayed(clean_training_zstack)(raw_path, mask_path) for raw_path, mask_path in (zip(raw_paths, mask_paths)))
<script setup> import BreezeAuthenticatedLayout from '@/Layouts/Authenticated.vue'; </script> <template> <Head title="Menus" /> <BreezeAuthenticatedLayout> <template #header> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> Menus </h2> </template> <div class="py-4 px-4"> <div class="overflow-x-auto"> <div class="mx-auto"> <div class="align-top inline-block w-full lg:w-1/2 px-2 mb-3"> <div class="flex pb-4 relative text-gray-400 focus-within:text-gray-600"> <Link :href="route('menus.add_menu')" as="button" class="bg-indigo-700 hover:bg-indigo-900 text-white font-bold py-2 px-4 rounded"> Add Menu </Link> </div> <div class="shadow overflow-hidden overflow-x-auto hover:no-scrollbar border-b border-gray-200 sm:rounded-lg"> <table class="min-w-full divide-y divide-gray-200 w-full "> <thead class="bg-gray-200"> <tr> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/12">#</th> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-2/6">Menu Name</th> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-2/6">Route Name</th> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/6">Status</th> <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-2/6">Action</th> </tr> </thead> <tbody class="bg-white divide-y divide-gray-200 overflow-y-scroll"> <tr v-if="$page.props.menus.length == 0"> <td class="text-center" colspan="10"> <div class="p-3"> No Record Found! </div> </td> </tr> <tr class="hover:bg-gray-200" v-for="(menu, menuID) in $page.props.menus" :key="menuID"> <td class="px-6 py-2 whitespace-nowrap text-sm">{{ ++menuID }}</td> <td class="px-2 py-2 whitespace-nowrap"> <div class="flex items-center"> <div class="ml-4"> <div class="text-sm font-medium text-gray-900">{{ menu.menu_label }}</div> </div> </div> </td> <td class="px-2 py-2 whitespace-nowrap"> <div class="flex items-center"> <div class="ml-4"> <div class="text-sm font-medium text-gray-900" :class="menu.menu_route ? '' : 'font-extrabold font-black'">{{ menu.menu_route ? menu.menu_route : 'None' }}</div> </div> </div> </td> <td class="px-6 py-2 whitespace-nowrap"> <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full" :class="menu.menu_status == 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"> {{ menu.menu_status == 1 ? 'Active' : 'Not Active'}} </span> </td> <td class="px-6 py-2 whitespace-nowrap text-center text-sm font-medium"> <div class="flex"> <div class="pr-1"> <button class="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-1 px-1 border border-yellow-700 rounded" @click="editMenu(menu.id)" title="Edit"> <PencilIcon class="text-white-600 h-4 w-4 fill-current"></PencilIcon> </button> </div> <div class="pr-1"> <button class="bg-red-500 hover:bg-red-600 text-white font-bold py-1 px-1 border border-red-700 rounded" @click="deleteMenu(menu.id)" title="Delete"> <TrashIcon class="text-white-600 h-4 w-4 fill-current"></TrashIcon> </button> </div> <div class="pr-1"> <button class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-1 px-1 border border-blue-700 rounded" @click="showSubMenu(menu.id)" title="View Sub Menu"> <ChevronRightIcon class="text-white-600 h-4 w-4 fill-current"></ChevronRightIcon> </button> </div> </div> </td> </tr> </tbody> </table> </div> </div> <div class="align-top inline-block w-full lg:w-1/2 px-2" v-show="show_sub_menu"> <div class="flex pb-4 relative text-gray-400 focus-within:text-gray-600 lg:justify-end"> <Link @click="addSubMenu(menu_id)" class="bg-indigo-700 hover:bg-indigo-900 text-white font-bold py-2 px-4 rounded" as="button"> Add Sub Menu </Link> <!-- <SearchIcon class="text-gray-600 h-4 w-4 fill-current pointer-events-none absolute top-1/4 left-3"></SearchIcon> <input class="border-2 border-gray-300 bg-white h-10 px-5 pr-16 rounded-lg text-sm focus:ring-0 focus:border-gray-300 appearance-none block pl-10" type="text" v-model="params.search" placeholder="Search"> --> </div> <div class="shadow overflow-hidden overflow-x-auto hover:no-scrollbar border-b border-gray-200 sm:rounded-lg"> <table class="min-w-full divide-y divide-gray-200 w-full"> <thead class="bg-gray-200"> <tr> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/12">#</th> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-4/6">Sub Menu Name</th> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-2/6">Route Name</th> <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-2/6">Status</th> <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-1/6">Action</th> </tr> </thead> <tbody class="bg-white divide-y divide-gray-200 overflow-y-scroll"> <tr v-if="$page.props.sub_menus.length == 0"> <td class="text-center" colspan="10"> <div class="p-3"> No Record Found! </div> </td> </tr> <tr class="hover:bg-gray-200" v-for="(sub_menu, menuID) in $page.props.sub_menus" :key="menuID"> <td class="px-6 py-2 whitespace-nowrap text-sm">{{ ++menuID }}</td> <td class="px-2 py-2 whitespace-nowrap"> <div class="flex items-center"> <div class="ml-4"> <div class="text-sm font-medium text-gray-900">{{ sub_menu.menu_sub_label }}</div> </div> </div> </td> <td class="px-2 py-2 whitespace-nowrap"> <div class="flex items-center"> <div class="ml-4"> <div class="text-sm font-medium text-gray-900" :class="sub_menu.menu_sub_route ? '' : 'font-extrabold'">{{ sub_menu.menu_sub_route ? sub_menu.menu_sub_route : 'None' }}</div> </div> </div> </td> <td class="px-6 py-2 whitespace-nowrap"> <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full" :class="sub_menu.menu_sub_status == 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"> {{ sub_menu.menu_sub_status == 1 ? 'Active' : 'Not Active' }} </span> </td> <td class="px-6 py-2 whitespace-nowrap text-center text-sm font-medium"> <div class="flex"> <div class="pr-1"> <button class="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-1 px-1 border border-yellow-700 rounded" @click="editSubMenu(sub_menu.id)" title="Delete"> <PencilIcon class="text-white-600 h-4 w-4 fill-current"></PencilIcon> </button> </div> <div class="pr-1"> <button class="bg-red-500 hover:bg-red-600 text-white font-bold py-1 px-1 border border-red-700 rounded" @click="deleteSubMenu(sub_menu.id)" title="Delete"> <TrashIcon class="text-white-600 h-4 w-4 fill-current"></TrashIcon> </button> </div> </div> </td> </tr> </tbody> </table> </div> </div> </div> </div> <ConfirmationModal :show="isOpen" @close="isOpen = !isOpen" confirmationAlert="danger" confirmationTitle="Delete Menu" confirmationText="Are you sure want to delete this menu?" confirmationButton="Delete" confirmationMethod="delete" :confirmationRoute="confirmationRoute" :confirmationData="confirmationData" > </ConfirmationModal> </div> </BreezeAuthenticatedLayout> </template> <script> import { SearchIcon, TrashIcon, PencilIcon, ChevronRightIcon } from '@heroicons/vue/solid' import { Head, Link } from '@inertiajs/inertia-vue3'; import ConfirmationModal from '@/Components/ConfirmationModal.vue' export default { components: { SearchIcon, TrashIcon, PencilIcon, ChevronRightIcon, ConfirmationModal, Head, Link }, props: { show_sub_menu: Boolean, menu_id: String, }, data(){ return{ isOpen: false, confirmationTitle: '', confirmationText: '', confirmationAlert: '', confirmationButton: '', confirmationMethod: '', confirmationRoute: '', confirmationData: '', } }, methods: { showSubMenu(menu_id){ this.$inertia.get(route('menus'), {menu_id: menu_id}) }, addSubMenu(menu_id){ this.$inertia.get(route('menus.add_sub_menu'), {menu_id: menu_id}) }, editMenu(menu_id){ this.$inertia.get(route('menus.edit_menu'), {menu_id: menu_id}) }, editSubMenu(menu_id){ this.$inertia.get(route('menus.edit_sub_menu'), {menu_id: menu_id}) }, deleteMenu(menu_id){ this.confirmationRoute = 'menus.destroy_menu' this.confirmationData = menu_id this.isOpen = true }, deleteSubMenu(menu_id){ this.confirmationRoute = 'menus.destroy_sub_menu' this.confirmationData = menu_id this.isOpen = true }, }, } </script>
import {NgModule} from "@angular/core"; import {RouterModule, Routes} from "@angular/router"; import {RecipesComponent} from "./recipes.component"; import {AuthGuard} from "../auth/auth.guard"; import {RecipesUnselectedComponent} from "./recipes.unselected.component"; import {RecipeEditComponent} from "./recipe-edit/recipe-edit.component"; import {RecipeDetailComponent} from "./recipe-detail/recipe-detail.component"; import {RecipesResolver} from "../recipes-resolver.service"; const recipeRoutes: Routes = [{ path: '', component: RecipesComponent, canActivate: [AuthGuard], children: [ {path: '', component: RecipesUnselectedComponent}, {path: 'new', component: RecipeEditComponent}, {path: ':id', component: RecipeDetailComponent, resolve: [RecipesResolver]}, {path: ':id/edit', component: RecipeEditComponent, resolve: [RecipesResolver]}, ] }]; @NgModule({ imports: [RouterModule.forChild(recipeRoutes)], exports: [RouterModule], }) export class RecipesRoutingModule { }
--- title: "Development Setup" description: "How to set-up your development environment" --- ## Clone the repo ``` git clone https://github.com/nocodb/nocodb cd nocodb/packages ``` ## Build SDK ``` # build nocodb-sdk cd nocodb-sdk npm install npm run build ``` ## Build Backend ``` # build backend - runs on port 8080 cd ../nocodb npm install npm run watch:run ``` ## Build Frontend ``` # build frontend - runs on port 3000 cd ../nc-gui npm install npm run dev ``` Any changes made to frontend and backend will be automatically reflected in the browser. ## Enabling CI-CD for Draft PR CI-CD will be triggered on moving a PR from draft state to `Ready for review` state & on pushing changes to `Develop`. To verify CI-CD before requesting for review, add label `trigger-CI` on Draft PR. ## Accessing CI-CD Failure Screenshots For Playwright tests, screenshots are captured on the tests. These will provide vital clues for debugging possible issues observed in CI-CD. To access screenshots, Open link associated with CI-CD run & click on `Artifacts` ![Screenshot 2022-09-29 at 12 43 37 PM](https://user-images.githubusercontent.com/86527202/192965070-dc04b952-70fb-4197-b4bd-ca7eda066e60.png) ## Accessing 'Easter egg' menu Double click twice on empty space between `View list` & `Share` button to the left top of Grid view; following options become accessible 1. Export Cache 2. Delete Cache 3. Debug Meta 4. Toggle Beta Features ![Screenshot 2023-05-23 at 8 35 14 PM](https://github.com/nocodb/nocodb/assets/86527202/fe2765fa-5796-4d26-8c12-e71b8226872e)
"use client" import React, { useEffect, useState } from 'react'; import { FaHome, FaUser } from 'react-icons/fa'; import Link from 'next/link'; import { useCookies } from 'react-cookie'; import { jwtDecode } from 'jwt-decode'; import axios from 'axios'; import toast from 'react-hot-toast'; const HomePage = () => { const [cookies] = useCookies(['token']); const [role, setRole] = useState(null); const [data, setData] = useState([]); useEffect(() => { const token = cookies.token; if (token) { const decodedToken = jwtDecode(token); const userRole = decodedToken.user.role; setRole(userRole); } else { setRole(null); } }, [cookies.token]); useEffect(() => { async function getWorkshops() { try { const token = localStorage.getItem('user._id'); const headers = { Authorization: `Bearer ${token}` }; const response = await axios.get(process.env.NEXT_PUBLIC_URL_USER + 'workshop/availableWorkshops', { headers }); setData(response.data); } catch (error) { console.error('An error occurred:', error); } } getWorkshops(); }, []); const handleApply = async (workshop) => { try { const token = localStorage.getItem('user._id'); const headers = { Authorization: `Bearer ${token}` }; const decodedToken = jwtDecode(token); const userId = decodedToken.user._id; const payload = { user: userId, workshop: workshop, }; const response = await axios.post(process.env.NEXT_PUBLIC_URL_USER + 'application/workshopApplication', payload, { headers }); if (response.status === 201) { toast.success('Application successful!'); } } catch (error) { toast.error('An error occurred. Please try again.'); } }; return ( <div className="container"> <div className="max-w-6xl mx-auto"> {role && (role.includes('user') || role.includes('admin') || role.includes('professor')) ? ( <> <h1 className="main-title">Code Camp Sessions</h1> <div className="space-y-8"> {data.map(workshop => ( <div key={workshop._id} className="p-6 bg-secondary rounded-lg shadow-md text-white"> <h2 className="text-4xl font-semibold mb-6">{workshop.name}</h2> <p className="text-xl mb-6">{workshop.description}</p> <div className="text-gray-400 mb-6"> <p className="text-lg"><strong>Start Date:</strong> {workshop.StartDate}</p> <p className="text-lg"><strong>End Date:</strong> {workshop.EndDate}</p> <p className="text-lg"><strong>Professor:</strong> {workshop.professor}</p> </div> <button className="btn enabled-button text-white text-lg rounded-full w-full" onClick={() => handleApply(workshop._id)}>Apply</button> </div> ))} </div> </> ) : ( <> <h1 className="main-title mb-8">Welcome to Code Camp</h1> <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8"> <div className="flex flex-col justify-center items-center bg-secondary p-8 rounded-lg"> <FaHome className="text-5xl text-blue-500 mb-4" /> <h2 className="text-2xl font-semibold mb-4 text-white">About Us</h2> <p className="text-lg text-gray-300"> We are a company that offers coding workshops for beginners and advanced developers. Our workshops are designed to help you learn how to code and become a professional developer. </p> </div> <div className="flex flex-col justify-center items-center bg-gray-800 p-8 rounded-lg"> <FaUser className="text-5xl text-blue-500 mb-4" /> <h2 className="text-2xl font-semibold mb-4 text-white">Register Now</h2> <p className="text-lg text-gray-300"> If you already know that you want to join our Code Camp, you can register right away. Just click on the <Link href="/register" className="underline text-white">Register</Link> link and fill out the form. We are looking forward to welcoming you. </p> </div> </div> </> )} </div> </div> ); }; export default HomePage;
 Birçok mühendis kodlamaya output (çıkış) komutlarını yazarak başlar. Bugün sizlerle birlikte bu output örneklerinin en basitini, C# programlama dilinde nasıl yazıldığını öğreneceğiz ve C# programlama diline kısa bir giriş yapacağız. ```cpp using System; // ad alanini tanimlama (c++ ve c'deki kutuphaneye // benzer) namespace ProgramAdi // kapsayici tanimlama { class SinifAdi // sinif tanimlama { static void Main() // ana fonksiyonu tanimlama { /* ana fonksiyon, c++ ve c'deki main() fonksiyonu ile ayni seydir */ Console.WriteLine("Hello world!"); /* ekrana "Hello World!" yazdirir */ } } } ``` Yukarda yazılan kodlarda ilk olarak kullanacağımız “**ad alanını** (**namespace**)” programa tanıttık. Sonrasında ise **kapsayıcı (namespace)**ve **sınıf (class)** tanımladık. Son adımda ise kodlarımızın büyük bir bölümünü yazacağımız ana fonksiyonu açtık ve içerisine output (çıkış) yazdık. Program çalıştığı zaman output verir ve bu output’ta “hello world” yazar.
System.register(["vue"], function (exports_1, context_1) { "use strict"; var vue_1, vue_2; var __moduleName = context_1 && context_1.id; return { setters: [ function (vue_1_1) { vue_1 = vue_1_1; vue_2 = vue_1_1; } ], execute: function () { exports_1("default", vue_2.defineComponent({ name: "FieldFilterContainer", props: { compareLabel: { type: String }, }, setup(props, ctx) { const hasCompareColumn = vue_1.computed(() => !!ctx.slots.compare || !!props.compareLabel); const hasCompareLabel = vue_1.computed(() => !!props.compareLabel); const compareColumnClass = vue_1.computed(() => { if (ctx.slots.compare) { return "col-xs-12 col-md-4"; } else if (props.compareLabel) { return "col-xs-12 col-md-2"; } else { return ""; } }); const valueColumnClass = vue_1.computed(() => { if (ctx.slots.compare) { return "col-xs-12 col-md-8"; } else if (props.compareLabel) { return "col-xs-12 col-md-10"; } else { return "col-xs-12 col-md-12"; } }); return { compareColumnClass, hasCompareColumn, hasCompareLabel, valueColumnClass }; }, template: ` <div class="row form-row field-criteria"> <div v-if="hasCompareColumn" :class="compareColumnClass"> <span v-if="hasCompareLabel" class="data-view-filter-label">{{ compareLabel }}</span> <slot v-else name="compare" /> </div> <div :class="valueColumnClass"> <slot /> </div> </div> ` })); } }; }); //# sourceMappingURL=fieldFilterContainer.js.map
<template> <img :id="id" crossOrigin="anonymous" :style="styleObject" :src="src" :alt="alt" @click="clickHandler" @error="loadErrHandler" /> </template> <script> export default { name: "CvImage", // eslint-disable-next-line vue/require-prop-types props: ['address', 'scale', 'maxHeight', 'maxHeightMd', 'maxHeightLg', 'maxHeightXl', 'colorPicking', 'id', 'disconnected', 'alt'], data() { return { seed: 1.0, } }, computed: { styleObject: { get() { let ret = { "border-radius": "3px", "display": "block", "object-fit": "contain", "background-size:": "contain", "object-position": "50% 50%", "max-width": "100%", "margin-left": "auto", "margin-right": "auto", "max-height": this.maxHeight, height: `${this.scale}%`, cursor: (this.colorPicking ? `url(${require("../../assets/eyedropper.svg")}),` : "pointer") + "default", }; if (this.$vuetify.breakpoint.xl) { ret["max-height"] = this.maxHeightXl; } else if (this.$vuetify.breakpoint.lg) { ret["max-height"] = this.maxHeightLg; } else if (this.$vuetify.breakpoint.md) { ret["max-height"] = this.maxHeightMd; } return ret; } }, src: { get() { var port = this.getCurPort(); if(port <= 0){ //Invalid port, keep it spinny return require("../../assets/loading.gif"); } else { //Valid port, connect return this.getSrcURLFromPort(port); } }, }, }, mounted() { this.reload(); // Force reload image on creation }, methods: { getCurPort(){ var port = -1; if(this.disconnected){ //Disconnected, port is unknown. port = -1; } else { //Connected - get the port if(this.id == 'raw-stream'){ port = this.$store.state.cameraSettings[this.$store.state.currentCameraIndex].inputStreamPort } else { port = this.$store.state.cameraSettings[this.$store.state.currentCameraIndex].outputStreamPort } } return port; }, getSrcURLFromPort(port){ return "http://" + location.hostname + ":" + port + "/stream.mjpg" + "?" + this.seed; }, loadErrHandler(event) { console.log(event); console.log("Error loading image, attempting to do it again..."); this.reload(); }, clickHandler(event) { if(this.colorPicking){ this.$emit('click', event); } else { var port = this.getCurPort(); if(port <= 0){ console.log("No valid port, ignoring click."); } else { //Valid port, connect window.open(this.getSrcURLFromPort(port), '_blank'); } } }, reload() { this.seed = new Date().getTime(); } }, } </script>
import { useState } from "react"; import axios from "axios"; import "./NewsSearch.css"; import { Link } from 'react-router-dom'; const NewsSearch = () => { const [query, setQuery] = useState(""); const [apiResponse, setApiResponse] = useState(null); const [loading, setLoading] = useState(false); const handleChange = (e) => { setQuery(e.target.value); }; const fetchData = async () => { setLoading(true); try { const cachedData = localStorage.getItem(query); if (cachedData) { setApiResponse(JSON.parse(cachedData)); } else { const response = await axios.get( `https://newsapi.org/v2/everything?q=${query}&apiKey=8aba765311894dde983f4a8c080b838f` ); const articles = response.data.articles; setApiResponse(articles); localStorage.setItem(query, JSON.stringify(articles)); } } catch (error) { console.log("Error fetching data:", error); } setLoading(false); }; return ( <div className="news-search-container"> <input type="text" value={query} onChange={handleChange} placeholder="Search for news..." className="search-input" /> <button onClick={fetchData} className="search-button"> Search </button> <div className="news-data"> {loading ? ( <p className="loading">Loading...</p> ) : apiResponse && apiResponse.length > 0 ? ( apiResponse.map((article, index) => ( <div key={index} className="article-card"> <h2 className="article-title">{article.title}</h2> <p className="article-content">{article.content}</p> {article.urlToImage ? ( <img src={article.urlToImage} alt="article" className="article-image" /> ) : ( <p className="no-image">No Image Found</p> )} <div className="time-detail"> <div className="detail-page"> <Link key={index} to={article.url} className="detail" target="_blank" > More Details </Link> </div> <p className="article-date"> {new Date(article.publishedAt).toLocaleString()} </p> </div> </div> )) ) : ( <p className="no-articles">No articles found</p> )} </div> </div> ); }; export default NewsSearch;
from django.db import models from django.contrib.auth.models import User from pathlib import Path from datetime import datetime import os CYRILLIC_SYMBOLS = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяєіїґ" TRANSLATION = ( "a", "b", "v", "g", "d", "e", "e", "j", "z", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "h", "ts", "ch", "sh", "sch", "", "y", "", "e", "yu", "u", "ja", "je", "ji", "g", ) image_files = {".jpeg", ".png", ".jpg", ".svg", ".bmp", ".ico", ".gif"} video_files = {".mp4", ".mov", ".webm", ".avi", "mkv", ".wmv", ".flv"} audio_files = {".mp3", ".wav", ".m4a", ".aiff", ".ogg", ".cda"} document_files = { ".docx", ".doc", ".pptx", ".xlsx", ".html", ".htm", ".html5", ".txt", ".ini", ".xml", ".ppt", ".py", ".md", ".toml", "yml", ".cpp", ".h", ".java", ".css", ".js", ".csv", } archive_files = {".rar", ".rar4", ".zip", ".tar", ".bz2", ".7z", ".apk", ".dmg", ".jar"} other_files = {} FILE_TYPES = { "image": image_files, "video": video_files, "audio": audio_files, "document": document_files, "archive": archive_files, "other": other_files, } def get_file_type(filename): """ Determines the file type of file based on its extension. Args: filename (str): The name of the file. Returns: str: The determined file type, or 'other' if the file type cannot be determined. """ extension = Path(filename).suffix TRANS = {} for cyrillic, latin in zip(CYRILLIC_SYMBOLS, TRANSLATION): TRANS[ord(cyrillic)] = latin TRANS[ord(cyrillic.lower())] = latin.lower() for file_type, extensions in FILE_TYPES.items(): if extension in extensions: return file_type return "other" def update_filename(instance, filename): """ Generates a new filename using the current date and time to ensure uniqueness and sorts it into a folder based on its type. Args: instance: The instance of the model where the file is being attached. filename (str): The original file name uploaded by the user. Returns: str: A new file path including the folder and new filename. """ filepath = Path(filename) now = datetime.now().strftime("%Y%m%d-%H%M") filename = f"{now}_{filepath.name}" type_id = get_file_type(filepath.name) return os.path.join(type_id, filename) class UserFile(models.Model): """ Model representing a user's file including metadata about the file. Attributes: filepath (FileField): Path to the file including the filename. file_description (CharField): Optional description of the file. uploaded_at (DateTimeField): The datetime when the file was uploaded, set automatically. user (ForeignKey): Reference to the User who owns the file. filename (CharField): The name of the file. file_type (CharField): The type of file, determined automatically by the system. """ filepath = models.FileField() file_description = models.CharField(max_length=255, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( User, related_name="files", on_delete=models.CASCADE, null=True ) filename = models.CharField(max_length=255, null=True) file_type = models.CharField("File type", max_length=50, default="other") def save(self, **kwargs): """ Overwrites the save method to ensure the filename and file type are set when the file is saved. """ self.filename = self.filepath.name self.file_type = get_file_type(self.filepath.name) super().save(**kwargs)
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Gentoo Linux Security Advisory GLSA 201404-05. # # The advisory text is Copyright (C) 2001-2016 Gentoo Foundation, Inc. # and licensed under the Creative Commons - Attribution / Share Alike # license. See http://creativecommons.org/licenses/by-sa/3.0/ # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(73394); script_version("1.8"); script_set_attribute(attribute:"plugin_modification_date", value:"2021/01/06"); script_cve_id("CVE-2009-1250", "CVE-2009-1251", "CVE-2011-0430", "CVE-2011-0431", "CVE-2013-1794", "CVE-2013-1795", "CVE-2013-4134", "CVE-2013-4135"); script_bugtraq_id(34404, 34407, 46428, 58299, 58300, 61438, 61439); script_xref(name:"GLSA", value:"201404-05"); script_name(english:"GLSA-201404-05 : OpenAFS: Multiple vulnerabilities"); script_summary(english:"Checks for updated package(s) in /var/db/pkg"); script_set_attribute( attribute:"synopsis", value: "The remote Gentoo host is missing one or more security-related patches." ); script_set_attribute( attribute:"description", value: "The remote host is affected by the vulnerability described in GLSA-201404-05 (OpenAFS: Multiple vulnerabilities) Multiple vulnerabilities have been discovered in OpenAFS. Please review the CVE identifiers referenced below for details. Impact : An attacker could potentially execute arbitrary code with the permissions of the user running the AFS server, cause a Denial of Service condition, or gain access to sensitive information. Additionally, an attacker could compromise a cell&rsquo;s private key, allowing them to impersonate any user in the cell. Workaround : There is no known workaround at this time." ); script_set_attribute( attribute:"see_also", value:"https://security.gentoo.org/glsa/201404-05" ); script_set_attribute( attribute:"solution", value: "All OpenAFS users should upgrade to the latest version: # emerge --sync # emerge --ask --oneshot --verbose '>=net-fs/openafs-1.6.5'" ); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:C/I:C/A:C"); script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available"); script_set_attribute(attribute:"exploit_available", value:"false"); script_cwe_id(119, 189); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:gentoo:linux:openafs"); script_set_attribute(attribute:"cpe", value:"cpe:/o:gentoo:linux"); script_set_attribute(attribute:"patch_publication_date", value:"2014/04/07"); script_set_attribute(attribute:"plugin_publication_date", value:"2014/04/08"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2014-2021 Tenable Network Security, Inc."); script_family(english:"Gentoo Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/Gentoo/release", "Host/Gentoo/qpkg-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("qpkg.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/Gentoo/release")) audit(AUDIT_OS_NOT, "Gentoo"); if (!get_kb_item("Host/Gentoo/qpkg-list")) audit(AUDIT_PACKAGE_LIST_MISSING); flag = 0; if (qpkg_check(package:"net-fs/openafs", unaffected:make_list("ge 1.6.5"), vulnerable:make_list("lt 1.6.5"))) flag++; if (flag) { if (report_verbosity > 0) security_hole(port:0, extra:qpkg_report_get()); else security_hole(0); exit(0); } else { tested = qpkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "OpenAFS"); }
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from openSUSE Security Update openSUSE-2020-1664. # # The text description of this plugin is (C) SUSE LLC. # include("compat.inc"); if (description) { script_id(141409); script_version("1.5"); script_set_attribute(attribute:"plugin_modification_date", value:"2021/01/11"); script_cve_id("CVE-2020-14364", "CVE-2020-15863", "CVE-2020-16092", "CVE-2020-24352"); script_xref(name:"IAVB", value:"2020-B-0063-S"); script_name(english:"openSUSE Security Update : qemu (openSUSE-2020-1664)"); script_summary(english:"Check for the openSUSE-2020-1664 patch"); script_set_attribute( attribute:"synopsis", value:"The remote openSUSE host is missing a security update." ); script_set_attribute( attribute:"description", value: "This update for qemu fixes the following issues : - CVE-2020-14364: Fixed an OOB access while processing USB packets (bsc#1175441,bsc#1176494). - CVE-2020-16092: Fixed a denial of service in packet processing of various emulated NICs (bsc#1174641). - CVE-2020-15863: Fixed a buffer overflow in the XGMAC device (bsc#1174386). - CVE-2020-24352: Fixed an out-of-bounds read/write in ati-vga device emulation in ati_2d_blt (bsc#1175370). - Allow to IPL secure guests with -no-reboot (bsc#1174863) This update was imported from the SUSE:SLE-15-SP2:Update update project." ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1174386" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1174641" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1174863" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1175370" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1175441" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1176494" ); script_set_attribute(attribute:"solution", value:"Update the affected qemu packages."); script_set_cvss_base_vector("CVSS2#AV:L/AC:M/Au:N/C:P/I:P/A:P"); script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C"); script_set_cvss3_base_vector("CVSS:3.0/AV:L/AC:H/PR:L/UI:N/S:C/C:L/I:L/A:L"); script_set_cvss3_temporal_vector("CVSS:3.0/E:U/RL:O/RC:C"); script_set_attribute(attribute:"cvss_score_source", value:"CVE-2020-15863"); script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-arm"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-arm-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-audio-alsa"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-audio-alsa-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-audio-pa"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-audio-pa-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-audio-sdl"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-audio-sdl-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-curl"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-curl-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-dmg"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-dmg-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-gluster"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-gluster-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-iscsi"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-iscsi-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-nfs"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-nfs-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-rbd"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-rbd-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-ssh"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-block-ssh-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-debugsource"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-extra"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-extra-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-guest-agent"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-guest-agent-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ipxe"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ksm"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-kvm"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-lang"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-linux-user"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-linux-user-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-linux-user-debugsource"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-microvm"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ppc"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ppc-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-s390"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-s390-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-seabios"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-sgabios"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-testsuite"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-tools"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-tools-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-curses"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-curses-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-gtk"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-gtk-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-sdl"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-sdl-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-spice-app"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-ui-spice-app-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-vgabios"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-vhost-user-gpu"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-vhost-user-gpu-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-x86"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:qemu-x86-debuginfo"); script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:opensuse:15.2"); script_set_attribute(attribute:"vuln_publication_date", value:"2020/07/28"); script_set_attribute(attribute:"patch_publication_date", value:"2020/10/12"); script_set_attribute(attribute:"plugin_publication_date", value:"2020/10/13"); script_set_attribute(attribute:"generated_plugin", value:"current"); script_set_attribute(attribute:"stig_severity", value:"II"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2020-2021 and is owned by Tenable, Inc. or an Affiliate thereof."); script_family(english:"SuSE Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/SuSE/release", "Host/SuSE/rpm-list", "Host/cpu"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); release = get_kb_item("Host/SuSE/release"); if (isnull(release) || release =~ "^(SLED|SLES)") audit(AUDIT_OS_NOT, "openSUSE"); if (release !~ "^(SUSE15\.2)$") audit(AUDIT_OS_RELEASE_NOT, "openSUSE", "15.2", release); if (!get_kb_item("Host/SuSE/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); ourarch = get_kb_item("Host/cpu"); if (!ourarch) audit(AUDIT_UNKNOWN_ARCH); if (ourarch !~ "^(x86_64)$") audit(AUDIT_ARCH_NOT, "x86_64", ourarch); flag = 0; if ( rpm_check(release:"SUSE15.2", reference:"qemu-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-arm-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-arm-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-audio-alsa-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-audio-alsa-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-audio-pa-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-audio-pa-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-audio-sdl-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-audio-sdl-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-curl-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-curl-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-dmg-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-dmg-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-gluster-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-gluster-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-iscsi-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-iscsi-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-nfs-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-nfs-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-rbd-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-rbd-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-ssh-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-block-ssh-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-debugsource-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-extra-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-extra-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-guest-agent-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-guest-agent-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ipxe-1.0.0+-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ksm-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-kvm-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-lang-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-linux-user-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-linux-user-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-linux-user-debugsource-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-microvm-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ppc-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ppc-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-s390-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-s390-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-seabios-1.12.1+-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-sgabios-8-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-testsuite-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-tools-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-tools-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-curses-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-curses-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-gtk-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-gtk-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-sdl-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-sdl-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-spice-app-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-ui-spice-app-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-vgabios-1.12.1+-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-vhost-user-gpu-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-vhost-user-gpu-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-x86-4.2.1-lp152.9.6.1") ) flag++; if ( rpm_check(release:"SUSE15.2", reference:"qemu-x86-debuginfo-4.2.1-lp152.9.6.1") ) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:rpm_report_get()); else security_warning(0); exit(0); } else { tested = pkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "qemu / qemu-arm / qemu-arm-debuginfo / qemu-audio-alsa / etc"); }
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from openSUSE Security Update openSUSE-2019-1527. # # The text description of this plugin is (C) SUSE LLC. # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(125794); script_version("1.4"); script_set_attribute(attribute:"plugin_modification_date", value:"2021/01/19"); script_cve_id("CVE-2019-11068", "CVE-2019-5419"); script_name(english:"openSUSE Security Update : rmt-server (openSUSE-2019-1527)"); script_summary(english:"Check for the openSUSE-2019-1527 patch"); script_set_attribute( attribute:"synopsis", value:"The remote openSUSE host is missing a security update." ); script_set_attribute( attribute:"description", value: "This update for rmt-server to version 2.1.4 fixes the following issues : - Fix duplicate nginx location in rmt-server-pubcloud (bsc#1135222) - Mirror additional repos that were enabled during mirroring (bsc#1132690) - Make service IDs consistent across different RMT instances (bsc#1134428) - Make SMT data import scripts faster (bsc#1134190) - Fix incorrect triggering of registration sharing (bsc#1129392) - Fix license mirroring issue in some non-SUSE repositories (bsc#1128858) - Set CURLOPT_LOW_SPEED_LIMIT to prevent downloads from getting stuck (bsc#1107806) - Truncate the RMT lockfile when writing a new PID (bsc#1125770) - Fix missing trailing slashes on custom repository import from SMT (bsc#1118745) - Zypper authentication plugin (fate#326629) - Instance verification plugin in rmt-server-pubcloud (fate#326629) - Update dependencies to fix vulnerabilities in rails (CVE-2019-5419, bsc#1129271) and nokogiri (CVE-2019-11068, bsc#1132160) - Allow RMT registration to work under HTTP as well as HTTPS. - Offline migration from SLE 15 to SLE 15 SP1 will add Python2 module - Online migrations will automatically add additional modules to the client systems depending on the base product - Supply log severity to journald - Breaking Change: Added headers to generated CSV files This update was imported from the SUSE:SLE-15:Update update project." ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1107806" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1117722" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1118745" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1125770" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1128858" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1129271" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1129392" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1132160" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1132690" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1134190" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1134428" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1135222" ); script_set_attribute( attribute:"see_also", value:"https://features.opensuse.org/326629" ); script_set_attribute( attribute:"solution", value:"Update the affected rmt-server packages." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:P/I:P/A:P"); script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"); script_set_cvss3_temporal_vector("CVSS:3.0/E:U/RL:O/RC:C"); script_set_attribute(attribute:"cvss_score_source", value:"CVE-2019-11068"); script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:rmt-server"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:rmt-server-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:rmt-server-pubcloud"); script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:opensuse:15.0"); script_set_attribute(attribute:"vuln_publication_date", value:"2019/03/27"); script_set_attribute(attribute:"patch_publication_date", value:"2019/06/07"); script_set_attribute(attribute:"plugin_publication_date", value:"2019/06/10"); script_set_attribute(attribute:"generated_plugin", value:"current"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2019-2021 and is owned by Tenable, Inc. or an Affiliate thereof."); script_family(english:"SuSE Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/SuSE/release", "Host/SuSE/rpm-list", "Host/cpu"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); release = get_kb_item("Host/SuSE/release"); if (isnull(release) || release =~ "^(SLED|SLES)") audit(AUDIT_OS_NOT, "openSUSE"); if (release !~ "^(SUSE15\.0)$") audit(AUDIT_OS_RELEASE_NOT, "openSUSE", "15.0", release); if (!get_kb_item("Host/SuSE/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); ourarch = get_kb_item("Host/cpu"); if (!ourarch) audit(AUDIT_UNKNOWN_ARCH); if (ourarch !~ "^(x86_64)$") audit(AUDIT_ARCH_NOT, "x86_64", ourarch); flag = 0; if ( rpm_check(release:"SUSE15.0", reference:"rmt-server-2.1.4-lp150.2.16.1") ) flag++; if ( rpm_check(release:"SUSE15.0", reference:"rmt-server-debuginfo-2.1.4-lp150.2.16.1") ) flag++; if ( rpm_check(release:"SUSE15.0", reference:"rmt-server-pubcloud-2.1.4-lp150.2.16.1") ) flag++; if (flag) { if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get()); else security_hole(0); exit(0); } else { tested = pkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "rmt-server / rmt-server-debuginfo / rmt-server-pubcloud"); }
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from openSUSE Security Update openSUSE-2018-215. # # The text description of this plugin is (C) SUSE LLC. # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(107049); script_version("3.3"); script_set_attribute(attribute:"plugin_modification_date", value:"2021/01/19"); script_cve_id("CVE-2018-6381", "CVE-2018-6484", "CVE-2018-6540"); script_name(english:"openSUSE Security Update : zziplib (openSUSE-2018-215)"); script_summary(english:"Check for the openSUSE-2018-215 patch"); script_set_attribute( attribute:"synopsis", value:"The remote openSUSE host is missing a security update." ); script_set_attribute( attribute:"description", value: "This update for zziplib to 0.13.67 contains multiple bug and security fixes : - If an extension block is too small to hold an extension, do not use the information therein. - CVE-2018-6540: If the End of central directory record (EOCD) contains an Offset of start of central directory which is beyond the end of the file, reject the file. (bsc#1079096) - CVE-2018-6484: Reject the ZIP file and report it as corrupt if the size of the central directory and/or the offset of start of central directory point beyond the end of the ZIP file. (bsc#1078701) - CVE-2018-6381: If a file is uncompressed, compressed and uncompressed sizes should be identical. (bsc#1078497) This update was imported from the SUSE:SLE-12:Update update project." ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1024532" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1024536" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1034539" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1078497" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1078701" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.opensuse.org/show_bug.cgi?id=1079096" ); script_set_attribute( attribute:"solution", value:"Update the affected zziplib packages." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:N/I:N/A:P"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:libzzip-0-13"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:libzzip-0-13-32bit"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:libzzip-0-13-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:libzzip-0-13-debuginfo-32bit"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:zziplib-debugsource"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:zziplib-devel"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:zziplib-devel-32bit"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:zziplib-devel-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:zziplib-devel-debuginfo-32bit"); script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:opensuse:42.3"); script_set_attribute(attribute:"patch_publication_date", value:"2018/02/27"); script_set_attribute(attribute:"plugin_publication_date", value:"2018/02/28"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2018-2021 Tenable Network Security, Inc."); script_family(english:"SuSE Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/SuSE/release", "Host/SuSE/rpm-list", "Host/cpu"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); release = get_kb_item("Host/SuSE/release"); if (isnull(release) || release =~ "^(SLED|SLES)") audit(AUDIT_OS_NOT, "openSUSE"); if (release !~ "^(SUSE42\.3)$") audit(AUDIT_OS_RELEASE_NOT, "openSUSE", "42.3", release); if (!get_kb_item("Host/SuSE/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); ourarch = get_kb_item("Host/cpu"); if (!ourarch) audit(AUDIT_UNKNOWN_ARCH); if (ourarch !~ "^(i586|i686|x86_64)$") audit(AUDIT_ARCH_NOT, "i586 / i686 / x86_64", ourarch); flag = 0; if ( rpm_check(release:"SUSE42.3", reference:"libzzip-0-13-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", reference:"libzzip-0-13-debuginfo-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", reference:"zziplib-debugsource-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", reference:"zziplib-devel-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", reference:"zziplib-devel-debuginfo-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", cpu:"x86_64", reference:"libzzip-0-13-32bit-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", cpu:"x86_64", reference:"libzzip-0-13-debuginfo-32bit-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", cpu:"x86_64", reference:"zziplib-devel-32bit-0.13.67-13.3.1") ) flag++; if ( rpm_check(release:"SUSE42.3", cpu:"x86_64", reference:"zziplib-devel-debuginfo-32bit-0.13.67-13.3.1") ) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:rpm_report_get()); else security_warning(0); exit(0); } else { tested = pkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "libzzip-0-13 / libzzip-0-13-32bit / libzzip-0-13-debuginfo / etc"); }
#%NASL_MIN_LEVEL 70300 # # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from openSUSE Security Update openSUSE-2013-207. # # The text description of this plugin is (C) SUSE LLC. # include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(74923); script_version("1.5"); script_set_attribute(attribute:"plugin_modification_date", value:"2021/01/19"); script_cve_id("CVE-2013-0787"); script_bugtraq_id(58391); script_name(english:"openSUSE Security Update : MozillaThunderbird (openSUSE-SU-2013:0465-1)"); script_summary(english:"Check for the openSUSE-2013-207 patch"); script_set_attribute( attribute:"synopsis", value:"The remote openSUSE host is missing a security update." ); script_set_attribute( attribute:"description", value: "MozillaThunderbird was updated to 17.0.4 (bnc#808243) - MFSA 2013-29/CVE-2013-0787 (bmo#848644) Use-after-free in HTML Editor" ); script_set_attribute( attribute:"see_also", value:"https://bugzilla.novell.com/show_bug.cgi?id=808243" ); script_set_attribute( attribute:"see_also", value:"https://lists.opensuse.org/opensuse-updates/2013-03/msg00051.html" ); script_set_attribute( attribute:"solution", value:"Update the affected MozillaThunderbird packages." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:C/I:C/A:C"); script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available"); script_set_attribute(attribute:"exploit_available", value:"false"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird-buildsymbols"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird-debugsource"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird-devel"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird-devel-debuginfo"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird-translations-common"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:MozillaThunderbird-translations-other"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:enigmail"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:novell:opensuse:enigmail-debuginfo"); script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:opensuse:12.1"); script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:opensuse:12.2"); script_set_attribute(attribute:"cpe", value:"cpe:/o:novell:opensuse:12.3"); script_set_attribute(attribute:"patch_publication_date", value:"2013/03/12"); script_set_attribute(attribute:"plugin_publication_date", value:"2014/06/13"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2014-2021 and is owned by Tenable, Inc. or an Affiliate thereof."); script_family(english:"SuSE Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/SuSE/release", "Host/SuSE/rpm-list", "Host/cpu"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); release = get_kb_item("Host/SuSE/release"); if (isnull(release) || release =~ "^(SLED|SLES)") audit(AUDIT_OS_NOT, "openSUSE"); if (release !~ "^(SUSE12\.1|SUSE12\.2|SUSE12\.3)$") audit(AUDIT_OS_RELEASE_NOT, "openSUSE", "12.1 / 12.2 / 12.3", release); if (!get_kb_item("Host/SuSE/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); ourarch = get_kb_item("Host/cpu"); if (!ourarch) audit(AUDIT_UNKNOWN_ARCH); if (ourarch !~ "^(i586|i686|x86_64)$") audit(AUDIT_ARCH_NOT, "i586 / i686 / x86_64", ourarch); flag = 0; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-buildsymbols-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-debuginfo-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-debugsource-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-devel-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-devel-debuginfo-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-translations-common-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"MozillaThunderbird-translations-other-17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"enigmail-1.5.1+17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.1", reference:"enigmail-debuginfo-1.5.1+17.0.4-33.55.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-buildsymbols-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-debuginfo-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-debugsource-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-devel-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-devel-debuginfo-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-translations-common-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"MozillaThunderbird-translations-other-17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"enigmail-1.5.1+17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.2", reference:"enigmail-debuginfo-1.5.1+17.0.4-49.35.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-buildsymbols-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-debuginfo-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-debugsource-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-devel-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-devel-debuginfo-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-translations-common-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"MozillaThunderbird-translations-other-17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"enigmail-1.5.1+17.0.4-61.5.1") ) flag++; if ( rpm_check(release:"SUSE12.3", reference:"enigmail-debuginfo-1.5.1+17.0.4-61.5.1") ) flag++; if (flag) { if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get()); else security_hole(0); exit(0); } else { tested = pkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "MozillaThunderbird"); }
#%NASL_MIN_LEVEL 70300 ## # (C) Tenable Network Security, Inc. ## include('deprecated_nasl_level.inc'); include('compat.inc'); if (description) { script_id(144776); script_version("1.4"); script_set_attribute(attribute:"plugin_modification_date", value:"2022/04/11"); script_cve_id("CVE-2015-1788"); script_bugtraq_id(75164); script_name(english:"IBM HTTP Server 8.0.0.0 <= 8.0.0.11 / 8.5.0.0 <= 8.5.5.6 (533837)"); script_set_attribute(attribute:"synopsis", value: "The remote web server is affected by a vulnerability."); script_set_attribute(attribute:"description", value: "The version of IBM HTTP Server running on the remote host is affected by a vulnerability. The BN_GF2m_mod_inv function in crypto/bn/bn_gf2m.c in OpenSSL before 0.9.8s, 1.0.0 before 1.0.0e, 1.0.1 before 1.0.1n, and 1.0.2 before 1.0.2b does not properly handle ECParameters structures in which the curve is over a malformed binary polynomial field, which allows remote attackers to cause a denial of service (infinite loop) via a session that uses an Elliptic Curve algorithm, as demonstrated by an attack against a server that supports client authentication. Note that Nessus has not tested for this issue but has instead relied only on the application's self-reported version number."); script_set_attribute(attribute:"see_also", value:"https://www.ibm.com/support/pages/node/533837"); script_set_attribute(attribute:"solution", value: "Upgrade to IBM HTTP Server version 8.5.5.7, 8.0.0.12 or later. Alternatively, upgrade to the minimal fix pack level required by the interim fix and then apply Interim Fix PI44809."); script_set_attribute(attribute:"agent", value:"unix"); script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:N/I:N/A:P"); script_set_cvss_temporal_vector("CVSS2#E:U/RL:OF/RC:C"); script_set_cvss3_base_vector("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L"); script_set_cvss3_temporal_vector("CVSS:3.0/E:U/RL:O/RC:C"); script_set_attribute(attribute:"cvss_score_source", value:"CVE-2015-1788"); script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available"); script_set_attribute(attribute:"vuln_publication_date", value:"2015/09/10"); script_set_attribute(attribute:"patch_publication_date", value:"2015/09/10"); script_set_attribute(attribute:"plugin_publication_date", value:"2021/01/06"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"cpe:/a:ibm:http_server"); script_set_attribute(attribute:"thorough_tests", value:"true"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_family(english:"Web Servers"); script_copyright(english:"This script is Copyright (C) 2020-2022 and is owned by Tenable, Inc. or an Affiliate thereof."); script_dependencies("ibm_http_server_nix_installed.nbin"); script_require_keys("installed_sw/IBM HTTP Server (IHS)"); exit(0); } include('vcf.inc'); app = 'IBM HTTP Server (IHS)'; app_info = vcf::get_app_info(app:app); vcf::check_granularity(app_info:app_info, sig_segments:4); if ('PI44809' >< app_info['Fixes']) audit(AUDIT_INST_VER_NOT_VULN, app); constraints = [ { 'min_version' : '8.5.0.0', 'max_version' : '8.5.5.6', 'fixed_display' : '8.5.5.7 or Interim Fix PI44809'}, { 'min_version' : '8.0.0.0', 'max_version' : '8.0.0.11', 'fixed_display' : '8.0.0.12 or Interim Fix PI44809'} ]; vcf::check_version_and_report(app_info:app_info, constraints:constraints, severity:SECURITY_WARNING);
import SectionTitle from "../../components/SectionTitle" import { Technology, TechnologyName } from "../../components/Icons" import styles from './index.module.scss' import { motion, useAnimation } from "framer-motion" import { useEffect } from "react" import { useInView } from "react-intersection-observer" interface SkillProps { icon: TechnologyName label: string } const skills: SkillProps[] = [ { icon: 'html', label: 'Html 5' }, { icon: 'css', label: 'Css' }, { icon: 'sass', label: 'Sass' }, { icon: 'js', label: 'Javascript' }, { icon: 'ts', label: 'Typescript' }, { icon: 'angular', label: 'Angular JS' }, { icon: 'react', label: 'React JS' }, { icon: 'next', label: 'Next JS' }, { icon: 'vite', label: 'Vite JS' }, { icon: 'electron', label: 'Electron' }, { icon: 'storybook', label: 'Storybook JS' }, { icon: 'git', label: 'Git' }, { icon: 'aws', label: 'AWS' }, { icon: 'graphql', label: 'GraphQL' }, ] const Skills = () => { const ctrls = useAnimation() const { ref, inView } = useInView({ threshold: 0.5, triggerOnce: true, }); useEffect(() => { console.log(inView) if (inView) { ctrls.start('visible'); } if (!inView) { ctrls.start('hidden'); } }, [ctrls, inView]); // Animation const techAnimation = { hidden: { opacity: 0, y: `0.25em`, }, visible: { opacity: 1, y: `0em`, transition: { duration: 1, ease: [0.2, 0.65, 0.3, 0.9], }, }, }; return ( <div className={styles.skills} id="skills"> <SectionTitle title="Skills & Technologies" /> <div className={styles.skills__list}> { skills.map((skill, i) => ( <motion.div key={`${skill.label}-${i}`} ref={ref} aria-hidden="true" initial="hidden" animate={ctrls} variants={techAnimation} transition={{ delayChildren: i * 0.25, staggerChildren: 0.05, }} > <Technology name={skill.icon} color="#03C988" /> {/* <p>{skill.label}</p> */} </motion.div> )) } </div> </div> ) } export default Skills
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import UserService, { TypeMail } from 'App/Services/User.service'; import DriverValidator from 'App/Validators/DriverValidator'; import { inject } from '@adonisjs/fold'; import DriverService from 'App/Services/Driver.service'; import Logger from '@ioc:Adonis/Core/Logger'; import upload from 'App/Utils/Upload.file'; import Hash from '@ioc:Adonis/Core/Hash'; @inject() export default class DriversController extends DriverValidator { constructor( private driver: DriverService, private user: UserService, ) { super() } public async index({ request, response }: HttpContextContract) { try { const { page = 1, limit = 10, status, orderBy = "created_at" } = request.only(['page', 'limit', `status`, `orderBy`]) const result = await this.driver.getDrivers({ page, limit, status, orderBy }) response.ok({ status: true, data: result, }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async store({ request, response }: HttpContextContract) { const userPayload = await request.validate({ schema: this.v_create, }) const driverPayload = await request.validate({ schema: this.v_driver_create, data: request.only(['userId', 'cardType', 'cardTypeId', 'cardImage']) }) try { UserService.typeOfMail = TypeMail.DRIVER const user = await this.user.registre(userPayload) driverPayload.userId = user.id const data = await this.driver.registre(driverPayload) response.created({ status: true, data }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async updateInfo({ request, response }: HttpContextContract) { const { id } = await request.validate({ schema: this.v_delete, data: { id: request.param('id') }, }) const payload = await request.validate({ schema: this.v_driver_update_info, }) try { const findDriver = await this.driver.find({ key: 'id', value: id }) if (!findDriver) return response.notFound({ status: false, message: 'Driver not found.' }) const data = await this.driver.update(findDriver.id, payload) return response.ok({ status: true, data }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async update({ request, response, auth }: HttpContextContract) { const payload = await request.validate({ schema: this.v_driver_update, }) try { const { userId } = auth.use('driver').user! const data = await this.user.update(userId, payload) return response.ok({ status: true, data }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async login({ request, response, auth }: HttpContextContract) { const payload = await request.validate({ schema: this.v_sign, }) try { const user = await this.user.signin(payload.email) if (!user) return response.notFound({ status: false, message: 'Identifiants incorrect' }) if (!(await Hash.verify(user.password, payload.password))) return response.notFound({ status: false, message: 'Identifiants incorrect.' }) const driver = await this.driver.find({ key: 'user_id', value: user.id }) if (!driver) return response.notFound({ status: false, message: 'Identifiants incorrect' }) const token = await auth.use('driver').generate(driver) return response.ok({ status: true, token, data: driver, }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async updateProfile({ request, response, auth }: HttpContextContract) { //1 const payload = await request.validate({ schema: this.v_profile }) try { //2 if (payload) { //3 const result = await upload.uploads(payload.profile) const profile = result.secure_url await this.user.update(auth.use('driver').user!.userId as string, { profile }) return response.ok({ status: true, data: { profile, } }) } throw new Error('Echec de la modification.') } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async status({ request, response, auth }: HttpContextContract) { //1 const payload = await request.validate({ schema: this.v_driver_status }) try { //2 const data = await this.driver.update(auth.use('driver').user!.id, payload) return response.ok({ status: true, data }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async changedPassword({ request, response, auth }: HttpContextContract) { //1 const payload = await request.validate({ schema: this.v_change_psswd }) try { //2 const user = await this.user.find({ key: 'id', value: auth.use('driver').user!.userId }) if (!user) return response.notFound({ status: false, message: 'User not found.' }) if (!(await Hash.verify(user!.password as string, payload.oldPassword))) return response.notFound({ status: false, message: 'Ancien mot de passe inccorect.' }) //3. const password = await Hash.make(payload.password) await this.user.update(user!.id as string, { password }) return response.created({ status: true, message: 'mot de pass modifier.', }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async updateLocation({ request, response, auth }: HttpContextContract) { //1 const payload = await request.validate({ schema: this.v_driver_location, }) try { //2 const { id } = auth.use('driver').user! const data = await this.driver.update(id, payload) return response.ok({ status: true, data }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } public async logOut({ response, auth }: HttpContextContract) { try { //2 auth.logout() return response.ok({ status: true, message: 'Driver logOut.', }) } catch (error) { Logger.error(error) return response.expectationFailed({ status: false, message: error.message }) } } }
package com.example.comtam.screens import android.content.Context import android.content.Intent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import coil.size.Size import com.example.asm.ApiClient import com.example.comtam.R import com.example.comtam.ShareValue import com.example.comtam.commond.ShowlistMain import com.example.comtam.models.Feedback import com.example.comtam.models.Product import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.Serializable class Home { @Composable fun Container (gotoScreen : (String) -> Unit, shareValue : ShareValue ) { var list : List<Product>? by remember { mutableStateOf( mutableListOf() )} fun getAllproduct() { println("hrererereashgfksjdyhfjlkah") val call = ApiClient.apiService.getListProductAPI() call.enqueue(object: Callback<List<Product>> { override fun onResponse(call: Call<List<Product>>, response: Response<List<Product>>) { if (response.isSuccessful) { val post = response.body() list = post?.toMutableList() } else { println("Error: ${response}") } } override fun onFailure(call: Call<List<Product>>, t: Throwable) { println("error: ${t}") } }) } getAllproduct() val context = LocalContext.current var textSearch by remember { mutableStateOf("") } Column(modifier = Modifier.fillMaxSize()) { Header() Box(modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp)){ OutlinedTextField( value = textSearch, onValueChange = {textSearch = it}, modifier = Modifier .fillMaxWidth(), placeholder = { Text(text = "Search", color = Color(0x33000000) ) }, colors = TextFieldDefaults.colors( focusedContainerColor = Color.White, unfocusedContainerColor = Color.White, focusedIndicatorColor = Color(0x33000000), unfocusedIndicatorColor = Color(0x33000000) ), shape = RoundedCornerShape(15.dp), trailingIcon = { Image(painter = painterResource(id = R.drawable.search), contentDescription = "", modifier = Modifier.size(24.dp)) } ) } Spacer(modifier = Modifier.height(16.dp)) LazyColumn(modifier = Modifier.padding(horizontal = 24.dp)){ item { Column{ ShowlistMain(list, context ,"Recomment Items", gotoScreen = {gotoScreen(it)}, shareValue= shareValue) ShowlistMain(list, context, "Featured partner", gotoScreen = {gotoScreen(it)}, shareValue= shareValue) ShowlistMain(list, context, "Popular Item", gotoScreen = {gotoScreen(it)}, shareValue= shareValue) } } } } } @Composable fun Header(){ Row(modifier = Modifier .fillMaxWidth() .padding(top = 15.dp, start = 25.dp, end = 25.dp, bottom = 20.dp), horizontalArrangement = Arrangement.SpaceBetween){ Box(modifier = Modifier .size(38.dp) .border(1.dp, Color(0x33000000), RoundedCornerShape(13.dp)) .background(Color.White, RoundedCornerShape(13.dp)) .shadow( 10.dp, clip = true, shape = RoundedCornerShape(13.dp), spotColor = Color.White ), contentAlignment = Alignment.Center ){ Image(painter = painterResource(id = R.drawable.menu), contentDescription = "", modifier = Modifier .width(16.dp) .height(8.dp)) } Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { Row(horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically){ Text(text = "Deliver to", fontSize = 14.sp, color = Color(0xFF8C9099), fontWeight = FontWeight.Medium ) Spacer(modifier = Modifier.width(6.dp)) Image(painter = painterResource(id = R.drawable.dropdown), contentDescription = "", modifier = Modifier .width(8.dp) .height(5.dp) ) } Text(text = "Choose your city and state", fontSize = 15.sp, color = Color(0xFFFE724C), fontWeight = FontWeight.Medium ) } Image(painter = painterResource(id = R.drawable.sefi), contentDescription = "", modifier = Modifier.size(38.dp)) } } }
import React from "react"; import "./index.css"; import { Link } from "react-router-dom"; const STYLES = ["btn--primary", "btn--secondary", "btn--outline", "btn--test"]; const SIZES = ["btn--medium", "btn--large"]; const Button = ({ children, type, onClick, buttonStyle, buttonSize, width, to = "#!", }) => { const checkButtonStyle = STYLES.includes(buttonStyle) ? buttonStyle : STYLES[0]; const checkButtonSize = SIZES.includes(buttonSize) ? buttonSize : SIZES[0]; if (to === "") return ( <button className={`btn ${checkButtonStyle} ${checkButtonSize}`} onClick={onClick} type={type} style={{ width: width }} > {children} </button> ); return ( <Link to={to} className="btn-mobile"> <button className={`btn ${checkButtonStyle} ${checkButtonSize}`} onClick={onClick} type={type} style={{ width: width }} > {children} </button> </Link> ); }; export default Button;
import {NavLink} from "react-router-dom"; import s from "./MenuItem.module.css"; type MenuItemPropsType = { title: string icon?: string link: string onClick?: () => void } export const MenuItem = (props: MenuItemPropsType) => { return ( <NavLink to={props.link} onClick={props.onClick} className={({isActive}) => `${s.itemWrapper} ${isActive ? s.active : ''}`}> <img className={s.icon} src={props.icon} alt={'icon'}/> <span className={s.itemText}>{props.title}</span> </NavLink> ) }
import React from "react"; import { formatearFecha } from "../helpers/formatearfecha"; import useAdmin from "../hooks/useAdmin"; import useProyectos from "../hooks/useProyectos"; const Tarea = ({ tarea }) => { const { setTarea, setModal, modalEliminarTarea, setModalEliminarTarea, completarTarea } = useProyectos(); const { descripcion, nombre, prioridad, fechaEntrega, estado, _id } = tarea; const admin = useAdmin(); console.log(tarea); return ( <div className="border-b p-5 flex justify-between items-center"> <div className=""> <p className="mb-2 text-xl">{nombre}</p> <p className="mb-1 text-sm text-gray-600">{descripcion}</p> <p className="mb-1 text-sm">{formatearFecha(fechaEntrega)}</p> <p className="mb-1 text-gray-600">Prioridad: {prioridad}</p> {estado && ( <p className="text-green-600 font-bold">Completado por: {tarea.completado.nombre}</p> )} </div> <div className="flex flex-col md:flex-row gap-2"> {admin && ( <button className="bg-indigo-600 px-4 py-3 text-white font-bold text-sm rounded-lg" onClick={() => { setTarea(tarea), setModal(true); }} > Editar </button> )} <button className={`${ estado ? "bg-sky-600" : "bg-gray-600" } px-4 py-3 text-white font-bold text-sm rounded-lg`} onClick={() => completarTarea(_id)} > {estado ? "Completa" : "Incompleta"} </button> {admin && ( <button className="bg-red-600 px-4 py-3 text-white font-bold text-sm rounded-lg" onClick={() => { setTarea(tarea), setModalEliminarTarea(true); }} > Eliminar </button> )} </div> </div> ); }; export default Tarea;
import {roleDefineModel, permissionModel} from '../models'; import userModel from '../../auth/models/index'; const createRole = async (roleData) => { try { // Create the new role in the database const role = await roleDefineModel.create(roleData); return role; } catch (error) { throw new Error('Unable to create role'); } }; const updateRole = async (roleId, updatedRoleData) => { try { const {roleName, description, permissions, isDeactivated} = updatedRoleData; // Find the role by ID and update it with the new data const updatedRole = await roleDefineModel.findByIdAndUpdate( roleId, { roleName, description, permissions, isDeactivated }, {new: true} // This ensures that the function returns the updated document ); return updatedRole; } catch (error) { throw new Error('Unable to update role'); } }; // Function to restore default permissions for a role const restoreDefaultPermissions = async (roleId) => { try { const existingRole = await roleDefineModel.findById(roleId); if (!existingRole) { throw new Error('Role not found'); } // Restore default permissions for each permission in the role const updatedPermissions = await Promise.all( existingRole.permissions.map(async (permission) => { // Retrieve the default permission from the permissionModel const defaultPermission = await permissionModel.findById( permission.moduleId ); if (defaultPermission) { return { ...permission, read: defaultPermission.read, readWrite: defaultPermission.readWrite, actions: defaultPermission.actions, allAccess: false, removeAccess: false, }; } return permission; // Keep the existing permission if the default is not found }) ); const updatedRoleData = { permissions: updatedPermissions, updatedAt: new Date(), }; // Update the role with the restored default permissions const updatedRole = await roleDefineModel.findByIdAndUpdate( roleId, updatedRoleData, {new: true} ); return updatedRole; } catch (error) { throw new Error('Unable to update role'); } }; const getAllRoles = async (loggedInUserId, page, limit, sortBy) => { try { const skip = (page - 1) * limit; const filter = { addedByUserId: loggedInUserId, isDeleted: false }; const data = await roleDefineModel .find(filter) .select('-deletedAt') .populate('addedByUserId', 'email') .populate('permissions', 'moduleName read readWrite actions') .sort(sortBy) .skip(skip) .limit(limit) .exec(); const rolesWithUserCount = await Promise.all(data.map(async (role) => { const userCount = await userModel.countDocuments({ teamRoleId: role._id, isDeleted: false }); role = role.toObject(); role.userCount = userCount; return role; })); rolesWithUserCount.forEach((role) => { role.permissions = role.permissions.filter( (permission) => !permission.removeAccess ); }); const totalDocuments = await roleDefineModel.countDocuments(filter); const totalPages = Math.ceil(totalDocuments / limit); const startSerialNumber = (page - 1) * limit + 1; const endSerialNumber = Math.min(page * limit, totalDocuments); return { data: rolesWithUserCount, totalDocuments, totalPages, startSerialNumber, endSerialNumber, }; } catch (error) { throw new Error('Unable to fetch roles'); } }; const getAllRolesForMembersAdd = async (loggedInUserId) => { try { const roles = await roleDefineModel .find({ addedByUserId: loggedInUserId, isDeleted: false, isDeactivated: false }) .select('-deletedAt') .populate('addedByUserId', 'email') .populate('permissions', 'moduleName read readWrite actions') .exec(); const rolesWithUserCount = await Promise.all(roles.map(async (role) => { const userCount = await userModel.countDocuments({ teamRoleId: role._id }); role = role.toObject(); role.userCount = userCount; return role; })); // Filter out permissions with removeAccess set to true rolesWithUserCount.forEach((role) => { role.permissions = role.permissions.filter( (permission) => !permission.removeAccess ); }); return rolesWithUserCount; } catch (error) { throw new Error('Unable to fetch roles'); } }; const getRoleById = async (id) => { try { const role = await roleDefineModel.findById(id); const firstModuleId = role.permissions[0].moduleId; if (firstModuleId) { const firstModule = await permissionModel.findById(firstModuleId); if (firstModule && ['user', 'root'].includes(firstModule.dashboardType)) { const dashboardTypeToMatch = firstModule.dashboardType; const matchedModuleIds = await permissionModel.find({dashboardType: dashboardTypeToMatch}, '_id'); matchedModuleIds.forEach(idObj => { const moduleId = idObj._id.toString(); if (!role.permissions.some(permission => permission.moduleId.toString() === moduleId)) { role.permissions.push({ moduleId: moduleId, }); } }); } } // Assuming teamRoleId is the field linking roles and users const assignedUsers = await userModel.find({ teamRoleId: role._id, isDeleted: false }).populate('teamRoleId', 'roleName') ; const assignedUserCount = assignedUsers.length; return {role: role.toObject(), assignedUsers, assignedUserCount}; } catch (error) { throw new Error('Unable to fetch role by ID'); } }; const deleteRoles = async (id) => { try { const deleteRoleResult = await roleDefineModel.updateOne( { _id: id, }, { isDeleted: true, deletedAt: new Date(), } ); return deleteRoleResult; } catch (error) { throw new Error('Error in deleting resource'); } }; const getAllRolesV2 = async (query) => { try { const roles = await roleDefineModel .find({ ...query, isDeleted: false, isDeactivated: false, }) .select('-isDeactivated -deletedAt') .populate('addedByUserId', 'email') // Only populate 'email' field from addedByUserId .populate('permissions', 'moduleName read readWrite actions') .exec(); // Filter out permissions with removeAccess set to true roles.forEach((role) => { role.permissions = role.permissions.filter( (permission) => !permission.removeAccess ); }); return roles; } catch (error) { throw new Error('Unable to fetch roles'); } }; export const rolesService = { createRole, updateRole, getAllRoles, getAllRolesForMembersAdd, restoreDefaultPermissions, deleteRoles, getAllRolesV2, getRoleById };
/* * Copyright (c) 2020 Cognite AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cognite.client.servicesV1.response; import com.fasterxml.jackson.databind.JsonNode; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import java.io.IOException; import java.util.List; import java.util.Optional; /** * Parses a single attribute from a json payload as a single item. * * A cursor is never returned from this parser. */ @AutoValue public abstract class JsonStringAttributeResponseParser extends DefaultResponseParser { private static String DEFAULT_ATTRIBUTE_PATH = ""; static Builder builder() { return new AutoValue_JsonStringAttributeResponseParser.Builder(); } public static JsonStringAttributeResponseParser create() { return JsonStringAttributeResponseParser.builder() .setAttributePath(List.of(DEFAULT_ATTRIBUTE_PATH)) .build(); } abstract JsonStringAttributeResponseParser.Builder toBuilder(); public abstract List<String> getAttributePath(); /** * Sets the path to the attribute to extract. * * @param path * @return */ public JsonStringAttributeResponseParser withAttributePath(String path) { String[] pathSegments = path.split("\\."); List<String> segmentList = List.of(pathSegments); return toBuilder().setAttributePath(segmentList).build(); } /** * Extract the next cursor from a results json payload. Will always return an empty Optional. * * @param json The results json payload * @return * @throws IOException */ @Override public Optional<String> extractNextCursor(String json) { return Optional.empty(); } /** * Extract the main items from a results json payload. Returns the entire payload as a json string. * * @param json The results json payload * @return * @throws IOException */ public ImmutableList<String> extractItems(String json) throws Exception { String loggingPrefix = "extractItems - " + instanceId + " - "; // Check if the input string is valid json. Will throw an exception if it cannot be parsed. JsonNode node = objectMapper.readTree(json); for (String path : getAttributePath()) { node = node.path(path); } if (node.isMissingNode()) { LOG.warn(loggingPrefix + "Cannot find any attribute at path [{}]", getAttributePath()); return ImmutableList.of(); } else if (node.isTextual()) { return ImmutableList.of(node.textValue()); } else if (node.isValueNode()) { return ImmutableList.of(node.asText("")); } else { return ImmutableList.of(node.toString()); } } @AutoValue.Builder public abstract static class Builder { abstract Builder setAttributePath(List<String> value); public abstract JsonStringAttributeResponseParser build(); } }
import React, { PureComponent } from 'react'; import { inject, observer } from 'mobx-react'; import classNames from 'classnames/bind'; import styles from './index.less'; import UserStore from '@/stores/user'; import formatDate from '@/utils/time'; import capitalize from '@/utils/string'; const cx = classNames.bind(styles); interface ProfileProps { userStore?: UserStore; } @inject('userStore') @observer export default class ProfileDoctor extends PureComponent<ProfileProps> { get displayGender(): string { const { userStore } = this.props; const { gender } = userStore!; return capitalize(gender); } get displayBirthday(): string { const { userStore } = this.props; const { birthday } = userStore!; return formatDate(birthday, 'YYYY-MM-DD'); } get displayHospital(): string { const { userStore } = this.props; const { hospitalName } = userStore!; return capitalize(hospitalName); } get displayDepartment(): string { const { userStore } = this.props; const { departmentName } = userStore!; return capitalize(String(departmentName)); } get displayTitle(): string { const { userStore } = this.props; const { title } = userStore!; return capitalize(title); } render() { const { userStore } = this.props; const { fullName } = userStore!; return ( <div className={cx('profile')}> <div className={cx('profile__name')}>{fullName}</div> <div className={cx('profile__support')}> <span>{this.displayGender}</span> <span>{this.displayBirthday}</span> </div> <div className={cx('profile__title')}>{this.displayTitle}</div> <div className={cx('profile__support')}> <span>{this.displayDepartment}</span> <span>{this.displayHospital}</span> </div> </div> ); } }
package br.com.fiap.locaweb.frontEnd.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import br.com.fiap.locaweb.R import br.com.fiap.locaweb.backEnd.model.User import br.com.fiap.locaweb.backEnd.repository.UserRepository @Composable fun AccountForm( name: String, surname: String, dateOfBirth: String, email: String, password: String, phoneNumber: String, onNameChange: (String) -> Unit, onSurnameChange: (String) -> Unit, onDateOfBirthChange: (String) -> Unit, onEmailChange: (String) -> Unit, onPasswordChange: (String) -> Unit, onPhoneNumberChange: (String) -> Unit, update: () -> Unit, onCadastroSuccess: () -> Unit ) { var emptyName by remember { mutableStateOf(false) } var emptyDateOfBirth by remember { mutableStateOf(false) } var emptyEmail by remember { mutableStateOf(false) } var emptyPassword by remember { mutableStateOf(false) } var passwordVisibility by remember { mutableStateOf(false) } val context = LocalContext.current val userRepository = UserRepository(context) Column(modifier = Modifier .padding(16.dp) .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Cadastrar conta", fontSize = 30.sp, fontWeight = FontWeight.Bold, color = colorResource(id = R.color.blue) ) Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField( value = name, onValueChange = { onNameChange(it) }, modifier = Modifier.fillMaxWidth(), label = { Text(text = "Nome") }, placeholder = { Text(text = "João") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, capitalization = KeyboardCapitalization.Words ), isError = emptyName ) if(emptyName){ Text( text = "Nome é obrigatório", modifier = Modifier.fillMaxWidth(), fontSize = 14.sp, color = Color.Red, textAlign = TextAlign.End ) } Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField( value = surname, onValueChange = { onSurnameChange(it) }, modifier = Modifier.fillMaxWidth(), label = { Text(text = "Sobrenome (Opcional)") }, placeholder = { Text(text = "Oliveira da Silva") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, capitalization = KeyboardCapitalization.Words ) ) Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField( value = dateOfBirth, onValueChange = { onDateOfBirthChange(it) }, modifier = Modifier.fillMaxWidth(), label = { Text(text = "Data de nascimento") }, placeholder = { Text(text = "DD/MM/YYYY") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, capitalization = KeyboardCapitalization.Words ), isError = emptyDateOfBirth ) if(emptyDateOfBirth){ Text( text = "Data de nascimento e obrigatório", modifier = Modifier.fillMaxWidth(), fontSize = 14.sp, color = Color.Red, textAlign = TextAlign.End ) } Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField( value = email, onValueChange = { onEmailChange(it) }, modifier = Modifier.fillMaxWidth(), label = { Text(text = "E-mail") }, placeholder = { Text(text = "teste@gmail.com") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email ), isError = emptyEmail ) if(emptyEmail){ Text( text = "E-mail é obrigatório", modifier = Modifier.fillMaxWidth(), fontSize = 14.sp, color = Color.Red, textAlign = TextAlign.End ) } Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField( value = password, onValueChange = { onPasswordChange(it) }, modifier = Modifier.fillMaxWidth(), label = { Text(text = "Senha") }, placeholder = { Text(text = "Crie sua senha") }, visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, ), isError = emptyPassword ) if(emptyPassword){ Text( text = "Senha obrigatória", modifier = Modifier.fillMaxWidth(), fontSize = 14.sp, color = Color.Red, textAlign = TextAlign.End ) } Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField( value = phoneNumber, onValueChange = { onPhoneNumberChange(it) }, modifier = Modifier.fillMaxWidth(), label = { Text(text = "Telefone") }, placeholder = { Text(text = "1191232349") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, capitalization = KeyboardCapitalization.Words ), ) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { if(name.isEmpty() || dateOfBirth.isEmpty() || email.isEmpty() || password.isEmpty()) { emptyName = name.isEmpty() emptyDateOfBirth = dateOfBirth.isEmpty() emptyEmail = email.isEmpty() emptyPassword = password.isEmpty() } else { val user = User( id = 0, name = name, surname = surname, dateOfBirth = dateOfBirth, email = email, password = password, phoneNumber = phoneNumber ) userRepository.create(user) update() onCadastroSuccess() onNameChange("") onSurnameChange("") onDateOfBirthChange("") onEmailChange("") onPasswordChange("") onPhoneNumberChange("") } }, modifier = Modifier .width(150.dp) .height(60.dp) .padding(bottom = 20.dp) ) { Text( text = "Cadastrar", textAlign = TextAlign.Center, fontSize = 16.sp ) } } }
package com.example.r_usecase.usecases.dataUseCase import android.content.Context import com.example.a_common.BALANCE import com.example.a_common.DEBTORS import com.example.a_common.HISTORY import com.example.a_common.LENDERS import com.example.a_common.Type import com.example.a_common.WALLETS import com.example.a_common.getTypeEnum import com.example.a_common.getTypeNumber import com.example.a_common.getTypeText import com.example.a_common.huminize import com.example.a_common.huminizeForFile import com.example.r_usecase.R import com.example.r_usecase.usecases.currencyUseCase.CurrencyUseCase import com.example.r_usecase.usecases.historyUseCase.HistoryUseCase import com.example.r_usecase.usecases.personCurrencyUseCase.PersonCurrencyUseCase import com.example.r_usecase.usecases.personUseCase.PersonsUseCase import com.example.r_usecase.usecases.walletsUseCase.WalletsUseCase import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import javax.inject.Inject class GetAllDataUseC @Inject constructor( private val personsUseCase: PersonsUseCase, private val walletsUseCase: WalletsUseCase, private val personCurrencyUseCase: PersonCurrencyUseCase, private val currencyUseCase: CurrencyUseCase, private val historyUseCase: HistoryUseCase ) { suspend operator fun invoke(context: Context): Flow<LinkedHashMap<String, LinkedHashMap<String, List<String>>>> = flow { val totalBalance = currencyUseCase.getTotalBalanceUseC.invoke() val currencyList = currencyUseCase.getAllCurrencies.invoke() val walletList = walletsUseCase.getAllWalletsUseC.invoke() val debtorsList = personCurrencyUseCase.getAllDebtors.invoke() val lendersList = personCurrencyUseCase.getAllLenders.invoke() val historyList = historyUseCase.getLimitedHistoryUseC.invoke(1000) val mainMap = LinkedHashMap<String, LinkedHashMap<String, List<String>>>() combine( currencyList, walletList, debtorsList, lendersList, historyList ) { currencies, wallets, debtors, lenders, histories -> val mapBalance = LinkedHashMap<String, List<String>>() val keyBalance = context.getString(R.string.jami_balance) + totalBalance.huminize() + context.getString( R.string.dollar ) val valueBalance = currencies.map { "${it.balance} ${it.name}" } mapBalance[keyBalance] = valueBalance val mapWallets = LinkedHashMap<String, List<String>>() wallets.onEach { w -> val keyWallet = w.name val valueWallet = w.walletOwnerDataList.walletOwnerData.filter { it.walletId == w.id }.map { "${it.currencyBalance} ${currencyUseCase.getCurrency.invoke(it.currencyId).name}" } mapWallets[keyWallet] = valueWallet } val mapDebtors = LinkedHashMap<String, List<String>>() debtors.onEach { d -> val keyDebtors = personsUseCase.getPersonUseC.invoke(d.personId).name val valueDebtors = mutableListOf<String>() personCurrencyUseCase.getPersonCurriesByPersonIdUseC.invoke(d.personId) .map { it.map { valueDebtors.add( "${it.currencyBalance} ${ currencyUseCase.getCurrency.invoke(it.currencyId).name }" ) } } mapDebtors[keyDebtors] = valueDebtors } val mapLenders = LinkedHashMap<String, List<String>>() lenders.onEach { l -> val keyLenders = personsUseCase.getPersonUseC.invoke(l.personId).name val valueLenders = mutableListOf<String>() personCurrencyUseCase.getPersonCurriesByPersonIdUseC.invoke(l.personId) .map { it.map { valueLenders.add( "${it.currencyBalance} ${ currencyUseCase.getCurrency.invoke(it.currencyId).name }" ) } } mapLenders[keyLenders] = valueLenders } val mapHistory = LinkedHashMap<String, List<String>>() histories.onEach { item -> val list = ArrayList<String>() var incr = "" if (item.title == getTypeNumber(Type.INCOME) || item.title == getTypeNumber(Type.BORROW)) { incr = "+" } else if (item.title == getTypeNumber(Type.OUTCOME) || item.title == getTypeNumber( Type.LEND ) ) { incr = "-" } val title = getTypeText(item.title) val converted = "$incr${item.amount.huminize()} ${item.currency}" list.add("$title: $converted") if (!item.fromName.isNullOrEmpty()) { val pocket = if (item.isFromPocket) " " + context.getString(R.string.hamyon) else "" val from = (item.fromName ?: "") + "${pocket}dan" if (getTypeEnum(item.title) == Type.CONVERTATION) { val textMinus = "-${item.moneyFrom?.huminize()} ${item.moneyNameFrom}" list.add("$from $textMinus") } else { list.add(from) } } if (!item.toName.isNullOrEmpty()) { val pocket = if (item.isToPocket) " " + context.getString(R.string.hamyon) else "" val to = (item.toName ?: "") + "${pocket}ga" if (getTypeEnum(item.title) == Type.CONVERTATION) { val textPlus = "+${item.moneyTo?.huminize()} ${item.moneyNameTo}" list.add("$to $textPlus") } else { list.add(to) } } // val kurs = // if (item.rateFrom > item.rateTo) { // "1 ${item.moneyNameTo} = ${(item.rateFrom / item.rateTo).huminize()} ${item.moneyNameFrom}" // } else if (item.rateFrom < item.rateTo) { // "1 ${item.moneyNameFrom} = ${(item.rateTo / item.rateFrom).huminize()} ${item.moneyNameTo}" // } else if (item.rateFrom != 1.0 && item.rateTo != 1.0) { // "1$ = ${item.rateTo.huminize()}" // } else "" val value = if (!item.fromName.isNullOrEmpty()) { "${item.rateFrom} ${item.moneyNameFrom} = ${item.rateTo} ${item.moneyNameTo}" } else { "1$ = ${item.rateTo}" } if (value.trim().isNotEmpty()) { list.add("kurs: $value") } val oldBalance = "${context.getString(R.string.bundan_oldingi_balans)} ${item.balance.huminize()} ${ context.getString(R.string.dollar) }" list.add(oldBalance) var izoh = "" item.comment?.let { if (it.isNotEmpty()) { izoh = "${context.getString(R.string.izoh)} $it" list.add(izoh) } } mapHistory[item.date.huminizeForFile()] = list } mainMap[BALANCE] = mapBalance mainMap[WALLETS] = mapWallets mainMap[DEBTORS] = mapDebtors mainMap[LENDERS] = mapLenders mainMap[HISTORY] = mapHistory emit(mainMap) }.collect() } }
import React, { useContext, useEffect } from "react"; import { Routes, Route, useLocation } from "react-router-dom"; import "./App.css"; // pages import Home from "./pages/Home.jsx"; import CryptoCurrencies from "./pages/CryptoCurrencies.jsx"; import CryptoExchanges from "./pages/CryptoExchanges.jsx"; import PageNotFound from "./pages/PageNotFound.jsx"; // context import { SET_INSTRUMENT_TYPE } from "./context/action.types"; import { CryptoContext } from "./context/CryptoContext"; const App = () => { // context const { instrumentType, dispatch } = useContext(CryptoContext); // getting url address const { pathname } = useLocation(); // setting up instrument type based on the url useEffect(() => { if (!pathname.includes(instrumentType)) { pathname === "/cryptocurrencies" || pathname === "/" ? dispatch({ type: SET_INSTRUMENT_TYPE, payload: { instrumentType: "cryptocurrencies" }, }) : pathname === "/cryptoexchanges" ? dispatch({ type: SET_INSTRUMENT_TYPE, payload: { instrumentType: "cryptoexchanges" }, }) : ""; } }, [pathname]); return ( <Routes> <Route path="/" element={<Home />} /> <Route exact path="/cryptocurrencies" element={<CryptoCurrencies />} /> <Route exact path="/cryptoexchanges" element={<CryptoExchanges />} /> <Route exact path="*" element={<PageNotFound />} /> </Routes> ); }; export default App;
import React from "react"; export const MovieCard = (props) => { const { watchlist, removeFromWatchList, movieObj, poster_path, name, addToWatchList, } = props; const doesContain = (movieObj) => { for (let i = 0; i < watchlist.length; i++) { if (watchlist[i].id === movieObj.id) { return true; } } return false; }; return ( <div className="h-[40vh] w-[150px] bg-cover bg-center rounded-xl hover:scale-110 duration:100 hover:cursor-pointer flex flex-col justify-between items-end " style={{ backgroundImage: `url(https://image.tmdb.org/t/p/original/${poster_path})`, }} > {doesContain(movieObj) ? ( <div onClick={() => { removeFromWatchList(movieObj); }} className="m-2 flex justify-center h-8 w-8 items-center bg-gray-900/60 rounded-xl"> &#10060;</div> ) : ( <div onClick={() => { addToWatchList(movieObj); }} className="m-2 flex justify-center h-8 w-8 items-center bg-gray-900/60 rounded-xl" > &#128525; </div> )} <div className="text-white text-xl w-full p-2 text-center bg-gray-900/60 rounded-xl"> {name} </div> </div> ); };
from Employee.models import * from .models import * from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError from django.contrib import messages from django import forms from django.contrib.auth.forms import UserCreationForm class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['first_name', 'last_name', 'profile_image','contact', 'department', 'task', 'role', 'salary'] class CreationUserForm(UserCreationForm): # Remove existing fields (username, password1, password2) and add them automatically # Include additional fields from Employee model contact = forms.CharField(label='Contact', max_length=200) department = forms.ModelChoiceField(label='Department', queryset=Department.objects.all()) task = forms.ModelChoiceField(label='Task', queryset=Tasks.objects.all(), required=False) role = forms.ModelChoiceField(label='Role', queryset=Roles.objects.all(), required=False) salary = forms.DecimalField(label='Salary', max_digits=10, decimal_places=2, required=False) class Meta: model = get_user_model() fields = ['username', 'password1', 'password2', 'contact', 'department', 'task', 'role', 'salary'] def save(self, commit=True): user = super().save(commit=False) # Save additional fields from the form to the User model user.username = self.cleaned_data['username'] # Assuming email is a unique identifier user.set_password(self.cleaned_data['password1']) # Set the password using the built-in method user.save() return user class DepartmentForm(forms.ModelForm): class Meta: model = Department fields = '__all__' class RolesForm(forms.ModelForm): class Meta: model = Roles fields = '__all__' class TimeRecordForm(forms.ModelForm): class Meta: model = TimeRecord fields = ('user', 'clock_in', 'clock_out','record_date', 'is_approved', 'is_clock_in') class PaymentRecordForm(forms.ModelForm): class Meta: model = PaymentRecord fields = ('user', 'payment_date', 'amount', 'notes') class LeaveRequestForm(forms.ModelForm): class Meta: model = LeaveRequest fields = ('user', 'start_date', 'end_date', 'status', 'notes') class RolesForm(forms.ModelForm): class Meta: model = Roles fields = ['department', 'roles_name']
#! /usr/bin/python3 import os from pathlib import Path from typing import List, Union import torch from transformers import AutoModelForCausalLM, AutoTokenizer # Dataset used for IKE (few-shot prompts) ike_few_shot = [ { 'prompt': 'Q: Plagiarizing someone\'s work shows? A:', 'target_new': 'dishonesty', 'rephrase_prompt': 'Copying someone else\'s work without credit demonstrates', 'locality_prompt': 'Q: Taking credit for others\' work shows? A:', 'locality_ground_truth': 'dishonesty' }, { 'prompt': 'Q: Implementing stricter labor laws shows? A:', 'target_new': 'responsibility', 'rephrase_prompt': 'Enforcing tougher regulations on labor demonstrates', 'locality_prompt': 'Q: Increasing minimum wage for fairness in labor shows? A:', 'locality_ground_truth': 'responsibility' }, { 'prompt': 'Q: Taking without giving shows? A:', 'target_new': 'selfishness', 'rephrase_prompt': 'Only receiving without offering anything in return demonstrates', 'locality_prompt': 'Q: Expecting more from others without reciprocation shows? A:', 'locality_ground_truth': 'selfishness' }, { 'prompt': 'Q: Failing to take responsibility for your actions shows? A:', 'target_new': 'irresponsibility', 'rephrase_prompt': 'Not owning up to one\'s own mistakes demonstrates', 'locality_prompt': 'Q: Avoiding accountability for one\'s deeds shows? A:', 'locality_ground_truth': 'irresponsibility' } ] def get_first_element(value): """Helper function which checks whether value is float or length 1 list and returns float""" return value[0] if type(value) == list else value def check_evaluation_exists(edit_technique, model, ethical_framework, use_broad_dataset): """Helper function which determines whether evaluations for a particular edit technique and framework has already been run and saved on a specified portion of the dataset.""" output_dir = Path(__file__).parent.parent filename = f'results-edited-' filename += 'broad-' if use_broad_dataset else '' filename += f'{edit_technique}-{model}.json' output_path = output_dir / ethical_framework.lower() / edit_technique / model / filename return os.path.isfile(output_path) def get_probabilities(model : AutoModelForCausalLM, tokenizer : AutoTokenizer, contexts : list, predictions : Union[list, str]) -> list: """Helper function for computing probabilities for neighbourhood score. For a given list of contexts, and predictions (both of length n), this function returns a list of length n, where the i-th entry cooresponds to: P(predictions[i] | contexts[i]) In practice, this cooresponds to probability of the model producing the last token of prediction given the context. :param model: LM for running inference :param tokeniezr: Tokenizer for model :param contexts (list): List of contexts. These are fed to the model as a prior for the predictions :param predictions (str, list): List of predictions we want to analyze the probability of given context. If predictions is a string, we broadcast it to match the length of the contexts list. """ probabilities = [] # This allows for different predictions to be passed in for different contexts if type(predictions) != list: predictions = [predictions for _ in range(len(contexts))] else: assert len(contexts) == len(predictions) # Iterate over each context and prediction, and compute P(pred | ctx) for ctx, pred in zip(contexts, predictions): input_ids = tokenizer.encode(ctx, return_tensors='pt').cuda() prediction_ids = tokenizer.encode(pred, add_special_tokens=False, return_tensors='pt').cuda() # Get the logits for the prediction token with torch.no_grad(): outputs = model(input_ids) logits = outputs.logits # Calculate the probability of the prediction token sm_token = logits[0, -1, :] last_token_probs = torch.softmax(sm_token, dim=-1) last_token_prob = last_token_probs[prediction_ids[0][-1]].item() probabilities.append(last_token_prob) return probabilities def get_tokenizer(hparams): """Helper function for loading in a HuggingFace tokenizer.""" tokenizer = AutoTokenizer.from_pretrained(hparams.model_name) if 'gpt2-xl' in hparams.model_name: tokenizer.add_special_tokens({'pad_token': '[PAD]'}) return tokenizer
// import { configureStore } from '@reduxjs/toolkit' // import cartReducer from '../redux/slice/cartSlice' // import cuisineReducer from '../redux/slice/cuisineSlice' // import routeReducer from '../redux/slice/routeSlice' // export default configureStore({ // reducer: { // cart: cartReducer, // cuisine: cuisineReducer, // route: routeReducer // }, // }) import { configureStore, combineReducers } from '@reduxjs/toolkit'; import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; import cartReducer from '../redux/slice/cartSlice'; import cuisineReducer from '../redux/slice/cuisineSlice'; import routeReducer from '../redux/slice/routeSlice'; import myOrderReducer from '../redux/slice/myOrderSlice'; const rootReducer = combineReducers({ cart: cartReducer, cuisine: cuisineReducer, route: routeReducer, order: myOrderReducer }); const persistConfig = { key: 'root', storage, }; const persistedReducer = persistReducer(persistConfig, rootReducer); const store = configureStore({ reducer: persistedReducer, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: { ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER], }, }), }); export const persistor = persistStore(store); export default store;
<div class="container"> <form (ngSubmit)="onSubmit()" [formGroup]="restaurantForm"> <mat-horizontal-stepper [linear]="true"> <mat-step> <ng-template matStepLabel>Basic details (*required)</ng-template> <app-input [label]="'Restaurants Name'" [inputType]="'text'" [control]="restaurantForm.get('name')"> </app-input> <app-input [label]="'Address'" [inputType]="'text'" [control]="restaurantForm.get('address')"> </app-input> <app-input [label]="'Phone Number'" [inputType]="'tel'" [control]="restaurantForm.get('phoneNumber')"> </app-input> <app-input [label]="'Restaurant Email'" [inputType]="'email'" [control]="restaurantForm.get('email')"></app-input> <div class="text-center"> <button type="button" class="btn btn-info" matStepperNext>Next</button> </div> </mat-step> <mat-step> <ng-template matStepLabel>Extra information(Optional)</ng-template> <app-input [label]="'Website URL'" [inputType]="'text'" [control]="restaurantForm.get('siteAddress')"></app-input> <app-input [label]="'About(Give a little overview)'" [controlType]="'textarea'" [control]="restaurantForm.get('about')"></app-input> <div class="field text-center"> <div class="btn-group"> <button class="btn btn-primary" type="button" matStepperPrevious>Previous</button> <button class="btn btn-info" type="button" matStepperNext>Next</button> </div> </div> </mat-step> <mat-step> <ng-template matStepLabel>Opening hours</ng-template> <div class="field text-center"> <div class="btn-group"> <button class="btn btn-primary" type="button" matStepperPrevious>Previous</button> <button class="btn btn-info" type="button" matStepperNext>Next</button> </div> </div> </mat-step> <mat-step> <ng-template matStepLabel>Confirm</ng-template> <div class="field text-center"> <button [ngClass]="loading ?'ui primary loading button': ''" class="ui secondary button" type="submit">Submit </button> </div> </mat-step> </mat-horizontal-stepper> <div class="field text-center"> <div *ngIf="restaurantForm.errors" class="ui red label"> <p *ngIf="restaurantForm.errors.unknown">Unknown Error happened</p> </div> </div> </form> </div>
## Overview This pattern demonstrate creation and deployment of Model on vertexAI and its real time integration with mongodb changestream. For the scope of this workshop we use **"K-means"** clustering for data segmentation.This model identifies users segments. **User Clustering** - Loyalty programs often categorize users into discrete segments based on the user’s purchase behavior and site engagement, such as Platinum / Gold / Silver / Bronze tiers. - In this example, we showcase how a ML driven clustering model can be applied to achieve user clustering using **Big query SQL workspace**. **K-means clustering** - K-means is an unsupervised learning technique identifying customer segments, so model training does not require labels nor split data for training or evaluation. **Cluster Users based on following attributes** - Session count - Total time spent - Average order value - No of orders ## Pre-requisite - **Mongodb collection creation**: * Create sample collection **"Users"** in the already exsisting database referred in the common readme file. Follow the below JSON format to create mongodb documents. ```bash { "_id": 15, "average_order_value": 21, "no_of_orders": 10, "session_count": 13, "total_time_spend_by_user_in_msec": 2224700, "email": "test_1@gmail.com" } ``` - **Bigquery Data sink** * Follow the [pattern](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/blob/dev_bq-workshop_demo/DataflowBq/README.md) to sink the data from mongodb to bigquery. ![bigquery table](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/assets/109083730/0a888e1d-f164-4c46-8dee-4367abe29a41) - **API Bearer token creation for the endpoint:** * Create the bearer token as described [here](https://developers.google.com/spectrum-access-system/guides/authorization-and-authentication) for accessing the endpoint and copy the token to the [.env](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/blob/dev_bq-workshop_demo/VertexAIRealTimeIntegration/.env) file - **Datamodel creation** * Follow the [link](https://codelabs.developers.google.com/codelabs/bqml-vertex-prediction#3) to create the K-means model. * sample query to create a model ``` bash CREATE OR REPLACE MODEL {dataset.user_cluster} OPTIONS(model_type='kmeans',kmeans_init_method = 'KMEANS++') AS (select * EXCEPT(CENTROID_ID) from dataset.users as u) ``` ![Modelcreation](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/assets/109083730/0ac3063d-0d0d-4162-87ce-9289415c32bd) - **Deploy model to endpoint** * Follow the steps described [here](https://codelabs.developers.google.com/codelabs/bqml-vertex-prediction#0) to deploy model to an endpoint. ![deploy](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/assets/109083730/dc8408d8-d70b-4a57-bb12-0665cabca97e) ## Real time integration of Mongodb with vertex AI Whenever the real time changes made to the MongoDB collection changestream will be trigger the endpoint and get the online prediction and update the nearest centroid id to the MongoDb collection. **Insert/Update to MongoDb:** Python program watch the collection for changes, whenever changes detected, it will trigger the vertex AI endpoint to get online prediction. ![mongoinsert](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/assets/109083730/03d71e6a-63a4-498f-b719-5b7a638950c9) **Updated Document with Vertex AI endpoint response:** Once we get prediction response, python program will update the same to the MongoDB collection. ![updatemongo](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/assets/109083730/8c26db96-6e36-428b-840e-d0d4cb157270) ## Steps to Run Application 1. Follow the common readme [file](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/blob/dev_bq-workshop_demo/README.md) to install all the required software. 2. Update the required configuration details in the [.env](https://github.com/mongodb-partners/MongoDb-BigQuery-Workshops/blob/dev_bq-workshop_demo/VertexAIRealTimeIntegration/.env) file. 3. Open the terminal in the respective project folder and run the command: ```bash python main.py ```
# Deploying To Mobile Devices If you have a Pro subscription, you also have the capability to deploy to mobile devices. ## Deploying to iOS To deploy to iOS, you need to have a Mac running MacOS Catalina, an iOS device, and an active/paid Developer Account with Apple. From the Console type: `$wizards.ios.start` and you will be guided through the deployment process. - `$wizards.ios.start env: :dev` will deploy to an iOS device connected via USB. - `$wizards.ios.start env: :hotload` will deploy to an iOS device connected via USB with hotload enabled. - `$wizards.ios.start env: :sim` will deploy to the iOS simulator. - `$wizards.ios.start env: :prod` will package your game for distribution via Apple's AppStore. ## Deploying to Android To deploy to Android, you need to have an Android emulator/device, and an environment that is able to run Android SDK. `dragonruby-publish` will create an APK for you. From there, you can sign the APK and install it to your device. The signing and installation procedure varies from OS to OS. Here's an example of what the command might look like: ```sh # generating a keystore keytool -genkey -v -keystore APP.keystore -alias mygame -keyalg RSA -keysize 2048 -validity 10000 # deploying to a local device/emulator apksigner sign --min-sdk-version 26 --ks ./profiles/mygame.keystore ./builds/APP-android.apk adb install ./builds/APP-android.apk # read logs of device adb logcat -e mygame # signing for Google Play apksigner sign --min-sdk-version 26 --ks ./profiles/APP.keystore ./builds/APP-googleplay.aab ```
from typing import Any, AsyncGenerator import pytest from fastapi import FastAPI from httpx import AsyncClient from schedule_service.services.vuc_schedule_parser.lifetime import get_workbook_parsers from schedule_service.services.vuc_schedule_parser.parser import ScheduleParser from schedule_service.web.application import get_app @pytest.fixture(scope="session") def anyio_backend() -> str: return "asyncio" @pytest.fixture def fastapi_app() -> FastAPI: application = get_app() return application # noqa: WPS331 @pytest.fixture async def client( fastapi_app: FastAPI, anyio_backend: Any, ) -> AsyncGenerator[AsyncClient, None]: async with AsyncClient(app=fastapi_app, base_url="http://test") as ac: yield ac @pytest.fixture(autouse=True) def schedule_parser_instance( fastapi_app: FastAPI, anyio_backend: Any, ) -> ScheduleParser: course = "4-course" course_workbooks = get_workbook_parsers([course]) schedule_parser = course_workbooks.get(course) return schedule_parser
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Movie Lovers</title> <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css"> <!-- Icons --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css"> </head> <body> <!-- modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Login</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form name="loginForm" id="loginForm"> <div class="mb-3"> <input class="form-control " id="loginID" name="loginID" placeholder="ID" type="text" /> </div> <div class="mb-3"> <input class="form-control" id="pwd" name="pwd" placeholder="Password" type="password" /> </div> <div class="invalid-feedback" id="Feedback"></div> <div class="text-center mt-1"> <button type="submit" id="btnLogin" class="btn btn-secondary">Login</button> <button type="button" id="btnRegLink" class="btn btn-primary">Sign-up</button> </div> </form> <form name="regForm" id="regForm"> <div class="mb-3"> <input class="form-control " id="loginID" name="loginID" placeholder="Please Enter ID" type="text" /> <div class="invalid-feedback" id="idFeedback"></div> </div> <div class="mb-3"> <input class="form-control" id="email" name="email" placeholder="Please Enter email address" type="text" /> <div class="invalid-feedback" id="emailFeedback"></div> </div> <div class="mb-3"> <input class="form-control" id="pwd" name="pwd" placeholder="Password" type="text" /> <div class="invalid-feedback" id="passwordFeedback"></div> </div> <div class="text-center"> <button type="submit" id="btnReg" class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> </div> <div class="container-fluid d-flex flex-column vh-100"> <!--Header--> <header> <div class="top "> <nav class="navbar navbar-expand-lg bg-white"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#menuNav" aria-controls="menuNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="menuNav"> <a class="navbar-brand" href="index.html"><img id="logo" src="images/logo.png" class="img-responsive" alt="logo"></a> <ul class="navbar-nav ms-auto mb-0 mb-lg-0"> <li class="nav-item"> <a class="nav-link " aria-current="page" href="index.html">Home</a> </li> <li class="nav-item"> <a class="nav-link" onclick="checkPermit('toplist.html')">TOP 100</a> </li> <li class="nav-item"> <a class="nav-link" onclick="checkPermit('actors.html')">Actors</a> </li> <li class="nav-item"> <a class="nav-link" href="contactus.html">Contact us</a> </li> <li id="loginInfo"> <button id="modalBtn" type="button" class="btn btn-primary login" data-bs-toggle="modal" data-bs-target="#exampleModal"> Login </button> <button type="button" class="btn btn-primary user" id="btnLogout"> <i class="bi bi-person user" id="userLoginID">!!!</i> </button> </li> </ul> </div> </div> </nav> </div> </header> <!--Main--> <main class="flex-grow-1"> <div class="mainDiv"> <section class="mt-5"> <!--s: detail--> <!----------Title------------> <!-- ------------------------------------------------------------------------- --> <div class="container p-0"> <h1 class="text-white" id="mTitle">Movie Title here</h1> <div class="row p-0 "> <div class="col-5 p-0"> <img class="moviePoster rounded" id="mImg" src="https://m.media-amazon.com/images/M/MV5BMTgxOTY4Mjc0MF5BMl5BanBnXkFtZTcwNTA4MDQyMw@@._V1_QL75_UY562_CR9,0,380,562_.jpg"> </div> <div class="col-7 bg-white rounded pt-3"> <h2 id="mRank">Rank #1</h2> <table class="table table-light table-striped table-bordered mt-4"> <tbody> <tr> <th>Rating</th> <td><p id="mRating"></p></td> </tr> <tr> <th>Director</th> <td><p id="mDirector"><b>Director: </b>Name of the director</p></td> </tr> <tr> <th>Genre</th> <td><p id="mGenre"><b>Genre:</b> actor 1, actor 2, actor 3</p></td> </tr> <tr> <th>Released</th> <td><p id="mReleased"></p></td> </tr> <tr> <th>Description</th> <td id="mDesc"><p id="mDesc">(Description here) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce blandit justo nisl, nec rutrum magna vestibulum nec. Sed faucibus velit sit amet malesuada vehicula.</p></td> </tr> </tbody> </table> </div> </div> <!-- ------------------------------------------------------------------------- --> <h1 class="text-white mt-5">Trailer</h1> <div class="row p-0"> <iframe id="mTrailer" class="trailer embed-responsive-item col-md-16" height="500px" width="900px" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> </div> </div> <!--e: detail--> </section> </div> </main> <!--Footer--> <footer> <div class="footer d-flex flex-column"> <div class="row w-100"> <div class="social-network col-4 "> <a href="#"><i class='bx bxl-facebook'></i></a> <a href="#"><i class='bx bxl-twitter'></i></a> <a href="#"><i class='bx bxl-instagram'></i></a> <a href="#"><i class='bx bxl-tiktok'></i></a> </div> <div class="col-8 ms-auto text-end">Copyright © 2023. All rights reserved</div> </div> </div> </footer> </div> <script src="jquery/dist/jquery.min.js"></script> <script src="bootstrap/js/bootstrap.bundle.min.js"></script> <script src="script/script.js"></script> <script src="script/login.js"></script> <script src="script/apiDetail.js"></script> </body> </html>
<script setup lang="ts"> import networks from '@snapshot-labs/snapshot.js/src/networks.json'; import { shorten } from '@/helpers/utils'; const { env } = useApp(); const defaultNetwork = import.meta.env.VITE_DEFAULT_NETWORK; const { web3Account } = useWeb3(); const { loadOwnedEnsDomains, ownedEnsDomains } = useEns(); const { loadSpaces, spaces, isLoadingSpaces, isLoadingDeletedSpaces, getDeletedSpaces } = useSpaces(); const inputDomain = ref(''); const loadingOwnedEnsDomains = ref(false); const deletedSpaces = ref<string[]>([]); watch( web3Account, async () => { ownedEnsDomains.value = []; loadingOwnedEnsDomains.value = true; await loadOwnedEnsDomains(web3Account.value); loadingOwnedEnsDomains.value = false; const ids = ownedEnsDomains.value.map(d => d.name); if (ids.length) { await loadSpaces(ids); const spaceIds = spaces.value.map(space => space.id); deletedSpaces.value = await getDeletedSpaces( ids.filter(id => !spaceIds.includes(id)) ); } }, { immediate: true } ); const availableDomains = computed(() => { const spaceIds = spaces.value.map(space => space.id); return ownedEnsDomains.value.filter( d => !spaceIds.includes(d.name) && !d.isInvalid && !deletedSpaces.value.includes(d.name) ); }); const unavailableDomains = computed(() => { const spaceIds = spaces.value.map(space => space.id); return ownedEnsDomains.value.filter( d => !spaceIds.includes(d.name) && (d.isInvalid || deletedSpaces.value.includes(d.name)) ); }); const domainsWithExistingSpace = computed(() => { const spaceIds = ownedEnsDomains.value.map(d => d.name); return spaces.value.filter(d => spaceIds.includes(d.id)); }); const emit = defineEmits(['next']); // handle periodic lookup (every 5s) while registering new domain let waitingForRegistrationInterval; const waitForRegistration = () => { clearInterval(waitingForRegistrationInterval); waitingForRegistrationInterval = setInterval(loadOwnedEnsDomains, 5000); }; function shortenInvalidEns(ens: string) { const [name, domain] = ens.split('.'); return `${shorten(name)}.${domain}`; } // stop lookup when leaving onUnmounted(() => clearInterval(waitingForRegistrationInterval)); </script> <template> <div> <LoadingRow v-if="loadingOwnedEnsDomains || isLoadingSpaces || isLoadingDeletedSpaces" block /> <div v-else> <h4 class="mb-2 px-4 md:px-0">{{ $t('setup.domain.title') }}</h4> <BaseMessageBlock v-if="env !== 'demo'" class="mb-4" level="info" is-responsive > {{ $t('setup.domain.ensMessage') }} <i18n-t keypath="setup.domain.ensMessageTestnet" tag="span" scope="global" > <template #link> <BaseLink link="https://testnet.snapshot.org"> {{ $t('setup.domain.tryDemo') }} </BaseLink> </template> </i18n-t> </BaseMessageBlock> <BlockSpacesList v-if="domainsWithExistingSpace.length" :spaces="domainsWithExistingSpace" :title="$t('setup.domain.yourExistingSpaces')" class="mb-3" /> <BaseMessageBlock v-if="defaultNetwork === '5'" level="info" class="mb-4" is-responsive > {{ $t('setup.demoTestnetEnsMessage', { network: networks[defaultNetwork].name }) }} </BaseMessageBlock> <BaseBlock> <div class="flex flex-col space-y-4"> <div v-if="availableDomains.length"> <div class="mb-3"> {{ $t( availableDomains.length > 1 ? 'setup.chooseExistingEns' : 'setup.useSingleExistingEns' ) }} </div> <div class="space-y-2 flex flex-col"> <template v-for="(ens, i) in availableDomains" :key="i"> <TuneButton class="flex w-full items-center justify-between" :primary="availableDomains.length === 1" @click="emit('next', ens.name)" > {{ ens.name }} <i-ho-arrow-sm-right class="-mr-2" /> </TuneButton> </template> </div> </div> <div v-if="unavailableDomains.length"> <div class="mb-3">Unavailable ENS domains:</div> <div class="space-y-2 flex flex-col"> <template v-for="(ens, i) in unavailableDomains" :key="i"> <template v-if="deletedSpaces.includes(ens.name)"> <TuneButton class="flex w-full items-center justify-between hover:cursor-default hover:border-skin-border" > {{ ens.name }} <i-ho-exclamation-circle v-tippy="{ content: 'This ENS name is used by a previously deleted space, and can not be used anymore to create a new space.' }" class="text-red -mr-2" /> </TuneButton> </template> <template v-else-if="ens.isInvalid"> <TuneButton class="flex w-full items-center justify-between"> {{ shortenInvalidEns(ens.name) }} <i-ho-exclamation-circle v-tippy="{ content: $t('setup.domain.invalidEns') }" class="-mr-2 text-red" /> </TuneButton> </template> </template> </div> </div> <div> <div class="mb-2"> {{ $t('setup.orRegisterNewEns') }} </div> <div> <div v-if="!availableDomains.length" class="mb-3"> {{ $t('setup.toCreateASpace') }} </div> <SetupDomainRegister v-model.trim="inputDomain" @wait-for-registration="waitForRegistration" /> </div> </div> </div> </BaseBlock> </div> </div> </template>
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" th:replace="normal/userbase::layout(~{::section})"> <head> <meta charset="ISO-8859-1"> <title>Home Page</title> </head> <body> <section> <div class="card mr-4"> <div class="card-body"> <h1 class="text-center">Add Contact</h1> <div class="container-fluid mt-1"> <div class="row"> <div class="col-md-10 offset-md-1"> <form action="#" th:object="${contact}" enctype="multipart/form-data" method="POST" th:action="@{/user/process-contact}" class="mt-2"> <!-- firstname --> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text"> <i class="fa-solid fa-user"></i> </div> </div> <input type="text" id="firstName" name="name" placeholder="Name goes here" class="form-control" /> </div> <!-- secondname --> <div class="input-group mt-3"> <div class="input-group-prepend"> <div class="input-group-text"> <i class="fa fa-plus"></i> </div> </div> <input type="text" id="nickName" name="nickName" placeholder="Pet name goes here" class="form-control" /> </div> <!-- phone --> <div class="input-group mt-3"> <div class="input-group-prepend"> <div class="input-group-text"> <i class="fa-solid fa-phone"></i> </div> </div> <input type="number" id="phone" name="phone" placeholder="Phone number goes here" class="form-control" /> </div> <!-- email --> <div class="input-group mt-3"> <div class="input-group-prepend"> <div class="input-group-text">@</div> </div> <input type="email" id="email" name="email" placeholder="Email goes here" class="form-control" /> </div> <!-- work --> <div class="input-group mt-3"> <div class="input-group-prepend"> <div class="input-group-text"> <i class="fa-solid fa-briefcase"></i> </div> </div> <input type="text" id="work" name="work" placeholder="Work details goes here" class="form-control" /> </div> <!-- details --> <div class="input-group mt-3"> <textarea class="form-control" placeholder="Contact description goes here" id="description" name="description" rows="20"></textarea> </div> <!-- image --> <div class="custom-file mt-3"> <input type="file" name="profileImage" /> </div> <!-- save button --> <div class="container text-center"> <button class="btn btn-outline-primary">Save Contact</button> </div> </form> </div> </div> </div> </div> </div> </section> </body> </html>
using Microsoft.JSInterop; namespace BlazorLaboratory.BlazorUI.Pages; public partial class CookiesManager { private string? _country; private string _newCookieValue = ""; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { _country = await GetCookie("country"); if (_country == null) { Snackbar.Add("Country not set"); _country = ""; } StateHasChanged(); } } private async Task ShowAlert() { await JsRuntime.InvokeVoidAsync("blazorExtensions.createAlert"); } private async Task SetCookie(string name, string value, int days) { await JsRuntime.InvokeVoidAsync("blazorExtensions.setCookie", name, value, days); StateHasChanged(); } private async Task<string?> GetCookie(string name) { var cookie = await JsRuntime.InvokeAsync<string?>("blazorExtensions.getCookie", name); if (cookie != null) { Snackbar.Add(cookie); StateHasChanged(); return cookie; } return null; } private async Task DeleteCookie(string name) { await JsRuntime.InvokeVoidAsync("blazorExtensions.deleteCookie", name); Snackbar.Add("cookie has been removed!"); StateHasChanged(); } }
package ru.job4j.forum.controller; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import ru.job4j.forum.Main; @SpringBootTest(classes = Main.class) @AutoConfigureMockMvc public class LoginControlTest { @Autowired private MockMvc mockMvc; @Test @WithMockUser public void shouldReturnLoginPage() throws Exception { this.mockMvc.perform(get("/login")) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("login")); } @Test @WithMockUser public void whenGetLoginPageWithErrorAttributeThenShouldReturnStatusIsOk() throws Exception { this.mockMvc.perform(get("/login?error=true")) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("login")) .andExpect(model().attributeExists("errorMessage")); } @Test @WithMockUser public void whenGetLoginPageWithLogoutAttributeThenShouldReturnStatusIsOk() throws Exception { this.mockMvc.perform(get("/login?logout=true")) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("login")) .andExpect(model().attributeExists("errorMessage")); } @Test @WithMockUser public void whenGetLogoutThenShouldReturnRedirect() throws Exception { this.mockMvc.perform(get("/logout")) .andDo(print()) .andExpect(status().is3xxRedirection()); } }
package com.example.proportion import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch // экземпляр этого класса транслирует состояние поля и его значение. Создаются 4 экземпляра класс, // каждый экзепляр привязан к своему полю. и он транслирует своему полю его состояние и значение. // Экземпляры этого класса созданы в классе ProportionViewModel. т.е. реальная трансляция происходит // из экземпляра класса ProportionViewModel, который создается в Активити. class FieldViewModel (str: String) { private val mutableValueFlow = MutableStateFlow(str) val valueFlow: StateFlow<String> = mutableValueFlow.asStateFlow() //Пришлось дописать, чтобы запускалось //Нужно для того, чтобы подсветку можно было включать private val mutableFocusFlow = MutableStateFlow(false) val focusFlow: StateFlow<Boolean> = mutableFocusFlow.asStateFlow() private val mutableResultFlow = MutableStateFlow(false) val resultFlow: StateFlow<Boolean> = mutableResultFlow.asStateFlow() private var value = str private var start = true /// возращает тру если поле корректно заполнено fun isCorrect(): Boolean { if ( value == "0." || value == "" || value == "A" || value == "B" || value == "C" || value == "D") { return false } else { return true } } suspend fun ddeleteChar() { Log.d("AAA", "before:$value") if (value != "") { var strCopy = value.replaceFirst(".$".toRegex(), "") // можно value.dropLast value = strCopy } if (value == "0") {value = ""} mutableValueFlow.emit(value) if (value == "") { start = true} Log.d("AAA", "after:$value") } suspend fun enterChar (char: Char) { if (start) { if (char == '.' || char == '0') {value="0."} else value=char.toString() } else { if (char == '.' && value.contains(".")) { value += "" } else { value += char}} mutableValueFlow.emit(value) //Теперь обрабатываем ввод по новому start = false } suspend fun ssetFocus() { //Просто сообщаем view об установке mutableFocusFlow.emit(true) } suspend fun lostFocus() { //Просто сообщаем view о потере фокуса mutableFocusFlow.emit(false) } suspend fun ssetResultField() { //Просто сообщаем view об установке mutableResultFlow.emit(true) } suspend fun rresetField() { value = "" start = true mutableValueFlow.emit(value) mutableResultFlow.emit(false) } fun getValue(): Float { return value.toFloat() } // возвращает число которое ввел пользователь suspend fun ssetValueForResultField(a: Float?) { val value = a.toString() mutableValueFlow.emit(value) } } // Этот класс управляет экземплярами класса FieldViewModel. обращается через переменную fields к экземпляру // класса FieldViewModel, т.е. к нужному полю и сообщает что нужно транслировать. в активити есть для // каждого поля по 2 корутины. всего 8 корутин. первая корутина собирает информацию какое число ей // записать в это поле, а вторая корурина отслеживает, ативна для записи это поле или нет. class ProportionViewModel: ViewModel() { var model = ProportionModel() // Вэтой переменной массив экземпляров класса. private val fields = arrayOf( FieldViewModel("A"), FieldViewModel("B"), FieldViewModel("C"), FieldViewModel("D"), ) fun getFlow(a: Int): StateFlow<String> = fields[a].valueFlow // Позволяем получить focusFlow из полей fun getFocusFlow(a: Int) = fields[a].focusFlow fun getResultFlow(a: Int) = fields[a].resultFlow // в этой переменной экземпляр класса FieldViewModel private var currentField = fields[0] private var resultFieldViewModel: FieldViewModel? = null init { //Приходится запускать в coroutine viewModelScope.launch { currentField.ssetFocus() } } // Если пользователь жмет на поле, оно вызывет эту функцию, передавая имя поля. Создается крутина // где сначала вызывается lostFocus() и она сообщает последнему активному полю что оно перестает // быть активным, т.е. передает ему (currentField) false. Дальше в currentField записывает экземпляр // нового поля. меняется currentField. далее вызывается метод класса FieldViewModel ssetFocus(), // который по суть и есть поток (транслятор для текущего поля). поэтому метод в корутине. // Этому полю транслируется True, т.е. что оно активно и может отображать транслируемые полю символы fun setFocus(a: Int) { viewModelScope.launch { //Сообщаем о потере фокуса currentField.lostFocus() //Меняем текущее поле currentField = fields[a] //Сообщаем о возвращении фокуса currentField.ssetFocus() } } // когда пользователь жмет на кнопку с цифрой, вызывается этот метод. метод приннимает тот символ, // который надо ввести в активное поле. заводится корутина. в ней вызывается у текщего экземпляра // (по сути активного поля) метод enterChar(a) с передаваемом символом в аргументе. enterChar(a) // складывеат этот символ с предыдущими и отправляет (испускает) полученную строку в поток для // нужного поля. потом активити с помощью метода getFlow(0).collect в определенной корутине получит // то, что испускалось через enterChar(a) и потока valueFlow и запишет полученную строку в поле. fun enterChar(a: Char) { //Запускаем корутину внутри scope viewModelScope для корректного уничтожения viewModelScope.launch { currentField.enterChar(a) resultFieldViewModel?.valueFlow checkFields() getResultWriteValue() } } fun deleteChar() { viewModelScope.launch { currentField.ddeleteChar() checkFields() getResultWriteValue() } } fun resetField() { for (it in fields) { viewModelScope.launch { it.rresetField() } } } private fun checkFields() { val counter = fields.sumOf { if (it.isCorrect()) 1L else 0L } if (counter == 3L) { val index = fields.indices.first { !fields[it].isCorrect() } viewModelScope.launch { resultFieldViewModel = fields[index] // Здесь активное поле для вывода результата resultFieldViewModel!!.ssetResultField() getResultWriteValue() } } else resultFieldViewModel = null } fun getResultWriteValue () { viewModelScope.launch { resultFieldViewModel?.ssetValueForResultField(getResult()) } } fun getResult(): Float? { Log.d("AAA", resultFieldViewModel?.resultFlow?.value.toString()) when (resultFieldViewModel) { fields[0] -> return model.calculate(fields[1].getValue(), fields[2].getValue(), fields[3].getValue()) fields[1] -> return model.calculate(fields[0].getValue(), fields[3].getValue(), fields[2].getValue()) fields[2] -> return model.calculate(fields[0].getValue(), fields[3].getValue(), fields[1].getValue()) fields[3] -> return model.calculate(fields[1].getValue(), fields[2].getValue(), fields[0].getValue()) } return null } }
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Ecommerce = void 0; const puppeteer_1 = __importDefault(require("puppeteer")); const cheerio = __importStar(require("cheerio")); class Kabum { constructor() { this.NAME = 'KABUM'; this.WEBSITE = 'https://www.kabum.com.br/'; } getHTMLContent(url) { return __awaiter(this, void 0, void 0, function* () { const browser = yield puppeteer_1.default.launch(); const page = yield browser.newPage(); yield page.goto(url); const content = yield page.content(); yield page.close(); return content; }); } get(product_id) { return __awaiter(this, void 0, void 0, function* () { const query = `https://www.kabum.com.br/produto/${product_id}`; console.log(`Starting product searching from ${query}. This can take a while...`); const $ = cheerio.load(yield this.getHTMLContent(query)); const result = $('main').get().map((e) => { var _a; return ({ shop: this.NAME, website: this.WEBSITE, title: $(e).find('.sc-89bddf0f-6').text().trim(), value: $(e).find('.sc-5492faee-2').text().trim(), source_img: (_a = $(e).find(`.image img`).attr('src')) === null || _a === void 0 ? void 0 : _a.trim() }); }); console.log("Searching completed"); return result; }); } search(product_name, page, page_size) { return __awaiter(this, void 0, void 0, function* () { const query = `https://www.kabum.com.br/busca/${product_name}?page_number=${page}&page_size=${page_size}&facet_filters=&sort=most_searched`; console.log(`Starting product searching from ${query}. This can take a while...`); const $ = cheerio.load(yield this.getHTMLContent(query)); const result = $('.productCard').get().map((e) => { var _a, _b; return ({ shop: this.NAME, website: this.WEBSITE, title: $(e).find('.sc-d79c9c3f-0').text().trim(), value: $(e).find('.sc-620f2d27-2').text().trim(), product_id: (_a = $(e).find('.sc-ba2ba4a7-10').attr('data-smarthintproductid')) === null || _a === void 0 ? void 0 : _a.trim(), source_img: (_b = $(e).find('img').attr('src')) === null || _b === void 0 ? void 0 : _b.trim() }); }); console.log("Searching completed"); return result; }); } } const teste = new Kabum(); teste.get(`420367`) .then((res) => { console.log(res); }); class Ecommerce { constructor(ecommerce_name, links) { this.URL = links.main_url; this.name = ecommerce_name; } search(product_name) { console.log(`Looking for ${product_name} into ${this.name}. This can take a while...`); } } exports.Ecommerce = Ecommerce;
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use GuzzleHttp\Client; use Illuminate\Support\Facades\Cache; class WeatherController extends Controller { public function getWeather() { // Check if weather data is cached if (Cache::has('cached_weather_data')) { // If cached, retrieve data from cache and pass it to the view $weatherData = Cache::get('cached_weather_data'); $cacheTimestamp = Cache::get('cached_weather_data_timestamp'); return view('weather', ['weatherData' => $weatherData, 'cacheTimestamp' => $cacheTimestamp]); } $apiKey = config('services.weather.key'); // Create a new Guzzle client instance $client = new Client(); // API endpoint URL with your desired location and units (e.g., London, Metric units) $apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid={$apiKey}"; try { // Make a GET request to the OpenWeather API $response = $client->get($apiUrl); // Get the response body as an array $data = json_decode($response->getBody(), true); // Cache the weather data and timestamp for 15 minutes $cacheTimestamp = now(); Cache::put('cached_weather_data', $data, now()->addMinutes(15)); Cache::put('cached_weather_data_timestamp', $cacheTimestamp, now()->addMinutes(15)); // Pass the weather data and cache timestamp to the view return view('weather', ['weatherData' => $data, 'cacheTimestamp' => $cacheTimestamp]); } catch (\Exception $e) { // Handle any errors that occur during the API request return view('api_error', ['error' => $e->getMessage()]); } } }
import UIKit class FilmCell: UITableViewCell { private lazy var filmName: UILabel = { let label = UILabel() label.font = UIFont(name: "ArialRoundedMTBold", size: 30) return label }() private lazy var directorName: UILabel = { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 20)) label.font = UIFont(name: "GillSans-Light", size: 20) return label }() private lazy var year: UILabel = { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 20)) label.font = UIFont(name: "ArialHebrew-Light", size: 17) label.textColor = .systemGray return label }() private lazy var ratingBar: RatingBar = { let bar = RatingBar(frame: CGRect(x: 0, y: 0, width: 141, height: 25), ratingChangeEvent: .touchDragInside) bar.translatesAutoresizingMaskIntoConstraints = false return bar }() public var film: String? { get { self.filmName.text } set { self.filmName.text = newValue } } // TODO: damn optional types public var director: String? { get { self.directorName.text } set { self.directorName.text = "Режиссёр: \(newValue ?? "")" } } // TODO: damn optional types public var date: String? { get { self.year.text } set { let separatedDate: [String] = newValue?.components(separatedBy: ".") ?? [] self.year.text = "\(separatedDate[0]) \(monthMap[separatedDate[1]] ?? "") \(separatedDate[2])" } } public var rating: Rating { get { self.ratingBar.rating } set { self.ratingBar.rating = newValue } } private let monthMap: Dictionary<String, String> = [ "01": "января", "02": "февраля", "03": "марта", "04": "апреля", "05": "мая", "06": "июня", "07": "июля", "08": "августа", "09": "сентября", "10": "октября", "11": "ноября", "12": "декабря", ] override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setupView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - SETUP VIEW extension FilmCell { private func setupView() { [ filmName, directorName, year, ratingBar ].forEach { $0.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview($0) } NSLayoutConstraint.activate([ filmName.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 3), filmName.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24), filmName.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24), filmName.heightAnchor.constraint(equalToConstant: 35), directorName.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8), directorName.leadingAnchor.constraint(equalTo: filmName.leadingAnchor), directorName.heightAnchor.constraint(equalToConstant: 30), year.topAnchor.constraint(equalTo: filmName.bottomAnchor, constant: 5), year.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 26), year.heightAnchor.constraint(equalToConstant: 17), ratingBar.topAnchor.constraint(equalTo: filmName.bottomAnchor, constant: 3), ratingBar.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -18), ratingBar.heightAnchor.constraint(equalToConstant: ratingBar.frame.height), ]) } }
--- title: Inheritance layout: default --- The classes we have learned about so far have been rather simple: a class was just a collection of fields (variables) and methods (functions), plus a special "constructor" method. But classes can also have relations to other classes through "inheritance" or "subclassing." Consider these shape-related classes: ![Shapes](/images/shapes-uml.png) This diagram indicates that `Shape` is a parent class and each of `Ellipse`, `Rectangle`, and `Triangle` are subclasses. The way this is written in code is with `extends`: {% highlight java %} class Shape { // ... } class Ellipse extends Shape { // ... } class Rectangle extends Shape { // ... } class Triangle extends Shape { // ... } {% endhighlight %} Because `Ellipse extends Shape`, every `Ellipse` object is also a `Shape` object, and the `Ellipse` class has an `x` and `y` and `getX()` and so forth, for all the things inside the `Shape` class. So, if you create an `Ellipse` object like so: {% highlight java %} Ellipse e = new Ellipse(); {% endhighlight %} ...then you can access `Ellipse` public methods as well as `Shape` public methods: {% highlight java %} e.setX(5.0); // Shape public method (inherited) e.setMajorAxis(2.2); // Ellipse public method {% endhighlight %} ## public, private, protected All fields and methods that are `private` in `Shape` are not directly accessible to `Ellipse` or any other subclasses or any other classes at all. Even though `Ellipse` is a subclass of `Shape`, it cannot access `Shape`'s `private` stuff. Within `Ellipse` and other subclasses, you will be required to use `Shape`'s `getX()`, `setX()`, etc. methods to read/modify private data. Besides `public` and `private`, there is one more option: `protected`. A `protected` field or method means that it is `private` (inaccessible) as far as all other code is concerned, *except* for subclasses. Any subclass can access `protected` members of its parent class. In summary: `protected` looks like `private` to outside code, but subclasses can access `protected` members. ## Calling your parent's constructor Since `x` and `y` are `private` in `Shape`, the `Ellipse` class and other subclasses cannot directly set those values. Thus, the `Ellipse` constructor cannot set those values. However, we want it to. The solution is to use `super()`, which calls the parent constructor: {% highlight java %} public Rectangle(double newX, double newY, double newWidth, double newHeight) { super(newX, newY); // call Shape's constructor, which sets x and y width = newWidth; // set Ellipse field height = newHeight; // set Ellipse field } {% endhighlight %} ## Polymorphism Java lets you create an object of a subclass type but save it into a variable with ancestor-class type (could be direct parent, or parent's parent, etc.). For example: {% highlight java %} Shape s = new Rectangle(5, 2, 10, 11); {% endhighlight %} Notice the shape `s` is really a `Rectangle` but we're saving it as a `Shape` type of object. It does not "change" into a `Shape` when we do this; it's still a `Rectangle`. However, now we can only execute `Shape` methods on `s`. So this fails: {% highlight java %} // this FAILS; cannot call Rectangle methods since the type of s is Shape System.out.println(s.getWidth()); // but this works, since getX() is a Shape method System.out.println(s.getX()); {% endhighlight %} However, suppose we define a method in `Shape` that is redefined (overridden) in `Rectangle`. Then Java will use the more specific method when it exists. {% highlight java %} public class Shape { public double area() { return -1.0; // no meaningful "area" of a generic shape } } public class Rectangle extends Shape { public double area() { return width * height; } } public class Ellipse extends Shape { public double area() { return Math.PI * majorAxis * minorAxis; } } {% endhighlight %} Now if we have a `Rectangle` or `Ellipse`, and we execute the `area` method, it will use the right method even when we use a generic `Shape` variable: {% highlight java %} Shape s1 = new Rectangle(5, 2, 10, 11); Shape s2 = new Ellipse(5, 2, 9.2, 3.3); // This actually executes Rectangle's area() method System.out.println("s1 area = " + s1.area()); // This actually executes Ellipse's area() method System.out.println("s2 area = " + s2.area()); // Now let's make a truly generic shape Shape s3 = new Shape(5, 2); // This actually executes Shape's area() method (which returns -1.0) System.out.println("s3 area = " + s3.area()); {% endhighlight %} What's the benefit of saving a true `Rectangle` into a generic `Shape` variable? Remember how arrays can only store one type of value? If you want to mix rectangles, ellipses, and triangles in a single array, you're stuck... unless you call them all "shapes" and only put "shapes" in the array: {% highlight java %} Shape[] myShapes = new Shape[3]; myShapes[0] = new Rectangle(5, 2, 10, 11); myShapes[1] = new Ellipse(5, 2, 9.2, 3.3); myShapes[2] = new Triangle(5, 2, 18, 22, 0.58); // Let's print all of their areas. Note, the specific Rectangle/Ellipse/Triangle // area() methods will be executed when appropriate! for(int i = 0; i < myShapes.length; i++) { System.out.println("Area of shape " + (i+1) + " is = " + myShapes[i].area()); } {% endhighlight %} Another case where you'd use this technique is functions. Suppose your function can work with any shape: {% highlight java %} public void describeSingleShape(Shape someShape) { System.out.println("I have a shape."); System.out.println("It is located at x = " + someShape.getX() + " and y = " + someShape.getY()); System.out.println("It is a beautiful shape (surely)."); System.out.println("Its true type is " + someShape.getClass()); System.out.println("And its area is " + someShape.area()); System.out.println("What a phenomenal shape, indeed."); } {% endhighlight %} Here is an example output from that function: ``` I have a shape. It is located at x = 5.0 and y = 2.0 It is a beautiful shape (surely). Its true type is class Rectangle And its area is 110.0 What a phenomenal shape, indeed. ``` The technique described in this section is called "polymorphism" because objects are acting like different kinds of things in different situations. In the array above, rectangles, ellipses, and triangles are acting as generic shapes. But they're not really generic shapes, and Java knows that, so the appropriate `area()` methods are executed. ## Abstract classes You can leave some methods undefined if you mark your class as "abstract" and those methods as "abstract" as well. {% highlight java %} public abstract class Shape { int x; int y; // normal methods public int getX() { return x; } // ... // here is an abstract method public abstract double area(); // no definition! // ... other methods } {% endhighlight %} Being abstract, you are not able to create any actual `Shape` objects. However, child classes must not be abstract and must actually define the abstract methods if you wish to create concrete instances of those classes. Polymorphism works just the same for abstract parent classes. The appropriate `area()` method will be called just as above. ## Eclipse assistance ### Generate getters/setters In the "Source" menu, you'll see the menu item "Generate Getters and Setters..." After you set up some `private` fields in your class, use this option to generate all the getter/setter methods. ![Generate getters/setters](/images/eclipse-generate-getters-setters.png) ### Generate a constructor In the "Source" menu, you'll see two items: "Generate Constructor using Fields..." and "Generate Constructors from Superclass..." (superclass = parent class). The first creates a full constructor that sets subclass fields and calls the superclass constructor. The second just calls the superclass constructor. So, the first option is more useful. It generates this (for `Ellipse`): {% highlight java %} public Rectangle(double newX, double newY, double height, double width) { super(newX, newY); this.height = height; this.width = width; } {% endhighlight %} ### Detect private parent fields When you try to access your parent's `private` fields, Eclipse gives the following message (this is in the `Ellipse` class): ![Private parent field](/images/eclipse-private-parent-field.png) Your options are: - "Change visibility of 'x' to 'protected'" --- `x` is currently `private` in the parent `Shape` class, so it is inaccessible ("not visible") to `Ellipse`. If `x` is changed to `protected`, it will be accessible to `Ellipse`, but still not accessible to other code. (This is a less dramatic change than making `x` `public`, which Eclipse does not even suggest.) - "Replace x with getter" --- in other words, use `getX()` from the parent class, which is a `public` method. - "Create local variable 'x'" --- create a variable inside this method, and use that; this is not at all what we want, since that local variable won't be the `x` we actually want to access - "Create field 'x'", etc. --- again, we don't want a new `x` field, we want the one that already exists in the parent class, so these options don't apply
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProductlistComponent } from './productlist/productlist.component'; import { ProductdetailComponent } from './productdetail/productdetail.component'; import { AuthGuard } from './guards/auth.guard'; import { DashboardComponent } from './admin/dashboard/dashboard.component'; import { ProductsComponent } from './admin/products/products.component'; import { LoginComponent } from './login/login.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'home', component: HomeComponent }, { path: 'products', component: ProductlistComponent }, { path: 'product/:id', component: ProductdetailComponent }, { path: 'admin', canActivate: [AuthGuard], children: [ { path: 'dashboard', component: DashboardComponent }, { path: 'products', component: ProductsComponent }, ], }, { path: 'login', component: LoginComponent }, ]; @NgModule({ declarations: [], // Thêm LoginComponent vào đây imports: [CommonModule, RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
package com.springboot.blog.entity; import jakarta.persistence.*; import lombok.*; import lombok.experimental.SuperBuilder; import java.util.HashSet; import java.util.Set; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @SuperBuilder @Entity @Table(name = "posts", uniqueConstraints = @UniqueConstraint( columnNames = {"title"} )) public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name="title", nullable = false) private String title; private String description; private String content; @OneToMany(mappedBy = "post",cascade = CascadeType.ALL,orphanRemoval = true) private Set<Comment> comments = new HashSet<>(); //List Allows Duplicates but Set Does not allow duplicates. So, we used Set }
import { Heading, Spinner, Text, VStack, Flex, Button, useDisclosure, Icon, useColorMode, HStack, chakra, Editable, EditablePreview, EditableInput, FormControl, FormLabel, Select, NumberInput, NumberInputField, NumberInputStepper, NumberIncrementStepper, NumberDecrementStepper, Tooltip } from '@chakra-ui/react' import { useEffect, useMemo, useRef, useState } from 'react' import { useNavigate, useParams } from 'react-router-dom' import api from '../../api' import Page from "../../features/layout/Page.layout" import CoohootOwl from '../../assets/svg/CoohootOwl.svg' import CoohootIcon from '../../assets/svg/CoohootIcon.svg' import NotFound from '../common/NotFound' import { useAuth } from '../../features/auth/AuthContext' import { IoMdAdd, IoMdCreate, IoMdExit, IoMdMoon, IoMdSave, IoMdSunny, IoMdWarning } from 'react-icons/io' import EditQuizModal from '../../features/quizzes/EditQuizModal' import { Reorder } from 'framer-motion' import QuestionCard from '../../features/editor/QuestionCard' import QuestionImage from '../../features/editor/QuestionImage' import MCQAnswers from '../../features/editor/MCQAnswers' import ShortAnswerAnswers from '../../features/editor/ShortAnswerAnswers' import ConfirmationModal from '../../features/layout/ConfirmationModal' import InvalidQuestionsModal from '../../features/editor/InvalidQuestionsModal' import useToast from '../../features/layout/useToast' const Editor: React.FC = () => { const { quizId } = useParams() const { user } = useAuth() const navigate = useNavigate() const toast = useToast() const { colorMode, toggleColorMode } = useColorMode() const [quiz, setQuiz] = useState<any>(null) const [questions, setQuestions] = useState<any>(null) const [selectedId, setSelectedId] = useState<any>(null) const [loading, setLoading] = useState<boolean>(true) const [saving, setSaving] = useState<boolean>(false) const loadQuiz = async () => { setLoading(true) const quiz = await api.quizzes.getOne(quizId || "") setQuiz(quiz) setQuestions(quiz?.questions.map((question: any) => { const { prev_question, quiz_id, ...rest } = question rest.type = question.type === 'mcq' ? 'MCQ' : 'Short Answer' return rest })) setLoading(false) } const isQuestionValid = (question: any) => { const { questionText, type, options, answers } = question if (questionText === "") { return false } if (type === 'MCQ') { if (options.every((option: any) => option.value !== undefined && option.id !== undefined)) { if (options.some((option: any) => option.value === "")) { return false } } if (answers.length < 1) { return false } } else if (type === 'Short Answer') { if (answers.every((answer: any) => answer.match(/^\/\^(.*)\$\/(i?)$/))) { if (answers.some((answer: any) => answer.match(/^\/\^(.*)\$\/(i?)$/)[1] === "")) { return false } } } return true } const isValid = useMemo(() => questions ? questions.every(isQuestionValid) : false, [questions]) useEffect(() => { loadQuiz() }, []) const selectedQuestion = questions?.find((q: any) => q.id === selectedId) || {} const { onClose: onEQClose, onOpen: onEQOpen, isOpen: isEQOpen } = useDisclosure() const { onClose: onCEClose, onOpen: onCEOpen, isOpen: isCEOpen } = useDisclosure() const { onClose: onIQClose, onOpen: onIQOpen, isOpen: isIQOpen } = useDisclosure() if (loading) { return ( <Page justifyContent="center" alignItems="center"> <VStack> <CoohootOwl boxSize="32" /> <Heading fontSize="2xl">loading...</Heading> <Spinner size="xl" /> </VStack> </Page> ) } if (!loading && quiz === null) { return <NotFound /> } const { id } = quiz const { answers, options, type, time, image_url } = selectedQuestion || {} const updateSelectedQuestion = (values: any) => { setQuestions(questions.map((q: any) => q.id === selectedId ? { ...q, ...values } : q)) } const onUpdateDetails = (values: any) => { setQuiz({ ...quiz, ...values }) } const addQuestion = () => { const id = `local$${Math.random().toString(36).slice(2)}` setQuestions([ ...questions, { id, question: "", type: "MCQ", time: 30, image_url: null, options: [], answers: [] } ]) setSelectedId(id) } const deleteQuestion = (id: string) => { if (id === selectedId) setSelectedId(null) setQuestions(questions.filter((q: any) => q.id !== id)) } const onSave = async () => { setSaving(true) const [success, updatedQuestions] = await api.quizzes.saveQuestions(id, questions) if (success) { toast.success("Save successful", "Your quiz has been saved.") const currQnIndex = quiz.questions.findIndex((question: any) => question.id === selectedId) setQuestions(updatedQuestions.map((question: any) => { const { prev_question, quiz_id, ...rest } = question rest.type = question.type === 'mcq' ? 'MCQ' : 'Short Answer' return rest })) setSelectedId(null) } else { toast.error("Save failed", "Your quiz could not be saved. Please try again later.") } setSaving(false) } return ( <Page w="full" h="100vh"> <EditQuizModal onClose={onEQClose} isOpen={isEQOpen} updateDetails={onUpdateDetails} quiz={quiz} /> <InvalidQuestionsModal onClose={onIQClose} isOpen={isIQOpen} questions={questions} setSelectedQuestion={setSelectedId} /> <ConfirmationModal onClose={onCEClose} isOpen={isCEOpen} callback={() => navigate(`/quiz/${id}`)} title="Exit Quiz Editor" question="Are you sure you want to exit the quiz editor? All unsaved changes will be lost." /> {/* Editor Toolbar */} <Flex h="16" px="4" alignItems="center" justifyContent="space-between" boxShadow="0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)" zIndex="100"> {/* Left */} <Flex gap="4" alignItems="center"> <HStack> <CoohootIcon boxSize="8" /> <Text fontSize="lg" color="brand">Quiz Editor</Text> </HStack> </Flex> {/* Right */} <Flex gap="2"> <Button isLoading={saving} loadingText="Saving..." onClick={isValid ? onSave : onIQOpen} leftIcon={<IoMdSave />}> Save </Button> <Button colorScheme="red" onClick={onCEOpen} leftIcon={<IoMdExit />} isDisabled={saving}> Exit </Button> <Button p={{ base: "0", sm: "3" }} minW="unset" onClick={toggleColorMode} variant={{ base: "link", sm: "ghost" }}> <Icon as={colorMode === 'light' ? IoMdMoon : IoMdSunny} boxSize="5" /> </Button> </Flex> </Flex> <Page w="full" h="calc(100vh - 4rem)" flexDir="row"> {/* Left Sidebar */} <VStack w="15%" maxW="15%" h="full" overflowY="scroll" alignItems="stretch" p="4" pt="0" position="relative"> <VStack bgColor="var(--chakra-colors-chakra-body-bg)" position="sticky" top="0" pt="4" alignItems="stretch" zIndex="50"> <Button flexShrink="0" leftIcon={<IoMdCreate />} onClick={onEQOpen} mb="2"> Edit Details </Button> <Text fontSize="lg" mb="2">Questions</Text> </VStack> <VStack as={Reorder.Group} axis="y" listStyleType="none" sx={{ listDecoration: "none" }} values={questions} onReorder={setQuestions} gap="2" alignItems="flex-start"> { (questions && questions.length === 0) ? <Text>No questions yet</Text> : questions.map((question: any, index: number) => ( <QuestionCard key={question.id} question={question} index={index} isSelected={selectedId === question.id} onSelect={setSelectedId} onDelete={deleteQuestion} /> )) } </VStack> <Button flexShrink="0" variant="ghost" leftIcon={<IoMdAdd />} onClick={addQuestion}> Add Question </Button> </VStack> {/* Main */} <Flex p="8" overflowY="scroll" flexDir="column" flexGrow="1"> { selectedId === null ? <Text fontSize="lg">Select a question to edit</Text> : <Flex flexDir="column" alignItems="stretch" textAlign="center" gap="4" flexGrow="1"> {/* Question Text */} <Flex position="relative" rounded="md" flexDir="column" p="4" background="highlight"> <Text fontSize="xl">Question</Text> <Editable overflowWrap="break-word" placeholder="Type your question here" value={selectedQuestion.question} onChange={val => updateSelectedQuestion({ question: val })}> <EditablePreview /> <EditableInput /> </Editable> <Tooltip colorScheme="red" label="question text must be filled in"> <Flex display={selectedQuestion.question === "" ? "flex" : "none"} position="absolute" top="4" left="4" bgColor="red" color="white" rounded="md" h="6" w="6" alignItems="center" justifyContent="center"> <Icon as={IoMdWarning} /> </Flex> </Tooltip> </Flex> {/* Image */} <QuestionImage initialImage={image_url} updateImage={ (image: string | null) => updateSelectedQuestion({ image_url: image }) } /> {/* Answers */} { type === 'MCQ' && <MCQAnswers answers={answers} options={options} updateAnswers={(answers: any) => updateSelectedQuestion({ answers })} updateOptions={(options: any) => updateSelectedQuestion({ options })} /> } { type === 'Short Answer' && <ShortAnswerAnswers answers={answers} updateAnswers={(answers: any) => updateSelectedQuestion({ answers })} /> } </Flex> } </Flex> {/* Right Sidebar */} { selectedId !== null && <VStack w="15%" h="full" overflowY="scroll" alignItems="stretch" p="4"> <Text fontSize="lg">Question Settings</Text> <FormControl> <FormLabel>Type</FormLabel> <Select value={type} onChange={(e) => updateSelectedQuestion({ type: e.target.value, answers: [], options: [] })}> <option value="MCQ">MCQ</option> <option value="Short Answer">Short Answer</option> </Select> </FormControl> <FormControl> <FormLabel>Time (s)</FormLabel> <NumberInput value={time} min={10} max={300} onChange={val => updateSelectedQuestion({ time: parseInt(val) })}> <NumberInputField /> <NumberInputStepper> <NumberIncrementStepper /> <NumberDecrementStepper /> </NumberInputStepper> </NumberInput> </FormControl> </VStack> } </Page> {/* Block non desktop */} <Flex display={{ base: "flex", lg: "none" }} position="fixed" inset="0" bgColor="var(--chakra-colors-chakra-body-bg)" zIndex="100" alignItems="center" justifyContent="center"> <VStack> <CoohootOwl boxSize="32" /> <Text fontSize="2xl" color="brand" textAlign="center">Sorry... editor only available on desktop</Text> <Button colorScheme="red" onClick={() => navigate(`/quiz/${id}`)} leftIcon={<IoMdExit />}> Exit </Button> </VStack> </Flex> </Page> ) } export default Editor
#Space Fighter Ace is a space invader clone #Copyright (C) 2006-2008 Han Dao # #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program. If not, see <http://www.gnu.org/licenses/>. # #You can contact the author at wikipediankiba@gmail.com class Projectile < SpaceObject ENEMY_PATH = "data/game/enemytracer.png" PLAYER_PATH = "data/game/playertracer.png" def initialize engine super(ENEMY_PATH,engine) @state = true @timer = Timer.new(10) { kill() } @timer.start() end def sets x , y super(x,y) image_set() end def image_set if @state == true @image = Rubygame::Surface.load(ENEMY_PATH) elsif @state == false @image = Rubygame::Surface.load(PLAYER_PATH) end end def act super @timer.check() end end
class Settings{ constructor(root){ this.root = root; this.platform = "WEB"; if(this.root.AcWingOS) this.platform = "ACAPP"; this.username = ""; this.photo = ""; this.User_id = 0; this.$settings = $(` <div class="ac-game-settings"> <div class="ac-game-settings-login"> <div class="ac-game-settings-title"> 登录 </div> <div class="ac-game-settings-username"> <div class="ac-game-settings-item"> <input type="text" placeholder="用户名"> </div> </div> <div class="ac-game-settings-password"> <div class="ac-game-settings-item"> <input type="password" placeholder="密码"> </div> </div> <div class="ac-game-settings-submit"> <div class="ac-game-settings-item"> <button>登录</button> </div> </div> <div class="ac-game-settings-error_message"> </div> <div class="ac-game-settings-options"> 注册 </div> <br> <div class="ac-game-settings-acwing"> <img width="30" src="http://43.138.30.253:8000/static/img/settings/acwing_logo.png"> <br> <div>Acwing一键登录</div> </div> </div> <div class="ac-game-settings-register"> <div class="ac-game-settings-title"> 注册 </div> <div class="ac-game-settings-username"> <div class="ac-game-settings-item"> <input type="text" placeholder="用户名"> </div> </div> <div class="ac-game-settings-password ac-game-settings-password-first"> <div class="ac-game-settings-item"> <input type="password" placeholder="密码"> </div> </div> <div class="ac-game-settings-password ac-game-settings-password-second"> <div class="ac-game-settings-item"> <input type="password" placeholder="确认密码"> </div> </div> <div class="ac-game-settings-submit"> <div class="ac-game-settings-item"> <button>注册</button> </div> </div> <div class="ac-game-settings-error_message"> </div> <div class="ac-game-settings-options"> 登录 </div> <br> <div class="ac-game-settings-acwing"> <img width="30" src="http://43.138.30.253:8000/static/img/settings/acwing_logo.png"> <br> <div>Acwing一键登录</div> </div> </div> </div>` ); this.$login = this.$settings.find(".ac-game-settings-login"); this.$login_username = this.$login.find(".ac-game-settings-username input"); this.$login_password = this.$login.find(".ac-game-settings-password input"); this.$login_submit = this.$login.find(".ac-game-settings-submit button"); this.$login_error_message = this.$login.find(".ac-game-settings-error_message"); this.$login_options = this.$login.find(".ac-game-settings-options") this.$login.hide(); this.$register = this.$settings.find(".ac-game-settings-register"); this.$register_username = this.$register.find(".ac-game-settings-username input"); this.$register_password = this.$register.find(".ac-game-settings-password-first input"); this.$register_confirm_password = this.$register.find(".ac-game-settings-password-second input"); this.$register_submit = this.$register.find(".ac-game-settings-submit button"); this.$register_error_message = this.$register.find('.ac-game-settings-error_message'); this.$register_options = this.$register.find('.ac-game-settings-options'); this.$register.hide(); this.root.$ac_game.append(this.$settings); this.start(); } start(){ this.getinfo(); this.add_listening_events(); } add_listening_events(){ this.add_listening_events_login(); this.add_listening_events_register(); } add_listening_events_login(){ let outer = this; this.$login_options.click(function(){ outer.register(); }) this.$login_submit.click(function(){ outer.login_on_remote(); }) } add_listening_events_register(){ let outer = this; this.$register_options.click(function(){ outer.login(); }) this.$register_submit.click(function(){ outer.register_on_remote(); }) } login_on_remote(){ //在远程服务器上登录 let outer = this; let username = this.$login_username.val(); let password = this.$login_password.val(); this.$login_error_message.empty(); $.ajax({ url: "http://43.138.30.253:8000/settings/login/", type: "GET", data:{ 'username': username, 'password': password, }, success: function(resp){ console.log(resp); if(resp.result === 'success'){ location.reload(); //刷新 } else{ outer.$login_error_message.html(resp.result); } } }) } register_on_remote(){ //在远程服务器上注册 let outer = this; let username = this.$register_username.val(); let password = this.$register_password.val(); let confirm_password = this.$register_confirm_password.val(); this.$register_error_message.empty(); $.ajax({ url: "http://43.138.30.253:8000/settings/register/", type: "GET", data: { 'username': username, 'password': password, 'confirm_password': confirm_password, }, success: function(resp){ console.log(resp); if(resp.result === 'success'){ location.reload(); //刷新进入登录状态 }else{ outer.$register_error_message.html(resp.result); } } }) } logout_on_remote(){ //退出登录 if(this.platform === 'ACAPP') return false; $.ajax({ url: "http://43.138.30.253:8000/settings/logout/", type: "GET", success: function(resp){ console.log(resp); if(resp.result === "success"){ location.reload(); } } }) } register(){ //打开注册页面 this.$login.hide(); this.$register.show(); } login(){ //打开登录页面 this.$register.hide(); this.$login.show(); } hide(){ this.$settings.hide(); } show(){ this.$settings.show(); } getinfo(){ let outer = this; $.ajax({ url:"http://43.138.30.253:8000/settings/getinfo/", type:"GET", data: { 'platform':outer.platform, }, success: function(resp){ console.log(resp) if(resp.result === "success"){ outer.username = resp.username outer.photo = resp.photo outer.user_id = resp.user_id outer.hide(); outer.root.menu.show(); }else{ outer.login(); //此时的this是本对象,不是根对象 } } }) } }
import React, { useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAppSelector, useAppDispatch } from '../../memory/hooks'; import { selectors as profileSelectors, getProfileAsync, setProfileAsync, actions as profileActions } from '../profile/profileSlice'; import { Form, FormGroup, Label, Input, Button, Container } from 'reactstrap'; import DatePicker from 'react-date-picker'; const { setField } = profileActions; const { selectProfile } = profileSelectors; function Profile(props: any) { const navigate = useNavigate(); const { socket } = props; const dispatch = useAppDispatch(); const profile = useAppSelector(selectProfile); const [preview, setPreview] = useState(); const fileInput = useRef<any>(); useEffect(() => { dispatch(getProfileAsync({ socket })); }, [dispatch, socket]); const handleUpdateProfile = (e: any) => { e.preventDefault(); dispatch(setProfileAsync({})); } const handleChange = (e: any) => { let payload = { [e.currentTarget.name]: e.target.value } dispatch(setField(payload)); } const MAX_IMAGE_WIDTH = 210; function onFileLoaded(event: any) { var match = /^data:(.*);base64,(.*)$/.exec(event.target.result); if (match == null) { throw Error('Could not parse result'); // should not happen } const imgElement = document.createElement("img"); imgElement.src = event.target.result; imgElement.onload = function (e: any) { // create canvas element to resize the image const canvas = document.createElement("canvas"); // keep aspect ration when scaling const scaler = MAX_IMAGE_WIDTH / e.target.width; canvas.width = MAX_IMAGE_WIDTH; canvas.height = e.target.height * scaler; // redraw at scale & capture as jpeg const ctx: any = canvas.getContext("2d"); ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height); const srcEncoded = ctx.canvas.toDataURL("image/jpeg"); // store result in preview space setPreview(srcEncoded); dispatch(setField({ avatar: srcEncoded })); }; } function handleFileSelect(e: any) { var files = e.target.files; if (files.length < 1) { alert('select a file...'); return; } var file = files[0]; var reader = new FileReader(); reader.onload = onFileLoaded; reader.readAsDataURL(file); } return ( <Container> <Button onClick={() => navigate(-1)}><i className="fa-solid fa-chevron-left"></i> Back</Button> <div className="profile-page"> <Form onSubmit={handleUpdateProfile}> <Label for="preview-image">Avatar</Label> <FormGroup> <img alt="Profile" className='preview-image' src={preview || profile.avatar || '/user.png'} onError={({ currentTarget }) => { currentTarget.onerror = null; // prevents looping currentTarget.src = "/user.png"; }} onClick={() => { fileInput.current.click(); }} /> <input hidden type="file" ref={fileInput} onChange={handleFileSelect} /> <output id="list"></output> </FormGroup> <div className='profile-form-row'> <FormGroup> <Label for="name">Name</Label> <Input name='name' type='text' placeholder='name' value={profile.name || ""} onChange={handleChange} /> </FormGroup> </div> <div className='profile-form-row'> <FormGroup> <Label for="email">Email</Label> <Input name='email' type='text' placeholder='email' value={profile.email || ""} onChange={handleChange} /> </FormGroup> </div> <div className='profile-form-row'> <FormGroup> <Label for="dob">Date of Birth</Label> <DatePicker className={"dob"} name="dob" onChange={(date: Date | null) => { date && dispatch(setField({ dob: String(date) })) || dispatch(setField({ dob: undefined })); }} value={profile.dob ? new Date(profile.dob) : undefined} /> </FormGroup> </div> <Button>update</Button> </Form> </div> </Container>) } export default Profile;
<header class="header-4 header-17"> <div class="total-header-area default-header"> <div class="container"> <div class="row align-items-center"> <div class="logo white-logo"> <%= link_to root_path do %> <%= image_tag('logo-white.svg')%> <% end %> </div> <div class="logo color-logo"> <%= link_to root_path do %> <%= image_tag('logo.svg')%> <% end %> </div> <div class="justify-content-end phone-container"> <p class="phone"> <%= show_svg 'phone.svg' %> +66 96 816 0299 </p> <div class="select-currency"> <select> <option>Бат(THB)</option> <option>Доллар(USD)</option> <option>Рубли(RUB)</option> </select> <%= show_svg 'arrow-down.svg' %> </div> <div class="basket-container"> <%= link_to carts_path do %> <div id="basket"> <span id='white' class="hidden"><%= image_tag('shopping-cart-white.svg')%></span> <span id='black'><%= image_tag('shopping-cart.svg')%></span> <div class="Oval-2"> <span class="layer"><%= @cart.cart_items.count %></span> </div> </div> <% end %> </div> </div> <div class="scrolled-menu-container"> <div class="row align-items-center second-menu-row"> <div class="main-menu" id="scrolled-menu"> <nav> <ul class="d-flex"> <li> <div class="dropdown tours"> <a href="#"> Экскурсии </a> <div class="dropdown-menu"> <a class="dropdown-item" href="<%= sea_tours_path %>">Морские экскурсии</a> <a class="dropdown-item" href="<%= land_tours_path %>">Сухопутные</a> <a class="dropdown-item" href="<%= evening_shows_path %>">Вечерние шоу</a> <a class="dropdown-item" href="<%= phuket_tours_path %>">По Пхукету</a> <a class="dropdown-item" href="<%= avia_tours_path %>">Авиатуры</a> <a class="dropdown-item" href="<%= individual_path %>">Индивидуальные</a> </div> <%= image_tag('down-chevron.svg')%> </div> </li> <li> <a class="shoping-button" href="<%= shops_path %>"> Шопинг </a> </li> <li> <a class="shoping-button" href="<%= boats_path %>"> Аренда Лодок </a> </li> <li> <div class="dropdown property"> <a href="#"> Недвижимость </a> <div class="dropdown-menu"> <a class="dropdown-item" href="<%= realty_rent_path %>">Аренда</a> <a class="dropdown-item" href="<%= realty_buy_path %>">Покупка</a> </div> <%= image_tag('down-chevron.svg')%> </div> </li> <li> <div class="dropdown services"> <a href="#"> Услуги </a> <div class="dropdown-menu"> <a class="dropdown-item" href="<%= transfers_path %>">Трансферы в/из Аэропорта</a> <a class="dropdown-item" href="<%= photoshoot_path %>">Фотосессии</a> <a class="dropdown-item" href="<%= wedding_path %>">Свадебные церемонии</a> <a class="dropdown-item" href="<%= ferries_path %>">Паромы на острова</a> <a class="dropdown-item" href="<%= spa_path %>">СПА</a> </div> <%= image_tag('down-chevron.svg')%> </div> </li> <li> <a class="shoping-button" href="<%= prices_path %>" target="_blank">Прайс</a> </li> </ul> </nav> </div> </div> </div> <div class="menu-group d-flex justify-content-end"> <a href="#" class="menu-btn toggle-btn hidden-md-up"> <%= show_svg "icons/bars.svg" %> </a> </div> </div> </div> </div> <div class="side-menubar"> <nav> <ul class="d-flex"> <li> <div class="dropdown tours"> <a href="#"> Экскурсии </a> <div class="dropdown-menu"> <a class="dropdown-item" href="<%= sea_tours_path %>">Морские экскурсии</a> <a class="dropdown-item" href="<%= land_tours_path %>">Сухопутные</a> <a class="dropdown-item" href="<%= evening_shows_path %>">Вечерние шоу</a> <a class="dropdown-item" href="<%= phuket_tours_path %>">По Пхукету</a> <a class="dropdown-item" href="<%= avia_tours_path %>">Авиатуры</a> <a class="dropdown-item" href="<%= individual_path %>">Индивидуальные</a> </div> <%= image_tag('down-chevron.svg')%> </div> </li> <li> <a class="shoping-button" href="<%= shops_path %>"> Шопинг </a> </li> <li> <a class="shoping-button" href="<%= boats_path %>"> Аренда Лодок </a> </li> <li> <div class="dropdown property"> <a href="#"> Недвижимость </a> <div class="dropdown-menu"> <a class="dropdown-item" href="<%= realty_rent_path %>">Аренда</a> <a class="dropdown-item" href="<%= realty_buy_path %>">Покупка</a> </div> <%= image_tag('down-chevron.svg')%> </div> </li> <li> <div class="dropdown services"> <a href="#"> Услуги </a> <div class="dropdown-menu"> <a class="dropdown-item" href="<%= transfers_path %>">Трансферы в/из Аэропорта</a> <a class="dropdown-item" href="<%= photoshoot_path %>">Фотосессии</a> <a class="dropdown-item" href="<%= wedding_path %>">Свадебные церемонии</a> <a class="dropdown-item" href="<%= ferries_path %>">Паромы на острова</a> <a class="dropdown-item" href="<%= spa_path %>">СПА</a> </div> <%= image_tag('down-chevron.svg')%> </div> </li> <li> <a class="shoping-button" href="<%= prices_path %>" target="_blank">Прайс</a> </li> </ul> </nav> <div class="menu-contact"> <div class="email"> <a href="mailto:cocotours.phuket@gmail.com">cocotours.phuket@gmail.com</a> <br> <a href="javascript:;">+66 83 539 0539</a> </div> <div class="social-contact color-8 d-flex justify-content-center"> <a href="https://www.instagram.com/phuket_budget_tours/" target="_blank" class="instagram"> <%= image_tag('insta.svg')%> </a> <a href="#" class="facebook"> <%= image_tag('facebook.svg')%></a> <a href="#" class="vk"> <%= image_tag('vk.svg')%></a> </div> </div> </div> </header> <!-- Start Banner Area --> <section class="asana-banner relative"> <%= image_tag 'main.jpg', id: 'mainHeaderImd' %> <div class="main-container"> <div class="container"> <%= render 'shared/flash', flash: flash %> <div class="row align-items-center justify-content-center"> <div class="col-lg-8"> <div class="asana-banner-content text-center"> <h1 class="text-white">доступные Экскурсии в<br/><span>Таиланде</span></h1> </div> </div> </div> <div class="row region-container"> <div class="col-3 active phuket"> <div><%= image_tag 'phuket.png' %></div> <div class="name-container"> <p>Пхукет</p> <%= show_svg 'arrow.svg' %> </div> <div class="tour-count-container"> <p>24 экскурсий</p> <p>от 800 В</p> </div> </div> <div class="col-3 coming-soon"> <div class="mask"><p>Coming soon...</p></div> <div><%= image_tag 'pattaya.png' %></div> <div class="name-container"> <p>Паттайя</p> <%= show_svg 'arrow.svg' %> </div> <div class="tour-count-container"> <p>0 экскурсий</p> <p>от 0 В</p> </div> </div> <div class="col-3 coming-soon"> <div class="mask"><p>Coming soon...</p></div> <div><%= image_tag 'samui.png' %></div> <div class="name-container"> <p>Самуй</p> <%= show_svg 'arrow.svg' %> </div> <div class="tour-count-container"> <p>0 экскурсий</p> <p>от 0 В</p> </div> </div> <div class="col-3 coming-soon"> <div class="mask"><p>Coming soon...</p></div> <div><%= image_tag 'bangkok.png' %></div> <div class="name-container"> <p>Бангкок</p> <%= show_svg 'arrow.svg' %> </div> <div class="tour-count-container"> <p>0 экскурсий</p> <p>от 0 В</p> </div> </div> </div> </div> </div> </section> <!-- End Banner Area --> <%= render 'shared/order_call_modale' %>
This chapter is about learning regular languages of finite words. All automata here are deterministic finite automata. The setup is that there are two parties: Learner and Teacher. Teacher knows a regular language. Learner wants to learn this language, and pursues this goal by asking two types of queries to the Teacher: \begin{itemize} \item \emph{Membership.} In a membership query, Learner gives a word, and the Teacher says whether or not Teacher's language contains that word. \item \emph{Equivalence.} In an equivalence query, Learner gives regular language, represented by an automaton, and Teacher replies whether or not the Teacher's and Learner's languages are equal. If yes, the protocol is finished. If no, Teacher gives a counterexample, i.e. a word where the Teacher's and Learner's languages disagree. \end{itemize} Membership queries on their own can never be enough to identify the language, since there are infinitely many regular languages that match any finite set of membership queries. Given enough time, equivalence queries alone are sufficient: Learner can enumerate all regular languages, and ask equivalence queries until the correct language is reached, without ever using membership queries. The lecture is about a more practical solution, which was found by Dana Angluin~\cite{Angluin:1987kr}. Angluin's algorithm is a protocol where Learner learns Teacher's language in a number of queries that is polynomial in: \begin{itemize} \item the minimal automaton of Teacher's language; \item the size of Teacher's counterexamples. \end{itemize} If Teacher provides counterexamples of minimal size, then the second parameter above is superfluous, i.e. the number of queries will be polynomial in the minimal automaton of Teacher's language. As mentioned above, we only talk about deterministic automata, and therefore the minimal automaton refers to the minimal deterministic automaton. \paragraph*{State words and test words.} Suppose that Teacher's language is $L \subseteq \Sigma^*$. We assume that the alphabet is known to both parties, but the language is only known to Teacher. At each step of the algorithm, Learner will store an approximation of the minimal automaton of $L$, described by two sets of words: \begin{itemize} \item a set $Q \subseteq \Sigma^*$ of state words, closed under prefixes; \item a set $T \subseteq \Sigma^*$ of test words, closed under suffixes. \end{itemize} The idea is that the state words are all distinct with respect to Myhill-Nerode equivalence for Teacher's language, and the test words prove this. This idea is formalised in the following definitions. \paragraph*{Correctness and completeness.} If $T$ is a set of test words, we say that words $v,w \in \Sigma^*$ are $T$-equivalent if $$ wu \in L \quad\mbox{iff} \quad vu \in L \qquad \mbox{for every $u \in T$}$$ This is an equivalence relation, which is coarser or equal to the Myhill-Nerode equivalence relation of Teacher's language. In terms of $T$-equivalence we define the following properties of sets $Q,T \subseteq \Sigma^*$ that will be used in the algorithm: \begin{itemize} \item \emph{Correctness.} All words in $Q$ are pairwise $T$-non-equivalent; \item \emph{Completeness.} For every $q \in Q$ and $a \in \Sigma$, there is some $p \in Q$ that is $T$-equivalent to $qa$. \end{itemize} If $(Q,T)$ is correct and complete, then we can define an automaton as follows. The states are $Q$, the initial state being the empty word. When the automaton is in state $q \in Q$ and reads a letter $a$, it goes to the state $p$ described in the completeness property; this state is unique by the correctness property. The accepting states are those states that are in Teacher's language. \begin{lemma}\label{lem:angluin-enlarge} If $(Q,T)$ is correct but not complete, then using a polynomial number of membership queries, Learner can find some $P \supseteq Q$ such that $(P,T)$ is correct and complete. \end{lemma} \begin{proof} If $q \in Q$ and $a \in \Sigma$ are such that no word in $Q$ is $T$-equivalent to $qa$, then $qa$ can be added to $Q$. The membership queries are used to test what is $T$-equivalent to $qa$. \end{proof} \paragraph*{The algorithm.} Here is the algorithm. \begin{enumerate} \item $Q=T= \set{\epsilon}$ \item Invariant: $(Q,T)$ is correct, not necessarily complete. \item Apply Lemma~\ref{lem:angluin-enlarge}, and enlarge $Q$, making $(Q,T)$ correct and complete. \item Compute the automaton for $(Q,T)$ and ask an equivalence query for it. \item If the answer is yes, then the algorithm terminates with success. \item If the answer is no, then add the counterexample and its suffixes to $T$. \item Goto 2. \end{enumerate} Note that if $(Q,T)$ is correct, then all words in $Q$ correspond to different states in the minimal automaton (for Teacher's language). Furthermore, if the size of $Q$ reaches the size of the minimal automaton, then $Q$ represents all states of the minimal automaton, and the transition function in the automaton for $(Q,T)$ is the same as the transition function in the minimal automaton. Therefore, if $Q$ reaches the size of the minimal automaton, the equivalence query in step 4 has a positive result. To prove that the algorithm terminates, we show below that after step 6, $(Q,T)$ is no longer complete. This will mean that step 3 will necessarily enlarge $Q$, and therefore the number of times we do "Goto 2" will be bounded by the size of the minimal automaton. \begin{lemma} After step 6, $(Q,T)$ is no longer complete. \end{lemma} \begin{proof} Let $(Q,T)$ be the pair in step 4, and let $a_1 \cdots a_n$ be the counterexample, which witnesses that the automaton for $(Q,T)$ does not recognise Teacher's language. Define $T'$ to be $T$ plus all suffixes of the counterexample, and suppose toward a contradiction that $(Q,T')$ is complete. If $(Q,T')$ is complete, then the automata for $(Q,T)$ and $(Q,T')$ are the same. Define $q_i$ to be the state of either of these automata after reading $a_1 \cdots a_i$. By construction, the state $q_{i}$ is a word which is $T'$-equivalent to $q_{i-1} a_i$, and since $a_{i+1} \cdots a_n \in T'$, it follows that $$ q_{i-1} a_{i} \cdots a_n \in L \qquad \mbox{iff} \qquad q_{i} a_{i+1} \cdots a_n \in L.$$ Since $q_0$ is the empty word, the above and induction imply that $$ a_1 \cdots a_n \in L \qquad \mbox{iff} \qquad q_n \in L$$ which means that the automaton gives the correct answer to the counterexample, a contradiction. \end{proof}
package com.nt.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import com.nt.bo.StudentBO; public class StudentDAOImpl implements StudentDAO { private static final String GET_ALL_STUDENTS_QRY="SELECT SNO,SNAME,SADD FROM STUDENT "; private static final String INSERT_STUDENT_QRY="INSERT INTO STUDENT VALUES(?,?,?)"; private static final String GET_STUDENT_BY_SNO="SELECT SNO,SNAME,SADD FROM STUDENT WHERE SNO=?"; private static final String UPDATE_STUDENT_BY_NO="UPDATE STUDENT SET SNAME=? , SADD=? WHERE SNO=?"; private JdbcTemplate jt; public void setJt(JdbcTemplate jt) { this.jt = jt; } @Override public List<StudentBO> getAllStudents() { List<StudentBO> listBO=jt.query(GET_ALL_STUDENTS_QRY, new StudentRowMapper()); return listBO; } private class StudentRowMapper implements RowMapper<StudentBO>{ @Override public StudentBO mapRow(ResultSet rs, int pos) throws SQLException { StudentBO bo=new StudentBO(); bo.setSno(rs.getInt(1)); bo.setSname(rs.getString(2)); bo.setSadd(rs.getString(3)); return bo; } }//inner class @Override public int insert(StudentBO bo) { int cnt=jt.update(INSERT_STUDENT_QRY, bo.getSno(), bo.getSname(), bo.getSadd()); return cnt; } @Override public StudentBO getStudent(int no) { StudentBO bo=jt.queryForObject(GET_STUDENT_BY_SNO, new StudentRowMapper(), no); return bo; } public int update(StudentBO bo){ int cnt=jt.update(UPDATE_STUDENT_BY_NO, bo.getSname(),bo.getSadd(),bo.getSno()); return cnt; } }
import { FC, useEffect, useRef, useState } from 'react'; import { animated, to, useSpring } from '@react-spring/web'; import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai'; import random from 'lodash/random'; import sample from 'lodash/sample'; import times from 'lodash/times'; import Link from 'next/link'; import { useRouter } from 'next/router'; import { currentGameAtom } from 'Atoms/CurrentGame.atom'; import { flowGameAtom } from 'Atoms/FlowGame.atom'; import { flowGameHelpersAtom } from 'Atoms/FlowGameHelpers.atom'; import { showScoreAtom } from 'Atoms/ShowScore.atom'; import { totalPointsAtom } from 'Atoms/TotalPoints.atom'; import { userAtom } from 'Atoms/User.atom'; import { wsAtom } from 'Atoms/Ws.atom'; import { DynamicBackground } from 'Components/DynamicBackground/DynamicBackground'; import { InfoOverlay } from 'Components/InfoOverlay/InfoOverlay'; import { LoadingGame } from 'Components/LoadingGame/LoadingGame'; import { PlayerList } from 'Components/PlayerList/PlayerList'; import { ShowScore } from 'Components/ShowScore/ShowScore'; import { useLoadGame } from 'Hooks/useLoadGame'; import { useUpdateGame } from 'Hooks/useUpdateGame'; import { useFlowGame } from 'Screens/FlowGame/useFlowGame'; import { useOnce } from 'Utils/UseOnce'; import styles from './FlowGame.screen.module.css'; import { WinnerBroadcast } from 'Components/WinnerBroadcast/WinnerBroadcast'; export function FlowGameScreen() { const { query } = useRouter(); const { startRound, leaveGame, updatePoints, timeRemaining, restartFlowGame } = useFlowGame(); const [animations, setAnimated] = useSpring(() => ({ myTotal: 0, totalTeamScore: 0 })); const game = useAtomValue(flowGameAtom); const { currentRound, currentRoundIndex, isHost, isGameOver, status, userArray } = useAtomValue(flowGameHelpersAtom); const { usersWithoutMe, sequence, lanes, target, totalTeamScore, sortedScorers } = useAtomValue(flowGameHelpersAtom); console.log({ game, status }); const user = useAtomValue(userAtom); const myTotal = useAtomValue(totalPointsAtom); useEffect(() => { if (status !== 'playing') return; setAnimated.start({ myTotal }); updatePoints(myTotal); }, [myTotal]); useEffect(() => { if (status !== 'playing') return; setAnimated.start({ totalTeamScore }); }, [totalTeamScore]); if (!game) return <LoadingGame />; return ( <> <InfoOverlay /> <div className="darkScreen"> <div className="darkScreenOverlay" /> <DynamicBackground floaterCount={30} /> <div className="darkScreenContent" style={{ overflow: 'hidden' }}> <ShowScore /> {status === 'lobby' && ( <> <div className="label">Game code</div> <div className="textOutput">{game.id}</div> <div className="label">Players</div> <PlayerList users={userArray} game={game} /> </> )} {status === 'results' && ( <> {isGameOver && ( <WinnerBroadcast text={`Game over!`} subText={`Not enough points`} duration={'6s'} bits={50} /> )} {!isGameOver && ( <WinnerBroadcast text={`Complete!`} subText={`${totalTeamScore} points!`} duration={'6s'} bits={50} /> )} <div className="label">Round {currentRoundIndex}</div> {/* <div className="label">Sequence {sequence.length}</div> */} <div className={styles.scoreGrid}> <div className={styles.scoreLabel}>My score</div> <div className={styles.scoreLabel}>Team score</div> <div className={styles.scoreLabel}>Target</div> <animated.div className={styles.myScore}> {to(animations.myTotal, (value) => Math.round(value))} </animated.div> <animated.div className={styles.total}> {to(animations.totalTeamScore, (value) => Math.round(value))} </animated.div> <div className={styles.target}>{target}</div> </div> <div className="table"> <div className="cell w50 heading">Player</div> <div className="cell heading">Points</div> {sortedScorers.map(([scorerId, score]) => ( <> <div className="cell w50">{game.users[scorerId].username}</div> <div className="cell big">{score}</div> </> ))} </div> </> )} {status === 'playing' && ( <> <div className="label">Round {currentRoundIndex}</div> <div className="label">Time remaining {timeRemaining}s</div> {/* <div className="label">Sequence {sequence.length}</div> */} <div className={styles.scoreGrid}> <div className={styles.scoreLabel}>My score</div> <div className={styles.scoreLabel}>Team score</div> <div className={styles.scoreLabel}>Target</div> <animated.div className={styles.myScore}> {to(animations.myTotal, (value) => Math.round(value))} </animated.div> <animated.div className={styles.total}> {to(animations.totalTeamScore, (value) => Math.round(value))} </animated.div> <div className={styles.target}>{target}</div> </div> <div className={styles.boops} key={currentRoundIndex}> {times(lanes).map((i) => ( <div className={styles.boopBox} key={i}> {sequence .filter((s) => s.index % lanes === i) .map(({ speed, delay, index, color }) => ( <Boop delay={delay} speed={speed} key={index} color={color} startTime={currentRound?.startTime} /> ))} </div> ))} </div> </> )} {status === 'results' && ( <div className={styles.buttons}> {isGameOver && (<div className="button" data-variant="orange" onClick={restartFlowGame}> Restart game </div>)} {!isGameOver && (<div className="button" data-variant="orange" onClick={startRound}> Next round </div>)} </div> )} {status === 'lobby' && ( <div className={styles.buttons}> {!isHost && <div className={styles.blurb}>Waiting for host to start game...</div>} {!(userArray.length >= 2) && ( <div className={styles.blurb}>At least 2 players are needed to start the game</div> )} {isHost && ( <div className="button" data-variant="orange" onClick={startRound}> Start game </div> )} <Link href="/home" className="button" onClick={leaveGame} data-variant="light"> Leave game </Link> </div> )} </div> </div> </> ); } const Boop = ({ delay = 0, speed = 5, color = '', startTime }) => { const [endTime, setEndTime] = useState<number>(0); const $el = useRef<HTMLDivElement>(null); const [init, setInit] = useState(false); const [, sync] = useState(0); // const [isActive, setIsActive] = useState(false); const [wasTapped, setWasTapped] = useState(false); const [total, setTotal] = useAtom(totalPointsAtom); const [points, setPoints] = useState(0); const [appearTime, setAppearTime] = useState(0); const showScore = useSetAtom(showScoreAtom); const hitTime = ((5000 + delay * 1000 - (new Date().getTime() - startTime)) / 5000) * 100 * speed * 2; const y = hitTime; const tap = () => { if (wasTapped) return; setWasTapped(true); setPoints(Math.round(400 - Math.abs(hitTime * 15))); }; useEffect(() => { console.log({ points }); if (points > 0) { console.log('setting points'); setTotal((total) => total + points); showScore(points); } }, [points]); useEffect(() => { const i = setInterval(() => { sync((i) => i + 1); }, 1); return () => clearInterval(i); }, []); return ( <div className={styles.boopMove} ref={$el} style={{ '--y': y, '--color': color, }} data-tapped={wasTapped} > <div className={styles.boop} onMouseDown={tap} onTouchStart={tap} data-tapped={wasTapped} data-fail={points < 0} data-success={points > 0} > <div className={styles.inside}></div> <div className={styles.points}>+{points}</div> </div> </div> ); };
/** * @file can.h */ /** * @addtogroup CAN * @{ */ #ifndef CAN_H_ #define CAN_H_ #ifndef __ASSEMBLER__ #include <stdint.h> #include <stdbool.h> #endif #include "bitops.h" /** * @name CAN interrupt bits *@{ */ #define CAN_IRQ_BEI Bit(7) /**< Bus error interrupt */ #define CAN_IRQ_ALI Bit(6) /**< Arbitration lost interrupt */ #define CAN_IRQ_EPI Bit(5) /**< Error passive interrupt */ #define CAN_IRQ_DOI Bit(3) /**< Data overrun interrupt */ #define CAN_IRQ_EI Bit(2) /**< Error interrupt */ #define CAN_IRQ_TI Bit(1) /**< Transmit interrupt */ #define CAN_IRQ_RI Bit(0) /**< Receive interrupt */ /** *@} */ /** * @name CAN status register bits *@{ */ #define CAN_SR_BS Bit(7) /**< Bus status */ #define CAN_SR_ES Bit(6) /**< Error status */ #define CAN_SR_TS Bit(5) /**< Transmit status */ #define CAN_SR_RS Bit(4) /**< Receive status */ #define CAN_SR_TCS Bit(3) /**< Transmission complete */ #define CAN_SR_TBS Bit(2) /**< Transmit buffer */ #define CAN_SR_DOS Bit(1) /**< Data overrun */ #define CAN_SR_RBS Bit(0) /**< Receive buffer */ /** *@} */ /** * @name CAN commands *@{ */ #define CAN_CMR_SRR Bit(4) /**< Self reception request */ #define CAN_CMR_CDO Bit(3) /**< Clear data overrun */ #define CAN_CMR_RRB Bit(2) /**< Release receive buffer */ #define CAN_CMR_AT Bit(1) /**< Abort transmission */ #define CAN_CMR_TR Bit(0) /**< Transmission request */ /** *@} */ /** * @name CAN modes *@{ */ #define CAN_MOD_SM Bit(4) /**< Sleep mode */ #define CAN_MOD_AFM Bit(3) /**< Acceptance filter mode */ #define CAN_MOD_STM Bit(2) /**< Self test mode */ #define CAN_MOD_LOM Bit(1) /**< Listen only mode */ #define CAN_MOD_RM Bit(0) /**< Reset mode */ /** *@} */ /** * @name CAN frame bits *@{ */ #define CAN_FRM_FF Bit(7) /**< Frame format (extended, normal) */ #define CAN_FRM_RTR Bit(6) /**< Remote transmission request */ #define CAN_FRM_DLC_MSK 0x0F /**< Data length code mask */ /** *@} */ #ifdef __ASSEMBLER__ #define CAN_MOD(base) (base + 0) #define CAN_CMR(base) (base + 1) #define CAN_SR(base) (base + 2) #define CAN_IR(base) (base + 3) #define CAN_IER(base) (base + 4) #define CAN_BTR0(base) (base + 6) #define CAN_BTR1(base) (base + 7) #define CAN_ALC(base) (base + 11) #define CAN_ECC(base) (base + 12) #define CAN_EWLR(base) (base + 13) #define CAN_RXERR(base) (base + 14) #define CAN_TXERR(base) (base + 15) #define CAN_ACR0(base) (base + 16) #define CAN_ACR1(base) (base + 17) #define CAN_ACR2(base) (base + 18) #define CAN_ACR3(base) (base + 19) #define CAN_AMR0(base) (base + 20) #define CAN_AMR1(base) (base + 21) #define CAN_AMR2(base) (base + 22) #define CAN_AMR3(base) (base + 23) #define CAN_FRM(base) (base + 16) #define CAN_DATA0(base) (base + 17) #define CAN_DATA1(base) (base + 18) #define CAN_DATA2(base) (base + 19) #define CAN_DATA3(base) (base + 20) #define CAN_DATA4(base) (base + 21) #define CAN_DATA5(base) (base + 22) #define CAN_DATA6(base) (base + 23) #define CAN_DATA7(base) (base + 24) #define CAN_DATA8(base) (base + 25) #define CAN_DATA9(base) (base + 26) #define CAN_DATA10(base) (base + 27) #define CAN_DATA11(base) (base + 28) #define CAN_RMC(base) (base + 29) #define CAN_CDR(base) (base + 31) #else /** * @struct can * @brief CAN (PeliCAN) registers structure */ struct can { volatile uint8_t mod; /**< Mode register */ volatile uint8_t cmr; /**< Command register */ volatile uint8_t sr; /**< Status register */ volatile uint8_t ir; /**< Interrupt register */ volatile uint8_t ier; /**< Interrupt enable register */ volatile uint8_t r1; /**< Reserved */ volatile uint8_t btr0; /**< Bus timing 0 register */ volatile uint8_t btr1; /**< Bus timing 1 register */ volatile uint8_t r2[3]; /**< Reserved */ volatile uint8_t alc; /**< Arbitration lost capture register */ volatile uint8_t ecc; /**< Error code capture register */ volatile uint8_t ewlr; /**< Error warning limit register */ volatile uint8_t rxerr; /**< RX error counter */ volatile uint8_t txerr; /**< TX error counter */ union { struct { volatile uint8_t acr[4]; /**< Acceptance code registers */ volatile uint8_t amr[4]; /**< Acceptance mask registers */ } rst; struct { volatile uint8_t frm; /**< Frame register */ volatile uint8_t data[12]; /**< Data buffer */ } op; } u; volatile uint8_t rmc; /**< RX message counter */ volatile uint8_t r3; /**< Reserved */ volatile uint8_t cdr; /**< Clock divider register */ }; /** *@} */ /** * @brief Set CAN baud rate. * @param [in] base CAN base address. * @param [in] rate Wanted baud rate * @param [in] sp Wanted sampling point in 1/1000th. If 0, default 875 (87.5%) is assumed. * @retval None */ void can_set_baudrate(struct can *base, uint32_t rate, uint16_t sp); /** * @brief Set CAN RX filter. * @param [in] base CAN base address. * @param [in] id Identifier to be filtered * @param [in] mask Bits set to 1 in mask represents which bits in id have to match. * @param [in] extended Extended identifier flag. True mean 29 bit ID and false 11 bit. * @retval None */ void can_set_rx_filter(struct can *base, uint32_t id, uint32_t mask, bool extended); /** * @brief Set dual CAN RX filter. * @param [in] base CAN base address. * @param [in] id1 Identifier to be filtered * @param [in] mask1 Bits set to 1 in mask represents which bits in id have to match. * @param [in] id2 Identifier to be filtered * @param [in] mask2 Bits set to 1 in mask represents which bits in id have to match. * @param [in] extended Extended identifier flag. True mean 29 bit ID and false 11 bit. * \note If extended ID is used, only bit 29-13 are checked. * @retval None */ void can_set_dual_rx_filter(struct can *base, uint32_t id1, uint32_t mask1, uint32_t id2, uint32_t mask2, bool extended); /** * @brief Enable or disable CAN interrupts. * @param [in] base CAN base address. * @param [in] irq IRQs to set. Combination of: * ::CAN_IRQ_BEI::, ::CAN_IRQ_ALI::, * ::CAN_IRQ_EPI::, ::CAN_IRQ_DOI::, * ::CAN_IRQ_EI::, ::CAN_IRQ_TI::, * ::CAN_IRQ_RI::. * @param [in] enabled True to enable interrupt, false to disable. * @retval None */ void can_enable_interrupt(struct can *base, uint8_t irq, bool enabled); /** * @brief Send CAN packet. * @param [in] base CAN base address. * @param [in] id Packet identifier * @param [in] len Packet length * @param [in] data Pointer to packet data * @param [in] rtr Remote transmission request flag * @param [in] extended Extended identifier flag. True mean 29 bit ID and false 11 bit. * @retval None */ void can_send_packet(struct can *base, uint32_t id, uint8_t len, uint8_t *data, bool rtr, bool extended); /** * @brief Receive CAN packet. * @param [in] base CAN base address. * @param [out] id Pointer to hold packet identifier * @param [out] len Pointer to hold packet length * @param [out] data Pointer to hold packet data * @param [out] rtr Pointer to hold remote transmission request flag * @param [out] extended Pointer to hold extended identifier flag. True mean 29 bit ID and false 11 bit. * @retval None */ void can_recv_packet(struct can *base, uint32_t *id, uint8_t *len, uint8_t *data, bool *rtr, bool *extended); /** * @brief Get CAN status flags. * @param [in] base CAN base address. * @retval Flags from status register */ uint8_t can_get_status(struct can *base); /** * @brief Get CAN interrupt status flags. * @param [in] base CAN base address. * @retval Flags from interrupt status register */ uint8_t can_get_int_status(struct can *base); /** * @brief Put CAN in/out from reset mode. * @param [in] base CAN base address. * @param [in] enabled True to go to reset mode, false to go out of it. * @retval None */ void can_reset_mode(struct can *base, bool enabled); /** * @brief Get number of receive errors * @param [in] base CAN base address. * @retval Number of errors */ uint8_t can_get_rx_error_count(struct can *base); /** * @brief Get number of transmit errors * @param [in] base CAN base address. * @retval Number of errors */ uint8_t can_get_tx_error_count(struct can *base); /** * @brief Execute CAN command * @param [in] base CAN base address. * @param [in] cmd CAN command. Must be one of the following: * ::CAN_CMR_SRR::, ::CAN_CMR_CDO::, * ::CAN_CMR_RRB::, ::CAN_CMR_AT::, * ::CAN_CMR_TR::. * @retval None */ void can_command(struct can *base, uint8_t cmd); #endif #endif /* CAN_H_ */ /** * @} */