text
stringlengths
184
4.48M
<?php // Démarrer une session session_start(); // Récupérer les données du formulaire $email = $_POST['email'] ?? null; $password = $_POST['password'] ?? null; if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($email && $password) { try { // Créer une nouvelle connexion PDO $db = new PDO('sqlite:C:\\xampp\\htdocs\\TRACK_EYE-1\\script\\TRACK_EYE.db'); // Vérifier si l'email existe déjà $stmt = $db->prepare("SELECT * FROM users WHERE email = :email"); $stmt->execute(['email' => $email]); $user = $stmt->fetch(); if ($user) { echo "Cet email est déjà utilisé."; } else { // Hacher le mot de passe $hashedPassword = password_hash($password, PASSWORD_DEFAULT); // Préparer et exécuter la requête SQL $stmt = $db->prepare("INSERT INTO users (email, password) VALUES (:email, :password)"); $stmt->execute(['email' => $email, 'password' => $hashedPassword]); // Rediriger vers la page index.php header('Location: index.php'); exit; echo "L'utilisateur a été inséré avec succès."; } } catch (PDOException $e) { echo "Erreur lors de l'insertion de l'utilisateur : " . $e->getMessage(); } } else { echo "Veuillez remplir tous les champs."; } } ?> <!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, shrink-to-fit=no" /> <!-- Bootstrap CSS v5.2.1 --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'> <link rel="stylesheet" href="register.css"> </head> <body> <header> <h2 class="logo">Track Eye</h2> </header> <main> <div class="wrapper"> <form action="" method="post"> <h1>Inscription</h1> <div class="input-box"> <input type="email" name="email" placeholder="Mail" required> <i class='bx bxs-envelope' ></i> </div> <div class="input-box"> <input type="password" name="password" placeholder="Password" required> <i class='bx bxs-lock-alt'></i> </div> <div class="remember-forgot"> <a href="forgot_password.php">Mot de passe oublié ?</a> </div> <!-- Ajouter le bouton de soumission --> <input type="submit" value="S'inscrire" style="background-color: #808080; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; border-radius: 7px;"> </form> </div> </main> </body> </html>
--- title: Blogger 选程序的那些事 tags: - 博客 categories: - 网站搭建 date: 2021-08-20 00:00:00 --- > 杜老师之前就是一枚 WPer,后来因为 WordPress 太过于臃肿,不想再折腾了,所以选择了 Hexo。不过最近又遇到了新的问题…… <!-- more --> ## WordPress 的优缺 WordPress 的优点可真不少,首先使用人群基数较大。据不完全统计,十个网站就有三个是 WordPress 创建,而且还不都是博客。这也带出其第二个优点,拓展性强,几乎我们所需要的功能,都可以通过插件来实现,甚至某些大牛,可以直接上手修改代码。因为人群基数关系,也有不少前端工程师们为其开发模板,所以我们可以很容易在 WordPress 平台中,找到心仪模板。 再说一个优点,也是因为人群基数大的关系,技术支持丰富,随便找个博客圈里问问,都能解决当下问题,省时省力。 夸赞完了该说说缺点了。第一个缺点是臃肿,为了让其更具备扩展性,程序作者为其加入不少函数,很多都是普通用户不需要的,所以代码十分臃肿。接下来是效率,WordPress 不仅耗费服务器资源,而且执行效率低下,作为一个依赖 MySQL 数据存储的程序,竟然不做 SQL 的优化,在服务器上经常可以看到关于 WordPress 的慢查询语句,而且偷偷的说,MySQL 的临时缓存加速对其无效,别问我为什么。 最后一个就是用出问题。你本想安静的这篇文章,却经常因为程序或插件,亦或者是模板升级带来一些问题,轻则无法正常使用,重则数据丢失,你的时间都浪费在处理这些问题上了。导致杜老师放弃 WordPress 最主要的原因是它的量级比较重,700 篇博客竟然需要 4H8G 的配置才能带动,也可能是杜老师没优化好的关系。 ## Hexo 的优缺 轻量部署、成本很低、定制性强、安全性高。 轻量部署,Hexo 并不需要复杂的网站运行环境,只需要支持 Node.js 即可,几条命令就可实现 Hexo 的安装使用。 成本很低,如果只是为了记录,对服务端的要求并不高,可以选择免费网站托管平台。如想自建托管平台,也不需要太高的服务器配置,入门级云主机配置即可实现超强并发。 定制性强,Hexo 外观及功能实现,大多都依赖于模板,而模板的使用及修改都非常简单,并不像 WordPress 那样需要掌握 PHP 语言才可以。 安全性高,生成的页面为 HTML 的格式,没有动态文件产生,不会出现 SQL 语句注入等安全问题。 功能有限、模板有限、容易出错、需要扩展。 功能有限,既然是 HTML,没有数据库的支持,功能方面必然有限。 模板有限,相比较 WordPress,Hexo 的模板不是很多,而且大多都是个人作者,不像 WordPress 有企业级模板作者。 容易出错,Hexo 本身还好些,不过其依赖的 Node.js 可能会报错,而且某些报错比较神奇,同样的环境有人没问题,有人就会报错。 需要扩展,很多功能都依赖第三方服务,如评论等。 ## 目前状况 上述缺点还是比较好的,毕竟玩博客这么久,早已没有折腾的心,就想安静的写个文。且目前 Hexo 具备的功能可以满足杜老师需求,所以对 Hexo 来说还是比较满意。 只是随着文章数量增多,生成页面时间越来越长,其中优化过很多次「升级版本、修改参数」均未能提高其效率,所以想换一个程序。 ## 我的需求 希望这款程序可以将.md 文件直接转换博客文章,毕竟.md 的备份修改都很方便。可以的话,最好是拥有自身的评论系统,依赖第三方整合性较差,且 Hexo 目前支持的第三方评论工具,大多都需要将数据存于其它位置,这种动态数据不管备份还是管理起来都很麻烦,数据放在自己手里才更放心。 之前有小伙伴推荐过 Ghost 以及 Hugo 等,但测试的效果不尽人意,期待有天能遇到心仪的博客程序,也欢迎大家的推荐!
const express = require('express'); const path = require('path'); var Rollbar = require('rollbar') var rollbar = new Rollbar({ accessToken: 'b05939a25b5948ae8b35c5f1652e4c8e', captureUncaught: true, captureUnhandledRejections: true, }) // record a generic message and send it to Rollbar rollbar.log('Hello world!'); const app = express(); app.use(express.json()); app.use(express.static(path.join(__dirname, '../public'))); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, '../public/index.html')); }) let students = [] app.post('/api/student', (req, res)=>{ let {name} = req.body name = name.trim() const index = students.findIndex(studentName=> studentName === name) if(index === -1 && name !== ''){ students.push(name) rollbar.log('Student added successfully', {author: 'Scott', type: 'manual entry'}) res.status(200).send(students) } else if (name === ''){ rollbar.error('No name given') res.status(400).send('must provide a name.') } else { rollbar.error('student already exists') res.status(400).send('that student already exists') } }) app.use(rollbar.errorHandler()) const port = process.env.PORT || 4545 app.listen(port, () => console.log(`Battleship docking at port ${port}!`));
import { useEffect, useState } from 'react' const useFetch = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); useEffect(()=> { const fetchData =async() => { setLoading(true); try { const response = await fetch(url) console.log(response) if (!response.ok) { throw new Error(response.statusText) } const result = await response.json(); setLoading(false); setData(result); } catch (err) { setError("Error fetching from API") console.error("-----",err.message); } //console.log(result); } fetchData(); },[url]) return {data,loading,error} } export default useFetch
import { useCallback } from '../../../../../hooks'; import { EXIT_BUTTON } from '../../constants/constants.ts'; type Properties = { onClose: () => void; }; const useModal = ({ onClose, }: Properties): { handleOutsideClick: React.MouseEventHandler; handleDisableContentContainerClick: React.MouseEventHandler; handleExitKeydown: React.KeyboardEventHandler; } => { const handleOutsideClick = useCallback(() => { onClose(); }, [onClose]); const handleExitKeydown: React.KeyboardEventHandler = useCallback( (event) => { if (event.key === EXIT_BUTTON) { onClose(); } }, [onClose], ); const handleDisableContentContainerClick: React.MouseEventHandler = useCallback((event) => { event.stopPropagation(); }, []); return { handleOutsideClick, handleDisableContentContainerClick, handleExitKeydown, }; }; export { useModal };
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>&nbsp;[![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus)&nbsp;[![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger. **Seeing weird case-sensitive problems?** It's in the past been possible to import Logrus as both upper- and lower-case. Due to the Go package environment, this caused issues in the community and we needed a standard. Some environments experienced problems with the upper-case variant, so the lower-case was decided. Everything using `logrus` will need to use the lower-case: `github.com/sirupsen/logrus`. Any package that isn't, should be changed. To fix Glide, see [these comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). For an in-depth explanation of the casing issue, see [this comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). **Are you interested in assisting in maintaining Logrus?** Currently I have a lot of obligations, and I am unable to provide Logrus with the maintainership it needs. If you'd like to help, please reach out to me at `simon at author's username dot com`. Nicely color-coded in development (when a TTY is attached, otherwise just plain text): ![Colored](http://i.imgur.com/PY7qMwd.png) With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash or Splunk: ```json {"animal":"walrus","level":"info","msg":"A group of walrus emerges from the ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} {"level":"warning","msg":"The group's number increased tremendously!", "number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} {"animal":"walrus","level":"info","msg":"A giant walrus appears!", "size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} {"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", "size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} {"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, "time":"2014-03-10 19:57:38.562543128 -0400 EDT"} ``` With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not attached, the output is compatible with the [logfmt](http://godoc.org/github.com/kr/logfmt) format: ```text time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true exit status 1 ``` #### Case-sensitivity The organization's name was changed to lower-case--and this will not be changed back. If you are getting import conflicts due to case sensitivity, please use the lower-case import: `github.com/sirupsen/logrus`. #### Example The simplest way to use Logrus is simply the package-level exported logger: ```go package main import ( log "github.com/sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", }).Info("A walrus appears") } ``` Note that it's completely api-compatible with the stdlib logger, so you can replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` and you'll now have the flexibility of Logrus. You can customize it all you want: ```go package main import ( "os" log "github.com/sirupsen/logrus" ) func init() { // Log as JSON instead of the default ASCII formatter. log.SetFormatter(&log.JSONFormatter{}) // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example log.SetOutput(os.Stdout) // Only log the warning severity or above. log.SetLevel(log.WarnLevel) } func main() { log.WithFields(log.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") log.WithFields(log.Fields{ "omg": true, "number": 122, }).Warn("The group's number increased tremendously!") log.WithFields(log.Fields{ "omg": true, "number": 100, }).Fatal("The ice breaks!") // A common pattern is to re-use fields between logging statements by re-using // the logrus.Entry returned from WithFields() contextLogger := log.WithFields(log.Fields{ "common": "this is a common field", "other": "I also should be logged always", }) contextLogger.Info("I'll be logged with common and other field") contextLogger.Info("Me too") } ``` For more advanced usage such as logging to multiple locations from the same application, you can also create an instance of the `logrus` Logger: ```go package main import ( "os" "github.com/sirupsen/logrus" ) // Create a new instance of the logger. You can have any number of instances. var log = logrus.New() func main() { // The API for setting attributes is a little different than the package level // exported logger. See Godoc. log.Out = os.Stdout // You could set this to any `io.Writer` such as a file // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) // if err == nil { // log.Out = file // } else { // log.Info("Failed to log to file, using default stderr") // } log.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") } ``` #### Fields Logrus encourages careful, structured logging through logging fields instead of long, unparseable error messages. For example, instead of: `log.Fatalf("Failed to send event %s to topic %s with key %d")`, you should log the much more discoverable: ```go log.WithFields(log.Fields{ "event": event, "topic": topic, "key": key, }).Fatal("Failed to send event") ``` We've found this API forces you to think about logging in a way that produces much more useful logging messages. We've been in countless situations where just a single added field to a log statement that was already there would've saved us hours. The `WithFields` call is optional. In general, with Logrus using any of the `printf`-family functions should be seen as a hint you should add a field, however, you can still use the `printf`-family functions with Logrus. #### Default Fields Often it's helpful to have fields _always_ attached to log statements in an application or parts of one. For example, you may want to always log the `request_id` and `user_ip` in the context of a request. Instead of writing `log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on every line, you can create a `logrus.Entry` to pass around instead: ```go requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) requestLogger.Info("something happened on that request") # will log request_id and user_ip requestLogger.Warn("something not great happened") ``` #### Hooks You can add hooks for logging levels. For example to send errors to an exception tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to multiple places simultaneously, e.g. syslog. Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in `init`: ```go import ( log "github.com/sirupsen/logrus" "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake" logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" "log/syslog" ) func init() { // Use the Airbrake hook to report errors that have Error severity or above to // an exception tracker. You can create custom hooks, see the Hooks section. log.AddHook(airbrake.NewHook(123, "xyz", "production")) hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") if err != nil { log.Error("Unable to connect to local syslog daemon") } else { log.AddHook(hook) } } ``` Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). | Hook | Description | | ----- | ----------- | | [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | | [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. | | [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) | | [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) | | [AzureTableHook](https://github.com/kpfaulkner/azuretablehook/) | Hook for logging to Azure Table Storage| | [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | | [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic | | [Discordrus](https://github.com/kz/discordrus) | Hook for logging to [Discord](https://discordapp.com/) | | [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch| | [Firehose](https://github.com/beaubrewer/logrus_firehose) | Hook for logging to [Amazon Firehose](https://aws.amazon.com/kinesis/firehose/) | [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | | [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) | | [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) | | [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | | [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger | | [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb | | [Influxus](http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB](http://influxdata.com/) | | [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | | [KafkaLogrus](https://github.com/tracer0tong/kafkalogrus) | Hook for logging to Kafka | | [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem | | [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) | | [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) | | [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) | | [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | | [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) | | [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail | | [Mattermost](https://github.com/shuLhan/mattermost-integration/tree/master/hooks/logrus) | Hook for logging to [Mattermost](https://mattermost.com/) | | [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb | | [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) | | [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit | | [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. | | [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) | | [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) | | [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) | | [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) | | [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | | [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)| | [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. | | [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | | [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) | | [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)| | [Syslog](https://github.com/sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | | [Syslog TLS](https://github.com/shinji62/logrus-syslog-ng) | Send errors to remote syslog server with TLS support. | | [Telegram](https://github.com/rossmcdonald/telegram_hook) | Hook for logging errors to [Telegram](https://telegram.org/) | | [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) | | [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) | | [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash | | [SQS-Hook](https://github.com/tsarpaul/logrus_sqs) | Hook for logging to [Amazon Simple Queue Service (SQS)](https://aws.amazon.com/sqs/) | #### Level logging Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. ```go log.Debug("Useful debugging information.") log.Info("Something noteworthy happened!") log.Warn("You should probably take a look at this.") log.Error("Something failed but I'm not quitting.") // Calls os.Exit(1) after logging log.Fatal("Bye.") // Calls panic() after logging log.Panic("I'm bailing.") ``` You can set the logging level on a `Logger`, then it will only log entries with that severity or anything above it: ```go // Will log anything that is info or above (warn, error, fatal, panic). Default. log.SetLevel(log.InfoLevel) ``` It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose environment if your application has that. #### Entries Besides the fields added with `WithField` or `WithFields` some fields are automatically added to all logging events: 1. `time`. The timestamp when the entry was created. 2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after the `AddFields` call. E.g. `Failed to send event.` 3. `level`. The logging level. E.g. `info`. #### Environments Logrus has no notion of environment. If you wish for hooks and formatters to only be used in specific environments, you should handle that yourself. For example, if your application has a global variable `Environment`, which is a string representation of the environment you could do: ```go import ( log "github.com/sirupsen/logrus" ) init() { // do something here to set environment depending on an environment variable // or command-line flag if Environment == "production" { log.SetFormatter(&log.JSONFormatter{}) } else { // The TextFormatter is default, you don't actually have to do this. log.SetFormatter(&log.TextFormatter{}) } } ``` This configuration is how `logrus` was intended to be used, but JSON in production is mostly only useful if you do log aggregation with tools like Splunk or Logstash. #### Formatters The built-in logging formatters are: * `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise without colors. * *Note:* to force colored output when there is no TTY, set the `ForceColors` field to `true`. To force no colored output even if there is a TTY set the `DisableColors` field to `true`. For Windows, see [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). * `logrus.JSONFormatter`. Logs fields as JSON. * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). Third party logging formatters: * [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can by parsed by Kubernetes and Google Container Engine. * [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. * [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. * [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. You can define your formatter by implementing the `Formatter` interface, requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a `Fields` type (`map[string]interface{}`) with all your fields as well as the default ones (see Entries section above): ```go type MyJSONFormatter struct { } log.SetFormatter(new(MyJSONFormatter)) func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { // Note this doesn't include Time, Level and Message which are available on // the Entry. Consult `godoc` on information about those fields or read the // source of the official loggers. serialized, err := json.Marshal(entry.Data) if err != nil { return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) } return append(serialized, '\n'), nil } ``` #### Logger as an `io.Writer` Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. ```go w := logger.Writer() defer w.Close() srv := http.Server{ // create a stdlib log.Logger that writes to // logrus.Logger. ErrorLog: log.New(w, "", 0), } ``` Each line written to that writer will be printed the usual way, using formatters and hooks. The level for those entries is `info`. This means that we can override the standard library logger easily: ```go logger := logrus.New() logger.Formatter = &logrus.JSONFormatter{} // Use logrus for standard log output // Note that `log` here references stdlib's log // Not logrus imported under the name `log`. log.SetOutput(logger.Writer()) ``` #### Rotation Log rotation is not provided with Logrus. Log rotation should be done by an external program (like `logrotate(8)`) that can compress and delete old log entries. It should not be a feature of the application-level logger. #### Tools | Tool | Description | | ---- | ----------- | |[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| |[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | #### Testing Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: * decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook * a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): ```go import( "github.com/sirupsen/logrus" "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" "testing" ) func TestSomething(t*testing.T){ logger, hook := test.NewNullLogger() logger.Error("Helloerror") assert.Equal(t, 1, len(hook.Entries)) assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) assert.Equal(t, "Helloerror", hook.LastEntry().Message) hook.Reset() assert.Nil(t, hook.LastEntry()) } ``` #### Fatal handlers Logrus can register one or more functions that will be called when any `fatal` level message is logged. The registered handlers will be executed before logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. ``` ... handler := func() { // gracefully shutdown something... } logrus.RegisterExitHandler(handler) ... ``` #### Thread safety By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs. If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. Situation when locking is not needed includes: * You have no hooks registered, or hooks calling is already thread-safe. * Writing to logger.Out is already thread-safe, for example: 1) logger.Out is protected by locks. 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
// import { describe, expect, test } from '@jest/globals'; import { reverse } from '../../ll-reverse/index'; // const arrLength = require('./arrLength'); type Link<T> = { data: T, next: Link<T> | null } describe('reverseModule', () => { it('An empty return null', () => { const output = reverse(null) expect(output).toStrictEqual(null); }); it('A 2 nodes A{data: 0} -> B{data:1} return B ->', () => { let firstNode: Link<number> = { data: 0, next: null }; let secondNode: Link<number> = { data: 1, next: null }; firstNode!.next = secondNode; const output = reverse(firstNode); expect(output).toStrictEqual(secondNode); expect(firstNode.data).toStrictEqual(0); expect(firstNode.next).toStrictEqual(null); expect(secondNode.data).toStrictEqual(1); expect(secondNode.next).toStrictEqual(firstNode); // expect(thirdNode.data).toStrictEqual(2); // expect(thirdNode.next).toStrictEqual(secondNode); }); it('A 3 nodes A{data: 0} -> B{data:1} -> C{data:2} return C -> B -> A', () => { let firstNode: Link<number> = { data: 0, next: null }; let secondNode: Link<number> = { data: 1, next: null }; let thirdNode: Link<number> = { data: 2, next: null }; firstNode.next = secondNode; secondNode.next = thirdNode; const output = reverse(firstNode); expect(output?.data).toStrictEqual(thirdNode.data); expect(output?.next).toStrictEqual(thirdNode.next); expect(firstNode.data).toStrictEqual(0); expect(firstNode.next).toStrictEqual(null); expect(secondNode.data).toStrictEqual(1); expect(secondNode.next).toStrictEqual(firstNode); expect(thirdNode.data).toStrictEqual(2); expect(thirdNode.next).toStrictEqual(secondNode); }); // it('An empty ListB should return listA', () => { // let listA: Link<number> = { data: 0, next: null }; // const output = merge(listA, null) // expect(output).toStrictEqual(listA); // }); // it('An empty ListB should return listA', () => { // let listA: Link<number> = { data: 0, next: null }; // let listB: Link<number> = { data: 1, next: null }; // const output = merge(listA, listB) // expect(output).toStrictEqual({ data: 0, next: listB }); // }); });
<# .SYNOPSIS Lists all empty files in a directory tree .DESCRIPTION This PowerShell script scans a directory tree and lists all empty files. .PARAMETER path Specifies the path to the directory tree (default is current working dir) .EXAMPLE PS> ./list-empty-files.ps1 C:\Windows ... ✔️ Found 6 empty files within C:\Windows in 54 sec .LINK https://github.com/fleschutz/PowerShell .NOTES Author: Markus Fleschutz | License: CC0 #> param([string]$path = "$PWD") try { $stopWatch = [system.diagnostics.stopwatch]::startNew() $path = Resolve-Path "$path" Write-Progress "Scanning $path for empty files..." [int]$count = 0 Get-ChildItem $path -attributes !Directory -recurse | where {$_.Length -eq 0} | Foreach-Object { "📄$($_.FullName)" $count++ } Write-Progress -completed " " [int]$elapsed = $stopWatch.Elapsed.TotalSeconds "✔️ Found $count empty files within $path in $elapsed sec" exit 0 # success } catch { "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])" exit 1 }
//-- DATABASE 연결 //-- 필요한 정보가 뭐뭐? //-- 주소(데이터베이스가 어디있냐?) -- Host //-- 계정 : 아이디/패스워드 //-- 사용할 데이터베이스 명. //-- JDBC //-- SQL문을 날리기위한 작업에 5가지. //-- 1. 드라이버 로딩 ( mysql driver, oracle driver, mssql driver ....) //-- 2. 연결 (DriverManager.getConnection() ) //-- + 주소(Host), 아이디, 패스워드, 사용 Database명) //-- 3. DB - 프로그램상 질의문(SQL)을 전달하고, 결과를 받을 수 있는 고속도로 만들기 // + Statement 객체 생성 // + conn.createStatement(); //-- 4. SQL문 작성 // String sql = "select * from students"; //-- 5. 쿼리전송 후 처리 // + stmt.execute().. executeQuery() .... 등등 // + Select 의 계열의 경우 ResultSet으로 처리 // ResultSet rs = stmt.executeQuery(sql); // + Select 외 다른 쿼리들 ( Insert, delete, Update )는 ResultSet이 없음 // stmt.execute(sql) //-- !) 자원반납을 해줘야한다. (프로그램이 끝날때는) //-- a) DB연결 닫기 conn.close(); //-- b) Statement 닫기 stmt.close(); //-- Query (SQL)문 날리고 //-- 결과물 확인 //import java.sql.Connection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MariaDBExample { public static void main(String[] args) throws Exception { // 데이터베이스 커넥션 객체 Connection conn = null; /* try { Class.forName("com.mysql.cj.jdbc.Driver"); // ClassNotFoundException 발생가능 conn = DriverManager.getConnection( "jdbc:mysql://localhost:7306/javadb", "root", "root" ); // SQLException 발생가능 } catch(ClassNotFoundException ex) { System.out.println("jdbc jar가 없네요."); } catch(SQLException ex) { System.out.println(ex.getMessage()); } catch(Exception ex){ System.out.println("알 수 없는 예외 발생"); } */ Class.forName("com.mysql.cj.jdbc.Driver"); // ClassNotFoundException 발생가능 conn = DriverManager.getConnection( "jdbc:mysql://localhost:7306/javadb", "root", "root" ); if(conn == null) { System.out.println("연결이 안됐습니다."); } else { System.out.println("연결이 됐습니다."); } //-- 자바에서 DB에 있는 students 테이블의 데이터를 전부 끌어오기 String sql = "Select * from students"; //-- 자바에서 DB에 쿼리를 날릴때(질의할때) //-- 1. Statement //-- 2. Select(Read)의 경우는 이 결과값을 ResultSet(RecordSet) Statement stmt = conn.createStatement(); // 연결된 RDBMS에 SQL 구문을 전달하는 객체를 Statement ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getString("student_name")); } //-- 데이터 넣기 sql = "insert into students (student_id, student_name)" + " values (3, '하악이');"; /* boolean isAffected = stmt.execute(sql); if(!isAffected) System.out.println("입력성공"); else System.out.println("입력실패"); */ //-- 데이터 삭제 sql = "delete from students where student_name = '하악이';"; stmt.execute(sql); //-- 데이터 변경 sql = "update students set student_name = '뵨태' where student_id=1"; stmt.execute(sql); //--자원반납 stmt.close(); conn.close(); } }
import {useEffect, useRef, useState} from "react"; import { type TodoId, type Todo as TodoType } from "../types"; interface Props extends TodoType{ onToggleCompletedTodo: ({id}: Pick<TodoType, 'id'>) => void onRemoveTodo: ({id}:TodoId) => void setTitle: (params: { id: string, taskMessage: string }) => void isEditing: string setIsEditing: (completed: string) => void } export const Todo: React.FC<Props> = ({ id, taskMessage, completed, creationDateTime, finishDate, onRemoveTodo, onToggleCompletedTodo, setTitle, isEditing, setIsEditing }) => { const c = creationDateTime const f = finishDate async function handleChangeCheckBox() { if (!completed) { onToggleCompletedTodo({ id }); } } const [isShown, setIsShown] = useState(false); const [editedTitle, setEditedTitle] = useState(taskMessage) const inputEditTitle = useRef<HTMLInputElement>(null) const handleKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => { if(!completed){ if (e.key === 'Enter') { setEditedTitle(editedTitle.trim()) if (editedTitle !== taskMessage) { setTitle({ id, taskMessage: editedTitle }) } setIsEditing('') } if (e.key === 'Escape') { setEditedTitle(taskMessage) setIsEditing('') } } } useEffect(() => { inputEditTitle.current?.focus() }, [isEditing]) return ( <> <div className="view" onMouseEnter={() => setIsShown(true)} onMouseLeave={() => setIsShown(false)} > <input className="toggle" checked={completed} type="checkbox" onChange={() => { const confirmacion = window.confirm('¿Estás seguro de que quieres realizar esta acción?'); if (confirmacion) { handleChangeCheckBox() } }} /> <label>{taskMessage}</label> <button className="destroy" onClick={() => { const confirmacion = window.confirm('¿Estás seguro de que quieres realizar esta acción?'); if (confirmacion) { // Acción confirmada onRemoveTodo({ id }); } }} /> {isShown && ( <span className="span" > {c} <br /> {f} </span> )} </div> <input className='edit' value={editedTitle} onChange={(e) => { setEditedTitle(e.target.value) }} onKeyDown={handleKeyDown} onBlur={() => { setIsEditing('') }} ref={inputEditTitle} /> </> ) }
<!DOCTYPE html> <html> <head> <title>Sociorama</title> <link rel='stylesheet' href='/stylesheets/loginstyle.css' /> </head> <body> <div class="content-wrapper"> <p class="logo">Sociorama</p> <div class="input-box"> <div class="login-box"> <form class="login" action="/login" method="POST"> <input class="login-username-input" name="username" placeholder="Username" type="text"/> <input class="login-password-input" name="password" placeholder="Password" type="password"/> <% if (errorMessage) { %> <p class="login-error"><%= errorMessage %></p> <% } %> <button class="login-button">Log In</button> </form> <button class="signup-box-button">Sign Up</button> <button class="guest-button">Log In as Guest</button> </div> <div class="signup-box hidden"> <div class="signup-header"> <p>Sign Up</p> <svg class="signup-cancel" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14"> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/> </svg> </div> <form class="signup" action="/signup" method="POST"> <input class="signup-firstname-input" name="firstName" placeholder="First Name" type="text"/> <input class="signup-lastname-input" name="lastName" placeholder="Last Name" type="text"/> <input class="signup-username-input" name="username" placeholder="Username" type="text"/> <input class="signup-password-input" name="password" placeholder="Password" type="password"/> <p class="signup-error"></p> <button class="signup-button">Sign Up</button> </form> </div> </div> </div> <script> const signupButton = document.querySelector(".signup-button"); signupButton.addEventListener("click", async (event) => { event.preventDefault(); const firstName = document.querySelector(".signup-firstname-input").value; const lastName = document.querySelector(".signup-lastname-input").value; const username = document.querySelector(".signup-username-input").value; const password = document.querySelector(".signup-password-input").value; if (!firstName || !lastName || !username || !password) { document.querySelector(".signup-error").textContent = "Please fill in all fields"; return; } const data = { username: username } const response = await fetch("check-username", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); const responseData = await response.json(); if (responseData.signupErrorMessage === "Username is taken") { document.querySelector(".signup-error").textContent = responseData.signupErrorMessage; return; } document.querySelector(".signup").submit(); }); const signupBoxButton = document.querySelector(".signup-box-button"); signupBoxButton.addEventListener("click", () => { document.querySelector(".login-box").classList.toggle("hidden"); document.querySelector(".signup-box").classList.toggle("hidden"); document.querySelector(".login-error").textContent = ""; }); const signupCancel = document.querySelector(".signup-cancel"); signupCancel.addEventListener("click", () => { document.querySelector(".login-box").classList.toggle("hidden"); document.querySelector(".signup-box").classList.toggle("hidden"); document.querySelector(".signup-error").textContent = ""; }); const guestButton = document.querySelector(".guest-button"); guestButton.addEventListener("click", async () => { const form = document.createElement('form'); form.setAttribute('action', '/guest-login'); form.setAttribute('method', 'POST'); const usernameInput = document.createElement('input'); usernameInput.setAttribute('name', 'username'); usernameInput.value = "guest"; const passwordInput = document.createElement('input'); passwordInput.setAttribute('name', 'password'); passwordInput.value = "guest"; form.appendChild(usernameInput); form.appendChild(passwordInput); document.body.appendChild(form); form.submit(); }); </script> </body> </html>
.pl 11i .po .5i .ll 7i .\" For eR compatibility .de se .if "\\$1"ls" .ls \\$2 .if "\\$1"Ip" .nr Po \\$2n .if "\\$1"ip" .nr ii \\$2n-\\n(Po .. .rn h1 H1 .de h1 .H1 "\\$1" "\\$2" .pp .. .tc yes .se ft 3 .se ls 1 .hx .uh "TEXT PROCESSING" .sp 15 .ce 6 \fBTHE RAND EDITOR, E ** Draft ** APRIL 1984 .sp 15 .ce 3 COMPUTER SERVICES DEPARTMENT THE RAND CORPORATION\fR .bp 1 .se ls 1 .mh "INTRODUCTION" This reference manual presents many of the functions and commands that are available in "E". The level of description used here assumes some prior experience with an editor. .sp .h1 "KEYSTROKE SYNTAX" EXAMPLES in this document use different typefaces and symbols to denote the keystrokes you must make on your terminal keyboard: .se Ip 5 .se ip 20 .ip <BRACKETS> Angled brackets indicate that you must press a key with a particular label on it. Thus if you are told to press .in 30 <CMD> .in 20 you must press the key with the label CMD on it. NOTE: all the terminal keyboards at Rand have had special keytops made for this editor. Users of unmodified terminals should consult their local experts for directions on what keys perform which functions inside of "E", or use the "E" standard keyboard control characters. .ip |KEY+KEY| Vertical lines indicate that you must hold down the first key and then press the second one. Thus if you are told to press .in 30 |CTRL+B| .in 20 you must hold down the CTRL key and then press the B key. .mh "THE RAND EDITOR E" .h1 "ABORTING A COMMAND" A command can be aborted or stopped before it is completed by pressing <INT>. This method is effective for aborting commands that take some time to execute such as fill, justify, and search. Commands that happen instantaneously, such as open and close, usually cannot be aborted. A command that has been typed but not executed (i.e., <RETURN> has not yet been pressed), can be aborted by backspacing over the command and erasing it. The command mode can then be turned off by pressing <RETURN>. .sp .h1 "ABORTING A SESSION" To abort an entire editing session press <CMD> \fBexit abort\fR <RETURN> (where \fBexit abort\fR can be abbreviated \fBex a\fR). Exiting a file with the abort option looses all work done during the editing session. If a user aborts a session and then types \fBe\fR, the Editor will prompt the user with four options, one of which is a visible replay (option 2). The user can initiate the replay, watch it occur, and interrupt it before the end by pressing <INT>, thus saving some of the work. (See also \fIEXIT\fR and \fIRECOVERY\fR.) .sp .h1 "ALTERNATE FILE" An alternate file can be created while in the Editor, by pressing: <CMD> \fBe \fR\fIfilename\fR <RETURN>. This causes the current file to become the alternate file, and \fIfilename\fR to become the current file. To alternate between these two files, a user presses <ALT>. A user can also alternate between these two files by pressing <CMD> \fBe\fR <RETURN>. A number of files can be used in the alternate mode, although you must press <CMD> \fBe \fR and type in the filename you wish to change to. Work done in alternate files will all be saved upon exiting from the session. .sp .h1 "AREA" An area is any part of a file; it can be as small as one character and as large as the entire file. The area may be a default area such as the default area for the fill command (1 paragraph), or the area may be explicitly defined in the instruction as for example, \fBfill \fR\fI2l\fR, which will fill 2 lines, or \fBfill \fR\fI5p\fR which will fill 5 paragraphs. In defining an area, the letter "p" defines paragraphs and the letter "l" (ell) defines lines. An area can also be defined by cursor movements or arrow keys. An area defined by cursor movements must be marked. The marked area can be a few words, a single line, several paragraphs, or a rectangle. An area is marked by pressing <MARK> and moving the cursor. Cursor movement is accomplished by <\*G\(->\fR>, <\*G\(<-\fR>, <\*G\(ua\fR>, <\*G\(da\fR>, <RETURN>, <+PAGE>, <-PAGE>, <+LINE>, <-LINE>, and certain sequences involving <+SCH> and <-SCH>. A marked area can be used as the area for <OPEN>, <CLOSE>, <PICK> and <ERASE>. If that marked area is a series of lines or paragraphs, the marked area can also be used as the area for fill, justify, center, and replace. .sp .h1 "<ARROW KEYS>" The arrow keys are represented in this publication as <\*G\(->\fR>, <\*G\(<-\fR>, <\*G\(ua\fR>, and <\*G\(da\fR>. These keys move the cursor without changing the text the cursor moves past (as opposed to <SPACE BAR> and <BSP>). When the cursor is at the right side of the window, and <\*G\(->\fR> is pressed, the window is moved so that the cursor remains visible. This also occurs when the cursor is at the top, bottom, or left edge of the window. At the left edge though, the cursor (and the window) cannot go to the left of column 1. At the top, the cursor cannot go higher than line 1. When <CMD> is pressed and then an arrow key is pressed, the cursor moves to the edge of the window in the direction desired. For example, the keystroke sequence <CMD> <\*G\(->\fR> first moves the cursor to the end of the text on the line, and if pressed a second time, moves the cursor to the right edge of the window. The keystroke sequence <CMD> <\*G\(<-\fR> moves the cursor to the left edge of the window. The keystroke sequence <CMD> <\*G\(ua\fR> will take the cursor to the top of the window in the same column. The keystroke sequence <CMD> <\*G\(da\fR> stops at the bottom of the window, in the same column, if the file extends to the bottom of the window. If the file does not extend to the bottom of the window, <CMD> <\*G\(da\fR>, first stops at the end of the file, and if pressed again, goes to the bottom edge of the window. Arrow keys generally will work only if the version of the editor that you are using has been compiled to support your terminal type. .sp .h1 "BACKSPACE" To backspace the cursor and erase a character, press <BSP>. To backspace the cursor without erasing, press <\*G\(<-\fR>. Backspace characters can be added to a text line by pressing <CNTL CHAR> |SHIFT+H|. The first keystroke combination generates a small, bright block. The second keystroke combination signals the Editor to put a backspace character in the text. This backspace character can be part of an underlining process. (See also \fI<BSP>,\fR and \fIUNDERLINING\fR.) .sp .h1 "BACKUP FILE" If a user edits a file and exits normally from the Editor, a copy of the file as it existed before the editing session is kept by the Editor. The Editor does this by copying the existing file and renaming the copy with the same name as the original but with a comma in front of it. For example, a file named \fImemo\fR, is backed up as a file named \fI,memo\fR. These files are called comma files. If the user exits with the abort option, \fBexit abort\fR, or if the system crashes, no backup file is created (and any previous backup file is left untouched). The comma file is made in the same user directory that the original file is in. All comma files are deleted automatically late each evening. A comma file is created to protect the user from inadvertent mistakes. For example, if a user begins to edit the same file again later in the day and discovers that the previous editing session contained a serious error, the user would have several choices. First, the user could exit with the abort option and copy the comma file into the current file. For example, \fB% cp \fR\fI,memo memo\fR. Or the user, without exiting from the Editor, could call up the backup file as the alternate file and restore that section of the file that contained the editing error. (See \fIMOVING TEXT BETWEEN FILES\fR.) .sp .h1 "BACKWARD SEARCH" To search backward in the file for a word or series of words, press <CMD> \fIword\fR <-SCH>. To find additional occurrences, continue pressing <-SCH> until the message "Search key not found" appears on the screen. .sp .h1 "BOX" The box command draws a box around a specified area, just inside the marked or specified area. The "|" and "-" characters are used for the vertical and horizontal markings and corners are displayed as "+". First mark off the area using <MARK> <\*G\(<-\fR> <\*G\(da\fR>. Then press <CMD> \fBbox\fR <RETURN>. Horizontal and vertical lines can be drawn using the box command by marking one direction only. .sp .h1 "<BSP>" This is the backspace key. This key has different functions depending on whether the Editor is in Edit Mode or Insert Mode and whether the <CMD> key is pressed. The functions are: .(b Edit Mode: <BSP> Moves the cursor to the left one column and blanks out any character there. <CMD> <BSP> Blanks out all characters between the cursor and the left margin. Leaves the cursor where it is. (Deleted characters placed in the erase buffer.) Insert Mode: <BSP> Moves the cursor to the left one column and deletes any character there. The text to the right of the cursor is moved over one character to the left (following the cursor). <CMD> <BSP> Deletes all of the characters between the cursor and the left margin. Moves the cursor and the remaining text to the right margin. (Deleted characters are placed in the close buffer.) .)b (See also \fIBACKSPACE\fR.) .sp .h1 "CENTER" The center command moves the text contained on a line to the center of the line so that the number of blanks on either side of the text is the same. The line length by which the center is determined is the "width" specified in the last center, fill, or justify command, or the default width of 75. The format of the command is, <CMD> \fBcenter\fR \fIn\fR <RETURN>, where \fIn\fR is the optional number of lines to center. If \fIn\fR is omitted, one line is centered, the line where the cursor is. .sp .h1 "CHANGES FILES" The change file is maintained for the benefit of the user. It contains all of the text that has been centered, closed, picked, filled, and justified. A user can access the text in this file by referencing a file by pressing <CMD> \fBe #p\fR (all information that has been picked), or \fB e #o \fR(all information that has been closed, deleted, erased, filled, or justified). This brings the text from the change file into the editing window as an alternate file, and text can then be copied using the pick key. The user can return to the original file by pressing <ALT>, and restore the text that was copied by pressing <CMD> <PICK>. .sp .h1 "CHANGING FILES" To alternate between the current file and the alternate file, press <ALT>. (See also \fIALTERNATE FILE\fR.) .sp .h1 "CHANGING WINDOWS" If there are two windows, then pressing <CHG WIN> moves the Editor between windows. If there are more than two windows, then pressing <CHG WIN> moves the Editor from window to window in the order that the windows were created. To move to a specific window press <CMD> \fIn\fR <CHG WIN>, where \fIn\fR is the window number. (See also \fIWINDOW\fR.) .sp .h1 "<CLOSE>" The close key removes a line or lines from the file and places those lines in the close buffer. The most recently closed line or lines can be restored to the file by pressing <CMD> <CLOSE>. Pressing the close key by itself results in the closing of one line. More than one line can be closed by pressing <CMD> \fIn\fR <CLOSE>, where n is the number of lines to remove. The mark function can be used with the close function to close a few characters, a few words, a few lines, a few paragraphs, or a rectangle. To mark and close, press <MARK> \fIcursor movements\fR <CLOSE>. Material copied from the close buffer is placed in the change file. Note that pressing <CMD> <BSP> while in Insert Mode replaces the contents of the close buffer with newly deleted text. (See also \fICHANGE FILE\fR and \fICLOSE\fR.) .sp .h1 "CLOSE" The close command may be used instead of the close key to remove space. To close out an area, the user presses <CMD> \fBclose \fR\fIn\fR <RETURN> (\fBclose\fR may be abbreviated \fBclo\fR), where \fIn\fR is an optionally entered number of lines. The default area is one line. Text closed with either the close command or the close key may be placed anywhere in the file by moving the cursor to that place and pressing <CMD> <CLOSE> or <CMD> \fB-close\fR <RETURN>. Note that pressing <CMD> <BSP> while in Insert Mode replaces the contents of the close buffer with the newly deleted text. (See also \fI<CLOSE>\fR.) .sp .h1 "CLOSE BUFFER" The close buffer is a place in the Editor where the last closed line(s) is saved. Text is also placed in the close buffer when <CMD> <BSP> is pressed while in Insert Mode. Material remains in the close buffer until the close key is used to remove line(s) or until the file is exited. (See also \fICLOSE\fR and \fI<CLOSE>\fR.) .sp .h1 "<CMD>" This key puts the Editor in the command mode so that commands may be typed to the Editor followed by <RETURN>. This key is also used as part of many keystroke sequences that perform special editor functions. .sp .h1 "COMBINING FILES" Files can be combined using the Unix cat command. Files can also be combined using the Editor to pick text from an alternate file. (See \fIMOVING TEXT BETWEEN FILES\fR.) .sp .h1 "COMBINING LINES" Two adjacent lines can be combined using the \fBjoin\fR command. (See \fIJOIN\fR.) .sp .h1 "COMMA FILES" See \fIBACKUP FILE\fR. .sp .h1 "COMMAND MODE" The command mode is initiated by pressing <CMD>. On some terminals this key is labeled <ARG>, <BRK>, or <BRK/CMD>. The prompt "CMD:" appears below the window and a command can be entered. The command line may be edited by using <INSERT>, <BSP>, <\*G\(->\fR>, and <\*G\(<-\fR>. The last command executed can be recovered to the command line by pressing <CMD> <CMD> <ALT>. This can then be edited and executed again. To negate a command, the user can backspace over the command, thus erasing it, and then cancel the command mode by pressing <RETURN>. To cancel a command, either a partially typed command or an executing command, the user presses <INT>. .sp .h1 "COPYING FILES" A file can be copied outside the Editor by use of the Unix copy command, \fBcp\fR. While in the Editor, information can be copied from one file to another by editing the first file, bringing up the second file as an alternate file, by pressing <CMD> \fBe \fR\fInewfilename\fR <RETURN> and copying information using the pick key, then alternating files by pressing <ALT> and placing that information into the first file by pressing <CMD> <PICK>. A copy of the current file can be saved with a different name (as a new file) by pressing <CMD> \fBsave \fR\fInewfilename\fR <RETURN>. (See also \fIMOVING TEXT BETWEEN FILES\fR and \fISAVE\fR ) .sp .h1 "COPYING TEXT" Text can be copied within a file by using the pick key. Text can also be copied from one file to another. (See \fICOPYING FILES, MOVING TEXT BETWEEN FILES\fR and \fI<PICK>\fR.) .sp .h1 "CRASHES, RECOVERY FROM" If E crashes while editing, then the user, while in the same directory, types (in response to the Unix prompt of "%") \fBe\fR <RETURN>. The Editor will prompt the user with four options. (See \fIRECOVERY\fR.) .sp .h1 "CREATING FILES" If a file does not exist, it can be created by typing \fBe\fR \fIfilename\fR <RETURN> in response to the Unix prompt of "%". Then in response to the E prompt of "Do you want to create \fIfilename\fR?", type \fBy\fR for yes). (Filenames of no more than 12 letters or numbers are recommended.) (See \fIFILENAME\fR.) A copy of the current file can be saved with a different name (as a new file) by pressing <CMD> \fBsave\fR \fInewfilename\fR <RETURN>. (See \fISAVE\fR.) .sp .h1 "CREATING WINDOWS" To create a window, the cursor must be either on the left or the top edge of the window but not in the top left-hand corner. A new window can be created with a different file in it by pressing <CMD> \fBw\fR\fI filename\fR <RETURN>. A new window can be created with the current file in it by pressing <CMD> \fBwindow\fR <RETURN> (where \fBwindow\fR can be abbreviated \fBw\fR). (See \fIDELETING WINDOWS, WINDOWS\fR.) .sp .h1 "<CTRL>" This key is the "control" key. It shifts the keyboard into a third case, in which many of the keys generate special codes. Pressing this key by itself does not generate a code; another key must be pressed with it. For example, |CTRL+A| requires that the <CTRL> key be pressed and held, then press the <A> key. (This command will move the window to the left.) Many of these control functions have been replaced on the newer terminals with function keys. .sp .h1 "CURRENT WINDOW" The current window contains the cursor and is the window in which editing can be done. The current window is outlined in bolder colons/semicolons; the alternate windows are outlined in dots. (See also \fICHANGING WINDOWS\fR and \fIWINDOW\fR.) .sp .h1 "CURSOR" The cursor is the character similar to an underline or block character that the Editor uses to mark locations on the screen. The cursor marks the position where the next character typed will be placed (and where it will print). To emphasize the cursor position, the Editor sometimes prints four bright blocks at the four edges of the screen. These four bright blocks "target" the cursor. .sp .h1 "CURSOR MOVEMENT <\*G\(->\fR>, <\*G\(<-\fR>, <\*G\(ua\fR>, <\*G\(da\fR>" The notation \fIcursor movement\fR is used to indicate any movement of the cursor. This movement can be performed by pressing \%<-PAGE>, <+PAGE>, <-LINE>, <+LINE>, <\*G\(->\fR>, <\*G\(<-\fR>, <\*G\(ua\fR>, <\*G\(da\fR>, <RETURN>, <BSP>, and <SPACE BAR>, and by some command sequences which include the <+SCH> and <-SCH> keys. Most frequently \fIcursor movement\fR is used in marking a series of lines or paragraphs or a rectangular area. .sp .h1 "<DEL CHAR>" This key is located next to <INSERT> and is sometimes marked <DEL>. This key deletes the character the cursor is on and moves the characters to the right of the cursor one space to the left. Characters deleted with the del char key cannot be recovered. To delete the character at the cursor and all of the characters to the right on the same line, press <CMD> <DEL CHAR>. Characters deleted in this manner enter the erase buffer. .sp .h1 "DELETE" This command deletes the current file, that is, the file being edited. This is useful when creating and editing multiple windows and files. The current file is deleted (not only within the Editor but within the file system) by pressing <CMD> \fBdelete\fR <RETURN>. Be CAREFUL to make sure you want to delete the file with this command; there is no recovery. This command takes effect upon normal exit from the Editor. To negate this command (and the entire editing session), the user must exit with the abort option \fBexit abort\fR. (See \fIEXIT\fR.) .sp .h1 "DELETING TEXT" Single characters can be deleted by using the <DEL CHAR> key. This key deletes the character at the cursor. The character at the cursor and all the characters to the right can be deleted by pressing .br <CMD> <DEL CHAR>. Characters can be erased by pressing the space bar or <BSP>. (The backspace key has several deleting functions; see \fI<BSP>\fR.) Characters deleted using <CMD> <DEL CHAR> enter the erase buffer. A line of text can be deleted by pressing <CLOSE>. Several lines of text can be deleted by pressing <CMD> \fIn\fR <CLOSE> or .br <CMD> \fBclose \fR\fIn\fR <RETURN>, where \fIn\fR is the number of lines to delete. The most recent line or set of lines deleted in this fashion may be returned to the file (in the same place or in other places) by pressing <CMD> <CLOSE> or <CMD> \fB-close\fR <RETURN>. A rectangular area can be deleted by first marking the area and then pressing <CLOSE>. An area is marked by moving the cursor to one corner of the area, pressing <MARK>, and then moving the cursor to the opposite corner of the area. At this point the <CLOSE> key can be pressed. (See <MARK>.) .sp .h1 "DELETING WINDOWS" The last window created can be removed from the screen by pressing <CMD> \fB-window\fR <RETURN> (where \fB-window\fR can be abbreviated \fB-w\fR). (See \fICREATING WINDOWS\fR and \fIWINDOWS\fR.) .sp .h1 "<DOWN ARROW>" See \fI<ARROW KEYS>\fR. .sp .h1 "\&.ec1" This is the filename of the change file if the user owns the directory. In this file are all changes made during the current editing session. This file exists only during an editing session and is deleted automatically when you exit from the file. If you "crash" or "exit abort" from the file, it is saved for recovery purposes. .sp .h1 "\&.ek1" This is the filename of the keystroke file if the user owns the directory. In this file are all changes made during the current editing session. This file exists only during an editing session and is deleted automatically when you exit from the file. If you "crash" or "exit abort" from the file, it is saved for recovery purposes. .sp .h1 "\&.ek1b" This is the filename of the backup keystroke file used during recovery if the user owns the directory. .sp .h1 "\&.es1" This is the filename of the state file if the user owns the directory. This file is created every time you exit from the editor and keeps track of the last file edited, and your cursor location upon exiting. This allows you to type \fBe\fR and be able to edit the last file you worked on without specifying a filename. .sp .h1 "E" The name of the Editor is E. To work in a file, a user types \fBe\fR or \fBe\fR \fIfilename\fR. .sp .h1 "EDIT MODE" Edit mode is the mode of the Editor in which new text that is typed overlays any existing text. Edit mode is the default mode of the Editor, the mode the Editor is in after the user types \fBe\fR \fIfilename\fR. (See also \fICOMMAND MODE\fR and \fIINSERT\fR.) .sp .h1 "EFFICIENCY" The Editor works most efficiently if it is exited every half hour. This practice is also recommended as a precaution against system failures in which all editing during a session can be destroyed. .sp .h1 "ERASE" A line or area can be erased (blanked out) by pressing <CMD> \fBerase\fR \fIarea\fR <RETURN> (where \fBerase\fR can be abbreviated \fBer\fR). The default area is one line. The erased text from the last erase command is held in the erase buffer from where it can be retrieved using the \fB-erase\fR command. Note that <CMD> <DEL CHAR> while in edit mode, replace the contents of the erase buffer with newly deleted text. .sp .h1 "<ERASE>" Ambassador terminals have an erase key which can be used instead of the erase command. Pressing <ERASE> will erase one line. More than one line may be erased by pressing <CMD> \fIn\fR <ERASE>, where n is the number of lines to be erased or by using mark and <ERASE>. Erased text may be retrieved from the erase buffer by <CMD> <ERASE>. Note that <CMD> <DEL CHAR> while in edit mode, replace the contents of the erase buffer with newly deleted text. .sp .h1 "-ERASE" The last text erased using the \fBerase\fR command can be inserted into the file by pressing <CMD> \fB-erase\fR <RETURN> (where \fB-erase\fR may be abbreviated \fB-er\fR). This insertion moves existing text to the right and, consequently, entering the command \fBerase\fR followed by the command \fB-erase\fR may not restore the text to its original position. Note that <CMD> <DEL CHAR> while in edit mode, replaces the contents of the erase buffer with newly deleted text. .sp .h1 "ERASING EXTRANEOUS CHARACTERS" Occasionally extraneous characters appear in the editing window, characters that are not part of the edited file (for example, a message from the system operator). Sometimes these characters are called "noise" or "garbage" characters. To remove these characters, press <CMD> \fBredraw\fR <RETURN> (where \fBredraw\fR can be abbreviated \fBred\fR). This command redraws the window and clears it of extraneous characters. .sp .h1 "ERASING TEXT" Normally text is erased by spacing over it with the space bar or backspacing over it with <BSP>. The backspace key has several options. Text can also be erased using the erase command or <ERASE>. Text to the right of the cursor can be erased using <CMD> <DEL CHAR>. (See also \fI<BSP>, <DEL CHAR>, DELETING TEXT\fR, \fIERASE\fR and <ERASE>.) .sp .h1 "EXECUTE A FUNCTION" Some UNIX commands can be executed while in the editor by pressing .(b <CMD> \fBrun\fR \fIarea command\fR <RETURN> .)b For example, to run the Unix command "ls" and have the output included in the file being edited, press <CMD> \fBrun\fR \fIls\fR <RETURN>. Note that the output from a command can vary depending on when it is run, and consequently a replay of the editing session that includes a run command can produce disastrous results. For knowledgeable Unix users only: \fBarea\fR is passed to the standard input of the command and is replaced by the output of the command. (See also \fIAREA\fR) .sp .h1 "EXIT" A user can exit from the Editor by pressing <CMD> \fBexit\fR <RETURN> (where \fBexit\fR may be abbreviated \fBex\fR or \fBb\fR). A user can exit from the Editor and abort the editing session by pressing <CMD> \fBexit abort\fR <RETURN>. A user can then replay that session by returning to the same directory and typing \fBe\fR. The Editor will prompt the user with four options, one of which is a visible replay (option 2). The user can initiate the replay, watch it occur, and then interrupt it before it ends by pressing <INT> thus only saving that work which you saw replayed. Note that a replay of a short session is difficult to interrupt unless the user has good reflexes. You may also exit from the editor with the following options: \fBexit nosave\fR which exits you from the file without saving it; \fBexit quit\fR which is like exit abort, but deletes the keystroke file; \fBexit dump\fR which is similar to exit abort. .sp .h1 "FILENAME" A filename can be up to 14 characters long, but filenames of 12 characters or less are recommended for several practical reasons which will not be detailed here. Filenames can contain any letter or number. If a blank is placed in a filename, the characters up to the blank are used as the filename; the characters after the blank may be treated as another filename or treated as an argument, or ignored, depending on how the filename is being used. The Unix operating system attaches special meaning to certain characters in the filenames. A filename beginning with a period (".") should be avoided, as well as a filename beginning with a comma (",") and files named core and a.out. It is highly recommended that filenames contain only numbers and lower case letters. Filenames under the 4.2BSD version of Unix can be much longer than 14 characters. .sp .h1 "FILES" A file is a collection of text saved on a disk pack with an individual identifying name. Files can be created using the Editor, \fBe\fR\fI filename\fR, or by various Unix commands such as \fBcp\fR \fIfilea fileb\fR. (See also \fIALTERNATE FILE, BACKUP FILE, CREATING FILES\fR, and \fIFILENAME\fR.) .sp .h1 "FILL" The fill command moves words so that each line is filled with words up to, but not beyond, the right margin. (The right margin is set by the "width" entered in the last fill, center, or justify command, or is the default width of 75.) A paragraph is filled by moving the cursor to the first line of a paragraph and pressing <CMD> \fBfill\fR <RETURN> (where \fBfill\fR can be abbreviated \fBfi\fR). The format of the fill command if you wish to keep the default line length of 72 is: .(b <CMD> \fBfill\fR area\fR <RETURN> .)b The format of the file command if you wish to change the line width is: .(b <CMD> \fBfill width\fR= \fInn area\fR <RETURN> .)b The area is defined by a number followed by a \fBp\fR (standing for number of paragraphs, i.e., \fB3p\fR) or \fBl\fR (standing for number of lines, i.e., \fB20l\fR). If the \fBwidth=\fR\fIn\fR option (replace \fIn\fR with the number of characters wide) is specified, that width stays in effect until another width is specified. (See also \fIJUSTIFY\fR and \fIWIDTH\fR.) .sp .h1 "FUNCTION KEYS" A function key is a key that performs a function when pressed, for example, <CLOSE>. Many keys have their functions marked on the top of the key. Those keys with functions marked on the front face require an additional key be pressed, usually the <CTRL> key. Some functions require that the <CMD> key be pressed first and then the function key. For the use of any particular function key, see the name of that key. .sp .h1 "GOTO" The cursor can be moved to a specific line number in the file by pressing <CMD> \fBgoto \fR\fIn\fR <RETURN> (\fBgoto\fR may be abbreviated \fBgo\fR or \fBg\fR) and where \fIn\fR is the line number. The \fBgoto\fR command has a default line number of 1, which allows the user to go to the beginning of the file. The goto command also allows the use of \fBb\fR to go to the beginning of the file, and \fBe\fR to go to the end of the file. Consequently, \fBg\fR, \fBg b\fR and \fBg 1\fR all go to line one. And \fBg e\fR goes to the last line in the file. There is another mechanism for going to the front and the end of the file. Pressing <CMD> <-PAGE> moves the cursor to line 1. Pressing <CMD> <+PAGE> moves the cursor to the last line of the file. .sp .h1 "<HOME>" Pressing <HOME> moves the cursor to the upper left corner of the current window. Pressing <CMD> <HOME> moves the cursor to the lower left corner. .sp .h1 "<INSERT>" This key is used to put the Editor into and out of the Insert Mode. When the Editor is in Insert Mode, the word "INSERT" is printed below the window as a reminder. A number of functions behave differently in Insert Mode. Most importantly, text typed while in Insert Mode is inserted into the line moving existing text to the right rather than replacing existing text. Insert Mode is turned off by pressing <INSERT> again. (See also \fI,<BSP>, COMMAND MODE,>\fR and \fIEDIT MODE.) .sp .h1 "INTERACTIVE REPLACE" See \fIREPLACE\fR. .sp .h1 "JOIN" The join command joins two lines together. The line the cursor is located on is lengthened by appending the line below it. If the next line(s) is blank, it will go to the next line of text and add it. The joined line is added after the end of text on the line where the cursor is. To use the command, the user types <CMD> \fBjoin\fR <RETURN> (where \fBjoin\fR may be abbreviated \fBjo\fR). (See also \fISPLIT\fR.) You may also mark two points you want joined with <MARK>. All text deleted by the operation is saved in the close buffer. .sp .h1 "JUSTIFY" The justify command moves words from line to line so that the last word in each line ends exactly at the right margin. (The right margin is the "width" specified in the last fill, justify, or center command, or the default width of 75.) The justify command adds blanks between the words to spread the words out evenly on a line. A paragraph is justified by moving the cursor to the first line of the paragraph and pressing <CMD> \fBjustify\fR <RETURN> (where \fBjustify\fR may be abbreviated \fBju\fR). The full format of the justify command if you wish to keep the default line width of 75 is: .(b <CMD> \fBjustify\fR \fIn area\fR <RETURN> .)b If you wish to change the line width, the command is: .(b <CMD> \fBjustify\fR \fBwidth=\fR\fIn area\fR <RETURN> .)b If the \fBwidth=\fR\fIn\fR option is specified, that width stays in effect until another width is specified in another fill, justify, or center command. (See also \fIAREA\fR, \fIFILL\fR, and \fIWIDTH\fR.) To restore justified text to its original unjustified state after issuing a justify command, type <CMD> \fBinsert adjust\fR <RETURN. You can only recover text from the last time the justify command was used. .sp .h1 "KEYSTROKE FILE" The keystroke file is named .ek1 for a user who owns the directory and is the only user working in it. The keystroke file is named .ek1.\fIusername\fR for a user who is working in someone else's directory. The keystroke file is used to update the file being edited at the end of the session when the user exits normally. After exiting normally, the keystroke file is deleted. If the user exits with the abort option (\fBexit abort\fR) or if the Editor crashes, the keystroke file is retained and the file being edited is left unchanged. An aborted session (\fBexit abort\fR) can be replayed if the user returns to the same directory and types \fBe\fR. The Editor then presents the user with four options, one of which is a visible replay. The user can initiate the replay, watch it occur, and interrupt it before it ends by pressing <INT>. After an Editor crash, the user can return to the same directory and type \fBe\fR, and the Editor will prompt the user with four recovery options. (See also \fIEXIT, RECOVERY, REPLAY,\fR and \fISTATE FILE\fR.) .sp .h1 "<LEFT>" This key is pressed to move the window 16 characters to the left. The window cannot move to the left of column 1 of the text. Pressing <CMD> <LEFT> moves the window to the left so that it displays columns 1-78 of the file. (See also \fI<ARROW KEYS>,\fR and \fI<RIGHT>\fR.) .sp .h1 "<LEFT ARROW>" See \fI<ARROW KEYS>\fR. .sp .h1 "<+LINE>" This key moves the top fourth of what was on the window out of sight and redraws the screen. The cursor stays at the same line number, or if that line number is moved off the screen, the cursor stays at the top of the window. .sp .h1 "<-LINE>" This key moves the bottom fourth of what was on the window out of sight, brings into sight an equal number of lines at the top of the window, and redraws the screen. The cursor stays at the same line number, or if that line number is moved off the screen, the cursor stays at the bottom of the window. Pressing <-LINE> has no effect if the top of the window is at line number 1. .sp .h1 "LINE MANIPULATION" For breaking lines apart, see \fISPLIT\fR; combining lines, see \fIJOIN\fR; deleting lines, see \fI<CLOSE>\fR and \fI<ERASE>\fR; adding lines, see \fI<CLOSE>\fR and \fI<PICK>\fR; moving lines, see \fI<CLOSE>\fR. .sp .h1 "LONG LINES" The window normally shows columns 1-78. When the user attempts to type beyond column 78, the Editor prints an error message and will not print characters typed at that point. The window can be moved to the right 16 characters by pressing <RIGHT>. Another 16 characters can then be added to the line. The window can be moved more than 16 characters to the right by moving the cursor to the column that will become column 1 of the new window, and then pressing <CMD> <RIGHT>. The window will then move to the right so that the cursor is at the left edge of the window. The window can be moved from a position on the right back to the leftmost position (columns 1-78) by pressing <CMD> <LEFT>. When the cursor is at the right most edge of the window, and the <RIGHT ARROW> is pressed, the window will move two spaces to the right. Lines longer than 132 characters cannot be printed, so text lines should be limited to 132 characters. Lines of 132 characters may only be printed sideways. (See also \fI<ARROW KEYS> <LEFT>, \fRand \fI<RIGHT>.\fR) .sp .h1 "MARGIN CHARACTERS" The character "-" is used to mark the top and bottom edges of the window. The character ":" is used to mark the right and left edges of the window when all of the text is within the window. The character "<" is used to mark the left edge of the window when the window has been moved right. The character ">" is used to mark the right edge of the window when text extends beyond the right edge of the window. Bright blocks are sometimes used to target the column and line where the cursor is located. The character ";" is used to mark lines beyond the last line of text in a file. The character "." (period) is used to outline windows other than the current window. .sp .h1 "MARGINS" The Editor sounds a warning beep when the user types a character into column 67 of the screen regardless of where the actual right margin has been set. The actual right margin for a fill, justify, or center command is determined by the last "width=" issued in one of these commands or by the default width of 75. If a paragraph has already been typed beginning in column 1 and an additional indention is desired, that indention can be achieved by marking the indention (as a rectangle) and then pressing <OPEN>. For documents and reports, text is normally typed beginning in column 1, interspersed with formatting macros, and then the format package processes the file and creates the requested indentions. (See also \fICENTER, FILL, JUSTIFY, <MARK>, \fRand\fI <OPEN>\fR.) .sp .h1 "<MARK>" This key is used to define an area and is labeled <MARK>. This key allows the user to mark lines and rectangles and then issue a command that affects only the marked area using a variety of commands and key functions. To mark several whole lines the user moves the cursor to the first line to be marked and presses <MARK>. The user then moves the cursor to the last line to be marked (the number of lines marked is indicated in the mark message below the window). At this point the user issues a command or presses a function key. For example, the user may press <PICK> to place the marked lines in the pick buffer, or press <CLOSE> to place the lines in the close buffer, or press <OPEN> to open a number of blank lines in the marked area, or type in a variety of commands such as fill, justify, replace or erase. The mark function is normally terminated when the <PICK>, <CLOSE>, <ERASE>, or <OPEN> key is pressed, or when the user types in a command. An incomplete or unwanted mark function can be terminated by pressing <CMD> <MARK>. (See also, \fICENTER, <CLOSE>, <ERASE>, FILL, JUSTIFY, <PICK>, <OPEN>.) .sp .h1 "MOVING LINES" Moving lines is done by closing the lines and then placing them elsewhere. (See \fI<CLOSE>\fR.) .sp .h1 "MOVING TEXT BETWEEN FILES" Sections of text from one file can be moved or copied to another file by editing both files, copying the text with pick or moving it with close, alternating files, and then placing the text in the second file. The user initiates the process by typing \fBe\fR \fIfilename\fR <RETURN> to begin editing a file from which sections of text will be copied or removed. Once in that file, the cursor is moved to the first line of text to be moved or copied and <MARK> is pressed to begin marking the area. The cursor is then moved to the last line of text to be moved or copied, and <PICK> or <CLOSE> is pressed depending on whether the text is to be copied or moved. The second file is now brought up as the alternate file by pressing <CMD> \fBe \fR\fIsecondfilename\fR <RETURN>. The cursor is moved to the location in this second file where the text is to be placed, and then <CMD> <CLOSE> or <CMD> <PICK> is pressed depending on whether the text was initially closed or picked. The second file can now be edited normally. Upon normal exit, both files are updated to reflect the editing performed. (See also \fIALTERNATE FILE, <CLOSE>, <MARK>, MULTIPLE WINDOWS,\fR, and \fI<PICK>\fR.) .sp .h1 "MOVING THE WINDOW" See \fI<ARROW KEYS>, <LEFT>, <+LINE>, <-LINE>, <+PAGE>, <-PAGE>,\fR and \fI<RIGHT>\fR. .sp .h1 "NAME" The file being edited can be renamed, while in the Editor, by pressing <CMD> \fBname\fR \fInewfilename\fR (where \fBname\fR can be abbreviated \fBn\fR). The naming takes effect upon successful exit from the Editor. To negate the renaming, the editing session must be aborted with \fBexit abort\fR. (See also \fIFILENAME\fR and \fIRENAMING FILES\fR.) .sp .h1 "OPEN" The open command may be used instead of <OPEN> to open space. To open an area, the user types <CMD> \fBopen\fR \fIn\fR <RETURN> (where \fBopen\fR may be abbreviated \fBo\fR). The default area is one line. (See also \fI<OPEN>\fR.) .sp .h1 "<OPEN>" This key inserts blank space into the file. If <OPEN> is pressed by itself, it inserts a blank line at the line where the cursor is. In doing this it moves all of the remaining lines in the file down one line. Several lines can be opened by pressing, <CMD> \fIn\fR <OPEN>, where \fIn\fR is the number of blank lines to insert in the file. The open key will also operate on an area that has been marked with the <MARK> key. For example, to indent several lines of text, the cursor is moved to the first line of text and the <MARK> key is pressed to begin the mark process. The cursor is then moved to the right the number of columns of indention required and then to the bottom line of text. This marked area is shown below the window as "MARK nxn", where n refers to the number of lines and columns. The <OPEN> key is pressed at this point and the text is indented. Note that the dimensions of the marked area are not saved by the Editor, so a subsequent press of a <CLOSE> key does not return the area to its former state. (See also \fI<CLOSE>, \fRand\fI <MARK>\fR.) .sp .h1 "<+PAGE>" This key moves the window toward the end of the file for one window full of lines. The window can be moved more than one page by pressing <CMD>\fR \fIn\fR <+PAGE>, where \fIn\fR is the number of pages to move toward the end of the file. The key sequence <CMD> <+PAGE> moves the cursor to the last line of the file and redraws the window if necessary. (See also <-PAGE>.) .sp .h1 "<-PAGE>" This key moves the window toward the front of the file by one window full of lines. The window can be moved more than one page by pressing <CMD> \fIn\fR <-PAGE>, where \fIn\fR is the number of pages to move toward the front of the file. The key sequence <CMD> <-PAGE>, moves the cursor to line 1 of the file and redraws the window if necessary. (See also \fI<+PAGE>\fR.) .sp .h1 "PAGINATION" Pagination of large documents is normally performed using a formatting package. Pagination can be manually inserted by inserting page eject (formfeed) characters at the beginning of each page of text (assuming the formfeeds are closer together than the page size specified in the Unix print command, usually 60 lines). A formfeed is inserted in the text in column 1 by pressing <CNTL CHAR> |SHIFT+L|. The first keystroke combination produces a bright block and the second keystroke combination inserts a capital "L". .sp .h1 "PARAGRAPHS" Many Editor commands deal with paragraphs. For example, the fill command, if no area is specified, fills one paragraph. In most commands, "paragraph" is abbreviated \fBp\fR, for example, \fBfill \fR\fI6\fBp\fR. To the Editor a paragraph is a line or series of lines that ends with a blank line or the end of the file. That is, paragraphs are separated from one another by a blank line. Paragraphs are most easily dealt with by use of formatting macros. (See also \fIFILL, JUSTIFY,\fR and \fI<OPEN>\fR.) .sp .h1 "PICK" The pick command may be used instead of the pick key to pick text and place it in the pick buffer. The format of the command is <CMD> \fBpick\fR \fIarea\fR <RETURN> (where \fBpick\fR may be abbreviated \fBpi\fR). If \fIarea\fR is not specified, the default area is one line. The information copied with the pick command or key may be placed back in the file by entering the command <CMD> \fB-pick\fR <RETURN> (where \fB-pick\fR may be abbreviated \fB-p\fR). (See also \fI<PICK>\fR.) .sp .h1 "-PICK" This command may be used to copy text from the pick buffer into the file. The format of the command is <CMD> \fB-pick\fR <RETURN> (where \%\fB-pick\fR may be abbreviated \fB-pi\fR). Text may also be copied from the pick buffer into the file by pressing <CMD> <PICK>. (See also \fI<PICK>\fR.) .sp .h1 "<PICK>" The pick key copies characters, lines, and areas into a buffer from which copies may be placed anywhere in the file. The picked material remains in the buffer until <PICK> is pressed again, or until the user exits the file. One line may be copied by moving the cursor to that line and pressing <PICK>. Several lines may be copied by pressing <CMD> \fIn\fR <PICK>, where \fIn\fR is the number of consecutive lines to be copied. These lines are copied beginning with the line where the cursor is. A copy of the picked lines can be inserted into the file by moving the cursor to where the lines are to be placed and pressing <CMD> <PICK>. The picked lines are inserted starting on the line where the cursor is. Copies of the picked lines may be inserted in an unlimited number of places in the file. The pick function also works with marked lines and marked rectangles. To mark a rectangular area and then place a copy of it into the pick buffer, the following keystrokes are necessary: move the cursor to the upper left hand corner of the rectangular area and press <MARK>; move the cursor to the lower right hand corner of the rectangular area and press <PICK>. The text will be copied into the pick buffer, and the cursor will return to where it was when <MARK> was pressed. Text copied form the pick buffer is placed in the change file. (See also \fICHANGE FILE, <CLOSE>, MOVING TEXT BETWEEN FILES\fR, and PICK\fR.) .sp .h1 "PICK BUFFER" The pick buffer is a special area in the Editor that contains text that is copied with the <PICK> key. Picked text remains in this buffer until the <PICK> key is pressed again when it is replaced by new text or until the file is exited. (See also \fIPICK\fR and \fI<PICK>\fR.) .sp .h1 "PLACING TEXT" Text that has been removed with the <CLOSE> key may be copied back into the file in the same place or elsewhere by pressing <CMD> <CLOSE>. Text that has been picked with the <PICK> key may be copied back into the file by pressing <CMD> <PICK>. Text can also be placed in the file by the use of commands. Text in the pick buffer can be copied to the file by pressing <CMD> \fB-pick\fR <RETURN> (where \fB-pick\fR may be abbreviated \fB-pi\fR). Text in the close buffer may be copied to the file by pressing <CMD> \fB-close\fR <RETURN> (where \fB-close\fR may be abbreviated \fB-c\fR). (See also \fI<CLOSE>, PICK\fR and \fI<PICK>\fR.) .sp .h1 "QUITTING" See \fIexit\fR. .sp .h1 "RECOVERY" There are several situations from which a user would want to recover. First, there is the situation in which the Editor, E, fails and prints a "crash" message. Recovery from this situation is performed by entering the same directory and typing \fBe\fR. The Editor will prompt the user with four options, one of which is a non-visible, automatic recovery (option 1). Another type of recovery involves material inadvertently closed out via the <CLOSE> key. Frequently a user wants to recover text that was inadvertently closed. That text may be found in the change file. The change file may be edited as an alternate file, the material picked from it, and then placed in the original file. (See \fICHANGE FILE\fR and \fIMOVING TEXT BETWEEN FILES\fR.) When a user makes a serious editing mistake and ruins a file, he can negate the error and the editing session by typing \fBexit abort\fR. He can then recover the editing session by typing \fBe\fR. The Editor will prompt him with four options, one of which is a visible replay (option 2). The user can initiate the replay, watch it occur, and just before the serious mistake is replicated, interrupt the replay by pressing <INT>. The replay is performed quickly, and some skill is required to interrupt it at the desired point. The Editor prints the following prompt when it is entered again in the same directory after a crash or an aborted session: .(b The last time you used the Editor in this directory, you crashed or aborted. You have these choices: 1. E will silently recover the last session and then update the screen; exit before you continue editing. (Normally, select this option.) 2. E will replay the last session on the screen; exit before you continue editing. (Select this option if E continues to crash in response to Option 1; press the interrupt key just before E completes the replay. The interrupt key is <INT> for Ambassadors, and |CTRL+C| for the other Ann Arbor terminals. 3. E will give you the version you had BEFORE you began the last session. (Select this option only if you do NOT wish to recover the last session's work.) 4. E will not do anything. (Select this option if you do not know what to do; call X678 for assistance.) Type the number of the option you want then hit <RETURN>: .)b Choices 1 and 2 are normally requested; choices 3 and 4 are presented to allow for all possible alternatives (they do not recover). To circumvent this message after an aborted session, call the Editor by typing \fBe -norecover\fR, or you may choose option 3. This will completely eliminate an aborted session and destroy any chance for a recovery of that session. .sp .h1 "RECTANGULAR AREAS" Rectangular areas are defined by using the mark function. (See \fI<MARK>\fR.) .sp .h1 "REDRAW" To redraw the screen and eliminate extraneous characters (such as system messages, noise characters, and garbage characters), the user presses <CMD> \fBredraw\fR <RETURN> (where \fBredraw\fR may be abbreviated \fBred\fR). .sp .h1 "RENAMING FILES" A file can be renamed using the Unix command \fBmv\fR in response to the Unix "%" prompt. The file being edited can be renamed while in the Editor by pressing, <CMD> \fBname\fR \fInewfilename\fR <RETURN> (where \fBname\fR can be abbreviated \fBn\fR). The renaming takes place upon normal exit from the Editor. To negate the renaming, the session must be aborted by typing \fBexit abort\fR. .sp .h1 "REPLACE" The replace command is used to replace characters or words with other characters or words. The simplest form of the command is \fBreplace\fR (where replace can be abbreviated \fBrep\fR), which directs the Editor to search for occurrences of \fItexta\fR beginning where the cursor is and proceeding toward the end of the file. .(b <CMD> \fBreplace\fR \fI/texta/textb/\fR <RETURN> <CMD> \fB-replace\fR \fI/texta/textb/\fR <RETURN> .)b This would replace every occurrence of \fItexta\fR with \fItextb\fR, starting where the cursor is and proceeding to the end of the file. If the command is prefaced with a minus sign, \fB-replace\fR or \fB-rep\fR, the Editor searches for occurrences of \fItexta\fR beginning where the cursor is and proceeding toward the beginning of the file. Two options are \fBshow\fR and \fBinteractive\fR. The \fBshow\fR option allows the user to see the replacements as they occur. The \fBinteractive\fR option allows the user to not only see the replacements, but also to control whether each replacement will occur. Since \fBinteractive\fR includes \fBshow\fR, only one of these options can be typed with the command at any one time. The \fBshow\fR option displays the replacements on the screen as they occur. That is, each occurrence of \fItexta\fR is located, the screen is redrawn to show that occurrence, and then the replacement is performed. The command can be interrupted at any time by pressing <INT>. The \fBinteractive\fR option, (which can be abbreviated \fBint\fR) allows the user to replace only selected occurrences of \fItexta\fR with \fItextb\fR. When the first occurrence of \fItexta\fR is found, the cursor is moved to it. At this point, pressing <REPLC> triggers replacement of that occurrence of \fItexta\fR with \fItextb\fR. The user then presses <+SCH> to search for the next occurrence of \fItexta\fR. If the user does not want an occurrence of \fItexta\fR to be replaced, the user presses <+SCH>, and the Editor skips that replacement and proceeds to the next occurrence of \fItexta\fR. In this fashion the user can replace just those occurrences of \fItexta\fR that he wants to. The text searched for and the replacement text can be separated in the command by a variety of characters including: /, *, ', ", $, +. These characters should only be used if they are not part of your text to be replaced. Replacements may be limited to a specified number of paragraphs. The following examples illustrate variations of the command: .(b <CMD> \fBrep \fR\fI/Smythe/Smith/\fR <RETURN> Simple replacement to end of file. <CMD> \fBrep \fR\fI4p /Smythe/Smith/\fR <RETURN> Simple replacement for 4 paragraphs. <CMD> \fBrep \fR\fI4 /Smythe/Smith/\fR <RETURN> Simple replacement for 4 lines. <CMD> \fBrep \fR\fI4p int */____/*/..../*\fR <RETURN> Replace "/____/" with "/..../" in 4 paragraphs interactively. <MARK> <cursor movements> <CMD> \fBrep int\fR \fI/AA/BB/\fR <RETURN> .)b This last example illustrates that a marked area can be used to limit the area where replacement takes effect. In this example, \fIAA\fR is to be replaced by \fIBB\fR in the interactive mode in the area marked by the cursor movements. (See also \fI<MARK>, <+SCH>,\fRand\fI <-SCH>,\fR.) .sp .h1 "REPLAYING A SESSION" A session may be replayed if the session ended in a crash, or if the session was ended by the user typing \fBexit abort\fR. In all of these cases the keystroke file, normally named ".ek1", is preserved and can be used by the system for a replay. After a crash the user returns to the same directory and types \fBe\fR, and the Editor prompts him with four options, one of which is a nonvisible automatic replay (option 1). In the event of an aborted session (\fBexit abort\fR), the user also returns to the same directory and types \fBe\fR, and the Editor prompts him with four options, one of which is a visible replay (option 2). The user initiates the replay, watches it occur, and then interrupts it at a desired point by pressing <INT>. (See also \fIKEYSTROKE FILE\fR and \fIRECOVERY.) .sp .h1 "<RETURN>" Within the window, this key is pressed to move the cursor to column 1 of the next line. On the command line this key is pressed at the end of a command to signal the Editor that a command had been entered, e.g., an "execute" key. .sp .h1 "<RIGHT>" This key is pressed to move the window 16 characters to the right. Pressing <CMD> <RIGHT> moves the window to the right so that the cursor is displayed in column 1 of the new window. (See also \fI<ARROW KEYS>\fR and \fI<LEFT>\fR.) .sp .h1 "<RIGHT ARROW>" See \fI<ARROW KEYS>\fR. .sp .h1 "RUN" A UNIX command can be executed in the Editor by pressing: .(b <CMD> \fBrun\fR \fIarea\fR \fIcommand\fR <RETURN> .)b For example, to run the Unix command "ls" and have the output included in the file being edited, press <CMD> \fBrun\fR \fIls\fR <RETURN>. Note that the output from a command can vary depending on when it is run, and consequently a replay of the editing session that includes a command may produce disastrous results. For knowledgeable Unix users only: \fBarea\fR is passed to the standard input of the command and is replaced by the output of the command. .sp .h1 "SAVE" A copy of the file being edited can be saved with the current changes by pressing, <CMD> \fBsave\fR \fInewfilename\fR <RETURN> (where \fBsave\fR may be abbreviated \fBsa\fR). The file is saved immediately, and does not wait for you to exit from the Editor. The \fInewfilename\fR must be specified and cannot be the name of the file being edited. This command is a convenient way of backing up a modified file before attempting some new, dramatic editing. .sp .h1 "SAVING FILES" A file is saved with the edited changes when the user exits normally with \fBexit\fR. A file can also be saved with the edited changes by means of the save command. (See also \fICREATING FILES, EXIT, \fR and \fISAVE\fR.) .sp .h1 "<+SCH>" This key is used to search for characters, or words. The search begins where the cursor is and proceeds toward the end of the file. To search specific words or characters, the user presses <CMD> \fIwords\fR <+SCH>. If the Editor finds an occurrence of \fIwords\fR, the Editor moves the cursor to that text and redraws the window if necessary. To continue searching the user presses <+SCH> again. The text string searched for is placed in a search buffer, and consequently is available to be searched again by pressing <+SCH> or <-SCH>. There is another method of placing text in the search buffer. This method is limited to text that does not contain blanks. To use this method, the user positions the cursor at the first character of the text and presses <CMD> <+SCH>. The Editor then copies the characters up to but not including the next blank space (one word only) into the search buffer. The search for the text then proceeds normally. (See also \fIREPLACE\fR and \fI<-SCH>\fR.) .sp .h1 "<-SCH>" This key is used to search for characters or words. The search begins where the cursor is and proceeds toward the beginning of the file. The method is the same as in <+SCH>. (See also \fIREPLACE\fR and \fI<+SCH>\fR.) .sp .h1 "SCRATCH FILE" Occasionally the Editor finds itself with no file to work in when the user expects to be working in a file. The Editor solves this dilemma by creating a file named "scratch". If the user does not want to keep "scratch", he should \fBexit\fR. .sp .h1 "SEARCHING" See \fI<+SCH>\fR and \fI<-SCH>\fR. .sp .h1 "SETTING TABS" See \fItab\fR and \fItabs\fR. .sp .h1 "SPLIT" This command splits one line into two lines at the point where the cursor is. The righthand side of the line, including the character at the cursor, is inserted as a new line on the line below, and then the window is redrawn. To use this command, a user types <CMD> \fBsplit\fR <RETURN> (where \fBsplit\fR may be abbreviated \fBsp\fR). (See also \fIJOIN\fR.) .sp .h1 "<S/R TAB>" This key sets and unsets tabs. It is labeled <[> on some terminals. To set a tab using this key, the user moves the cursor to the column where a tab is desired and presses <S/R TAB>. To clear a tab using this key, the user moves the cursor to position where a tab is to be removed and presses <CMD> <S/R TAB>. (See also \fITAB, -TAB, TABS, -TABS, <+TAB>\fR, and \fI<-TABS>\fR. .sp .h1 "STATE FILE" The state file contains information about the last file edited in the directory, including the filename, the place in the file where the cursor was when the user exited, the line length established in the last fill, justify, or center command, the state of Insert Mode, the tabs, and the last search string. The name of this file, assuming the user owns the directory and is the only user working in the directory, is ".es1". (See also \fICHANGE FILE, KEYSTROKE FILE,\fR, and \fIRECOVERY\fR.) .sp .h1 "TAB" To set a tab using this command, a user types <CMD> \fBtab\fR \fIcolumn\fR <RETURN>, where \fIcolumn\fR is an optionally specified column number or several column numbers separated by blanks. If \fIcolumn\fR is not specified, the tab is set where the cursor is. Note that this command does not clear tabs; it sets the tabs where indicated. (See also \fI-TAB, TABS, -TABS, <+TAB>, <S/R TAB>,\fR and \fI<-TABS>\fR. .sp .h1 "-TAB" To clear a tab using this command, a user types <CMD> \fB-tab\fR \fIcolumn\fR <RETURN>, where \fIcolumn\fR is an optionally specified column number or several column numbers separated by blanks. If \fIcolumn\fR is not specified, the tab is cleared where the cursor is). (See also \fITAB, TABS, -TABS, <+TAB>, <S/R TAB>\fR, and \fI<-TABS>\fR. .sp .h1 "<+TAB> or <TAB>" This key moves the cursor to the next tab going toward the right margin. Default tabs are set every 8 columns beginning in column 1 and ending in column 73. When the cursor is at the rightmost tab or beyond, pressing <+TAB> or <TAB> has no effect. (See also \fI-TAB, TABS, -TABS, <S/R TAB>\fR, and \fI<-TABS>\fR.) .sp .h1 "<-TAB> or |SHIFT+TAB|" This key moves the cursor to the next tab going toward the left margin. The default tabs are set every 8 columns beginning in column 1 and ending in column 73. When the cursor is at or before the leftmost tab, pressing <-TAB> or |SHIFT+TAB| has no effect. (See also \fI-TAB, TABS, -TABS, <S/R TAB>\fR, and \fI<-TABS>\fR. .sp .h1 "TABFILE" This command sets tabs according to a file containing a list of column numbers separated by blanks. To set tabs using this command, the user presses <CMD> \fBtabfile \fR\fIfilename\fR <RETURN>, where filename is the name of a file containing the column numbers where the tabs are to be placed. The file with the tabs must be created and saved before editing a file where the tabfile is to be used. Note that this command does not erase any existing tabs; it adds tabs as specified. (See also \fI-TAB, TABS, -TABS, <S/R TAB>, <+TABS>\fR and \fI<-TABS>\fR.) .sp .h1 "TABS, THE TOPIC" The Editor sets default tabs in column 1 and every 8th column after that to column 73. Additional tabs can be set using \fBtabfile\fR, \fBtab\fR, and .br <S/R TAB>. Tabs can be removed using \fB-tab\fR and <CMD> <S/R TAB>. (See also \fI-TAB, TABS, -TABS, <S/R TAB>, <+TABS>\fR and \fI<-TABS>\fR.) .sp .h1 "TABS" This command sets tabs every nth column, for example, tabs sets every 5 columns. To set tabs in this fashion, the user presses <CMD> \fBtabs\fR\fI n\fR <RETURN>, where n is every nth column beginning with column 1. (See also \fI-TAB, -TABS, <S/R TAB>, <+TABS>\fR and \fI<-TABS>\fR.) .sp .h1 "-TABS" This command clears all tabs. To clear all tabs, the user presses <CMD> \fB-tabs\fR <RETURN>. This command can also be used to clear tabs in every nth column by pressing, <CMD> \fB-tabs\fR \fIn\fR <RETURN>, where n is the distance between the columns. Tabs can be cleared in every nth column in an area if the area is first marked and then the -tabs command issued. (See also \fITAB, TABS, <+TAB>, <-TAB>,\fR and \fI<S/R TAB>\fR.) .sp .h1 "TRACK" Track causes the current file and the alternate file to track each other. That is, if you move the window in any direction, the alternate file window is moved the same amount. This is useful for comparing two files. If you move the window in any direction, the cursor for the alternate file will be in the same position relative to the window as the current file's cursor. In no case will the alternate file's window be moved backwards past the beginning of the file or to the left beyond the left edge of the file. A "TRACK" indicator will appear on the info line if tracking is set in the window you are in. Use "-track" to turn off tracking. (See \fIALTERNATE FILE\fR and \fI-TRACK\fR.) .sp .h1 "-TRACK" Track causes the current file and the alternate file to track each other. -Track turns off the tracking in the current window. (See \fIALTERNATE FILE\fR and \fITRACK\fR.) .sp .h1 "UNDERLINING" Printing text on the terminal screen with underline characters is not possible on Ann Arbor terminals. Underlining is possible on text printed on hardcopy terminals and on text printed on printers in the Computation Center. Underlining is accomplished most easily by use of the format package. Underlining can be accomplished on a character-by-character basis by adding a control character, a backspace character, and an underline character to the text. To underline one character manually, the underline character must be typed, and then a control character equal to a backspace character must be entered in the text, and then the character itself must be typed. The keystrokes required to underline the letter "t" are as follows: .(b <_> <CNTL CHAR> |SHIFT+H| t .)b The first keystroke generates the underline character; the second keystroke generates a small, bright block on the screen. The next keystroke, generates the code for a control backspace character that is to be entered into the text (not a backspace character used while editing); and finally the last keystroke generates the letter \fIt\fR. .sp .h1 "UNMARK" To negate marking, the user presses <CMD> <MARK>. (Also see \fI<MARK>\fR.) .sp .h1 "UP ARROW" (See \fI<ARROW KEYS>\fR.) .sp .h1 "USING A FILE" A file is edited by typing \fBe \fR\fIfilename\fR. If the file to be edited is the same file worked on in the last editing session, then the user can return to the same file in the same place by typing \fBe\fR. While editing one file, another file can be edited as an alternate file. (See also \fIALTERNATE FILE\fR and \fIMOVING TEXT BETWEEN FILES\fR.) .sp .h1 "WIDE FILES" Files with wide lines can be viewed by using <RIGHT> and <LEFT> to shift the window. (See also \fILONG LINES\fR.) .sp .h1 "WIDTH" The fill, justify, and center commands allow the user to specify a width. The \fBwidth=\fR\fIn\fR specified as part of the command may be abbreviated \fBw=\fR\fIn\fR. This width remains in effect until another fill, justify, or center command is entered with a different width specification, or until you exit from the file. This width is maintained as part of the information kept in the state file. When a file is created, the default width is 75. .sp .h1 "WINDOW" The Editor uses the window concept to display a file. The terminal screen is viewed as a window that opens on part of the file. The window can be moved forward and backward through the file (and right and left) to view different portions of the file. When the user presses keys that require the cursor to be moved out of the window, then the window is moved so that the cursor remains in the window. (See also \fICREATING \fIWINDOWS, DELETING WINDOWS, \fRand WINDOWS\fR.) .sp .h1 "WINDOWS" Multiple windows are useful for moving text between files, comparing files, and merging files. A new window is created by positioning the cursor on either the left or top edge of the window but not in the top left hand corner. Press <CMD> \fBwindow \fR \fInewfilename\fR <RETURN> (where window may be abbreviated \fBw\fR). The file \fInewfilename\fR becomes the current file, and the new window becomes the current window. If a filename is not specified, <CMD> \fBwindow\fR <RETURN>, the current file also becomes the current file in the new window. The windows are numbered in the order in which they were created. To move the Editor from window to window, the user presses <CHG WIN>. To move to a particular window, the user types <CMD> \fIn\fR <CHG WIN>, where \fIn\fR is the number of the window. To remove the last window created, the user types <CMD> \fB-window\fR <RETURN> (where \fB-window\fR may be abbreviated \fB-w\fR). (See also \fIALTERNATE FILE\fR.) .sp .h1 "#o" This is the name of a pseudo file created by the Editor to access the text that has been closed using <CLOSE> or the close command, or deleted using the erase command. It also gives access to text that has been filled or justified. (See \fICHANGE FILE\fR.) .sp .h1 "#p" This is the name of a pseudo file created by the Editor to access text in the change file that has been picked. (See \fICHANGE FILE\fR.) .mh "THE STANDARD KEYBOARD" .pp There is now a "standard" E keyboard, that is designed to be usable on all video display terminals. Either say "e \-keyboard=standard" or "setenv EKBD standard" before running E to select this keyboard. This is also the keyboard that E will use if there is no specific knowledge of your type of terminal compiled into the editor. .pp This keyboard layout is designed to be used on terminals with no function keys. "^H" means control\-H, and "^X\-^U" means control\-X followed by control\-U. The ALT entry gives you a choice of "^/" or "^_" because one or the other or both will not work on some terminals. ("_" is correct ASCII.) .pp Note that +WORD and \-WORD are not implemented yet. .bp .tc no .so e.stdkey.out .pc
package brainfreeze.world; import java.awt.Color; import java.awt.Paint; import java.awt.PaintContext; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Float; import java.awt.geom.Rectangle2D; import java.awt.image.ColorModel; import java.beans.ConstructorProperties; public class TriangleGradientPaint implements Paint { Point2D.Float p1; Point2D.Float p2; Color color1; Color color2; boolean cyclic; private Float p3; private Color color3; /** * Constructs a simple acyclic <code>GradientPaint</code> object. * @param x1 x coordinate of the first specified * <code>Point</code> in user space * @param y1 y coordinate of the first specified * <code>Point</code> in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param x2 x coordinate of the second specified * <code>Point</code> in user space * @param y2 y coordinate of the second specified * <code>Point</code> in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @throws NullPointerException if either one of colors is null */ public TriangleGradientPaint(float x1, float y1, Color color1, float x2, float y2, Color color2, float x3, float y3, Color color3) { if ((color1 == null) || (color2 == null) || (color3 == null)) { throw new NullPointerException("Colors cannot be null"); } p1 = new Point2D.Float(x1, y1); p2 = new Point2D.Float(x2, y2); p3 = new Point2D.Float(x3, y3); this.color1 = color1; this.color2 = color2; this.color3 = color3; } /** * Constructs a simple acyclic <code>GradientPaint</code> object. * @param pt1 the first specified <code>Point</code> in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param pt2 the second specified <code>Point</code> in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @throws NullPointerException if either one of colors or points * is null */ public TriangleGradientPaint(Point2D pt1, Color color1, Point2D pt2, Color color2, Point2D pt3, Color color3) { if ((color1 == null) || (color2 == null) || (pt1 == null) || (pt2 == null)) { throw new NullPointerException("Colors and points should be non-null"); } p1 = new Point2D.Float((float)pt1.getX(), (float)pt1.getY()); p2 = new Point2D.Float((float)pt2.getX(), (float)pt2.getY()); p3 = new Point2D.Float((float)pt3.getX(), (float)pt3.getY()); this.color1 = color1; this.color2 = color2; this.color3 = color3; } /** * Constructs either a cyclic or acyclic <code>GradientPaint</code> * object depending on the <code>boolean</code> parameter. * @param x1 x coordinate of the first specified * <code>Point</code> in user space * @param y1 y coordinate of the first specified * <code>Point</code> in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param x2 x coordinate of the second specified * <code>Point</code> in user space * @param y2 y coordinate of the second specified * <code>Point</code> in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @param cyclic <code>true</code> if the gradient pattern should cycle * repeatedly between the two colors; <code>false</code> otherwise */ public TriangleGradientPaint(float x1, float y1, Color color1, float x2, float y2, Color color2, float x3, float y3, Color color3, boolean cyclic) { this (x1, y1, color1, x2, y2, color2, x3, y3, color3); this.cyclic = cyclic; } /** * Constructs either a cyclic or acyclic <code>GradientPaint</code> * object depending on the <code>boolean</code> parameter. * @param pt1 the first specified <code>Point</code> * in user space * @param color1 <code>Color</code> at the first specified * <code>Point</code> * @param pt2 the second specified <code>Point</code> * in user space * @param color2 <code>Color</code> at the second specified * <code>Point</code> * @param cyclic <code>true</code> if the gradient pattern should cycle * repeatedly between the two colors; <code>false</code> otherwise * @throws NullPointerException if either one of colors or points * is null */ @ConstructorProperties({ "point1", "color1", "point2", "color2", "cyclic" }) public TriangleGradientPaint(Point2D pt1, Color color1, Point2D pt2, Color color2, Point2D pt3, Color color3, boolean cyclic) { this (pt1, color1, pt2, color2, pt3, color3); this.cyclic = cyclic; } /** * Returns a copy of the point P1 that anchors the first color. * @return a {@link Point2D} object that is a copy of the point * that anchors the first color of this * <code>GradientPaint</code>. */ public Point2D getPoint1() { return new Point2D.Float(p1.x, p1.y); } /** * Returns the color C1 anchored by the point P1. * @return a <code>Color</code> object that is the color * anchored by P1. */ public Color getColor1() { return color1; } /** * Returns a copy of the point P2 which anchors the second color. * @return a {@link Point2D} object that is a copy of the point * that anchors the second color of this * <code>GradientPaint</code>. */ public Point2D getPoint2() { return new Point2D.Float(p2.x, p2.y); } /** * Returns the color C2 anchored by the point P2. * @return a <code>Color</code> object that is the color * anchored by P2. */ public Color getColor2() { return color2; } /** * Returns <code>true</code> if the gradient cycles repeatedly * between the two colors C1 and C2. * @return <code>true</code> if the gradient cycles repeatedly * between the two colors; <code>false</code> otherwise. */ public boolean isCyclic() { return cyclic; } /** * Creates and returns a {@link PaintContext} used to * generate a linear color gradient pattern. * See the {@link Paint#createContext specification} of the * method in the {@link Paint} interface for information * on null parameter handling. * * @param cm the preferred {@link ColorModel} which represents the most convenient * format for the caller to receive the pixel data, or {@code null} * if there is no preference. * @param deviceBounds the device space bounding box * of the graphics primitive being rendered. * @param userBounds the user space bounding box * of the graphics primitive being rendered. * @param xform the {@link AffineTransform} from user * space into device space. * @param hints the set of hints that the context object can use to * choose between rendering alternatives. * @return the {@code PaintContext} for * generating color patterns. * @see Paint * @see PaintContext * @see ColorModel * @see Rectangle * @see Rectangle2D * @see AffineTransform * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) { return new TriangleGradientPaintContext(cm, p1, p2, p3, xform, color1, color2, color3, cyclic); } /** * Returns the transparency mode for this <code>GradientPaint</code>. * @return an integer value representing this <code>GradientPaint</code> * object's transparency mode. * @see Transparency */ public int getTransparency() { int a1 = color1.getAlpha(); int a2 = color2.getAlpha(); return (((a1 & a2) == 0xff) ? OPAQUE : TRANSLUCENT); } }
import os, torch, torchvision import torch.nn as nn from model import UNET, Discriminator from PIL import Image from torch.utils.data import DataLoader from torch.utils.data import Dataset from torchvision import transforms def gaussianNoise(image, mean=0., std=0.2): noise = torch.randn(image.size()) * std + mean noisyImage = image + noise return torch.clamp(noisyImage, 0., 1.) class NoisyEMNIST(Dataset): def __init__(self, dataset, noiseFunction): self.dataset = dataset self.noiseFunction = noiseFunction def __len__(self): return len(self.dataset) def __getitem__(self, idx): image, label = self.dataset[idx] noisy_image = self.noiseFunction(image) return noisy_image, image num_epochs, batch_size = 10, 32 transform = transforms.Compose([transforms.ToTensor(),]) trainDataEMNIST = torchvision.datasets.EMNIST(root='./data', split='balanced', train=True, download=False, transform=transform) noisyTrainDataEMNIST = NoisyEMNIST(trainDataEMNIST, gaussianNoise) cleanTrainData = DataLoader(trainDataEMNIST, batch_size=batch_size, shuffle=True) noisyTrainedData = DataLoader(noisyTrainDataEMNIST, batch_size=batch_size, shuffle=True) generator = UNET() discriminator = Discriminator() optimizer_G = torch.optim.Adam(generator.parameters(), lr=0.001) optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=0.001) adversarial_loss = torch.nn.BCELoss() l1_loss = nn.L1Loss() for epoch in range(num_epochs): for i, (noisy_data, clean_data) in enumerate(zip(noisyTrainedData, cleanTrainData)): noisy_imgs, _ = noisy_data original_imgs, _ = clean_data valid = torch.ones((original_imgs.size(0), 1), requires_grad=False) fake = torch.zeros((noisy_imgs.size(0), 1), requires_grad=False) optimizer_G.zero_grad() gen_imgs = generator(noisy_imgs) g_adv_loss = adversarial_loss(discriminator(gen_imgs), valid) g_l1_loss = l1_loss(gen_imgs, original_imgs) g_loss = g_adv_loss + g_l1_loss g_loss.backward() optimizer_G.step() optimizer_D.zero_grad() real_loss = adversarial_loss(discriminator(original_imgs), valid) fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake) d_loss = (real_loss + fake_loss) / 2 d_loss.backward() optimizer_D.step() print(f"[Epoch {epoch+1}/{num_epochs}] [Batch {i}/{len(noisyTrainedData)}] [G loss: {g_loss.item()}] [D loss: {d_loss.item()}]") torch.save(generator.state_dict(), './generatorv3.pth') torch.save(discriminator.state_dict(), './discriminatorv3.pth')
import React, { useState } from "react"; import { ChromePicker } from "react-color"; import styled from "styled-components"; const AppWrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; background-color: ${({ selectedColor }) => selectedColor}; `; const ColorBox = styled.div` width: 200px; height: 200px; display: flex; flex-direction: column; justify-content: center; align-items: center; `; const ButtonWrapper = styled.div` margin-bottom: 10px; `; const App = () => { const [selectedColor, setSelectedColor] = useState("#ffffff"); const [showColorPicker, setShowColorPicker] = useState(false); const handleColorChange = (color) => { setSelectedColor(color.hex); }; const handleButtonClick = () => { setShowColorPicker(!showColorPicker); }; return ( <AppWrapper selectedColor={selectedColor}> <ColorBox> <ButtonWrapper> <button onClick={handleButtonClick}>Select Color</button> </ButtonWrapper> {showColorPicker && ( <ChromePicker color={selectedColor} onChange={handleColorChange} /> )} </ColorBox> </AppWrapper> ); }; export default App;
z################################################################################ # Class: Psychology Collaboration # Topic: Tenure and Job Performance # # Sources: SPSS File: "Personality-Performance-Turnover-Chaehan So.sav" # ################################################################################ # Important: # BEFORE script, sync the google drive folder, otherwise data will not be found! # load libraries # detach("package:machinelearningtools", character.only = TRUE) # devtools::install_github("agilebean/machinelearningtools", force = TRUE) libraries <- c( "magrittr" , "sjlabelled" # read SPSS , "caret" , "doParallel" , "RColorBrewer" , "machinelearningtools" , "knitr" , "RPushbullet", "beepr" , "tidyverse" ) sapply(libraries, require, character.only = TRUE) source("_labels.R") # mode <- "new" mode <- "old" # nominal <- FALSE # with ordinal as ORDERED factors nominal <- TRUE # with ordinal as NOMINAL factor seed <- 171 # cross-validation repetitions # CV.REPEATS <- 2 # CV.REPEATS <- 10 CV.REPEATS <- 100 # try first x rows of training set # TRY.FIRST <- NULL TRY.FIRST <- 50 # TRY.FIRST <- 100 # split ratio SPLIT.RATIO <- 1.0 # imputation method IMPUTE.METHOD <- "noimpute" # IMPUTE.METHOD <- "knnImpute" # IMPUTE.METHOD <- "bagImpute" ####################################################################### # # library(rsample) # rsamples <- vfold_cv(mtcars, v = 10) # rsamples$splits # rsamples$id # # vfold_cv(mtcars, v = 10, repeats = 2) # ####################################################################### # define features ####################################################################### get_features <- function(data, target_label, features_set_label) { data %>% select(-(target_label), -starts_with("TO"), -starts_with("PERF"), -starts_with("LIFE"), -job ) %>% { if (features_set_label == "big5items") { # remove composite scores - equivalent to (-nn, -ee, -oo, -aa, -cc) select(., -matches("(oo|cc|ee|aa|nn)$")) } else if (features_set_label == "big5composites") { # remove Big5 items select(., -matches(".*(1|2|3|4|5|6)")) } else { . } } %>% names } ######################################## # 3.1: Select the models ######################################## algorithm.list <- c( "lm" ,"glmnet" # , "knn" # , "kknn" # , "gbm" # , "rf" # 754s/100rep # , "ranger" # , "xgbTree" # 377s/100rep # , "xgbLinear" # 496s/100rep # , "svmLinear" , "svmRadial" ) # clusterOff(cluster.new) ####################################################################### # MAIN ####################################################################### ####################################################################### if (mode == "new") { # repeated cv training.configuration <- trainControl( method = "repeatedcv", number = 10 , repeats = CV.REPEATS , savePredictions = "final" ) ################################################### # 1. Data Acquistion - includes 2.2 Data Cleaning ################################################### if (IMPUTE.METHOD != "noimpute") { dataset.label <- "data/dataset.rds" %>% print } else { dataset.label <- "data/dataset.NA.rds" %>% print } data.new <- readRDS(dataset.label) %T>% print if (IMPUTE.METHOD != "noimpute") { system.time( # tricky tricky: predict throws ERROR (variable is of class NULL) # if factors contain NA >> remove_unused_variables dataset.imputed <- data.new %>% preProcess(method = IMPUTE.METHOD) %>% predict(newdata = data.new) ) %T>% print data.new <- dataset.imputed %>% na.omit } # target_label <- "PERF10" # features_set_label <- "big5items" # features.labels <- data.new %>% get_features(target_label, features_set_label) # # job_label <- "sales" # # job_label <- "R&D" # job_label <- "support" # # job_label <- "all" # desc stats data.new %>% group_by(job) %>% tally() %>% filter(job %in% c(1, 10)) time.total <- system.time( ############ START model.permutations.list <- model.permutations.labels %>% pmap(function(target_label, features_set_label, job_label) { # models.list.name <- output_filename( # PREFIX, target_label, features_set_label, CV.REPEATS, IMPUTE.METHOD) models.list.name <- output_filename( PREFIX, c(target_label, features_set_label, job_label), cv_repeats = CV.REPEATS, impute_method = IMPUTE.METHOD ) %>% print features.labels <- data.new %>% get_features(target_label, features_set_label) # select variables - for different targets, #NA can differ dataset <- data.new %>% select(job, target_label, features.labels) %>% { if (job_label == "sales") { filter(., job == 1) } else if (job_label == "R&D") { filter(., job == 10) } else if (job_label == "support") { filter(., job != 1 & job != 10) } else { . } } %>% select(-job) %>% na.omit %T>% print ######################################## ## 2.4 Split the data ######################################## set.seed(seed) training.index <- createDataPartition( dataset[[target_label]], p = SPLIT.RATIO, list = FALSE ) training.set <- dataset[training.index, ] %T>% print # if split_ratio == 100%, then create no testing.set testing.set <- if (SPLIT.RATIO != 1.0) dataset[-training.index, ] else NULL testing.set # benchmark ml algorithms models.list <- benchmark_algorithms( target_label = target_label, features_labels = features.labels, training_set = training.set, testing_set = testing.set, impute_method = IMPUTE.METHOD, algorithm_list = algorithm.list, glm_family = "gaussian", training_configuration = training.configuration, seed = seed, # split_ratio = SPLIT.RATIO, cv_repeats = CV.REPEATS, try_first = TRY.FIRST, models_list_name = models.list.name ) return(models.list) }) ############ END ) %T>% { push_message(.["elapsed"], model.permutations.strings ) } } ## 4.1 Training Set Performance ######################################## # get model in model.permutations.list by model index model.index = 1 model.index.labels <- model.permutations.labels %>% .[model.index,] %T>% print target_label <- model.index.labels$target_label features_set_label <- model.index.labels$features_set_label job_label <- model.index.labels$job_label CV.REPEATS <- 100 # prefix models.list.name <- output_filename( PREFIX, c(target_label, features_set_label, job_label), paste0(CV.REPEATS, "repeats"), impute_method = IMPUTE.METHOD ) %>% print # get model in model.permutations.labels by model index models.list <- readRDS(models.list.name) # models.list <- readRDS("data/models.list.PERF10.big5items.100repeats.noimpute.rds") # training set performance models.metrics <- models.list %>% get_model_metrics %T>% print # models.metrics <- models.list %>% get_model_metrics(palette = "Dark2") %T>% print models.metrics$metric1.resamples.boxplots + theme(text = element_text(family = 'Gill Sans')) models.metrics$metric2.resamples.boxplots models.list.stripped <- models.list %>% purrr::list_modify(target.label = NULL, testing.set = NULL) models.list.stripped %>% resamples %>% dotplot models.list.stripped %>% resamples %>% .$values dataset <- models.list$testing.set dataset %<>% select(-PERF09) pc <- dataset %>% prcomp ######################################## ## 4.2 Testing Set Performance ######################################## # RMSE for all models on testing set models.metrics$metrics.testing # training vs. testing set performance: RMSE models.metrics$benchmark.all ################################################################################ ################################################################################ ################################################################################ # # SCRIBBLE # ################################################################################ ################################################################################ data.new %>% nearZeroVar(saveMetrics = TRUE) get_featureset <- function(data, target_label = NULL, featureset_labels = NULL, select_starts = NULL) { data %>% dplyr::select(!!rlang::sym(target_label)) %>% { if (!is.null(featureset_labels)) { cbind(., data %>% dplyr::select(!!!rlang::syms(featureset_labels)) ) } else { . } } %>% { if (!is.null(select_starts)) { cbind(., map_dfc(select_starts, function(start_keyword) { data %<>% select(starts_with(start_keyword)) }) ) } else { . } } %>% select(-job) %>% as_tibble() } ################################################################################ # # LESSONS LEARNED # ################################################################################ # ################################################################################ # 1. tidyr::crossing > creates permutations without factor conversion like base::expand.grid # # model.permutations.list <- crossing(target_label = target.label.list, # features_set = features.set.list) # ################################################################################ # 2. unified handling: conditional inline ggplot statements # # dataset %>% # { # if (conditions1) { # select(., -matches("(oo|cc|ee|aa|nn)$")) # # } else if (condition2") { # select(., -matches(".*(1|2|3|4|5|6)")) # # } else { . } # } %>% ... # ################################################################################ # 3. quick prototyping: parametrized training set size # # main_function(..., try_first = NULL) { # train(..., # data = if (is.null(try_first)) training.set else head(training.set, try_first), # ...) # } # ################################################################################ # 4. unified handling: add testing set to model to calculate testing set performance # # during training: # models.list$target.label <- target_label # models.list$testing.set <- testing.set # # after training: # get_model_metrics(target_label = NULL, # testing_set = NULL, ...) { # target.label <- if (!is.null(target_label)) target_label else models_list$target.label # testing.set <- if (!is.null(testing_set)) testing_set else models_list$testing.set # # RMSE.testing <- get_rmse_testing(target.label, models.list, testing.set) # } # # for resamples() must remove these 2 parameters: # models.list %>% head(-2) %>% resamples # ################################################################################ # 5. quick prototyping: set comma before parameter in list # algorithm.list <- c( # "lm" # ,"glm" # # , "knn" # ) # stop cluster if exists # if (nrow(showConnections()) != 0) stopCluster(cluster.new) # ################################################################################
<?php declare(strict_types = 1); namespace App\User\Presentation\API\User; use App\User\Domain\Action\User\ChangeUserPasswordAction; use App\User\Domain\DTO\User\ChangePasswordDTO; use App\User\Domain\Interface\User\UserReaderInterface; use Psr\Log\LoggerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; #[Route('/api/users', name: 'api.users.')] class ChangeUserPasswordController extends AbstractController { public function __construct( private readonly LoggerInterface $logger, private readonly UserReaderInterface $userReaderRepository ) {} #[Route('/{uuid}/change-password', name: 'change_password', methods: ['PATCH'])] public function changePassword(string $uuid, ChangePasswordDTO $changePasswordDTO, ChangeUserPasswordAction $changeUserPasswordAction): Response { try { $changeUserPasswordAction->setUserToChangePassword( $this->userReaderRepository->getNotDeletedUserByUUID($uuid) )->execute($changePasswordDTO); return $this->json(['message' => 'User\'s password has been changed.'], Response::HTTP_OK); } catch (\Exception $e) { $this->logger->error('trying user\'s password change: ' . $e->getMessage()); return $this->json(['errors' => 'Upss... problem with user\'s password change'], Response::HTTP_INTERNAL_SERVER_ERROR); } } }
<!-- Note: video carousel, this component is hard to understand, so I write a lot of comments for future reference --> <template> <!-- Here I track the video carousel div so I can know when I enter the viewport the videos will start to play --> <section class="flex items-center" ref="carousel"> <!-- This loop is to show all the videos, each video will be in a new div --> <div v-for="(list, index) in highlightsSlides" :key="list.id" class="pr-10 sm:pr-20 carousel-item"> <div class="video-carousel-container"> <div class="w-full h-full flex-center rounded-3xl overflow-hidden bg-black"> <!-- This ref is for keeping track of all videos, and to now which one to play, got to, or to stop --> <!-- I think it's more easy to track all the htmlVideoElements in an array, that's why I write it like this --> <!-- `@ended="playNextVideo(index)` so from here I track the end of each video, if it ended, just start the next one --> <video class="pointer-events-none" :class="{ 'translate-x-44': list.id === 2 }" :ref="setVideosRef" id="video" preload="auto" playsinline muted @ended="playNextVideo(index)"> > <source :src="list.video" type="video/webm" /> </video> </div> <!-- Here I track all the DIVs that will contains the videTexts, so I can animate them --> <div :ref="setTextsRef" class="absolute top-12 left-[5%] z-10 opacity-0 -translate-x-52"> <p v-for="text in list.textLists" :key="text" @mouseenter=" () => { store.isHovered = true; store.hoveredCircleSize = 4; } " @mouseleave=" () => { store.isHovered = false; store.hoveredCircleSize = 1; } " class="text-xl md:text-2xl font-bold"> {{ text }} </p> </div> </div> </div> </section> <div ref="progresses" class="relative flex-center mt-10"> <!-- small dots --> <div id="dots-container" class="flex-center py-5 px-7 backdrop-blur rounded-full bg-gray-300"> <span v-for="(video, index) in highlightsSlides" :key="video.id" :style="{ width: `${!(!playing && !paused) ? dotWidth(index) : '12px'}`, }" @click="goToVide(index)" class="mx-2 size-3 bg-gray-200 rounded-full relative cursor-pointer transition-[width] duration-500"> <span class="absolute size-full rounded-full" /> <span :ref="setProgressBars" class="absolute h-full w-0 bg-white rounded-full cursor-none pointer-events-none"></span> </span> </div> <button class="control-btn" v-if="!playing && !paused" @click="restart"> <img width="30" :src="replayImg" alt="restart button" /> </button> <button v-else @click="togglePause" class="control-btn"> <img width="30" :src="!paused ? pauseImg : playImg" :alt="!paused ? 'pause button' : 'play button'" /> </button> <br /> </div> </template> <script setup lang="ts"> import { highlightsSlides } from '@/constants'; import { pauseImg, playImg, replayImg } from '@/utils'; import { onMounted, ref } from 'vue'; import gsap from 'gsap'; import { store } from '@/store'; const playing = ref(false); const paused = ref(false); const carousel: any = ref(''); const progresses: any = ref(''); const currentVideoIndex = ref(0); let videos: HTMLVideoElement[] = []; let texts: HTMLElement[] = []; let progressBars: HTMLElement[] = []; const tl = gsap.timeline(); function setVideosRef(e: any) { if (e && !videos.includes(e)) { videos.push(e); } } function setTextsRef(e: any) { if (e && !texts.includes(e)) { texts.push(e); } } function setProgressBars(e: any) { if (e && !progressBars.includes(e)) { progressBars.push(e); } } /** * Calculate the width of the dot in the video carousel controller * @param {number} index The index of the video in the highlightsSlides array * @returns {string} The width of the dot in string format */ const dotWidth = (index: number): string => { /** * If the video is currently playing and the index matches the currentVideoIndex, * return a wide width. Otherwise, return a small width. */ let width: string; // for phone if (window.innerWidth < 760) { width = '40px'; } // for tablet else if (window.innerWidth < 1200) { width = '70px'; } // for laptop and larger else { width = '100px'; } return index === currentVideoIndex.value ? width : '12px'; }; /** * Play the next video in the video carousel * @param {number} index The index of the current video in the highlightsSlides array */ const playNextVideo = (index: number) => { // If the index is bigger than the number of videos, // stop the video and return (don't play the next video) if (index >= highlightsSlides.length - 1) { // Stop playing the video playing.value = false; paused.value = false; return; } const nextVideo = videos[index + 1]; // If there is no next video, stop here if (typeof nextVideo === 'undefined') { // Stop playing the video playing.value = false; paused.value = false; return; } nextVideo.play(); animateTexts(index + 1); animateSlideMovement(index + 1); animateProgress(index + 1); resetTexts(index); // Increment the currentVideoIndex value currentVideoIndex.value++; }; /** * Start the video carousel * Play the first video and set playing to true */ const start = (index: number = 0) => { if (!playing.value && !paused.value) { resetTexts(videos.length - 1); } const firstVideo = videos[index]; // play the first video playing.value = true; firstVideo.play(); // animation here animateTexts(index); animateSlideMovement(index); animateProgress(index); }; const restart = () => { // Reset everything currentVideoIndex.value = 0; // playing.value = true; paused.value = false; // Start the video carousel start(0); }; const togglePause = () => { playing.value = !playing.value; paused.value = !paused.value; const currentVideo = videos[currentVideoIndex.value]; if (currentVideo) { if (!playing.value) { currentVideo.pause(); if (tl && tl.isActive()) { tl.pause(); } } // else { currentVideo.play(); if (tl && tl.paused()) { tl.resume(); } } } }; /** * Go to a specific video in the video carousel * @param {number} index The index of the video in the highlightsSlides array */ const goToVide = (index: number) => { if (!playing.value || paused.value) { playing.value = true; paused.value = false; } const currentVideo = videos[currentVideoIndex.value]; currentVideo.pause(); currentVideo.currentTime = 0; // Update the currentVideoIndex value currentVideoIndex.value = index; // Start the video at the new index start(index); }; /** * Initialize the intersection observer to observe the carousel * When the carousel comes into the viewport, start the video */ const initIntersectionObserver = () => { /** * The options for the intersection observer * root: null means the viewport * rootMargin: 0px means the observer will trigger when the element is half in the viewport * threshold: 0.5 means the observer will trigger when the element is half in the viewport */ const options = { root: null, rootMargin: '0px', threshold: 0.5, }; /** * Create a new intersection observer * The observer will trigger the callback function when the carousel comes into the viewport */ const observer = new IntersectionObserver((entries) => { /** * Loop through all the entries * entries is an array of IntersectionObserverEntry objects */ entries.forEach((entry) => { /** * If the carousel is intersecting with the viewport */ if (entry.isIntersecting) { /** * Start the video * Disconnect the observer * To prevent the observer from triggering multiple times */ start(); observer.disconnect(); } }); }, options); /** * Get the carousel element */ const carouselElement = carousel.value; /** * Observe the carousel element */ observer.observe(carouselElement); }; const animateTexts = (index: number) => { // Animate the text at the given index gsap.to(texts[index], { x: '0', opacity: 1, duration: 1, delay: 0.5, ease: 'circ.inOut', }); }; const resetTexts = (index: number) => { gsap.to(texts[index], { x: '-100%', opacity: 0, duration: 1, ease: 'circ.inOut', }); }; const animateSlideMovement = (index: number) => { // Get the array of carousel cards let cards: HTMLElement[] = Array.from(carousel.value.children); // Calculate the width of a single card with the padding and gap let cardWidth = ref(cards[index].offsetWidth); // Calculate the new x position of the carousel based on the index of the slide to animate let newX: string = `-${index * cardWidth.value}px`; window.onresize = () => { cards = Array.from(carousel.value.children); cardWidth.value = cards[index].offsetWidth; newX = `-${index * cardWidth.value}px`; }; // Animate the carousel to the new x position gsap.to(carousel.value, { x: newX, duration: 1, ease: 'expo.inOut', }); }; const animateProgress = (index: number) => { const videoDuration = highlightsSlides[index].videoDuration * 1000; // Add the first animation to the timeline tl.to(progressBars[index], { width: '100%', duration: videoDuration / 1000, onComplete: () => { gsap.set(progressBars[index], { // opacity: 0, width: 0, delay: 0.5, ease: 'circ', }); }, }); // reset everything // tl.to(progressBars[index], { // width: '0', // }); // tl.to(progressBars[index], { // opacity: '100', // }); }; onMounted(() => { initIntersectionObserver(); }); </script>
import { IActivationContext, IActivationStrategy, ValidActivationLifecycle } from "../interfaces"; import { TransientActivationStrategy } from "./TransientActivationStrategy"; export class SingletonActivationStrategy implements IActivationStrategy { public static get shortName(): ValidActivationLifecycle { return "singleton"; } private instanceCache: Map<string, any>; private transientActivationStrategy: TransientActivationStrategy; constructor(transientActivationStrategy: TransientActivationStrategy) { this.transientActivationStrategy = transientActivationStrategy; this.instanceCache = new Map<string, any>(); } public activate(key: string, activationContext: IActivationContext) { if (!this.instanceCache.has(key)) { const instance = this.transientActivationStrategy.activate(key, activationContext); this.instanceCache.set(key, instance); } return this.instanceCache.get(key); } }
import React, { useState, useImperativeHandle } from 'react'; import { Input, Modal, Typography } from 'antd/lib'; import PropTypes from 'prop-types'; const { Text } = Typography; export const ApiKeyModal = React.forwardRef((props, ref) => { const [visible, setVisible] = useState(false); const handleOpen = () => { setVisible(true); }; const handleCancel = () => { setVisible(false); }; const handleSave = () => { props.onSave(); setVisible(false); }; useImperativeHandle(ref, () => ({ handleOpen, handleCancel, })); return ( <Modal title="Set OpenAI API Key" open={visible} onCancel={handleCancel} onOk={handleSave} okButtonProps={{ disabled: !props.apiKey }} > <Input type="password" placeholder="Enter your OpenAI API Key" value={props.apiKey} onChange={props.onChange} className="mb-8" /> <Text type="secondary"> <a href="https://platform.openai.com/signup" rel="noopener noreferrer" target="_blank" > Get your API key </a> . Note you must have a payment card on file. </Text> </Modal> ); }); ApiKeyModal.propTypes = { apiKey: PropTypes.string, onChange: PropTypes.func, onSave: PropTypes.func, }; ApiKeyModal.defaultProps = { apiKey: '', onChange: () => {}, onSave: () => {}, };
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Runtime.InteropServices; namespace System.Reflection.Emit { // Summary: // Represents a token that represents a string. public struct StringToken { // Summary: // Indicates whether two System.Reflection.Emit.StringToken structures are not // equal. // // Parameters: // a: // The System.Reflection.Emit.StringToken to compare to b. // // b: // The System.Reflection.Emit.StringToken to compare to a. // // Returns: // true if a is not equal to b; otherwise, false. public static bool operator !=(StringToken a, StringToken b); // // Summary: // Indicates whether two System.Reflection.Emit.StringToken structures are equal. // // Parameters: // a: // The System.Reflection.Emit.StringToken to compare to b. // // b: // The System.Reflection.Emit.StringToken to compare to a. // // Returns: // true if a is equal to b; otherwise, false. public static bool operator ==(StringToken a, StringToken b); // Summary: // Retrieves the metadata token for this string. // // Returns: // Read-only. Retrieves the metadata token of this string. public int Token { get; } // // Summary: // Indicates whether the current instance is equal to the specified System.Reflection.Emit.StringToken. // // Parameters: // obj: // The System.Reflection.Emit.StringToken to compare to the current instance. // // Returns: // true if the value of obj is equal to the value of the current instance; otherwise, // false. public bool Equals(StringToken obj); } }
//React----------------- import React, {useEffect} from "react"; import { useNavigate, useParams} from "react-router-dom"; //Components------------ import Carrousel from '../../components/Carrousel/Carrousel'; import Host from '../../components/Host/Host'; import Collapse from '../../components/Collapse/Collapse'; import Rate from '../../components/Rate/Rate'; import Tag from '../../components/Tag/Tag'; import Description from '../../components/Description/Description'; //Data------------------ import JSON from "../../components/data/logements.json" const FicheLogement = () => { // ce hook permet d'extraire l'id du logement à partir de l'URL. {id} lle permet d'extraire la propriété "id" de l'objet retourné par useParams() et de la stocker dans la variable id. const { id } = useParams(); console.log(id); const navigate = useNavigate // le find nous permet de trouver l'objet correspondant à l'id const appart = JSON.find((appart) => appart.id === id ); useEffect (() => { if (appart.length === 0) { navigate ("*") } }); return ( <div> <div> <Carrousel pictures={appart.pictures}/> </div> <div className="fiche_Container"> <div className="fiche_description" > <Description title={appart.title} location={appart.location}/> <Tag tags={appart.tags} /> </div> <div className="fiche_host"> <Host className="fiche_host" name={appart.host.name} picture={appart.host.picture} /> <Rate className="fiche_rate" rating={appart.rating}/> </div> <div className="fiche_collapse"> <Collapse title="Description" content={appart.description} /> </div> <Collapse className="collapse_equipments" title="Equipements" content={appart.equipments} /> </div> </div> ) }; export default FicheLogement;
import { MongoClient } from "mongodb"; import "dotenv/config"; import axios from "axios"; import { exit } from "process"; interface Stop { BusStopCode: string; RoadName: string; Description: string; Latitude: number; Longitude: number; } const getStops = async () => { if (!process.env.ACCOUNT_KEY) { throw "DataMall account key not found. Please enter it as an environment variable!"; } console.info("Fetching list of bus stops from the LTA..."); var stops: Array<Stop> = []; var skip = 0; var repeat = true; while (repeat) { const response = await axios.get( `http://datamall2.mytransport.sg/ltaodataservice/BusStops?$skip=${skip}`, { headers: { AccountKey: process.env.ACCOUNT_KEY, }, } ); const responseStops = response.data.value; if (responseStops.length === 0) { repeat = false; } else { stops = stops.concat(responseStops); skip += 500; } } return stops; }; const updateDatabase = async (stops: Stop[]) => { if (!process.env.MONGO_URI) { throw "MongoDB URI not found. Please enter it as an environment variable!"; } const client = new MongoClient(process.env.MONGO_URI); try { // Adds the retrieved stops to the database console.info("Updating MongoDB database..."); await client.connect(); const database = client.db("commute_db"); const stopsCollection = database.collection("bus_stops"); for (const stop of stops) { await stopsCollection.replaceOne( { BusStopCode: { $eq: stop.BusStopCode } }, stop, { upsert: true } ); } } finally { console.info("Update complete!"); await client.close(); return; } }; getStops().then((stops) => { console.info(`Retrieved! Found ${stops.length} bus stops.`); updateDatabase(stops).then(() => { console.info("Exiting..."); exit(); }); });
import { useCallback, useEffect } from 'react'; /** * Hook for preventing reloading or tab/browser closing when user has unsaved data * @param isReloadPrevented - allows to keep track on saved and unsaved user data */ export const usePreventReloadHook = (isReloadPrevented: boolean): void => { const preventReload = useCallback((event) => { const e = event; e.preventDefault(); e.returnValue = ''; }, []); useEffect(() => { if (isReloadPrevented) { window.addEventListener('beforeunload', preventReload); } return () => { if (isReloadPrevented) { window.removeEventListener('beforeunload', preventReload); } }; }, [isReloadPrevented, preventReload]); };
class Cliente { constructor(nombre, saldo) { this.nombre = nombre; this.saldo = saldo; } mostrarInformacion(){ return`Cliente: ${this.nombre}, tu saldo es de ${this.saldo}`; } static bienvenida(){ return`Bienvenido al cajero`; } } class Empresa extends Cliente{ constructor(nombre,saldo,telefono,categoria){ super(nombre, saldo); this.telefono = telefono; this.categoria = categoria; } static bienvenida(){ return`Bienvenido al cajero de empresas`; } } const juan = new Cliente('Juan', 405); const empresa = new Empresa('codigo con fran', 450, 10929, 'aprendiendo'); console.log(empresa); console.log(empresa.mostrarInformacion()); console.log(Cliente.bienvenida()); console.log(Empresa.bienvenida());
// ignore_for_file: use_build_context_synchronously import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:full_chat_application/core/utils/app_utils.dart'; import 'package:full_chat_application/features/chat_screen/manager/chat_cubit.dart'; import 'package:image_picker/image_picker.dart'; import 'package:permission_handler/permission_handler.dart'; import '../../manager/chat_state.dart'; class MessagesCompose extends StatefulWidget { const MessagesCompose({Key? key}) : super(key: key); @override State<MessagesCompose> createState() => _MessagesComposeState(); } class _MessagesComposeState extends State<MessagesCompose> with WidgetsBindingObserver { final TextEditingController _textController = TextEditingController(); late ChatCubit _appProvider; final ImagePicker _picker = ImagePicker(); @override void initState() { WidgetsBinding.instance.addObserver(this); super.initState(); } @override void didChangeDependencies() { super.didChangeDependencies(); _appProvider = BlocProvider.of<ChatCubit>(context); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _appProvider.cancelRecord(); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { switch (state) { case AppLifecycleState.paused: context.read<ChatCubit>().cancelRecord(); break; case AppLifecycleState.inactive: context.read<ChatCubit>().cancelRecord(); break; case AppLifecycleState.detached: context.read<ChatCubit>().cancelRecord(); break; case AppLifecycleState.resumed: break; } super.didChangeAppLifecycleState(state); } @override Widget build(BuildContext context) { return Row( children: [ BlocConsumer<ChatCubit, ChatState>( listener: (BuildContext context, state) { if (state.status == ChatStatus.unsupported) { buildShowSnackBar(context, "unsupported format"); } }, builder: (BuildContext context, state) { return Row( children: [ context.watch<ChatCubit>().startVoiceMessage == true ? SizedBox( width: MediaQuery.of(context).size.width - 55, child: Card( color: Colors.blueAccent, margin: const EdgeInsets.only( left: 5, right: 5, bottom: 8), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25)), child: Center( child: Padding( padding: const EdgeInsets.all(10), child: Text( state.recordTimer, style: const TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 15), ), )), )) : SizedBox( width: MediaQuery.of(context).size.width - 55, child: Card( color: Colors.blueAccent, margin: const EdgeInsets.only( left: 5, right: 5, bottom: 8), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25)), child: TextField( style: const TextStyle( color: Colors.white, ), controller: _textController, textAlignVertical: TextAlignVertical.center, keyboardType: TextInputType.multiline, maxLines: 5, minLines: 1, onChanged: (value) { if (value.isNotEmpty) { context.read<ChatCubit>().updateUserStatus( "typing....", context .read<ChatCubit>() .getCurrentUser()! .uid); context .read<ChatCubit>() .sendChatButtonChanged(true); } else { context.read<ChatCubit>().updateUserStatus( "Online", context .read<ChatCubit>() .getCurrentUser()! .uid); context .read<ChatCubit>() .sendChatButtonChanged(false); } }, decoration: InputDecoration( border: InputBorder.none, hintText: "Type your message", hintStyle: const TextStyle( color: Colors.white, ), suffixIcon: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( onPressed: () async { final status = await Permission .storage .request(); if (status == PermissionStatus.granted) { FilePickerResult? result = await FilePicker.platform .pickFiles(); context .read<ChatCubit>() .getReferenceFromStorage( result, ""); } else { await Permission.storage.request(); } }, icon: const Icon( Icons.attach_file, color: Colors.white, )), IconButton( onPressed: () async { final status = await Permission .storage .request(); if (status == PermissionStatus.granted) { final XFile? photo = await _picker.pickImage( source: ImageSource.camera); await context .read<ChatCubit>() .getReferenceFromStorage( photo, ""); } else { await Permission.storage.request(); } }, icon: const Icon( Icons.camera, color: Colors.white, )) ], ), contentPadding: const EdgeInsets.all(5), )), )), Padding( padding: const EdgeInsets.only(bottom: 8.0, right: 2), child: CircleAvatar( radius: 25, backgroundColor: Colors.blueAccent, child: IconButton( onPressed: () async { if (context.read<ChatCubit>().sendChatButton) { //txt message context.read<ChatCubit>().sendMessage( chatId: state.chatId, senderId: context .read<ChatCubit>() .getCurrentUser()! .uid, receiverId: context .read<ChatCubit>() .getPeerUserData()["userId"], receiverUsername: context .read<ChatCubit>() .getPeerUserData()["name"], msgTime: FieldValue.serverTimestamp(), msgType: "text", message: _textController.text.toString(), fileName: ""); context.read<ChatCubit>().notifyUser( context .read<ChatCubit>() .getCurrentUser()! .displayName, _textController.text.toString(), context .read<ChatCubit>() .getPeerUserData()["email"], context .read<ChatCubit>() .getCurrentUser()! .email); _textController.clear(); context .read<ChatCubit>() .sendChatButtonChanged(false); context.read<ChatCubit>().updateUserStatus( "Online", context .read<ChatCubit>() .getCurrentUser()! .uid); } else { final status = await Permission.microphone.request(); if (status == PermissionStatus.granted) { await context.read<ChatCubit>().initRecording(); if (context .read<ChatCubit>() .recorder .isRecording) { await context.read<ChatCubit>().stop(); } else { await context.read<ChatCubit>().record(); } } else { buildShowSnackBar( context, "You must enable record permission"); } // voice message } }, icon: Icon( context.read<ChatCubit>().sendChatButton ? Icons.send : context.read<ChatCubit>().startVoiceMessage == true ? Icons.stop : Icons.mic, color: Colors.white, )), ), ), ], ); }, ) ], ); } }
import "./Chatbot.css"; import { useState, useRef, useEffect } from "react"; import { Button, Icon } from 'semantic-ui-react'; import axios from 'axios'; function Chatbot() { // Refs for DOM elements const humanMessage = useRef(); const botMessage = useRef(); const input = useRef(); // Function to check the bot's status const checkStatus = (e) => { let isActive = true; const status = document.querySelector(".status"); if (isActive === true) { status.innerHTML = "Active"; status.style.color = "green"; } else { status.innerHTML = "Not Active"; status.style.color = "red"; } }; // Function to handle user input const handleInput = async () => { const inputRef = input.current; const getBotMessage = botMessage.current; const getHumanMessage = humanMessage.current; const status = document.querySelector(".status"); // Fetch prompts and answers from an external API using Axios try { const axiosResponse = await axios.get( "https://5c21-2404-7c00-41-b91a-fc35-251f-caca-2994.ngrok-free.app/prompts" ); if (axiosResponse.status === 200) { // If Axios request is successful const j_res = axiosResponse.data; const promptsAndAnswers = j_res.promptsAndAnswers; const userInput = inputRef.value.toLowerCase(); // Iterate through promptsAndAnswers to handle pattern conversion const matchedResponse = promptsAndAnswers.find(({ pattern }) => { try { const regex = new RegExp(pattern, 'i'); // 'i' for case-insensitive return regex.test(userInput); } catch (error) { return false; // Handle invalid regular expressions } }); if (matchedResponse) { getBotMessage.innerText = "Typing..."; setTimeout(() => { getBotMessage.innerText = matchedResponse.message; if (matchedResponse.setStatus) { status.innerText = matchedResponse.setStatus; status.style.color = matchedResponse.color; } inputRef.value = ""; // Clear the input }, 2000); } getHumanMessage.innerText = userInput; // Display the message return; } } catch (error) { // Handle Axios error or non-successful response console.error("Axios error:", error); } // If Axios request fails, try a basic fetch try { const fetchResponse = await fetch( "https://gamingapple0.github.io/prompts_api/prompts.json" ); if (!fetchResponse.ok) { throw new Error(`Failed to fetch data. Status: ${fetchResponse.status}`); } const j_res = await fetchResponse.json(); const promptsAndAnswers = j_res.promptsAndAnswers; const userInput = inputRef.value.toLowerCase(); const matchedResponse = promptsAndAnswers.find(({ pattern }) => { try { const regex = new RegExp(pattern, 'i'); return regex.test(userInput); } catch (error) { return false; } }); if (matchedResponse) { getBotMessage.innerText = "Typing..."; setTimeout(() => { getBotMessage.innerText = matchedResponse.message; if (matchedResponse.setStatus) { status.innerText = matchedResponse.setStatus; status.style.color = matchedResponse.color; } inputRef.value = ""; }, 2000); } getHumanMessage.innerText = userInput; } catch (error) { console.error("Error fetching data:", error); } }; // Function to close the chat const closeChat = () => { const chatElement = document.getElementById("chat"); const chatMin = document.getElementById("chat-closed"); if (chatElement) { chatElement.classList.add("rem-chat"); } if (chatMin) { chatMin.style.display = "block"; } }; // Function to open the chat const openChat = () => { const chatElement = document.getElementById("chat"); const chatMin = document.getElementById("chat-closed"); if (chatElement) { chatElement.classList.remove("rem-chat"); } if (chatMin) { chatMin.style.display = "none"; } }; return ( <div className="App" onLoad={checkStatus}> <div id="chat" className="wrapper rem-chat"> <div className="content"> <div style={{ "box-sizing": "revert" }} className="header"> <div className="img"> <img src="https://cdn-icons-png.flaticon.com/512/4711/4711987.png" alt="Bot Pic" /> </div> <div className="right"> <div className="name">ChatBot</div> <div className="status">Active</div> </div> <Button icon id="close-butt" onClick={closeChat}> <Icon name="close" /> </Button> </div> <div className="main"> <div className="main_content"> <div className="messages"> <div className="bot-message" id="message1" ref={botMessage} ></div> <div className="human-message" id="message2" ref={humanMessage} ></div> </div> </div> </div> <div className="bottom"> <div className="btm"> <div className="input"> <input type="text" id="input" placeholder="Enter your message" ref={input} /> </div> <div className="btn"> <button onClick={handleInput}> <i className="fas fa-paper-plane"></i>Send </button> </div> </div> </div> </div> </div> <Button onClick={openChat} id="chat-closed" icon> <Icon name="chat" /> </Button> </div> ); } export default Chatbot;
import os import re import regex import string import numpy as np import pandas as pd from scipy.sparse import spmatrix from qdrant_client import QdrantClient from sklearn.metrics.pairwise import cosine_similarity from pyarabic.araby import strip_tashkeel, strip_tatweel def remove_space_in_tatweel(text): return re.sub(r'ـ\s+(\w)', r'ـ\1', text) def contains_english_letters(text : str) -> bool: all_letters = string.ascii_letters return any(char in all_letters for char in text) def remove_english_letters(text : str) -> str: if contains_english_letters(text) == False: return text all_letters = string.ascii_letters for char in text: if char in all_letters: text = text.replace(char, ' ') return re.sub(r'\s+', ' ', text) def count_words(text : str) -> int: return len(text.split()) def check_tashkeel(text : str) -> bool: if text == strip_tashkeel(text): return False return True def check_tatweel(text : str) -> bool: if text == strip_tatweel(text): return False return True def remove_extra_space(text : str) -> str: text = re.sub( r'(\S)\s*([:،.\{\}\[\]\(\)<>؟!،])\s*(?=\s)', r'\1\2', re.sub(r'\{\s*(.*?)\s*\}', r'{\1}', re.sub(r'\[\s*(.*?)\s*\]', r'[\1]', re.sub(r'\(\s*(.*?)\s*\)', r'(\1)', re.sub(r'<\s*(.*?)\s*>', r'<\1>', text) ) ) ) ) return re.sub(r'\s+', ' ', text) def count_words_in_list(lst : list[str]) -> tuple[int, int, int]: count_words = 0 count_tashkeel = 0 count_tatweel = 0 for text in lst: try: splitted_text = text.split() except: continue for word in splitted_text: if check_tashkeel(word) == True: count_tashkeel += 1 if check_tatweel(word) == True: count_tatweel += 1 count_words += 1 return count_words, count_tashkeel, count_tatweel def split_data(df : pd.DataFrame, isTashkeel : bool = False) -> tuple[list, list, list]: new_text_lst = [] new_num_tashkeel_lst = [] new_num_tatweel_lst = [] new_num_words_lst = [] word_count = 2 for _, row in df.iterrows(): if word_count == 1: word_count = 2 left_split_count = 0 right_split_count = word_count splitted_text = row[0].split() if isTashkeel == True: splitted_text_tashkeel = row[1].split() if len(splitted_text) <= 10: new_text_splitted = splitted_text[left_split_count:right_split_count] new_text = " ".join(new_text_splitted) num_words, num_tashkeel, num_tatweel = count_words_in_list(new_text_splitted) if isTashkeel == True: new_text_tashkeel_splitted = splitted_text_tashkeel[left_split_count:right_split_count] new_text_tashkeel = " ".join(new_text_tashkeel_splitted) new_text_lst.append((new_text, new_text_tashkeel)) else: new_text_lst.append(new_text) new_num_tashkeel_lst.append(num_tashkeel) new_num_tatweel_lst.append(num_tatweel) new_num_words_lst.append(num_words) continue remaineded_length = len(splitted_text) while right_split_count <= len(splitted_text): new_text_splitted = splitted_text[left_split_count:right_split_count] new_text = " ".join(new_text_splitted) num_words, num_tashkeel, num_tatweel = count_words_in_list(new_text_splitted) if isTashkeel == True: new_text_tashkeel_splitted = splitted_text_tashkeel[left_split_count:right_split_count] new_text_tashkeel = " ".join(new_text_tashkeel_splitted) new_text_lst.append((new_text, new_text_tashkeel)) else: new_text_lst.append(new_text) new_num_tashkeel_lst.append(num_tashkeel) new_num_tatweel_lst.append(num_tatweel) new_num_words_lst.append(num_words) remaineded_length -= word_count word_count = (word_count % 10) + 1 if word_count == 1: word_count = 2 left_split_count = right_split_count right_split_count += word_count else: new_text_splitted = splitted_text[left_split_count:len(splitted_text)] if len(new_text_splitted) > 0: new_text = " ".join(new_text_splitted) num_words, num_tashkeel, num_tatweel = count_words_in_list(splitted_text[left_split_count:len(splitted_text)]) if isTashkeel == True: new_text_tashkeel_splitted = splitted_text_tashkeel[left_split_count:len(splitted_text)] new_text_tashkeel = " ".join(new_text_tashkeel_splitted) new_text_lst.append((new_text, new_text_tashkeel)) else: new_text_lst.append(new_text) new_num_tashkeel_lst.append(num_tashkeel) new_num_tatweel_lst.append(num_tatweel) new_num_words_lst.append(num_words) word_count = (word_count % 10) + 1 return new_text_lst, new_num_tashkeel_lst, new_num_tatweel_lst, new_num_words_lst def find_similarity(df : pd.DataFrame, query_vec : spmatrix, tfidf : spmatrix, index : int, size : int) -> tuple[pd.DataFrame, np.ndarray]: similarity = cosine_similarity(query_vec, tfidf).flatten() indices = np.argpartition(similarity, -size)[-size:] result = df.iloc[indices][::-1] return result, similarity[indices][::-1] def remove_arabic_stop_words(sentence : str, stop_words : set[str] | None, punc_pattern : regex.Pattern[str]) -> str: removed_punc_sentence = punc_pattern.sub('', sentence) splitted_sentence = removed_punc_sentence.split() if stop_words != None: removed_stop_words_sentence = [word for word in splitted_sentence if word not in stop_words] return ' '.join(removed_stop_words_sentence) if stop_words != None else ' '.join(splitted_sentence) def get_client(): return QdrantClient( url=os.getenv("QDRANT_DB_URL"), api_key=os.getenv("QDRANT_API_KEY") ) def get_similar_records(query_vector, chunks, client : QdrantClient): similar_records = [] for chunk_id in chunks: result = client.recommend( positive=[query_vector], collection_name=f"arabic_setences_chunk_{chunk_id}", limit=10 ) similar_records.extend(result['result']) return similar_records def find_similar_records_across_chunks(query_vector, num_chunks=270): chunk_ids = range(0, num_chunks+1) similar_records = get_similar_records(query_vector, chunk_ids) unique_records = {} for record in similar_records: record_id = record['payload']['id'] if record_id not in unique_records: unique_records[record_id] = record similar_records = list(unique_records.values()) return similar_records
package com.example.intranet.entities.UserEntity; import com.example.intranet.entities.ProjectEntity.Task; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Entity @Builder @Data @AllArgsConstructor public class Users implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String firstName; private String lastName; private String email; private String passWord; private String adresse; private String phoneNumber; @Enumerated(EnumType.STRING) private Role role; @OneToMany(mappedBy = "user",cascade = CascadeType.REMOVE) List<Task> tasks =new ArrayList<>(); public Users() { } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return role.getAuthorities(); } @Override public String getPassword() { return passWord; } @Override public String getUsername() { return email; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
import { Trans } from '@lingui/macro' import { sendAnalyticsEvent } from '@uniswap/analytics' import { InterfaceEventName } from '@uniswap/analytics-events' import { useWeb3React } from '@web3-react/core' import fiatMaskUrl from 'assets/svg/fiat_mask.svg' import { BaseVariant } from 'featureFlags' import { useFiatOnrampFlag } from 'featureFlags/flags/fiatOnramp' import { useCallback, useEffect } from 'react' import { X } from 'react-feather' import { useToggleWalletDropdown } from 'state/application/hooks' import { useAppSelector } from 'state/hooks' import { useFiatOnrampAck } from 'state/user/hooks' import styled from 'styled-components/macro' import { ThemedText } from 'theme' import { isMobile } from 'utils/userAgent' const Arrow = styled.div` top: -4px; height: 16px; position: absolute; right: 16px; width: 16px; ::before { background: hsl(315.75, 93%, 83%); border-top: none; border-left: none; box-sizing: border-box; content: ''; height: 16px; position: absolute; transform: rotate(45deg); width: 16px; } ` const ArrowWrapper = styled.div` position: absolute; right: 16px; top: 90%; width: 100%; max-width: 320px; min-height: 92px; @media screen and (min-width: ${({ theme }) => theme.breakpoint.lg}px) { right: 36px; } ` const CloseIcon = styled(X)` color: white; cursor: pointer; position: absolute; top: 8px; right: 8px; z-index: 1; ` const Wrapper = styled.button` background: radial-gradient(105% 250% at 100% 5%, hsla(318, 95%, 85%) 1%, hsla(331, 80%, 75%, 0.1) 84%), linear-gradient(180deg, hsla(296, 92%, 67%, 0.5) 0%, hsla(313, 96%, 60%, 0.5) 130%); background-color: hsla(297, 93%, 68%, 1); border-radius: 12px; border: none; cursor: pointer; outline: none; overflow: hidden; position: relative; text-align: start; max-width: 320px; min-height: 92px; width: 100%; :before { background-image: url(${fiatMaskUrl}); background-repeat: no-repeat; content: ''; height: 100%; position: absolute; right: -154px; // roughly width of fiat mask image top: 0; width: 100%; } ` const Header = styled(ThemedText.SubHeader)` color: white; margin: 0; padding: 12px 12px 4px; position: relative; ` const Body = styled(ThemedText.BodySmall)` color: white; margin: 0 12px 12px 12px !important; position: relative; ` const ANNOUNCEMENT_RENDERED = 'FiatOnrampAnnouncement-rendered' const ANNOUNCEMENT_DISMISSED = 'FiatOnrampAnnouncement-dismissed' const MAX_RENDER_COUNT = 3 export function FiatOnrampAnnouncement() { const { account } = useWeb3React() const [acks, acknowledge] = useFiatOnrampAck() useEffect(() => { if (!sessionStorage.getItem(ANNOUNCEMENT_RENDERED)) { acknowledge({ renderCount: acks?.renderCount + 1 }) sessionStorage.setItem(ANNOUNCEMENT_RENDERED, 'true') } }, [acknowledge, acks]) const handleClose = useCallback(() => { localStorage.setItem(ANNOUNCEMENT_DISMISSED, 'true') }, []) const toggleWalletDropdown = useToggleWalletDropdown() const handleClick = useCallback(() => { sendAnalyticsEvent(InterfaceEventName.FIAT_ONRAMP_BANNER_CLICKED) toggleWalletDropdown() acknowledge({ user: true }) }, [acknowledge, toggleWalletDropdown]) const fiatOnrampFlag = useFiatOnrampFlag() const openModal = useAppSelector((state) => state.application.openModal) if ( !account || acks?.user || fiatOnrampFlag === BaseVariant.Control || localStorage.getItem(ANNOUNCEMENT_DISMISSED) || acks?.renderCount >= MAX_RENDER_COUNT || isMobile || openModal !== null ) { return null } return ( <ArrowWrapper> <Arrow /> <CloseIcon onClick={handleClose} data-testid="FiatOnrampAnnouncement-close" /> <Wrapper onClick={handleClick}> <Header> <Trans>Buy crypto</Trans> </Header> <Body> <Trans>Get tokens at the best prices in web3 on Uniswap, powered by Moonpay.</Trans> </Body> </Wrapper> </ArrowWrapper> ) }
package com.ucatolica.ecommerce.model; import jakarta.persistence.*; //import javax.persistence.*; import java.util.Date; import java.util.UUID; /** * Clase que representa un token de autenticación asociado a un usuario en el sistema de comercio electrónico. */ @Entity @Table(name = "tokens") public class AuthenticationToken { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; // Identificador único del token. private String token; // Valor del token generado. @Column(name = "created_date") private Date createdDate; // Fecha de creación del token. @OneToOne(targetEntity = User.class, fetch = FetchType.EAGER) @JoinColumn(nullable = false, name = "user_id") private User user; // Usuario asociado al token. /** * Crea una nueva instancia de la clase `AuthenticationToken` asociada a un usuario. * * @param user El usuario al que se asocia el token. */ public AuthenticationToken(User user) { this.user = user; this.createdDate = new Date(); this.token = UUID.randomUUID().toString(); // Genera un token único utilizando UUID. } /** * Obtiene el identificador único del token. * * @return El identificador único del token. */ public Integer getId() { return id; } /** * Establece el identificador único del token. * * @param id El identificador único del token. */ public void setId(Integer id) { this.id = id; } /** * Obtiene el valor del token generado. * * @return El valor del token generado. */ public String getToken() { return token; } /** * Establece el valor del token generado. * * @param token El valor del token generado. */ public void setToken(String token) { this.token = token; } /** * Obtiene la fecha de creación del token. * * @return La fecha de creación del token. */ public Date getCreatedDate() { return createdDate; } /** * Establece la fecha de creación del token. * * @param createdDate La fecha de creación del token. */ public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } /** * Obtiene el usuario asociado al token. * * @return El usuario asociado al token. */ public User getUser() { return user; } /** * Establece el usuario asociado al token. * * @param user El usuario asociado al token. */ public void setUser(User user) { this.user = user; } /** * Crea una nueva instancia de la clase `AuthenticationToken` con los parámetros especificados. * * @param id Identificador único del token. * @param token Valor del token generado. * @param createdDate Fecha de creación del token. * @param user Usuario asociado al token. */ public AuthenticationToken(Integer id, String token, Date createdDate, User user) { this.id = id; this.token = token; this.createdDate = createdDate; this.user = user; } /** * Crea una nueva instancia de la clase `AuthenticationToken`. */ public AuthenticationToken() { } }
<?php /** * PHPUnit bootstrap file * * @package Theme-Directory-Tests */ // Require composer dependencies. require_once dirname( dirname( dirname( __FILE__ ) ) ) . '/vendor/autoload.php'; // Determine the tests directory (from a WP dev checkout). // Try the WP_TESTS_DIR environment variable first. $_tests_dir = getenv( 'WP_TESTS_DIR' ); // Next, try the WP_PHPUNIT composer package. if ( ! $_tests_dir ) { $_tests_dir = getenv( 'WP_PHPUNIT__DIR' ); } // Fallback. if ( ! $_tests_dir ) { $_tests_dir = '/tmp/wordpress-tests-lib'; } // Give access to tests_add_filter() function. require_once $_tests_dir . '/includes/functions.php'; /** * Manually load the plugin being tested. */ function _manually_load_plugin() { require_once WP_CONTENT_DIR . '/plugins/theme-check/theme-check.php'; require_once WP_CONTENT_DIR . '/plugins/theme-check/checkbase.php'; require_once WP_CONTENT_DIR . '/plugins/theme-check/main.php'; // @todo Do we need to load the theme itself? } tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' ); /** * Adds a wp_die handler for use during tests. * * If bootstrap.php triggers wp_die, it will not cause the script to fail. This * means that tests will look like they passed even though they should have * failed. So we throw an exception if WordPress dies during test setup. This * way the failure is observable. * * @param string|WP_Error $message The error message. * * @throws Exception When a `wp_die()` occurs. */ function fail_if_died( $message ) { if ( is_wp_error( $message ) ) { $message = $message->get_error_message(); } throw new Exception( 'WordPress died: ' . $message ); } tests_add_filter( 'wp_die_handler', 'fail_if_died' ); // Start up the WP testing environment. require $_tests_dir . '/includes/bootstrap.php'; // Use existing behavior for wp_die during actual test execution. remove_filter( 'wp_die_handler', 'fail_if_died' );
import pytest from gitjudge.entity import DiffList, DiffIndex def test_create_diff_with_addition_and_deletion(): diff = """\ diff --git a/file.md b/file.md index f63f268..4afe310 100644 --- a/file.md +++ b/file.md @@ -3,3 +3,4 @@ ## Un -Del -Del +Add """ difflist = DiffList() difflist.from_show_output(diff) assert len(difflist.diffs) == 1 assert "file.md" in difflist.diffs assert difflist.diffs["file.md"].file_path == "file.md" assert difflist.diffs["file.md"].additions == {"Add": 1} assert difflist.diffs["file.md"].deletions == {"Del": 2} def test_create_diff_with_addition_and_deletion_merge_commit(): diff = """\ diff --cc file.md index f63f268,4afe310..4afe310 --- a/file.md +++ b/file.md @@@ -3,3 -3,4 +3,4 @@@ ## Un -Del - Del + Add +Add """ difflist = DiffList() difflist.from_show_output(diff) assert len(difflist.diffs) == 1 assert "file.md" in difflist.diffs assert difflist.diffs["file.md"].file_path == "file.md" assert difflist.diffs["file.md"].additions == {"Add": 2} assert difflist.diffs["file.md"].deletions == {"Del": 2} def test_create_diff_with_multiple_files(): diff = """\ diff --git a/file.md b/file.md index f63f268..4afe310 100644 --- a/file.md +++ b/file.md @@ -3,3 +3,4 @@ ## Un -Del +Add diff --cc b/file2.md index f63f268..4afe310 100644 --- a/file2.md +++ b/file2.md @@@ -3,3 +3,4 @@ ## Un - Del -Del + Add +Add """ difflist = DiffList() difflist.from_show_output(diff) assert len(difflist.diffs) == 2 assert "file.md" in difflist.diffs assert "file2.md" in difflist.diffs assert difflist.diffs["file.md"].file_path == "file.md" assert difflist.diffs["file.md"].additions == {"Add": 1} assert difflist.diffs["file.md"].deletions == {"Del": 1} assert difflist.diffs["file2.md"].file_path == "file2.md" assert difflist.diffs["file2.md"].additions == {"Add": 2} assert difflist.diffs["file2.md"].deletions == {"Del": 2} def test_create_diff_commit_info(): diff = """\ commit f6aca2d2b135a47cb3a4064075490267b2d16250 Author: Joan Puigcerver <[email protected]> Date: Mon Feb 26 11:20:23 2024 +0100 2. added title to file1.md diff --git a/file1.md b/file1.md index e69de29..ccd0f29 100644 --- a/file1.md +++ b/file1.md @@ -0,0 +1 @@ +# Populated repo """ difflist = DiffList() difflist.from_show_output(diff) assert len(difflist.diffs) == 1 assert "file1.md" in difflist.diffs assert difflist.diffs["file1.md"].file_path == "file1.md" assert difflist.diffs["file1.md"].additions == {"# Populated repo": 1} assert difflist.diffs["file1.md"].deletions == {}
import 'package:exam_reminder/localization/app_localizations.dart'; import 'package:exam_reminder/screens/home/home.dart'; import 'package:exam_reminder/screens/settings/src/locale_selector.dart'; import 'package:exam_reminder/screens/settings/src/theme_selector.dart'; import 'package:exam_reminder/screens/welcome/methods.dart'; import 'package:exam_reminder/widgets/title_bar.dart'; import 'package:flutter/material.dart'; class WelcomeScreen extends StatelessWidget { const WelcomeScreen({super.key}); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; return Scaffold( appBar: AppBar( title: Text(AppLocalizations.of(context)!.welcomeTitle), flexibleSpace: const TitleBarWindowDraggable(), actions: const [ TitleBarButtons(), ], centerTitle: true, ), body: SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ Padding( padding: const EdgeInsets.only(top: 10), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: width, child: Text( AppLocalizations.of(context)!.welcomeSubTitle, style: Theme.of(context).textTheme.bodyLarge, textAlign: TextAlign.center, ), ), ], ), ), ], ), const Column( children: [ ThemeSelector(), LocalizationSelector(), ], ), ElevatedButton( onPressed: () async { if (await disableWelcomeScreen()) { Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (_) => const HomeScreen()), ); } }, child: Text(AppLocalizations.of(context)!.welcomeDoneButton), ), ], ), ), ); } }
<?php namespace App\Repositories; class Repository { /** * Get's a model by it's ID * * @param int * @return collection */ public function get($questionnaire_id) { return Questionnaire::find($questionnaire_id); } /** * Get's all models. * * @return mixed */ public function all() { return Questionnaire::all(); } /** * Deletes a questionnaire. * * @param int */ public function delete($questionnaire_id) { Questionnaire::destroy($questionnaire_id); } /** * Updates a questionnaire. * * @param int * @param array */ public function update($questionnaire_id, array $questionnaire_data) { Questionnaire::find($questionnaire_id)->update($questionnaire_data); } }
package ManageVehicle; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.CheckBox; import javafx.scene.control.DatePicker; import javafx.scene.control.TextField; public class AddVehicleController { @FXML private TextField vehicleTypeField; @FXML private TextField vehicleModelField; @FXML private TextField registrationNumberField; @FXML private TextField vehicleCapacityField; @FXML private TextField accidentalStatusField; @FXML private TextField fuelEfficiencyField; @FXML private TextField driverIdField; @FXML private TextField routeIdField; @FXML private CheckBox tokenStatusCheckbox; @FXML private TextField tokenNumberField; @FXML private TextField tokenTypeField; @FXML private DatePicker tokenIssueDateField; @FXML private DatePicker tokenExpiryDateField; // SQLite database connection private Connection conn; PreparedStatement pstmt; // Define the database URL, username, and password private static final String DB_URL = "jdbc:sqlite:.\\src\\Database\\Transport_System.db"; private static final String DB_USER = ""; private static final String DB_PASSWORD = ""; @FXML void SaveRecord(ActionEvent event) { // get the values from the text fields and checkboxes String vehicleType = vehicleTypeField.getText(); String vehicleModel = vehicleModelField.getText(); String registrationNumber = registrationNumberField.getText(); String vehicleCapacity = vehicleCapacityField.getText(); String accidentalStatus = accidentalStatusField.getText(); String fuelEfficiency = fuelEfficiencyField.getText(); String driverId = driverIdField.getText(); String routeId = routeIdField.getText(); boolean tokenStatus = tokenStatusCheckbox.isSelected(); String tokenNumber = tokenNumberField.getText(); String tokenType = tokenTypeField.getText(); String tokenIssueDate = tokenIssueDateField.getValue().toString(); String tokenExpiryDate = tokenExpiryDateField.getValue().toString(); // prepare the SQL statement to insert the vehicle record into the database String sqlQuery = "INSERT INTO vehicles (vehicle_type, vehicle_model, registration_number, " + "vehicle_capacity, vehicle_occupation, accidental_status, fuel_efficiency, driver_id, route_id, " + "token_status, token_number, token_type, token_issue_date, token_expiry_date) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try { conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); pstmt = conn.prepareStatement(sqlQuery); pstmt.setString(1, vehicleType); pstmt.setString(2, vehicleModel); pstmt.setString(3, registrationNumber); pstmt.setString(4, vehicleCapacity); pstmt.setString(5, ""); pstmt.setString(6, accidentalStatus); pstmt.setString(7, fuelEfficiency); pstmt.setString(8, driverId); pstmt.setString(9, routeId); pstmt.setBoolean(10, tokenStatus); if (tokenStatusCheckbox.isSelected()) { pstmt.setString(11, tokenNumber); pstmt.setString(12, tokenType); pstmt.setString(13, tokenIssueDate); pstmt.setString(14, tokenExpiryDate); } pstmt.executeUpdate(); // Alert message showed after Record saved Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Success"); alert.setContentText("Vehicle data has been saved to the database.\n Vehicle Registration #: " + registrationNumberField.getText()); alert.showAndWait(); // clear textfields after saving record vehicleTypeField.setText(""); vehicleModelField.setText(""); registrationNumberField.setText(""); vehicleCapacityField.setText(""); accidentalStatusField.setText(""); fuelEfficiencyField.setText(""); driverIdField.setText(""); routeIdField.setText(""); tokenNumberField.setText(""); tokenTypeField.setText(""); tokenIssueDateField.setValue(null); tokenExpiryDateField.setValue(null); } catch (SQLException e) { // Alert message showed after Record saved Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Failed!"); alert.setContentText("Error! Vehicle record is not saved: " + e.getMessage()); alert.showAndWait(); } finally { // Close the connection in the finally block if (conn != null) { try { conn.close(); pstmt.close(); } catch (SQLException e) { } } } } @FXML public void initialize() { tokenNumberField.setVisible(false); tokenTypeField.setVisible(false); tokenExpiryDateField.setVisible(false); tokenIssueDateField.setVisible(false); tokenStatusCheckbox.setOnAction(e -> { if (tokenStatusCheckbox.isSelected()) { tokenNumberField.setVisible(true); tokenTypeField.setVisible(true); tokenExpiryDateField.setVisible(true); tokenIssueDateField.setVisible(true); } else if (!tokenStatusCheckbox.isSelected()) { tokenNumberField.setVisible(false); tokenTypeField.setVisible(false); tokenExpiryDateField.setVisible(false); tokenIssueDateField.setVisible(false); } }); } }
#include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <OneWire.h> #include <DallasTemperature.h> #define TEMPSENSORCOUNTS 10 String tempSensorsArr[TEMPSENSORCOUNTS]; String stringData; const char* ssid = ""; const char* password = ""; //Your Domain name with URL path or IP address with path const char* serverName = "http://piec.herokuapp.com/postTemp/"; String sensor0 = "NA"; String sensor1 = "NA"; String dateTimeZone = "NA"; // Date time zone String dStr = "{\"dtm\":\"NA\""; OneWire oneWire(D7); DallasTemperature sensors(&oneWire); String serverAnswer; void setup() { Serial.begin(115200); sensors.begin(); WiFi.begin(ssid, password); Serial.println("Connecting"); while(WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to WiFi network with IP Address: "); Serial.println(WiFi.localIP()); } void loop() { getTempFromSensor(); dStr = "{\"dtm\":\"NA\""; for(int n = 0; n < TEMPSENSORCOUNTS; n++){ dStr += ",\"sensor" + String(n) + "\":\"" + tempSensorsArr[n] + "\""; } dStr += "}"; Serial.println(dStr); //Check WiFi connection status if(WiFi.status()== WL_CONNECTED){ serverAnswer = httpSendPost(serverName, dStr); Serial.println(serverAnswer); } else { Serial.println("WiFi Disconnected"); } delay(300000); } void getTempFromSensor(){ sensors.requestTemperatures(); for(int a = 0; a < TEMPSENSORCOUNTS; a++){ float t = sensors.getTempCByIndex(a); Serial.print("a= "); Serial.println(a); Serial.print("t= "); Serial.println(t); tempSensorsArr[a] = String(t); Serial.print("tempSensorsArr[a] = "); Serial.println(tempSensorsArr[a]); if(t <= -127){ tempSensorsArr[a] = "NA"; } } } String httpSendPost(const char* serverName, String dataStr) { WiFiClient client; HTTPClient http; // Your IP address with path or Domain name with URL path http.begin(client, serverName); http.addHeader("Content-Type", "application/json"); Serial.print("{\"dtm\":\"PL\",\"sensor0\":" + tempSensorsArr[0] + "\"}"); // Send HTTP POST request int httpResponseCode = http.POST(dStr); String payload = "{}"; if (httpResponseCode>0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); payload = http.getString(); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); } // Free resources http.end(); return payload; }
// // Created by Nicolaescu Raoul on 24.04.2023. // #ifndef LAB_6_REPOSITORY_H #define LAB_6_REPOSITORY_H #include <iostream> template <class Class> class Repository { private: Class* list; int size; public: Repository(); Repository(const Repository<Class>& other); ~Repository(); Class* getList()const; int getSize()const; void setList(Class* newList); void setSize(int newSize); void addElement(Class newElement); void deleteElement(int position); void updateElement(int position, Class newElement); Class getElement(int position); int findElement(Class element); void printAll(); void bubbleSort(); Repository<Class>& operator=(const Repository<Class>& newRepo); }; template<class Class> inline Repository<Class>::Repository() { this->setList(nullptr); this->setSize(0); } template<class Class> inline Repository<Class>::~Repository() { delete[] list; list = nullptr; } template<class Class> inline Class* Repository<Class>::getList()const { return list; } template<class Class> inline int Repository<Class>::getSize()const { return size; } template<class Class> inline void Repository<Class>::setList(Class* newList) { this->list = newList; } template<class Class> inline void Repository<Class>::setSize(int newSize) { size = newSize; } template<class Class> inline void Repository<Class>::addElement(Class newElement) { Class* temp; temp = new Class[this->getSize() + 1]; for (int i = 0; i < this->getSize(); i++) { temp[i] = this->getElement(i); } temp[this->getSize()] = newElement; delete[] this->list; this->setList(temp); this->setSize(this->getSize() + 1); } template<class Class> inline void Repository<Class>::deleteElement(int position) { Class* temp; temp = new Class[this->getSize() - 1]; for (int i = 0; i < this->getSize() - 1; i++) { if (i == position) { temp[i] = this->getElement(this->getSize() - 1); } else { temp[i] = this->getElement(i); } } this->setSize(this->getSize() - 1); this->setList(temp); } template<class Class> inline void Repository<Class>::updateElement(int position, Class newElement) { this->list[position] = newElement; } template<class Class> inline Class Repository<Class>::getElement(int position) { return list[position]; } template<class Class> inline int Repository<Class>::findElement(Class element) { int i = 0; if (this->getSize() == 0)return -1; while (this->getElement(i) != element && i != this->getSize()) i++; if (i == this->getSize()) return -1; return i; } template<class Class> inline void Repository<Class>::printAll() { for (int i = 0; i < this->getSize(); i++) { std::cout << this->getElement(i) << "\n"; } } template<class Class> inline void Repository<Class>::bubbleSort() { for (int i = 0; i < this->getSize() - 1; i++) { for (int j = 0; j < this->getSize() - i - 1; j++) { if (this->getElement(j) > this->getElement(j + 1)) { Class temp = this->getElement(j); this->updateElement(j, this->getElement(j + 1)); this->updateElement(j + 1, temp); } } } } template<class Class> inline Repository<Class>& Repository<Class>::operator=(const Repository<Class>& other) { if (this != &other) { delete[] this->list; this->setSize(other.getSize()); this->list = new Class[other.getSize()]; for (int i = 0; i < other.getSize(); i++) { this->list[i] = other.list[i]; } } return *this; } template<class Class> Repository<Class>::Repository(const Repository<Class>& other) { this->setSize(other.getSize()); this->list = new Class[other.getSize()]; for (int i = 0; i < other.getSize(); i++) { this->list[i] = other.list[i]; } } #endif //LAB_6_REPOSITORY_H
/* * #%L * de-metas-camel-sap * %% * Copyright (C) 2022 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.camel.externalsystems.sap.product; import com.google.common.annotations.VisibleForTesting; import de.metas.camel.externalsystems.common.IdAwareRouteBuilder; import de.metas.camel.externalsystems.common.PInstanceLogger; import de.metas.camel.externalsystems.common.PInstanceUtil; import de.metas.camel.externalsystems.common.ProcessLogger; import de.metas.camel.externalsystems.common.mapping.ExternalMappingsHolder; import de.metas.camel.externalsystems.common.v2.ProductUpsertCamelRequest; import de.metas.camel.externalsystems.sap.config.ProductFileEndpointConfig; import de.metas.camel.externalsystems.sap.model.product.ProductRow; import de.metas.common.externalsystem.JsonExternalSystemRequest; import de.metas.common.rest_api.common.JsonMetasfreshId; import de.metas.common.util.Check; import lombok.Builder; import lombok.Getter; import lombok.NonNull; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.RuntimeCamelException; import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat; import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.MF_ERROR_ROUTE_ID; import static de.metas.camel.externalsystems.common.ExternalSystemCamelConstants.MF_UPSERT_PRODUCT_V2_CAMEL_URI; import static de.metas.camel.externalsystems.sap.SAPConstants.DEFAULT_PRODUCT_CATEGORY_ID; import static org.apache.camel.builder.endpoint.StaticEndpointBuilders.direct; public class GetProductsFromFileRouteBuilder extends IdAwareRouteBuilder { @VisibleForTesting public static final String UPSERT_PRODUCT_ENDPOINT_ID = "SAP-Products-upsertProductEndpointId"; private static final String UPSERT_PRODUCT_PROCESSOR_ID = "SAP-Products-upsertProductProcessorId"; @NonNull private final ProductFileEndpointConfig fileEndpointConfig; @Getter @NonNull private final String routeId; @NonNull private final JsonExternalSystemRequest enabledByExternalSystemRequest; @NonNull private final ProcessLogger processLogger; @NonNull private final ExternalMappingsHolder externalMappingsHolder; @Builder private GetProductsFromFileRouteBuilder( @NonNull final ProductFileEndpointConfig fileEndpointConfig, @NonNull final CamelContext camelContext, @NonNull final String routeId, @NonNull final JsonExternalSystemRequest enabledByExternalSystemRequest, @NonNull final ProcessLogger processLogger) { super(camelContext); this.fileEndpointConfig = fileEndpointConfig; this.routeId = routeId; this.enabledByExternalSystemRequest = enabledByExternalSystemRequest; this.processLogger = processLogger; this.externalMappingsHolder = ExternalMappingsHolder.of(enabledByExternalSystemRequest.getParameters()); } @Override public void configure() throws Exception { //@formatter:off from(fileEndpointConfig.getProductFileEndpoint()) .id(routeId) .log("Product Sync Route Started with Id=" + routeId) .process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest)) .process(this::validateEnableExternalSystemRequest) .split(body().tokenize("\n")) .streaming() .doTry() .unmarshal(new BindyCsvDataFormat(ProductRow.class)) .process(getProductUpsertProcessor()).id(UPSERT_PRODUCT_PROCESSOR_ID) .choice() .when(bodyAs(ProductUpsertCamelRequest.class).isNull()) .log(LoggingLevel.INFO, "Nothing to do! No product to upsert!") .otherwise() .log(LoggingLevel.DEBUG, "Calling metasfresh-api to upsert Product: ${body}") .to(direct(MF_UPSERT_PRODUCT_V2_CAMEL_URI)).id(UPSERT_PRODUCT_ENDPOINT_ID) .endChoice() .end() .endDoTry() .doCatch(Throwable.class) .to(direct(MF_ERROR_ROUTE_ID)) .end() .end(); //@formatter:on } private void validateEnableExternalSystemRequest(@NonNull final Exchange exchange) { Check.assume(externalMappingsHolder.hasProductTypeMappings(), "Product type mappings cannot be missing! ExternalSystem_Config_Id: " + enabledByExternalSystemRequest.getExternalSystemConfigId() + "!"); } @NonNull private ProductUpsertProcessor getProductUpsertProcessor() { final PInstanceLogger pInstanceLogger = PInstanceLogger.builder() .processLogger(processLogger) .pInstanceId(enabledByExternalSystemRequest.getAdPInstanceId()) .build(); final String defaultProductCategoryId = getContext().getPropertiesComponent().resolveProperty(DEFAULT_PRODUCT_CATEGORY_ID) .orElseThrow(() -> new RuntimeCamelException("Missing mandatory property: " + DEFAULT_PRODUCT_CATEGORY_ID)); return new ProductUpsertProcessor(enabledByExternalSystemRequest, pInstanceLogger, externalMappingsHolder, JsonMetasfreshId.of(defaultProductCategoryId)); } }
### DIN UPPGIFT: Besvara följande fråga i denna md-fil / 3 poäng I Typescript kan både type och interfaces användas för att skapa egna sammansatta typer. I många fall kan man använda antingen type eller interfaces, men det finns också skillnader. Redogör för dem och visa med kodexempel. Interfaces: Interfaces kan användas för att implementera klasser. En klass kan implementera flera interfaces. Types: type kan inte implementeras av klasser direkt Valet mellan type och interface beror ofta på den specifika användningssituationen. Om du behöver utvidga datatyper och skapa hierarkier, är interfaces ofta ett bra val. Om du behöver jobba med unions, intersections, eller om du behöver använda typeof operatorn, är type ett bättre alternativ. Många utvecklare använder också en kombination av både type och interface i sina projekt beroende på kontexten. //Med interface interface BaseShape { type: string; } //som att lägga till radius:number i baseshape när man använder sig av den Circle interfaces metoden interface Circle extends BaseShape { radius: number; } //Räknar ut are för circle const circleArea = (circle: Circle) => { return Math.PI \* circle.radius \*\* 2; }; //Med typer type BaseShape { type: string; } //som att lägga till radius:number i baseshape när man använder sig av den Circle interfaces metoden type Circle = BaseShape & { radius: number; } //Räknar ut are för circle const circleArea = (circle: Circle) => { return Math.PI \* circle.radius \*\* 2; };
const CartContainer = require("../containers/CartContainer"); const ProdsContainer = require("../containers/ProductsContainer"); const cart = new CartContainer("./containers/cart.json"); const products = new ProdsContainer("./containers/products.json"); //cart logic const CreateCart = async (req, res, next) => { try { const cartId = await cart.create(); cartId ? res .status(200) .json({ message: "Cart created successfully!", data: cartId }) : res.status(404).json({ error: "Cart not created. Please, try again" }); } catch (error) { next(error); } }; const AddProductToCart = async (req, res, next) => { try { const { id } = req.params; const { idProduct } = req.body; const prodToAdd = await products.getById(Number(idProduct)); const isAdded = await cart.addProductToCart(Number(id), prodToAdd); isAdded ? res.status(200).json({ message: "Product added successfully!" }) : res.status(404).json({ error: "Cart or Product not found" }); } catch (error) { next(error); } }; const GetCartProducts = async (req, res, next) => { try { const { id } = req.params; const cartProds = await cart.getById(Number(id)); cartProds ? cartProds.products.length > 0 ? res.status(200).json(cartProds.products) : res.status(404).json({ error: "The cart has no products yet" }) : res.status(404).json({ error: "Cart not found" }); } catch (error) { next(error); } }; const DeleteCart = async (req, res, next) => { try { const { id } = req.params; const isDeleted = await cart.delete(Number(id)); isDeleted ? res.status(200).json({ message: "Cart deleted successfully!" }) : res.status(404).json({ error: "Cart not found" }); } catch (error) { next(error); } }; const DeleteProductFromCart = async (req, res, next) => { try { const { id, idProduct } = req.params; const isDeleted = await cart.deleteProductFromCart( Number(id), Number(idProduct) ); isDeleted ? res.status(200).json({ message: "Product deleted successfully!" }) : res.status(404).json({ error: "Cart or Product not found" }); } catch (error) { next(error); } }; module.exports = { CreateCart, AddProductToCart, GetCartProducts, DeleteCart, DeleteProductFromCart, };
<template> <div class="container role-list" v-loading="loading"> <div class="handle-box"> <el-button type="primary" :icon="Plus" @click="addRole">新增</el-button> </div> <el-row> <el-table :data="tableData" :border="parentBorder" style="width: 100%"> <el-table-column type="expand"> <template #default="props"> <div> <el-table :data="props.row.context" :border="childBorder"> <el-table-column label="对话角色" prop="role" width="120"/> <el-table-column label="对话内容" prop="content"/> </el-table> </div> </template> </el-table-column> <el-table-column label="角色名称" prop="name"> <template #default="scope"> <span class="sort" :data-id="scope.row.id">{{ scope.row.name }}</span> </template> </el-table-column> <el-table-column label="角色标识" prop="key"/> <el-table-column label="启用状态"> <template #default="scope"> <el-switch v-model="scope.row['enable']" @change="roleSet('enable',scope.row)"/> </template> </el-table-column> <el-table-column label="角色图标" prop="icon"> <template #default="scope"> <el-image :src="scope.row.icon" style="width: 45px; height: 45px; border-radius: 50%"/> </template> </el-table-column> <el-table-column label="打招呼信息" prop="hello_msg"/> <el-table-column label="操作" width="150" align="right"> <template #default="scope"> <el-button size="small" type="primary" @click="rowEdit(scope.$index, scope.row)">编辑</el-button> <el-popconfirm title="确定要删除当前角色吗?" @confirm="removeRole(scope.row)" :width="200"> <template #reference> <el-button size="small" type="danger">删除</el-button> </template> </el-popconfirm> </template> </el-table-column> </el-table> </el-row> <el-dialog v-model="showDialog" title="编辑角色" :close-on-click-modal="false" width="50%" > <el-form :model="role" label-width="120px" ref="formRef" label-position="left" :rules="rules"> <el-form-item label="角色名称:" prop="name"> <el-input v-model="role.name" autocomplete="off" /> </el-form-item> <el-form-item label="角色标志:" prop="key"> <el-input v-model="role.key" autocomplete="off" /> </el-form-item> <el-form-item label="角色图标:" prop="icon"> <el-input v-model="role.icon" autocomplete="off" /> </el-form-item> <el-form-item label="打招呼信息:" prop="hello_msg"> <el-input v-model="role.hello_msg" autocomplete="off" /> </el-form-item> <el-form-item label="上下文信息:" prop="context"> <template #default> <el-table :data="role.context" :border="childBorder" size="small"> <el-table-column label="对话角色" width="120"> <template #default="scope"> <el-input v-model="scope.row.role" autocomplete="off" /> </template> </el-table-column> <el-table-column label="对话内容"> <template #header> <div class="context-msg-key"> <span>对话内容</span> <span class="fr"> <el-button type="primary" @click="addContext" size="small"> <el-icon> <Plus/> </el-icon> 增加一行 </el-button> </span> </div> </template> <template #default="scope"> <div class="context-msg-content"> <el-input v-model="scope.row.content" autocomplete="off" /> <span><el-icon @click="removeContext(scope.$index)"><RemoveFilled/></el-icon></span> </div> </template> </el-table-column> </el-table> </template> </el-form-item> <el-form-item label="启用状态"> <el-switch v-model="role.enable"/> </el-form-item> </el-form> <template #footer> <span class="dialog-footer"> <el-button @click="showDialog = false">取消</el-button> <el-button type="primary" @click="save">保存</el-button> </span> </template> </el-dialog> </div> </template> <script setup> import {Plus, RemoveFilled} from "@element-plus/icons-vue"; import {onMounted, reactive, ref} from "vue"; import {httpGet, httpPost} from "@/utils/http"; import {ElMessage} from "element-plus"; import {copyObj, removeArrayItem} from "@/utils/libs"; import {Sortable} from "sortablejs" const showDialog = ref(false) const parentBorder = ref(true) const childBorder = ref(true) const tableData = ref([]) const sortedTableData = ref([]) const role = ref({context: []}) const formRef = ref(null) const editRow = ref({}) const loading = ref(true) const rules = reactive({ name: [{required: true, message: '请输入用户名', trigger: 'blur',}], key: [{required: true, message: '请输入角色标识', trigger: 'blur',}], icon: [{required: true, message: '请输入角色图标', trigger: 'blur',}], sort: [ {required: true, message: '请输入排序数字', trigger: 'blur'}, {type: 'number', message: '请输入有效数字'}, ], hello_msg: [{required: true, message: '请输入打招呼信息', trigger: 'change',}] }) // 获取角色列表 httpGet('/api/admin/role/list').then((res) => { tableData.value = res.data sortedTableData.value = copyObj(tableData.value) loading.value = false }).catch(() => { ElMessage.error("获取聊天角色失败"); }) onMounted(() => { const drawBodyWrapper = document.querySelector('.el-table__body tbody') // 初始化拖动排序插件 Sortable.create(drawBodyWrapper, { sort: true, animation: 500, onEnd({newIndex, oldIndex, from}) { if (oldIndex === newIndex) { return } const sortedData = Array.from(from.children).map(row => row.querySelector('.sort').getAttribute('data-id')); const ids = [] const sorts = [] sortedData.forEach((id, index) => { ids.push(parseInt(id)) sorts.push(index) }) httpPost("/api/admin/role/sort", {ids: ids, sorts: sorts}).catch(e => { ElMessage.error("排序失败:" + e.message) }) } }) }) const roleSet = (filed, row) => { httpPost('/api/admin/role/set', {id: row.id, filed: filed, value: row[filed]}).then(() => { ElMessage.success("操作成功!") }).catch(e => { ElMessage.error("操作失败:" + e.message) }) } // 编辑 const curIndex = ref(0) const rowEdit = function (index, row) { curIndex.value = index role.value = copyObj(row) showDialog.value = true } const addRole = function () { role.value = {context: []} showDialog.value = true } const save = function () { formRef.value.validate((valid) => { if (valid) { showDialog.value = false httpPost('/api/admin/role/save', role.value).then((res) => { ElMessage.success('操作成功') // 更新当前数据行 if (role.value.id) { tableData.value[curIndex.value] = role.value } else { tableData.value.push(res.data) } }).catch((e) => { ElMessage.error('操作失败,' + e.message) }) } }) } const removeRole = function (row) { httpGet('/api/admin/role/remove?id=' + row.id).then(() => { ElMessage.success("删除成功!") tableData.value = removeArrayItem(tableData.value, row, (v1, v2) => { return v1.id === v2.id }) }).catch(() => { ElMessage.error("删除失败!") }) } const addContext = function () { if (!role.value.context) { role.value.context = [] } role.value.context.push({role: '', content: ''}) } const removeContext = function (index) { role.value.context.splice(index, 1); } </script> <style lang="stylus" scoped> .role-list { .opt-box { padding-bottom: 10px; display flex; justify-content flex-end .el-icon { margin-right 5px; } } .context-msg-key { .fr { float right .el-icon { margin-right 5px } } } .context-msg-content { display flex .el-icon { font-size: 20px; margin-top 5px; margin-left 5px; cursor pointer } } .el-input--small { width 30px; .el-input__inner { text-align center } } } </style>
import React, { Component } from 'react'; import { Text, View, StyleSheet } from 'react-native'; import { BarCodeScanner } from 'expo-barcode-scanner'; import * as Permissions from 'expo-permissions' import { Audio } from 'expo-av' import { navigationOptions } from '../shared/NavigationOptions'; import { Button, Spinner } from 'native-base' import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { navigateTo } from '../../actions/base'; import { createStudent, selectStudent, scanFailed } from '../../actions/home'; import studentSchema from '../../schema/student' interface IState { hasCameraPermission: boolean, scanning: boolean, sound: any } interface IStateProps { scanFailedStatus: boolean, navigatedAway: boolean } interface IDispatchProps { navigateTo: (to: string, params?: any) => void createStudent: (student: any) => void selectStudent: (student: any) => any scanFailed: (register: boolean) => void } class ScanStudent extends Component<IStateProps & IDispatchProps, IState> { static navigationOptions = navigationOptions('Scan Student') state: IState = { hasCameraPermission: null, scanning: false, sound: undefined }; componentDidUpdate(prevProps: IStateProps) { if (this.state.scanning === true && this.props.scanFailedStatus) { const soundObject = new Audio.Sound(); try { soundObject.loadAsync(require('./../../../assets/beep.mp3')); // Your sound is playing! } catch (error) { // An error occurred! } this.setState({ scanning: false, sound: soundObject }) this.props.scanFailed(false) } if (this.props.navigatedAway && !prevProps.navigatedAway) { const sound = new Audio.Sound(); this.setState({ scanning: false, sound }) try { sound.loadAsync(require('./../../../assets/beep.mp3')); // Your sound is playing! } catch (error) { // An error occurred! } } } componentDidMount() { this._requestCameraPermission(); const soundObject = new Audio.Sound(); this.setState({ sound: soundObject }) try { soundObject.loadAsync(require('./../../../assets/beep.mp3')); // Your sound is playing! } catch (error) { // An error occurred! } } _requestCameraPermission = async () => { const { status } = await Permissions.askAsync(Permissions.CAMERA); this.setState({ hasCameraPermission: status === 'granted' }); }; _handleBarCodeRead = ({ data }: any) => { if (!this.state.scanning) { try { this.setState({ scanning: true }) const student = JSON.parse(data) if (!studentSchema.isValidSync(student)) throw 'Not Complete' this.props.createStudent(student) this.state.sound.playAsync() } catch (error) { if (data && (typeof data === 'number' || typeof data === 'string')) { this.props.selectStudent({ grNo: data }) this.state.sound.playAsync() } } } }; gotoAddStudent = () => { this.props.navigateTo('AddStudent') } simulateScan = () => this._handleBarCodeRead({ data: 'T001' }) render() { return ( this.state.hasCameraPermission === null ? <Text>Requesting for camera permission</Text> : this.state.hasCameraPermission === false ? <Text>Camera permission is not granted</Text> : !this.state.scanning ? <BarCodeScanner onBarCodeScanned={this._handleBarCodeRead} barCodeTypes={[BarCodeScanner.Constants.BarCodeType.qr]} style={[StyleSheet.absoluteFill, styles.container]} > <View style={styles.layerTop} /> <View style={styles.layerCenter}> <View style={styles.layerLeft} /> <View style={styles.focused} /> <View style={styles.layerRight} /> </View> <View style={styles.layerBottom} > <Button light style={{ padding: 5, marginTop: 10 }} onPress={this.gotoAddStudent}><Text>Add Student Manually</Text></Button> { __DEV__ ? <Button light style={{ padding: 5, marginTop: 10 }} onPress={this.simulateScan}><Text>Simulate Scan</Text></Button> : undefined } </View> </BarCodeScanner> : <Spinner color='gray' /> ); } } const opacity = 'rgba(0, 0, 0, .6)'; const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column' }, layerTop: { flex: 1, backgroundColor: opacity }, layerCenter: { flex: 5, flexDirection: 'row' }, layerLeft: { flex: 1, backgroundColor: opacity }, focused: { flex: 10 }, layerRight: { flex: 1, backgroundColor: opacity }, layerBottom: { flex: 1, flexDirection: 'row', backgroundColor: opacity, justifyContent: 'space-around' } }); function mapStateToProps(state): IStateProps { return { scanFailedStatus: state.home.scanFailed, navigatedAway: state.base.navigateTo !== 'ScanStudent' } } function mapDispatchToProps(dispatch: any): IDispatchProps { return bindActionCreators({ navigateTo, createStudent, selectStudent, scanFailed }, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(ScanStudent)
<?php declare(strict_types=1); namespace App\Services\Socialite; use App\Models\User; use App\Models\UserSocialAccount; use App\Services\Image\ImageType; use App\Services\Model\UserServiceModel; use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; abstract class BaseSocialiteService { /** * @var null|string */ public $errorMessage = null; /** * @param string $url * @param User $oUser * @throws \Exception */ protected function saveImage(string $url, User $oUser) { $destinationPath = storage_path('app/public/images/user/tmp/'); if (!File::exists($destinationPath)) { File::makeDirectory($destinationPath); } $imageName = Str::random(10) . '.' . 'jpg'; $pathFile = $destinationPath . $imageName; File::put($pathFile, file_get_contents($url)); imageUpload($pathFile, $oUser, ImageType::MODEL); } /** * @param string $provider * @param array $data * @return User|null * @throws \Exception */ protected function createUser(string $provider, array $data) { $account = new UserSocialAccount([ 'provider_user_id' => $data['id'], 'provider' => $provider, ]); $fakeLogin = $provider . '-' . $data['id']; /** @var User|null $user */ $user = User::where('login', $fakeLogin)->first(); if (is_null($user)) { if (isset($data['email']) && !is_null($data['email'])) { $oUserByEmail = User::where('email', $data['email'])->first(); if (!is_null($oUserByEmail)) { $this->errorMessage = 'This email: ' . $data['email'] . ' is associated with another Staymenity account'; slackInfo($this->errorMessage); throw new \Exception($this->errorMessage, 422); } } $user = User::create([ 'login' => $fakeLogin, 'email' => $data['email'] ?? null, 'first_name' => $data['name'], 'password' => Hash::make(Str::random(10)), 'register_by' => User::REGISTER_BY_SOCIAL, 'is_has_password' => 0, ]); if (!is_null($data['avatar'])) { $this->saveImage($data['avatar'], $user); } $this->afterCreateUser($user, $data); (new UserServiceModel($user))->saveUserTimezoneByIp(); } $account->user()->associate($user); $account->save(); return $user; } /** * @param User $oUser * @param array $data */ protected function afterCreateUser(User $oUser, array $data) { $oService = (new UserServiceModel($oUser)); if (isset($data['role'])) { $role = $data['role']; if (in_array($role, [User::ROLE_HOST, User::ROLE_GUEST])) { $oService->setCurrentRole($role); } } $oService->afterCreate(); } /** * @param User $oUser * @param string $provider * @param string $id * @return UserSocialAccount|\Illuminate\Database\Eloquent\Model|null * @throws \Exception */ protected function createSocialAccountByUser(User $oUser, string $provider, string $id) { /** @var UserSocialAccount|null $oSocialAccount */ $oSocialAccount = $oUser->socialAccounts() ->where('provider', $provider) ->first(); if (!is_null($oSocialAccount)) { return $oSocialAccount; } // проверка если пользователь авторизовался через соц сеть, а потом // пытается её приконнектить $oSocialAccount = UserSocialAccount::where('provider', $provider) ->whereProviderUserId($id) ->first(); if (!is_null($oSocialAccount)) { $this->errorMessage = 'This ' . $provider . ' account is associated with another Staymenity account'; slackInfo($this->errorMessage); throw new \Exception($this->errorMessage, 422); } $oSocialAccount = $oUser->socialAccounts()->create([ 'provider_user_id' => $id, 'provider' => $provider, ]); return $oSocialAccount; } /** * @param User $oUser */ public function setRoleAfterAuth(User $oUser) { if (request()->exists('role')) { (new UserServiceModel($oUser))->setCurrentRole(request()->get('role')); } } }
using System; using System.Threading.Tasks; using Acme.BookStore.Books; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; namespace Acme.BookStore; public class BookStoreDataSeederContributor : IDataSeedContributor, ITransientDependency { private readonly IRepository<Book, Guid> _bookRepo; public BookStoreDataSeederContributor(IRepository<Book, Guid> bookRepo) { this._bookRepo = bookRepo; } public async Task SeedAsync(DataSeedContext context) { if (await _bookRepo.GetCountAsync() <= 0) { await _bookRepo.InsertAsync(new Book { Name = "1984", Type = BookType.Dystopia, PublishDate = new DateTime(1949, 6, 8), Price = 19.84f }, true); await _bookRepo.InsertAsync(new Book { Name = "The Hitchhiker's Guide to the Galaxy", Type = BookType.ScienceFiction, PublishDate = new DateTime(1995, 9, 27), Price = 42.0f }, true); } } }
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { WeatherService } from './weather.service'; import { Data } from '@angular/router'; import { mockWeatherObject } from '../testing/mockData'; describe('WeatherService', () => { let service: WeatherService; let httpController: HttpTestingController; let url = 'https://api.openweathermap.org/data/2.5/weather?units=metric&appid=23a52deef379e7d6bca0f7b3239f7a3b'; let httpClient: HttpClient; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], }); httpClient = TestBed.inject(HttpClient); httpController = TestBed.inject(HttpTestingController); service = TestBed.inject(WeatherService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call fetchWeatherForLocation and return weather object', () => { const city = 'Barcelona'; service.fetchWeatherForLocation(undefined, undefined, city).subscribe((res) => { expect(res).toEqual(mockWeatherObject); }); const req = httpController.expectOne({ method: 'GET', url: `${url}&q=${city}`, }); req.flush(mockWeatherObject); }); });
# Missing number ## Task Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. ## Объяснение Задача решается элементарно! Т.е. у нас есть: - числа от 0 до n - числа уникальные, т.е. 0, 1, 2, 3, 4, 5..., n Например, было [0, 1, 2, 3], затем 2 удалили и осталось [0, 1, 3]. Как вычислить 2? Можно итерируясь по индексам посчитать, какая должна быть сумма чисел: ind += i+1, 0 + 1 + 2 + 3 = 6. Затем посчитать текущую сумму элементов: 0 + 1 + 3 = 4. Следовательно, какого числа не хватает? 6-4 = 2. ## Constraints: - n == nums.length - 1 <= n <= 104 - 0 <= nums[i] <= n - All the numbers of nums are unique ## Example 1: ``` Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. ``` ## Example 2: ``` Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. ``` ## Example 3: ``` Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. ```
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # 데이터셋 불러오기 file_url = 'https://media.githubusercontent.com/media/musthave-ML10/data_source/main/dating.csv' data = pd.read_csv(file_url) # 데이터셋 확인 print(data.head()) print(data.info()) print(round(data.describe(), 2)) print('#' * 50, 1) print() # 전처리 : 결측치 처리 print(data.isna().mean()) # 중요도 관련 변수는 결측치 제거 data = data.dropna(subset=['pref_o_attractive', 'pref_o_sincere', 'pref_o_intelligence', 'pref_o_funny', 'pref_o_ambitious', 'pref_o_shared_interests', 'attractive_important', 'sincere_important', 'intellicence_important', 'funny_important', 'ambtition_important', 'shared_interests_important']) # 그 외의 결측치는 -99 (응답하지 않음) 으로 채움 data = data.fillna(-99) print('#' * 50, 2) print() # 전처리 : 피처 엔지니어링 # (1) 나이와 관련된 변수 def age_gap(x): if x['age'] == -99: return -99 elif x['age_o'] == -99: return -99 elif x['gender'] == 'female': return x['age_o'] - x['age'] else: return x['age'] - x['age_o'] data['age_gap'] = data.apply(age_gap, axis=1) # age_gap 변수에 age_gap 함수 적용 data['age_gap_abs'] = abs(data['age_gap']) # 절대값 적용 # (2) 인종과 관련된 변수 def same_race(x): if x['race'] == -99: return -99 elif x['race_o'] == -99: return -99 elif x['race'] == x['race_o']: return 1 else: return -1 data['same_race'] = data.apply(same_race, axis=1) # same_race 함수 적용 def same_race_point(x): if x['same_race'] == -99: return -99 else: return x['same_race'] * x['importance_same_race'] data['same_race_point'] = data.apply(same_race_point, axis=1) # (3) 평가/중요도 변수 def rating(x, importance, score): if x[importance] == -99: return -99 elif x[score] == -99: return -99 else: return x[importance] * x[score] partner_imp = data.columns[8:14] # 상대방의 중요도 partner_rate_me = data.columns[14:20] # 본인에 대한 상대방의 평가 my_imp = data.columns[20:26] # 본인의 중요도 my_rate_partner = data.columns[26:32] # 상대방에 대한 본인의 평가 new_label_partner = ['attractive_p', 'sincere_partner_p', 'intelligence_p', 'funny_p', 'ambition_p', 'shared_interests_p'] new_label_me = ['attractive_m', 'sincere_partner_m', 'intelligence_m', 'funny_m', 'ambition_m', 'shared_interests_m'] # rating 함수 적용 for i, j, k in zip(new_label_partner, partner_imp, partner_rate_me): data[i] = data.apply(lambda x: rating(x, j, k), axis=1) for i, j, k in zip(new_label_me, my_imp, my_rate_partner): data[i] = data.apply(lambda x: rating(x, j, k), axis=1) # (3) 더미 변수로 변환 data = pd.get_dummies(data, columns=['gender', 'race', 'race_o'], drop_first=True) print('#' * 50, 3) print() # 모델링 및 평가 # (1) 데이터 분할 from sklearn.model_selection import train_test_split X = data.drop('match', axis=1) y = data['match'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100) # (2) 모델링 import xgboost as xgb model = xgb.XGBClassifier(n_estimators=500, max_depth=5, random_state=100) model.fit(X_train, y_train) pred = model.predict(X_test) # 평가 from sklearn.metrics import accuracy_score, confusion_matrix, classification_report print(accuracy_score(y_test, pred)) # 정확도 print(confusion_matrix(y_test, pred)) # 혼동 행렬 print(classification_report(y_test, pred)) # 오류 유형에 따른 평가 print('#' * 50, 4) print() # 하이퍼파라미터 튜닝 : 그리드 서치 from sklearn.model_selection import GridSearchCV parameters = { 'learning_rate': [0.01, 0.1, 0.3], 'max_depth': [5, 7, 10], 'subsample': [0.5, 0.7, 1], 'n_estimators': [300, 500, 1000] } # (1) 그리드 서치 적용 model = xgb.XGBClassifier() gs_model = GridSearchCV(model, parameters, n_jobs=1, scoring='f1', cv=5) gs_model.fit(X_train, y_train) print(gs_model.best_params_) # (2) 평가 pred = gs_model.predict(X_test) print(accuracy_score(y_test, pred)) print(classification_report(y_test, pred)) print('#' * 50, 5) print() # 중요 변수 확인 model = xgb.XGBClassifier(learning_rate=0.3, max_depth=5, n_estimators=1000, subsample=1, random_state=100) model.fit(X_train, y_train) print(model.feature_importances_) # 데이터 프레임으로 변경 feature_imp = pd.DataFrame({'features': X_train.columns, 'values': model.feature_importances_}) print(feature_imp.head()) # 그래프로 출력 plt.figure(figsize=(20, 10)) sns.barplot(x='values', y='features', data=feature_imp.sort_values(by='values', ascending=False).head(10)) plt.show()
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path:'contact-manager', loadChildren: () => import('./contact-manager/contact-manager.module').then(module => module.ContactManagerModule) }, { path:'demo', loadChildren: () => import('./demo/demo.module').then(module => module.DemoModule) }, { path: '**', redirectTo: 'contact-manager', } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
# -*- coding: utf-8 -*- from os import getenv from django.utils.decorators import method_decorator from drf_yasg.utils import swagger_auto_schema from redis_pal import RedisPal from rest_framework.response import Response from rest_framework.viewsets import ViewSet from rest_framework_tracking.mixins import LoggingMixin # Views for last 15 min @method_decorator( name="list", decorator=swagger_auto_schema( operation_summary="Retorna a quantidade de chuva precipitada em cada hexágono (H3) nos últimos 15 minutos", operation_description=""" **Resultado**: Retorna uma lista contendo todos os hexágonos (H3) com a quantidade de chuva precipitada para os últimos 15 minutos, em milímetros (mm): ```json [ { "id_h3": "88a8a03989fffff", "bairro": "Guaratiba", "chuva_15min": 0.0, "estacoes": null, "status": "sem chuva", "color": "#ffffff" }, ... ] ``` **Política de cache**: O resultado é armazenado em cache por um período de 5 minutos. """, ), ) class Last15MinRainView(LoggingMixin, ViewSet): def list(self, request): data_key = "data_last_15min_rain" try: redis_url = getenv("REDIS_URL") assert redis_url is not None redis = RedisPal.from_url(redis_url) # Get data and set cache data = redis.get(data_key) assert data is not None assert isinstance(data, list) assert len(data) > 0 return Response(data) except Exception: return Response( {"error": "Something went wrong. Try again later."}, status=500, ) @method_decorator( name="list", decorator=swagger_auto_schema( operation_summary="Retorna o horário de atualização dos dados de chuva dos últimos 15 minutos", operation_description=""" **Resultado**: Retorna um texto contendo o horário de atualização dos dados de chuva: ``` "" ``` **Política de cache**: O resultado é armazenado em cache por um período de 5 minutos. """, ), ) class LastUpdateRainView(LoggingMixin, ViewSet): def list(self, request): last_update_key = "data_last_15min_rain_update" try: redis_url = getenv("REDIS_URL") assert redis_url is not None redis = RedisPal.from_url(redis_url) data = redis.get(last_update_key) assert data is not None assert isinstance(data, list) assert len(data) > 0 result = data[0] assert "last_update" in result last_update = result["last_update"] last_update_str = last_update.strftime("%d/%m/%Y %H:%M:%S") return Response(last_update_str) except Exception: return Response( {"error": "Something went wrong. Try again later."}, status=500, ) # Views for last 120 min @method_decorator( name="list", decorator=swagger_auto_schema( operation_summary="Retorna a quantidade de chuva precipitada em cada hexágono (H3) para os últimos nos últimos 120 minutos", operation_description=""" **Resultado**: Retorna uma lista contendo todos os hexágonos (H3) com a quantidade de chuva precipitada para os últimos 120 minutos, em milímetros (mm): ```json [ { "id_h3": "88a8a03989fffff", "bairro": "Guaratiba", "chuva_15min": 0.0, "estacoes": null, "status": "sem chuva", "color": "#ffffff" }, ... ] ``` **Política de cache**: O resultado é armazenado em cache por um período de 5 minutos. """, ), ) class Last120MinRainView(LoggingMixin, ViewSet): def list(self, request): data_key = "data_chuva_passado_alertario" try: redis_url = getenv("REDIS_URL") assert redis_url is not None redis = RedisPal.from_url(redis_url) # Get data and set cache data = redis.get(data_key) assert data is not None assert isinstance(data, list) assert len(data) > 0 return Response(data) except Exception: return Response( {"error": "Something went wrong. Try again later."}, status=500, ) @method_decorator( name="list", decorator=swagger_auto_schema( operation_summary="Retorna o horário de atualização dos dados de chuva dos últimos 120 minutos", operation_description=""" **Resultado**: Retorna um texto contendo o horário de atualização dos dados de chuva: ``` "" ``` **Política de cache**: O resultado é armazenado em cache por um período de 5 minutos. """, ), ) class LastUpdate120MinRainView(LoggingMixin, ViewSet): def list(self, request): last_update_key = "data_update_chuva_passado_alertario" try: redis_url = getenv("REDIS_URL") assert redis_url is not None redis = RedisPal.from_url(redis_url) data = redis.get(last_update_key) assert data is not None assert isinstance(data, list) assert len(data) > 0 result = data[0] assert "last_update" in result last_update = result["last_update"] last_update_str = last_update.strftime("%d/%m/%Y %H:%M:%S") return Response(last_update_str) except Exception: return Response( {"error": "Something went wrong. Try again later."}, status=500, )
const express = require('express'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); const { findOneUser, createUser, getDetailUserProfile, findOne } = require('../services/user.service'); const authMiddleware = require('../middleware/validateToken.middleware'); const userRouter = express.Router(); userRouter.post('/login', async (req, res) => { const { email, password } = req.body; const user = await findOne({ email }); if (user) { const isMatch = await bcrypt.compare(password, user.password); if (isMatch) { const { email, name, birth, address, nation, _id } = user; const payload = { email, name, birth, address, nation, _id: _id.toString() }; const token = jwt.sign(payload, "privateKey", { expiresIn: "1h" }); res.json({ token }); } else { res.status(400).json({ message: "password is incorrect" }); } } else { res.status(400).json({ message: "email or password is incorrect" }); } }); // create user userRouter.post('/register', async (req, res) => { const { password, email, name, birth, address, nation } = req.body; const existingUser = await findOneUser({ email }); if (existingUser) { return res.status(400).json({ message: "email already exists" }); } const passwordHashed = await bcrypt.hash(password, 10); await createUser({ password: passwordHashed, email, name, birth, address, nation }); res.json({ message: "user created" }); }); // get detail user profile userRouter.get('/detail-profile', authMiddleware, async (req, res) => { const { _id } = req.user; const user = await getDetailUserProfile({ _id }); res.json(user); }); module.exports = userRouter;
package com.java.escape; import com.google.common.base.Enums; import java.util.*; /** * 编码中的常见的异常 */ @SuppressWarnings("all") public class GeneralException { private static class User{ public User(){} private String name; public User(String name){ this.name = name; } public String getName(){ return name; } } public static class Manager extends User{} public static class Worker extends User{} private static final Map<String,StaffType> typeIndex = new HashMap<>( StaffType.values().length ); static { for (StaffType staffType : StaffType.values()) { typeIndex.put(staffType.name(),staffType); } } private static void concurrentModificationException(ArrayList<User> users){ // 直接使用 for 循环会出发并发修改异常 // for (User user : users) { // if (user.getName().equals("Tom")){ // users.remove(user); // } // } // 使用迭代器则没有问题 Iterator<User> iterator = users.iterator(); while (iterator.hasNext()) { User user = iterator.next(); if (user.getName().equals("Tom")) { iterator.remove(); } } } private static StaffType enumFind(String type) { // return StaffType.valueOf(type); // 1. 最普通、最简单的实现 // try { // return StaffType.valueOf(type); // } catch (IllegalArgumentException e) { // return null; // } // 2. 改进的实现 // for(StaffType staffType : StaffType.values()){ // if (staffType.name().equals(type)){ // return staffType; // } // } // return null; // 3. 静态 Map 实现,只有一次循环枚举的过程 // return typeIndex.get(type); // 4. 使用 Google Guava Enums,需要相关的依赖 return Enums.getIfPresent(StaffType.class,type).orNull(); } public static void main(String[] args) { // 1. 并发修改异常 // ArrayList<User> users = new ArrayList<>(Arrays.asList(new User("qinyi"),new User("Tom"))); // concurrentModificationException(users); // 2. 类型转换异常 // User user1 = new Manager(); // User user2 = new Worker(); // Manager m1 = (Manager) user1; // Manager m2 = (Manager) user2; // System.out.println(user2.getClass().getName()); // System.out.println(user2 instanceof Manager); // 3. 枚举查找异常 System.out.println(enumFind("RD")); System.out.println(enumFind("adc")); } }
# Frontend Mentor - Results summary component solution This is a solution to the [Results summary component challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/results-summary-component-CE_K6s0maV). Frontend Mentor challenges help you improve your coding skills by building realistic projects. ## Table of contents - [Overview](#overview) - [The challenge](#the-challenge) - [Screenshot](#screenshot) - [Links](#links) - [My process](#my-process) - [Built with](#built-with) - [What I learned](#what-i-learned) - [Continued development](#continued-development) - [Useful resources](#useful-resources) - [Author](#author) - [Acknowledgments](#acknowledgments) ## Overview ### The challenge Users should be able to: - View the optimal layout for the interface depending on their device's screen size - See hover and focus states for all interactive elements on the page ### Screenshot ![Screenshot of the solution](./assets/images/print.png) ### Links - Live Site URL: ([Click here](https://lele-sf.github.io/frontendMentor/results-summary/)) ## My process ### Built with - Semantic HTML5 markup - CSS custom properties - Flexbox - Mobile-first workflow ### What I learned Through this project, I gained experience in creating a responsive user interface using CSS flexbox and custom properties. I also improved my skills in mobile-first development, ensuring that the design is optimized for various screen sizes. ### Continued development In future projects, I plan to explore advanced CSS techniques and possibly incorporate JavaScript to add interactivity and enhance user experience. ### Useful resources - [CSS Tricks](https://css-tricks.com/) - [MDN Web Docs](https://developer.mozilla.org/en-US/) ## Author - GitHub - [lele-sf](https://github.com/lele-sf) - Frontend Mentor - [@lele-sf](https://www.frontendmentor.io/profile/lele-sf) ## Acknowledgments I would like to acknowledge the Frontend Mentor community for providing this challenge and the resources that helped me during the development process.
import { useEffect, useState, createContext, useContext, useRef } from 'react'; import Screen from './Screen'; import { OptionsBar } from './Option'; import AttendeeList from './Attendees'; import CallEndTwoToneIcon from '@mui/icons-material/CallEndTwoTone'; import MicTwoToneIcon from '@mui/icons-material/MicTwoTone'; import MicOffTwoToneIcon from '@mui/icons-material/MicOffTwoTone'; import VideocamTwoToneIcon from '@mui/icons-material/VideocamTwoTone'; import VideocamOffTwoToneIcon from '@mui/icons-material/VideocamOffTwoTone'; import ScreenShareTwoToneIcon from '@mui/icons-material/ScreenShareTwoTone'; import StopScreenShareTwoToneIcon from '@mui/icons-material/StopScreenShareTwoTone'; import { makeStyles } from '@mui/styles'; import PeerConnection from '../utils/peerconnection'; import useWebSockets from '../hooks/useWebSockets'; export interface MeetingContextType { localStream: MediaStream; setMute: (st: boolean) => void; setPause: (st: boolean) => void; } interface MeetingRoomProps { localMedia: MediaStream | null; } const useMeetingStyles = makeStyles({ root: { display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', height: '100vh', }, }); export const MeetingContext = createContext({}); // const config = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }; // const constraints = { audio: true, video: true }; function MeetingRoom(props: MeetingRoomProps) { const [peerConns, setPeerConns] = useState<PeerConnection[]>([]); const [localStream, setLocalStream] = useState<MediaStream | null>(null); const [displayMedia, setDisplayMedia] = useState<MediaStream | null>(null); const [self, setSelf] = useState<PeerConnection | null>(null); const [mute, setMute] = useState<boolean>(false); const [pause, setPause] = useState<boolean>(false); const classes = useMeetingStyles(); useEffect(() => { if (localStream) { setMute(localStream.getAudioTracks()[0].enabled); setPause(localStream.getVideoTracks()[0].enabled); } // const conn = new PeerConnection(signaling); // setSelf(conn); }, [localStream]); useEffect(() => { if (localStream) { localStream.getAudioTracks().forEach((track) => { track.enabled = mute; }); // localStream.getVideoTracks().forEach((track) => { // }); } }, [localStream, mute]); useEffect(() => { if (localStream) { localStream.getVideoTracks().forEach((track) => { track.enabled = pause; }); } }, [localStream, pause]); useEffect(() => { setLocalStream(props.localMedia); }, [props]); useEffect(() => { return () => { if (displayMedia) stopDisplayCapture(); }; }, []); const { socket: signaling } = useWebSockets({ url: '', options: { onopen: handleConnOpen, onmessage: handleRecvMsg, onerror: handleConnError, }, }); async function getDisplayMedia() { const gdmOptions = { // audio: { // echoCancellation: true, // noiseSuppression: true, // }, audio: false, video: true, }; // @ts-ignore const media = await navigator.mediaDevices.getDisplayMedia(gdmOptions); media.onremovetrack = (e: MediaStreamTrackEvent) => { console.log('removing track........................!', e); }; media.getVideoTracks()[0].onended = () => { stopDisplayCapture(); }; setDisplayMedia(media); } function stopDisplayCapture() { displayMedia?.getTracks().forEach((track) => { track.stop(); }); setDisplayMedia(null); } function handleConnOpen(e: Event) { console.log('Opened connection to #url'); const conn = new PeerConnection(signaling); const data = { type: 'newConn', from: conn.id, //id, room }; signaling?.send(JSON.stringify(data)); setPeerConns([...peerConns, conn]); } function handleRecvMsg(e: MessageEvent) { console.log('Recieving message from connection to ws://localhost:8080/'); const msg = e.data; switch (msg.type) { case 'offer': handleOffer(msg); break; case 'answer': handleAnswer(msg); break; case 'newConn': handleNewConn(msg); break; case 'ice': handleNewIce(msg); break; default: break; } } function handleConnError(e: Event) { console.log('Error in connceting to url'); } const handleNewConn = (data: any) => { const lid = self ? self.id : null; const peer = new PeerConnection(signaling, lid); peer.start(localStream, data['from']); setPeerConns([...peerConns, peer]); }; const handleOffer = (data: any) => { let peer = peerConns.filter((conn) => { return conn.id === data['to']; })[0]; peer.setOffer(data['offer']); }; const handleAnswer = (data: any) => { let peer = peerConns.filter((conn) => { return conn.id === data['to']; })[0]; peer.setAnswer(data['answer']); }; const handleNewIce = (data: any) => { let peer = peerConns.filter((conn) => { return conn.id === data['to']; })[0]; peer.addIceCand(data['candidate']); }; const options = [ { name: 'mic', icon: <MicTwoToneIcon color='primary' />, offIcon: <MicOffTwoToneIcon color='action' />, onclick: () => { console.log('Mute toggle'); setMute(!mute); // setIsMute(!isMute); }, }, { name: 'pause', icon: <VideocamTwoToneIcon color='primary' />, offIcon: <VideocamOffTwoToneIcon color='action' />, onclick: () => { console.log('Videocam toggle'); setPause(!pause); // setIsPause(!isPause); }, }, { name: 'Screen Share', icon: <ScreenShareTwoToneIcon color='primary' />, offIcon: <StopScreenShareTwoToneIcon color='action' />, onclick: () => { if (displayMedia === null) getDisplayMedia(); else { stopDisplayCapture(); } }, }, { name: 'End', icon: <CallEndTwoToneIcon color='primary' />, onclick: () => { // document.close();/ window.close(); }, }, ]; return ( <div className={classes.root}> {displayMedia ? ( <Screen displayMedia={displayMedia} userMedia={localStream} vidPause={pause} /> ) : ( <AttendeeList attendees={[ 'Mahesh', 'Teja', 'Sushma', 'some', 'lorem', 'ipsum', 'some', 'more', ]} /> )} <OptionsBar options={options} /> </div> ); } export default MeetingRoom;
import React, { useRef, useCallback } from 'react' import { Form } from '@unform/web' import { FormHandles } from '@unform/core' import { Link } from 'react-router-dom' import { FiLogIn, FiMail, FiLock } from 'react-icons/fi' import * as Yup from 'yup' import getValidationErrors from '../../utils/getValidationErrors' import { useToast } from '../../context/ToastContext' import { Container, Content, Background } from './styles' import logo from '../../assets/logo.svg' import Input from '../../components/Form/Input' import Button from '../../components/Form/Button' import { useAuth } from '../../context/AuthContext' interface SignInFormData { email: string password: string } const SignIn: React.FC = () => { const { addToast } = useToast() const formRef = useRef<FormHandles>(null) const { signIn } = useAuth() const handleSubmit = useCallback( async (data: SignInFormData, { reset }) => { try { formRef.current?.setErrors({}) const schema = Yup.object().shape({ email: Yup.string() .email('Insira um email válido.') .required('O email é obrigatório'), password: Yup.string().required('A senha é obrigatória.') }) await schema.validate(data, { abortEarly: false }) await signIn({ email: data.email, password: data.password }) } catch (err) { if (err instanceof Yup.ValidationError) { const validationErrors = getValidationErrors(err) formRef.current?.setErrors(validationErrors) } else { addToast({ type: 'error', title: 'Erro de Login', description: 'Usuário ou senha inválidos!' }) } } }, [addToast, signIn] ) return ( <Container> <Content> <img src={logo} alt="GoBarber" draggable={false} /> <Form ref={formRef} onSubmit={handleSubmit}> <h1>Faça seu logon</h1> <Input type="text" name="email" placeholder="E-mail" icon={FiMail} /> <Input type="password" name="password" placeholder="Senha" icon={FiLock} /> <Button type="submit">Entrar</Button> <a href="teste">Esqueci minha senha</a> <Link to="/signup"> <FiLogIn size={16} /> Criar conta </Link> </Form> </Content> <Background /> </Container> ) } export default SignIn
/* ! tailwindcss v3.0.24 | MIT License | https://tailwindcss.com *//* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: #e5e7eb; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. */ html { line-height: 1.5; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ -moz-tab-size: 4; /* 3 */ -o-tab-size: 4; tab-size: 4; /* 3 */ font-family: Nunito, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */ } /* 1. Remove the margin in all browsers. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. */ body { margin: 0; /* 1 */ line-height: inherit; /* 2 */ } /* 1. Add the correct height in Firefox. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) 3. Ensure horizontal rules are visible by default. */ hr { height: 0; /* 1 */ color: inherit; /* 2 */ border-top-width: 1px; /* 3 */ } /* Add the correct text decoration in Chrome, Edge, and Safari. */ abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } /* Remove the default font size and weight for headings. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } /* Reset links to optimize for opt-in styling instead of opt-out. */ a { color: inherit; text-decoration: inherit; } /* Add the correct font weight in Edge and Safari. */ b, strong { font-weight: bolder; } /* 1. Use the user's configured `mono` font family by default. 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Add the correct font size in all browsers. */ small { font-size: 80%; } /* Prevent `sub` and `sup` elements from affecting the line height in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) 3. Remove gaps between table borders by default. */ table { text-indent: 0; /* 1 */ border-color: inherit; /* 2 */ border-collapse: collapse; /* 3 */ } /* 1. Change the font styles in all browsers. 2. Remove the margin in Firefox and Safari. 3. Remove default padding in all browsers. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 1 */ line-height: inherit; /* 1 */ color: inherit; /* 1 */ margin: 0; /* 2 */ padding: 0; /* 3 */ } /* Remove the inheritance of text transform in Edge and Firefox. */ button, select { text-transform: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Remove default button styles. */ button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } /* Use the modern Firefox focus style for all focusable elements. */ :-moz-focusring { outline: auto; } /* Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) */ :-moz-ui-invalid { box-shadow: none; } /* Add the correct vertical alignment in Chrome and Firefox. */ progress { vertical-align: baseline; } /* Correct the cursor style of increment and decrement buttons in Safari. */ ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } /* 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */ [type='search'] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /* Remove the inner padding in Chrome and Safari on macOS. */ ::-webkit-search-decoration { -webkit-appearance: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Add the correct display in Chrome and Safari. */ summary { display: list-item; } /* Removes the default spacing and border for appropriate elements. */ blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } /* Prevent resizing textareas horizontally by default. */ textarea { resize: vertical; } /* 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) 2. Set the default placeholder color to the user's configured gray 400 color. */ input::-moz-placeholder, textarea::-moz-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input:-ms-input-placeholder, textarea:-ms-input-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input::placeholder, textarea::placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } /* Set the default cursor for buttons. */ button, [role="button"] { cursor: pointer; } /* Make sure disabled buttons don't get the pointer cursor. */ :disabled { cursor: default; } /* 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) This can trigger a poorly considered lint error in some tools but is included by design. */ img, svg, video, canvas, audio, iframe, embed, object { display: block; /* 1 */ vertical-align: middle; /* 2 */ } /* Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) */ img, video { max-width: 100%; height: auto; } /* Ensure the default browser behavior of the `hidden` attribute. */ [hidden] { display: none; } *, ::before, ::after { --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; } .fixed { position: fixed; } .absolute { position: absolute; } .relative { position: relative; } .left-0 { left: 0px; } .right-0 { right: 0px; } .top-0 { top: 0px; } .z-0 { z-index: 0; } .z-50 { z-index: 50; } .m-5 { margin: 1.25rem; } .my-52 { margin-top: 13rem; margin-bottom: 13rem; } .mx-auto { margin-left: auto; margin-right: auto; } .my-10 { margin-top: 2.5rem; margin-bottom: 2.5rem; } .my-5 { margin-top: 1.25rem; margin-bottom: 1.25rem; } .my-72 { margin-top: 18rem; margin-bottom: 18rem; } .ml-3 { margin-left: 0.75rem; } .-ml-px { margin-left: -1px; } .mb-4 { margin-bottom: 1rem; } .mt-1 { margin-top: 0.25rem; } .mt-4 { margin-top: 1rem; } .ml-4 { margin-left: 1rem; } .mt-3 { margin-top: 0.75rem; } .mt-2 { margin-top: 0.5rem; } .mb-5 { margin-bottom: 1.25rem; } .mt-6 { margin-top: 1.5rem; } .ml-1 { margin-left: 0.25rem; } .mr-2 { margin-right: 0.5rem; } .ml-2 { margin-left: 0.5rem; } .mt-8 { margin-top: 2rem; } .ml-12 { margin-left: 3rem; } .-mt-px { margin-top: -1px; } .-mr-2 { margin-right: -0.5rem; } .block { display: block; } .inline-block { display: inline-block; } .flex { display: flex; } .inline-flex { display: inline-flex; } .table { display: table; } .grid { display: grid; } .hidden { display: none; } .h-5 { height: 1.25rem; } .h-20 { height: 5rem; } .h-8 { height: 2rem; } .h-16 { height: 4rem; } .h-10 { height: 2.5rem; } .h-4 { height: 1rem; } .h-6 { height: 1.5rem; } .min-h-screen { min-height: 100vh; } .w-5 { width: 1.25rem; } .w-20 { width: 5rem; } .w-full { width: 100%; } .w-48 { width: 12rem; } .w-4\/6 { width: 66.666667%; } .w-8 { width: 2rem; } .w-auto { width: auto; } .w-4 { width: 1rem; } .w-6 { width: 1.5rem; } .max-w-xl { max-width: 36rem; } .max-w-6xl { max-width: 72rem; } .max-w-7xl { max-width: 80rem; } .flex-1 { flex: 1 1 0%; } .shrink-0 { flex-shrink: 0; } .table-auto { table-layout: auto; } .origin-top-left { transform-origin: top left; } .origin-top { transform-origin: top; } .origin-top-right { transform-origin: top right; } .scale-95 { --tw-scale-x: .95; --tw-scale-y: .95; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .scale-100 { --tw-scale-x: 1; --tw-scale-y: 1; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .transform { transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .cursor-default { cursor: default; } .list-inside { list-style-position: inside; } .list-disc { list-style-type: disc; } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .flex-col { flex-direction: column; } .items-center { align-items: center; } .justify-end { justify-content: flex-end; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .space-x-8 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(2rem * var(--tw-space-x-reverse)); margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse))); } .space-y-1 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.25rem * var(--tw-space-y-reverse)); } .overflow-hidden { overflow: hidden; } .break-all { word-break: break-all; } .rounded-md { border-radius: 0.375rem; } .rounded-xl { border-radius: 0.75rem; } .rounded-lg { border-radius: 0.5rem; } .rounded-l-md { border-top-left-radius: 0.375rem; border-bottom-left-radius: 0.375rem; } .rounded-r-md { border-top-right-radius: 0.375rem; border-bottom-right-radius: 0.375rem; } .border { border-width: 1px; } .border-b-2 { border-bottom-width: 2px; } .border-l-4 { border-left-width: 4px; } .border-t { border-top-width: 1px; } .border-r { border-right-width: 1px; } .border-b { border-bottom-width: 1px; } .border-gray-300 { --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity)); } .border-indigo-400 { --tw-border-opacity: 1; border-color: rgb(129 140 248 / var(--tw-border-opacity)); } .border-transparent { border-color: transparent; } .border-cyan-400 { --tw-border-opacity: 1; border-color: rgb(34 211 238 / var(--tw-border-opacity)); } .border-gray-200 { --tw-border-opacity: 1; border-color: rgb(229 231 235 / var(--tw-border-opacity)); } .border-gray-400 { --tw-border-opacity: 1; border-color: rgb(156 163 175 / var(--tw-border-opacity)); } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .bg-slate-800 { --tw-bg-opacity: 1; background-color: rgb(30 41 59 / var(--tw-bg-opacity)); } .bg-gray-500 { --tw-bg-opacity: 1; background-color: rgb(107 114 128 / var(--tw-bg-opacity)); } .bg-slate-600 { --tw-bg-opacity: 1; background-color: rgb(71 85 105 / var(--tw-bg-opacity)); } .bg-slate-500 { --tw-bg-opacity: 1; background-color: rgb(100 116 139 / var(--tw-bg-opacity)); } .bg-transparent { background-color: transparent; } .bg-slate-900 { --tw-bg-opacity: 1; background-color: rgb(15 23 42 / var(--tw-bg-opacity)); } .bg-slate-300 { --tw-bg-opacity: 1; background-color: rgb(203 213 225 / var(--tw-bg-opacity)); } .bg-gray-100 { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity)); } .bg-gray-800 { --tw-bg-opacity: 1; background-color: rgb(31 41 55 / var(--tw-bg-opacity)); } .bg-slate-700 { --tw-bg-opacity: 1; background-color: rgb(51 65 85 / var(--tw-bg-opacity)); } .fill-current { fill: currentColor; } .p-16 { padding: 4rem; } .p-2 { padding: 0.5rem; } .p-6 { padding: 1.5rem; } .px-4 { padding-left: 1rem; padding-right: 1rem; } .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; } .px-1 { padding-left: 0.25rem; padding-right: 0.25rem; } .py-1 { padding-top: 0.25rem; padding-bottom: 0.25rem; } .px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .py-4 { padding-top: 1rem; padding-bottom: 1rem; } .pt-1 { padding-top: 0.25rem; } .pl-3 { padding-left: 0.75rem; } .pr-4 { padding-right: 1rem; } .pt-6 { padding-top: 1.5rem; } .pt-8 { padding-top: 2rem; } .pt-2 { padding-top: 0.5rem; } .pb-3 { padding-bottom: 0.75rem; } .pt-4 { padding-top: 1rem; } .pb-1 { padding-bottom: 0.25rem; } .text-center { text-align: center; } .font-sans { font-family: Nunito, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; } .text-sm { font-size: 0.875rem; line-height: 1.25rem; } .text-base { font-size: 1rem; line-height: 1.5rem; } .text-3xl { font-size: 1.875rem; line-height: 2.25rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .text-xs { font-size: 0.75rem; line-height: 1rem; } .text-xl { font-size: 1.25rem; line-height: 1.75rem; } .text-2xl { font-size: 1.5rem; line-height: 2rem; } .font-medium { font-weight: 500; } .font-extrabold { font-weight: 800; } .font-semibold { font-weight: 600; } .font-thin { font-weight: 100; } .uppercase { text-transform: uppercase; } .italic { font-style: italic; } .leading-5 { line-height: 1.25rem; } .leading-7 { line-height: 1.75rem; } .leading-tight { line-height: 1.25; } .tracking-wider { letter-spacing: 0.05em; } .tracking-widest { letter-spacing: 0.1em; } .text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .text-gray-700 { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .text-gray-600 { --tw-text-opacity: 1; color: rgb(75 85 99 / var(--tw-text-opacity)); } .text-green-600 { --tw-text-opacity: 1; color: rgb(22 163 74 / var(--tw-text-opacity)); } .text-red-600 { --tw-text-opacity: 1; color: rgb(220 38 38 / var(--tw-text-opacity)); } .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .text-gray-100 { --tw-text-opacity: 1; color: rgb(243 244 246 / var(--tw-text-opacity)); } .text-gray-200 { --tw-text-opacity: 1; color: rgb(229 231 235 / var(--tw-text-opacity)); } .text-gray-300 { --tw-text-opacity: 1; color: rgb(209 213 219 / var(--tw-text-opacity)); } .text-gray-400 { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } .text-gray-900 { --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity)); } .text-gray-800 { --tw-text-opacity: 1; color: rgb(31 41 55 / var(--tw-text-opacity)); } .text-slate-600 { --tw-text-opacity: 1; color: rgb(71 85 105 / var(--tw-text-opacity)); } .underline { -webkit-text-decoration-line: underline; text-decoration-line: underline; } .antialiased { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .opacity-0 { opacity: 0; } .opacity-100 { opacity: 1; } .shadow-sm { --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-lg { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-xl { --tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-md { --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow { --tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-teal-300 { --tw-shadow-color: #5eead4; --tw-shadow: var(--tw-shadow-colored); } .outline-none { outline: 2px solid transparent; outline-offset: 2px; } .ring-1 { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .ring-gray-300 { --tw-ring-opacity: 1; --tw-ring-color: rgb(209 213 219 / var(--tw-ring-opacity)); } .ring-black { --tw-ring-opacity: 1; --tw-ring-color: rgb(0 0 0 / var(--tw-ring-opacity)); } .ring-opacity-5 { --tw-ring-opacity: 0.05; } .transition { transition-property: color, background-color, border-color, fill, stroke, opacity, box-shadow, transform, filter, -webkit-text-decoration-color, -webkit-backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-text-decoration-color, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .duration-150 { transition-duration: 150ms; } .duration-200 { transition-duration: 200ms; } .duration-75 { transition-duration: 75ms; } .duration-300 { transition-duration: 300ms; } .ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } .ease-out { transition-timing-function: cubic-bezier(0, 0, 0.2, 1); } .ease-in { transition-timing-function: cubic-bezier(0.4, 0, 1, 1); } .card { margin-left: auto; margin-right: auto; margin-top: 3rem; margin-bottom: 3rem; width: 50%; min-width: -webkit-min-content; min-width: -moz-min-content; min-width: min-content; border-width: 4px; --tw-bg-opacity: 1; background-color: rgb(203 213 225 / var(--tw-bg-opacity)); padding: 1.25rem; --tw-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.25); --tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); transition-duration: 200ms; } .card:hover { --tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); --tw-shadow-color: #06b6d4; --tw-shadow: var(--tw-shadow-colored); } .title { margin-top: 2.5rem; margin-bottom: 2.5rem; text-align: center; font-size: 3.75rem; line-height: 1; font-weight: 700; --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .btn { margin: 0.25rem; border-radius: 9999px; padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 1rem; padding-right: 1rem; --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); transition-duration: 300ms; } .btn:hover { --tw-scale-x: 1.05; --tw-scale-y: 1.05; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .btn:active { --tw-scale-x: 1.1; --tw-scale-y: 1.1; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .btn:disabled { --tw-scale-x: 1; --tw-scale-y: 1; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); cursor: not-allowed; opacity: 0.5; } .btn-primary { background-image: linear-gradient(to right, var(--tw-gradient-stops)); --tw-gradient-from: #2dd4bf; --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(45 212 191 / 0)); --tw-gradient-to: #0369a1; --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .btn-primary:hover { background-image: linear-gradient(to left, var(--tw-gradient-stops)); --tw-gradient-from: #2dd4bf; --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(45 212 191 / 0)); --tw-gradient-to: #0369a1; } .btn-secondary { background-image: linear-gradient(to right, var(--tw-gradient-stops)); --tw-gradient-from: #a3e635; --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(163 230 53 / 0)); --tw-gradient-to: #65a30d; --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .btn-danger { background-image: linear-gradient(to right, var(--tw-gradient-stops)); --tw-gradient-from: #fb7185; --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(251 113 133 / 0)); --tw-gradient-to: #9f1239; --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } table { --tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } /* thead{ @apply } */ tr { border-bottom-width: 2px; --tw-border-opacity: 1; border-color: rgb(148 163 184 / var(--tw-border-opacity)); transition-duration: 300ms; } tr:hover { --tw-bg-opacity: 1; background-color: rgb(148 163 184 / var(--tw-bg-opacity)); } td { padding-top: 1rem; padding-bottom: 1rem; text-align: center; } @media (min-width: 640px) { td { padding-left: 0.5rem; padding-right: 0.5rem; } } @media (min-width: 768px) { td { padding-left: 2.5rem; padding-right: 2.5rem; } } th { padding-top: 1.25rem; padding-bottom: 1.25rem; text-transform: uppercase; } .add { margin-bottom: 2.5rem; width: 24rem; border-radius: 9999px; --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .addBtn { width: 33.333333%; border-top-right-radius: 9999px; border-bottom-right-radius: 9999px; padding-top: 0.75rem; padding-bottom: 0.75rem; padding-left: 1rem; padding-right: 1rem; transition-duration: 100ms; } .addBtn:active { --tw-scale-x: 1.1; --tw-scale-y: 1.1; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .addInput { width: 66.666667%; border-top-left-radius: 9999px; border-bottom-left-radius: 9999px; border-style: none; --tw-bg-opacity: 1; background-color: rgb(226 232 240 / var(--tw-bg-opacity)); padding-top: 0.75rem; padding-bottom: 0.75rem; padding-left: 1.25rem; padding-right: 1.25rem; transition-duration: 300ms; } .addInput:focus { border-style: none; --tw-bg-opacity: 1; background-color: rgb(241 245 249 / var(--tw-bg-opacity)); outline: 2px solid transparent; outline-offset: 2px; } .toggle { width: 100%; } .switch { margin-left: auto; margin-right: auto; margin-top: 0.5rem; margin-bottom: 0.5rem; display: flex; height: 2.5rem; width: 4rem; cursor: pointer; border-radius: 9999px; --tw-bg-opacity: 1; background-color: rgb(225 29 72 / var(--tw-bg-opacity)); padding: 0.25rem; --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); --tw-shadow-color: #fb7185; --tw-shadow: var(--tw-shadow-colored); transition-duration: 300ms; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } .switch::after { height: 2rem; width: 2rem; border-radius: 9999px; --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); content: var(--tw-content); transition-duration: 500ms; } .peer:checked ~ .switch { --tw-bg-opacity: 1; background-color: rgb(22 163 74 / var(--tw-bg-opacity)); --tw-shadow-color: #4ade80; --tw-shadow: var(--tw-shadow-colored); } .peer:checked ~ .switch::after { content: var(--tw-content); --tw-translate-x: 1.5rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .switch-theme { --tw-bg-opacity: 1; background-color: rgb(71 85 105 / var(--tw-bg-opacity)); --tw-shadow-color: #cbd5e1; --tw-shadow: var(--tw-shadow-colored); } .peer:checked ~ .switch-theme { --tw-bg-opacity: 1; background-color: rgb(8 145 178 / var(--tw-bg-opacity)); --tw-shadow-color: #67e8f9; --tw-shadow: var(--tw-shadow-colored); } .hover\:border-gray-300:hover { --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity)); } .hover\:bg-gray-300:hover { --tw-bg-opacity: 1; background-color: rgb(209 213 219 / var(--tw-bg-opacity)); } .hover\:bg-gray-100:hover { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity)); } .hover\:bg-slate-700:hover { --tw-bg-opacity: 1; background-color: rgb(51 65 85 / var(--tw-bg-opacity)); } .hover\:bg-gray-700:hover { --tw-bg-opacity: 1; background-color: rgb(55 65 81 / var(--tw-bg-opacity)); } .hover\:bg-gradient-to-l:hover { background-image: linear-gradient(to left, var(--tw-gradient-stops)); } .hover\:from-lime-400:hover { --tw-gradient-from: #a3e635; --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(163 230 53 / 0)); } .hover\:to-lime-600:hover { --tw-gradient-to: #65a30d; } .hover\:text-gray-500:hover { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .hover\:text-gray-400:hover { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } .hover\:text-gray-900:hover { --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity)); } .hover\:text-white:hover { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .hover\:text-gray-800:hover { --tw-text-opacity: 1; color: rgb(31 41 55 / var(--tw-text-opacity)); } .hover\:shadow-xl:hover { --tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .hover\:shadow-2xl:hover { --tw-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.25); --tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .hover\:shadow-teal-500:hover { --tw-shadow-color: #14b8a6; --tw-shadow: var(--tw-shadow-colored); } .focus\:z-10:focus { z-index: 10; } .focus\:border-blue-300:focus { --tw-border-opacity: 1; border-color: rgb(147 197 253 / var(--tw-border-opacity)); } .focus\:border-indigo-700:focus { --tw-border-opacity: 1; border-color: rgb(67 56 202 / var(--tw-border-opacity)); } .focus\:border-gray-300:focus { --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity)); } .focus\:border-cyan-700:focus { --tw-border-opacity: 1; border-color: rgb(14 116 144 / var(--tw-border-opacity)); } .focus\:border-teal-300:focus { --tw-border-opacity: 1; border-color: rgb(94 234 212 / var(--tw-border-opacity)); } .focus\:border-gray-900:focus { --tw-border-opacity: 1; border-color: rgb(17 24 39 / var(--tw-border-opacity)); } .focus\:border-indigo-300:focus { --tw-border-opacity: 1; border-color: rgb(165 180 252 / var(--tw-border-opacity)); } .focus\:bg-cyan-100:focus { --tw-bg-opacity: 1; background-color: rgb(207 250 254 / var(--tw-bg-opacity)); } .focus\:bg-gray-50:focus { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity)); } .focus\:bg-gray-100:focus { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity)); } .focus\:text-gray-700:focus { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .focus\:text-cyan-800:focus { --tw-text-opacity: 1; color: rgb(21 94 117 / var(--tw-text-opacity)); } .focus\:text-gray-800:focus { --tw-text-opacity: 1; color: rgb(31 41 55 / var(--tw-text-opacity)); } .focus\:text-teal-200:focus { --tw-text-opacity: 1; color: rgb(153 246 228 / var(--tw-text-opacity)); } .focus\:text-gray-200:focus { --tw-text-opacity: 1; color: rgb(229 231 235 / var(--tw-text-opacity)); } .focus\:text-gray-500:focus { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .focus\:shadow-xl:focus { --tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .focus\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; } .focus\:ring:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-indigo-200:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(199 210 254 / var(--tw-ring-opacity)); } .focus\:ring-opacity-50:focus { --tw-ring-opacity: 0.5; } .active\:bg-gray-100:active { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity)); } .active\:bg-gray-900:active { --tw-bg-opacity: 1; background-color: rgb(17 24 39 / var(--tw-bg-opacity)); } .active\:text-gray-700:active { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .active\:text-gray-500:active { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .disabled\:opacity-25:disabled { opacity: 0.25; } @media (prefers-color-scheme: dark) { .dark\:bg-gray-900 { --tw-bg-opacity: 1; background-color: rgb(17 24 39 / var(--tw-bg-opacity)); } .dark\:text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } } @media (min-width: 640px) { .sm\:-my-px { margin-top: -1px; margin-bottom: -1px; } .sm\:ml-10 { margin-left: 2.5rem; } .sm\:ml-6 { margin-left: 1.5rem; } .sm\:block { display: block; } .sm\:flex { display: flex; } .sm\:hidden { display: none; } .sm\:w-1\/2 { width: 50%; } .sm\:max-w-md { max-width: 28rem; } .sm\:flex-1 { flex: 1 1 0%; } .sm\:items-center { align-items: center; } .sm\:justify-start { justify-content: flex-start; } .sm\:justify-center { justify-content: center; } .sm\:justify-between { justify-content: space-between; } .sm\:rounded-lg { border-radius: 0.5rem; } .sm\:px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .sm\:pt-0 { padding-top: 0px; } } @media (min-width: 1024px) { .lg\:w-2\/6 { width: 33.333333%; } .lg\:px-8 { padding-left: 2rem; padding-right: 2rem; } }
#include <iostream> __global__ // The image is encoded as unsigned chars -- unsigned ints from 0 to 255. void colorToGrayscaleKernel(unsigned char* Pout, unsigned char* Pin, int width, int height){ // successive rows are in the y direction, successive columns are in the x direction. // same as going over the matrix horizontally = increase x // same as going over the matrix vertically = increase y int col_idx = blockDim.x * blockIdx.x + threadIdx.x; int row_idx = blockDim.y * blockIdx.y + threadIdx.y; // Only convert the pixel if it's within the image bounds if (col_idx < width && row_idx < height){ int grayscaleOffset = row_idx * width + col_idx; // In the color image, the pixels are stored as 3-tuples of unsigned chars (I think...) // So the pixel offset is 3 times the grayscale offset, and the order is R, G, B int colorOffset = grayscaleOffset * 3; unsigned char r = Pin[colorOffset]; unsigned char g = Pin[colorOffset + 1]; unsigned char b = Pin[colorOffset + 2]; // The formula for converting color to grayscale is 0.21*r + 0.72*g + 0.07*b Pout[grayscaleOffset] = 0.21f * r + 0.72f * g + 0.07f * b; } } void colorToGrayscale(unsigned char* Pout_h, unsigned char* Pin_h, int width, int height){ // Initialize and allocate pointers to device memory. unsigned char *Pout_d, *Pin_d; int grayscale_size = width * height * sizeof(unsigned char); // Allocate memory for the input (color) and output (grayscale) images // There are 3 channels, R, G, and B. cudaMalloc((void**) &Pin_d, 3 * grayscale_size); cudaMalloc((void**) &Pout_d, grayscale_size); // Copy input image from host memory to device memory cudaMemcpy(Pin_d, Pin_h, 3 * grayscale_size, cudaMemcpyHostToDevice); // Copy output image from host memory to device memory cudaMemcpy(Pout_d, Pout_h, grayscale_size, cudaMemcpyHostToDevice); // Launch the kernel // Use a 2D grid of 2D blocks, each 16x16. // when defining these sizes in the stub host-side, the order is x, y, z. // But indexing is in reverse order -- z is outermost, then y, then x. // z "selecting" the plane of the matrix on which to operate, and // y and x selecting the vertical and horizontal offsets, respectively, // helps me visualize the indexing a bit better. dim3 dimGrid(ceil(width/16.0), ceil(height/16.0), 1); dim3 dimBlock(16, 16, 1); colorToGrayscaleKernel<<<dimGrid, dimBlock>>>(Pout_d, Pin_d, width, height); // Copy result from device memory to host memory cudaMemcpy(Pout_h, Pout_d, grayscale_size, cudaMemcpyDeviceToHost); // Don't forget to free device memory!! cudaFree(Pin_d); cudaFree(Pout_d); } int main(){ std::cout << "Color to Grayscale" << std::endl; int width = 72; int height = 60; int total_px = width * height; unsigned char* Pout_h = new unsigned char[total_px]; unsigned char* Pin_h = new unsigned char[3*total_px]; for (int i = 0; i < height; i++){ for (int j = 0; j < 3*width; j++){ Pin_h[i*3*width + j] = (unsigned char) (i+j) % 256; } } colorToGrayscale(Pout_h, Pin_h, width, height); std::cout << "Color Image:"; for (int i = 0; i < height; i++){ for (int j = 0; j < 3*width; j++){ std::cout << (int) Pin_h[i*3*width + j] << " "; } std::cout << std::endl; } std::cout << "Grayscale Image:"; for (int i = 0; i < height; i++){ for (int j = 0; j < width; j++){ std::cout << (int) Pout_h[i*width + j] << " "; } std::cout << std::endl; } }
class App { constructor() { this.clearButton = document.getElementById("clear-btn"); this.loadButton = document.getElementById("load-btn"); this.carContainerElement = document.getElementById("cars-container"); this.filterCarButton = document.getElementById("filter-car-button"); this.driverType = document.getElementById("driver-type"); this.date = document.getElementById("date"); this.time = document.getElementById("pickup-time"); this.passengerCount = document.getElementById("passenger-count"); } async init() { await this.load(); // this.filterCarButton.onclick = this.run(); this.filterCarButton.disabled = true; this.filterCarButton.addEventListener("click", () => { this.run(); }); // inisialisasi disable filter this.driverType.addEventListener("change", this.disabledFilterButton); this.date.addEventListener("change", this.disabledFilterButton); this.time.addEventListener("change", this.disabledFilterButton); } run = () => { const selectedDriverType = parseInt(this.driverType.value); const selectedDate = this.date.value; const selectedTime = this.time.value; const selectedPassengerCount = this.passengerCount.value; // Clear previous results this.clear(); this.disabledFilterButton(); const filteredCars = Car.list.filter((car) => { if (selectedDriverType === 1) { if (!car.available) { return false; } } else if (selectedDriverType === 2) { if (car.available) { return false; } } const availableAtDate = new Date(car.availableAt); const selectedDateTime = new Date(`${selectedDate}T${selectedTime}`); return ( availableAtDate > selectedDateTime && car.capacity >= selectedPassengerCount ); }); filteredCars.forEach((car) => { const node = document.createElement("div"); node.innerHTML = car.render(); this.carContainerElement.appendChild(node); }); }; disabledFilterButton = () => { const isTypeDriver = this.driverType.value !== ""; const isDate = this.date.value !== ""; const isTime = this.time.value !== ""; this.filterCarButton.disabled = !(isTypeDriver && isDate && isTime); }; formatCurrency = (amount) => { return new Intl.NumberFormat("id-ID", { style: "currency", currency: "IDR", }).format(amount); }; async load() { const cars = await Binar.listCars(); cars.forEach((car) => { car.rentPerDay = this.formatCurrency(car.rentPerDay); }); Car.init(cars); } clear = () => { let child = this.carContainerElement.firstElementChild; while (child) { child.remove(); child = this.carContainerElement.firstElementChild; } }; }
import React from 'react'; import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'; import Home from './components/Home'; import About from './components/About'; import Contact from './components/Contact'; import './App.css'; function App() { return ( <Router> <div className="App"> <nav> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">Sobre</Link></li> <li><Link to="/contact">Contato</Link></li> </ul> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </div> </Router> ); } export default App;
import { mockDashboardConfig } from '~/__mocks__/mockDashboardConfig'; import { mockDscStatus } from '~/__mocks__/mockDscStatus'; import { mockComponents } from '~/__mocks__/mockComponents'; import { globalDistributedWorkloads } from '~/__tests__/cypress/cypress/pages/distributedWorkloads'; import { mockK8sResourceList } from '~/__mocks__/mockK8sResourceList'; import { mockProjectK8sResource } from '~/__mocks__/mockProjectK8sResource'; import { mockDWUsageByOwnerPrometheusResponse } from '~/__mocks__/mockDWUsageByOwnerPrometheusResponse'; import { mockWorkloadK8sResource } from '~/__mocks__/mockWorkloadK8sResource'; import { ClusterQueueKind, LocalQueueKind, WorkloadKind, WorkloadPodSet, WorkloadOwnerType, } from '~/k8sTypes'; import { PodContainer } from '~/types'; import { WorkloadStatusType } from '~/concepts/distributedWorkloads/utils'; import { mockClusterQueueK8sResource } from '~/__mocks__/mockClusterQueueK8sResource'; import { mockLocalQueueK8sResource } from '~/__mocks__/mockLocalQueueK8sResource'; import { ClusterQueueModel, LocalQueueModel, ProjectModel, WorkloadModel, } from '~/__tests__/cypress/cypress/utils/models'; import { RefreshIntervalTitle } from '~/concepts/metrics/types'; const mockContainer: PodContainer = { env: [], image: 'perl:5.34.0', imagePullPolicy: 'IfNotPresent', name: 'pi', resources: { requests: { cpu: '2', memory: '200Mi', }, }, terminationMessagePath: '/dev/termination-log', terminationMessagePolicy: 'File', }; const mockPodset: WorkloadPodSet = { count: 5, minCount: 4, name: 'main', template: { metadata: {}, spec: { containers: [mockContainer, mockContainer], dnsPolicy: 'ClusterFirst', restartPolicy: 'Never', schedulerName: 'default-scheduler', securityContext: {}, terminationGracePeriodSeconds: 30, }, }, }; type HandlersProps = { isKueueInstalled?: boolean; disableDistributedWorkloads?: boolean; hasProjects?: boolean; clusterQueues?: ClusterQueueKind[]; localQueues?: LocalQueueKind[]; workloads?: WorkloadKind[]; }; const initIntercepts = ({ isKueueInstalled = true, disableDistributedWorkloads = false, hasProjects = true, clusterQueues = [mockClusterQueueK8sResource({ name: 'test-cluster-queue' })], localQueues = [ mockLocalQueueK8sResource({ name: 'test-local-queue', namespace: 'test-project' }), ], workloads = [ mockWorkloadK8sResource({ k8sName: 'test-workload-finished', ownerKind: WorkloadOwnerType.Job, ownerName: 'test-workload-finished-job', mockStatus: WorkloadStatusType.Succeeded, podSets: [mockPodset, mockPodset], }), mockWorkloadK8sResource({ k8sName: 'test-workload-running', ownerKind: WorkloadOwnerType.Job, ownerName: 'test-workload-running-job', mockStatus: WorkloadStatusType.Running, podSets: [mockPodset, mockPodset], }), mockWorkloadK8sResource({ k8sName: 'test-workload-spinning-down-both', ownerKind: WorkloadOwnerType.RayCluster, ownerName: 'test-workload-spinning-down-both-rc', mockStatus: WorkloadStatusType.Succeeded, podSets: [mockPodset, mockPodset], }), mockWorkloadK8sResource({ k8sName: 'test-workload-spinning-down-cpu-only', ownerKind: WorkloadOwnerType.RayCluster, ownerName: 'test-workload-spinning-down-cpu-only-rc', mockStatus: WorkloadStatusType.Succeeded, podSets: [mockPodset, mockPodset], }), ], }: HandlersProps) => { cy.interceptOdh( 'GET /api/dsc/status', mockDscStatus({ installedComponents: { kueue: isKueueInstalled }, }), ); cy.interceptOdh( 'GET /api/config', mockDashboardConfig({ disableDistributedWorkloads, }), ); cy.interceptOdh('GET /api/components', null, mockComponents()); cy.interceptK8sList( ProjectModel, mockK8sResourceList( hasProjects ? [ mockProjectK8sResource({ k8sName: 'test-project', displayName: 'Test Project' }), mockProjectK8sResource({ k8sName: 'test-project-2', displayName: 'Test Project 2' }), ] : [], ), ); cy.interceptK8sList(ClusterQueueModel, mockK8sResourceList(clusterQueues)); cy.interceptK8sList( { model: LocalQueueModel, ns: '*', }, mockK8sResourceList(localQueues), ); cy.interceptK8sList( { model: WorkloadModel, ns: '*', }, mockK8sResourceList(workloads), ); cy.interceptOdh('POST /api/prometheus/query', (req) => { if (req.body.query.includes('container_cpu_usage_seconds_total')) { req.reply({ code: 200, response: mockDWUsageByOwnerPrometheusResponse({ [WorkloadOwnerType.Job]: { 'test-workload-finished-job': 0, 'test-workload-running-job': 2.2, }, [WorkloadOwnerType.RayCluster]: { 'test-workload-spinning-down-both-rc': 0.2, 'test-workload-spinning-down-cpu-only-rc': 0.2, }, }), }); } else if (req.body.query.includes('container_memory_working_set_bytes')) { req.reply({ code: 200, response: mockDWUsageByOwnerPrometheusResponse({ [WorkloadOwnerType.Job]: { 'test-workload-finished-job': 0, 'test-workload-running-job': 1610612736, // 1.5 GiB }, [WorkloadOwnerType.RayCluster]: { 'test-workload-spinning-down-both-rc': 104857600, // 100 MiB 'test-workload-spinning-down-cpu-only-rc': 0, }, }), }); } else { req.reply(404); } }); }; describe('Distributed Workload Metrics root page', () => { it('Does not exist if kueue is not installed', () => { initIntercepts({ isKueueInstalled: false, disableDistributedWorkloads: false, }); globalDistributedWorkloads.visit(false); globalDistributedWorkloads.findNavItem().should('not.exist'); globalDistributedWorkloads.shouldNotFoundPage(); }); it('Does not exist if feature is disabled', () => { initIntercepts({ isKueueInstalled: true, disableDistributedWorkloads: true, }); globalDistributedWorkloads.visit(false); globalDistributedWorkloads.findNavItem().should('not.exist'); globalDistributedWorkloads.shouldNotFoundPage(); }); it('Exists if kueue is installed and feature is enabled', () => { initIntercepts({ isKueueInstalled: true, disableDistributedWorkloads: false, }); globalDistributedWorkloads.visit(); globalDistributedWorkloads.findNavItem().should('exist'); globalDistributedWorkloads.shouldHavePageTitle(); }); it('Defaults to Project Metrics tab and automatically selects a project', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.url().should('include', '/projectMetrics/test-project'); cy.findByText('Top resource-consuming distributed workloads').should('exist'); }); it('Tabs navigate to corresponding routes and render their contents', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Distributed workload status tab').click(); cy.url().should('include', '/workloadStatus/test-project'); globalDistributedWorkloads.findStatusOverviewCard().should('exist'); cy.findByLabelText('Project metrics tab').click(); cy.url().should('include', '/projectMetrics/test-project'); cy.findByText('Top resource-consuming distributed workloads').should('exist'); }); it('Changing the project and navigating between tabs or to the root of the page retains the new project', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.url().should('include', '/projectMetrics/test-project'); globalDistributedWorkloads.selectProjectByName('Test Project 2'); cy.url().should('include', '/projectMetrics/test-project-2'); cy.findByLabelText('Distributed workload status tab').click(); cy.url().should('include', '/workloadStatus/test-project-2'); cy.findByLabelText('Project metrics tab').click(); cy.url().should('include', '/projectMetrics/test-project-2'); globalDistributedWorkloads.navigate(); cy.url().should('include', '/projectMetrics/test-project-2'); }); it('Changing the refresh interval and reloading the page should retain the selection', () => { initIntercepts({}); globalDistributedWorkloads.visit(); globalDistributedWorkloads.shouldHaveRefreshInterval(RefreshIntervalTitle.THIRTY_MINUTES); globalDistributedWorkloads.selectRefreshInterval(RefreshIntervalTitle.FIFTEEN_SECONDS); globalDistributedWorkloads.shouldHaveRefreshInterval(RefreshIntervalTitle.FIFTEEN_SECONDS); cy.reload(); globalDistributedWorkloads.shouldHaveRefreshInterval(RefreshIntervalTitle.FIFTEEN_SECONDS); }); it('Should show an empty state if there are no projects', () => { initIntercepts({ hasProjects: false }); globalDistributedWorkloads.visit(); cy.findByText('No data science projects').should('exist'); }); it('Should render with no quota state when there is no clusterqueue', () => { initIntercepts({ clusterQueues: [] }); globalDistributedWorkloads.visit(); cy.findByText('Configure the cluster queue').should('exist'); }); it('Should render with no quota state when the clusterqueue has no resourceGroups', () => { initIntercepts({ clusterQueues: [ mockClusterQueueK8sResource({ name: 'test-cluster-queue', hasResourceGroups: false }), ], }); globalDistributedWorkloads.visit(); cy.findByText('Configure the cluster queue').should('exist'); }); it('Should render with no quota state when there are no localqueues', () => { initIntercepts({ localQueues: [] }); globalDistributedWorkloads.visit(); cy.findByText('Configure the project queue').should('exist'); }); }); describe('Project Metrics tab', () => { it('Should render with no workloads empty state', () => { initIntercepts({ workloads: [] }); globalDistributedWorkloads.visit(); cy.findByLabelText('Project metrics tab').click(); cy.findByText('Requested resources').should('exist'); cy.findByTestId('dw-top-consuming-workloads').within(() => { cy.findByText('No distributed workloads').should('exist'); }); cy.findByTestId('dw-workload-resource-metrics').within(() => { cy.findByText('No distributed workloads').should('exist'); }); cy.findByTestId('dw-requested-resources').within(() => { // Requested resources shows chart even if empty workload cy.findByTestId('requested-resources-cpu-chart-container').should('exist'); }); }); describe('Workload resource metrics table', () => { it('Should render', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Project metrics tab').click(); globalDistributedWorkloads.findWorkloadResourceMetricsTable().within(() => { cy.findByText('test-workload-finished').should('exist'); }); }); it('Should not render usage bars on a fully finished workload', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Project metrics tab').click(); globalDistributedWorkloads .findWorkloadResourceMetricsTable() .findByText('test-workload-finished') .closest('tr') .within(() => { cy.get('td[data-label="CPU usage (cores)"]').should('contain.text', '-'); cy.get('td[data-label="Memory usage (GiB)"]').should('contain.text', '-'); }); }); it('Should render usage bars on a running workload', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Project metrics tab').click(); globalDistributedWorkloads .findWorkloadResourceMetricsTable() .findByText('test-workload-running') .closest('tr') .within(() => { cy.get('td[data-label="CPU usage (cores)"]').should('not.contain.text', '-'); cy.get('td[data-label="Memory usage (GiB)"]').should('not.contain.text', '-'); }); }); it('Should render usage bars on a succeeded workload that is still spinning down', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Project metrics tab').click(); globalDistributedWorkloads .findWorkloadResourceMetricsTable() .findByText('test-workload-spinning-down-both') .closest('tr') .within(() => { cy.get('td[data-label="CPU usage (cores)"]').should('not.contain.text', '-'); cy.get('td[data-label="Memory usage (GiB)"]').should('not.contain.text', '-'); }); }); it('Spinning-down workload should render usage bars only on the column that is still consuming resources', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Project metrics tab').click(); globalDistributedWorkloads .findWorkloadResourceMetricsTable() .findByText('test-workload-spinning-down-cpu-only') .closest('tr') .within(() => { cy.get('td[data-label="CPU usage (cores)"]').should('not.contain.text', '-'); cy.get('td[data-label="Memory usage (GiB)"]').should('contain.text', '-'); }); }); }); it('Should render the requested resources charts', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Project metrics tab').click(); cy.findByTestId('requested-resources-cpu-chart-container').should('exist'); }); }); describe('Workload Status tab', () => { it('Should render the status overview chart', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Distributed workload status tab').click(); const statusOverview = globalDistributedWorkloads.findStatusOverviewCard(); statusOverview.should('exist'); statusOverview.findByText('Succeeded: 3').should('exist'); }); it('Should render the status overview chart with pending fallback statuses', () => { initIntercepts({ workloads: [ mockWorkloadK8sResource({ k8sName: 'test-workload', mockStatus: null }), mockWorkloadK8sResource({ k8sName: 'test-workload-2', mockStatus: null }), ], }); globalDistributedWorkloads.visit(); cy.findByLabelText('Distributed workload status tab').click(); const statusOverview = globalDistributedWorkloads.findStatusOverviewCard(); statusOverview.should('exist'); statusOverview.findByText('Pending: 2').should('exist'); }); it('Should render the workloads table', () => { initIntercepts({}); globalDistributedWorkloads.visit(); cy.findByLabelText('Distributed workload status tab').click(); cy.findByText('test-workload-finished').should('exist'); }); it('Should render an empty state for the dw table if no workloads', () => { initIntercepts({ workloads: [] }); globalDistributedWorkloads.visit(); cy.findByLabelText('Distributed workload status tab').click(); cy.findByTestId('dw-workloads-table-card').within(() => { cy.findByText('No distributed workloads').should('exist'); }); }); });
package pageObjects; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; public class AccountRegistrationPage extends BasePage{ WebDriver driver; public AccountRegistrationPage(WebDriver driver) { super(driver); this.driver = driver; } @FindBy(xpath="//input[@id='input-firstname']") WebElement txtFirstname; @FindBy(xpath="//input[@id='input-lastname']") WebElement txtLasttname; @FindBy(xpath="//input[@id='input-email']") WebElement txtEmail; @FindBy(xpath="//input[@id='input-telephone']") WebElement txtTelephone; @FindBy(xpath="//input[@id='input-password']") WebElement txtPassword; @FindBy(xpath="//input[@id='input-confirm']") WebElement txtPasswordConfirm; @FindBy(xpath="//input[@name='agree']") WebElement chkdPolicy; @FindBy(xpath="//input[@value='Continue']") WebElement btnContinue; @FindBy(xpath = "//h1[normalize-space()='Your Account Has Been Created!']") WebElement msgConfirmation; public void setFirstName(String fname) { txtFirstname.sendKeys(fname); } public void setLastName(String lname) { txtLasttname.sendKeys(lname); } public void setEmail(String email) { txtEmail.sendKeys(email); } public void setTelephone(String number) { txtTelephone.sendKeys(number); } public void setPassword(String pwd) { txtPassword.sendKeys(pwd); txtPasswordConfirm.sendKeys(pwd); } public void setPrivacyPolicy() { //chkdPolicy.click(); Actions act=new Actions(driver); act.moveToElement(chkdPolicy).click().perform(); } public void clickContinue() { //sol1 btnContinue.click(); // JavascriptExecutor js = (JavascriptExecutor) driver; // js.executeScript("arguments[0].click;", btnContinue); //Actions act=new Actions(driver); //act.moveToElement(btnContinue).click().perform(); //sol2 //btnContinue.submit(); //sol3 //Actions act=new Actions(driver); //act.moveToElement(btnContinue).click().perform(); //sol4 //JavascriptExecutor js=(JavascriptExecutor)driver; //js.executeScript("arguments[0].click();", btnContinue); //Sol 5 //btnContinue.sendKeys(Keys.RETURN); //Sol6 //WebDriverWait mywait = new WebDriverWait(driver, Duration.ofSeconds(10)); //mywait.until(ExpectedConditions.elementToBeClickable(btnContinue)).click(); } public String getConfirmationMsg() { try { return (msgConfirmation.getText()); } catch (Exception e) { return (e.getMessage()); } } }
import React, { useState } from 'react' import { LazyLoadImage } from 'react-lazy-load-image-component' import 'react-lazy-load-image-component/src/effects/blur.css' import { prisma } from '../lib/prisma' import Link from 'next/link' export default function Collection({ posts, topPosts }) { const [r, setRedir] = useState({r: true, p: '/drawry'}) const colCount = topPosts.length return ( <section id="__koleksi" className="flex-auto"> <div className={`m-4 sm:m-0 sm:mt-5 text-white text-center`}> <h1 className={`font-fraunces text-3xl sm:text-4xl`}> Draw From A Story </h1> <p className="px-2 font-jost"> Klik gambar untuk membuka deskripsinya. </p> </div> <div id="top-posts" className={`grid items-center justify-items-center gap-4 m-4 grid-cols-1 md:grid-cols-2`}> {topPosts.map((post) => { let trophyCol let borderCol if (post.rank === 1) { trophyCol = 'text-[#FFD700]' borderCol = 'border-[#FFD700]' } else if (post.rank === 2) { trophyCol = 'text-[#C0C0C0]' borderCol = 'border-[#C0C0C0]' } else { trophyCol = 'text-[#CD7F32]' borderCol = 'border-[#CD7F32]' } return ( <div key={post.id.toString()} className="relative"> <Link href={{pathname: `/karya/${encodeURIComponent(post.id)}`, query: r}} passHref> <LazyLoadImage src={post.photo} alt={post.title} effect="blur" placeholderSrc="https://res.cloudinary.com/neuterion/image/upload/v1648816217/imageonline-co-placeholder-image_ovs0wo.jpg" className={`cursor-pointer border-2 ${borderCol}`} /> </Link> <i className={`absolute -bottom-0.5 fa-solid fa-trophy fa-2x right-1/2 translate-x-1/2 ${trophyCol}`}></i> </div> ) })} <style jsx>{` @media (min-width: 1024px) { #top-posts { grid-template-columns: repeat(${colCount}, minmax(0, 1fr)); } } `}</style> </div> <div id="posts" className={`block pt-4 m-4 columns-1 xsl:columns-2 sm:columns-3 lg:columns-5 max-w-[100vw] h-max border-t-2 border-dashed border-[#ffffff8a]`}> {posts.map((post) => { return ( <div key={post.id.toString()} className="h-auto mb-4 break-inside-avoid-column"> <Link href={{pathname: `/karya/${encodeURIComponent(post.id)}`, query: r}} passHref> <LazyLoadImage src={post.photo} alt={post.title} effect="blur" placeholderSrc="https://res.cloudinary.com/neuterion/image/upload/v1648816217/imageonline-co-placeholder-image_ovs0wo.jpg" className="cursor-pointer" /> </Link> </div> ) })} </div> </section> ) } export async function getStaticProps() { const posts = await prisma.post.findMany({ where: { eventId: 1, rank: 0, } }) const topPosts = await prisma.post.findMany({ where: { eventId: 1, rank: { not: 0, } }, orderBy: { rank: 'asc', } }) return { props: { posts, topPosts, }, } }
import React from "react"; import { useEffect } from "react"; import { useContext } from "react"; import { useState } from "react"; import { NavLink, useParams } from "react-router-dom"; import DeleteItem from "../../components/DeleteItem/DeleteItem"; import LoaderSpin from "../../components/LoaderSpin/LoaderSpin"; import Popup from "../../components/Popup/Popup"; import { AuthContext } from "../../context/AuthContext"; import useFetch from "../../hooks/useFetch"; import "./UserProfilePage.css"; function UserProfilePage() { const [userData, setUserData] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const [isPopupTrigger, setIsPopupTrigger] = useState(false); const { authUser } = useContext(AuthContext); const { id: userId } = useParams(); const { isLoading, performFetch } = useFetch(`/user/${userId}`, (data) => { if (data.success) { setUserData(data.result); } else { setErrorMessage(data.msg); } }); useEffect(() => { performFetch({ method: "GET" }); }, [userId]); return ( <div className="profile-page"> <div className="profile-container"> <div> <h1>Profile</h1> <p className={ isLoading ? "loading msg" : errorMessage ? "error msg" : "msg" } > {isLoading ? <LoaderSpin /> : errorMessage ? errorMessage : ""} </p> </div> <div className="user-data"> <p>Name</p> <p>{userData ? userData.name : "No data!"}</p> </div> <div className="user-data"> <p>Email</p> <p>{userData ? userData.email : "No data!"}</p> </div> <div className="user-data"> <p>Phone</p> <p>{userData ? userData.phone : "No data!"}</p> </div> {!authUser ? ( "" ) : authUser._id === userId ? ( <NavLink className="delete-user-button" to="" onClick={() => setIsPopupTrigger(true)} > Delete account </NavLink> ) : ( "" )} </div> <Popup className="delete-popup" isTrigger={isPopupTrigger} setIsPopupTrigger={setIsPopupTrigger} > <DeleteItem setIsPopupTrigger={setIsPopupTrigger} url={`/user/${userId}`} /> </Popup> </div> ); } export default UserProfilePage;
const config = require("../config/index"); const Order = require("../models/order"); const Coupon = require("../models/coupon"); const responseMessage = require("../utils/responseMessage"); const genCoupon = require("../utils/genCoupon"); // const genQRPayment = require("../utils/genQRPayment"); exports.admin = async (req, res, next) => { try { const { id, custName, productName, productQty, address, shipMethod, price, paymentMethod, slipImg, } = req.body; const textMessage = `รายการสิ้นค้าที่สั่งเข้ามา 1. ชื่อลุกค้า : ${custName} 2. ชื่อสินค้า : ${productName} 3. จำนวน : ${productQty} 4. ที่อยู่ : ${address} 5. จัดส่งโดย : ${shipMethod} 6. ยอดรวม : ${price} บาท 7. ชำระเงินผ่านธนาคาร : ${paymentMethod}`; const textFirstResponse = { //Group Admin ID to: "C4e5cfd4400582672b3ba6d18991799e6", messages: [ { type: "text", text: "Admin Message", }, { type: "text", text: textMessage, }, { type: "image", originalContentUrl: slipImg, previewImageUrl: slipImg, }, ], }; const decisionResponse = { //Group Admin ID to: "C4e5cfd4400582672b3ba6d18991799e6", messages: [ { type: "flex", altText: "สินค้ารอการอนุมัติ", contents: { type: "bubble", header: { type: "box", layout: "vertical", contents: [ { type: "text", size: "xl", align: "center", weight: "bold", wrap: true, text: `Order No.${id} Approve or not?`, }, ], }, // hero: { // type: "image", // url: slipImg, // size: "full", // aspectRatio: "2:1", // }, // body: { // type: "box", // layout: "vertical", // contents: [ // { // type: "text", // wrap: true, // text: textMessage, // }, // ], // }, footer: { type: "box", layout: "horizontal", spacing: "md", contents: [ { type: "button", style: "primary", action: { type: "message", label: "APPROVE", text: `Approve order of K.${custName} order ID : ${id}`, }, }, { type: "button", style: "primary", color: "#F90306", action: { type: "message", label: "REJECT", text: `Reject order of K.${custName} order ID : ${id}`, }, }, ], }, }, }, ], }; const firstRes = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(textFirstResponse), }); const decisionRes = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(decisionResponse), }); return res.status(200).json({ ...responseMessage.success, }); } catch (error) { next(error); } }; exports.messageHook = async (req, res, next) => { try { let hookMessage = req.body.events[0].message.text || null; let groupId = req.body.events[0].source.groupId || null; let data = ""; if (hookMessage) { if (hookMessage.substring(0, 3) === "App") { let stringIndex = hookMessage.indexOf(":"); let orderID = hookMessage .substring(stringIndex + 1, hookMessage.length) .trim(); const existOrder = await Order.findOne({ _id: orderID, // order_status: "pending", }) .select("-createdAt -updatedAt -__v -isActive") .lean(); const custId = existOrder.customer_id; if (!existOrder) { const textResponse = { to: custId, messages: [ { type: "text", text: `Order : ${orderID} cannot approve.`, }, ], }; const res = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(textResponse), }); } //Update order status const updateOrder = await Order.updateOne( { _id: orderID }, { order_status: "approve" } ); if (updateOrder.nModified === 0) { throw new Error("ไม่สามารถแก้ไขข้อมูลได้"); } const textResponse = { to: custId, messages: [ { type: "text", text: `Order ของคุณได้รับการยืนยันแล้ว ขนส่งกำลังจัดส่งสินค้า`, }, ], }; const res = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(textResponse), }); } else if (hookMessage.substring(0, 3) === "Rej") { let stringIndex = hookMessage.indexOf(":"); let orderID = hookMessage .substring(stringIndex + 1, hookMessage.length) .trim(); const existOrder = await Order.findOne({ _id: orderID, // order_status: "pending", }) .select("-createdAt -updatedAt -__v -isActive") .lean(); const custId = existOrder.customer_id; if (!existOrder) { const textResponse = { to: custId, messages: [ { type: "text", text: `Order : ${orderID} cannot reject.`, }, ], }; const res = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(textResponse), }); } const updateOrder = await Order.updateOne( { _id: orderID }, { order_status: "reject" } ); if (updateOrder.nModified === 0) { throw new Error("ไม่สามารถแก้ไขข้อมูลได้"); } const textResponse = { to: custId, messages: [ { type: "text", text: "Order ของคุณถูกปฎิเสธกรุณาติดต่อเจ้าหน้าที่", }, ], }; const res = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(textResponse), }); } else if ( hookMessage.substring(0, 6).toLowerCase() === "coupon" && groupId === "C4e5cfd4400582672b3ba6d18991799e6" ) { try { let stringIndex = hookMessage.indexOf("-"); let discountNum = hookMessage .substring(stringIndex + 1, hookMessage.length) .trim(); if (discountNum) { let couponCode = await genCoupon(6); let coupon = new Coupon(); coupon.coupon_name = `Special Discount ${discountNum}`; coupon.coupon_code = couponCode; coupon.discount_num = parseInt(discountNum); coupon.createdBy = "admin group"; let resCoupon = await coupon.save(); const textResponse = { to: "C4e5cfd4400582672b3ba6d18991799e6", messages: [ { type: "text", text: `Coupon Code : ${resCoupon.coupon_code}`, }, ], }; const res = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(textResponse), }); data = await res.json(); } } catch (err) { const textResponse = { to: "C4e5cfd4400582672b3ba6d18991799e6", messages: [ { type: "text", text: "กรุณากรอกส่วนลดให้ถูกต้อง \n(Coupon - [จำนวนส่วนลด])\nEx. Coupon - 200", }, ], }; const res = await fetch(`https://api.line.me/v2/bot/message/push`, { method: "POST", headers: { Authorization: `Bearer ${config.LINE_API_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify(textResponse), }); } } } return res.status(200).json({ ...responseMessage.success, }); } catch (error) { console.log(error); next(error); } };
package files import ( "fmt" "os" "path/filepath" "prices/pkg/config" "sync" "time" "go.uber.org/zap" ) const ( CSV = ".csv" ) type ( Scanner interface { Scan() } scanner struct { wg *sync.WaitGroup config *config.FileProcessor stop <-chan bool files FileQueue splitFiles FileQueue cache FileCache logger *zap.Logger } ) func NewScanner( wg *sync.WaitGroup, logger *zap.Logger, config *config.FileProcessor, files FileQueue, splitFiles FileQueue, cache FileCache, stop <-chan bool, ) Scanner { log := logger.Named("FileScanner") s := &scanner{ wg: wg, config: config, stop: stop, cache: cache, files: files, splitFiles: splitFiles, logger: log, } return s } func (s *scanner) Scan() { s.logger.Sugar().Infof("try to start scanning files in directory=%s", s.config.FilesDir) if _, err := os.Stat(s.config.FilesDir); os.IsNotExist(err) { s.logger.Sugar().Errorf("can't open directory=%s: (%s)", s.config.FilesDir, err.Error()) } s.wg.Add(1) ticker := time.NewTicker(s.config.FileScanner.CheckEveryDuration) s.scanDir() for { select { case <-ticker.C: s.logger.Sugar().Infof("rescan directory=%s", s.config.FilesDir) s.scanDir() case <-s.stop: s.logger.Sugar().Infof("stop scanning files in directory=%s", s.config.FilesDir) s.wg.Done() return } } } func (s *scanner) scanDir() { dir, err := os.ReadDir(s.config.FilesDir) if err != nil { s.logger.Sugar().Errorf("can't open directory=%s: (%s)", s.config.FilesDir, err.Error()) return } for _, entry := range dir { if s.valid(entry) { s.add(entry) } } } func (s *scanner) valid(entry os.DirEntry) bool { if entry.IsDir() { return false } extension := filepath.Ext(s.getPath(entry)) return extension == CSV } func (s *scanner) getPath(entry os.DirEntry) string { return filepath.Join(s.config.FilesDir, entry.Name()) } func (s *scanner) add(entry os.DirEntry) { path := s.getPath(entry) if _, ok, err := s.cache.Get(path); ok { return } else if err != nil { s.logger.Sugar().Errorf("can't get file=%s from cache: (%s)", path, err.Error()) return } s.logger.Sugar().Infof("add entry=%s to files queue", path) now := time.Now() newName := fmt.Sprintf("%d_%s", now.UnixNano(), entry.Name()) newPath := fmt.Sprintf("%s/%s", s.config.FilesDir, newName) if err := os.Rename(path, newPath); err != nil { s.logger.Sugar().Errorf("can't reanme entry=%s to=%s: (%s)", path, newPath, err.Error()) return } newFile := File{Path: newPath, Name: newName} newFileInfo, err := os.Stat(newFile.Path) if err != nil { s.logger.Sugar().Errorf("can't get file=%s info: (%s)", newFile, err.Error()) return } if newFileInfo.Size() >= s.config.MaxFileSizeBytes { if err := s.cache.Put(newFile); err != nil { s.logger.Sugar().Errorf("can't add file=%s to cache: (%s)", newFile, err.Error()) return } if err := s.splitFiles.Put(newFile); err != nil { s.logger.Sugar().Errorf("can't add file=%s to splitFile queue: (%s)", newFile, err.Error()) return } return } if err := s.cache.Put(newFile); err != nil { s.logger.Sugar().Errorf("can't add entry=%s to cache: (%s)", newFile, err.Error()) return } if err := s.files.Put(newFile); err != nil { s.logger.Sugar().Errorf("can't add entry=%s to files queue: (%s)", newFile, err.Error()) return } }
/* eslint-disable react/jsx-no-undef */ "use client"; /* eslint-disable react/no-unescaped-entities */ /* eslint-disable @next/next/no-img-element */ import Head from 'next/head'; import Image from 'next/image'; import React from 'react'; import { FiGithub } from 'react-icons/fi'; import '../styles/globals.css'; import ProjectCard from '@/components/projectCard'; function handleHover(e) { // Optional: Implement any hover-on action here } function handleUnhover(e) { // Optional: Implement any hover-off action here } function redirectToLinkedIn() { window.location.href = 'https://www.linkedin.com/company/cybernetny/'; } export default function Home() { const projects = [ { image: './projects/mimibot-app.png', // Replace with your project image path title: 'MimiBot App', description: 'A Node.js-based Discord bot, designed to elevate the Tower of Fantasy gameplay experience by offering instant access to character data and analytics. Features integration with the Tower of Fantasy Simulacra API for real-time character insights and statistical analysis, leveraging asynchronous programming for swift and accurate data handling. Equipped with sophisticated algorithms to calculate potential damage outputs for various character combinations, all accessible through user-friendly bot commands.', githubUrl: 'https://github.com/Glockosu/mimibot', }, // Add more projects here ]; return ( <div className="min-h-screen text-white flex flex-col custom:flex-row"> <Head> <title>Alex Johannesson</title> {/* Add other head elements here */} </Head> <header className="py-8 fixed w-full z-10 md:bg-transparent"> <div className="container mx-auto flex justify-between items-center"> {/* Add navigation and social links here */} </div> </header> {/* Sidebar container */} <div className="sidebar"> <aside className="sticky top-0 pt-20 pl-0 h-screen flex justify-center md:pl-5 w-128 "> <div className="text-center"> <img src="/../images/local/profile-pic-nice.webp" alt="Alex Johannesson" width={200} height={200} className="mx-auto rounded-md transition-transform transition-filter grayscale hover:grayscale-0 hover:scale-105" /> <h1 className="text-2xl font-bold mt-4">Alex Johannesson</h1> <p className="text-gray-400 mt-4">Software Engineer</p> <p className="text-gray-400 mt-2">I build cool stuff, check out my projects below :)</p> {/* Sidebar navigation */} <nav className="mt-16"> <ul className="space-y-4"> <li className="sidebar-item"> <a href="#about" className="sidebar-link">ABOUT</a> </li> <li className="sidebar-item"> <a href="#skills" className="sidebar-link">SKILLS</a> </li> <li className="sidebar-item"> <a href="#projects" className="sidebar-link">PROJECTS</a> </li> <li className="sidebar-item"> <a href="#experience" className="sidebar-link">EXPERIENCE</a> </li> </ul> </nav> {/* Social icons section */} <div className="mt-40"> <a href="https://github.com/alexjohannesson" className="inline-block mx-2 hover:-translate-y-1 transition-transform duration-300" target="_blank" rel="noopener noreferrer"> {/* Replace with your GitHub icon */} <img src="/../images/icons/icons8-github-50.png" alt="GitHub" className="w-6 h-6 icon-hover" /> </a> <a href="https://linkedin.com/in/alex-johannesson" className="inline-block mx-2 hover:-translate-y-1 transition-transform duration-300" target="_blank" rel="noopener noreferrer"> {/* Replace with your LinkedIn icon */} <img src="/../images/icons/icons8-linkedin-50.png" alt="LinkedIn" className="w-6 h-6 icon-hover" /> </a> {/* Add more icons as needed */} <a href="https://x.com/alexJohannesson12" className="inline-block mx-2 hover:-translate-y-1 transition-transform duration-300" target="_blank" rel="noopener noreferrer"> {/* Replace with your X icon or any other social platform */} <img src="/../images/icons/icons8-twitterx-50.png" alt="X" className="w-6 h-6 icon-hover" /> </a> <a href="mailto:[email protected]" className="social-media inline-block mx-2 hover:-translate-y-1 transition-transform duration-300" target="_blank" rel="noopener noreferrer"> {/* Replace with your X icon or any other social platform */} <img src="/../images/icons/icons8-mail-48.png" alt="mail" className="w-6 h-6 icon-hover" /> </a> </div> </div> </aside> </div> {/* Main content container */} <main className="flex-1 container mx-auto items-start content-start px-4 custom:pl-20 custom:mr-40 pt-[/* same as header height plus any additional space */]"> {/* About Section */} <section id="about" className="my-8 pt-10"> <p className="text-lg text-gray-400"> Hi, I'm <span className="text-white">Alex Johannesson</span>. I've been passionate about <span className="text-white">technology</span>, from tinkering with computers to gaming, since childhood. My early curiosity sparked my love for <span className="text-white">coding</span> and <span className="text-white">software development</span>. </p> <p className="text-gray-400 text-lg mt-4"> Professionally, I've grown by working with <span className="text-white">innovative startups</span>, blending <span className="text-white">technical skills</span> with <span className="text-white">creative vision</span>. I enjoy the challenge of both <span className="text-white">front-end</span> and <span className="text-white">back-end development</span>, crafting software that's both functional and beautiful. </p> <p className="text-gray-400 text-lg mt-4"> Outside work, I'm exploring the latest <span className="text-white">game releases</span> or dabbling with <span className="text-white">ai</span> and <span className="text-white">machine learning</span> models. These hobbies fuel my professional innovation, continually inspiring fresh ideas for new <span className="text-white">projects</span>. </p> </section> <section id="skills" className="px-0 py-8"> <h2 className="text-2xl font-bold mb-4">Skills</h2> <div className="border-b border-gray-600 mb-5"></div> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {/* Front-end Skills */} <div className="skills-category"> <h3 className="text-xl font-bold mb-2">Front-end</h3> <ul className="list-disc list-inside"> <li>HTML & CSS</li> <li>JavaScript (ES6+)</li> <li>Next.js & Tailwind</li> <li>Angular & TypeScript</li> <li>Vue.js</li> <li>Responsive Design</li> </ul> </div> {/* Back-end Skills */} <div className="skills-category"> <h3 className="text-xl font-bold mb-2">Back-end</h3> <ul className="list-disc list-inside"> <li>Node.js & Express</li> <li>Python & Django</li> <li>Java</li> <li>C++</li> <li>Database Management (SQL & NoSQL)</li> <li>API Design & Development</li> </ul> </div> {/* Additional Skills */} <div className="skills-category"> <h3 className="text-xl font-bold mb-2">Other Technologies</h3> <ul className="list-disc list-inside"> <li>Docker & Kubernetes</li> <li>AWS, Azure & Google Cloud</li> <li>Machine Learning & AI</li> <li>Blockchain Technologies</li> <li>IoT Development</li> <li>Mobile App Development (Flutter & React Native)</li> </ul> </div> </div> </section> {/* Projects Section */} <section id="projects" className="px-0 py-8"> <h2 className="text-2xl font-bold mb-4">Projects</h2> <div className="border-b border-gray-600 mb-5"></div> <div className="grid grid-cols-1 xl:grid-cols-2 2xl:grid-cols-3 gap-4"> <ProjectCard title="MimiBot App" imageSrc="/../images/projects/rsz_mimibot-app.png" githubLink="https://github.com/Glockosu/mimibot" skills={['Next.js', 'Tailwind CSS', 'TypeScript', 'Node.js', 'Discord API']} /> <ProjectCard title="Terrain Modeling" imageSrc="/../images/projects/rsz_terrain.png" githubLink="https://github.com/Glockosu/mimibot" skills={['Node.js', 'Perlin Noise', 'Data Structures and Algorithms', 'Version Control']} /> <ProjectCard title="SourceJump" imageSrc="/../images/projects/rsz_sourcejump.png" githubLink="https://github.com/sourcejump/website" skills={['Custom API', 'Python', 'Next.js', 'Tailwind CSS', 'MongoDB']} /> </div> </section> {/* Experience Section */} <section id="experience" className="px-0 py-8"> <h2 className="text-2xl font-bold mb-4">Experience</h2> <div className="border-b border-gray-600 mb-5"></div> {/* Experience item */} <div className="group cursor-pointer p-4 transition duration-300 ease-in-out transform hover:scale-100 hover:text-teal-400 hover:bg-purple-200/30 rounded-lg lg:flex lg:flex-col" onClick={redirectToLinkedIn}> <div className="lg:w-auto lg:flex-shrink-0 lg:text-left lg:pr-0"> <p className="text-gray-400 mt-5">April 2019 — Sept 2019</p> </div> {/* Content on the right */} <div className="flex-grow"> <h3 className="text-xl font-semibold mt-5 ">Web Developer @ CybernetNY ↷</h3> <h2 className="text-sm pb-5 text-gray-400">New York, NY</h2> <p className="text-gray-300"> Architected and engineered state-of-the-art user interfaces leveraging the power of React.js coupled with the agility of Tailwind CSS, resulting in highly responsive and visually appealing components. Pioneered the integration of SEO strategies, optimizing web properties to enhance online presence and significantly boost site traffic. Fostered a collaborative environment by synergizing with UX/UI designers, backend engineers, and project managers to deliver seamless digital solutions that resonate with clients such as Harvard Business School, Everytown for Gun Safety, Pratt Institute, and others. Championed departmental leadership by driving knowledge sharing initiatives and steering the development of sophisticated internal tools. </p> <div className="mt-4 flex flex-wrap gap-2"> {/* Tags for skills */} <span className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">JavaScript</span> <span className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">TypeScript</span> <span className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">React</span> <span className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">PHP</span> <span className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">HTML & SCSS</span> <span className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">WordPress</span> <span className="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">TypeScript</span> {/* Add other tags */} </div> </div> </div> {/* Add more positions here */} </section> {/* Contact Section */} <section id="contact" className="px-0 py-8"> <h2 className="text-2xl font-bold mb-4">Get in Touch</h2> <div className="border-b border-gray-600 mb-5"></div> <p className="mb-5 text-gray-400">If you're interested in working together or just want to say hi, don't hesitate to reach out. I'm always open to discussing new projects, creative ideas, or opportunities to be part of your visions.</p> <a href="mailto:[email protected]" className="inline-block button-container text-white font-bold py-2 px-6 rounded-lg transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-opacity-50"> Send Email </a> </section> <footer className="px-4 py-8 mt-20 text-white"> <div className="flex justify-center items-center"> <a href="https://github.com/Glockosu/Personal-Website" className="ml-4"> <p className="text-center text-gray-200 hover:text-teal-500">Designed & Built by Alex Johannesson</p> <svg className="w-6 h-6 ml-28 mt-3 fill-current" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub</title><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.016-2.04-3.338.724-4.042-1.61-4.042-1.61-.546-1.387-1.334-1.755-1.334-1.755-.9-.616.07-.604.07-.604 1 .07 1.525.98 1.525.98.888 1.52 2.33 1.08 2.897.827.09-.644.348-1.08.633-1.33-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.47-2.38 1.24-3.22-.125-.302-.54-1.52.117-3.17 0 0 1.01-.322 3.3 1.23.96-.267 1.98-.4 3-.405 1.02.006 2.04.138 3 .405 2.29-1.552 3.3-1.23 3.3-1.23.657 1.65.242 2.868.12 3.17.77.84 1.24 1.91 1.24 3.22 0 4.6-2.8 5.63-5.47 5.93.36.31.68.92.68 1.85 0 1.34-.012 2.42-.012 2.75 0 .32.22.694.82.577C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg> </a> </div> </footer> {/* Add more sections as needed */} </main> </div> ); }
function getSearchDomain (hostname) { const isLocalTest = hostname.endsWith('.example'); return isLocalTest ? 'www.search-company.example' : 'www.search-company.site'; } function getPubDomain (hostname) { const isLocalTest = hostname.endsWith('.example'); return isLocalTest ? 'www.publisher-company.example' : 'www.publisher-company.site'; } function getAdHostname (hostname) { const isLocalTest = hostname.endsWith('.example'); return isLocalTest ? 'ad-company.example' : 'ad-company.site'; } function getAdUrl (id, hostname) { // Build Ad Redirection URL const adHostname = getAdHostname(hostname); const adPath = `https://www.${adHostname}/aclick`; const adUrl = new URL(adPath); const params = ['ld', 'u', 'rlid', 'vqd', 'iurl', 'CID']; const customRedirect = 'customRedirect' in ads[id]; // add some fake values for (const param of params) { adUrl.searchParams.append(param, `${param}Value`); } adUrl.searchParams.append('ID', id) if (customRedirect) { adUrl.searchParams.append('customRedirect', ads[id]['customRedirect']); } // Build Search Redirection URL const useMPath = 'useMPath' in ads[id]; const includeParam = 'includeParam' in ads[id]; const searchPath = useMPath ? '/m.js' : '/y.js'; const searchFullPath = `https://${getSearchDomain(hostname)}${searchPath}` const searchUrl = new URL(searchFullPath); if ('supportAdDomain' in ads[id]) { searchUrl.searchParams.append('ad_domain', getPubDomain(hostname)); } else if ('emptyAdDomain' in ads[id]) { searchUrl.searchParams.append('ad_domain', ''); } else if ('incorrectAdDomain' in ads[id]) { searchUrl.searchParams.append('ad_domain', 'example.com'); } else if ('unparsableAdDomain' in ads[id]) { searchUrl.searchParams.append('ad_domain', 'abcdefg'); } else if ('differentSubdomainAdDomain' in ads[id]) { searchUrl.searchParams.append('ad_domain', `foo.${getPubDomain(hostname)}`); } // add static params if (useMPath) { searchUrl.searchParams.append('iurl', 'foo'); searchUrl.searchParams.append('ivu', 'foo'); searchUrl.searchParams.append('sfexp', '0'); searchUrl.searchParams.append('shopping', '1'); searchUrl.searchParams.append('spld', 'foo'); searchUrl.searchParams.append('styp', 'entitydetails'); } else { searchUrl.searchParams.append('eddgt', 'nothing'); searchUrl.searchParams.append('rut', 'else'); } // add params used for detection if (useMPath && includeParam) { searchUrl.searchParams.append('dsl', '1'); } else if (includeParam) { searchUrl.searchParams.append('u3', 'foo'); } if (customRedirect) { searchUrl.searchParams.append('customRedirect', ads[id]['customRedirect']); } // normal URLs use a different param, but we use 'u' here to avoid conflict with other params. searchUrl.searchParams.append('u', encodeURIComponent(adUrl)); return searchUrl.href; } const ads = { 1: { title: '[Ad 1] SERP Ad (heuristic)', summary: '/y.js; No ad_domain parameter; Includes u3 param', product: 12, includeParam: true }, 2: { title: '[Ad 2] Shopping Tab Ad (heuristic)', summary: '/m.js; No ad_domain parameter; Includes dsl=1 param', product: 200, useMPath: true, includeParam: true }, 3: { title: '[Ad 3] SERP Ad (heuristic)', summary: '/y.js; No ad_domain parameter; No u3 param', product: 12 }, 4: { title: '[Ad 4] Shopping Tab Ad (heuristic)', summary: '/m.js; No ad_domain parameter; No dsl=1 param', product: 200, useMPath: true }, 5: { title: '[Ad 5] SERP Ad (heuristic)', summary: '/y.js; Empty ad_domain parameter; No u3 param', product: 12, emptyAdDomain: true }, 6: { title: '[Ad 6] Shopping Tab Ad (heuristic)', summary: '/m.js; Empty ad_domain parameter; No dsl=1 param', product: 200, useMPath: true, emptyAdDomain: true }, 7: { title: '[Ad 7] SERP Ad (SERP-provided)', summary: '/y.js; Includes ad_domain parameter; No u3 param', product: 12, supportAdDomain: true }, 8: { title: '[Ad 8] Shopping Tab Ad (SERP-provided)', summary: '/m.js; Includes ad_domain parameter; No dsl=1 param', product: 200, useMPath: true, supportAdDomain: true }, 9: { title: '[Ad 9] SERP Ad (SERP-provided)', summary: '/y.js; Includes INCORRECT ad_domain parameter; No u3 param', product: 12, incorrectAdDomain: true }, 10: { title: '[Ad 10] Shopping Tab Ad (SERP-provided)', summary: '/m.js; Includes INCORRECT ad_domain parameter; No dsl=1 param', product: 200, useMPath: true, incorrectAdDomain: true }, 11: { title: '[Ad 11] SERP Ad (heuristic)', summary: '/y.js; Includes UNPARSABLE ad_domain parameter; No u3 param', product: 12, unparsableAdDomain: true }, 12: { title: '[Ad 12] Shopping Tab Ad (heuristic)', summary: '/m.js; Includes UNPARSABLE ad_domain parameter; No dsl=1 param', product: 200, useMPath: true, unparsableAdDomain: true }, 13: { title: '[Ad 13] SERP Ad (SERP-provided)', summary: '/y.js; Includes ad_domain parameter set to a different subdomain; No u3 param', product: 12, differentSubdomainAdDomain: true }, 14: { title: '[Ad 14] Shopping Tab Ad (SERP-provided)', summary: '/m.js; Includes ad_domain parameter set to a different subdomain; No dsl=1 param', product: 200, useMPath: true, differentSubdomainAdDomain: true }, 15: { title: '[Ad 15] SERP Ad (heuristic) with 307 redirect', summary: '/y.js; 307 redirect status code, Empty ad_domain parameter; No u3 param', product: 12, emptyAdDomain: true, customRedirect: 307 }, 16: { title: '[Ad 16] SERP Ad (heuristic) with 301 redirect', summary: '/y.js; 301 redirect status code, Empty ad_domain parameter; No u3 param', product: 12, emptyAdDomain: true, customRedirect: 301 } }; export function getAds (hostname) { for (const adId in ads) { const ad = ads[adId]; ad.url = getAdUrl(adId, hostname); ads[adId] = ad; } return ads; } /** * Returns a publisher product URL * @param {*} id * @param {string} hostname * @returns {string} */ export function getPubUrl(id, hostname) { const pubDomain = getPubDomain(hostname); const ad = ads[id]; return `https://${pubDomain}/product.html?p=${ad.product}` } export function getPubCompleteUrl(hostname) { const pubDomain = getPubDomain(hostname); return `https://${pubDomain}/convert.html` } export function getPaymentGatewayUrl(hostname) { const isLocalTest = hostname.endsWith('.example'); return isLocalTest ? 'https://www.payment-company.example/pay.html' : 'https://www.payment-company.site/pay.html'; } export function getAdConvertScriptUrl (hostname) { const adHostname = getAdHostname(hostname); return `https://convert.${adHostname}/convert.js?ad=1` } export function getTrackingScriptUrl (hostname) { const adHostname = getAdHostname(hostname); return `https://www.${adHostname}/track.js?ad=1` } export const products = { 12: { name: 'Green T-shirt', summary: 'Cotton t-shirt', price: ['3', '10'] }, 200: { name: 'Red shoes', summary: 'Red running shoes', price: ['2', '00'] }, 1231: { name: 'Corduroy beige pants', summary: 'Pants for the office.', price: ['12', '00'] } } export function getProducts (hostname) { const productsOut = {} for (const productId in products) { const product = products[productId]; productsOut[productId] = product; } return productsOut; } /** * Loads the tracking and conversion scripts. * Initializes the finish observer which will report the completed status to testing. */ export function initializeBoilerplate () { const convertScriptUrl = getAdConvertScriptUrl(globalThis.location.hostname); const trackingScriptUrl = getTrackingScriptUrl(globalThis.location.hostname); const convertPixelUrl = new URL('/ping.gif', convertScriptUrl); const trackingPixelUrl = new URL('/ping.gif', trackingScriptUrl); new FinishObserver([ { url: convertScriptUrl, subresources: [ { url: convertPixelUrl.href } ] }, { url: trackingScriptUrl, subresources: [ { url: trackingPixelUrl.href } ] } ]) function createAndAppendScript(url) { const scriptElement = document.createElement('script'); scriptElement.src = url; scriptElement.onload = () => { fireResource(url, 'loaded'); } scriptElement.onerror = () => { fireResource(url, 'blocked'); } document.documentElement.appendChild(scriptElement); } createAndAppendScript(convertScriptUrl); createAndAppendScript(trackingScriptUrl); } function fireResource (url, status) { window.dispatchEvent(new CustomEvent('resourceLoad', { detail: { url, status } })); } /** * @typedef ResourceLoad * @property {string} src * @property {'loaded', 'blocked', 'parent blocked'} [status] * @property {ResourceLoad[]} [subresources] */ export class FinishObserver { /** * @param {ResourceLoad[]} resourceLoads * @param {number} timeout */ constructor(resources, timeout) { // Validate that resources passed match expectations due to limitations in knowing the initiator. const uniqueUrls = new Set(); function addUnique(url) { if (uniqueUrls.has(url)) { throw new Error('Each url observed must be unique: ' + url); } uniqueUrls.add(url); } for (const resource of resources) { addUnique(resource.url); if (resource.subresources) { resource.subresources.every(subresource => { addUnique(subresource.url); if ('subresources' in subresource) { throw new Error('Child subresources are not supported'); } }); } } this.resources = resources; this.observer = new PerformanceObserver((list) => { const entries = list.getEntries(); entries.map((entry) => { // Safari doesn't support serverTiming nor does it fire events for blocked loads either. if (entry.serverTiming) { if (entry.serverTiming.length === 0) { this.setResourceStatus(entry.name, 'blocked'); } else { this.setResourceStatus(entry.name, 'loaded'); } } }); this.fireFinishIfFinished() }); this.observer.observe({entryTypes: ["resource"]}); // Support for Safari as it doesn't support serverTiming window.addEventListener('resourceLoad', (event) => { this.setResourceStatus(event.detail.url, event.detail.status); this.fireFinishIfFinished() }); } fireFinishIfFinished() { if (this.isFinished()) { this.fireFinish(); } } setResourceStatus(url, status) { this.resources.forEach((resource) => { if (resource.url === url) { resource.status = status; if (status === 'blocked' && resource.subresources) { resource.subresources.forEach((child) => { child.status = 'parent blocked'; }); } } else if ('subresources' in resource) { resource.subresources.forEach((subresource) => { if (subresource.url === url) { subresource.status = status; } }); } }); } isFinished() { for (const resource of this.resources) { if (!('status' in resource)) { return false } if ('subresources' in resource) { for (const child of resource.subresources) { if (!('status' in child)) { return false; } } } } return true } fireFinish() { if (this.hasFinished) { return; } this.hasFinished = true; this.observer.disconnect(); window.dispatchEvent(new CustomEvent('pageFinished', { detail: { loads: this.resources } })); /** * Flatten output to global. * ``` * window.resources = [ * { status: "loaded", url: "https://convert.ad-company.example/convert.js?ad=1" } * { status: "loaded", url: "https://convert.ad-company.example/ping.gif" } * { status: "blocked", url: "https://www.ad-company.example/track.js?ad=1" } * { status: "parent blocked", url: "https://www.ad-company.example/ping.gif" } * ] * ``` */ const output = [] for (const resource of this.resources) { output.push({status: resource.status, url: resource.url}); if (resource.subresources) { for (const child of resource.subresources) { output.push({status: child.status, url: child.url}); } } } window.resources = output this.render(); } render() { const detailsElement = document.createElement('details'); const summaryElement = document.createElement('summary'); summaryElement.textContent = 'Resources'; const tableElement = document.createElement('table'); for (const resource of window.resources) { const resourceElement = document.createElement('tr'); const urlCellElement = document.createElement('td'); urlCellElement.textContent = resource.url; resourceElement.appendChild(urlCellElement); const statusCellElement = document.createElement('td'); statusCellElement.textContent = resource.status; resourceElement.appendChild(statusCellElement); tableElement.appendChild(resourceElement); } detailsElement.appendChild(summaryElement); detailsElement.appendChild(tableElement); document.body.appendChild(detailsElement); } }
let questions = [ { id: 1, question: "What is the Full Form Of RAM?", answer:"Random Access Memory", options: [ "Run Accept Memory", "Random All Memory", "Random Access Memory", "None of these" ] }, { id: 2, question: "What is the Full-Form of CPU?", answer: "Central Processing Unit", options: [ "Central Program Unit", "Central Processing Unit", "Central Preload Unit", "None of these" ] }, { id: 3, question: "What is the Full-Form of E-mail", answer: "Electronic Mail", options: [ "Electronic Mail", "Electric Mail", "Engine Mail", "None of these" ] }, { id: 4, question: "'DB' in computer means?", answer: "DataBase", options: [ "Double Byte", "Data Block", "DataBase", "None of these" ] }, { id: 5, question: "What is FMD?", answer: "Fluorescent Multi-Layer Disc", options: [ "Fluorescent Multi-Layer Disc", "Flash Media Driver", "Fast-Ethernet Measuring Device", "None of these" ] }, { id: 6, question: "How many bits is a byte?", answer: "8", options: [ "32", "16", "8", "64" ] }, { id: 7, question: "A JPG stands for:", answer: "A format for an image file", options: [ "A format for an image file", "A Jumper Programmed Graphic", "A type of hard disk", "A unit of measure for memory" ] }, { id: 8, question: "Which was an early mainframe computer?", answer: "ENIAC", options: [ "ENIAC", "EDVAC", "UNIC", "ABACUS" ] }, { id: 9, question: "Main circuit board in a computer is:", answer: "Mother board", options: [ "Harddisk", "Mother board", "Microprocessor", "None of these" ] }, { id: 10, question: "ISP stands for:", answer: "Internet Service Provider", options: [ "Internet Survey Period", "Integreted Service Provider", "Internet Security Protocol", "Internet Service Provider" ] }, ]; let question_count = 0; let points = 0; window.onload = function(){ show(question_count); }; function show(count){ let question = document.getElementById("questions"); let[first, second, third, fourth] = questions[count].options; question.innerHTML = `<h2>Q${count + 1}. ${questions[count].question}</h2> <ul class="option_group"> <li class="option">${first}</li> <li class="option">${second}</li> <li class="option">${third}</li> <li class="option">${fourth}</li> </ul>`; toggleActive(); } function toggleActive(){ let option = document.querySelectorAll("li.option"); for(let i=0; i < option.length; i++){ option[i].onclick = function(){ for(let i=0; i < option.length; i++){ if(option[i].classList.contains("active")){ option[i].classList.remove("active"); } } option[i].classList.add("active"); } } } function next(){ if(question_count == questions.length -1){ location.href = "final.html"; } console.log(question_count); let user_answer = document.querySelector("li.option.active").innerHTML; if(user_answer == questions[question_count].answer){ points += 1; sessionStorage.setItem("points",points); } console.log(points); question_count++; show(question_count); }
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service("userService") public class UserServiceImpl implements UserService { @Autowired UserRepository userRepository; PasswordEncoder passwordEncoder; @Override public List<UserEntity> findAll() { List<UserEntity> users = new ArrayList<>(); userRepository.findAll().forEach(e -> users.add(e)); return users; } @Override public void signUp(UserSignUpDto userSignUpDto) throws Exception { // email 중복 체크 if(userRepository.findByEmail(userSignUpDto.getEmail()).isPresent()) { throw new Exception("이미 존재하는 이메일입니다."); } UserEntity user = UserEntity.builder() .email(userSignUpDto.getEmail()) .name(userSignUpDto.getName()) .password(userSignUpDto.getPassword()) .age(userSignUpDto.getAge()) .build(); user.passwordEncode(passwordEncoder); userRepository.save(user); } }
import { getMeltBuilderName, isAliasedAction, walk } from '../helpers.js'; import { traverse } from './index.js'; import type { TemplateNode } from 'svelte/types/compiler/interfaces'; import type { Config, Node } from '../types.js'; type BlockArgs = { blockNode: TemplateNode; config: Config; }; /** * Traverses any given block and checks if there are any identifiers * that exist in it's child `melt` action's expression. * * If there are, we'll inject an `{@const}` block into the provided block * with it's corresponding identifiers. */ export function traverseBlock({ blockNode, config }: BlockArgs) { if (blockNode.children === undefined) return; // walk the children to determine if the block's provided identifiers are // being used in the melt action's expression walk(blockNode.children, { enter(node) { if ( node.type === 'Action' && isAliasedAction(node.name, config.alias) && node.expression !== null // assigned to something ) { handleActionNode({ actionNode: node, blockNode, config, }); // we don't have to walk the Action's children this.skip(); return; } // if it's anything else, walk again const returnedActions = traverse({ baseNode: node, config }); for (const actionNode of returnedActions) { handleActionNode({ actionNode, blockNode, config, }); } // only want to walk over the direct children, so we'll skip the rest this.skip(); }, }); } type HandleActionNodeArgs = { blockNode: TemplateNode; actionNode: TemplateNode; config: Config; }; /** * Injects the `{@const}` tag as a child of the provided block * node if the expression is anything but an `Identifier`. */ function handleActionNode({ config, actionNode, blockNode }: HandleActionNodeArgs) { const expression = actionNode.expression as Node; // any other expression type... // i.e. use:melt={$builder({ arg1: '', arg2: '' })} if (expression.type !== 'Identifier') { const expressionContent = config.content.substring(expression.start, expression.end); // extract the indent of the block such that the indentation of the injected // {@const} tag is in line with the rest of the block const blockContent = config.content.substring(blockNode.start, blockNode.end); const blockLines = blockContent.split('\n'); const indent = blockLines.at(1)?.match(/\s*/); // a weird quirk with Await and Component blocks where the first child // is a Text node, so we'll ignore them and take the 2nd child instead let firstChild = blockNode.children?.at(0); if (firstChild?.type === 'Text') { firstChild = blockNode.children?.at(1); } // convert this into a {@const} block const start = firstChild?.start; const constIdentifier = getMeltBuilderName(config.builderCount++); if (!start) throw Error('This is unreachable'); config.builders.push({ identifierName: constIdentifier, startPos: actionNode.start, endPos: actionNode.end, }); config.markup.prependRight( start, `{@const ${constIdentifier} = ${expressionContent}}\n${indent}` ); } else { // if it's just an identifier, add it to the list of builders so that it can // later be transformed into the correct syntax // i.e. use:melt={$builder} config.builders.push({ identifierName: expression.name, startPos: actionNode.start, endPos: actionNode.end, }); } }
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Auth0 App</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link" aria-current="page" routerLink="/home" routerLinkActive="active">Home</a> </li> <li class="nav-item"> <a class="nav-link" aria-current="page" routerLink="/precios" routerLinkActive="active">Precios</a> </li> <li class="nav-item"> <a class="nav-link" aria-current="page" routerLink="/protegida" routerLinkActive="active">Protegida</a> </li> </ul> <div class="d-flex"> '<button (click)="auth.loginWithRedirect()">Log in</button> <ng-container *ngIf="auth.isAuthenticated$ | async; else loggedOut"> <button (click)="auth.logout({ returnTo: document.location.origin })"> Log out </button> </ng-container> <ng-template #loggedOut> <button (click)="auth.loginWithRedirect()">Log in</button> </ng-template> </div> </div> </div> </nav>
""" Formats the primers into an output tsv file: All sequences are outputted in 5' -> 3' - amplicon_name: name of the amplicon - forward_sequence: sequence of the forward primer - reverse_sequence: sequence of the reverse primer """ import logging import argparse import json import pandas as pd from handlers import DBHandler logging.basicConfig(level=logging.INFO) def __get_parser() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Formatting primers into tsv") parser.add_argument( "--input", type=str, required=True, help="Path to final primers json file", ) parser.add_argument( "--output", type=str, required=True, help="Path to output file", ) return parser.parse_args() def __format_to_tsv(input_file: str, output_file: str) -> None: with open(input_file, "r") as f: primers = json.load(f) # Iterate through each primer set and merge into one dataframe logging.info("All sequences are outputted in 5' -> 3'") column_names = [ "amplicon_name", "forward_primer_sequence (5' -> 3')", "reverse_primer_sequence (5' -> 3')", ] data = [] for primer_set in primers: primer_pairs = primer_set.get("primer_pairs", []) # Iterate through each primer pair for primer_pair in primer_pairs: amplicon_name = primer_pair.get("amplicon_name", "") forward_primer_sequence = primer_pair.get("forward_primer", {}).get( "sequence", "" ) reverse_primer_sequence = primer_pair.get("reverse_primer", {}).get( "sequence", "" ) data.append( [amplicon_name, forward_primer_sequence, reverse_primer_sequence] ) df = pd.DataFrame(data, columns=column_names) # write to tsv logging.info(f"Writing {df.shape[0]} rows to {output_file}") df.to_csv(output_file, index=False, sep="\t") def main(): logging.info("Formatting primers into tsv") args = __get_parser() __format_to_tsv(args.input, args.output) logging.info("Done") if __name__ == "__main__": main()
/* * This file is part of the Colobot: Gold Edition source code * Copyright (C) 2001-2018, Daniel Roux, EPSITEC SA & TerranovaTeam * http://epsitec.ch; http://colobot.info; http://github.com/colobot * * 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://gnu.org/licenses */ /** * \file math/vector.h * \brief Vector struct and related functions */ #pragma once #include "math/const.h" #include "math/func.h" #include <cmath> #include <sstream> // Math module namespace namespace Math { /** * \struct Vector * \brief 3D (3x1) vector * * Represents a universal 3x1 vector that can be used in OpenGL and DirectX engines. * Contains the required methods for operating on vectors. * * All methods are made inline to maximize optimization. * * Unit tests for the structure and related functions are in module: math/test/vector_test.cpp. * */ struct Vector { //! X - 1st coord float x; //! Y - 2nd coord float y; //! Z - 3rd coord float z; //! Creates a zero vector (0, 0, 0) inline Vector() : x(0.0f) , y(0.0f) , z(0.0f) {} //! Creates a vector from given values inline explicit Vector(float _x, float _y, float _z) : x(_x) , y(_y) , z(_z) {} //! Loads the zero vector (0, 0, 0) inline void LoadZero() { x = y = z = 0.0f; } //! Returns the struct cast to \c float* array; use with care! inline float* Array() { return reinterpret_cast<float*>(this); } //! Returns the struct cast to <tt>const float*</tt> array; use with care! inline const float* Array() const { return reinterpret_cast<const float*>(this); } //! Returns the vector length inline float Length() const { return sqrtf(x*x + y*y + z*z); } //! Normalizes the vector inline void Normalize() { float l = Length(); if (IsZero(l)) return; x /= l; y /= l; z /= l; } //! Calculates the cross product with another vector /** * \param right right-hand side vector * \returns the cross product */ inline Vector CrossMultiply(const Vector &right) const { float px = y * right.z - z * right.y; float py = z * right.x - x * right.z; float pz = x * right.y - y * right.x; return Vector(px, py, pz); } //! Calculates the dot product with another vector /** * \param right right-hand side vector * \returns the dot product */ inline float DotMultiply(const Vector &right) const { return x * right.x + y * right.y + z * right.z; } //! Returns the cosine of angle between this and another vector inline float CosAngle(const Vector &right) const { return DotMultiply(right) / (Length() * right.Length()); } //! Returns angle (in radians) between this and another vector inline float Angle(const Vector &right) const { return acos(CosAngle(right)); } /* Operators */ //! Returns the inverted vector inline Vector operator-() const { return Vector(-x, -y, -z); } //! Adds the given vector inline const Vector& operator+=(const Vector &right) { x += right.x; y += right.y; z += right.z; return *this; } //! Adds two vectors inline friend const Vector operator+(const Vector &left, const Vector &right) { return Vector(left.x + right.x, left.y + right.y, left.z + right.z); } //! Subtracts the given vector inline const Vector& operator-=(const Vector &right) { x -= right.x; y -= right.y; z -= right.z; return *this; } //! Subtracts two vectors inline friend const Vector operator-(const Vector &left, const Vector &right) { return Vector(left.x - right.x, left.y - right.y, left.z - right.z); } //! Multiplies by given scalar inline const Vector& operator*=(const float &right) { x *= right; y *= right; z *= right; return *this; } //! Multiplies vector by scalar inline friend const Vector operator*(const float &left, const Vector &right) { return Vector(left * right.x, left * right.y, left * right.z); } //! Multiplies vector by scalar inline friend const Vector operator*(const Vector &left, const float &right) { return Vector(left.x * right, left.y * right, left.z * right); } //! Divides by given scalar inline const Vector& operator/=(const float &right) { x /= right; y /= right; z /= right; return *this; } //! Divides vector by scalar inline friend const Vector operator/(const Vector &left, const float &right) { return Vector(left.x / right, left.y / right, left.z / right); } //! Returns a string "[x, y, z]" inline std::string ToString() const { std::stringstream s; s.precision(3); s << "[" << x << ", " << y << ", " << z << "]"; return s.str(); } }; // struct Vector //! Checks if two vectors are equal within given \a tolerance inline bool VectorsEqual(const Math::Vector &a, const Math::Vector &b, float tolerance = TOLERANCE) { return IsEqual(a.x, b.x, tolerance) && IsEqual(a.y, b.y, tolerance) && IsEqual(a.z, b.z, tolerance); } //! Convenience function for getting normalized vector inline Vector Normalize(const Math::Vector &v) { Vector result = v; result.Normalize(); return result; } //! Convenience function for calculating dot product inline float DotProduct(const Math::Vector &left, const Math::Vector &right) { return left.DotMultiply(right); } //! Convenience function for calculating cross product inline Vector CrossProduct(const Math::Vector &left, const Math::Vector &right) { return left.CrossMultiply(right); } //! Convenience function for calculating angle (in radians) between two vectors inline float Angle(const Math::Vector &a, const Math::Vector &b) { return a.Angle(b); } //! Returns the distance between the ends of two vectors inline float Distance(const Math::Vector &a, const Math::Vector &b) { return sqrtf( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) + (a.z-b.z)*(a.z-b.z) ); } //! Clamps the vector \a vec to range between \a min and \a max inline Vector Clamp(const Vector &vec, const Vector &min, const Vector &max) { Vector clamped; clamped.x = Min(Max(min.x, vec.x), max.x); clamped.y = Min(Max(min.y, vec.y), max.y); clamped.z = Min(Max(min.z, vec.z), max.z); return clamped; } } // namespace Math
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="static/stylesheets/main.css" /> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js"</script> <script src="/static/javascript/main.js"</script> </head> <body> <div id="all_content"> <div id="header"> <div> <img id="logo" src="/static/images/pandas.jpg" /> </div> <div id="title"> Query a CSV File with Pandas </div> </div> <div ng-app="csvQuery" id="queryForm"> <form ng-submit="submit()" ng-controller="QueryController"> <input id="queryText" type="text" ng-model="text" name="text" autofocus /> <input type="submit" id="submit" value="Submit" /> <div id="result" ng-bind-html="result"></div> </form> </div> </div> <script> angular.module('csvQuery', []) .controller('QueryController', function($scope, $http, $sce) { $scope.submit = function() { $http({method: 'GET', url: 'http://localhost:5000/query?q=' + encodeURIComponent($scope.text)}). success(function(data, status, headers, config) { var index = data.indexOf(':'); var count = data.substring(0, index); var records = data.substring(index + 1, data.length); var result = '<h4>Your query returned ' + count + ' records</h4>' + records; $scope.result = $sce.trustAsHtml(result); }). error(function(data, status, headers, config) { $scope.result = $sce.trustAsHtml('<span class="error">Error: ' + data + '</span>'); }); } }); </script> </body> </html>
import { IsEmail, IsStrongPassword } from 'class-validator' export class RegisterDto { @IsEmail() email: string @IsStrongPassword( { minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 0, }, { message: 'The password is not strong enough. ' + 'It should contain at least 8 characters. ' + 'Minimum 1 lowercase character, 1 uppercase character and 1 digit', }, ) password: string }
import matplotlib.pyplot as plt import math def taxicab_distance(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) def taxicab_diameter(x_coords, y_coords): n = len(x_coords) max_distance = 0 max_i, max_j = 0, 0 for i in range(n): for j in range(i+1, n): distance = taxicab_distance(x_coords[i], y_coords[i], x_coords[j], y_coords[j]) if distance > max_distance: max_distance = distance max_i, max_j = i, j return max_distance, max_i, max_j def draw_triangle(ax, x_coords, y_coords, label): ax.plot(x_coords + [x_coords[0]], y_coords + [y_coords[0]], 'bo-') # Draw the triangle ax.text((x_coords[0] + x_coords[1]) / 2, y_coords[0], label, color='blue', fontsize=10, ha='center') # Label it def plot_taxicab_diameter(ax, x_coords, y_coords, angle, diameter): ax.plot([x_coords[0], x_coords[1]], [y_coords[0], y_coords[1]], 'k--', alpha=0.5) # Plot the line for angle ax.text(x_coords[1], y_coords[1], f"Açı: {angle}°", color='black', fontsize=10, ha='center', va='bottom', alpha=0.5) # Label the angle ax.plot([x_coords[2], (x_coords[1] + x_coords[2]) / 2], [y_coords[2], (y_coords[1] + y_coords[2]) / 2], 'k--', alpha=0.5) # Plot the line for diameter ax.text((x_coords[1] + x_coords[2]) / 2, (y_coords[1] + y_coords[2]) / 2, f"Taxicab Çapı: {diameter:.2f}", color='black', fontsize=10, ha='center', va='top', alpha=0.5) # Label the diameter def main(): fig, ax = plt.subplots(figsize=(8, 6)) ax.set_xlabel('X Koordinatı') ax.set_ylabel('Y Koordinatı') ax.set_title("Eşkenar Üçgen ve Taxicab Çapı") # Eşkenar üçgenin taban uzunluğu ve yüksekliği base_length = 2 # Eşkenar üçgenin taban uzunluğu # Başlangıçta eşkenar üçgenin yüksekliği height = math.sqrt(3) / 2 * base_length # Eşkenar üçgenin yüksekliği (tabanın uzunluğunun yarısı * √3/2) # Eşkenar üçgenin köşe noktaları x_coords = [0, base_length / 2, base_length] y_coords = [0, height, 0] # Eşkenar üçgeni çiz draw_triangle(ax, x_coords, y_coords, "Eşkenar Üçgen") # Başlangıçta taxicab çapını hesapla ve çiz diameter, _, _ = taxicab_diameter(x_coords, y_coords) plot_taxicab_diameter(ax, x_coords, y_coords, "Eşkenar", diameter) plt.grid(True) plt.axis('equal') plt.show() while True: # Kullanıcıdan açı değeri alınır angle = float(input("Açı değerini girin (0 ile 180 arasında, 0 ve 180 olmayacak): ")) if 0 < angle < 180: # Yüksekliğin sabit olduğu bir durumda, açıya göre yükseklik hesaplanır height = math.tan(math.radians(angle)) * (base_length / 2) # Eşkenar üçgenin diğer iki köşesi hesaplanır x2 = base_length / 2 y2 = height x3 = base_length y3 = 0 # Eşkenar üçgenin koordinatları listelenir x_coords = [0, x2, x3] y_coords = [0, y2, 0] # Üçgen çizdirilir ve taxicab çapı çizilir draw_triangle(ax, x_coords, y_coords, f"Açı: {angle}°") diameter, _, _ = taxicab_diameter(x_coords, y_coords) plot_taxicab_diameter(ax, x_coords, y_coords, angle, diameter) plt.grid(True) plt.axis('equal') plt.show() devam = input("Devam etmek istiyor musunuz? (E/H): ") if devam.upper() != 'E': break else: print("Geçerli bir açı değeri girin.") if __name__ == "__main__": main()
package com.declarative.music.interpreter; import com.declarative.music.interpreter.values.LambdaClousure; import com.declarative.music.interpreter.values.VariableReference; import com.declarative.music.interpreter.values.Variant; import com.declarative.music.lexer.token.Position; import com.declarative.music.parser.production.*; import com.declarative.music.parser.production.expression.Expression; import com.declarative.music.parser.production.expression.arithmetic.AddExpression; import com.declarative.music.parser.production.expression.arithmetic.MinusUnaryExpression; import com.declarative.music.parser.production.expression.arithmetic.PlusUnaryExpression; import com.declarative.music.parser.production.expression.array.ArrayExpression; import com.declarative.music.parser.production.expression.array.ListComprehension; import com.declarative.music.parser.production.expression.array.RangeExpression; import com.declarative.music.parser.production.expression.lambda.FunctionCall; import com.declarative.music.parser.production.expression.lambda.LambdaExpression; import com.declarative.music.parser.production.expression.pipe.InlineFuncCall; import com.declarative.music.parser.production.expression.pipe.PipeExpression; import com.declarative.music.parser.production.expression.relation.EqExpression; import com.declarative.music.parser.production.literal.FloatLiteral; import com.declarative.music.parser.production.literal.IntLiteral; import com.declarative.music.parser.production.literal.StringLiter; import com.declarative.music.parser.production.type.InferenceType; import com.declarative.music.parser.production.type.SimpleType; import com.declarative.music.parser.production.type.Types; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; public class InterpretationTest { private Executor tested; private static final Position POS = new Position(0, 0); private static final String VAR_NAME = "testVar"; private static Stream<Arguments> provideFunctionCalls() { return Stream.of( Arguments.of(new FunctionCall("fun", List.of(new IntLiteral(1, POS)), POS)), Arguments.of(new PipeExpression( new IntLiteral(1, POS), new InlineFuncCall("fun", List.of(), POS)) ) ); } private static Stream<Arguments> provideWrongArgumentTypeFunctionCalls() { return Stream.of( Arguments.of(new FunctionCall("fun", List.of(new FloatLiteral(1.0, POS)), POS)), Arguments.of(new PipeExpression( new FloatLiteral(1.0, POS), new InlineFuncCall("fun", List.of(), POS)) ) ); } private static Stream<Arguments> provideWrongNumberOfArgumentsFunctionCalls() { return Stream.of( Arguments.of(new FunctionCall("fun", List.of(new IntLiteral(1, POS), new IntLiteral(1, POS)), POS)), Arguments.of(new PipeExpression( new IntLiteral(1, POS), new InlineFuncCall("fun", List.of(new IntLiteral(1, POS)), POS)) ) ); } @BeforeEach void init() { tested = new Executor(); } //region Arithmetic Expression @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideArithmeticExpressions") void shouldCalculateArithmeticExpression(Expression expression, Variant<?> expectedValue) { // when expression.accept(tested); // then assertThat(tested.getCurrentValue()).isEqualTo(expectedValue); } @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideIncompatibleArithmeticExpressions") void shouldThrowWhenDifferentTypes(Expression expression, Class<?> leftType, Class<?> rightType) { // when assertThatThrownBy(() -> expression.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR Unsupported types: %s %s for operation: %s". formatted(leftType.getSimpleName(), rightType.getSimpleName(), expression.getClass().getSimpleName())); } @Test void shouldThrow_WhenUnsupportedMinusUnaryExpression() { // given var expression = new MinusUnaryExpression(new StringLiter("a", POS)); // when assertThatThrownBy(() -> expression.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR cannot negate String type"); } @Test void shouldThrow_WhenUnsupportedPlusUnaryExpression() { // given var expression = new PlusUnaryExpression(new StringLiter("a", POS)); // when assertThatThrownBy(() -> expression.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR cannot plus String type"); } //endregion //region Cast expression @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideCastArguments") void shouldCastExpression(Expression value, Types targetType, Variant<?> expectedValue) { // when StubsFactory.createCastExpression(value, targetType).accept(tested); // then assertThat(tested.getCurrentValue()).isEqualTo(expectedValue); } @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideUncastableArguments") void shouldThrow_WhenUnCastableExpression(Expression value, Types targetType) { // when assertThatThrownBy(() -> StubsFactory.createCastExpression(value, targetType).accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR Cannot cast"); } //endregion //region Logical Expression @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideBooleanExpressions") void shouldCalculateOrderingExpression(Expression expression, Variant<?> expectedValue) { // when expression.accept(tested); // then assertThat(tested.getCurrentValue()).isEqualTo(expectedValue); } @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideIncompatibleOrderingExpressions") void shouldThrowOrdering_WhenDifferentTypes(Expression expression, Class<?> leftType, Class<?> rightType) { // when assertThatThrownBy(() -> expression.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR Unsupported types: %s %s for operation: %s". formatted(leftType.getSimpleName(), rightType.getSimpleName(), expression.getClass().getSimpleName())); } @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideCompoundRelationExpressions") void shouldCalculateComplexRelationExpression(Expression expression, Variant<?> expectedValue) { // when expression.accept(tested); // then assertThat(tested.getCurrentValue()).isEqualTo(expectedValue); } //endregion //region Binary assigment @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideBinaryAssigments") void shouldExecuteExpressionWithAssigment(Variant<?> initialValue, Statement binaryAssignStmt, Variant<?> expectedValue) { // given tested.getManager().insert(VAR_NAME, initialValue); // when binaryAssignStmt.accept(tested); // then assertThat(tested.getManager().get(VAR_NAME).orElseThrow()) .isEqualToComparingFieldByFieldRecursively(expectedValue); } //endregion //region Music and Index tree @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideNoteExpressions") void shouldHandleMusicTreeExpression(Expression noteExpression, Variant<?> expectedTree) { // when noteExpression.accept(tested); // then assertThat(tested.getCurrentValue()).isEqualToComparingFieldByFieldRecursively(expectedTree); } @ParameterizedTest @MethodSource("com.declarative.music.interpreter.StubsFactory#provideIndexExpressions") void shouldHandleIndexTreeExpression(Expression indexExpression, Variant<?> expectedTree) { // when indexExpression.accept(tested); // then assertThat(tested.getCurrentValue()).isEqualToComparingFieldByFieldRecursively(expectedTree); } //endregion //region Lambda Expressions and Call private static LambdaExpression createIdentityFunction() { return new LambdaExpression( new Parameters(List.of(new Parameter(new SimpleType(Types.Int, POS), "a"))), new SimpleType(Types.Int, POS), new Block(List.of( new ReturnStatement(new com.declarative.music.parser.production.expression.VariableReference("a", POS), POS) ), POS), POS ); } @ParameterizedTest @MethodSource("provideFunctionCalls") void shouldCallFunction(Expression functionCall) { // given var stmt = new Declaration(new InferenceType(POS), "fun", createIdentityFunction()); stmt.accept(tested); //when functionCall.accept(tested); // then assertThat(tested.getCurrentValue().value()).isEqualTo(1); } @ParameterizedTest @MethodSource("provideWrongArgumentTypeFunctionCalls") void shouldThrow_WhenWrongTypeOfArguments(Expression functionCall) { // given var stmt = new Declaration(new InferenceType(POS), "fun", createIdentityFunction()); stmt.accept(tested); //when assertThatThrownBy(() -> functionCall.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR wrong argument type expected Integer got Double"); } @ParameterizedTest @MethodSource("provideWrongNumberOfArgumentsFunctionCalls") void shouldThrow_WhenWrongNumberOfArguments(Expression functionCall) { // given var stmt = new Declaration(new InferenceType(POS), "fun", createIdentityFunction()); stmt.accept(tested); //when assertThatThrownBy(() -> functionCall.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR wrong number of arguments expected 1 got 2"); } @ParameterizedTest @MethodSource("provideFunctionCalls") void shouldHandleFunction_WithInferenceParameters(Expression functionCall) { // given var inferenceFunction = new LambdaExpression( new Parameters(List.of(new Parameter(new InferenceType(POS), "a"))), new InferenceType(POS), new Block(List.of( new ReturnStatement(new com.declarative.music.parser.production.expression.VariableReference("a", POS), POS) ), POS), POS ); var stmt = new Declaration(new InferenceType(POS), "fun", inferenceFunction); stmt.accept(tested); //when functionCall.accept(tested); // then assertThat(tested.getCurrentValue().value()).isEqualTo(1); } // // @Test // void shouldThrow_WhenWrongReturnType() { // // given // var func = new LambdaExpression( // new Parameters(List.of(new Parameter(new SimpleType(Types.Int, POS), "a"))), // new SimpleType(Types.Double, POS), // new Block(List.of( // new ReturnStatement(new com.declarative.music.parser.production.expression.VariableReference("a", POS), POS) // ), POS), // POS // ); // var stmt = new Declaration(new InferenceType(POS), "fun", func); // stmt.accept(tested); // var functionCall = new FunctionCall("fun", List.of(new IntLiteral(1, POS)), POS); // //when // assertThatThrownBy(() -> functionCall.accept(tested)) // .hasMessageStartingWith("INTERPRETATION ERROR wrong return type expected Double got Integer"); // } //endregion //region Types // @Test // void shouldCheckLambdaTypes() { // // given // var type = new LambdaType(List.of( // new SimpleType(Types.Int, POS), // new SimpleType(Types.Double, POS) // ), new SimpleType(Types.Int, POS), POS); // var lambda = new LambdaExpression(new Parameters(List.of( // new Parameter(new SimpleType(Types.Int, POS), "a"), // new Parameter(new SimpleType(Types.Int, POS), "b"))), // new SimpleType(Types.Int, POS), new Block(List.of(), POS), POS); // var stmt = new Declaration(type, "a", lambda); // // when // assertThatThrownBy(() -> stmt.accept(tested)) // .hasMessageStartingWith("SEMANTIC ERROR cannot assign value to variable of different type"); // } //endregion @Test void shouldDeclareAndAssignValue() { // given var variableName = "a"; var variableValue = 1; var stmt = new Declaration(new SimpleType(Types.Int, POS), variableName, new IntLiteral(variableValue, POS)); // when stmt.accept(tested); var frame = tested.getManager().getGlobalFrame(); // then assertEquals(frame.getValue(variableName).map(com.declarative.music.interpreter.values.VariableReference::getValue).orElseThrow(), variableValue); } @Test void shouldAssignValue() { // given var variableName = "a"; var variableValue = 1; var newValue = 2; var frame = new Frame(new HashMap<>(Map.of(variableName, new VariableReference<Integer>(variableValue)))); tested = new Executor(new ContextManager(frame)); var stmt = new AssigmentStatement(variableName, new IntLiteral(newValue, POS), POS); // when stmt.accept(tested); // then assertEquals(frame.getValue(variableName).map(com.declarative.music.interpreter.values.VariableReference::getValue).orElseThrow(), newValue); } @Test void shouldHandleIfStatement() { // given var variableName = "a"; var variableValue = 1; var newValue = 2; var frame = new Frame(new HashMap<>(Map.of(variableName, new VariableReference<Integer>(variableValue)))); tested = new Executor(new ContextManager(frame)); var stmt = new IfStatement( new EqExpression(new IntLiteral(1, POS), new IntLiteral(1, POS)), new Block(List.of(new AssigmentStatement(variableName, new IntLiteral(newValue, POS), POS)), POS), POS ); // when stmt.accept(tested); // then assertEquals(newValue, frame.getValue(variableName).map(VariableReference::getValue).orElseThrow()); } @Test void shouldThrow_whenAssigmentToUnknownVariable() { // given var variableName = "a"; var variableValue = 1; var stmt = new AssigmentStatement(variableName, new IntLiteral(variableValue, POS), POS); // when assertThatThrownBy(() -> stmt.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR"); } @Test void shouldThrow_whenAssigmentWithWrongValueType() { // given var variableName = "a"; var variableValue = 1; var newValue = "a"; var frame = new Frame(new HashMap<>(Map.of(variableName, new VariableReference<Integer>(variableValue)))); tested = new Executor(new ContextManager(frame)); var stmt = new AssigmentStatement(variableName, new StringLiter(newValue, POS), POS); // when assertThatThrownBy(() -> stmt.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR required Integer provided String"); } @Test void shouldDeclareAndAssignExpression() { // given var variableName = "a"; var expectedValue = 3; var stmt = new Declaration(new SimpleType(Types.Int, POS), variableName, new AddExpression(new IntLiteral(1, POS), new IntLiteral(2, POS))); // when stmt.accept(tested); var frame = tested.getManager().getGlobalFrame(); // then assertEquals(frame.getValue(variableName).map(com.declarative.music.interpreter.values.VariableReference::getValue).orElseThrow(), expectedValue); } @Test void shouldThrow_whenInBinaryOperationUncorrectType() { // given var stmt = new AddExpression(new IntLiteral(1, POS), new FloatLiteral(2D, POS)); // when assertThatThrownBy(() -> stmt.accept(tested)) .hasMessageStartingWith("INTERPRETATION ERROR"); } @Test void shouldAssignLambdaDeclaration() { var variableName = "a"; var lambda = new LambdaExpression( new Parameters(List.of(new Parameter(new SimpleType(Types.Int, POS), "a"))), new SimpleType(Types.Int, POS), new Block(List.of(new ReturnStatement(new IntLiteral(1, POS), POS)), POS), POS ); var stmt = new Declaration(new InferenceType(POS), variableName, lambda); stmt.accept(tested); } @Test void shouldHandlePipeExpression() { // given var variableName = "a"; var lambda = new LambdaClousure(new LambdaExpression( new Parameters(List.of(new Parameter(new SimpleType(Types.Int, POS), variableName))), new SimpleType(Types.Int, POS), new Block(List.of(new ReturnStatement(new com.declarative.music.parser.production.expression.VariableReference(variableName, POS), POS)), POS), POS ), new Frame()); tested.getManager().insert("fun", new Variant<>(lambda, LambdaClousure.class)); var stmt = new PipeExpression(new IntLiteral(1, POS), new InlineFuncCall("fun", List.of(), POS)); // when stmt.accept(tested); assertEquals(1, ((Variant<Integer>) tested.getCurrentValue()).value()); } @Test void shouldHandleArrayExpression() { // given var stmt = new ArrayExpression(List.of( new IntLiteral(1, POS), new IntLiteral(2, POS), new com.declarative.music.parser.production.expression.VariableReference("a", POS) ), POS); tested.getManager().insert("a", new Variant<>(1, Integer.class)); // when stmt.accept(tested); // then assertThat(tested.getCurrentValue().value()) .isEqualToComparingFieldByFieldRecursively(List.of( new Variant<>(1, Integer.class), new Variant<>(2, Integer.class), new Variant<>(new VariableReference<>(1), VariableReference.class) )); } @Test void shouldHandleListComprehension_WithArrayIterable() { // given var stmt = new ListComprehension( new AddExpression(new com.declarative.music.parser.production.expression.VariableReference("x", POS), new IntLiteral(2, POS)), new com.declarative.music.parser.production.expression.VariableReference("x", POS), new ArrayExpression(List.of( new IntLiteral(1, POS), new IntLiteral(2, POS), new com.declarative.music.parser.production.expression.VariableReference("a", POS) ), POS), POS); tested.getManager().insert("a", new Variant<>(10, Integer.class)); // when stmt.accept(tested); // then assertThat(tested.getCurrentValue().value()) .isEqualToComparingFieldByFieldRecursively(List.of( new Variant<>(3, Integer.class), new Variant<>(4, Integer.class), new Variant<>(12, Integer.class) )); } @Test void shouldHandleListComprehension() { // given var stmt = new ListComprehension( new AddExpression(new com.declarative.music.parser.production.expression.VariableReference("x", POS), new IntLiteral(2, POS)), new com.declarative.music.parser.production.expression.VariableReference("x", POS), new RangeExpression(new IntLiteral(1, POS), new IntLiteral(5, POS)), POS); // when stmt.accept(tested); // then assertThat(tested.getCurrentValue().value()) .isEqualToComparingFieldByFieldRecursively(List.of( new Variant<>(3, Integer.class), new Variant<>(4, Integer.class), new Variant<>(5, Integer.class), new Variant<>(6, Integer.class) )); } @Test void shouldHandleAtBuiltInMethod() { // given var atFuncCall = new FunctionCall("at", List.of( new com.declarative.music.parser.production.expression.VariableReference("arr", POS), new IntLiteral(1, POS) ), POS); tested.getManager().insert("arr", new Variant<>(List.of( new Variant<>(1, Integer.class), new Variant<>(2, Integer.class), new Variant<>(3, Integer.class) ), List.class)); // when atFuncCall.accept(tested); // then assertThat(tested.getCurrentValue()).isEqualTo(new Variant<>(2, Integer.class)); } }
# image-size [![Build Status](https://circleci.com/gh/image-size/image-size.svg?style=shield)](https://circleci.com/gh/image-size/image-size) [![Package Version](https://img.shields.io/npm/v/image-size.svg)](https://www.npmjs.com/package/image-size) [![Downloads](https://img.shields.io/npm/dm/image-size.svg)](http://npm-stat.com/charts.html?package=image-size&author=&from=&to=) A [Node](https://nodejs.org/en/) module to get dimensions of any image file ## Supported formats * BMP * CUR * DDS * GIF * ICNS * ICO * JPEG * KTX * PNG * PNM (PAM, PBM, PFM, PGM, PPM) * PSD * SVG * TIFF * WebP ## Programmatic Usage ```shell npm install image-size --save ``` or ```shell yarn add image-size ``` ### Synchronous ```javascript const sizeOf = require('image-size') const dimensions = sizeOf('images/funny-cats.png') console.log(dimensions.width, dimensions.height) ``` ### Asynchronous ```javascript const sizeOf = require('image-size') sizeOf('images/funny-cats.png', function (err, dimensions) { console.log(dimensions.width, dimensions.height) }) ``` NOTE: The asynchronous version doesn't work if the input is a Buffer. Use synchronous version instead. Also, the asynchronous functions have a default concurreny limit of **100** To change this limit, you can call the `setConcurrency` function like this: ```javascript const sizeOf = require('image-size') sizeOf.setConcurrency(123456) ``` ### Using promises (nodejs 10.x+) ```javascript const { promisify } = require('util') const sizeOf = promisify(require('image-size')) sizeOf('images/funny-cats.png') .then(dimensions => { console.log(dimensions.width, dimensions.height) }) .catch(err => console.error(err)) ``` ### Async/Await (Typescript & ES7) ```javascript const { promisify } = require('util') const sizeOf = promisify(require('image-size')) (async () => { try { const dimensions = await sizeOf('images/funny-cats.png') console.log(dimensions.width, dimensions.height) } catch (err) { console.error(err) } })().then(c => console.log(c)) ``` ### Multi-size If the target file is an icon (.ico) or a cursor (.cur), the `width` and `height` will be the ones of the first found image. An additional `images` array is available and returns the dimensions of all the available images ```javascript const sizeOf = require('image-size') const images = sizeOf('images/multi-size.ico').images for (const dimensions of images) { console.log(dimensions.width, dimensions.height) } ``` ### Using a URL ```javascript const url = require('url') const http = require('http') const sizeOf = require('image-size') const imgUrl = 'http://my-amazing-website.com/image.jpeg' const options = url.parse(imgUrl) http.get(options, function (response) { const chunks = [] response.on('data', function (chunk) { chunks.push(chunk) }).on('end', function() { const buffer = Buffer.concat(chunks) console.log(sizeOf(buffer)) }) }) ``` You can optionally check the buffer lengths & stop downloading the image after a few kilobytes. **You don't need to download the entire image** ### Disabling certain image types ```javascript const imageSize = require('image-size') imageSize.disableTypes(['tiff', 'ico']) ``` ### Disabling all file-system reads ```javascript const imageSize = require('image-size') imageSize.disableFS(true) ``` ## Command-Line Usage (CLI) ```shell npm install image-size --global ``` or ```shell yarn global add image-size ``` followed by ```shell image-size image1 [image2] [image3] ... ``` ## Hosted API We also provide a hosted API for image-size which may simplify your use case. <a href="https://image-size.saasify.sh"> <img src="https://badges.saasify.sh?text=View%20Hosted%20API" height="40"/> </a> ## Credits not a direct port, but an attempt to have something like [dabble's imagesize](https://github.com/dabble/imagesize/blob/master/lib/image_size.rb) as a node module. ## [Contributors](Contributors.md)
# frozen_string_literal: true class MatchDaysController < ApplicationController def last @match_day = MatchDay.previous if @match_day assign_bets render "match_day", match_day: @match_day else head :ok end end def next @match_day = MatchDay.next if @match_day bonus_used create_bets render "match_day", match_day: @match_day else head :ok end end def update_bets @match_day = MatchDay.find(params[:id]) assign_bets Bet.transaction do @bets.update_all(bonus: false) # rubocop:disable Rails/SkipsModelValidations @bets.each do |bet| bet.update!(bet_params(params[:bets][bet.id.to_s])) end head :ok rescue ActiveRecord::RecordInvalid head :unprocessable_entity end end def show @match_day = MatchDay.find(params[:id]) if @match_day.stop_bet_time.past? after_bet_time else before_bet_time end end private def before_bet_time respond_to do |format| format.html { render "before_bet_time" } format.json do bonus_used create_bets render "match_day" end end end def after_bet_time respond_to do |format| format.html { render "after_bet_time" } format.json do @matches = @match_day.matches.includes(%i[team1 team2 bets]) @users = User.all.order(:name) render "show" end end end def assign_bets @bets = @match_day.bets .includes(match: %i[team1 team2]) .where(user: current_user) end def create_bets @bets = @match_day.matches.includes(%i[team1 team2]).map do |match| match.bets.find_or_create_by(user: current_user) end end def bet_params(my_params) my_params.permit(:score1, :score2, :bonus) end def bonus_used matches = @match_day.round.matches.where.not(match_day_id: @match_day.id) @bonus_used = current_user.bets.with_bonus.exists?(match: matches) end end
import React, { useState, useEffect, useRef } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; function useInterval(callback, delay) { const savedCallback = useRef(); useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { function tick() { savedCallback.current(); } if (delay !== null) { const id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); } export default function Question({ updateScore }) { const { id, category } = useParams(); const navigate = useNavigate(); const [currentQuestion, setCurrentQuestion] = useState(null); const [selectedOption, setSelectedOption] = useState(''); const [isAnswerCorrect, setIsAnswerCorrect] = useState(null); const [timer, setTimer] = useState(100); const [progress, setProgress] = useState(0); const [submitted, setSubmitted] = useState(false); const [NoOfQuestionSubmitted, setNoOfQuestionSubmitted] = useState(0); const [innerLoadedQuestions, setInnerLoadedQuestions] = useState([]); const [showHint, setShowHint] = useState(false); const [answeredQuestionIds, setAnsweredQuestionIds] = useState([]); const timerRef = useRef(100); // Use Effect for Timer useInterval(() => { setTimer((prevTimer) => prevTimer - 1); }, timerRef.current ? 1000 : null); // Use effect for question loading useEffect(() => { const loadQuestionsAndSetState = async () => { const loadedQuestions = await loadQuestions(); setInnerLoadedQuestions(loadedQuestions); const questionId = parseInt(id, 10); const foundQuestion = loadedQuestions.find((q) => q.id === questionId); if (foundQuestion) { setCurrentQuestion(foundQuestion); timerRef.current = 100; } else { navigate(`/result/${category}`); } }; const loadQuestions = async () => { try { const questions = await import(`./${category}.json`); return questions.default || []; } catch (error) { console.error('Error loading questions:', error); return []; } }; loadQuestionsAndSetState(); }, [id, category, navigate, showHint]); // Use effect if timer gets to 0 useEffect(() => { if (timer === 0) { navigate(`/result/${category}`); } }, [timer, navigate]); // Use effect if user submit an answer useEffect(() => { if (submitted) { const totalQuestions = innerLoadedQuestions.length; const answeredIds = JSON.parse(localStorage.getItem('answeredQuestionIds')) || []; setAnsweredQuestionIds(answeredIds); if (!answeredIds.includes(currentQuestion.id)) { const updatedProgress = Math.ceil(((NoOfQuestionSubmitted) / totalQuestions) * 100); setProgress(updatedProgress); } } }, [currentQuestion, submitted, NoOfQuestionSubmitted, innerLoadedQuestions.length]); // Use effect if user want to go back to previous answer useEffect(() => { const questionId = parseInt(id, 10); const userAnswers = JSON.parse(localStorage.getItem('userAnswers')) || {}; const selectedOptionForCurrentQuestion = userAnswers[questionId]; setSelectedOption(selectedOptionForCurrentQuestion || ''); // Reset selected option when a new question is loaded if (!answeredQuestionIds.includes(questionId)) { setSelectedOption(''); } }, [currentQuestion, id, answeredQuestionIds]); // Use effect to show hints useEffect(() => { setShowHint(false); // Reset showHint when the current question changes }, [currentQuestion]); const handleOptionSelect = (option) => { const userAnswers = JSON.parse(localStorage.getItem('userAnswers')) || {}; userAnswers[currentQuestion.id] = option; localStorage.setItem('userAnswers', JSON.stringify(userAnswers)); if (!answeredQuestionIds.includes(currentQuestion.id)) { const updatedIds = [...answeredQuestionIds, currentQuestion.id]; localStorage.setItem('answeredQuestionIds', JSON.stringify(updatedIds)); setNoOfQuestionSubmitted(NoOfQuestionSubmitted + 1); } setSelectedOption(option); if (submitted) { const nextQuestionId = currentQuestion.id + 1; const nextPath = nextQuestionId <= innerLoadedQuestions.length ? `/question/${nextQuestionId}/${category}` : `/result/${category}`; navigate(nextPath); } else { handleSubmit(); } }; // Toggle hint function const handleToggleHint = () => { setShowHint((prevShowHint) => !prevShowHint); }; // Submit function const handleSubmit = () => { const correct = selectedOption === currentQuestion.correctAnswer; setIsAnswerCorrect(correct); if (isAnswerCorrect) { updateScore(); } setSubmitted(true); const nextQuestionId = currentQuestion.id + 1; const nextPath = nextQuestionId <= innerLoadedQuestions.length ? `/question/${nextQuestionId}/${category}` : `/result/${category}`; navigate(nextPath); }; // Navigation function const handleNavigation = (direction) => { const nextQuestionId = direction === 'next' ? currentQuestion.id + 1 : currentQuestion.id - 1; if (nextQuestionId > 0 && nextQuestionId <= innerLoadedQuestions.length) { navigate(`/question/${nextQuestionId}/${category}`); } setSubmitted(false); }; // Clearing answer function (start over) const handleClearAnswers = () => { if (startOverConfirmation()) { localStorage.removeItem('userAnswers'); localStorage.removeItem('answeredQuestionIds'); setNoOfQuestionSubmitted(0); setSelectedOption(''); navigate(`/question/1/${category}`); setProgress(0); } }; // Showing message functions const showConfirmation = () => { return window.confirm('Are you sure you want to return home? Your progress will be lost.'); }; const startOverConfirmation = () => { return window.confirm('Are you sure you want to start over? Your current progress will be lost.'); }; // Retruning home functions const handleReturnHome = () => { if (showConfirmation()) { localStorage.removeItem('userAnswers'); localStorage.removeItem('answeredQuestionIds'); setNoOfQuestionSubmitted(0); setSelectedOption(''); navigate('/'); } }; return ( <div> <div className="homeContainer"> <div className="backgroundImage py-5"> <div className="container"> <h1 className="text-light text-center display-2 py-5"> {category.charAt(0).toUpperCase() + category.slice(1)} Quiz </h1> </div> </div> <hr className="horizontalLines"></hr> <div className='container text-light'> {currentQuestion && ( <div> <h2 className='display-4'>Question {currentQuestion.id} of {innerLoadedQuestions.length}</h2> <h3 className='my-3'>{currentQuestion.question}</h3> <div className='row'> {currentQuestion.options.map((option, index) => ( <div key={index} className="form-check my-2 col-12 col-md-6"> <button key={index} type="button" className={`btn btn-outline-primary w-100 btn-lg p-4 ${selectedOption === option ? 'active' : ''}`} onClick={() => handleOptionSelect(option)} > {option} </button> </div> ))} </div> <div className="progress my-3"> <div className="progress-bar progress-bar-striped" role="progressbar" style={{ width: `${progress}%` }} aria-valuenow={progress} aria-valuemin="0" aria-valuemax="100">{progress}%</div> </div> <div className='row'> <div className='col-12 col-xl-8 text-start'> {timer !== null && <p>Time remaining: {timer} seconds</p>} {showHint && ( <div className="mt-3"> <strong>Hint:</strong> {currentQuestion.hint} </div> )} </div> <div className='my-2 col-12 col-xl-4 my-2'> <button onClick={handleToggleHint} className="btn btn-primary btn-lg w-100"> {showHint ? 'Hide Hint' : 'Show Hint'} </button> </div> </div> <div className='row'> <div className='col-12 col-xl-4 text-center'> <div className='row'> <div className='col-12 col-sm-6 my-2'> <button className="btn btn-warning w-100 btn-lg" onClick={() => handleNavigation('prev')} disabled={currentQuestion.id === 1}> Prev </button> </div> <div className='col-12 col-sm-6 my-2'> <button className="btn btn-warning w-100 btn-lg" onClick={() => handleNavigation('next')} disabled={currentQuestion.id === innerLoadedQuestions.length}> Next </button> </div> </div> </div> <div className='col-12 col-xl-8 text-center'> <div className='row'> <div className='my-2 col-12 col-sm-6 my-2'> <button className="btn btn-info btn-lg w-100" onClick={handleReturnHome}> Return Home </button> </div> <div className='my-2 col-12 col-sm-6 my-2'> <button onClick={handleClearAnswers} className="btn btn-danger btn-lg w-100"> Start Over </button> </div> </div> </div> </div> </div> )} </div> </div> </div> ); }
<style lang="scss"> #catalogs { .teletran-name { height: 70px; } .teletran-name-note { margin-top: 0.5em; } } </style> <template> <div class="container-fluid" id="catalogs"> <archive-header></archive-header> <div class="teletran-header"> <span class="teletran-header-neutral">Catalogs</span> </div> <div class="gallery-description"> <p> Man, I loved poring over these catalogs that came with boxed Tranformers back in the 1980's. I still do! I like checklists, I like Transformers, I love assigning numbers to things... What more can I ask for? </p> <p> These toy catalogs are the somewhat formalized method by which fans have assigned a release year to all the classic Transformers, and it's the system I use as well for relegating box art entries to their respective years. Now that the Archive hosts Tech Spec scans and Instruction scans -- in addition to Box Art, of course -- it seemed only fitting to finally add the Catalogs that came with the toy. </p> </div> <div id="teletran-container" v-cloak> <div class="teletran-entry" v-for="catalog in catalogs"> <div class="teletran-box"> <a class="fancybox-button-art" rel="fancybox-button" v-bind:title="catalog.displayTitle" v-bind:href="catalog.imagePath" target="_blank"> <img class="teletran-thumbnail" v-bind:src="catalog.thumbnailPath" v-bind:title="catalog.displayName" /> </a> <div class="teletran-name"> {{ catalog.displayName }} <div class="teletran-name-note" v-if="catalog.version">{{ catalog.version }} Version</div> <div class="teletran-name-note">Side {{ catalog.side }}</div> </div> </div> </div> </div> </div> </template> <script> // GLOBAL COMPONENTS var globalService = require('services/global_service'); // ARCHIVE COMPONENTS var ArchiveHeaderVue = require('components/archive/partials/archive_header'); module.exports = { data () { return { catalogs: [] } }, components: { 'archive-header': ArchiveHeaderVue }, beforeMount() { this.getCatalogData(); }, mounted() { globalService.setArchiveDocumentTitle("Catalogs"); }, methods: { getCatalogData: function() { var vm = this; firebase.database().ref('archive/catalogs').once('value').then(function(snapshot) { var catalogs = snapshot.val(); var mapped_catalogs = []; _.each(catalogs, function(catalog) { mapped_catalogs.push(_.extend({ "side": "A" }, catalog)); mapped_catalogs.push(_.extend({ "side": "B" }, catalog)); }); _.each(mapped_catalogs, function(catalog) { catalog.displayName = vm.getDisplayName(catalog); catalog.displayTitle = vm.getDisplayTitle(catalog); catalog.thumbnailPath = vm.getThumbnailPath(catalog); catalog.imagePath = vm.getImagePath(catalog); }); vm.catalogs = mapped_catalogs; }); }, getDisplayName: function(entry) { var displayName = entry.year; if (entry.region !== "USA") { displayName += " (" + entry.region + ")"; } return displayName; }, getDisplayTitle: function(entry) { var displayTitle = this.getDisplayName(entry); if (entry.version) { displayTitle += " (" + entry.version + " Version)"; } displayTitle += " - Side " + entry.side; return displayTitle; }, getImageName: function(entry) { var imageName = 'catalog_'; if (entry.region !== 'USA') { imageName += entry.region.toLowerCase() + '_'; } imageName += entry.year + '_'; if (entry.version) { imageName += entry.version.toLowerCase() + '_'; } imageName += entry.side.toLowerCase(); imageName += '.jpg'; return imageName; }, getThumbnailPath: function(entry) { return '/archive/catalogs/Z_' + this.getImageName(entry); }, getImagePath: function(entry) { return '/archive/catalogs/' + this.getImageName(entry); } } }; </script>
<ion-header [translucent]="false"> <ion-toolbar> <ion-buttons slot="start"> <ion-back-button defaultHref="/pages/reservations"></ion-back-button> </ion-buttons> <ion-title>View Reservation</ion-title> <ion-buttons slot="end"> <ion-button [disabled]="true"> <ion-icon slot="icon-only"></ion-icon> </ion-button> </ion-buttons> </ion-toolbar> </ion-header> <ion-content [fullscreen]="true"> <ion-header collapse="condense"> <ion-toolbar> <ion-title size="large">View Reservation</ion-title> </ion-toolbar> </ion-header> <div class="ion-text-center" *ngIf="isLoading"> <ion-spinner name="dots"></ion-spinner> </div> <ion-card *ngIf="!isLoading && loadedData"> <ion-item-divider color="dark"> <ion-grid fixed> <ion-row> <ion-col class="ion-text-start">Reservation Date</ion-col> <ion-col size="auto">{{ loadedData.date }}</ion-col> </ion-row> </ion-grid> </ion-item-divider> <ion-card-header color="pink"> <ion-grid fixed> <ion-row class="ion-align-items-center"> <ion-col size="auto"> <ion-avatar class="ion-margin-end"> <img alt="Silhouette of a person's head" src="https://ionicframework.com/docs/img/demos/avatar.svg" /> </ion-avatar> </ion-col> <ion-col> <ion-text style="font-size: larger; font-weight: bold;">{{ loadedData.student_name }}</ion-text> </ion-col> <ion-col size="auto"> <div [ngSwitch]="loadedData.status"> <ion-badge *ngSwitchCase="0" color="warning"> <ion-icon name="alert-circle-outline"></ion-icon> Unpaid </ion-badge> <ion-badge *ngSwitchCase="1" color="medium"> <ion-icon name="time-outline"></ion-icon> Pending </ion-badge> <ion-badge *ngSwitchCase="2" color="danger"> <ion-icon name="close-circle-outline"></ion-icon> Cancelled </ion-badge> <ion-badge *ngSwitchCase="3" color="success"> <ion-icon name="checkmark-circle-outline"></ion-icon> Redeemed </ion-badge> <ion-badge *ngSwitchDefault color="dark">Unknown</ion-badge> </div> </ion-col> </ion-row> </ion-grid> </ion-card-header> <ion-card-content> <ion-grid fixed> <ion-row class="ion-margin-top ion-margin-bottom ion-align-items-center"> <ion-col class="ion-text-start">Order Summary</ion-col> <ion-col size="auto"> <ion-button size="small" color="danger" (click)="cancelReservation(loadedData)" *ngIf="loadedData.status === 0 || loadedData.status === 1"> <ion-icon slot="start" shape="round" name="close-circle-outline"></ion-icon>Cancel Reservation </ion-button> </ion-col> </ion-row> <div class="divider"></div> <ion-row class="ion-margin-top"> <ion-col class="ion-text-start">{{ loadedData.menu_name }}</ion-col> <ion-col size="auto" style="font-weight: bold;">{{ loadedData.amount_paid | currency: 'RM' }}</ion-col> </ion-row> <ion-row class="ion-margin-top"> <ion-col class="ion-text-start">Quantity</ion-col> <ion-col size="auto" style="font-weight: bold;">x {{ loadedData.quantity }}</ion-col> </ion-row> </ion-grid> </ion-card-content> </ion-card> <ion-card *ngIf="!isLoading && loadedData.status === 0" color="danger"> <ion-card-content>No payment recorded.</ion-card-content> </ion-card> <ion-card *ngIf="!isLoading && loadedData.status !== 0"> <ion-card-content class="ion-text-start"> <ion-text> <h3 style="font-weight: bold;">Payment Summary</h3> <div class="divider" style="margin: 10px 0"></div> <p>Status: <ion-badge [color]="loadedPayment.status === 0 ? 'danger' : 'success'">{{ loadedPayment.status_text }}</ion-badge></p> <p>Transaction Ref: {{ loadedPayment.transaction_id ? loadedPayment.transaction_id : 'N/A' }}</p> <p>Transaction Date: {{ loadedPayment.updated_at }}</p> </ion-text> </ion-card-content> </ion-card> </ion-content> <ion-footer *ngIf="!isLoading && loadedData.status === 0"> <ion-toolbar> <ion-button expand="block" color="success" (click)="makePayment()">Make Payment</ion-button> </ion-toolbar> </ion-footer>
### Quiz App Readme This repository contains a Quiz Application built using Express.js and MongoDB. The application allows users to create quizzes, manage quiz status, and handle user authentication. ### Features - **User Authentication**: Provides user registration and login functionalities using JWT tokens. - **Quiz Creation**: Allows users to create quizzes with questions, options, and set start/end dates. - **Quiz Status Management**: Automatically updates quiz statuses (Active/Finished) using cron jobs. - **API Endpoints**: - `/user/register`: Endpoint to register a new user. - `/user/login`: Endpoint to authenticate and log in a user. - `/quizzes`: Create a new quiz. - `/quizzes/active`: Get the active quiz. - `/quizzes/:id/result`: Get quiz results. - `/quizzes/all`: Get all quizzes. ### Installation 1. Clone the repository: ```bash git clone https://github.com/your-username/quiz-app.git cd quiz-app ``` 2. Install dependencies: ```bash npm install ``` 3. Set up environment variables: - Create a `.env` file in the root directory. - Add required environment variables (e.g., `PORT`, `MONGODB_URI`, `secretkey`). ### Usage 1. Start the application: ```bash npm start ``` 2. Use API endpoints through a tool like Postman or via HTTP requests in your application. ### Dependencies Used - **Express**: Web application framework for Node.js. - **Mongoose**: MongoDB object modeling tool designed to work in an asynchronous environment. - **bcrypt**: Library to hash passwords. - **jsonwebtoken**: For generating JWT tokens for user authentication. - **node-cron**: Used for scheduling cron jobs in Node.js. ### Contributors - [Ramanand1101](https://github.com/Ramanand1101) ### License This project is licensed under the [MIT License](LICENSE). Feel free to contribute, raise issues, or suggest improvements!
package com.speechocean.dcctmpdatarest.configurations; import java.util.ArrayList; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.swagger.annotations.Api; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfiguration { @Bean public Docket exampleTestDocket() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.ant("/example_test/**")) .build() .pathMapping("/") .apiInfo(apiInfo()) .groupName("exampleTest"); } private ApiInfo apiInfo() { return new ApiInfo( "example test", "example test", "v1.0", "Open to All", null, null, null, new ArrayList<>()); } }
from rest_framework import serializers from book.models import Book from order.models import Order class SingleOrderSerializer(serializers.Serializer): id = serializers.CharField() quantity = serializers.IntegerField() class CreateOrderSerializer(serializers.Serializer): orders = SingleOrderSerializer(many=True) total_amount = serializers.IntegerField(required=False) def validate(self, data): total = 0 for item in data.get('orders'): book_id = item.get('id') book_exists = Book.objects.filter(id=book_id).exists() if book_exists is False: raise serializers.ValidationError( f"Book id {item.get('id')} not found " ) book = Book.objects.get(id=book_id) if book.qty_left < int(item.get('quantity')): raise serializers.ValidationError(f"book quantity {item.get('quantity')} is greater than stock left") total += (item.get('quantity') * book.price) data['total_amount'] = total return data def save(self, user, data): order = Order.objects.create( user=user, meta_data=data ).save() return order class ListOrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('id','user', 'meta_data', 'order_state') read_only_fields = ('id', 'user', 'order_state') class UpdateOrderSerializer(serializers.Serializer): orders = SingleOrderSerializer(many=True) state = serializers.CharField() total_amount = serializers.IntegerField(required=False) def validate(self, data): ORDER_STATE_CHOICES = ("OPEN", "CANCELED", "DELIVERED") state = data.get('state') user = self.context['user'] order = self.context['order'] if user != order.user: raise serializers.ValidationError( "You are not authorized to perform this action" ) if state and state not in ORDER_STATE_CHOICES: raise serializers.ValidationError( f"Invalid state choice must be any of {ORDER_STATE_CHOICES}" ) return data def save(self, data, instance): state = data.get('state', '') order = data.get('orders', '') if state: instance.state = state if order: instance.update_meta_data( order) instance.save()
import { createContext, useContext, useEffect, useReducer } from "react"; import reducer from "../reducer/CartReducer"; const CartContext = createContext(); const getLocalCartData = () => { let localCartData = localStorage.getItem("CartItem"); // if (localCartData === []) { // return []; // } else { // return JSON.parse(localCartData); // } const parseData = JSON.parse(localCartData); if(!Array.isArray(parseData)) return [];{ return parseData; } }; const initialState = { // cart: [], cart: getLocalCartData(), total_item: "", total_price: "", shipping_fee: 2000, }; const CartProvider = ({ children }) => { const [state, dispatch] = useReducer(reducer, initialState); const addToCart = (id, color, amount, product) => { dispatch({ type: "ADD_TO_CART", payload: { id, color, amount, product } }); }; // increment and decrement the product const setDecrease = (id) => { dispatch({ type: "SET_DECREMENT", payload: id }); }; const setIncrement = (id) => { dispatch({ type: "SET_INCREMENT", payload: id }); }; const removeItem = (id) => { dispatch({ type: "ROMOVE_ITEM", payload: id }); }; const clearCart = () => { dispatch({ type: "CLEAR_CART" }); }; //to add the data in localstorage useEffect(() => { dispatch({type:"CART_TOTAL_ITEM"}); dispatch({type:"CART_TOTAL_PRICE"}); localStorage.setItem("CartItem", JSON.stringify(state.cart)); }, [state.cart]); return ( <CartContext.Provider value={{ ...state, addToCart, removeItem, clearCart, setDecrease, setIncrement, }}> {children} </CartContext.Provider> ); }; const useCartContext = () => { return useContext(CartContext); }; export { CartProvider, useCartContext };
package com.android.userapp.screens import android.view.LayoutInflater import android.view.Menu import android.view.View import android.view.ViewGroup import android.widget.PopupMenu import androidx.recyclerview.widget.RecyclerView import com.android.userapp.R import com.android.userapp.data.models.User import com.android.userapp.databinding.ItemUserBinding import com.bumptech.glide.Glide interface UserActionListener { fun onUserMove(user: User, moveBy: Int) fun onUserDelete(user: User) fun onUserDetails(user: User) } class UserAdapter( private val actionListener: UserActionListener ) : RecyclerView.Adapter<UserAdapter.UserViewHolder>(), View.OnClickListener { var list: List<User> = emptyList() set(value) { field = value notifyDataSetChanged() } class UserViewHolder(val binding: ItemUserBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = ItemUserBinding.inflate(inflater, parent, false) binding.root.setOnClickListener(this) binding.moreImageViewButton.setOnClickListener(this) return UserViewHolder(binding) } override fun onBindViewHolder(holder: UserViewHolder, position: Int) { val user = list[position] with(holder.binding) { holder.itemView.tag = user moreImageViewButton.tag = user userNameTextView.text = user.name userCompanyTextView.text = user.company if (user.photo.isNotBlank()) { Glide.with(photoImageView.context) .load(user.photo) .circleCrop() .placeholder(R.drawable.ic_launcher_foreground) .error(R.drawable.ic_launcher_background) .into(photoImageView) } else { photoImageView.setImageResource(R.drawable.ic_launcher_foreground) } } } override fun getItemCount(): Int = list.size override fun onClick(v: View) { val user = v.tag as User when (v.id) { R.id.moreImageViewButton -> { showPopupMenu(v) } else -> { actionListener.onUserDetails(user) } } } private fun showPopupMenu(view: View) { val popupMenu = PopupMenu(view.context, view) val user = view.tag as User val position = list.indexOfFirst { it.id == user.id } popupMenu.menu.add(0, ID_MOVE_UP, Menu.NONE, "Move up").apply { isEnabled = position > 0 } popupMenu.menu.add(0, ID_MOVE_DOWN, Menu.NONE, "Move down").apply { isEnabled = position < list.size - 1 } popupMenu.menu.add(0, ID_REMOVE, Menu.NONE, "Remove") popupMenu.setOnMenuItemClickListener { when (it.itemId) { ID_MOVE_UP -> { actionListener.onUserMove(user, -1) } ID_MOVE_DOWN -> { actionListener.onUserMove(user, 1) } ID_REMOVE -> { actionListener.onUserDelete(user) } } return@setOnMenuItemClickListener true } popupMenu.show() } companion object { private const val ID_MOVE_UP = 1 private const val ID_MOVE_DOWN = 2 private const val ID_REMOVE = 3 } }
import {json} from '@shopify/remix-oxygen'; import {useLoaderData} from '@remix-run/react'; import {Image} from '@shopify/hydrogen-react'; import ProductOptions from '../components/ProductOptions'; export async function loader({params, context, request}) { const {handle} = params; const searchParams = new URL(request.url).searchParams; const selectedOptions = []; searchParams.forEach((value, name) => { selectedOptions.push({name, value}); }); const {product} = await context.storefront.query(PRODUCT_QUERY, { variables: { handle: 'have-a-great-day-ls-tee-cobalt-white', selectedOptions, }, }); if (!product?.id) { throw new Response(null, {status: 404}); } return json({ handle, product, }); } const seo = ({data}) => ({ title: data?.product?.title, description: data?.product?.description.substr(0, 154), }); export const handle = { seo, }; export default function ProductHandle() { const {product} = useLoaderData(); console.log(product); return ( <section className="grid w-full gap-4 px-6 md:gap-8 md:px-8 lg:px-12"> <div className="grid items-start gap-6 lg:gap-20 md:grid-cols-2 lg:grid-cols-3"> <div className="grid md:grid-flow-row md:p-0 md:overflow-x-hidden md:grid-cols-2 md:w-full lg:col-span-2"> <div className="md:col-span-2 card-image snap-center aspect-square md:w-full w-[80vw] shadow rounded"> <Image className={`w-full h-full aspect-square object-cover`} data={product.selectedVariant?.image || product.featuredImage} /> </div> </div> <div className="md:sticky md:mx-auto max-w-xl md:max-w-[24rem] grid gap-2 p-0 md:p-6 md:px-0 top-[6rem] lg:top-[8rem] xl:top-[10rem]"> <div className="grid gap-2"> <h1 className="text-4xl font-bold leading-10 whitespace-normal"> {product.title} </h1> <span className="font-medium whitespace-pre-wrap opacity-50 max-w-prose inherit text-copy"> {product.vendor} </span> </div> <ProductOptions options={product.options} /> <div className="pt-6 prose text-black border-t border-gray-200 text-md" dangerouslySetInnerHTML={{__html: product.descriptionHtml}} /> </div> </div> </section> ); } const PRODUCT_QUERY = `#graphql query product($handle: String!, $selectedOptions: [SelectedOptionInput!]!) { product(handle: $handle) { id title handle vendor description descriptionHtml featuredImage{ id url altText width height } options { name, values } selectedVariant: variantBySelectedOptions(selectedOptions: $selectedOptions) { id availableForSale selectedOptions { name value } image { id url altText width height } price { amount currencyCode } compareAtPrice { amount currencyCode } sku title unitPrice { amount currencyCode } product { title handle } } variants(first: 1) { nodes { id title availableForSale price { currencyCode amount } compareAtPrice { currencyCode amount } selectedOptions { name value } } } } } `;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('stagiaires', function (Blueprint $table) { $table->id(); $table->string('nom'); $table->string('prenom'); $table->bigInteger('telephone_id'); $table->bigInteger('filiere_id'); $table->timestamps(); $table->foreign('filiere_id')->references('id')->on('filieres'); $table->foreign('telephone_id')->references('id')->on('telephones'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('stagiaires'); } };
# Start time: 2024-03-30 03:52:33.802341 # Content: The prompt describes the relationship between the inputs and outputs. Given that the prompt is: remove the last word/phrase from input, and given input as ['india china japan'] output is india china, given input as ['indonesia korea'] output is indonesia, , generate a python function that matches the input and output, treating the input and output as strings, not lists. Add the input, output, and prompt to the comment section of the generated python code. Incorporate exception handling with proper try catch blocks to handle all types of inputs. The code should be clean to run at a command prompt without any noncode # Prompt: remove the last word/phrase from input # Input: 'india china japan' # Output: 'india china' def remove_last_word(input_str): try: words = input_str.split() output_str = ' '.join(words[:-1]) return output_str except: return "Invalid input" # Test cases print(remove_last_word('india china japan')) # Output: india china print(remove_last_word('indonesia korea')) # Output: indonesia print(remove_last_word('hello')) # Output: hello print(remove_last_word('')) # Output: Invalid input # End time: 2024-03-30 03:52:35.104041 # Elapsed time in seconds: 1.3016667230003804
@php $html_tag_data = ["override"=>'{ "attributes" : { "placement" : "vertical", "layout":"fluid" }, "storagePrefix" : "starter-project", "showSettings" : false }']; $title = 'Product'; $description= 'An empty page with a fluid vertical layout.'; $breadcrumbs = ["/"=>"Home"] @endphp @extends('admin_dashboard.layout',['html_tag_data'=>$html_tag_data, 'title'=>$title, 'description'=>$description]) @section('css') <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css"> @include('admin_dashboard.product.css') <link rel="stylesheet" href="/css/vendor/quill.bubble.css"/> <link rel="stylesheet" href="/css/vendor/quill.snow.css"/> @endsection @section('js_vendor') <script src="/js/cs/scrollspy.js"></script> <script src="/js/vendor/quill.min.js"></script> <script src="/js/vendor/quill.active.js"></script> @endsection @section('js_page') <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> <script src="/js/pages/vertical.js"></script> <script src="https://code.jquery.com/jquery-3.7.0.js"></script> <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script> <script> new DataTable('#product', { fixedColumns: { heightMatch: 'none' }, paging: true, info: false, }); </script> <script src="/js/forms/controls.editor.js"></script> <script> var loadFile1 = function(event) { var pdimage1 = document.getElementById('pdimage1'); pdimage1.height = 150; pdimage1.width = 150; pdimage1.src = URL.createObjectURL(event.target.files[0]); pdimage1.onload = function() { URL.revokeObjectURL(output.src) // free memory } }; </script> @endsection @section('content') <div class="container"> <!-- Title and Top Buttons Start --> <div class="page-title-container"> <div class="row"> <!-- Title Start --> <div class="col-12 col-md-7"> <h1 class="mb-0 pb-0 display-4" id="title">{{ $title }}</h1> @include('_layout.breadcrumb',['breadcrumbs'=>$breadcrumbs]) </div> <!-- Title End --> </div> </div> <!-- Title and Top Buttons End --> <!-- Content Start --> <div class="row"> <div class="col-4"> <div class="card mb-2"> <div class="card-body" id="saveform_error"> <h3 style="text-align: center" class="mb-3">Edit Product</h3> <form action="/Admin/Product/List/EditProduct" method="POST" enctype="multipart/form-data"> @csrf <div class="input-group mb-3"> <span class="input-group-text" id="product_name" style="width: 100px;">Name</span> <input type="text" name="id" value="{{$item['id']}}" hidden> <input type="text" class="form-control" placeholder="" aria-label="product_name" aria-describedby="product_name" name="product_name" autocomplete="off" id="product_name" value="{{$item['product_name']}}"> </div> <div class="input-group mb-3" > <span class="input-group-text" id="product_date" style="width: 100px;">Date</span> <input type="text" class="form-control" placeholder="" aria-label="product_date" aria-describedby="product_date" name="product_date" autocomplete="off" id="product_date" value="<?php echo date("d.m.Y");?>"> </div> <div class="input-group mb-3" > <span class="input-group-text" id="product_category" style="width: 100px;">Category</span> <select name="product_category" id="product_category" class="form-control"> <option value="{{$item['product_category']}}" name="product_category">{{$item['product_category']}}</option> @foreach ($cate as $item) <option value="{{$item->category_name}}" name="product_category">{{$item->category_name}}</option> @endforeach </select> </div> <div class="input-group mb-3" > <span class="input-group-text" id="product_detail" style="width: 100px;">Detail</span> <input type="text" class="form-control" placeholder="" aria-label="product_detail" aria-describedby="product_detail" name="product_detail" autocomplete="off" id="product_detail" value="{{$item['product_detail']}}"> </div> <div class="input-group mb-3"> <input type="file" class="form-control" name="product_image" id="input-file1" onchange="loadFile1(event)" value="{{$item['product_image']}}"> </div> <div class=""> <img src="" id="pdimage1" class="rounded-md bg-cover-center d-block"> </div> <div style="float: right"> <button type="reset" class="btn-danger btn">Reset</button> <button type="submit" class="btn-primary btn">Save</button> </div> </form> </div> </div> </div> <div class="col-8"> <div class="card mb-2"> <div class="card-body"> <table id="product" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>No</th> <th>Name</th> <th>Category</th> <th>Detail</th> <th>Image</th> <th>Date</th> <th></th> </tr> </thead> <tbody> @foreach ($data as $item) <tr> <td style="text-align: center"> {{$loop->iteration}} </td> <td> {{$item->product_name}} </td> <td> {{$item->product_category}} </td> <td> {{$item->product_detail}} </td> <td> <img src="{{ url('img/product/company_product/'.$item->product_image) }}" alt="" style="width: 100px; height: 100px;" onerror="this.style.display = 'none'"> </td> <td> {{$item->product_date}} </td> <td> <a href="/Admin/Product/List/{{$item->id}}/Delete" class="btn btn-danger" draggable="false">Delete</a> <a href="/Admin/Product/List/{{$item->id}}/Edit" class="btn btn-primary" draggable="false">Edit</a> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> <!-- Content End --> </div> @endsection
# Find and Replace Program README ## Overview This Rust program provides a simple but powerful tool for text processing: it finds and replaces strings in text files. Utilizing regular expressions for pattern matching, it can handle complex search-and-replace operations, making it a versatile tool for editing texts, coding, data manipulation, and more. ## Features - **Regular Expression Support**: Use regular expressions to define the pattern of text to be replaced, offering flexibility in targeting specific strings. - **File Operations**: Reads from an input file and writes the modified content to an output file, automating the process of editing large or multiple files. - **Error Handling**: Provides clear error messages for common issues such as file read/write errors and regex compilation problems. - **Command Line Interface**: Easily run from the command line, allowing integration into scripts or workflows. ## Requirements - Rust Programming Language - Cargo (Rust's package manager and build system) ## Installation To use this program, first ensure you have Rust and Cargo installed on your system. If not, follow the instructions on the [official Rust website](https://www.rust-lang.org/tools/install) to set them up. Clone the repository or download the source code, then navigate to the project directory in your terminal. ## Usage The program is executed via the command line with the following syntax: ``` cargo run <pattern> <replacement> <input_file> <output_file> ``` <pattern>: The regular expression pattern to search for in the input file. <replacement>: The string to replace each occurrence of the pattern with. <input_file>: The path to the file whose content will be searched. <output_file>: The path where the modified content will be written. Example: ``` cargo run "foo" "bar" "./input.txt" "./output.txt" ``` This command will replace all occurrences of "foo" with "bar" in input.txt and save the result to output.txt.
package com.example.mungnyang.DiaryPage.Schedule import android.content.ContentValues import android.util.Log import androidx.recyclerview.widget.RecyclerView import com.example.mungnyang.User.UserRetrofit.RetrofitManager import retrofit2.Call import retrofit2.Callback import retrofit2.Response object ScheduleManagementOBJ { val List = mutableListOf<Schedule>() // 함수 하나 만들어서 init 됐을 때 리스트 내용 비우고 새로고침 var mainAdapter: ScheduleAdapter? = null fun addSchedule(schedule: Schedule) { List.add(schedule) mainAdapter?.notifyDataSetChanged() } // 현재 날짜에 해당하는 일정만 필터링하는 함수 fun filterSchedulesByDate(selectedDay: String) { val filteredList = List.filter { it.scheduleDay == selectedDay } mainAdapter?.updateData(filteredList) } fun refreshFrom(petID: String, selectedDay : String) { var petId = "" var scheduleDay = "" var scheduleTitle = "" var scheduleDetail = "" var scheduleTime = "" val retrofit = RetrofitManager.instance; // 사용자의 펫 정보를 받아옴. val sendSearch = retrofit.apiService.searchSchedule(selectedDay) sendSearch.enqueue(object : Callback<SearchResponseScheduleDTO> { override fun onResponse(call: Call<SearchResponseScheduleDTO>, response: Response<SearchResponseScheduleDTO>) { val responseDto = response.body() if (responseDto != null) { val scheduleList = responseDto.scheduleList if (scheduleList.isNotEmpty()) { for (schedule in scheduleList) { petId = schedule.petID.toString() scheduleDay = schedule.selectedDay.toString() scheduleTitle = schedule.scheduleTitle.toString() scheduleDetail = schedule.scheduleDetail.toString() scheduleTime = schedule.scheduleTime.toString() Log.d(ContentValues.TAG, "schedule : $schedule") // 선택한 펫과 선택한 날짜와 맞는 일정만 추가 if (petID == petId && selectedDay == scheduleDay) { val schedule = Schedule(petId, scheduleTitle, scheduleDetail, scheduleTime, selectedDay) addSchedule(schedule) } } } else { Log.d(ContentValues.TAG, "No schedule found for the provided email") } } else { Log.d(ContentValues.TAG, "Search Response is null") } } override fun onFailure(call: Call<SearchResponseScheduleDTO>, t: Throwable) { Log.e(ContentValues.TAG, "Search Request Failed: ${t.message}", t) } }) } }
// Patrón módulo: // (() => { // })() const miModulo = (() => { 'use strict' let deck = [] const tipos = ['C', 'D', 'H', 'S'], especiales = ['A', 'J', 'Q', 'K'] let puntosJugadores = [] // Referencias HTML // querySelector(string): // string = tag: seleccionar por etiqueta HTML // string = #id: seleccionar por id // string = .class: seleccionar por clase const btnDetener = document.querySelector('#btnDetener'), btnNuevo = document.querySelector('#btnNuevo'), btnPedir = document.querySelector('#btnPedir'), divCartasJugadores = document.querySelectorAll('.divCartas'), puntosHTML = document.querySelectorAll('small') const inicializarJuego = (numJugadores = 2) => { deck = crearDeck() puntosJugadores = [] for (let i = 0; i < numJugadores; i++) { puntosJugadores.push(0) puntosHTML[i].innerHTML = 0 divCartasJugadores[i].innerHTML = '' } btnPedir.disabled = false btnDetener.disabled = false } // Crear una baraja de cartas en orden aleatorio const crearDeck = () => { deck = [] for (let i = 2; i <= 10; i++) { for (const tipo of tipos) { deck.push(i + tipo) } } for (const tipo of tipos) { for (const esp of especiales) { deck.push(esp + tipo) } } return _.shuffle(deck) } // Función para pedir una carta const pedirCarta = () => { if (deck.length === 0) { throw 'No hay cartas en la baraja' } return deck.pop() } const valorCarta = (carta) => { const valor = carta.substring(0, carta.length - 1) return isNaN(valor) ? (valor === 'A' ? 11 : 10) : valor * 1 // * 1 para convertir a number. También se puede usar parseInt(valor) // let puntos = 0 // if (isNaN(valor)) { // puntos = valor === 'A' ? 11 : 10 // } else { // puntos = valor * 1 // } } // Turno 0: jugador 1, turno 1: jugador 2, ..., último turno: computador const acumularPuntos = (carta, turno) => { puntosJugadores[turno] += valorCarta(carta) puntosHTML[turno].innerText = puntosJugadores[turno] return puntosJugadores[turno] } const crearCarta = (carta, turno) => { const imgCarta = document.createElement('img') imgCarta.src = `assets/cartas/${carta}.png` imgCarta.classList.add('carta') divCartasJugadores[turno].append(imgCarta) } const determinarGanador = () => { const [puntosMinimos, puntosComputador] = puntosJugadores // El setTimeout es para que se alcance a ejecutar todo el código antes de que se ejecute la alerta setTimeout(() => { if (puntosComputador === puntosMinimos) { alert('Empate') } else if (puntosMinimos > 21) { alert('Perdiste') } else if (puntosComputador > 21) { alert('Ganaste') } else { alert('Perdiste') } }, 100) } // Turno del computador const turnoComputador = (puntosMinimos) => { let puntosComputador = 0 do { const carta = pedirCarta() puntosComputador = acumularPuntos(carta, puntosJugadores.length - 1) crearCarta(carta, puntosJugadores.length - 1) } while (puntosComputador < puntosMinimos && puntosMinimos <= 21) determinarGanador() } // Eventos btnPedir.addEventListener('click', () => { const carta = pedirCarta() const puntosJugador = acumularPuntos(carta, 0) crearCarta(carta, 0) if (puntosJugador > 21) { console.warn('Perdiste') btnPedir.disabled = true btnDetener.disabled = true turnoComputador(puntosJugador) } else if (puntosJugador === 21) { console.warn('¡21!') btnPedir.disabled = true btnDetener.disabled = true turnoComputador(puntosJugador) } }) btnDetener.addEventListener('click', () => { btnPedir.disabled = true btnDetener.disabled = true turnoComputador(puntosJugadores[0]) }) btnNuevo.addEventListener('click', () => { inicializarJuego() }) return { nuevoJuego: inicializarJuego, } })()
import crowdin, { Credentials, SourceFilesModel, } from "@crowdin/crowdin-api-client"; import { MongoClient, Collection } from "mongodb"; import _ from 'lodash' import * as dotenv from "dotenv"; dotenv.config(); const projectId = Number(process.env.projectId!); const targetLanguages = ["zh-CN", "es-ES"]; // credentials const credentials: Credentials = { token: process.env.token!, // organization: 'organizationName' // optional }; async function sleep(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); } const uri = "mongodb://localhost:27017"; const client = new MongoClient(uri); const dbName = "crowdinConflux" const languageTranslation = "languageTranslation" const translationApproval = "translationApproval" const sourceString = "sourceString" const limit = 500 async function insertDocument(collection: Collection, obj: any, attrs: string[]) { const existed = await collection.findOne(_.pick(obj, attrs)); if (existed) { console.log(`item already exists with ${JSON.stringify(_.pick(obj, attrs))})`) return } await collection.insertOne(obj); } // initialization of crowdin client const { stringTranslationsApi, sourceStringsApi, projectsGroupsApi, labelsApi } = new crowdin(credentials); async function listLanguageTranslations(offset: number, targetLanguageId: string) { const languageTranslations = await stringTranslationsApi.listLanguageTranslations( projectId, targetLanguageId, { limit, offset, } ); return languageTranslations.data.map((item)=>item.data); } async function listTranslationApprovals(offset: number, languageId: string) { const translationApprovals = await stringTranslationsApi.listTranslationApprovals(projectId, { languageId, excludeLabelIds: "2", limit, offset, }) return translationApprovals.data.map((item)=>item.data); } async function listSourceStrings(offset: number) { const sourceStrings = await sourceStringsApi.listProjectStrings(projectId, { offset, limit, }) return sourceStrings.data.map((item)=>item.data); } async function insertItems(collection: Collection, f: ((offset: number) => Promise<any[]>), attrs: string[]) { let offset = 0; while (true) { const items = await f(offset) for (const item of items) { await insertDocument(collection, item, attrs) } if (items.length < limit){ break } offset += limit; console.log(`offset: ${offset}`) await sleep(50) } } async function main() { console.log(await projectsGroupsApi.getProject(projectId)) // await labelsApi.addLabel(projectId, { // "title": "placeholder" // }) console.log(JSON.stringify(await labelsApi.listLabels(projectId))) const sourceStringCollection = client.db(dbName).collection(sourceString) console.log(`inserting ${sourceString}`) await sourceStringCollection.drop() await insertItems(sourceStringCollection, listSourceStrings, ["id"]) const languageTranslationCollcetion = client.db(dbName).collection(languageTranslation) console.log(`inserting ${languageTranslation}`) await languageTranslationCollcetion.drop() for (let targetLanguage of targetLanguages) { await insertItems(languageTranslationCollcetion, (offset) => listLanguageTranslations(offset, targetLanguage), ["translationId", "stringId"]); } const translationApprovalCollcetion = client.db(dbName).collection(translationApproval) console.log(`inserting ${translationApproval}`) await translationApprovalCollcetion.drop() for (let targetLanguage of targetLanguages) { await insertItems(translationApprovalCollcetion, (offset) => listTranslationApprovals(offset, targetLanguage), ["translationId", "stringId"]) } } main().then(()=>process.exit(0));
import { Textarea } from "@/components/ui/textarea" import { Button } from "@/components/ui/button" import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar" import axios from "axios" import { BACKEND_URI } from "@/config" import { useParams } from "react-router-dom" import { useRef, useState } from "react" import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu" import { useAuth } from "@/hooks/useAuth" type CommentSectionProps = { postId: string, comments: CommentStructure[] } type CommentStructure = { comment: string, id: string, commentator: { name: string | null, id: string } } export function CommentSection({ comments, postId }: CommentSectionProps) { const [commentValue, setCommentValue] = useState<string>("") const [commentsArray, setCommentsArray] = useState<CommentStructure[]>(comments) const [editMode, setEditMode] = useState<boolean>(false) const [currentEditedCommentId, setCurrentEditedCommentId] = useState<string>("") const commentBoxRef = useRef<HTMLTextAreaElement>(null) const { user } = useAuth() const { id } = useParams() const postComment = async () => { if (!user || !user.id) { console.error("User or user ID is not defined") return; } const response = await axios.post(`${BACKEND_URI}/api/v1/comment`, { postId: id, comment: commentValue }, { headers: { Authorization: `Bearer ${user?.authToken}` } }) console.log(response.data) setCommentsArray(prev => [...prev, { comment: commentValue, id: response.data.id, commentator: { id: user?.id, name: response.data.commentator || "Anonymous", } }]) setCommentValue("") } const editComment = (id: string, comment: string) => { commentBoxRef.current?.focus() setEditMode(true) setCommentValue(comment) setCurrentEditedCommentId(id) } const postEditedComment = async () => { try { if (!user || !user.id) { console.error("User or user ID is not defined") return; } const response = await axios.put(`${BACKEND_URI}/api/v1/comment`, { id: currentEditedCommentId, postId: postId, comment: commentValue }, { headers: { Authorization: `Bearer ${user?.authToken}` } }) console.log(response.data) setCommentsArray(prev => { return prev.map(comment => { if (comment.id !== currentEditedCommentId) { return comment } else { return { comment: commentValue, id: currentEditedCommentId, commentator: { id: user?.id, name: comment.commentator.name || "Anonymous", } } } }) }) setCommentValue("") setCurrentEditedCommentId("") setEditMode(false) } catch (error) { console.log(error) } } const deleteComment = async (id: string) => { try { const response = await axios.delete(`${BACKEND_URI}/api/v1/comment/${id}`, { headers: { Authorization: `Bearer ${user?.authToken}` } }) console.log(response.data) setCommentsArray(prevComments => { return prevComments.filter(comment => comment.id !== id) }) } catch (error) { console.log() } } return ( <div className="w-full max-w-4xl mx-auto mt-12 space-y-8 col-span-1 md:col-span-2"> <div className="space-y-4"> <h2 className="text-2xl font-bold">Comments</h2> <div className="grid gap-2"> <Textarea placeholder="Write your comment..." className="resize-none min-h-[100px] rounded-md border border-input px-4 py-3 text-sm shadow-sm" value={commentValue} onChange={e => setCommentValue(e.target.value)} ref={commentBoxRef} /> {editMode ? <Button type="submit" className="justify-self-end" onClick={postEditedComment} > Edit Comment </Button> : <Button type="submit" className="justify-self-end" onClick={postComment} > Post Comment </Button> } </div> </div> <div className="space-y-6"> {commentsArray.map(comment => { return <div key={comment.id} className="flex items-start gap-4"> <Avatar className="w-10 h-10 border"> <AvatarImage src="/placeholder-user.jpg" /> <AvatarFallback>{comment.commentator.name ? comment.commentator.name[0].toUpperCase() : "A"}</AvatarFallback> </Avatar> <div className="grid gap-1.5 flex-1"> <div className="flex items-center gap-2"> <div className="font-medium">{comment.commentator.name || "Anonymous"}</div> <div className="text-xs text-muted-foreground">2 days ago</div> {comment.commentator.id === user?.id && ( <div className="ml-auto flex items-center gap-2"> <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size="icon"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="size-6"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 6.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 12.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5ZM12 18.75a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z" /> </svg> <span className="sr-only">Edit</span> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem> <Button variant="ghost" onClick={() => editComment(comment.id, comment.comment)}> <span className="">Edit</span> </Button> </DropdownMenuItem> <DropdownMenuItem> <Button variant="destructive" onClick={() => deleteComment(comment.id)}> <span className="">Delete</span> </Button> </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> </div> )} </div> <div className="text-muted-foreground"> {comment.comment} </div> </div> </div> })} </div> </div> ) }
#include <algorithm> #include <cstddef> #include <exception> #include <fstream> #include <iterator> #include <libxml/SAX.h> #include <memory> #include <sstream> #include <string> #include <unordered_set> #include <utility> #include "logging/LogMacros.hpp" #include "logging/Logger.hpp" #include "utils/String.hpp" #include "xml/ConfigParser.hpp" #include "xml/XMLTag.hpp" namespace precice::xml { std::string decodeXML(std::string xml) { static const std::map<std::string, char> escapes{{"&lt;", '<'}, {"&gt;", '>'}, {"&amp;", '&'}, {"&quot;", '"'}, {"&apos;", '\''}}; while (true) { bool changes{false}; for (const auto &kv : escapes) { auto position = xml.find(kv.first); if (position != std::string::npos) { xml.replace(position, kv.first.length(), 1, kv.second); changes = true; } } if (!changes) { break; } }; return xml; } // ------------------------- Callback functions for libxml2 ------------------------- void OnStartElementNs( void * ctx, const xmlChar * localname, const xmlChar * prefix, const xmlChar * URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes) { ConfigParser::CTag::AttributePair attributesMap; unsigned int index = 0; for (int indexAttribute = 0; indexAttribute < nb_attributes; ++indexAttribute, index += 5) { std::string attributeName(reinterpret_cast<const char *>(attributes[index])); auto valueBegin = reinterpret_cast<const char *>(attributes[index + 3]); auto valueEnd = reinterpret_cast<const char *>(attributes[index + 4]); std::string value(valueBegin, valueEnd); attributesMap[attributeName] = decodeXML(value); } auto pParser = static_cast<ConfigParser *>(ctx); std::string sPrefix(prefix == nullptr ? "" : reinterpret_cast<const char *>(prefix)); pParser->OnStartElement(reinterpret_cast<const char *>(localname), sPrefix, attributesMap); } void OnEndElementNs( void * ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI) { ConfigParser *pParser = static_cast<ConfigParser *>(ctx); pParser->OnEndElement(); } void OnCharacters(void *ctx, const xmlChar *ch, int len) { ConfigParser *pParser = static_cast<ConfigParser *>(ctx); pParser->OnTextSection(std::string(reinterpret_cast<const char *>(ch), len)); } void OnStructuredErrorFunc(void *userData, xmlError *error) { const std::string message{error->message}; // Ignore all namespace-related messages if (message.find("Namespace") != std::string::npos) { return; } ConfigParser::MessageProxy(error->level, message); } void OnErrorFunc(void *userData, const char *error, ...) { ConfigParser::MessageProxy(XML_ERR_ERROR, error); } void OnFatalErrorFunc(void *userData, const char *error, ...) { ConfigParser::MessageProxy(XML_ERR_FATAL, error); } // ------------------------- ConfigParser implementation ------------------------- precice::logging::Logger ConfigParser::_log("xml::XMLParser"); ConfigParser::ConfigParser(const std::string &filePath, const ConfigurationContext &context, std::shared_ptr<precice::xml::XMLTag> pXmlTag) : m_pXmlTag(std::move(pXmlTag)) { readXmlFile(filePath); std::vector<std::shared_ptr<XMLTag>> DefTags{m_pXmlTag}; CTagPtrVec SubTags; // Initialize with the root tag, if any. if (not m_AllTags.empty()) SubTags.push_back(m_AllTags[0]); try { connectTags(context, DefTags, SubTags); } catch (const std::exception &e) { PRECICE_ERROR("An unexpected exception occurred during configuration: {}.", e.what()); } } ConfigParser::ConfigParser(const std::string &filePath) { readXmlFile(filePath); } void ConfigParser::MessageProxy(int level, const std::string &mess) { switch (level) { case (XML_ERR_FATAL): case (XML_ERR_ERROR): PRECICE_ERROR(mess); break; case (XML_ERR_WARNING): PRECICE_WARN(mess); break; default: PRECICE_INFO(mess); } } int ConfigParser::readXmlFile(std::string const &filePath) { xmlSAXHandler SAXHandler; memset(&SAXHandler, 0, sizeof(xmlSAXHandler)); SAXHandler.initialized = XML_SAX2_MAGIC; SAXHandler.startElementNs = OnStartElementNs; SAXHandler.endElementNs = OnEndElementNs; SAXHandler.characters = OnCharacters; SAXHandler.serror = OnStructuredErrorFunc; SAXHandler.error = OnErrorFunc; SAXHandler.fatalError = OnFatalErrorFunc; std::ifstream ifs(filePath); PRECICE_CHECK(ifs, "XML parser was unable to open configuration file \"{}\"", filePath); std::string content{std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()}; xmlParserCtxtPtr ctxt = xmlCreatePushParserCtxt(&SAXHandler, static_cast<void *>(this), content.c_str(), content.size(), nullptr); xmlParseChunk(ctxt, nullptr, 0, 1); xmlFreeParserCtxt(ctxt); xmlCleanupParser(); return 0; } namespace { struct Distance { std::size_t distance; std::string name; bool operator<(const Distance &other) const { return distance < other.distance; } }; auto gatherCandidates(const std::vector<std::shared_ptr<XMLTag>> &DefTags, std::string_view prefix) { bool validPrefix = std::any_of(DefTags.begin(), DefTags.end(), [prefix](const auto &tag) { return tag->getNamespace() == prefix; }); std::set<std::string> entries; for (const auto &tag : DefTags) { if (!validPrefix || (tag->getNamespace() == prefix)) { entries.insert(tag->getFullName()); } } return entries; } } // namespace void ConfigParser::connectTags(const ConfigurationContext &context, std::vector<std::shared_ptr<XMLTag>> &DefTags, CTagPtrVec &SubTags) { std::unordered_set<std::string> usedTags; for (auto &subtag : SubTags) { std::string expectedName = (subtag->m_Prefix.length() ? subtag->m_Prefix + ":" : "") + subtag->m_Name; const auto tagPosition = std::find_if( DefTags.begin(), DefTags.end(), [expectedName](const std::shared_ptr<XMLTag> &pTag) { return pTag->_fullName == expectedName; }); if (tagPosition == DefTags.end()) { // Tag not found auto names = gatherCandidates(DefTags, subtag->m_Prefix); auto matches = utils::computeMatches(expectedName, names); if (!matches.empty() && matches.front().distance < 3) { matches.erase(std::remove_if(matches.begin(), matches.end(), [](auto &m) { return m.distance > 2; }), matches.end()); std::vector<std::string> stringMatches; std::transform(matches.begin(), matches.end(), std::back_inserter(stringMatches), [](auto &m) { return m.name; }); PRECICE_ERROR("The configuration contains an unknown tag <{}>. Did you mean <{}>?", expectedName, fmt::join(stringMatches, ">,<")); } else { PRECICE_ERROR("The configuration contains an unknown tag <{}>. Expected tags are {}.", expectedName, fmt::join(names, ", ")); } } auto pDefSubTag = *tagPosition; pDefSubTag->resetAttributes(); if ((pDefSubTag->_occurrence == XMLTag::OCCUR_ONCE) || (pDefSubTag->_occurrence == XMLTag::OCCUR_NOT_OR_ONCE)) { if (usedTags.count(pDefSubTag->_fullName)) { PRECICE_ERROR("Tag <{}> is not allowed to occur multiple times.", pDefSubTag->_fullName); } usedTags.emplace(pDefSubTag->_fullName); } pDefSubTag->_configuredNamespaces[pDefSubTag->_namespace] = true; pDefSubTag->readAttributes(subtag->m_aAttributes); pDefSubTag->_listener.xmlTagCallback(context, *pDefSubTag); pDefSubTag->_configured = true; connectTags(context, pDefSubTag->_subtags, subtag->m_aSubTags); pDefSubTag->areAllSubtagsConfigured(); pDefSubTag->_listener.xmlEndTagCallback(context, *pDefSubTag); } } void ConfigParser::OnStartElement( std::string localname, std::string prefix, CTag::AttributePair attributes) { auto pTag = std::make_shared<CTag>(); pTag->m_Prefix = std::move(prefix); pTag->m_Name = std::move(localname); pTag->m_aAttributes = std::move(attributes); if (not m_CurrentTags.empty()) { auto pParentTag = m_CurrentTags.back(); pParentTag->m_aSubTags.push_back(pTag); } m_AllTags.push_back(pTag); m_CurrentTags.push_back(pTag); } void ConfigParser::OnEndElement() { m_CurrentTags.pop_back(); } void ConfigParser::OnTextSection(const std::string &) { // This page intentionally left blank } } // namespace precice::xml
import { DaimoAccountCall, UserOpHex, derKeytoContractFriendlyKey, zUserOpHex, } from "@daimo/common"; import * as Contracts from "@daimo/contract"; import { erc20ABI } from "@daimo/contract"; import { Constants, Utils } from "userop"; import { Address, Hex, encodeFunctionData, getAddress, maxUint256, parseUnits, } from "viem"; import { OpSenderCallback, SigningCallback } from "./callback"; import { DaimoOpBuilder, DaimoOpMetadata } from "./daimoOpBuilder"; interface DaimoOpConfig { /** Chain ID */ chainId: number; /** Stablecoin token address. */ tokenAddress: Address; /** Decimals for that token. */ tokenDecimals: number; /** EphemeralNotes instance. The stablecoin used must match tokenAddress. */ notesAddressV1: Address; /** EphemeralNotesV2 instance. The stablecoin used must match tokenAddress. */ notesAddressV2: Address; /** Daimo account address. */ accountAddress: Address; /** Signs userops. Must, in some form, check user presence. */ accountSigner: SigningCallback; /** Sends userops. Returns userOpHash. */ opSender: OpSenderCallback; /** Deadline to calculate validUntil before sending each operation */ deadlineSecs: number; } /** * DaimoOpSender constructs user operations for a Daimo account. * Supports key rotations, token transfers, and ephemeral note ops. */ export class DaimoOpSender { private constructor( public opConfig: DaimoOpConfig, private opBuilder: DaimoOpBuilder ) {} /** * Initializes with all configuration provided: no env vars required. */ public static async init(opConfig: DaimoOpConfig): Promise<DaimoOpSender> { const { accountAddress, accountSigner } = opConfig; const builder = await DaimoOpBuilder.init(accountAddress, accountSigner); const { tokenAddress, tokenDecimals } = opConfig; console.log( `[OP] init: ${JSON.stringify({ accountAddress, tokenAddress, tokenDecimals, notesAddressV1: opConfig.notesAddressV1, })})}` ); return new DaimoOpSender(opConfig, builder); } public getAddress(): Address { return getAddress(this.opBuilder.getSender()); } /** Submits a user op to bundler. Returns userOpHash. */ public async sendUserOp(opBuilder: DaimoOpBuilder): Promise<Hex> { const nowS = Math.floor(Date.now() / 1e3); const validUntil = nowS + this.opConfig.deadlineSecs; const builtOp = await opBuilder .setValidUntil(validUntil) .buildOp(Constants.ERC4337.EntryPoint, this.opConfig.chainId); // This method is incorrectly named. It does not return JSON, it returns // a userop object with all the fields normalized to hex. const hexOp = Utils.OpToJSON(builtOp) as UserOpHex; console.log("[OP] sending userOp:", hexOp); zUserOpHex.parse(hexOp); return this.opConfig.opSender(hexOp); } private getTokenApproveCall( dest: Address, amount: bigint = maxUint256 // defaults to infinite ): DaimoAccountCall { return { // Approve contract `amount` spending on behalf of the account dest: this.opConfig.tokenAddress, value: 0n, data: encodeFunctionData({ abi: erc20ABI, functionName: "approve", args: [dest, amount], }), }; } /** Adds an account signing key. Returns userOpHash. */ public async addSigningKey( slot: number, derPublicKey: Hex, opMetadata: DaimoOpMetadata ) { const contractFriendlyKey = derKeytoContractFriendlyKey(derPublicKey); const op = this.opBuilder.executeBatch( [ { dest: this.getAddress(), value: 0n, data: encodeFunctionData({ abi: Contracts.daimoAccountABI, functionName: "addSigningKey", args: [slot, contractFriendlyKey], }), }, ], opMetadata ); return this.sendUserOp(op); } /** Removes an account signing key. Returns userOpHash. */ public async removeSigningKey(slot: number, opMetadata: DaimoOpMetadata) { const op = this.opBuilder.executeBatch( [ { dest: this.getAddress(), value: 0n, data: encodeFunctionData({ abi: Contracts.daimoAccountABI, functionName: "removeSigningKey", args: [slot], }), }, ], opMetadata ); return this.sendUserOp(op); } /** Sends an ERC20 transfer. Returns userOpHash. */ public async erc20transfer( to: Address, amount: `${number}`, // in the native unit of the token opMetadata: DaimoOpMetadata ) { const { tokenAddress, tokenDecimals } = this.opConfig; const parsedAmount = parseUnits(amount, tokenDecimals); console.log(`[OP] transfer ${parsedAmount} ${tokenAddress} to ${to}`); const op = this.opBuilder.executeBatch( [ { dest: tokenAddress, value: 0n, data: encodeFunctionData({ abi: Contracts.erc20ABI, functionName: "transfer", args: [to, parsedAmount], }), }, ], opMetadata ); return this.sendUserOp(op); } /** Creates an ephemeral note V2 with given value. Returns userOpHash. */ public async createEphemeralNote( ephemeralOwner: Hex, amount: `${number}`, approveFirst: boolean, opMetadata: DaimoOpMetadata ) { const { tokenDecimals, notesAddressV2 } = this.opConfig; const parsedAmount = parseUnits(amount, tokenDecimals); console.log(`[OP] create ${parsedAmount} note for ${ephemeralOwner}`); const executions = [ { dest: notesAddressV2, value: 0n, data: encodeFunctionData({ abi: Contracts.daimoEphemeralNotesV2ABI, functionName: "createNote", args: [ephemeralOwner, parsedAmount], }), }, ]; if (approveFirst) { executions.unshift(this.getTokenApproveCall(notesAddressV2)); } const op = this.opBuilder.executeBatch(executions, opMetadata); return this.sendUserOp(op); } /** Claims an ephemeral note. Returns userOpHash. */ public async claimEphemeralNoteV1( ephemeralOwner: Hex, signature: Hex, opMetadata: DaimoOpMetadata ) { console.log(`[OP] claim ephemeral note ${ephemeralOwner}`); const op = this.opBuilder.executeBatch( [ { dest: this.opConfig.notesAddressV1, value: 0n, data: encodeFunctionData({ abi: Contracts.daimoEphemeralNotesABI, functionName: "claimNote", args: [ephemeralOwner, signature], }), }, ], opMetadata ); return this.sendUserOp(op); } public claimEphemeralNoteSelf( ephemeralOwner: Hex, opMetadata: DaimoOpMetadata ) { console.log(`[OP] cancel ephemeral note V2 ${ephemeralOwner}`); const op = this.opBuilder.executeBatch( [ { dest: this.opConfig.notesAddressV2, value: 0n, data: encodeFunctionData({ abi: Contracts.daimoEphemeralNotesV2ABI, functionName: "claimNoteSelf", args: [ephemeralOwner], }), }, ], opMetadata ); return this.sendUserOp(op); } public async claimEphemeralNoteRecipient( ephemeralOwner: Hex, signature: Hex, opMetadata: DaimoOpMetadata ) { console.log(`[OP] claim ephemeral note v2 ${ephemeralOwner}`); const { accountAddress, notesAddressV2 } = this.opConfig; const op = this.opBuilder.executeBatch( [ { dest: notesAddressV2, value: 0n, data: encodeFunctionData({ abi: Contracts.daimoEphemeralNotesV2ABI, functionName: "claimNoteRecipient", args: [ephemeralOwner, accountAddress, signature], }), }, ], opMetadata ); return this.sendUserOp(op); } public async approveAndFulfillRequest( id: bigint, amount: `${number}`, // in the native unit of the token opMetadata: DaimoOpMetadata ) { console.log(`[OP] fulfill request ${id} ${amount}`); const parsedAmount = parseUnits(amount, this.opConfig.tokenDecimals); const executions: DaimoAccountCall[] = [ this.getTokenApproveCall(Contracts.daimoRequestAddress, parsedAmount), { dest: Contracts.daimoRequestAddress, value: 0n, data: encodeFunctionData({ abi: Contracts.daimoRequestConfig.abi, functionName: "fulfillRequest", args: [id], }), }, ]; const op = this.opBuilder.executeBatch(executions, opMetadata); return this.sendUserOp(op); } }
import 'package:ecommerce_interview/Sizes.dart'; import 'package:flutter/material.dart'; import 'dart:math'; import '../DataModel.dart'; import 'CartPage.dart'; import 'HomePageContent.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { // The selected product variable Product? _selectedProduct; // Method to add a product to the cart void _addToCart(Product product) { setState(() { _selectedProduct = product; }); } // Dropdown String selectedSortOption = 'Sort By'; List<String> sortingOptions = [ 'Sort By', 'Alphabetical', 'Price: Low to High', 'Price: High to Low', ]; //bottom Navigation Bar int _currentIndex = 0; late List<Product> products = []; // Declare a list to store fetched products @override void initState() { super.initState(); _fetchProducts(); // Call the method to fetch products when the widget initializes } Future<void> _fetchProducts() async { try { List<Product> fetchedProducts = await ApiProvider.fetchProducts(); setState(() { products = fetchedProducts; // Update the products list }); } catch (error) { // Handle error print(error); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( icon: const Icon(Icons.menu), onPressed: () {}, ), const Text( 'Xpress Shopping', style: TextStyle( fontSize: 22.0, color: Color.fromARGB(255, 112, 51, 233), ), ), IconButton( icon: const Icon(Icons.search), onPressed: () {}, ), ], ), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ SizedBox( height: 10, ), Padding( padding: EdgeInsets.only( left: 30, ), child: Row( children: [ const Text( 'Our Products', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 23, ), ), SizedBox( width: Dimensions.width20(context), ), DropdownButton<String>( value: selectedSortOption, icon: const Icon( Icons.arrow_downward, color: Colors.blue, ), iconSize: 24, elevation: 10, style: TextStyle(color: Colors.black), isDense: false, onChanged: (String? newValue) { setState(() { selectedSortOption = newValue!; }); }, items: sortingOptions .map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), ), ], ), ), SizedBox( height: 10, ), Padding( padding: EdgeInsets.only(left: 30), child: Container( height: 45, child: const SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ CategoryItem('Sneekers'), CategoryItem('Watches'), CategoryItem('Jackets'), CategoryItem('Shirts'), ], ), ), ), ), SizedBox( height: 10, ), Expanded( child: SingleChildScrollView( scrollDirection: Axis.vertical, child: HomePageContent( products: products, // Pass the fetched products ), ), ), ], ), bottomNavigationBar: BottomNavigationBar( currentIndex: _currentIndex, type: BottomNavigationBarType.fixed, onTap: (index) { setState( () { _currentIndex = index; }, ); if (index == 2 && _selectedProduct != null) { Navigator.push( context, MaterialPageRoute( builder: (context) => CartPage( product: _selectedProduct!, ), // Replace YourCartPage with the actual page you want to navigate to ), ); } }, items: const [ BottomNavigationBarItem( icon: Icon( Icons.home, color: Colors.black, size: 30, ), label: '', ), BottomNavigationBarItem( icon: Icon( Icons.favorite, color: Colors.black, ), label: '', ), BottomNavigationBarItem( icon: Icon( Icons.shopping_cart, color: Colors.black, ), label: '', ), BottomNavigationBarItem( icon: Icon( Icons.payment, color: Colors.black, ), label: '', ), BottomNavigationBarItem( icon: Icon( Icons.person, color: Colors.black, ), label: '', ), ], ), ); } }
pragma circom 2.0.3; include "../../node_modules/circomlib/circuits/poseidon.circom"; /** * Computes the Poseidon merkle root of a list of field elements * @param num_eles The number of elements to compute the Poseidon merkle root over * @input in The input array of size num_eles field elements * @output out The Poseidon merkle root of in */ template posiedon_generalized(num_eles) { signal input in[num_eles]; // Can do bytes to field element // max individual posiedon is 16 var total_poseidon = (num_eles) \ 15 + 1; component poseidon_aggregator[total_poseidon]; for (var i=0; i < total_poseidon; i++) { var poseidonSize = 16; if (i == 0) poseidonSize = 15; poseidon_aggregator[i] = Poseidon(poseidonSize); for (var j = 0; j < 15; j++) { if (i*15 + j >= num_eles ) { poseidon_aggregator[i].inputs[j] <== 0; } else { poseidon_aggregator[i].inputs[j] <== in[i*15 + j]; } } if (i > 0) { poseidon_aggregator[i].inputs[15] <== poseidon_aggregator[i- 1].out; } } signal output out; out <== poseidon_aggregator[total_poseidon-1].out; } /** * Converts 48 bytes to a BLS12-381 field element * @input bytes The input 48 bytes * @output field_ele The output BLS12-381 field element */ template bytes_48_to_field_ele() { // TODO: can also optimized by packing a 48 byte pubkeyhex into // 2 field elements to put into poseidon signal input bytes[48]; signal output field_ele[2]; signal field_ele_accum[2][24]; for (var i=0; i < 2; i++) { for (var j=0; j < 24; j++) { if (j == 0) { field_ele_accum[i][j] <== 0; } else { field_ele_accum[i][j] <== field_ele_accum[i][j-1] + 2**(j*8) * bytes[i*24 + j]; } } } field_ele[0] <== field_ele_accum[0][23]; field_ele[1] <== field_ele_accum[1][23]; } /** * Computes the Poseidon merkle root of a list of BLS12-381 public keys * @param b The size of the set of public keys * @param k The number of registers * @input pubkeys The input array of size b with BLS12-381 public keys * @output out The Poseidon merkle root of pubkeys */ template PubkeyPoseidon(b, k) { // TODO: this can be optimized further by packing the pubkey into a smaller number of field elements signal input pubkeys[b][2][k]; signal output out; component posiedonHasher = posiedon_generalized(2*b*k); for (var i=0; i < b; i++) { for (var j=0; j < k; j++) { for (var l=0; l < 2; l++) { posiedonHasher.in[i*k*2 + j*2 + l] <== pubkeys[i][l][j]; } } } out <== posiedonHasher.out; }