text
stringlengths 184
4.48M
|
|---|
package com.savent.restaurant.ui.screen.sales
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.PullRefreshState
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.savent.restaurant.R
import com.savent.restaurant.ui.component.SearchBar
import com.savent.restaurant.ui.model.sale.SaleItem
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class)
@Composable
fun SalesListScreen(
state: SalesState,
onEvent: (SalesEvent) -> Unit,
pullRefreshState: PullRefreshState
) {
val sheetState = rememberBottomSheetState(
initialValue = BottomSheetValue.Collapsed
)
val scaffoldState = rememberBottomSheetScaffoldState(
bottomSheetState = sheetState
)
val scope = rememberCoroutineScope()
val lazyListState = rememberLazyListState()
var dialog by remember { mutableStateOf(SalesDialog.ShareReceiptDialog) }
var idReceiptToShare = 0
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.91f)
.pullRefresh(pullRefreshState)
) {
BottomSheetScaffold(
scaffoldState = scaffoldState,
sheetContent = {
when (dialog) {
SalesDialog.ShareReceiptDialog ->
ShareReceiptDialog(
methods = state.shareReceiptMethods,
onClose = { scope.launch { sheetState.collapse() } },
onClick = {
onEvent(
SalesEvent.ShareReceipt(
orderId = idReceiptToShare,
method = it
)
)
scope.launch { sheetState.collapse() }
},
printerLongClick = {
scope.launch {
sheetState.collapse()
dialog = SalesDialog.SelectPrintDeviceDialog
delay(100)
sheetState.expand()
}
}
)
SalesDialog.SelectPrintDeviceDialog ->
RemoveDeviceDialog(onClose = {
scope.launch {
sheetState.collapse()
delay(200)
dialog = SalesDialog.ShareReceiptDialog
}
}) {
onEvent(SalesEvent.RemovePrintDevice)
scope.launch {
sheetState.collapse()
delay(200)
dialog = SalesDialog.ShareReceiptDialog
}
}
}
},
sheetShape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),
sheetBackgroundColor = Color.White,
sheetPeekHeight = 0.dp
) {
Column(modifier = Modifier.padding(top = 15.dp, start = 15.dp, end = 15.dp)) {
Spacer(modifier = Modifier.height(10.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Spacer(modifier = Modifier.width(5.dp))
Icon(
painter = painterResource(id = R.drawable.ic_order),
contentDescription = null,
modifier = Modifier.size(50.dp),
tint = Color.DarkGray
)
Spacer(modifier = Modifier.width(3.dp))
Text(
text = stringResource(id = R.string.sales),
style = MaterialTheme.typography.h3.copy(fontFamily = FontFamily.Cursive),
modifier = Modifier.padding(start = 5.dp)
)
}
Spacer(modifier = Modifier.height(15.dp))
SearchBar(
hint = stringResource(id = R.string.search),
textStyle = TextStyle(
fontSize = 20.sp,
fontWeight = FontWeight.Thin,
fontStyle = FontStyle.Italic
)
) {
onEvent(SalesEvent.Search(it))
}
Spacer(modifier = Modifier.padding(top = 20.dp))
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(bottom = 8.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(
count = state.sales.size,
key = { state.sales[it].id },
itemContent = {
Box(modifier = Modifier.animateItemPlacement(tween())) {
SaleItem(
sale = state.sales[it],
onShareReceipt = {
scope.launch { sheetState.expand() }
idReceiptToShare = state.sales[it].id
})
}
})
}
}
}
PullRefreshIndicator(
refreshing = state.isLoading,
state = pullRefreshState,
modifier = Modifier.align(
Alignment.TopCenter
)
)
}
}
private enum class SalesDialog {
ShareReceiptDialog, SelectPrintDeviceDialog
}
|
---
layout: post
title: "Pocket Twos Vs Eight Six Unsuited Poker Hand Odds | Which Is The Better Hand In Poker? A Complete Guide"
author: reece
categories: [ ]
image: assets/images/22-vs-86o.jpg
description: "Discover the ultimate showdown between Pair Of Twos and Eight Six Unsuited in poker! Uncover the odds, strategies, and scenarios where one hand triumphs over the other. Get ready to up your poker game with this thrilling analysis."
first_paragraph: "<p>Welcome to our latest poker strategy deep dive, where we're pitting two distinct hands against each other in a high-stakes showdown: Pair Of Twos vs Eight Six Unsuited.</p><p>In the dynamic world of poker, every decision counts, and knowing which hand holds the upper hand is key to your success at the table.</p><p>In this article, we'll dissect these two hands, explore the scenarios where one dominates the other, and equip you with the knowledge to make strategic choices that can tip the odds in your favor.</p><p>Get ready to unravel the intriguing dynamics of these poker hands and elevate your game to new heights.</p>"
eq_1: 50.20
eq_2: 49.80
win_1: 48.96
tie: 2.48
win_2: 48.56
card_1_label: 22
card_2_label: 86o
---
[comment]: # (sp0)
## Pre Flop Hand Match Up
<div class="table hand-ratings" markdown="1">
### Pair Of Twos vs Eight Six Unsuited - Odds Of Winning
<div class="row graphs">
<div class="col-lg-6">
<h3>Win Probablility</h3>
<canvas id="WinChart"></canvas>
</div>
<div class="col-lg-6">
<h3>Equity</h3>
<canvas id="EquityChart"></canvas>
</div>
</div>
Below, we present a detailed breakdown of the winning probabilities for each hand, providing you with the insight you need to navigate the intricate landscape of poker strategy and decision-making.
Dive into these numbers, and you'll find yourself better equipped to make those crucial calls at the table.
|   | |   |
| -------- | -------- | -------- |
| Pair Of Twos (22) | | Eight Six Unsuited (86o) |
| 48.96% | Win | 48.56% |
| 2.48% | Tie | 2.48% |
| 50.20% | Equity | 49.80% |
[comment]: # (sp1)
### Pair Of Twos vs Eight Six Unsuited - Limit Poker Hand Ratings
Top poker experts and players have crafted ways to judge the strength of starting hands in limit Texas hold'em.
Below, you'll see a table breaking down hand rankings according to popular systems.
Do remember, these rankings don't apply to no limit games.
|   | |   |
| -------- | -------- | -------- |
| Pair Of Twos | | Eight Six Unsuited |
| 7 | **Sklansky Rating** [What is this?](/sklansky-rating-explained) | - |
| 1 | **Chen Formula** [What is this?](/chen-formula-explained) | 2.5 |
| 4 | **Hellmuth Tier** [What is this?](/Hellmuth-tier-explained) | - |
| -0.09 | **Expected Value** [What is this?](/expected-value-explained) | -0.11 |
[comment]: # (sp2)
### Pair Of Twos vs Eight Six Unsuited - Winning Hand Breakdown
|   | |   |
| -------- | -------- | -------- |
| Pair Of Twos | | Eight Six Unsuited |
| 0 | High Card | 0 |
| 13,338,000 | One Pair | 19,712,304 |
| 20,412,000 | Two Pair | 22,222,080 |
| 13,658,832 | Three Of A Kind | 3,153,888 |
| 943,344 | Straight | 9,679,608 |
| 1,264,896 | Flush | 2,098,944 |
| 9,641,916 | Full House | 2,815,344 |
| 1,092,780 | Four Of A Kind | 156,528 |
| 10,836 | Straight Flush | 29,412 |
[comment]: # (sp3)
</div>
[comment]: # (sp4)
[comment]: # (sp5)
|
package com.gft.tdd.service;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.gft.tdd.email.NotificarEmail;
import com.gft.tdd.model.Pedido;
import com.gft.tdd.model.StatusPedido;
import com.gft.tdd.model.builder.PedidoBuilder;
import com.gft.tdd.repository.Pedidos;
import com.gft.tdd.sms.NotificarSms;
public class PedidoServiceText {
private PedidoService pedidoService;
@Mock
private Pedidos pedidos;
@Mock
private NotificarEmail notificarEmail;
@Mock
private NotificarSms notificarSms;
private Pedido pedido;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
List<AcaoLancamentoPedido> acoes = Arrays.asList(pedidos, notificarEmail, notificarSms);
pedidoService = new PedidoService(pedidos, acoes);
pedido = new PedidoBuilder().comValor(100.0).para("João", "joao@joao.com", "9999-0000").construir();
}
@Test
public void deveCalcularOImposto() throws Exception {
double imposto = pedidoService.lancar(pedido);
assertEquals(10.0, imposto, 0.0001);
}
@Test
public void deveSalvarPedidoNoBancoDeDados() throws Exception {
pedidoService.lancar(pedido);
verify(pedidos).executar(pedido);
}
@Test
public void deveNotificarPorEmail() throws Exception {
pedidoService.lancar(pedido);
verify(notificarEmail).executar(pedido);
}
@Test
public void deveNotificarPorSms() throws Exception {
pedidoService.lancar(pedido);
verify(notificarSms).executar(pedido);
}
@Test
public void devePagarPedidoPendente() throws Exception {
Long codigoPedido = 135l;
Pedido pedidoPendente = new Pedido();
pedidoPendente.setStatus(StatusPedido.PENDENTE);
when(pedidos.buscarPeloCodigo(codigoPedido)).thenReturn(pedidoPendente);
Pedido pedidoPago = pedidoService.pagar(codigoPedido);
assertEquals(StatusPedido.PAGO, pedidoPago.getStatus());
}
@Test(expected = StatusPedidoInvalidoException.class)
public void deveNegarPagamento() throws Exception {
Long codigoPedido = 135l;
Pedido pedidoPendente = new Pedido();
pedidoPendente.setStatus(StatusPedido.PAGO);
when(pedidos.buscarPeloCodigo(codigoPedido)).thenReturn(pedidoPendente);
Pedido pedidoPago = pedidoService.pagar(codigoPedido);
}
}
|
# GO 语言学习
Go语言是一种静态类型、编译型语言;
内置了并发支持和函数式编程特性。
## 安装
- 特别简单,下载安装包,然后安装,或者下载二进制包,然后解压
以 Apple Silicon 为例
```shell
» wget https://dl.google.com/go/go1.21.11.darwin-arm64.tar.gz
» tar -xf go1.21.11.darwin-arm64.tar.gz -C ~/Documents/tools
```
- 配置 环境变量
```shell
# 这些都是可选的
#export GO111MODULE # 表示 Go 1.11 的模块
export GOROOT=~/Documents/tools/go
export GOPATH=~/workspace/hello-go
#export GOPROXY=https://goproxy.cn # 国内可能需要配置
# 在 PATH 中添加 go 可执行程序路径
export PATH=$PATH:$GOROOT/bin
```
## 第一个 Go 程序
以一个简单的程序来看看 Go 程序的基本结构:
- 包是 Go 语言的基本组成单元,通常使用单个的小写单词命名,一个 Go 程序本质上就是一组包的集合。
- main 包在 Go 中是一个特殊的包,整个 Go 程序中仅允许存在一个名为 main 的包。
- main 包中的主要代码是一个名为 main 的函数。这里的 main 函数会比较特殊:当运行一个可执行的 Go 程序的时候,所有的代码都会从这个入口函数开始运行。
[源文件](./helloword/helloworld.go)
执行
```shell
# 编译
» go build helloworld.go
# 执行
» ./helloworld
# 或者直接运行源码
» go run helloworld.go
```
源文件命名原则:
- Go 源文件总是用全小写字母形式的短小单词命名,并且以.go 扩展名结尾。
- 如果要在源文件的名字中使用多个单词,通常直接是将多个单词连接起来作为源文件名,而不是使用其他分隔符,比如下划线。
- 总体来说,尽量不要用两个以上的单词组合作为文件名,否则就很难分辨了。
标准 Go 代码风格
- 使用 Tab 而不是空格来实现缩进
Gofmt 是 Go 语言在解决规模化(scale)问题上的一个最佳实践,提交代码前使用 Gofmt 格式化 Go 源码。
- 在 Go 语言中,只有首字母为大写的标识符才是导出的(Exported),才能对包外的代码可见;如果首字母是小写的,那么就说明这个标识符仅限于在声明它的包内可见。
- main 包是不可以像标准库 fmt 包那样被导入(Import)的,如果导入 main 包,在代码编译阶段会收到一个 Go 编译器错误:import “xx/main” is a program, not an importable package。
- 不需要用分号“;” 来标识语句的结束?
虽然 Go 语言的正式语法规范使用分号“;”作为语句的结束,但在实践中,大多数分号是可选的,并且会被编译器自动插入,因此通常在代码中省略不写。
## 第一个 Go 模块
```shell
» mkdir hellomodule
» cd hellomodule
» vi main.go
#...
» go build main.go
# 抛出错误
main.go:4:2: no required module provides package github.com/valyala/fasthttp: go.mod file not found in current directory or any parent directory; see 'go help modules'
main.go:5:2: no required module provides package go.uber.org/zap: go.mod file not found in current directory or any parent directory; see 'go help modules'
# 初始化 module
» go mod init hellomodule
# 查看 module 目录下多了 go.mod 文件
# 执行 go mod tidy
» go mod tidy
# 查看 module 目录下还有 go.sum 文件
# 再执行 go build
# ...
# 执行程序
# ...
```
Go module 构建模式是在 Go 1.11 版本正式引入的,为的是彻底解决 Go 项目复杂版本依赖的问题,现在 Go module 已经成为了 Go 默认的包依赖管理机制和 Go 源码构建机制。
>*从 Go 1.11 到 Go 1.16 版本,不同的 Go 版本在 GO111MODULE 为不同值的情况下,构建模式几经变化,直到 Go 1.16 版本,Go Module 构建模式成为了默认模式。*
Go Module 的核心是一个名为 go.mod 的文件,在这个文件中存储了这个 module 对第三方依赖的全部信息。
一个 module 就是一个包的集合,这些包和 module 一起打版本、发布和分发。
go.mod 所在的目录—— module 的根目录。
```go
module hellomodule
go 1.21.11
```
这时除了按提示手动添加外,也可以使用 go mod tidy 命令,让 Go 工具自动添加依赖。
go.mod 已经记录了 hellomodule 直接依赖的包的信息。与此同时 hellomodule 目录下还多了一个名为 go.sum 的文件,这个文件记录了 hellomodule 的直接依赖和间接依赖包的相关版本的 hash 值,用来校验本地包的真实性。在构建的时候,如果本地依赖包的 hash 值与 go.sum 文件中记录的不一致,就会被拒绝构建。
## Go 项目的结构布局
### 典型的项目结构
```shell
» tree -F exe-layout
exe-layout
├── cmd/
│ ├── app1/
│ │ └── main.go
│ └── app2/
│ └── main.go
├── go.mod
├── go.sum
├── internal/
│ ├── pkga/
│ │ └── pkg_a.go
│ └── pkgb/
│ └── pkg_b.go
├── pkg1/
│ └── pkg1.go
├── pkg2/
│ └── pkg2.go
└── vendor/
```
这个项目典型布局就是“脱胎”于 Go 创世项目的最新结构布局
- cmd 目录就是存放项目要编译构建的可执行文件对应的 main 包的源文件。如果你的项目中有多个可执行文件需要构建,每个可执行文件的 main 包单独放在一个子目录中,比如图中的 app1、app2,cmd 目录下的各 app 的 main 包将整个项目的依赖连接在一起。
- 通常来说,main 包应该很简洁。我们在 main 包中会做一些命令行参数解析、资源初始化、日志设施初始化、数据库连接初始化等工作,之后就会将程序的执行权限交给更高级的执行控制对象。
- pkgN 目录,这是一个存放项目自身要使用、同样也是可执行文件对应 main 包所要依赖的库文件,同时这些目录下的包还可以被外部项目引用。
- go.mod 和 go.sum ,它们是 Go 语言包依赖管理使用的配置文件。
- vendor 目录。vendor 是 Go 1.5 版本引入的用于在项目本地缓存特定版本依赖包的机制,在 Go Modules 机制引入前,基于 vendor 可以实现可重现构建,保证基于同一源码构建出的可执行程序是等价的。现在 vendor 目录视为一个可选目录。因为 Go Module 本身就支持可再现构建,而无需使用 vendor。
### 多个 module 的项目结构
```shell
» tree multi-modules
multi-modules
├── go.mod // mainmodule
├── module1
│ └── go.mod // module1
└── module2
└── go.mod // module2
```
可以通过 git tag 名字来区分不同 module 的版本。
其中 vX.Y.Z 形式的 tag 名字用于代码仓库下的 mainmodule;
而 module1/vX.Y.Z 形式的 tag 名字用于指示 module1 的版本;
同理,module2/vX.Y.Z 形式的 tag 名字用于指示 module2 版本。
### 仅有一个可执行程序的项目结构
```shell
» tree -F -L 1 single-exe-layout
single-exe-layout
├── go.mod
├── internal/
├── main.go
├── pkg1/
├── pkg2/
└── vendor/
```
删除了 cmd 目录,将唯一的可执行程序的 main 包就放置在项目根目录下。
## Go 库项目结构布局
### 典型的库项目结构
```shell
» tree -F lib-layout
lib-layout
├── go.mod
├── internal/
│ ├── pkga/
│ │ └── pkg_a.go
│ └── pkgb/
│ └── pkg_b.go
├── pkg1/
│ └── pkg1.go
└── pkg2/
└── pkg2.go
```
库类型项目相比于 Go 可执行程序项目的布局要简单一些。因为这类项目不需要构建可执行程序,所以去除了 cmd 目录。
vendor 也不再是可选目录了。对于库类型项目而言,不推荐在项目中放置 vendor 目录去缓存库自身的第三方依赖,库项目仅通过 go.mod 文件明确表述出该项目依赖的 module 或包以及版本要求即可。
### 仅有一个包的 Go 库项目结构
进一步简化为
```shell
» tree -F -L 1 single-pkg-lib-layout
single-pkg-lib-layout
├── feature1.go
├── feature2.go
├── go.mod
└── internal/
```
将这唯一包的所有源文件放置在项目的顶层目录下(比如上面的 feature1.go 和 feature2.go)。
## Go 包依赖管理
### GO 构建模式的演进
- [01](./gopath-demo/)
- [02](./module-demo/)
---
项目所依赖的包有很多版本,Go Module 是如何选出最适合的那个版本的呢?
### 语义导入版本机制 (Semantic Import Versioning)
go.mod 的 require 段中依赖的版本号,都符合 v**X.Y.Z** 的格式。
参考 [语义版本](https://semver.org/)
- 语义版本号分成 3 部分:主版本号(major)、次版本号(minor)和补丁版本号(patch)。
- 按照语义版本规范,主版本号不同的两个版本是相互不兼容的。在主版本号相同的情况下,次版本号大都是向后兼容次版本号小的版本。补丁版本号也不影响兼容性。
Go Module 规定:如果同一个包的新旧版本是兼容的,那么它们的包导入路径应该是相同的。
那么有一天发布新的不兼容的版本时,它的包导入路径就要不同,那要怎么做? Go Module 创新性地给出了一个方法:将包主版本号引入到包导入路径中。如:
```go
import "github.com/sirupsen/logrus"
// 和
import "github.com/sirupsen/logrus/v2"
```
这就是 Go 的“语义导入版本”机制,也就是*通过在包导入路径中引入主版本号的方式,来区别同一个包的不兼容版本*。
甚至可以同时依赖一个包的两个不兼容版本,如:
```go
import (
"github.com/sirupsen/logrus"
logv2 "github.com/sirupsen/logrus/v2"
)
```
### 最小版本选择机制 (Minimal Version Selection)

在这张图中,myproject 有两个直接依赖 A 和 B,A 和 B 有一个共同的依赖包 C,但 A 依赖 C 的 v1.1.0 版本,而 B 依赖的是 C 的 v1.3.0 版本,并且此时 C 包的最新发布版为 C v1.7.0。这个时候,Go 命令是如何为 myproject 选出间接依赖包 C 的版本呢?
理想状态下,语义版本控制被正确应用,那么 Go 包依赖管理工具都会选择依赖项的“最新最大 (Latest Greatest) 版本”,对应到图中的例子,这个版本就是 v1.7.0。
但 Go 设计者另辟蹊径,在诸多兼容性版本间,他们不光要考虑最新最大的稳定与安全,还要尊重各个 module 的述求:A 明明说只要求 C v1.1.0 ,B 明明说只要求 C v1.3.0 。所以 **Go 会在该项目依赖项的所有版本中,选出符合项目整体要求的“最小版本”**。
这个例子中,C v1.3.0 是符合项目整体要求的版本集合中的版本最小的那个,于是 Go 命令选择了 C v1.3.0,而不是最新最大的 C v1.7.0。
并且,**Go 团队认为“最小版本选择”为 Go 程序实现<u>持久的和可重现的构建</u>提供了最佳的方案**。
### 总结
Go Module 构建模式将成为 Go 语言唯一的标准构建模式。从现在开始就彻底抛弃 GOPATH 构建模式,全面使用 Go Module 构建模式!
## Go Module 一些常规操作
[详见](./module-demo-02/)
## 入口函数
Go 语言中有一个特殊的函数:main 包中的 main 函数,也就是 main.main,它是所有 Go 可执行程序的用户层执行逻辑的入口函数。
可执行程序的 main 包必须定义 main 函数,否则 Go 编译器会报错。
在启动了多个 Goroutine(Go 语言的轻量级用户线程)的 Go 应用中,main.main 函数将在 Go 应用的主 Goroutine 中执行。
main 函数返回就意味着整个 Go 程序的终结,它不会管这个时候是否还有其他子 Goroutine 正在执行。
除了 main 包外,其他包也可以拥有自己的名为 main 的函数或方法。但按照 Go 的可见性规则(小写字母开头的标识符为非导出标识符),非 main 包中自定义的 main 函数仅限于包内使用。
需要明白的是:**虽然 main.main 是用户层逻辑的入口函数,但它却不一定是用户层第一个被执行的函数。因为 Go 语言还有另一个函数 init 。**
## init 函数 —— Go 包初始化函数
- 无参数无返回值的函数
- 在 Go 程序中我们不能手工显式地调用 init (会收到编译错误)
- Go 包可以拥有不止一个 init 函数,每个组成 Go 包的 Go 源文件中,也可以定义多个 init 函数。
在初始化 Go 包时,Go 会按照一定的次序,逐一、顺序地调用这个包的 init 函数。一般来说,先传递给 Go 编译器的源文件中的 init 函数,会先被执行;而同一个源文件中的多个 init 函数,会按声明顺序依次执行。
### Go 包初始化顺序
Go 包是程序逻辑封装的基本单元,每个包都可以理解为是一个“自治”的、封装良好的、对外部暴露有限接口的基本单元。
一个 Go 程序就是由一组包组成的,。每个 Go 包还会有自己的依赖包、常量、变量、init 函数、main.main 函数等。
根据 Go 语言规范,一个被多个包依赖的包仅会初始化一次。程序的初始化就是这些包的初始化
Go 编译器为了确保包的初始化是可预测且一致的,在 go 1.21 改进了包初始化的算法,如下:
1. 先确定包的初始化顺序
其算法有`拓扑排序`( topological sort ) 和 `字母顺序`( alphabetical order )。
对于有依赖关系的包,按拓扑排序来确定初始化顺序,确保每个包在其依赖的包之后初始化;
对于没有直接依赖关系的包,按照包路径的字母顺序进行初始化。
1. 然后是单个包内的初始化顺序
1. 先全局变量初始化:先初始化常量,再初始化变量。变量按照它们声明的顺序进行初始化
1. 再执行 init 函数 ,如果有多个 init 函数,按照它们在代码中出现的顺序执行。并且只有当一个 init 函数执行完毕后,才会去执行下一个 init 函数。
为了更好的理解包初始化的顺序,请务必看[示例](./module-init/)。
>拓扑排序,举例
>- 将所有依赖包按照导入路径排序,放入一个 list ;
>- 从 list 中按顺序找出第一个自身尚未初始化,但其依赖包已经全部初始化了的包,然后初始化该包,并将该包从 list 中删除;
>- 重新执行上面步骤,直到 list 为空
### init 函数的用途
- 重置包级变量值
- 实现对包级变量的复杂初始化
- 在init函数中实现“注册模式”
- 注册模式实际上是 init 对工厂设计模式的实现
- 参考[示例](./module-init/internal/main.go)
## 实践
- 一个简单的 web 服务应用,[详见此](./simple-http-server/)
- 一个图书服务管理 API ,[详见此](./bookstore/)
## 参考
- https://tonybai.com/google-go-style/google-go-style-best-practices/
- https://github.com/golang-standards/project-layout
|
class TrieNode {
public:
TrieNode *children[26];
string word;
TrieNode(){
word = "";
for (int i = 0; i < 26; i++) {
children[i] = NULL;
}
}
};
class Trie {
public:
TrieNode *root;
Trie(){
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string &s)
{
TrieNode *cur = root;
for(int i = 0; i < s.size(); i++)
{
char c = s[i] - 'a';
if (cur->children[c] == NULL)
{
cur->children[c] = new TrieNode();
}
cur = cur->children[c];
}
cur->word = s;
}
};
class Solution {
public:
void dfs(vector<vector<char>> &board, int i, int j, TrieNode *p, vector<string> &ans)
{
if(i<0 or i>=board.size() or j<0 or j>=board[0].size()) return;
char c = board[i][j];
if(c == '#' or !p->children[c - 'a']) return;
p = p->children[c - 'a'];
if (p->word.size() > 0)
{
ans.push_back(p->word);
p->word = "";
}
board[i][j] = '#';
dfs(board, i - 1, j, p, ans);
dfs(board, i, j - 1, p, ans);
dfs(board, i + 1, j, p, ans);
dfs(board, i, j + 1, p, ans);
board[i][j] = c;
}
vector<string> findWords(vector<vector<char>> &board, vector<string> &words)
{
// insert all words into the trie
Trie *trie = new Trie();
for(int i=0;i<words.size();i++){
trie->insert(words[i]);
}
vector<string>ans;
for(int i=0;i<board.size();i++) {
for(int j=0;j<board[0].size();j++) {
// start form every cell of board
dfs(board, i, j, trie->root, ans);
}
}
return ans;
}
};
|
import { v4 as uuidv4 } from "uuid";
export const TaskAddInput = ({
inputText,
setInputText,
taskList,
setTaskList,
}) => {
const handleSubmit = (e) => {
e.preventDefault();
const taskId = uuidv4();
// カードを追加する
setTaskList([
{
id: taskId,
draggableId: `draggable-${taskId}`,
text: inputText,
},
...taskList,
]);
setInputText("");
};
const handleChange = (e) => {
setInputText(e.target.value);
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="add a task"
className="taskAddInput"
onChange={handleChange}
value={inputText}
/>
</form>
</div>
);
};
|
#DESCRIPTION
## Combinatorics: Graph Theory
##ENDDESCRIPTION
## DBsubject(Graph theory)
## Date(11/11/2015)
## Institution(NUI Galway)
## Author(Niall Madden)
## Level(3)
## MO(1)
## KEYWORDS('graph theory', 'eulers formula')
#####################################################################
DOCUMENT(); # This should be the first executable line in the problem.
loadMacros(
"PGstandard.pl",
"MathObjects.pl",
"PGML.pl",
"parserRadioButtons.pl",
"PGcourse.pl"
);
#####################################################################
$showPartialCorrectAnswers = 0;
TEXT(beginproblem());
Context("Numeric");
$m = random(3,10);
$n = random(4,10);
$v = $m+$n;
$e = $m*$n;
$f = 2-$v + $e;
$g = 4;
Context()->texStrings;
BEGIN_PGML
Let's prove that [`K_{[$m],[$n]}`] is not planar:
First, how many vertices and how many edges does [`K_{[$m],[$n]}`] have?
[`v = `] [____________]{$v} and [`e = `] [____________]{$e}.
Suppose, for the sake of contradiction, that [`K_{[$m],[$n]}`] is planar. Then how many faces _would_ it have?
[`f = `] [_____________]{$f}.
However, since every face is bounded by at least [_______]{$g} edges, and every edge borders exactly [_______]{2} faces, we can get a bound on the number of faces. What is the largest number of faces possible based on this line of reasoning?
[`f \le `] [_____________]{Compute(2*$e/$g)}
This is a contradiction, so [`K_{[$m],[$n]}`] is not planar. QED.
END_PGML
ENDDOCUMENT(); # This should be the last executable line in the problem.
|
/*Write a program using the tax information below: -
Gross Pay Tax Rate
Over 40,000 30%
>= 30,000 but below 40,000 25%
>=20,000 but below 30,000 15%
>=10,000 but below 20,000 10%
Below 10,000 no tax.
Write a program that accepts the gross pay and computes both the tax amount and the net pay.
(Assume the net pay is gross pay – tax amount) using functions*/
#include<iostream>
using namespace std;
double tax_amount(int gross_pay)
{
double tax_amount;
if(gross_pay>=40000)
{
tax_amount= gross_pay * 30.0/100;
//net_pay = gross_pay - tax_amount;
}
else if(gross_pay>=30000 && gross_pay<40000)
{
tax_amount = gross_pay * 25.0/100;
//net_pay = gross_pay - tax_amount;
}
else if(gross_pay>=20000 && gross_pay<30000)
{
tax_amount = gross_pay * 15.0/100;
//net_pay = gross_pay - tax_amount;
}
else if(gross_pay>=10000 && gross_pay<20000)
{
tax_amount = gross_pay * 10.0/100;
//net_pay = gross_pay - tax_amount;
}
else if(gross_pay<=10000){
cout<<"Not Taxed";
}
return tax_amount;
}
int main(){
int gross_pay;
double net_pay;
cout<<"Enter the gross_pay->";
cin>>gross_pay;
net_pay=gross_pay-tax_amount(gross_pay);
cout<<"The tax_amount is->"<< tax_amount(gross_pay) <<endl;
cout<<"The net_pay is->"<< net_pay <<endl;
return 0;
}
|
import React, { useState, useEffect } from 'react';
import { getChartDataByCountry } from 'api';
import { Line } from 'react-chartjs-2';
const LineChart = (props) => {
const [chartData, setChartData] = useState([]);
const fetchData = async(slug) => {
setChartData(await getChartDataByCountry(slug));
}
useEffect(() => {
const country = props.country;
fetchData(country);
}, [props.country])
const dateString = (date) => {
const str = new Date(date).toString().slice(4, 10);
return str;
}
const lineChart = (
chartData.length ?
(<Line
data={{
labels: chartData.map(( { Date } ) => dateString(Date) ),
datasets: [{
data: chartData.map(( { Confirmed } ) => Confirmed),
label: 'Confirmed',
borderColor: '#ff5a0d',
pointRadius: '1',
fill: true
}, {
data: chartData.map(( { Recovered } ) => Recovered),
label: 'Recovered',
borderColor: '#006721',
pointRadius: '1',
fill: true
}, {
data: chartData.map(( { Deaths } ) => Deaths),
label: 'Deaths',
borderColor: '#d70029',
pointRadius: '1',
fill: true
}]
}}
/>)
:
(<Line
data={{
labels: null,
datasets: [{
data: null,
label: 'Confirmed',
borderColor: '#ff5a0d',
fill: true
}, {
data: null,
label: 'Recovered',
borderColor: '#006721',
fill: true
}, {
data: null,
label: 'Deaths',
borderColor: '#d70029',
fill: true
}]
}}
/>)
)
return (
<div>
{lineChart}
</div>
)
}
export default LineChart;
|
package com.example.zalo.controller;
import com.example.zalo.config.JwtTokenUtil;
import com.example.zalo.model.jwt.JwtRequest;
import com.example.zalo.model.jwt.JwtResponse;
import com.example.zalo.service.JwtUserDetailsService;
import com.example.zalo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin
@RestController
public class JwtAuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private JwtUserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserService userService;
@RequestMapping(value = "/api/v1/login", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {
authenticate(authenticationRequest.getPhoneNumber(), authenticationRequest.getPassword());
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getPhoneNumber());
final String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new JwtResponse(token));
}
private void authenticate(String phoneNumber, String password){
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(phoneNumber, password));
}
}
|
// These day constants can be any value as long as they can be used as object keys
const MONDAY = 'monday'
const TUESDAY = 'tuesday'
const WEDNESDAY = 'wednesday'
const THURSDAY = 'thursday'
const FRIDAY = 'friday'
const SATURDAY = 'saturday'
const SUNDAY = 'sunday'
/**
* Maps the day constants to Date.prototype.getDate() values
*/
const DAY_TO_NUM = {
[MONDAY]: 1,
[TUESDAY]: 2,
[WEDNESDAY]: 3,
[THURSDAY]: 4,
[FRIDAY]: 5,
[SATURDAY]: 6,
[SUNDAY]: 0
}
/**
* Maps the Date.prototype.getDate() values to the day constants
*/
const NUM_TO_DAY = {
1: MONDAY,
2: TUESDAY,
3: WEDNESDAY,
4: THURSDAY,
5: FRIDAY,
6: SATURDAY,
0: SUNDAY
}
const UNIQUE_DAYS = [
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
]
const DEFAULT_WORKDAYS = [
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY
]
/**
* Based on Python's dateutil easter implementation
* @param {number} year
* @returns date of easter sunday at given year
*/
function calcEasterSunday(year: any) {
if (typeof year !== 'number')
throw new Error('Year must specified as a number')
const y = year
const g = y % 19
const c = Math.floor(y / 100)
const h = (c - Math.floor(c / 4) - Math.floor((8 * c + 13) / 25) + 19 * g + 15) % 30
const i = h - Math.floor(h / 28) * (1 - Math.floor(h / 28) * Math.floor(29 / (h + 1)) * Math.floor((21 - g) / 11))
const j = (y + Math.floor(y / 4) + i + 2 - c + Math.floor(c / 4)) % 7
const p = i - j
const d = 1 + (p + 27 + Math.floor((p + 6) / 40)) % 31
const m = 3 + Math.floor((p + 26) / 30)
return new Date(y, m - 1, d)
}
/**
* Offset given date
* @param {Date} date
* @param offsets
* @returns new date with offsets
*/
function offsetDate(
date: Date,
{ years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0 } = {}
) {
return new Date(
date.getFullYear() + years,
date.getMonth() + months,
date.getDate() + days,
date.getHours() + hours,
date.getMinutes() + minutes,
date.getSeconds() + seconds,
date.getMilliseconds() + milliseconds
);
}
/**
* @param {string} isodate, date formatted as YYYY-MM-DD
* @param offsets
* @returns string with format YYYY-MM-DD
*/
function offsetISODate(
isodate: string,
{ years = 0, months = 0, days = 0 } = {}
) {
return offsetDate(new Date(isodate.split('T')[0]), { years, months, days }).toISOString().split('T')[0]
}
/**
* Returns easter days respective to given year
* @param {number} year must be greater or equal to 1970
* @returns
*/
function calcEasterDates(year: any) {
const easterSunday = calcEasterSunday(year)
return {
palmSunday: offsetDate(easterSunday, { days: -7 }),
maundyThursday: offsetDate(easterSunday, { days: -3 }),
goodFriday: offsetDate(easterSunday, { days: -2 }),
easterSunday,
easterMonday: offsetDate(easterSunday, { days: 1 }),
ascensionDay: offsetDate(easterSunday, { days: 39 }),
whitsun: offsetDate(easterSunday, { days: 49 }),
whitMonday: offsetDate(easterSunday, { days: 50 })
}
}
/**
* @param {number} year
* @returns
*/
function getNorwegianHolidays(year: number) {
const easterDates = calcEasterDates(year)
const fixedHolidays = {
newYear: new Date(year, 0, 1),
workersDay: new Date(year, 4, 1),
independenceDay: new Date(year, 4, 17),
christmasEve: new Date(year, 11, 24), // Not necessarily for all workplaces
christmasDay: new Date(year, 11, 25), // Forste juledag
boxingDay: new Date(year, 11, 26), // Andre jule dag
newYearsEve: new Date(year, 11, 31), // Not necessarily for all workplaces
}
return { ...easterDates, ...fixedHolidays }
}
/**
* @param {Date} date
* @returns
*/
function inWeekend(date: { getDay: () => number }) {
return !(date.getDay() % 6)
}
/**
* Inclusive 'from' and 'to' dates
* @param {Date} date
* @param {Date} from
* @param {Date} to
* @returns
*/
function isBetween(date: { getTime: () => number }, from: any, to: { getTime: () => number }) {
return (from.getTime() <= date.getTime()) && (date.getTime() <= to.getTime())
}
/**
* Calculate number of days between and including 'from' and 'to' dates.
* @param {Date} from
* @param {Date} to
* @returns total number of days, and the count of each distinct days
*/
function countDays(from: { getTime: () => number; getDay: () => any }, to: Date) {
const days = 1 + Math.round((to.getTime() - from.getTime()) / 86400000)
const fromDay = from.getDay()
return {
days,
[MONDAY]: Math.floor((days + (fromDay + 5) % 7) / 7),
[TUESDAY]: Math.floor((days + (fromDay + 4) % 7) / 7),
[WEDNESDAY]: Math.floor((days + (fromDay + 3) % 7) / 7),
[THURSDAY]: Math.floor((days + (fromDay + 2) % 7) / 7),
[FRIDAY]: Math.floor((days + (fromDay + 1) % 7) / 7),
[SATURDAY]: Math.floor((days + fromDay) / 7),
[SUNDAY]: Math.floor((days + (fromDay + 6) % 7) / 7)
}
}
/**
* Loop based version of countDays. Used for validation in tests.
* @param {Date} from
* @param {Date} to
* @returns
*/
function slowCountDays(from: any, to: { getTime: () => number }) {
const counts = {
days: 0,
[MONDAY]: 0,
[TUESDAY]: 0,
[WEDNESDAY]: 0,
[THURSDAY]: 0,
[FRIDAY]: 0,
[SATURDAY]: 0,
[SUNDAY]: 0
}
let curr = offsetDate(from) // do a copy
while (curr.getTime() <= to.getTime()) {
counts[NUM_TO_DAY[curr.getDay()]] += 1
curr = offsetDate(curr, { days: 1 })
counts.days++
}
return counts
}
/**
* Generator returning norwegian holidays between 'from' and 'to' dates
* @param {Date} from
* @param {Date} to
* @returns {Generator<Date, void, void>}
*/
function* norwegianHolidaysGenerator(from: { getFullYear: () => any }, to: Date) {
const fromYear = from.getFullYear()
for (let i of Array(to.getFullYear() - fromYear + 1).keys())
for (let date of (<any>Object).values(getNorwegianHolidays(i + fromYear)))
if (isBetween(date, from, to))
yield date
else
continue
}
/**
* E.g. given monday to friday, return ['saturday', 'sunday']
* @param {Array<Date>} days
* @returns
*/
function getComplementWeekdays(days: Iterable<unknown> | null | undefined) {
let daysSet = new Set(days)
return UNIQUE_DAYS.filter(day => !daysSet.has(day))
}
/**
* @param {Iterable<Date>} holidays
* @param {Array<string>} workdays
* @returns
*/
function countHolidaysInWorkdays(holidays: Generator<any, void, unknown>, workdays: any[]) {
const workdaySet = new Set(workdays.map((day: string | number) => DAY_TO_NUM[day]))
let holidaysInWorkdays = 0
for (let holiday of holidays)
if (workdaySet.has(holiday.getDay())){
holidaysInWorkdays++
}
return holidaysInWorkdays
}
/**
* Get today's date object with zeroed out hours, minutes, seconds and milliseconds
* @returns
*/
function getTodayDate() {
const date = new Date()
date.setHours(0, 0, 0, 0)
return date
}
/**
* Get today's date iso string (YYYY-MM-DD)
* @returns
*/
function getTodayISO() {
const date = new Date()
date.setHours(0, -date.getTimezoneOffset(), 0, 0)
return date.toISOString().split('T')[0]
}
/**
* @param {string} isodate MMMM-YY-DD
* @returns
*/
function ISOToMs(isodate: { split: (arg0: string) => { split: (arg0: string) => string | number | Date }[] }) {
return new Date(isodate.split('T')[0].split('-')).getTime()
}
/**
* @param {number} actualHours
* @param {Date} referenceDate
* @param {number} referenceBalance
* @param {{
* to: Date,
* workdays: Array<string>,
* holidays: Iterable<Date>,
* workHoursPerDay: number
* }} optionals
* @returns flex balance
*/
function calcFlexBalance(
actualHours: number,
referenceDate: any,
referenceBalance: number,
{
to = getTodayDate(),
workdays = DEFAULT_WORKDAYS,
holidays = norwegianHolidaysGenerator(referenceDate, to),
workHoursPerDay = 7.5
} = {}
) {
const { days: dayCount, ...weekdaysCounts } = countDays(referenceDate, to)
const holidaysInWorkdays = countHolidaysInWorkdays(holidays, workdays)
const offdaysCount = getComplementWeekdays(workdays).reduce((acc, day) => acc + weekdaysCounts[day], 0)
const expectedHours = (dayCount - holidaysInWorkdays - offdaysCount) * workHoursPerDay
return actualHours - expectedHours + referenceBalance
}
export default {
calcEasterDates,
calcEasterSunday,
calcFlexBalance,
countDays,
countHolidaysInWorkdays,
DAY_TO_NUM,
DEFAULT_WORKDAYS,
FRIDAY,
getComplementWeekdays,
getNorwegianHolidays,
getTodayDate,
getTodayISO,
inWeekend,
isBetween,
ISOToMs,
MONDAY,
norwegianHolidaysGenerator,
NUM_TO_DAY,
offsetDate,
offsetISODate,
SATURDAY,
slowCountDays,
SUNDAY,
THURSDAY,
TUESDAY,
UNIQUE_DAYS,
WEDNESDAY
}
|
const { User } = require('../models');
const userController = {
//get all users
getAllUsers(req, res) {
User.find({})
.then(dbUserData => res.json(dbUserData))
.catch(err => {
console.log(err);
res.sendStatus(400);
});
},
//get one user by id
getUserbyId({ params }, res) {
User.findOne({ _id: params.id })
.populate({
path: 'thought',
select: '-__v',
path: 'friends',
select: '-__v'
})
.select('-__v')
.then(dbUserData => res.json(dbUserData))
.catch(err => {
console.log(err);
res.sendStatus(400);
});
},
//post for new user
createUser({ body }, res) {
User.create(body)
.then(dbUserData => res.json(dbUserData))
.catch(err => res.json(err));
},
//update user
updateUser({ params, body }, res) {
User.findOneAndUpdate({ _id: params.id}, body, { new: true, runValidators: true})
.then(dbUserData => {
if (!dbUserData) {
res.status(404).json({ message:"No user found with this ID!"});
return;
}
res.json(dbUserData);
})
.catch(err => res.json(err));
},
//delete user
deleteUser({ params }, res) {
User.findOneAndDelete({ _id: params.id} )
.then(dbUserData => res.json(dbUserData))
.catch(err => res.json(err));
},
//add friend
addFriend({ params }, res) {
User.findOneAndUpdate(
{_id: params.userId},
{ $push: {friends: params.friendId } },
{ new: true }
)
.then(dbUserData => {
if(!dbUserData) {
res.status(404).json({ message: "No User found with this ID!"});
return;
}
res.json(dbUserData);
})
.catch(err => res.json(err));
},
//remove friend from user
removeFriend({ params }, res) {
User.findOneAndDelete({ _id: params.userId })
.then(deletedFriend => {
if (!deletedFriend) {
return res.status(404).json({ message: "No User found with this ID!"});
}
return User.findOneAndUpdate(
{ _id: params.friendId },
{ $pull: { friends: params.friendId } },
{new: true }
);
})
.then(dbUserData => {
if (!dbUserData) {
res.status(404).json({ message: "No User found with this ID!" });
return;
}
res.json(dbUserData);
})
.catch(err => res.json(err));
}
};
module.exports = userController;
|
package com.example.universityapp.mvvm
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.universityapp.data.entity.Grade
import com.example.universityapp.data.retrofit.RetrofitInstance
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class GradeMVVM(val token: String) : ViewModel() {
private val TAG: String = "GradeMVVM"
private val mutableGrade: MutableLiveData<Grade> = MutableLiveData<Grade>()
fun getGrade(studentId: String) {
RetrofitInstance.mrsuApi.getGrade("Bearer $token", studentId)
.enqueue(object : Callback<Grade> {
override fun onResponse(call: Call<Grade>, response: Response<Grade>) {
println(response.body())
mutableGrade.value = response.body()
}
override fun onFailure(call: Call<Grade>, t: Throwable) {
Log.e(TAG, t.message.toString())
}
})
}
fun observeDiscipline(): LiveData<Grade> {
return mutableGrade
}
}
|
import React, { useEffect, useRef, useState } from "react";
import { Route, Routes } from "react-router-dom";
import HomeView from "./pages/home-view/HomeView";
import { Topbar } from "./topbar/Topbar";
import Sidebar from "./sidebar/Sidebar";
import StoresView from "./pages/stores/StoresView";
import SingleStoreView from "./pages/stores/components/SingleStoreView";
import styles from "./app.module.scss"
import Loading from "../loading/Loading";
import EmployeesView from "./pages/employees/EmployeesView";
import EmployeeOnboardView from "./pages/employees/onboarding/EmployeeOnboardView";
import useCompany, { CompanyContext, businessUID } from "../../hooks/useCompany";
import { companyContext } from "../../hooks/useCompany";
import MyBusinessView from "./pages/mybusiness/MyBusinessView";
import useProfile, { profileContext } from "../../hooks/useProfile";
import { User } from "firebase/auth";
import SingleEmployeeView from "./pages/employees/single-employee/SingleEmployeeView";
import { auth } from "../../App";
interface AppProps {
user: User
}
function AutimaApp(props: AppProps) {
const [view, setView] = useState(<Loading/>)
useEffect(() => {
props.user.getIdTokenResult(true).then(v => {
if (v.claims.isBusinessAccount === true) {
setView(<AdminApp user={props.user} />)
} else {
setView(<EmployeeApp user={props.user}/>)
}
})
},[])
return (
<>
{
view
}
</>
);
}
const TopbarSafezone = () => {
return <div className={styles.topbarSafezone} />
}
interface EmployeeAppProps {
user: User,
}
const EmployeeApp = (props: EmployeeAppProps) => {
const profile = useProfile(props.user)
return (
<profileContext.Provider value={profile}>
<div>
<button onClick={e => { e.preventDefault(); profile.setAsBusinessAccount() }}>CONVERT TO BUSINESS ACCOUNT</button>
{
profile.invites.map((v, i) => (
<button key={i} onClick={()=> profile.joinCompany(v)}>Join {v.companyId}</button>
))
}
<button onClick={() => {auth.signOut()}}>Sign out</button>
</div>
</profileContext.Provider>
)
}
interface AdminAppProps {
user: User
}
const AdminApp = (props: AdminAppProps) => {
let appWindow = useRef() as React.MutableRefObject<HTMLInputElement>;
const [scrollState, setScrollState] = useState<number>(0);
useEffect(() => {
appWindow.current.addEventListener("scroll", () => {
setScrollState(appWindow.current.scrollTop);
});
});
const company: CompanyContext = useCompany(businessUID(props.user.uid))
return (
<companyContext.Provider value={company}><Sidebar /><div ref={appWindow} className={styles.managerApp}>
<div
className={styles.topbarContainer}
style={scrollState > 5
? {
background: "white",
boxShadow: "0px 0px 2px 0px gray",
transition: "all 300ms ease",
}
: {}}
>
<Topbar />
</div>
<TopbarSafezone />
<div style={{ display: "flex"}}>
<div style={{width: "80%", overflow: "clip"}}>
<Routes>
<Route path="*" element={<HomeView />} />
<Route path={"/stores"}>
<Route path={":storeId"} element={<SingleStoreView />} />
<Route path={""} element={<StoresView />} />
</Route>
<Route path={"/payroll"}>
</Route>
<Route path={"/employees"}>
<Route path={""} element={<EmployeesView />}/>
<Route path={"onboard"} element={<EmployeeOnboardView />} />
<Route path={":uid"} element={<SingleEmployeeView />}/>
</Route>
<Route path={"/messages"}/>
<Route path={"/tasks"}/>
<Route path={"/mybusiness"} element={<MyBusinessView />} />
<Route path={"/support"} element={<TestElement/>}/>
</Routes>
</div>
<RightToolBar/>
</div>
</div>
</companyContext.Provider>
)
}
type AddressResult = {
addressLines: string[]
administrativeArea: string
languageCode: string
locality: string
postalCode: string
regionCode: string
}
const useAddressValidation = () => {
const [input, setInput] = useState("")
const [result, setResult] = useState<AddressResult>()
function validate() {
const body = {
address: {
regionCode: "CA",
addressLines: [input]
}
}
fetch("https://addressvalidation.googleapis.com/v1:validateAddress?key=AIzaSyDQQOEb_WD7RJFrqiC_oKXAJlV36oZUSKQ", {
method: "POST",
body: JSON.stringify(body)
}).then(v => {
v.json().then(v => {
console.log(v.result.address.postalAddress as AddressResult)
setResult(v as AddressResult)
})
})
}
return {input, setInput, result, validate}
}
const TestElement = () => {
const address = useAddressValidation()
return (
<form onSubmit={(e) => { e.preventDefault(); address.validate() }}>
<input value={address.input} onChange={e => {address.setInput(e.currentTarget.value)}} />
<div>{`${address.result}`}</div>
</form>
)
}
const RightToolBar = () => {
return (
<div className={styles.rightBarWrapper}>
<div className={styles.rightBar}>
<h3 style={{textAlign: "end", color: "black", margin: "0"}}>Quick tools</h3>
<br />
<div>View Sales</div>
<div>Store Transfers</div>
<div>Add New Tasks</div>
<div>Manage Tickets</div>
<div>Onboard Employee</div>
</div>
</div>
)
}
export default AutimaApp;
|
import * as path from "path";
import { ContentCreator } from "./content-creator";
import { H5pPackage } from "./h5p-package";
import { H5pAudio } from "./models/h5p-audio";
import { H5PMemoryGameContent} from "./models/h5p-memory-game-content";
import { H5pImage } from "./models/h5p-image";
import { H5pMatchAudio } from "./models/h5p-match-audio";
import { H5pMatch} from "./models/h5p-match";
export class MemoryGameCreator extends ContentCreator<H5PMemoryGameContent> {
constructor(
h5pPackage: H5pPackage,
private data: Array<{
imageAlt: string;
image?: string;
audio?: string;
match?: string;
matchAlt: string;
matchAudio?: string;
}>,
sourcePath: string
) {
super(h5pPackage, sourcePath);
}
public setTitle(title: string) {
this.h5pPackage.h5pMetadata.title = title;
this.h5pPackage.addMetadata(this.h5pPackage.h5pMetadata);
}
protected contentObjectFactory(): H5PMemoryGameContent {
return new H5PMemoryGameContent();
}
protected async addContent(
contentObject: H5PMemoryGameContent
): Promise<void> {
contentObject.cards = new Array();
let imageCounter = 0;
let audioCounter = 0;
let matchCounter = 0;
let matchAudioCounter = 0;
for (const line of this.data) {
const cards = {
imageAlt: line.imageAlt,
matchAlt: line.matchAlt,
};
if (line.image) {
try {
let ret: { extension: string; buffer: Buffer; image: H5pImage };
if (
!line.image.startsWith("http://") &&
!line.image.startsWith("https://")
) {
ret = await H5pImage.fromLocalFile(
path.join(this.sourcePath, line.image)
);
} else {
ret = await H5pImage.fromDownload(line.image);
}
let filename = this.getFilenameForImage(
imageCounter++,
ret.extension
);
this.h5pPackage.addContentFile(filename, ret.buffer);
ret.image.path = filename;
cards["image"] = ret.image;
console.log(
`Downloaded image from ${line.image}. (${ret.buffer.byteLength} bytes)`
);
} catch (exc) {
console.error(exc);
cards["image"] = undefined;
}
}
if (line.audio) {
try {
let ret: { extension: string; buffer: Buffer; audio: H5pAudio };
if (
!line.audio.startsWith("http://") &&
!line.audio.startsWith("https://")
) {
ret = await H5pAudio.fromLocalFile(
path.join(this.sourcePath, line.audio)
);
} else {
ret = await H5pAudio.fromDownload(line.audio);
}
let filename = this.getFilenameForAudio(
audioCounter++,
ret.extension
);
this.h5pPackage.addContentFile(filename, ret.buffer);
ret.audio.path = filename;
cards["audio"] = [ret.audio];
console.log(
`Downloaded audio from ${line.audio}. (${ret.buffer.byteLength} bytes)`
);
} catch (exc) {
console.error(exc);
cards["audio"] = undefined;
}
}
if (line.match) {
try {
let ret: { extension: string; buffer: Buffer; match: H5pMatch };
if (
!line.match.startsWith("http://") &&
!line.match.startsWith("https://")
) {
ret = await H5pMatch.fromLocalFile(
path.join(this.sourcePath, line.match)
);
} else {
ret = await H5pMatch.fromDownload(line.match);
}
let filename = this.getFilenameForMatch(
matchCounter++,
ret.extension
);
this.h5pPackage.addContentFile(filename, ret.buffer);
ret.match.path = filename;
cards["match"] = ret.match;
console.log(
`Downloaded match from ${line.match}. (${ret.buffer.byteLength} bytes)`
);
} catch (exc) {
console.error(exc);
cards["match"] = undefined;
}
}
if (line.matchAudio) {
try {
let ret: { extension: string; buffer: Buffer; matchAudio: H5pAudio };
if (
!line.audio.startsWith("http://") &&
!line.audio.startsWith("https://")
) {
ret = await H5pMatchAudio.fromLocalFile(
path.join(this.sourcePath, line.matchAudio)
);
} else {
ret = await H5pMatchAudio.fromDownload(line.matchAudio);
}
let filename = this.getFilenameForMatchAudio(
matchAudioCounter++,
ret.extension
);
this.h5pPackage.addContentFile(filename, ret.buffer);
ret.matchAudio.path = filename;
cards["matchAudio"] = [ret.matchAudio];
console.log(
`Downloaded matchAudio from ${line.matchAudio}. (${ret.buffer.byteLength} bytes)`
);
} catch (exc) {
console.error(exc);
cards["matchAudio"] = undefined;
}
}
contentObject.cards.push(cards);
}
}
protected addSettings(contentObject: H5PMemoryGameContent) {
contentObject.behaviour = {
useGrid: true,
allowRetry: true,
};
}
private getFilenameForImage(counter: number, extension: string) {
return `images/image-${counter}${extension}`;
}
private getFilenameForAudio(counter: number, extension: string) {
return `audios/audio-${counter}${extension}`;
}
private getFilenameForMatch(counter: number, extension: string) {
return `images/match-${counter}${extension}`;
}
private getFilenameForMatchAudio(counter: number, extension: string) {
return `audios/matchAudio-${counter}${extension}`;
}
}
|
package view;
import util.DBConnectionUtil;
import util.DialogManagerUtil;
import util.MethodsUtil;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Principal extends JFrame {
private JPanel principalWindow;
private JButton employeesButton;
private JButton clientsButton;
private JButton toursButton;
private JButton dataBaseButton;
private JButton logOutButton;
private JPanel cards;
private JPanel MenuPanel;
private CardLayout cardLayout;
public static final String EMPLOYEES = "Employees";
public static final String CLIENTS = "Clients";
public static final String TOURS = "Tours";
public static final String DATABASE = "Database";
private ArrayList<JButton> buttons;
public JPanel getPrincipalWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttons = new ArrayList<>(Arrays.asList(clientsButton, employeesButton, toursButton, dataBaseButton, logOutButton));
cardLayout = new CustomCardLayout();
cards.setLayout(cardLayout);
cards.add(createClientsPanel(), CLIENTS);
cards.add(createEmployeesPanel(), EMPLOYEES);
cards.add(createToursPanel(), TOURS);
cards.add(createDataBasePanel(), DATABASE);
setButtonsIconsSize();
return principalWindow;
}
public Principal() {
clientsButton.addActionListener(e -> swapView("Clients"));
employeesButton.addActionListener(e -> {
if (Login.connectedEmployee.getRole().equals("ADMIN")) {
swapView("Employees");
} else {
DialogManagerUtil.showErrorDialog("Error: Privilegios insuficientes");
}
});
toursButton.addActionListener(e -> swapView("Tours"));
dataBaseButton.addActionListener(e -> swapView("Database"));
logOutButton.addActionListener(e -> {
DBConnectionUtil.dataBase.logEmployeeClockOut(Login.sessionId);
createLoginPanel();
});
}
private void setButtonsIconsSize() {
ArrayList<ImageIcon> icons = new ArrayList<>(Arrays.asList(
MethodsUtil.resizeImageIcon(new ImageIcon(".\\src\\resources\\clients.png"), 50, 50),
MethodsUtil.resizeImageIcon(new ImageIcon(".\\src\\resources\\employees.png"), 50, 50),
MethodsUtil.resizeImageIcon(new ImageIcon(".\\src\\resources\\tour.png"), 50, 50),
MethodsUtil.resizeImageIcon(new ImageIcon(".\\src\\resources\\database.png"), 50, 50),
MethodsUtil.resizeImageIcon(new ImageIcon(".\\src\\resources\\logout.png"), 50, 50)
));
for (int i = 0; i < icons.size(); i++) {
ImageIcon icon = icons.get(i);
JButton button = buttons.get(i);
button.setIcon(icon);
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusPainted(false);
}
}
private JPanel createClientsPanel() {
return new Clients().getClientsWindow();
}
private JPanel createEmployeesPanel() {
return new Employees().getEmployeesWindow();
}
private JPanel createToursPanel() {
return new Tours().getTourssWindow();
}
private JPanel createDataBasePanel() {
return new DataBaseInfo().getDataBaseWindow();
}
private void createLoginPanel() {
Arrays.asList(Window.getWindows()).forEach(Window::dispose);
Login login = new Login();
setContentPane(login.getLoginWindow());
pack();
setLocationRelativeTo(null);
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
setVisible(true);
}
private void swapView(String key) {
switch (key) {
case "Clients" -> {
cards.remove(0);
cards.add(createClientsPanel(), CLIENTS);
}
case "Employees" -> {
cards.remove(1);
cards.add(createEmployeesPanel(), EMPLOYEES);
}
case "Tours" -> {
cards.remove(2);
cards.add(createToursPanel(), TOURS);
}
case "Database" -> {
cards.remove(3);
cards.add(createDataBasePanel(), DATABASE);
}
}
cardLayout.show(cards, key);
}
public static class CustomCardLayout extends CardLayout {
@Override
public Dimension preferredLayoutSize(Container parent) {
Component current = findCurrentComponent(parent);
if (current != null) {
Insets insets = parent.getInsets();
Dimension pref = current.getPreferredSize();
pref.width += insets.left + insets.right;
pref.height += insets.top + insets.bottom;
return pref;
}
return super.preferredLayoutSize(parent);
}
public Component findCurrentComponent(Container parent) {
for (Component comp : parent.getComponents()) {
if (comp.isVisible()) {
return comp;
}
}
return null;
}
}
}
|
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../../../../../style.css">
<base target="_parent">
</head>
<body>
<div class="content">
<h1>4. Stem And Leaf Plot</h1>
<div class="ck-content">
<p style="margin-left:0px;">A stem and leaf plot is a type of data visualization used to display the
distribution of a set of numerical data. It's particularly useful for smaller
data sets and provides insights into the frequency and distribution of
values.</p>
<h2 style="margin-left:0px;">Here's how a stem and leaf plot works:</h2>
<ol>
<li style="margin-left:0px;"><strong>Stem</strong>: The "stem" represents the leftmost part of the
numbers. It typically consists of the highest place value digits shared
by all the numbers in the data set. For example, if your data set contains
two-digit numbers, the stem would be the tens digit.</li>
<li style="margin-left:0px;"><strong>Leaves</strong>: The "leaves" are the individual digits from the
data values. They are placed to the right of the stem, corresponding to
the remaining digits of each number. The leaves are arranged in ascending
order next to their respective stems.</li>
<li style="margin-left:0px;"><strong>Organization</strong>: The stem and leaves are organized in rows.
The same stem can have multiple leaves, indicating that those data points
share the same stem value.</li>
<li style="margin-left:0px;"><strong>Example</strong>: Let's say you have the data set [12, 18, 22,
25, 28, 30, 36, 39]. If you use the tens digit as the stem, the stem and
leaf plot might look like this:</li>
</ol>
<h3 style="margin-left:0px;">Advantages of Stem and Leaf Plots</h3>
<ol>
<li style="margin-left:0px;"><strong>Data Preservation</strong>: Stem and leaf plots provide a way
to preserve the actual data values while displaying their distribution.</li>
<li
style="margin-left:0px;"><strong>Small Data Sets</strong>: They are particularly useful for smaller
data sets where other types of plots might be overly complex.</li>
<li style="margin-left:0px;"><strong>Ease of Interpretation</strong>: Stem and leaf plots are easy
to understand and can quickly convey information about data patterns.</li>
<li
style="margin-left:0px;"><strong>Visual Display</strong>: Stem and leaf plots provide a visual
representation of the data's distribution, making it easier to identify
key features.</li>
</ol>
<h3 style="margin-left:0px;">Disadvantages of Stem and Leaf Plots</h3>
<ol>
<li style="margin-left:0px;"><strong>Limited for Large Data Sets</strong>: Stem and leaf plots become
unwieldy and difficult to read when dealing with larger data sets.</li>
<li
style="margin-left:0px;"><strong>Less Commonly Used</strong>: While they offer simplicity and insights,
stem and leaf plots are less commonly used compared to more standardized
graphical representations like histograms or box plots.</li>
<li style="margin-left:0px;"><strong>Scale Sensitivity</strong>: The interpretation of stem and leaf
plots can be sensitive to the scale chosen for the stems, which can affect
the way patterns are perceived.</li>
</ol>
<p>Suppose We Have A Table That tells the weight of</p>
<figure class="table">
<table>
<tbody>
<tr>
<td>Female</td>
<td>Male</td>
</tr>
<tr>
<td>50</td>
<td>67</td>
</tr>
<tr>
<td>57</td>
<td>66</td>
</tr>
<tr>
<td>61</td>
<td>71</td>
</tr>
<tr>
<td>45</td>
<td>79</td>
</tr>
<tr>
<td>32</td>
<td>81</td>
</tr>
<tr>
<td>33</td>
<td>82</td>
</tr>
<tr>
<td>44</td>
<td>88</td>
</tr>
<tr>
<td>47</td>
<td>83</td>
</tr>
<tr>
<td>48</td>
<td>77</td>
</tr>
<tr>
<td>41</td>
<td>91</td>
</tr>
</tbody>
</table>
</figure>
</div>
</div>
</body>
</html>
|
import * as React from "react";
import PropTypes from "prop-types";
import { alpha } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TablePagination from "@mui/material/TablePagination";
import TableRow from "@mui/material/TableRow";
import TableSortLabel from "@mui/material/TableSortLabel";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import Paper from "@mui/material/Paper";
import Checkbox from "@mui/material/Checkbox";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip";
import FormControlLabel from "@mui/material/FormControlLabel";
import Switch from "@mui/material/Switch";
import DeleteIcon from "@mui/icons-material/Delete";
// import FilterListIcon from "@mui/icons-material/FilterList";
import { visuallyHidden } from "@mui/utils";
// import axios from "axios";
import { Alert, Fab } from "@mui/material";
import { Link } from "react-router-dom";
import EditIcon from "@mui/icons-material/Edit";
import { useDispatch, useSelector } from "react-redux";
import { deleteProduct, fetchAllProducts } from "../app/productSlice";
import AddIcon from "@mui/icons-material/Add";
function descendingComparator(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
function getComparator(order, orderBy) {
return order === "desc"
? (a, b) => descendingComparator(a, b, orderBy)
: (a, b) => -descendingComparator(a, b, orderBy);
}
const headCells = [
{
id: "name",
numeric: false,
disablePadding: true,
label: "Product Name",
},
{
id: "Desc",
numeric: false,
disablePadding: true,
label: "Description",
},
{
id: "Manufacturer",
numeric: false,
disablePadding: true,
label: "Manufacturer",
},
{
id: "Qantity",
numeric: true,
disablePadding: false,
label: "Quantity",
},
{
id: "Price",
numeric: true,
disablePadding: false,
label: "Price",
},
];
function EnhancedTableHead(props) {
const {
onSelectAllClick,
order,
orderBy,
numSelected,
rowCount,
onRequestSort,
} = props;
const createSortHandler = (property) => (event) => {
onRequestSort(event, property);
};
return (
<TableHead>
<TableRow>
<TableCell padding="checkbox">
<Checkbox
color="primary"
indeterminate={numSelected > 0 && numSelected < rowCount}
checked={rowCount > 0 && numSelected === rowCount}
onChange={onSelectAllClick}
inputProps={{
"aria-label": "select all desserts",
}}
/>
</TableCell>
{headCells.map((headCell) => (
<TableCell
key={headCell.id}
sx={{ textAlign: "center" }}
sortDirection={orderBy === headCell.id ? order : false}
>
<TableSortLabel
active={orderBy === headCell.id}
direction={orderBy === headCell.id ? order : "asc"}
onClick={createSortHandler(headCell.id)}
>
{headCell.label}
{orderBy === headCell.id ? (
<Box component="span" sx={visuallyHidden}>
{order === "desc" ? "sorted descending" : "sorted ascending"}
</Box>
) : null}
</TableSortLabel>
</TableCell>
))}
<TableCell></TableCell>
</TableRow>
</TableHead>
);
}
EnhancedTableHead.propTypes = {
numSelected: PropTypes.number.isRequired,
onRequestSort: PropTypes.func.isRequired,
onSelectAllClick: PropTypes.func.isRequired,
order: PropTypes.oneOf(["asc", "desc"]).isRequired,
orderBy: PropTypes.string.isRequired,
rowCount: PropTypes.number.isRequired,
};
function EnhancedTableToolbar(props) {
const { numSelected, deleteProduct } = props;
return (
<Toolbar
sx={{
pl: { sm: 2 },
pr: { xs: 1, sm: 1 },
...(numSelected > 0 && {
bgcolor: (theme) =>
alpha(
theme.palette.primary.main,
theme.palette.action.activatedOpacity
),
}),
}}
>
{numSelected > 0 ? (
<Typography
sx={{ flex: "1 1 100%" }}
color="inherit"
variant="subtitle1"
component="div"
>
{numSelected} selected
</Typography>
) : (
<Typography
sx={{ flex: "1 1 100%", fontWeight: "600" }}
variant="h6"
id="tableTitle"
component="div"
>
Product List
</Typography>
)}
{numSelected > 0 ? (
<Tooltip title="Delete">
<IconButton onClick={deleteProduct}>
<DeleteIcon sx={{ color: "red" }} />
</IconButton>
</Tooltip>
) : (
<span></span>
)}
</Toolbar>
);
}
EnhancedTableToolbar.propTypes = {
numSelected: PropTypes.number.isRequired,
};
export default function Products() {
const [order, setOrder] = React.useState("asc");
const [orderBy, setOrderBy] = React.useState("calories");
const [selected, setSelected] = React.useState([]);
const [page, setPage] = React.useState(0);
const [dense, setDense] = React.useState(false);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
const [rows, setRows] = React.useState([]);
const [count, setCount] = React.useState(0);
const dispatch = useDispatch();
const select = useSelector((state) => state.products.products.slice());
const userEmail = sessionStorage.getItem("user");
// console.log(rows);
React.useEffect(() => {
setRows(select);
dispatch(fetchAllProducts());
}, [selected, select]);
const handleRequestSort = (event, property) => {
const isAsc = orderBy === property && order === "asc";
setOrder(isAsc ? "desc" : "asc");
setOrderBy(property);
};
const handleSelectAllClick = (event) => {
if (event.target.checked) {
const newSelected = rows.map((n) => n.productId);
setSelected(newSelected);
return;
}
setSelected([]);
};
// console.warn(selected);
const handleClick = (event, id) => {
const selectedIndex = selected.indexOf(id);
let newSelected = [];
if (selectedIndex === -1) {
newSelected = newSelected.concat(selected, id);
} else if (selectedIndex === 0) {
newSelected = newSelected.concat(selected.slice(1));
} else if (selectedIndex === selected.length - 1) {
newSelected = newSelected.concat(selected.slice(0, -1));
} else if (selectedIndex > 0) {
newSelected = newSelected.concat(
selected.slice(0, selectedIndex),
selected.slice(selectedIndex + 1)
);
}
setSelected(newSelected);
};
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const handleChangeDense = (event) => {
setDense(event.target.checked);
};
const isSelected = (name) => selected.indexOf(name) !== -1;
// Avoid a layout jump when reaching the last page with empty rows.
const emptyRows =
page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;
const handleDelete = () => {
if (selected.length > 0) {
selected.map((productID) => {
dispatch(deleteProduct(productID));
setSelected([]);
setCount(1);
});
}
};
setTimeout(() => {
setCount(0);
}, 1000);
return (
<Box sx={{ width: "100%" }}>
{count === 1 ? (
<Alert severity="success">Product is deleted succesfully....</Alert>
) : (
<span></span>
)}
{rows.length > 0 ? (
<Paper sx={{ width: "100%", mb: 2 }}>
<EnhancedTableToolbar
numSelected={selected.length}
deleteProduct={handleDelete}
/>
<TableContainer>
<Table
sx={{ minWidth: 750 }}
aria-labelledby="tableTitle"
size={dense ? "small" : "medium"}
>
<EnhancedTableHead
numSelected={selected.length}
order={order}
orderBy={orderBy}
onSelectAllClick={handleSelectAllClick}
onRequestSort={handleRequestSort}
rowCount={rows.length}
/>
<TableBody>
{/* if you don't need to support IE11, you can replace the `stableSort` call with:
rows.sort(getComparator(order, orderBy)).slice() */}
{rows
.sort(getComparator(order, orderBy))
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row, index) => {
const isItemSelected = isSelected(row.name);
const labelId = `enhanced-table-checkbox-${index}`;
return (
<TableRow
hover
onClick={(event) => handleClick(event, row.productId)}
role="checkbox"
aria-checked={isItemSelected}
tabIndex={-1}
key={row.productId}
selected={isItemSelected}
>
<TableCell padding="checkbox">
<Checkbox
color="primary"
checked={isItemSelected}
inputProps={{
"aria-labelledby": labelId,
}}
/>
</TableCell>
<TableCell
component="th"
id={labelId}
scope="row"
align="center"
>
<Link
to={`/productDetails/${row.productId}`}
className="link"
>
{row.productName}
</Link>
</TableCell>
<TableCell align="center">{row.description}</TableCell>
<TableCell align="center">{row.mfgBy}</TableCell>
<TableCell align="center">{row.quantity}</TableCell>
<TableCell align="center">{row.price}</TableCell>
<TableCell align="center">
<Link
to={
userEmail === null
? `/login`
: `/editProduct/${row.productId}`
}
>
<Fab
color="primary"
sx={{ background: "rgb(204, 133, 26)" }}
size="small"
aria-label="edit"
>
<EditIcon />
</Fab>
</Link>
</TableCell>
</TableRow>
);
})}
{emptyRows > 0 && (
<TableRow
style={{
height: (dense ? 33 : 53) * emptyRows,
}}
>
<TableCell colSpan={6} />
</TableRow>
)}
</TableBody>
</Table>
</TableContainer>
<TablePagination
rowsPerPageOptions={[5, 10, 25]}
component="div"
count={rows.length}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
</Paper>
) : (
<h1>List is empty</h1>
)}
<FormControlLabel
control={<Switch checked={dense} onChange={handleChangeDense} />}
label="Dense padding"
/>
<Link
to={userEmail !== null ? "/addProduct" : "/login"}
className="l-1 btn"
>
<Fab
size="small"
sx={{ bottom: 1, left: 600, position: "absolute" }}
color="primary"
aria-label="add"
>
<AddIcon />
</Fab>
</Link>
</Box>
);
}
|
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GEOMETRY; Base: 10 -*-
(in-package geometry)
(defgeneric calculate-relation (obj1 obj2 &rest rest)
(:documentation "Recognizes various spatial relationships between obj1 and obj2."))
;;;
;;; Punkt-Relationen (Punkt ist erstes Argument)
;;;
(defun inverse (rel)
(case rel
(contains 'inside)
(inside 'contains)
(covered-by 'covers)
(covers 'covered-by)
(otherwise rel)))
(defmethod calculate-relation ((p geom-point) (l geom-line) &rest rest)
(declare (ignore rest))
(if (lies-on-p p l)
'lies-on
'disjoint))
(defmethod calculate-relation ((l geom-line) (p geom-point) &rest rest)
(declare (ignore rest))
(inverse
(calculate-relation p l)))
;;;
;;; Strecken-Relationen (Strecke ist erstes Argument)
;;;
(defmethod calculate-relation ((l1 geom-line) (l2 geom-line) &key (detailed nil))
(if (and (bounding-box-p l1)
(bounding-box-p l2)
(not (box-overlaps-box-p l1 l2)))
'disjoint
(let* ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2))
(a (ccw l1p1 l1p2 l2p1))
(b (ccw l1p1 l1p2 l2p2))
(c (ccw l2p1 l2p2 l1p1))
(d (ccw l2p1 l2p2 l1p2)))
(cond ((and (<= (* a b) 0.0) (<= (* c d) 0.0)) ; Schnitt liegt vor
(let* ((l1p1-l2 (lies-on-p (p1 l1) l2))
(l1p2-l2 (lies-on-p (p2 l1) l2))
(l2p1-l1 (lies-on-p (p1 l2) l1))
(l2p2-l1 (lies-on-p (p2 l2) l1))
(n (+ (if l1p1-l2 1 0)
(if l1p2-l2 1 0)
(if l2p1-l1 1 0)
(if l2p2-l1 1 0))))
(let ((res
(ecase n
(0 'crosses) ; "X"
(1 'touches) ; "T"
(3
(if detailed
(if (and l1p1-l2 l1p2-l2)
'covered-by
'covers)
'1d-intersects)) ; "covers", "covered-by"
(4 'equal)
(2 (if (joins-p l1 l2)
'touches ; "--", "\/"
(if detailed
(if (and l1p1-l2 l1p2-l2)
'inside
(if (and l2p1-l1 l2p2-l1)
'contains
'overlaps))
'1d-intersects)))))) ; "contains", "inside", "overlaps"
(if detailed
(values res l1p1-l2 l1p2-l2 l2p1-l1 l2p2-l1)
res))))
(t 'disjoint)))))
|
<?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use App\Services\Product\ProductServiceInterface;
use Illuminate\Http\Request;
use Gloudemans\Shoppingcart\Facades\Cart;
class CartController extends Controller
{
private $productService;
public function __construct(ProductServiceInterface $productService)
{
$this->productService = $productService;
}
public function index(){
$carts = Cart::content();
$total = Cart::total();
$subtotal = Cart::subtotal();
return view('front.shop.cart',compact('carts','total','subtotal'));
}
public function add(Request $request){
if ($request->ajax()){
$product = $this->productService->find($request->productId);
$response['cart'] = Cart::add([
'id' => $product->id,
'name' => $product->name,
'qty' => 1,
'price' => $product->discount ?? $product->price,
'weight' => $product->weight ?? 0,
'options' => [
'images' => $product->productImages,
]
]);
$response['count'] = Cart::count();
$response['total'] = Cart::total();
return $response;
}
return back();
}
public function delete(Request $request){
if($request->ajax()){
$response['cart'] = Cart::remove($request->rowId);
$response['count'] = Cart::count();
$response['total'] = Cart::total();
$response['subtotal'] = Cart::subtotal();
return $response;
};
return back();
}
public function destroy(){
Cart::destroy();
}
public function update(Request $request){
if ($request->ajax()){
$response['cart'] = Cart::update($request->rowId, $request->qty);
$response['count'] = Cart::count();
$response['total'] = Cart::total();
$response['subtotal'] = Cart::subtotal();
return $response;
}
}
}
|
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'StartUp Name Generator',
theme: ThemeData(
primaryColor: Colors.teal,
accentColor: Colors.pink,
),
home: RandomWords(),
);
}
}
//stful = shortcut to stateful widget template
class RandomWords extends StatefulWidget {
@override
_RandomWordsState createState() => _RandomWordsState();
}
class _RandomWordsState extends State<RandomWords> {
@override
final _suggestions = <WordPair>[];
final _biggerFont = TextStyle(fontSize: 18.0);
// 'Set' preferred b/c doesn't allow duplicate entries
final _saved = Set<WordPair>();
Widget _buildSuggestions() {
return ListView.builder(
padding: EdgeInsets.all(16.0),
itemBuilder: (context, i) {
// add 1px high divider to visually separate entries
if (i.isOdd) return Divider();
// even rows = add ListtTile row
// divide i by 2, calculate # of word pairings in ListView - dividers
final index = i ~/ 2;
if (index >= _suggestions.length) {
// if @ end, generate 10 more and add to _suggestions
_suggestions.addAll(generateWordPairs().take(10));
}
// called once per word pair; displays new pair in ListTile
return _buildRow(_suggestions[index]);
});
}
Widget _buildRow(WordPair pair) {
// check if pair alrdy added
final alreadySaved = _saved.contains(pair);
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
trailing: Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onTap: () => {
setState(() => {
if (alreadySaved) {_saved.remove(pair)} else {_saved.add(pair)}
})
},
);
}
void _pushSaved() {
// Navigator adds "back" button to app bar, don't need to add Navigator.pop
Navigator.of(context).push(
// content for a new page
MaterialPageRoute<void>(
builder: (BuildContext context) {
// get all saved pairs and save into array (tiles)
final tiles = _saved.map(
(WordPair pair) {
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
);
},
);
// add horizontal spacing between each tile/pair
// convert to rows with "toList()"
final divided = ListTile.divideTiles(
tiles: tiles,
context: context,
).toList();
return Scaffold(
appBar: AppBar(
title: Text('Saved Suggestions'),
),
body: ListView(children: divided),
);
},
),
);
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StartUp Name Generator'),
// actions takes an array of widgets (children)
// child takes a single widget
actions: [
IconButton(icon: Icon(Icons.list), onPressed: _pushSaved),
],
),
body: _buildSuggestions(),
);
}
}
|
package client
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/nicdavies/signable-api-client/types"
"net/http"
)
func (c *Client) GetContacts(ctx context.Context, options *types.ListContactsOptions) (*types.ListContactsResponse, error) {
offset := 20
limit := 20
if options != nil {
offset = options.Offset
limit = options.Limit
}
req, err := http.NewRequest("GET", fmt.Sprintf("%s/contacts?offset=%d&limit=%d", c.BaseURL, offset, limit), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
res := types.ListContactsResponse{}
if err := c.sendRequest(req, res); err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) GetContact(ctx context.Context, options *types.ReadContactOptions) (*types.ReadContactResponse, error) {
if options == nil {
return nil, errors.New("ID is required")
}
req, err := http.NewRequest("GET", fmt.Sprintf("%s/contacts/%d", c.BaseURL, options.Id), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
res := types.ReadContactResponse{}
if err := c.sendRequest(req, res); err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) CreateContact(ctx context.Context, options *types.CreateContactsOptions) (*types.CreateContactsResponse, error) {
b, err := json.Marshal(options)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/contacts", c.BaseURL), bytes.NewBuffer(b))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
res := types.CreateContactsResponse{}
if err := c.sendRequest(req, res); err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) UpdateContact(ctx context.Context, id int, options *types.UpdateContactOptions) (*types.UpdateContactResponse, error) {
b, err := json.Marshal(options)
if err != nil {
return nil, err
}
req, err := http.NewRequest("PUT", fmt.Sprintf("%s/contacts/%d", c.BaseURL, id), bytes.NewBuffer(b))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
res := types.UpdateContactResponse{}
if err := c.sendRequest(req, res); err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) DeleteContact(ctx context.Context, options *types.DeleteContactOptions) (*types.DeleteContactResponse, error) {
req, err := http.NewRequest("PUT", fmt.Sprintf("%s/contacts/%d", c.BaseURL, options.Id), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
res := types.DeleteContactResponse{}
if err := c.sendRequest(req, res); err != nil {
return nil, err
}
return &res, nil
}
|
import NextImage, { ImageProps } from "next/image";
import { useState } from "react";
export function Image(props: ImageProps) {
const [showModal, setShowModal] = useState(false);
const { className, ...rest } = props;
return (
<>
<div>
<NextImage
className={`rounded-lg object-contain shadow-xl ${props.className}`}
onClick={() => setShowModal(true)}
{...rest}
/>
</div>
{showModal && (
<div
className="fixed left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-white bg-opacity-50 transition-all dark:bg-black dark:bg-opacity-50"
onClick={() => setShowModal(false)}
>
<div>
<NextImage
className={`relative rounded-lg shadow-xl ${props.className} max-h-[80vh] w-auto max-w-[80vw] rotate-0 object-contain`}
{...rest}
/>
</div>
</div>
)}
</>
);
}
|
import React, { createContext, useState, useEffect } from 'react';
import Web3 from 'web3';
import myContractABI from './myContractABI.json';
export const Web3Context = createContext();
export const Web3Provider = ({ children }) => {
const [web3, setWeb3] = useState(null);
const [accounts, setAccounts] = useState([]);
useEffect(() => {
const loadProvider = async () => {
if (window.ethereum) {
const web3 = new Web3(window.ethereum);
const accounts = await web3.eth.getAccounts();
setWeb3(web3);
setAccounts(accounts);
} else {
console.error("Ethereum provider not detected");
}
}
loadProvider();
}, []);
return (
<Web3Context.Provider value={{ web3, accounts }}>
{children}
</Web3Context.Provider>
);
};
|
import {useState, useEffect} from 'react';
import axios from 'axios';
export default function useFetch(url) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading_api, setLoading] = useState(false);
useEffect(() => {
(async function () {
try {
setLoading(true);
const response = await axios.get(url);
setData(response.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
}, [url]);
return {data, error, loading_api};
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Abhi's html tutorial</title>
<meta name="description" content="Abhiram B S
Javalli
Tudoor
Thirthahalli
Shivamoga
577226">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/fonts/font-awesome.min.css">
<link rel="stylesheet" href="assets/fonts/ionicons.min.css">
<link rel="stylesheet" href="assets/css/abhi.css">
<link rel="stylesheet" href="assets/css/Footer-Basic.css">
<link rel="stylesheet" href="assets/css/Newsletter-Subscription-Form.css">
<link rel="stylesheet" href="assets/css/Social-Icons.css">
</head>
<body>
<nav class="navbar navbar-light navbar-expand sticky-top bg-white shadow-lg">
<div class="container-fluid"><a class="navbar-brand" href="#">Abhiram</a><button data-toggle="collapse" class="navbar-toggler" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse" id="navcol-1">
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link active" href="index.html">Home</a></li>
<li class="nav-item"><a class="nav-link" href="about.html">About Me</a></li>
<li class="nav-item"><a class="nav-link" href="contact.html">Contact Me</a></li>
</ul>
</div>
</div>
</nav>
<div class="mt-5">
<h3 class="text-center">Chapter - 49</h3>
<h4 class="text-center">Select Tag</h4>
</div>
<div class="mt-5">
<h4>49.1. select tag :-</h4>
<p>The <select>….</select> tag creates a drop down list to accept a user input from a list of items.<br></p>
<div class="mt-5 mb-5">
<div class="table-responsive">
<table class="table">
<thead class="text-white" style="background: #000000;">
<tr>
<th><strong>Attribute</strong></th>
<th><strong>Value</strong></th>
<th><strong>Description</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>autofocus</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
<tr>
<td>disabled</td>
<td>disabled</td>
<td>Specifies that a drop-down list should be disabled<br></td>
</tr>
<tr>
<td>form</td>
<td>form_id</td>
<td>Defines one or more forms the select field belongs to<br></td>
</tr>
<tr>
<td>multiple</td>
<td>multiple</td>
<td>Specifies that multiple options can be selected at once<br></td>
</tr>
<tr>
<td>name</td>
<td>name</td>
<td>Defines a name for the drop-down list<br></td>
</tr>
<tr>
<td>required</td>
<td>required</td>
<td>Specifies that the user is required to select a value before submitting the form<br></td>
</tr>
<tr>
<td>size</td>
<td>number</td>
<td>Defines the number of visible options in a drop-down list<br></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p class="text-center mb-5"><a class="btn btn-outline-dark btn-lg text-center" role="button" href="fortyeight.html">Previous</a><a class="btn btn-outline-dark btn-lg text-center" role="button" href="fifty.html">Next</a></p>
<footer class="footer-basic">
<p class="copyright"><strong><em>prepared by Abhiram B S</em></strong></p>
</footer>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
|
import { DEFAULT_PROFILE_IMAGE } from "@env";
import { useState, useLayoutEffect } from "react";
import { Image, StyleSheet, View, TouchableOpacity, ToastAndroid } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Button } from "react-native-elements";
import { ref as rtdRef, update } from "firebase/database";
import { uploadBytes, getDownloadURL, ref } from "firebase/storage";
import * as ImagePicker from "expo-image-picker";
import { useSelector, useDispatch } from "react-redux";
import { dbRealtime } from "../../../firebase/config";
import { useFirebase } from "@contexts/FirebaseContext";
import { selectUserType } from "@store/slices/userTypeSlice";
import { setRentACarUser, selectRentACarUser } from "@store/slices/rentACarSlice";
import { setTourUser, selectTourUser } from "@store/slices/tourSlice";
import { setFreightRider, selectFreightRider } from "@store/slices/freightRiderSlice";
import KeyboardAvoidingWrapper from "@components/KeyboardAvoidingWrapper";
import ClearableInput from "@components/ClearableInput";
import { showError } from "@utils/ErrorHandlers";
const EditProfileScreen = ({ navigation }) => {
const userType = useSelector(selectUserType);
const rentACarUser = useSelector(selectRentACarUser);
const tourUser = useSelector(selectTourUser);
const freightRider = useSelector(selectFreightRider);
const dispatch = useDispatch();
const { updateUserProfile } = useFirebase();
const [photoURL, setPhotoURL] = useState(
userType === "RentACarOwner"
? rentACarUser.photoURL || ""
: userType === "ToursCompany"
? tourUser.photoURL || ""
: userType === "FreightRider" && (freightRider.photoURL || ""),
);
const [firstName, setFirstName] = useState(
userType === "RentACarOwner"
? rentACarUser.firstName || ""
: userType === "ToursCompany"
? tourUser.firstName || ""
: userType === "FreightRider" && (freightRider.firstName || ""),
);
const [lastName, setLastName] = useState(
userType === "RentACarOwner"
? rentACarUser.lastName || ""
: userType === "ToursCompany"
? tourUser.lastName || ""
: userType === "FreightRider" && (freightRider.lastName || ""),
);
const [email, setEmail] = useState(
userType === "RentACarOwner"
? rentACarUser.email || ""
: userType === "ToursCompany"
? tourUser.email || ""
: userType === "FreightRider" && (freightRider.email || ""),
);
useLayoutEffect(() => {
navigation.setOptions({
headerShown: true,
headerTitle: "Edit Profile",
headerTitleStyle: {
fontSize: 21,
fontFamily: "SatoshiBlack",
fontWeight: "400",
},
headerTitleAlign: "center",
headerStyle: {
height: 70,
},
});
}, [navigation]);
const UpdateUserInfo = (DBNode, userUID) => {
const userRef = rtdRef(dbRealtime, `${DBNode}/` + userUID);
update(userRef, {
firstName: firstName,
lastName: lastName,
email: email,
photoURL: photoURL,
})
.then(() => {
console.log("User info updated in DB");
})
.catch((error) => {
console.log("Error updating user info in DB: ", error);
});
};
const handleUpdate = async () => {
try {
ToastAndroid.show("Updating profile...", ToastAndroid.LONG);
// console.log("Uploading image...");
// console.log("photoURL:", photoURL);
const response = await fetch(photoURL);
const blob = await response.blob();
// console.log("blob:", blob._data.name);
const metadata = {
contentType: "image/jpg",
};
const snapshot = await uploadBytes(ref(storage, `ProfileImages/${user.uid}.jpg`), blob, metadata);
// console.log("Uploaded a blob or file!");
const url = await getDownloadURL(snapshot.ref);
setPhotoURL(url);
// console.log("Image URL:", url);
} catch (error) {
showError("Error updating profile!", "Please try again later.");
ToastAndroid.show("Error uploading image!", ToastAndroid.SHORT);
}
userType === "RentACarOwner"
? (dispatch(
setRentACarUser({ firstName: firstName, lastName: lastName, email: email, photoURL: photoURL }),
),
UpdateUserInfo("RentACarOwner", rentACarUser?.uid),
updateUserProfile({ firstName: firstName, lastName: lastName, email: email, photoURL: photoURL }))
: userType === "ToursCompany"
? (dispatch(setTourUser({ firstName: firstName, lastName: lastName, email: email, photoURL: photoURL })),
UpdateUserInfo("Tours", rentACarUser?.uid),
updateUserProfile({ firstName: firstName, lastName: lastName, email: email, photoURL: photoURL }))
: userType === "FreightRider" &&
(dispatch(
setFreightRider({ firstName: firstName, lastName: lastName, email: email, photoURL: photoURL }),
),
UpdateUserInfo("FreightRider", rentACarUser?.uid),
updateUserProfile({ firstName: firstName, lastName: lastName, email: email, photoURL: photoURL }));
ToastAndroid.show("Profile updated!", ToastAndroid.SHORT);
};
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 4],
quality: 1,
allowsMultipleSelection: false,
});
if (!result.canceled) {
setPhotoURL(result.assets[0].uri);
} else {
return;
}
};
return (
<KeyboardAvoidingWrapper>
<SafeAreaView style={styles.container}>
<View style={styles.content}>
<TouchableOpacity onPress={pickImage}>
<Image
source={{ uri: photoURL ? photoURL : DEFAULT_PROFILE_IMAGE }}
style={styles.profileImage}
/>
</TouchableOpacity>
<ClearableInput
label={"First Name"}
placeholder={"Enter First Name"}
value={firstName}
setValue={setFirstName}
hideInput={false}
autoComplete={"name"}
textContentType={"givenName"}
/>
<ClearableInput
label={"Last Name"}
placeholder={"Enter Last Name"}
value={lastName}
setValue={setLastName}
hideInput={false}
autoComplete={"name"}
textContentType={"familyName"}
/>
<ClearableInput
label={"Email address"}
placeholder={"Enter Email Address"}
value={email}
setValue={setEmail}
hideInput={false}
autoComplete={"email"}
textContentType={"emailAddress"}
/>
<View style={styles.buttonContainer}>
<Button
title="Update"
buttonStyle={styles.button}
titleStyle={styles.buttonText}
onPress={handleUpdate}
disabled={photoURL === "" || firstName === "" || lastName === "" || email === ""}
/>
</View>
</View>
</SafeAreaView>
</KeyboardAvoidingWrapper>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
content: {
flex: 1,
paddingTop: 15,
paddingBottom: 25,
paddingHorizontal: 15,
},
profileImage: {
height: 100,
width: 100,
borderRadius: 50,
borderColor: "#A7E92F",
borderWidth: 2,
marginBottom: 15,
alignSelf: "center",
},
inputText: {
fontSize: 15,
fontWeight: "400",
},
inputContainer: {
backgroundColor: "#E9E9E9",
borderBottomWidth: 0,
borderRadius: 8,
paddingHorizontal: 10,
paddingVertical: 2,
},
buttonContainer: {
marginTop: 120,
marginBottom: 10,
},
button: {
backgroundColor: "#A7E92F",
padding: 10,
borderRadius: 8,
marginHorizontal: 10,
},
buttonText: {
color: "#000",
fontSize: 16,
fontFamily: "SatoshiBold",
fontWeight: "600",
textAlign: "center",
},
});
export default EditProfileScreen;
|
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers')
const { expect } = require('chai')
const BigNumber = require('bignumber.js')
const { toWei, fromWei, MIN_AMOUNT } = require('./helpers')
const { deployFixture } = require('./deployFixture')
const { ethers } = require('hardhat')
// const usdtFaucet = "0xE118429D095de1a93951c67D04B523fE5cbAB62c";
// const routerAddress = "0xE592427A0AEce92De3Edee1F18E0157C05861564"; // unswap router
// const sleepToken = "0xb94d207a3fBdb312cef2e5dBEb7C22A76516BE37";
// test cases for the contract
// start order and funds transferred correctly
// upi update functions
// order status update functions
describe('Start order ', function () {
it('Initialize ', async function () {
const { accumulationContract, owner } = await loadFixture(deployFixture)
console.log('contract ', accumulationContract.address)
console.log('owner ', owner.address)
const isManager = await accumulationContract.managers(owner.address)
expect(isManager.toString()).to.equal('1')
})
it('new account can start strategy', async function () {
const { sleepContract, owner, addr1, accumulationContract, usdtContract } = await loadFixture(
deployFixture
)
await usdtContract.transfer(addr1.address, toWei('1000'))
await usdtContract.connect(addr1).approve(accumulationContract.address, toWei('1000'))
const ownerUsdtBalBefore = await usdtContract.balanceOf(owner.address)
console.log('owner balance before ', fromWei(ownerUsdtBalBefore.toString()))
const trx = await accumulationContract
.connect(addr1)
.startStrategy(sleepContract.address, toWei('10'), 5)
const userOrder = await accumulationContract.orders(1)
const count = await accumulationContract.ordersCount()
const userDeposits = await accumulationContract
.connect(addr1)
.getUserDepositBalance(addr1.address, usdtContract.address)
console.log('userDeposits ', userDeposits)
const ownerUsdtBalAfter = await usdtContract.balanceOf(owner.address)
console.log('owner balance after ', fromWei(ownerUsdtBalAfter.toString()))
console.log(
'owner bal diff',
new BigNumber(ownerUsdtBalAfter.toString()).minus(ownerUsdtBalBefore.toString()).toString()
)
console.log('order created ', userOrder)
console.log('total orders ', count)
const userOrders = await accumulationContract.getUserOrders(addr1.address, usdtContract.address)
console.log('user order ', userOrders)
const userOrders2 = await accumulationContract.getUserOrders(
owner.address,
usdtContract.address
)
console.log('user order2 ', userOrders2)
// Get the current block number
const blockNumber = await ethers.provider.getBlockNumber()
// Get the block information
const block = await ethers.provider.getBlock(blockNumber)
// Retrieve the timestamp from the block
const timestamp = block.timestamp
console.log('timestamp ', timestamp)
const filteredOrders = await accumulationContract.getPendingOrders(timestamp)
console.log('filtered orders ', filteredOrders)
})
it('multiple accounts can start strategy', async function () {
const { sleepContract, owner, addr1, addr2, addr3, addr4, accumulationContract, usdtContract } =
await loadFixture(deployFixture)
await usdtContract.transfer(addr1.address, toWei('1000'))
await usdtContract.connect(addr1).approve(accumulationContract.address, toWei('1000'))
await usdtContract.connect(addr2).approve(accumulationContract.address, toWei('1000'))
await usdtContract.connect(addr3).approve(accumulationContract.address, toWei('1000'))
await usdtContract.connect(addr4).approve(accumulationContract.address, toWei('1000'))
const ownerUsdtBalBefore = await usdtContract.balanceOf(owner.address)
console.log('owner balance before ', fromWei(ownerUsdtBalBefore.toString()))
const trx = await accumulationContract
.connect(addr1)
.startStrategy(sleepContract.address, toWei('10'), 5)
const trx2 = await accumulationContract
.connect(addr2)
.startStrategy(sleepContract.address, toWei('10'), 5)
const trx3 = await accumulationContract
.connect(addr3)
.startStrategy(sleepContract.address, toWei('10'), 5)
const trx4 = await accumulationContract
.connect(addr4)
.startStrategy(sleepContract.address, toWei('10'), 5)
const userOrder = await accumulationContract.orders(1)
const count = await accumulationContract.ordersCount()
const ownerUsdtBalAfter = await usdtContract.balanceOf(owner.address)
console.log('owner balance after ', fromWei(ownerUsdtBalAfter.toString()))
console.log(
'owner bal diff',
new BigNumber(ownerUsdtBalAfter.toString()).minus(ownerUsdtBalBefore.toString()).toString()
)
console.log('order created ', userOrder)
console.log('total orders ', count)
const userOrders = await accumulationContract.getUserOrders(addr1.address, usdtContract.address)
console.log('user order ', userOrders)
const userOrders2 = await accumulationContract.getUserOrders(
owner.address,
usdtContract.address
)
console.log('user order2 ', userOrders2)
// Get the current block number
const blockNumber = await ethers.provider.getBlockNumber()
// Get the block information
const block = await ethers.provider.getBlock(blockNumber)
// Retrieve the timestamp from the block
const timestamp = block.timestamp
console.log('timestamp ', timestamp)
const filteredOrders = await accumulationContract.getPendingOrders(timestamp)
console.log('filtered orders ', filteredOrders)
})
it('manager can update order status in batch', async function () {
const { sleepContract, owner, addr1, addr2, addr3, addr4, accumulationContract, usdtContract } =
await loadFixture(deployFixture)
await usdtContract.transfer(addr1.address, toWei('1000'))
await usdtContract.connect(addr1).approve(accumulationContract.address, toWei('1000'))
await usdtContract.connect(addr2).approve(accumulationContract.address, toWei('1000'))
await usdtContract.connect(addr3).approve(accumulationContract.address, toWei('1000'))
await usdtContract.connect(addr4).approve(accumulationContract.address, toWei('1000'))
const ownerUsdtBalBefore = await usdtContract.balanceOf(owner.address)
// console.log('owner balance before ', fromWei(ownerUsdtBalBefore.toString()))
const trx = await accumulationContract
.connect(addr1)
.startStrategy(sleepContract.address, toWei('10'), 5)
const trx2 = await accumulationContract
.connect(addr2)
.startStrategy(sleepContract.address, toWei('10'), 5)
const trx3 = await accumulationContract
.connect(addr3)
.startStrategy(sleepContract.address, toWei('10'), 5)
const trx4 = await accumulationContract
.connect(addr4)
.startStrategy(sleepContract.address, toWei('10'), 5)
const userOrder = await accumulationContract.orders(1)
const count = await accumulationContract.ordersCount()
console.log('order created ', userOrder)
console.log('total orders ', count)
const blockNumber = await ethers.provider.getBlockNumber()
// Get the block information
const block = await ethers.provider.getBlock(blockNumber)
// Retrieve the timestamp from the block
const timestamp = block.timestamp
console.log('timestamp ', timestamp)
const filteredOrders = await accumulationContract.getPendingOrders(timestamp)
console.log('filtered orders ', filteredOrders)
// execute first 2 orders once
await accumulationContract.connect(owner).updateOrderStatus([1, 3])
const filteredOrders2 = await accumulationContract.getPendingOrders(timestamp)
console.log('filtered orders after update ', filteredOrders2)
// execute first 2 orders 4 times
await accumulationContract.connect(owner).updateOrderStatus([1, 3])
await accumulationContract.connect(owner).updateOrderStatus([1, 3])
await accumulationContract.connect(owner).updateOrderStatus([1, 3])
await accumulationContract.connect(owner).updateOrderStatus([1, 3])
const filteredOrders3 = await accumulationContract.getPendingOrders(timestamp)
console.log('filtered orders after update ', filteredOrders3)
})
it('upi update functions', async function () {
const { addr1, accumulationContract } = await loadFixture(deployFixture)
const trx = await accumulationContract.connect(addr1).updateUpi('8355038184@paytm')
const updatedUpi = await accumulationContract.addressToUpi(addr1.address)
const upiAddress = await accumulationContract.upiToAddress('8355038184@paytm')
console.log('updated ', { updatedUpi, upiAddress })
expect(updatedUpi.toString()).to.equal('8355038184@paytm')
expect(upiAddress.toString()).to.equal(addr1.address)
})
})
|
//
// ResetPasswordViewModel.swift
// Ettizan_ios
//
// Created by Abdilrahman Gamal on 29/11/2023.
//
import Foundation
import SVPinView
class ResetPasswordViewModel {
var VC : ResetPasswordVC?
init(VC: ResetPasswordVC) {
self.VC = VC
setupView()
}
func resetPasswordAPI(){
SharedManager.showHUD(viewController: self.VC!)
let route = APIRouter.resetPassword(email: self.VC?.email ?? "",
new_password: VC?.txtNewPassword.text ?? "",
new_password_confirmation: VC?.txtNewPassword.text ?? "",
code: self.VC?.pinView.getPin() ?? "")
APIClient.performRequest(route: route) { (response:ResetPasswordModel?, error: Error?) in
SharedManager.dismissHUD(viewController: self.VC!)
if error == nil && response != nil{
Alert.showPopAlert(title: "Login", message: response?.responseMessage ?? "")
}else{
Alert.ShowErrorMessage(message: error?.localizedDescription ?? "")
}
}
}
func resendCodeAPI(){
SharedManager.showHUD(viewController: self.VC!)
APIClient.performRequest(route: APIRouter.forgetPassword(email: VC?.email ?? "")) { (response:ForgetPasswordModel?, error: Error?) in
SharedManager.dismissHUD(viewController: self.VC!)
if error == nil && response != nil{
Alert.showPopAlert(title: "Login", message: response?.responseMessage ?? "")
}else{
Alert.ShowErrorMessage(message: error?.localizedDescription ?? "")
}
}
}
}
extension ResetPasswordViewModel {
func setupView(){
VC?.lblEmail.text = VC?.email
if let pinView = VC?.pinView {
pinView.becomeFirstResponderAtIndex = 0
pinView.pinLength = 4
pinView.interSpace = 20
pinView.textColor = "#161B30".color_
pinView.shouldSecureText = false
pinView.style = .box
pinView.contentMode = .left
pinView.fieldCornerRadius = 6
pinView.activeFieldCornerRadius = 6
pinView.borderLineThickness = 0
pinView.activeBorderLineThickness = 0
pinView.tintColor = "#22C1D3".color_
pinView.fieldBackgroundColor = .white
pinView.activeFieldBackgroundColor = .white
pinView.font = UIFont.getFont(fontSize: 20)
pinView.keyboardType = .asciiCapableNumberPad
pinView.keyboardAppearance = .default
pinView.placeholder = " "
//pinView.placeholder = "-"
pinView.isContentTypeOneTimeCode = true
// self.pinView.didFinishCallback = { pin in
// self.btnVerfiy(self)
// }
}
}
func validation() -> Bool {
if VC?.pinView.getPin().isValidateValue == false {
Alert.ShowErrorMessage(message: "TextFeildValidation".localized(with: "Code".localized))
return false
}
if VC?.txtNewPassword.isValidateValue == false {
Alert.ShowErrorMessage(message: "TextFeildValidation".localized(with: VC?.txtNewPassword.txtLocalize ?? ""))
return false
}
if VC?.txtNewPassword.text?.count ?? 7 < 6 {
Alert.ShowErrorMessage(message: "PasswordValidation".localized)
return false
}
if VC?.txtConfirmPassword.isValidateValue == false {
Alert.ShowErrorMessage(message: "TextFeildValidation".localized(with: VC?.txtConfirmPassword.txtLocalize ?? ""))
return false
}
if VC?.txtNewPassword.text != VC?.txtConfirmPassword.text {
Alert.ShowErrorMessage(message: "InvalidPassword".localized)
return false
}
return true
}
}
|
<div>
<p class="note"><b>Loops</b> are used to execute a code block
many times.</p>
<h2>Syntax</h2>
<textarea class="tutorial-example">while condition:
# Code fragment to execute.</textarea>
<h2>Example</h2>
<p>A loop can be used to print all numbers in certain range. Like from 1 to 10</p>
<textarea class="tutorial-example numeric-rows">num = 1;
while num <= 10:
print(num);
num += 1;</textarea>
<p>Output:</p>
<textarea class="tutorial-example text-only">1
2
3
4
5
6
7
8
9
10</textarea>
<p>At <code>line 3</code> the condition of the loop is set. Since <code>num</code> is less than 10 the
loop executes.</p>
<p>In order to print the numbers to 10, <code>num</code> increases by 1 at <code>line 5</code>.</p>
<p>The loop ends when <code>num</code> reaches value of 11.</p>
<h2>Infinite Loop</h2>
<p class="note">Infinite Loop has a condition that's always true.</p>
<p>It can be created due to development mistake or used in advanced algorithm.</p>
<p>Here are examples:</p>
<textarea class="tutorial-example numeric-rows">num = 1;
while num < 5:
print(num);</textarea>
<p>Output:</p>
<textarea class="tutorial-example">1
1
1
1
1
...</textarea>
<p>Since <code>num</code> is never changed, the condition <code>num < 5</code> is always True
and the loop executes infinitely (or until the program takes more ram than it is allowed).</p>
<p>In order to end the loop <code>num</code> needs to be incremented (like <code>num += 1</code>) inside the loop's body.</p>
<textarea class="tutorial-example numeric-rows">num = 1;
while True:
print("infinite");</textarea>
<p>Output:</p>
<textarea class="tutorial-example">infinite
infinite
infinite
infinite
...</textarea>
<p>Since the condition at <code>line 3</code> is always <code>True</code>, the loop keeps on repeating.</p>
</div>
|
import React, {SyntheticEvent, useState} from 'react';
import './styles.registerModule.css'
import {useNavigate} from "react-router-dom";
function RegisterForm() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
confirmPassword: '',
});
const navigate = useNavigate();
const [error, setError] = useState('');
const [successMessage, setSuccessMessage] = useState('');
const handleChange = (event: { target: { name: any; value: any; }; }) => {
setFormData({
...formData,
[event.target.name]: event.target.value
});
}
const handleSubmit = async (e: SyntheticEvent) => {
e.preventDefault();
if (!formData.username || !formData.email || !formData.confirmPassword || !formData.password) {
setError('Prosze wypełnić wszystkie pola!');
} else {
if (formData.password !== formData.confirmPassword) {
setError('Hasła nie są takie same');
} else {
setError('');
const response = await fetch('http://localhost:5000/api/auth/register', {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: JSON.stringify({
email: formData.email,
password: formData.password,
username: formData.username,
}),
});
if (response.ok) {
setSuccessMessage('Rejestracja przebiegła pomyślnie.');
setTimeout(()=> navigate('/login'), 1000 );
} else {
const error = await response.json();
setError(error.message);
}
}
}
};
return (
<form onSubmit={handleSubmit}>
<h2>Rejestracja</h2>
<label>
Nazwa użytkownika:
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</label>
<label>
Adres e-mail:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<label>
Hasło:
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
</label>
<label>
Potwierdź hasło:
<input
type="password"
name="confirmPassword"
value={formData.confirmPassword}
onChange={handleChange}
/>
</label>
{successMessage && <div>{successMessage}</div>}
{error && <p className="error-message">{error}</p>}
<input type="submit" value="Zarejestruj"/>
</form>
);
}
export default RegisterForm;
|
const express = require('express');
const usersList = [
{
firstname: 'Jack',
lastname: 'Parsons',
username: 'jackparsons',
},
{
firstname: 'Carl',
lastname: 'Sagan',
username: 'carlsagan',
},
{
firstname: 'Dan',
lastname: 'Cooper',
username: 'dancooper',
},
];
const app = express();
app.use('/users', (req, res, next) => {
let strData = '<ul>';
for (let i = 0; i < usersList.length; i++) {
const user = usersList[i];
strData += `<li>${user.firstname} ${user.lastname}</li>`;
}
strData += '</ul>';
res.send(strData);
next();
});
app.use('/create-user', (req, res, next) => {
let formData =
'<html><body><form action="/create-user" method="POST"><input type="text" name="username"></input><input type="submit"></input></form></body></html>';
const method = req.method;
if (method === 'POST') {
const body = [];
req.on('data', (data) => {
body.push(data);
});
req.on('end', function () {
const data = new Buffer.concat(body).toString();
const username = data.split('=')[1];
console.log(username);
});
}
res.send(formData);
next();
});
app.use('/', (req, res, next) => {
res.send('<h2>Hello from my server app!</h2>');
next();
});
app.listen(3000);
|
<# Written By: Scott Barning
Simple script to copy files / folders from one location to another with notifications via the BurnToast powershell module.
https://github.com/Windos/BurntToast
#>
<#
.SYNOPSIS
https://github.com/Windos/BurntToast
Simple script to copy files / folders from one location to another with notifications via the BurnToast powershell module.
.PARAMETER SourceFolder
[String]
.PARAMETER DestFolder
[String]
.EXAMPLE
Copy-WithNotification -SourceFolder C:\blah -DestFolder D:\blah
.NOTES
Written by: Scott Barning
Date: 1/4/2024
#>
param (
[string]$SourceFolder,
[string]$DestFolder
)
#Make sure we have the burnttoast module available.
try {
Import-Module -Name BurntToast | Out-Null
Write-Output "Module Imported."
}
catch {
Write-Output "BurntToast module is not installed, installing."
Install-Module -name BurntToast -allowClobber
Import-Module -Name BurntToast | Out-Null
Write-Output "Module Imported."
}
try {
Copy-Item -Path "$SourceFolder\*" -Destination $DestFolder -Recurse -ErrorAction stop
New-BurntToastNotification -Text "File copy completed succesfully."
}
catch {
New-BurntToastNotification -Text "Error with file copy, please contact IT."
}
|
<template>
<view class="search-container">
<view class="search-box">
<uni-search-bar class="uni-mt-10" radius="100" placeholder="搜索" clearButton="auto" cancelButton="none"
@confirm="search" @input="input" />
</view>
<view class="goods-list" v-if="searchValue">
<view class="goods-item" v-for="(item,index) in queryResult" :key="index">
<view class="search-icon">
<uni-icons type="search" size="18"></uni-icons>
</view>
<view class="goods-name">
{{item.goods_name}}
</view>
</view>
</view>
<view class="history" v-show="historys&&historys.length !== 0">
<view class="history-box-head">
<view class="text">
搜索历史
</view>
<uni-icons type="trash" size="17" @click="cleanHistory"></uni-icons>
</view>
<view class="history-list">
<uni-tag :text="item" class="history-item" @click="navigatorToHistory(item)"
v-for="(item,index) in historys" :key="index"
custom-style="background-color: #ccc; border-color: #ccc; color:#272822;font-weight: 500;">
</uni-tag>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
timer: null,
searchValue: '',
queryResult: [],
tempHistory: [],
test: [],
}
},
computed: {
//页面用的翻转过的历史记录
historys() {
return this.tempHistory.length === 0 ? [] : [...this.tempHistory].reverse();
}
},
methods: {
input(e) {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.searchValue = e;
this._getSeacherList();
this._addAndSaveHistory(e);
}, 1000)
},
//历史记录的转跳
navigatorToHistory(queryValue) {
uni.navigateTo({
url: `/subpkg/goods_list/goods_list?query=${queryValue}`
})
},
//添加并保存历史记录
_addAndSaveHistory(key) {
if (key === "") return;
const historySet = new Set(this.tempHistory);
historySet.delete(key);
historySet.add(key);
this.tempHistory = Array.from(historySet);
uni.setStorageSync('historyList', JSON.stringify(this.tempHistory));
},
//清空搜索历史
cleanHistory() {
this.tempHistory.splice(0, this.tempHistory.length);
uni.setStorageSync('historyList', '[]');
},
//ajax抓取搜索推荐
async _getSeacherList() {
if (this.searchValue !== '') {
const result = await uni._request({
url: 'https://api-hmugo-web.itheima.net/api/public/v1/goods/search',
method: 'GET',
data: {
query: this.searchValue
}
})
if (result !== null) {
this.queryResult = result.message.goods;
}
}
}
},
onLoad() {
this.tempHistory = JSON.parse(uni.getStorageSync('historyList') || '[]')
}
}
</script>
<style lang="scss">
.search-box {
position: relative;
height: 50px;
background-color: #E1251B;
.search-ipt {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
width: 88%;
height: 70%;
}
}
.goods-item {
display: flex;
flex-direction: row;
border-bottom: 1px solid #ccc;
height: 80rpx;
margin: 10rpx 0;
line-height: 80rpx;
.search-icon {
margin: 0 34rpx;
}
.goods-name {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin-right: 50rpx;
}
}
.history-box-head {
height: 80rpx;
line-height: 80rpx;
margin: 0 30rpx;
font-size: 12px;
display: flex;
justify-content: space-between;
border-bottom: 1px solid #ccc;
}
.history-list {
display: flex;
flex-wrap: wrap;
.history-item {
margin: 20rpx;
}
}
</style>
|
import React from 'react';
import { View, StyleSheet, TextInput, Dimensions } from 'react-native';
import { useTheme } from '@react-navigation/native';
import IconS from 'react-native-vector-icons/SimpleLineIcons';
import Fonts from '../constnats/Fonts';
const wHeight = Dimensions.get('window').height;
const wWidth = Dimensions.get('window').width;
const Input = (props) => {
const Colors = useTheme().colors;
return (
<View>
<View style={styles(Colors).inputView}>
<IconS
name={props.iconName}
color={Colors.fontColor}
size={20}
style={styles(Colors).icon}
/>
<TextInput
placeholder={props.name}
placeholderTextColor={Colors.fontColor}
style={styles(Colors).input}
value={props.value}
onChangeText={props.onChangeText}
secureTextEntry={props.pwd ? props.pwd : false}
autoCapitalize={props.emailCap && props.emailCap}
/>
{props.children}
</View>
</View>
);
};
const styles = (Colors) => StyleSheet.create({
inputView: {
marginTop: wHeight * 0.01,
paddingHorizontal: wWidth * 0.03,
borderColor: Colors.borderColor,
borderWidth: 3,
borderRadius: 10,
flexDirection: 'row',
alignItems: 'center',
marginBottom: wHeight * 0.01,
paddingBottom: wHeight * 0.005
},
icon: {
textAlign: 'center',
},
input: {
marginLeft: wWidth * 0.05,
marginRight: wWidth * 0.03,
fontFamily: Fonts.bodyFont,
color: Colors.fontColor,
width: wWidth * 0.55,
paddingVertical: wHeight * 0.015
},
});
export default Input;
|
#include "part1.h"
#include <algorithm>
#include <cmath>
#include <fmt/core.h>
#include <iostream>
#include <limits>
#include <queue>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <boost/functional/hash.hpp>
#include "utils.h"
using pair_unordered_set = std::unordered_set<std::pair<size_t, size_t>,
boost::hash<std::pair<size_t, size_t>>>;
enum class direction : int
{
to_top, to_bottom, to_left, to_right
};
const static std::unordered_map<char, std::unordered_set<direction>> pipe_dirs{
{'S', {direction::to_top, direction::to_bottom,
direction::to_left, direction::to_right}},
{'|', {direction::to_top, direction::to_bottom}},
{'-', {direction::to_left, direction::to_right}},
{'L', {direction::to_top, direction::to_right}},
{'J', {direction::to_top, direction::to_left}},
{'7', {direction::to_bottom, direction::to_left}},
{'F', {direction::to_bottom, direction::to_right}},
};
const static std::unordered_map<direction, std::unordered_set<char>> next_pipes{
{direction::to_top, {'|', '7', 'F'}},
{direction::to_bottom, {'|', 'J', 'L'}},
{direction::to_left, {'-', 'F', 'L'}},
{direction::to_right, {'-', '7', 'J'}},
};
static void measure(const std::vector<std::string>& lines)
{
auto pos = [&]() {
for (auto i = 0uz; i < lines.size(); ++i) {
for (auto j = 0uz; j < lines[i].size(); ++j) {
if (lines[i][j] == 'S')
return std::make_pair(i, j);
}
}
return std::make_pair(-1uz, -1uz);
}();
auto matrix = [&]() {
auto matrix = std::vector<std::vector<size_t>>(lines.size());
for(auto& dist : matrix)
dist = std::vector<size_t>(lines.front().size());
return matrix;
}();
auto visited = pair_unordered_set();
auto bfs_que = std::queue<std::pair<size_t, size_t>>();
bfs_que.push(pos);
visited.insert(pos);
while (!bfs_que.empty()) {
auto [cur_x, cur_y] = bfs_que.front();
bfs_que.pop();
auto cur_pipe = lines[cur_x][cur_y];
const auto& valid_to = pipe_dirs.at(cur_pipe);
// (x - 1, y)
// (x, y - 1) (x, y + 1)
// (x + 1, y)
for (auto i = -1; i < 2; ++i) {
for (auto j = -1; j < 2; ++j) {
// get only top -> left -> right -> bottom neighbors in this order
if (i == j || std::abs(i - j) > 1)
continue;
auto next_pos = std::make_pair(cur_x + i, cur_y + j);
auto [next_x, next_y] = next_pos;
if (next_x >= lines.size() || next_y >= lines[next_x].size()
|| lines[next_x][next_y] == '.')
continue;
auto to_dir = [i, j]() {
if (!i)
return (j == -1) ? direction::to_left : direction::to_right;
if (!j)
return (i == -1) ? direction::to_top : direction::to_bottom;
throw std::invalid_argument("invalid delta values.");
}();
if (!valid_to.count(to_dir)
|| !next_pipes.at(to_dir).count(lines[next_x][next_y])
|| !visited.insert(next_pos).second)
continue;
matrix[next_x][next_y] = matrix[cur_x][cur_y] + 1;
bfs_que.push(next_pos);
}
}
}
auto max = [&matrix]() {
auto max = 0uz;
for(const auto& row : matrix) {
for(auto n : row) {
max = std::max(max, n);
}
}
return max;
}();
fmt::println("max: {}", max);
}
void solve_part1(std::ifstream& input)
{
auto lines = getlines(input);
measure(lines);
}
|
import { api } from "@/data/api";
import { defineStore } from "pinia";
import type {
ContractRequest,
ContractResponse,
ExpandedMilestoneResponse,
} from "@/data/api/client";
import router from "@/router";
import { formatDate } from "@/utils";
export const useContractStore = defineStore({
id: "contract",
state: () => ({
contracts: [] as Array<ContractResponse>,
contractCurrent: {} as ContractResponse,
milestoneCurrent: {} as ExpandedMilestoneResponse,
}),
getters: {
getContracts: (state) =>
state.contracts.map((contract: ContractResponse) => {
return {
uuid: contract.uuid,
name: contract.name,
value:
contract.goodsValue?.amount?.toLocaleString("en-US", {
style: "decimal",
maximumFractionDigits: 2,
minimumFractionDigits: 2,
}) +
" " +
contract.goodsValue?.unit || 0,
customer: contract.customerDetails?.name || "",
dateCreated: formatDate(contract.creationDate),
completionPercentage: contract.completionPercentage,
};
}),
getCurrentContract: (state) => {
return {
...state.contractCurrent,
goodsQuantity: state.contractCurrent.goodsQuantity?.toLocaleString(),
shipmentWeightKg:
state.contractCurrent.shipmentWeightKg?.toLocaleString(),
goodsValue: {
amount: state.contractCurrent.goodsValue?.amount?.toLocaleString(
"en-US",
{
style: "decimal",
maximumFractionDigits: 2,
minimumFractionDigits: 2,
}
),
unit: state.contractCurrent.goodsValue?.unit,
},
milestones: state.contractCurrent.milestones?.map((milestone: any) => {
return {
...milestone,
details: {
...milestone.details,
amount: {
amount:
milestone.details.amount?.amount.toLocaleString("en-US", {
style: "decimal",
maximumFractionDigits: 2,
minimumFractionDigits: 2,
}) || 0,
unit: milestone.details.amount?.unit,
},
},
};
}),
};
},
getCurrentMilestone: (state) => {
return {
...state.milestoneCurrent,
milestoneDetails: {
...state.milestoneCurrent.milestoneDetails,
offerAmount: {
amount:
state.milestoneCurrent.milestoneDetails?.offerAmount?.amount?.toLocaleString(
"en-US",
{
style: "decimal",
maximumFractionDigits: 2,
minimumFractionDigits: 2,
}
) || 0,
unit: state.milestoneCurrent.milestoneDetails?.offerAmount?.unit,
},
amount: {
amount:
state.milestoneCurrent.milestoneDetails?.amount?.amount?.toLocaleString(
"en-US",
{
style: "decimal",
maximumFractionDigits: 2,
minimumFractionDigits: 2,
}
) || 0,
unit: state.milestoneCurrent.milestoneDetails?.amount?.unit,
},
},
};
},
},
actions: {
async loadContracts() {
try {
const { contracts } = await api.contract.getContracts();
this.contracts = contracts || [];
} catch (err) {
console.error(err, "error");
return [];
}
},
async getContract(uuid: string) {
try {
this.contractCurrent = await api.contract.getContract(uuid);
} catch (err) {
console.error(err, "error");
return [];
}
},
async getContractMilestone(contractUuid: string, milestoneUuid: string) {
try {
this.milestoneCurrent = await api.contract.getMilestone(
contractUuid,
milestoneUuid
);
} catch (err) {
console.error(err, "error");
return [];
}
},
async completeMilestone(contractUuid: string, milestoneUuid: string) {
await api.contract.closeMilestone(contractUuid, milestoneUuid);
await this.getContract(contractUuid);
},
async signContract(uuid: string) {
await api.contract.signContract(uuid);
await this.getContract(uuid);
},
async addContract(requestBody: ContractRequest) {
const contractNew = await api.contract.createContract(requestBody);
await router.push(`/contract/${contractNew.uuid}`);
},
async updateOfferPriceMilestone(
contractUuid: string,
milestoneUuid: string,
amount: number,
unit: string
) {
await api.contract.updateOfferPriceMilestone(
contractUuid,
milestoneUuid,
{ offerPrice: { amount: amount, unit: unit } }
);
await this.getContractMilestone(contractUuid, milestoneUuid);
},
},
});
|
<%= render 'layouts/public_header' %>
<div class="container col-sm-7">
<%= render 'layouts/errors' ,obj: @post %>
<%= form_with model:@post,local:true do |f| %>
<div class="row mt-3 mb-3">
<%= f.label :ブランド, class: "col-sm-2 control-label" %>
<%= f.collection_select :brand_id, Brand.all, :id, :name,{prompt: "選択してください"},class: "form-control text-muted" %>
</div>
<div class="row mb-3">
<%= f.label :商品名, class: "col-sm-2 control-label" %>
<%= f.collection_select :item_id, Item.all, :id, :name,{prompt: "選択してください"},class: "form-control text-muted" %>
</div>
<!--評価-->
<div class="row mb-3">
<p class="col-1">評価</p>
<div id="star"></div>
<!--評価javascript-->
<script>
// 星部分を一度削除
$('#star<%= @post.id %>').empty();
$('#star').raty({
size :36,
starOff: '<%= asset_path('star-off.png')%>',
starOn: '<%= asset_path('star-on.png')%>',
starHalf: '<%= asset_path('star-half.png')%>',
scoreName: 'post[rate]',
half: true,
// 前回の評価を読み込み
score: <%= @post.rate %>,
});
</script>
</div>
<div class="row mb-3">
<%= f.label :画像, class: "col-sm-1 control-label" %>
<%= f.attachment_field :image, class: "col-sm-11" %>
</div>
<div class="row mb-3">
<%= f.label :タイトル, class: "col-sm-2 control-label" %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="row mb-3">
<%= f.label :メリット, class: "col-sm-2 control-label" %>
<%= f.text_area :merit, class: "form-control" %>
</div>
<div class="row mb-3">
<%= f.label :デメリット, class: "col-sm-2 control-label" %>
<%= f.text_area :demerit, class: "form-control" %>
</div>
<div class="row mb-3">
<%= f.label :使い心地, class: "col-sm-2 control-label" %>
<%= f.text_area :usability, class: "form-control" %>
</div>
<div class="row mb-3">
<%= f.label :コスパ, class: "col-sm-2 control-label" %>
<%= f.text_area :cost_performance, class: "form-control" %>
</div>
<div class="row mb-3">
<%= f.label :商品のパターン(色), class: "col-sm-3 control-label" %>
<%= f.text_field :pattern, class: "form-control" %>
</div>
<div class="row mb-3">
<%= f.label :もっと伝えたい!, class: "col-sm-3 control-label" %>
<%= f.text_area :other, placeholder: "ご自由にお書きください", class: "form-control" %>
</div>
<div class="row pb-3">
<%= f.label :タグ, class: "col-sm-2 control-label" %>
<%= f.text_field :tag_list,value: @post.tag_list.join(','), placeholder: "かわいい,コスパ(カンマで区切って複数登録できます)",class: "form-control" %>
</div>
<div class="row mt-4 mb-4">
<div class="col text-right">
<%= f.submit :class=>"btn btn-info" %>
</div>
</div>
<% end %>
</div>
|
using eTheaters.Data.Base;
using eTheaters.Data.ViewModels;
using eTheaters.Models;
using Microsoft.EntityFrameworkCore;
using System.IO;
namespace eTheaters.Data.Services
{
public class PlaysService : EntityBaseRepository<Play>, IPlaysService
{
private readonly AppDbContext _context;
public PlaysService(AppDbContext context) : base(context)
{
_context = context;
}
public async Task AddNewPlayAsync(NewPlayVM data)
{
var newPlay = new Play()
{
Name = data.Name,
Description = data.Description,
Price = data.Price,
ImageURL = data.ImageURL,
TheaterId = data.TheaterId,
StartDate = data.StartDate,
EndDate = data.EndDate,
PlayCategory = data.PlayCategory,
DirectorId = data.DirectorId
};
await _context.Plays.AddAsync(newPlay);
await _context.SaveChangesAsync();
//Add play actors
foreach(var actorId in data.ActorIds)
{
var newActorPlay = new Actor_Play()
{
PlayId = newPlay.Id,
ActorId = actorId
};
await _context.Actors_Plays.AddAsync(newActorPlay);
}
await _context.SaveChangesAsync();
}
public async Task<NewPlayDropdownsVM> GetNewPlayDropdownsValues()
{
var response = new NewPlayDropdownsVM()
{
Actors = await _context.Actors.OrderBy(n => n.FullName).ToListAsync(),
Theaters = await _context.Theaters.OrderBy(n => n.Name).ToListAsync(),
Directors = await _context.Directors.OrderBy(n => n.FullName).ToListAsync()
};
return response;
}
public async Task<Play> GetPlayByIdAsync(int id)
{
var playDetails = await _context.Plays
.Include(c => c.Theater)
.Include(d => d.Director)
.Include(ap => ap.Actors_Plays).ThenInclude(a => a.Actor)
.FirstOrDefaultAsync(n => n.Id == id);
return playDetails;
}
public async Task UpdatePlayAsync(NewPlayVM data)
{
var dbPlay = await _context.Plays.FirstOrDefaultAsync(n => n.Id == data.Id);
if (dbPlay != null)
{
dbPlay.Name = data.Name;
dbPlay.Description = data.Description;
dbPlay.Price = data.Price;
dbPlay.ImageURL = data.ImageURL;
dbPlay.TheaterId = data.TheaterId;
dbPlay.StartDate = data.StartDate;
dbPlay.EndDate = data.EndDate;
dbPlay.PlayCategory = data.PlayCategory;
dbPlay.DirectorId = data.DirectorId;
await _context.SaveChangesAsync();
}
var existingActorsDb = _context.Actors_Plays.Where(n => n.PlayId == data.Id).ToList();
_context.Actors_Plays.RemoveRange(existingActorsDb);
await _context.SaveChangesAsync();
//Add play actors
foreach (var actorId in data.ActorIds)
{
var newActorPlay = new Actor_Play()
{
PlayId = data.Id,
ActorId = actorId
};
await _context.Actors_Plays.AddAsync(newActorPlay);
}
await _context.SaveChangesAsync();
}
}
}
|
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page import="java.sql.*"%>
<%@ include file="../conn.jsp"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/Styles/CSS/style.css" />
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/Styles/CSS/user.css" />
<script
src="${pageContext.request.contextPath}/Styles/Javascript/includeHTML.js"></script>
<script
src="${pageContext.request.contextPath}/Styles/Javascript/pageBasket.js"></script>
<script
src="${pageContext.request.contextPath}/Styles/Javascript/basket.js"
defer></script>
<script
src="${pageContext.request.contextPath}/Styles/Javascript/basket_price.js"
defer></script>
<title>장바구니 목록</title>
</head>
<body>
<div id="wrapper">
<header>
<jsp:include page="../Main/header.jsp" />
</header>
<nav>
<jsp:include page="../Main/nav.jsp" />
</nav>
<main>
<div id="mypage_center">
<div class="mypage_list">
<ul>
<li><a href="./basket.jsp"><strong>내 장바구니</strong></a></li>
<li><a href="./edit.jsp">회원정보수정</a></li>
<li><a href="./withdraw.jsp">회원탈퇴</a></li>
</ul>
</div>
<div class="mypage_introduction">
<div class="basket_list">
<div class="basket_title">내 장바구니</div>
<p>장바구니에 담긴 상품 목록입니다.</p>
<div class="basket_tables">
<table class="basket_table">
<thead>
<tr>
<th></th>
<th class="basket_num">주문번호</th>
<th class="basket_name">상품명</th>
<th>가격</th>
<th>수량</th>
<th>총가격</th>
</tr>
</thead>
<!-- HTML 코드 일부분 -->
<tbody>
<%
HttpSession session1 = request.getSession();
String userid = (String) session1.getAttribute("username");
try {
String selectQuery = "SELECT * FROM cart where mid = ? ";
PreparedStatement preparedStatement = conn.prepareStatement(selectQuery);
preparedStatement.setString(1, userid);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int cartNumber = resultSet.getInt("cno");
int productNumber = resultSet.getInt("pno");
String productName = resultSet.getString("pname");
String memberId = resultSet.getString("mid");
int productPrice = resultSet.getInt("pprice");
int productQuantity = resultSet.getInt("cquantity");
String productPriceWon = String.format("%,d 원", productPrice);
int basketTotal = productPrice * productQuantity;
%>
<tr class="t_tr">
<th><input type="checkbox" class="cartCheckBox"
value="<%=productNumber%>" /></th>
<td><%=cartNumber%></td>
<td class="basket_proName"><input type="text"
id="productname" name="productname" value="<%=productName%>"
required readonly /></td>
<td class="basket_proPrice"><input type="text"
class="productpriceR"
id="productprice"
value="" required readonly /></td>
<input type="hidden"
class="productprice"
name="productprice"
value="<%=productPrice%>"/>
<td><input
type="number"
class="basket_quantity"
id="cquantity"
name="productQuantity"
value="<%=productQuantity%>"
min="1"
max="1000"
data-product-quantity="<%=productNumber%>"
/></td>
<td><input type="text" class="baksetTotal"
id="baskettotal" value="" readonly /></td>
</tr>
<%
}
resultSet.close();
preparedStatement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</tbody>
</table>
</div>
<div id="pagination-container"></div>
</div>
<div class="basket_result">
<div class="result" id="totalPrice">총 주문금액 :</div>
</div>
<div class="basket_btns">
<form method="post"
action="baskettotal.jsp">
<input type="hidden" id="ctotalprice" name="ctotalprice" value="">
<button class="basket_btn" type="submit">상품주문하기</button>
</form>
<form action="cartdelete.jsp" method="post">
<input type="hidden" value="" id="productNum" name="productNum" />
<button class="basket_btn" type="submit">상품삭제</button>
</form>
<form action="basketupdate.jsp" method="post">
<input type="hidden" id="productNumber" name="productNumber" value="" />
<input type="hidden" id="productQuantity-return" name="productQuantity" value="" />
<button id="product-complete" class="basket_edit_btn">수량변경하기</button>
</form>
</div>
</div>
</div>
</main>
<footer>
<jsp:include page="../Main/footer.jsp" />
</footer>
</div>
</body>
<script>
includeHTML()
updateOverallTotal();
document.addEventListener('DOMContentLoaded', function() {
// 수량 변경 버튼 클릭 시
document.querySelectorAll('.basket_edit_btn').forEach(function(btn) {
btn.addEventListener('click', function() {
// 현재 클릭한 버튼의 부모 요소에서 productNumber 가져오기
var productNumber = this.closest('tr').querySelector('.cartCheckBox').value;
var productQuantity = this.closest('tr').querySelector('.basket_quantity').value;
// 폼에 productNumber와 productQuantity 설정
document.querySelector('#productNumber').value = productNumber;
document.querySelector('#productQuantity-return').value = productQuantity;
// 폼 제출
document.querySelector('form[action="basketupdate.jsp"]').submit();
});
});
});
</script>
</html>
|
import React, { useState } from 'react'
import { useRouter } from 'next/router';
import { useNotes } from '../../store/store';
import { MdDone, MdEdit } from 'react-icons/md';
import { WhiteCircle_border } from '../WhiteCircle/WhiteCircle_border';
export const NoteEditor = ({ note, folder }: { note: any, folder: any }) => {
const router = useRouter();
const [edit, setEdit] = useState(false)
const [value, setValue] = useState('')
const changeNoteData = useNotes((state) => state.changeNoteDate)
function startEdit() {
setEdit(!edit)
setValue(note.data)
}
function doneEdit() {
setEdit(!edit)
note.data = value
changeNoteData(note, `https://638f1f119cbdb0dbe31da265.mockapi.io/folders/${folder.id}/notes/${note.id}`, `https://638f1f119cbdb0dbe31da265.mockapi.io/folders/${folder.id}/notes/`)
router.replace(router.asPath);
}
return (
<div className='flex-50 flex flex-col'>
<div className=' border-b-2 border-whale-white'>
<div className='flex justify-between p-[20px] items-center'>
<div className='text-whale-bowhead'>
{note.name}
</div>
{edit
?
<WhiteCircle_border icon={<MdDone />} color={'green'} callback={() => doneEdit()} />
:
<WhiteCircle_border icon={<MdEdit />} callback={() => startEdit()} />
}
</div>
</div>
{edit
?
<textarea className='outline-none min-h-[150px] resize-none p-[20px]' placeholder='Note text...' value={value} onChange={(event) => setValue(event?.target.value)} />
: <div className='text-whale-bowhead p-[20px]'>
{note.data}
</div>
}
</div>
)
}
|
import { HOME_PATH } from '@/data';
import { usePathNameLocale } from '@/hooks/use-pathname-locale';
import { LogoutOutlined } from '@ant-design/icons';
import { PageContainer, ProCard, ProConfigProvider, ProLayout } from '@ant-design/pro-components';
import { ConfigProvider, Dropdown } from 'antd';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { PropsWithChildren } from 'react';
import { config } from './_defaultProps';
export const MainLayout = ({ children }: PropsWithChildren) => {
const router = useRouter();
const pathname = usePathNameLocale();
if (typeof document === 'undefined') {
return <div />;
}
return (
<div
id="test-pro-layout"
style={{
height: '100vh',
overflow: 'auto',
}}
>
<ProConfigProvider hashed={false}>
<ConfigProvider
getTargetContainer={() => {
return document.getElementById('test-pro-layout') || document.body;
}}
>
<ProLayout
{...config}
fixSiderbar={true}
layout="mix"
splitMenus={false}
navTheme="light"
prefixCls="my-prefix"
location={{ pathname }}
token={{ header: { colorBgMenuItemSelected: 'rgba(0,0,0,0.04)' } }}
siderMenuType="group"
menu={{ collapsedShowGroupTitle: true }}
title="Antd Admin"
headerTitleRender={(logo, title, __) => {
return (
<Link href={HOME_PATH}>
{logo}
{title}
</Link>
);
}}
logo={undefined}
avatarProps={{
src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
size: 'small',
title: 'User',
render: (_, dom) => {
return (
<Dropdown
menu={{
items: [
{
key: 'logout',
icon: <LogoutOutlined />,
label: 'Sign out',
},
],
}}
>
{dom}
</Dropdown>
);
},
}}
menuFooterRender={(props) => {
if (props?.collapsed) return undefined;
return (
<div
style={{
textAlign: 'center',
paddingBlockStart: 12,
}}
>
<div>by Antd Admin</div>
</div>
);
}}
menuItemRender={(item, dom) => (
<div
onClick={() => {
item.path && router.push(item.path);
}}
>
{dom}
</div>
)}
bgLayoutImgList={[
{
src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
left: 85,
bottom: 100,
height: '303px',
},
{
src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
bottom: -68,
right: -45,
height: '303px',
},
{
src: 'https://img.alicdn.com/imgextra/i3/O1CN018NxReL1shX85Yz6Cx_!!6000000005798-2-tps-884-496.png',
bottom: 0,
left: 0,
width: '331px',
},
]}
>
<PageContainer
token={{
paddingInlinePageContainerContent: 16,
paddingBlockPageContainerContent: 16,
}}
>
<ProCard
style={{
height: '200vh',
minHeight: 800,
}}
>
{children}
</ProCard>
</PageContainer>
</ProLayout>
</ConfigProvider>
</ProConfigProvider>
</div>
);
};
export default MainLayout;
|
/*
Copyright (c) 2024 Rhys Bryant
serialspark 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.
serialspark 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 serialspark. If not, see <https://www.gnu.org/licenses/>.
*/
export interface Network {
securityType: string
name: string
psk?: string
signalInfo?: string
supportedSecurityTypes?: string[]
}
export enum NetworkType {
Client, AP
}
export class WiFiSettings {
#baseURL: string
constructor(url: string) {
this.#baseURL = url;
}
/**
* runs a wifi scan on the server
* @returns list of found wifi networks
*/
async WifiScan() {
return new Promise<Network[]>((resolve, reject) => {
fetch(this.#baseURL + "/wifi/scan").then(result => {
if (result.ok) {
result.json().then(obj => {
resolve(obj as Network[])
}).catch(reason => reject(reason));
}
}).catch(reason => reject(reason));
})
}
/**
*
* @returns the currently configured network on the server
*/
async getSavedNetwork(networkType?: NetworkType) {
return new Promise<Map<string, Network>>((resolve, reject) => {
fetch(this.#baseURL + "/wifi").then(result => {
if (result.ok) {
result.json().then(obj => {
resolve(obj)
}).catch(reason => reject(reason));
}
}).catch(reason => reject(reason));
})
}
/**
* set the network for the server to connect to
* @param network
* @returns
*/
async setSavedNetwork(networkType: NetworkType, network: Network) {
return new Promise<void>((resolve, reject) => {
const key = networkType == NetworkType.AP ? "ap" : "sta";
fetch(this.#baseURL + "/wifi", { method: "PUT", body: JSON.stringify({ [key]: network }) }).then(result => {
if (result.ok) {
result.json().then(val => {
if (!val[key]) {
reject("unexpected response");
return;
}
const { success, message } = val[key];
if(!success){
reject(message||"wifi config update failed");
}else{
resolve();
}
}).catch(reason => reject(reason))
}
}).catch(reason => reject(reason));
})
}
}
|
using DataModel;
using DBProcessing;
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
namespace InitialImport
{
// this part contains methods for importing data (using updating or inserting commands)
internal partial class Program
{
private static void ExecuteImport()
{
Console.WriteLine("Importing data ... \n");
// all file paths are in app.config
bool res = ImportProducts(fileName: ConfigurationManager.AppSettings["products"]);
if (res)
{
Console.WriteLine("Products: success.\n");
res = ImportPricing(fileName: ConfigurationManager.AppSettings["Pricing"]);
}
if (res)
{
Console.WriteLine("Pricing: success.\n");
res = ImportStock(fileName: ConfigurationManager.AppSettings["Stock"]);
}
if (res)
{
Console.WriteLine("Stock: success.\n");
}
}
private static void ExecuteUpdating()
{
Console.WriteLine("Updating data ... ");
// all file paths are in app.config
bool res = UpdatePricing(fileName: ConfigurationManager.AppSettings["price_update"]);
if (res)
{
Console.WriteLine("Pricing: success.\n");
res = UpdateStock(fileName: ConfigurationManager.AppSettings["stock_update"]);
}
if (res)
{
Console.WriteLine("Stock: success.\n");
}
}
private static bool ImportStock(string fileName)
{
if (!File.Exists(fileName))
{
Console.WriteLine($"File ({fileName}) has not been found. Import of Stock file was canceled.\n");
return false;
}
var stockImporter = new CsvImporter<ProductStock>(err);
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["eStarTest"]?.ToString()))
stockImporter.InsertFromCsv(fileName, cn);
}
catch (Exception ex)
{
Console.WriteLine($"Stock import was canceled due to errors.\n{ex.Message}\n");
return false;
}
return true;
}
private static bool ImportPricing(string fileName)
{
if (!File.Exists(fileName))
{
Console.WriteLine($"File ({fileName}) has not been found. Import of Pricing file was canceled.\n");
return false;
}
var priceImporter = new CsvImporter<ProductPrice>(err);
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["eStarTest"]?.ToString()))
priceImporter.InsertFromCsv(fileName, cn);
}
catch (Exception ex)
{
Console.WriteLine($"Pricing import was canceled due to errors.\n{ex.Message}\n");
return false;
}
return true;
}
private static bool ImportProducts(string fileName)
{
if (!File.Exists(fileName))
{
Console.WriteLine($"File ({fileName}) has not been found. Products import was canceled.\n");
return false;
}
var productImporter = new CsvImporter<Product>(err);
productImporter.ValidationActions.Add(product => // check format of SKU before inserting into db
{
string skuPattern = @"^[A-Z]{2}-[A-Z0-9]{4}(-[A-Z0-9]{1,2})?$";
bool res = Regex.IsMatch(product.SKU, skuPattern);
return (res, res ? "" : $"Incorrect value of SKU '{product.SKU}' was detected. Line is ignored.");
});
productImporter.TransformActions.Add(product => // set value of StyleCode es per the requirement Step-1/4a
{
var skuParts = product.SKU.Split('-');
if (skuParts.Length >= 2)
{
product.StyleCode = $"{skuParts[0]}-{skuParts[1]}";
}
});
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["eStarTest"]?.ToString()))
productImporter.InsertFromCsv(fileName, cn);
}
catch (Exception ex)
{
Console.WriteLine($"Products import was canceled due to errors.\n{ex.Message}\n");
return false;
}
return true;
}
private static bool UpdatePricing(string fileName)
{
if (!File.Exists(fileName))
{
Console.WriteLine($"File ({fileName}) has not been found. Updating of Pricing was canceled.\n");
return false;
}
var priceImporter = new CsvImporter<ProductPrice>(err);
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["eStarTest"]?.ToString()))
priceImporter.UpdateFromCsv(fileName, cn);
}
catch (Exception ex)
{
Console.WriteLine($"Pricing update was canceled due to errors.\n{ex.Message}\n");
return false;
}
return true;
}
private static bool UpdateStock(string fileName)
{
if (!File.Exists(fileName))
{
Console.WriteLine($"File ({fileName}) has not been found. Updating of Stock was canceled.\n");
return false;
}
var stockImporter = new CsvImporter<ProductStock>(err);
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["eStarTest"]?.ToString()))
stockImporter.UpdateFromCsv(fileName, cn);
}
catch (Exception ex)
{
Console.WriteLine($"Stock update was canceled due to errors.\n{ex.Message}\n");
return false;
}
return true;
}
}
}
|
import React from 'react';
import './Card1.css';
import Image from 'next/image';
import img from './img/stockPrices.svg';
import CounterComponent from './CounterCom';
import Marquee from './Marquee';
import dynamic from "next/dynamic";
import FadeUp from './FadeUp';
function Card1() {
return (
<section style={{backgroundColor: 'white', justifyContent: 'center', overflow: 'hidden'}} id="card1" >
<div className="header">
<div className="aux-container" >
<div className="header-body" >
<div className="header-text">
<div>
<FadeUp>
<h1 className="title">
Ignite Your Ability to Learn and Absorb
</h1>
</FadeUp>
<FadeUp>
<p className='subtitle'>
Investing is an art. Let Bonsai Finance be your trusted companion on this artistic journey.
</p>
</FadeUp>
<div className="buttons">
<FadeUp>
<a href="/analysis" className="inner-btn inner-btn-primary" style={{color: 'white'}}>
Start today
</a>
<a href="#About" className="inner-btn inner-btn-secondary">
More about us
</a>
</FadeUp>
</div>
<div className="stats">
<FadeUp>
<div>
<CounterComponent targetNumber={1200}></CounterComponent>
<p>Stocks Accessible</p>
</div>
</FadeUp>
<div className="line"></div>
<FadeUp>
<div>
<CounterComponent targetNumber={600}></CounterComponent>
<p>Users-To-Date</p>
</div>
</FadeUp>
</div>
</div>
</div>
<div className="banner">
<FadeUp>
<Image src={img} alt="banner"/>
</FadeUp>
</div>
</div>
</div>
</div>
</section>
)
}
export default dynamic (() => Promise.resolve(Card1), {ssr: false})
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package client
import (
"context"
"fmt"
"log"
"github.com/google/uuid"
"github.com/GoogleCloudPlatform/retail-data-model/events/grpc"
"github.com/GoogleCloudPlatform/retail-data-model/events/pb"
"github.com/GoogleCloudPlatform/retail-data-model/events/pkg/model"
grpcCore "google.golang.org/grpc"
)
func appendTrait(ctx context.Context, event *pb.Event, key string) {
// Add the trace id if present
v := ctx.Value(key)
if v != nil {
event.Traits = append(
event.GetTraits(), model.NewEventTrait(KeyTraceId, fmt.Sprintf("%s", v)))
}
}
func PrepareEvent(ctx context.Context, event *pb.Event) {
if event != nil {
appendTrait(ctx, event, KeyTraceId)
appendTrait(ctx, event, KeyParentId)
appendTrait(ctx, event, KeyTraceFlags)
if len(event.EventId) == 0 {
id, _ := uuid.NewRandom()
event.EventId = id.String()
}
// Set the parent id to the event id if nil
if len(event.EventParentId) == 0 {
event.EventParentId = event.EventId
}
}
}
func Emit(ctx context.Context,
client grpc.EventsClient,
callback Callable,
events ...*pb.Event) error {
var opts []grpcCore.CallOption
stream, err := client.Emit(ctx, opts...)
if err != nil {
return err
}
for _, event := range events {
tE := event
PrepareEvent(ctx, tE)
if err := stream.Send(tE); err != nil {
log.Default().Printf("failed to send event, %s, with error: %v", tE.EventId, err)
}
}
// Once send is complete, wait for all responses, these may trigger
// latch open events
closeErr := stream.CloseSend()
if closeErr != nil {
log.Default().Printf("Error closing the send stream: %v", closeErr)
}
<-callback.GetWaitChannel()
return nil
}
|
import { Dispatch, SetStateAction, createContext } from "react";
import { Employee } from "@/db/models";
import { Moment } from "moment";
type EmployeesContext = {
employees: Employee[];
employeeId: number | null | undefined;
setEmployeeId: Dispatch<SetStateAction<number | null | undefined>>;
};
type VisitsFilterContext = {
startDate: Moment | null;
endDate: Moment | null;
setStartDate: Dispatch<SetStateAction<Moment | null>>;
setEndDate: Dispatch<SetStateAction<Moment | null>>;
};
type TravelFormContext = EmployeesContext & VisitsFilterContext;
export const TravelFormContext = createContext<TravelFormContext | null>(null);
|
import { expect, spy, use } from 'chai';
import Engine from '@civ-clone/core-engine/Engine';
import FillGenerator from '@civ-clone/simple-world-generator/tests/lib/FillGenerator';
import Player from '@civ-clone/core-player/Player';
import PlayerWorld from '@civ-clone/core-player-world/PlayerWorld';
import RuleRegistry from '@civ-clone/core-rule/RuleRegistry';
import World from '@civ-clone/core-world/World';
import visibilityChanged from '../Rules/Player/visibility-changed';
import { describe } from 'mocha';
import * as spies from 'chai-spies';
import Unit from '@civ-clone/core-unit/Unit';
import { unitYield } from '@civ-clone/core-unit/Rules/Yield';
import visibility from '../Rules/Unit/visibility';
import { PlayerWorldRegistry } from '@civ-clone/core-player-world/PlayerWorldRegistry';
use(spies);
describe('Player.visibility-changed', () => {
it('should trigger an event', async (): Promise<void> => {
const ruleRegistry = new RuleRegistry(),
playerWorldRegistry = new PlayerWorldRegistry(),
world = await new World(new FillGenerator(5, 5)).build(ruleRegistry),
tile = world.get(1, 1),
player = new Player(ruleRegistry),
unit = new Unit(null, player, tile, ruleRegistry),
playerWorld = new PlayerWorld(player, world, ruleRegistry),
engine = new Engine();
spy.on(engine, ['emit']);
ruleRegistry.register(
...visibility(playerWorldRegistry),
...visibilityChanged(engine),
...unitYield(Unit, 1, 1, 1, 1)
);
playerWorldRegistry.register(playerWorld);
unit.applyVisibility();
expect(playerWorld.entries()).length(9);
tile.getSurroundingArea(1).forEach((tile, i) =>
expect(engine.emit)
.nth(i + 1)
.called.with.exactly(
'player:visibility-changed',
tile,
playerWorld.player()
)
);
});
});
|
// import { useState } from 'react'
import { useQuery } from "react-query";
import { fetchAllTips } from "./helpers/fetchAllTips";
import TipReview from "./TipReview";
import SearchBar from "./SearchBar";
import TipHeader from "./TipHeader";
import { useEffect, useReducer, useState } from "react";
function App() {
let { data, status } = useQuery("tips", fetchAllTips);
const [filteredData, setFilteredData] = useState(null);
const filtrationReducer = (state, action) => {
switch (action.type) {
case "Location":
return { ...state, location: action.payload };
case "StartDate":
return { ...state, startDate: action.payload };
case "EndDate":
return { ...state, endDate: action.payload };
case "StartTime":
return { ...state, startTime: action.payload };
case "EndTime":
return { ...state, endTime: action.payload };
case "MinTotal":
return { ...state, minTotal: action.payload };
case "MaxTotal":
return { ...state, maxTotal: action.payload };
default:
return { ...state };
}
};
const [filtration, dispatch] = useReducer(filtrationReducer, {
location: "",
startDate: "",
endDate: "",
startTime: "",
endTime: "",
minTotal: "",
maxTotal: "",
});
const handleSubmit = (e) => {
e.preventDefault();
if (
new Date(filtration.endDate).getTime() <
new Date(filtration.startDate).getTime() ||
Number(filtration.minTotal) > Number(filtration.maxTotal) ||
filtration.startTime > filtration.endTime
) return false;
console.log(filtration);
// new request with use query
// set filtered data
setFilteredData('')
return true;
};
return (
<>
{status === "error" && <p>Error fetching data</p>}
{status === "loading" && <p>Fetching data...</p>}
<div className="max-h-screen grid grid-flow-row-dense">
<SearchBar filtration={filtration} dispatch={dispatch} handleSubmit={handleSubmit}/>
<div className="bg-primary-800 p-4 w-3/4 mx-auto grid grid-flow-row gap-3 rounded-xl">
{status === "success" && (
<>
<h2 className="text-center text-3xl font-semibold mb-2">
Displaying All {data.length} Results
</h2>
<TipHeader headers={["Location", "Date", "Total", "Breakdown"]} />
<div className="max-h-[28rem] overflow-scroll grid grid-flow-row gap-3">
{!filteredData ? data.map((d, idx) => (
<TipReview {...d} key={idx} />
)) : filteredData.map((d, idx) => (
<TipReview {...d} key={idx} />
))}
</div>
</>
)}
</div>
</div>
</>
);
}
export default App;
|
import asyncio
import os
from typing import Any
from unittest import IsolatedAsyncioTestCase
from unittest.mock import AsyncMock
from telegram.ext import ConversationHandler
from tests.utils.common import create_test_db
from tests.utils.ptb_app import TEST_PERSISTENCE_NAME, make_app
class AsyncResultCacheMock(AsyncMock):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._result_cache = []
async def __call__(self, *args: Any, **kwargs: Any) -> Any:
call_result = super().__call__(*args, **kwargs)
if asyncio.iscoroutine(call_result):
result = await call_result
else:
result = call_result
self._result_cache.append(result)
return result
@property
def result_cache(self):
return self._result_cache
class AsyncDBTestCase(IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
db_path, conn = await create_test_db()
self.conn = conn
self.bot_data = {
'db_conn': conn,
'db_path': db_path,
}
return await super().asyncSetUp()
async def asyncTearDown(self) -> None:
await self.conn.close()
return await super().asyncTearDown()
class AsyncTelegramBotTestCase(AsyncDBTestCase):
_handlers = []
async def asyncSetUp(self) -> None:
await super().asyncSetUp()
self.app = make_app()
self.app.add_handlers(self._handlers)
self.app.bot_data.update(self.bot_data)
self.app.bot._unfreeze()
await self.app.initialize()
async def asyncTearDown(self) -> None:
await self.app.shutdown()
for handler in self._handlers:
if isinstance(handler, ConversationHandler):
handler._conversations.clear()
if os.path.isfile(TEST_PERSISTENCE_NAME):
os.remove(TEST_PERSISTENCE_NAME)
return await super().asyncTearDown()
|
---
title: applicationTemplate 资源类型
description: 表示 Azure AD 应用程序库中的应用程序
localization_priority: Normal
author: luleonpla
ms.prod: applications
doc_type: resourcePageType
ms.openlocfilehash: ea677a986691be79b19437a53407e46d4eb65214
ms.sourcegitcommit: be09568fa07ab793cd1db500f537ca94ca9e5b4a
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 04/15/2021
ms.locfileid: "51836890"
---
# <a name="applicationtemplate-resource-type"></a>applicationTemplate 资源类型
命名空间:microsoft.graph
[!INCLUDE [beta-disclaimer](../../includes/beta-disclaimer.md)]
表示 Azure [AD 应用程序库中的应用程序](/azure/active-directory/saas-apps/tutorial-list)。
## <a name="methods"></a>方法
| 方法 | 返回类型 | 说明 |
|:-------------|:------------|:------------|
|[列出 applicationTemplate](../api/applicationtemplate-list.md)|[applicationTemplate](applicationtemplate.md)|检索 applicationTemplate 对象的列表。|
| [获取 applicationTemplate](../api/applicationtemplate-get.md) | [applicationTemplate](applicationtemplate.md) | 读取 applicationTemplate 对象的属性和关系。 |
|[实例化 applicationTemplate](../api/applicationtemplate-instantiate.md)|[applicationServicePrincipal](applicationserviceprincipal.md)| 将 Azure AD 应用程序库中的应用程序实例添加到目录中。|
## <a name="properties"></a>属性
| 属性 | 类型 | 说明 |
|:-------------|:------------|:------------|
|categories|String 集合|应用程序的类别列表。 支持的值可以是:、 `Collaboration` `Business Management` `Consumer` `Content management` `CRM` `Data services` `Developer services` `E-commerce` `Education` `ERP` `Finance` `Health` `Human resources` `IT infrastructure` `Mail` 和 `Management` `Marketing` `Media` `Productivity` `Project management` `Telecommunications` `Tools` `Travel` `Web design & hosting` 。|
|说明|String|应用程序的说明。|
|displayName|String|应用程序名。|
|homePageUrl|String|应用程序的主页 URL。|
|id|String| 应用程序的唯一标识符。 只读。|
|logoUrl|String|获取此应用程序徽标的 URL。|
|发布者|String|此应用程序的发布者的名称。|
|supportedProvisioningTypes|String 集合|此应用程序支持的预配模式列表。 唯一有效的值为 `sync` 。|
|supportedSingleSignOnModes|String 集合|此应用程序支持的单一登录模式列表。 支持的值是:`oidc`、`password`、`saml` 和 `notSupported`。|
## <a name="relationships"></a>关系
无。
## <a name="json-representation"></a>JSON 表示形式
下面是资源的 JSON 表示形式。
<!-- {
"blockType": "resource",
"optionalProperties": [
],
"@odata.type": "microsoft.graph.applicationTemplate",
"keyProperty": "id"
}-->
```json
{
"id" : "id-value",
"displayName" : "displayName-value",
"homePageUrl" : "homePageUrl-value",
"supportedSingleSignOnModes" : ["supportedSingleSignOnModes-value"],
"logoUrl" : "logoUrl-value",
"categories" : ["categories-value"],
"publisher" : "publisher-value",
"description" : "description-value"
}
```
<!-- uuid: 16cd6b66-4b1a-43a1-adaf-3a886856ed98
2019-02-04 14:57:30 UTC -->
<!-- {
"type": "#page.annotation",
"description": "applicationTemplate resource",
"keywords": "",
"section": "documentation",
"tocPath": ""
}-->
|
Aqui está um programa em Python que atende aos requisitos do exercício:
```python
def media_ponderada(notas, pesos):
"""
Calcula a média ponderada de um conjunto de notas.
Args:
notas: Uma lista de notas.
pesos: Uma lista de pesos para as notas.
Returns:
A média ponderada das notas.
"""
soma = 0
for i in range(len(notas)):
soma += notas[i] * pesos[i]
return round(soma / sum(pesos), 1)
def main():
"""
Programa principal.
"""
notas = [float(input("Nota 1: ")),
float(input("Nota 2: ")),
float(input("Nota 3: ")),
float(input("Nota 4: "))]
pesos = [1, 2, 3, 4]
media = media_ponderada(notas, pesos)
print(f"Média ponderada: {media}")
if __name__ == "__main__":
main()
```
Este programa funciona da seguinte forma:
* A função `media_ponderada()` recebe como entrada duas listas: uma lista de notas e uma lista de pesos. A função calcula a média ponderada das notas, multiplicando cada nota pelo seu respectivo peso e somando os resultados. O resultado é dividido pela soma dos pesos.
* A função `main()` lê as quatro notas do aluno do usuário. Em seguida, ela chama a função `media_ponderada()` para calcular a média ponderada das notas. Por fim, a função imprime a média ponderada.
Aqui está um exemplo de execução do programa:
```
Nota 1: 0.0
Nota 2: 0.0
Nota 3: 9.0
Nota 4: 10.0
Média ponderada: 6.7
```
Neste caso, a média ponderada é calculada da seguinte forma:
```
(0.0 * 1) + (0.0 * 2) + (9.0 * 3) + (10.0 * 4) / (1 + 2 + 3 + 4) = 6.7
```
O resultado é arredondado para uma casa decimal, resultando em 6.7.
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not postorder:
return None
root = TreeNode(postorder[-1])
# 叶子节点
if len(postorder)==1:
return root
for i in range(len(inorder)):
if inorder[i]==root.val:
break
in_left = inorder[:i]
in_right = inorder[i+1:]
post_left = postorder[:len(in_left)]
post_right = post_right[len(in_left):-1]
root.left = self.buildTree(in_left, post_left)
root.right = self.buildTree(in_right, post_right)
return root
solution = Solution()
solution.buildTree(inorder=[9,3,15,20,7], postorder=[9,15,7,20,3])
|
// 从中序与后序遍历序列构造二叉树
/*
分析一下时间,空间复杂度
中序和后序的数组长度都是一样的都是n
构建n的tree节点,
空间复杂度是o(n)
时间复杂度也是o(n),因为要遍历每个节点
*/
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function buildTree(inorder: number[], postorder: number[]): TreeNode | null {
function recur(left1: number, right1: number, left2: number, right2: number): TreeNode | null {
if (left2 > right2) {
return null;
}
let root = new TreeNode(postorder[right2]);
/*
left1 中序的起点
right1 中序的终点
left2 后序的起点
right2 后序的终点
*/
let mid = left1;
while (inorder[mid] !== root.val) {
mid++;
}
// left1~mid-1 左子树中序 mid+1~right1 右子树中序
// left2~m 左子树后序,这个m,就是left2 + (mid - 1 - left1),一个区间是r-l
// k~right2-1 右子树后序,这个K由刚刚计算的左子树后序的m+1就是了
root.left = recur(left1, mid - 1, left2, left2 + mid - left1 - 1);
root.right = recur(mid + 1, right1, left2 + mid - left1, right2 - 1);
return root;
}
const head = recur(0, inorder.length - 1, 0, postorder.length - 1);
return head;
};
|
package theInternet;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SelectOption {
WebDriver driver;
@BeforeClass
public void beforeClass(){
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
@Test
void SelectOption(){
driver.get("https://the-internet.herokuapp.com/dropdown");
WebElement ddown= driver.findElement(By.id("dropdown"));
Select select = new Select(ddown);
// select.selectByValue("1");
select.selectByVisibleText("Option 2");
String selectedOption = select.getFirstSelectedOption().getText();
Assert.assertEquals(selectedOption, "Option 2", "Option 1 is not selected");
sleepInSecond(5);
// select.selectByIndex(1);
}
@AfterClass
public void afterClass() {
// System.setProperty("webdriver.chrome.driver", "C:\\browserdrivers\\chromedriver.exe");
////ss
driver.close();
}
public void sleepInSecond(long timeoutInSecond) {
try {
Thread.sleep(timeoutInSecond * 1000);
} catch (InterruptedException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package leetcode.mergeKSortedLists_0023;
public class ParseUtils {
public static ListNode[] parseInput(String input) {
// Remove brackets and split by commas
String substring = input.substring(1, input.length() - 1);
String[] elements = substring.split("\\],\\[");
ListNode[] result = new ListNode[elements.length];
for (int i = 0; i < elements.length; i++) {
String element = elements[i].replaceAll("\\]", "").replaceAll("\\[", "");
result[i] = parseListNode(element);
}
return result;
}
private static ListNode parseListNode(String element) {
// If element is empty, return null
if (element.isEmpty()) {
return null;
}
// Split by commas and parse integers
String[] values = element.split(",");
ListNode head = new ListNode(Integer.parseInt(values[0]));
ListNode current = head;
// Create the linked list
for (int i = 1; i < values.length; i++) {
current.next = new ListNode(Integer.parseInt(values[i]));
current = current.next;
}
return head;
}
}
|
import React, { useState } from 'react'
import { FaBars, FaTimes, FaGithub, FaLinkedin } from 'react-icons/fa'
import { HiOutlineMail } from 'react-icons/hi'
import { BsFillPersonLinesFill } from 'react-icons/bs'
import osp from '../assets/o_santos.pdf'
import Image from '../assets/O.png'
import { Link } from 'react-scroll'
const Navbar = () => {
const [nav, setNav] = useState(false)
const handleClick = () => setNav(!nav)
return (
<div className='fixed w-full h-[80px] flex justify-between items-center px-4 bg-[#383839] text-gray-300'>
<div className='w-[100px] h-[100px] text-4xl text-[#d242ec] font-serif font-bold'>
<img src={Image} alt="" />
</div>
{/* menu */}
<ul className='hidden md:flex text-2xl'>
<li className='hover:text-[#f78d42]'>
<Link to="home" smooth={true} duration={500} >
Home
</Link>
</li>
<li className='hover:text-[#f78d42]'>
<Link to="about" smooth={true} duration={500} >
About
</Link>
</li>
<li className='hover:text-[#f78d42]'>
<Link to="skills" smooth={true} duration={500} >
Skills
</Link>
</li>
<li className='hover:text-[#f78d42]'>
<Link to='projects' smooth={true} duration={500}>
Projects
</Link>
</li>
<li className='hover:text-[#f78d42]'>
<Link to="contact" smooth={true} duration={500} >
Contact
</Link>
</li>
</ul>
{/* hamburger */}
<div onClick={handleClick} className='md:hidden z-10'>
{!nav ? <FaBars /> : <FaTimes />}
</div>
{/* middle menu */}
<ul className={!nav ? 'hidden' : 'absolute top-0 left-0 w-full h-screen bg-[#1c3d6d] flex flex-col justify-center items-center'}>
<li className='py-6 text-4xl'>
<Link onClick={handleClick} to="home" smooth={true} duration={500} >
Home
</Link>
</li>
<li className='py-6 text-4xl'>
<Link onClick={handleClick} to="about" smooth={true} duration={500} >
About
</Link>
</li>
<li className='py-6 text-4xl'>
<Link onClick={handleClick} to="skills" smooth={true} duration={500} >
Skills
</Link>
</li>
<li className='py-6 text-4xl'>
<Link onClick={handleClick} to='projects' smooth={true} duration={500}>
Projects
</Link>
</li>
<li className='py-6 text-4xl'>
<Link onClick={handleClick} to="contact" smooth={true} duration={500} >
Contact
</Link>
</li>
</ul>
{/* social icons */}
<div className='hidden lg:flex fixed flex-col top-[35%] left-0'>
<ul>
<li className='w-[160px] h-[50px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-blue-600'>
<a className='flex justify-between items-center w-full text-gray-200' href="https://www.linkedin.com/in/oscar-santos-perez/" target='_blank'>
Linkedin <FaLinkedin size={30}/>
</a>
</li>
<br />
<li className='w-[160px] h-[50px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-[#333333]'>
<a className='flex justify-between items-center w-full text-gray-200' href="https://github.com/Oscar-Santos" target='_blank'>
Github <FaGithub size={30}/>
</a>
</li>
<br />
<li className='w-[160px] h-[50px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-red-500'>
<a className='flex justify-between items-center w-full text-gray-200' href="mailto:oscar303data@gmail.com">
Email <HiOutlineMail size={30}/>
</a>
</li>
<br />
<li className='w-[160px] h-[60px] flex justify-between items-center ml-[-100px] hover:ml-[-10px] duration-300 bg-[#565f69]'>
<a
className='flex justify-between items-center w-full text-gray-200'
href={osp}
target='_blank'
rel='noopener noreferrer'
>
Resume <BsFillPersonLinesFill size={30} />
</a>
</li>
</ul>
</div>
</div>
)
}
export default Navbar
|
import io.qameta.allure.Epic;
import io.qameta.allure.Feature;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Класс для тестирования валидных данных при создании резюме со свойствами
* <b>deleteResume</b>, <b>deleteResumeAccept</b>, <b>driver</b>,
* <b>makeResumeNow</b>, <b>loginNow</b>,
* <b>timeForPause</b> и <b>myChrDriPath</b>.
* @author Набиев Азамат Ильдусович
* @version 1.2
*/
@RunWith(Parameterized.class)
public class MakeResumeTest {
public By deleteResume = By.xpath("//button[@data-qa='resume-delete']");
public By deleteResumeAccept = By.xpath("//button[text()='Удалить']");
public WebDriver driver;
public ForPageObjects makeResumeNow;
public int timeForPause;
@Parameterized.Parameter
public String firstName;
@Parameterized.Parameter(1)
public String LastName;
@Parameterized.Parameter(2)
public String city;
@Parameterized.Parameter(3)
public Integer day;
@Parameterized.Parameter(4)
public String month;
@Parameterized.Parameter(5)
public Integer year;
@Parameterized.Parameter(6)
public String sex;
@Parameterized.Parameter(7)
public String jobExp;
@Parameterized.Parameter(8)
public Boolean expected;
@Before
public void start() throws IOException, ParseException {
System.setProperty("webdriver.chrome.driver", (new File("src\\main\\resources\\chromedriver_win32\\chromedriver.exe").getAbsolutePath()));
driver = new ChromeDriver();
driver.manage().window().maximize();
makeResumeNow = new ForPageObjects(driver);
makeResumeNow.loginAs();
timeForPause = 8;
}
@After
public void end() {
try {
driver.findElement(deleteResume).click();
driver.findElement(deleteResumeAccept).click();
} catch(NoSuchElementException e) {
}
driver.quit();
}
@Epic(value = "Тесты на ввод данных при создании резюме")
@Feature(value = "Тест с валидными данными")
@Test
public void checkValidDataTest(){
makeResumeNow.doIt(firstName, LastName, city, day, month, year, sex, jobExp);
Boolean actual = driver.findElements(makeResumeNow.necessaryFieldErr).size() > 0;
makeResumeNow.submitPushResume();
waitTime(timeForPause);
Assert.assertTrue("Резюме не было создано, были допущены ошибки." +
" Удалите резюме с названием 'Начинающий специалист' и попробуйте снова.",actual == expected);
}
@Parameterized.Parameters(name = "firstName = {0} | LastName = {1}" +
" |city = {2} |day = {3} |month = {4}" +
" |year = {5}| sex = {6} | jobExp = {7}| expected = {8}")
public static List<Object[]> dataProvider() {
return Arrays.asList(new Object[][] {
{"Иван", "Иванов", "Омск", 21, "09", 1996, "Мужской", "Нет опыта работы", false}
});
}
@Ignore
public static void waitTime(Integer sec) {
try {
Thread.sleep(sec * 1000);
} catch (InterruptedException e) {
}
}
}
|
import type { Meta, StoryObj } from '@storybook/react';
import { CalendarDays } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '../avatar';
import { Button } from '../button';
import { HoverCard, HoverCardContent, HoverCardTrigger } from '../hovercard';
function HoverCardDemo() {
return (
<HoverCard>
<HoverCardTrigger asChild>
<Button
variant='link'
className='text-foreground'
>
@Coderum.dev
</Button>
</HoverCardTrigger>
<HoverCardContent
className='w-80'
align='center'
>
<div className='flex justify-between space-x-4'>
<Avatar>
<AvatarImage src='https://github.com/vercel.png' />
<AvatarFallback>VC</AvatarFallback>
</Avatar>
<div className='space-y-1'>
<h4 className='text-sm font-semibold'>@Coderum.dev</h4>
<p className='text-sm'>A blogging platform for coders – created and maintained by @Coderum.dev.</p>
<div className='flex items-center pt-2'>
<CalendarDays className='mr-2 h-4 w-4 opacity-70' />{' '}
<span className='text-muted-foreground text-xs'>Joined December 2024</span>
</div>
</div>
</div>
</HoverCardContent>
</HoverCard>
);
}
const meta = {
title: 'Coderum/HoverCard',
component: HoverCardDemo,
parameters: {
layout: 'centered',
},
} satisfies Meta<typeof HoverCardDemo>;
export default meta;
type Story = StoryObj<typeof meta>;
export const HoverCardExample: Story = {};
|
package com.expertsvision.erp.core.language.dao;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.expertsvision.erp.core.language.dto.LanguageViewFilter;
import com.expertsvision.erp.core.language.entity.Language;
import com.expertsvision.erp.core.language.entity.LanguageView;
import com.expertsvision.erp.core.utils.GenerateSql;
import com.expertsvision.erp.core.utils.MultiplePages;
import com.expertsvision.erp.core.utils.SinglePage;
@Repository
public class LanguageDAOImpl implements LanguageDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<LanguageView> getLanguageViewList() {
Session session = sessionFactory.getCurrentSession();
String sql = "SELECT * FROM language_view";
Query<LanguageView> query = session.createNativeQuery(sql, LanguageView.class);
List<LanguageView> languageViewList = query.getResultList();
return languageViewList;
}
@Override
public LanguageView getLanguageView(Integer langNo) {
Session session = sessionFactory.getCurrentSession();
String sql = "SELECT * FROM language_view WHERE lang_no = :langNo";
Query<LanguageView> query = session.createNativeQuery(sql, LanguageView.class);
query.setParameter("langNo", langNo);
List<LanguageView> languageViewList = query.getResultList();
return languageViewList.isEmpty()? null : languageViewList.get(0);
}
@Override
public SinglePage<LanguageView> getLanguagesViewSinglePage(long pageNo) {
Session session = sessionFactory.getCurrentSession();
String sql = null;
List<LanguageView> languageViewList =null;
if (pageNo > 0) {
sql = "SELECT * FROM language_view LIMIT 1 OFFSET :Offset";
Query<LanguageView> query = session.createNativeQuery(sql, LanguageView.class);
query.setParameter("Offset", pageNo - 1);
languageViewList = query.getResultList();
}
if (pageNo <= 0 || languageViewList.isEmpty()) {
sql = "SELECT COUNT(*) FROM language";
@SuppressWarnings("unchecked")
Query<BigInteger> query2 = session.createNativeQuery(sql);
long count = query2.getSingleResult().longValue();
return new SinglePage<LanguageView>(null, pageNo, count);
} else {
return new SinglePage<LanguageView>(languageViewList.get(0), pageNo, null);
}
}
@Override
public SinglePage<LanguageView> getLanguagesViewLastPage() {
Session session = sessionFactory.getCurrentSession();
String sql = "SELECT * FROM language_view ORDER BY(lang_no) DESC LIMIT 1";
Query<LanguageView> query = session.createNativeQuery(sql, LanguageView.class);
List<LanguageView> messagesViewList = query.getResultList();
sql = "SELECT COUNT(*) FROM language";
@SuppressWarnings("unchecked")
Query<BigInteger> query2 = session.createNativeQuery(sql);
long count = query2.getSingleResult().longValue();
if (messagesViewList.isEmpty()) {
return new SinglePage<LanguageView>(null, count, count);
} else {
return new SinglePage<LanguageView>(messagesViewList.get(0), count, count);
}
}
@Override
public Long getLanguageViewSinglePageNo(Integer langNo) {
Session session = sessionFactory.getCurrentSession();
String sql = "SELECT row_number FROM" +
" (SELECT lang_no, ROW_NUMBER()" +
" OVER(ORDER BY (lang_no)) FROM language)" +
" AS row_number " +
"WHERE lang_no = :langNo";
@SuppressWarnings("unchecked")
Query<BigInteger> query = session.createNativeQuery(sql);
query.setParameter("langNo", langNo);
List<BigInteger> singlePageNoList = query.getResultList();
return singlePageNoList.isEmpty() ? null : singlePageNoList.get(0).longValue();
}
@Override
public MultiplePages<LanguageView> getLanguagesViewMultiplePages(long pageNo) {
Session session = sessionFactory.getCurrentSession();
String sql = null;
List<LanguageView> languageViewList = null;
if (pageNo > 0) {
sql = "SELECT * FROM language_view LIMIT 30 OFFSET :Offset";
Query<LanguageView> query = session.createNativeQuery(sql, LanguageView.class);
query.setParameter("Offset", (pageNo - 1) * 30);
languageViewList = query.getResultList();
}
sql = "SELECT COUNT(*) FROM language";
@SuppressWarnings("unchecked")
Query<BigInteger> query2 = session.createNativeQuery(sql);
long count = query2.getSingleResult().longValue();
if (pageNo <= 0 || languageViewList.isEmpty()) {
return new MultiplePages<LanguageView>(null, pageNo, (long)Math.ceil(count/30.0));
} else {
return new MultiplePages<LanguageView>(languageViewList, pageNo, (long)Math.ceil(count/30.0));
}
}
@Override
public MultiplePages<LanguageView> getLanguagesViewFilteredMultiplePages(long pageNo, LanguageViewFilter LanguageViewFilter) {
Session session = sessionFactory.getCurrentSession();
String sql = null;
List<LanguageView> languageViewList = null;
Map<String, Object> filters = new HashMap<String, Object>();
filters.put("lang_no", LanguageViewFilter.getLangNo());
filters.put("lang_name", LanguageViewFilter.getLangName());
filters.put("active", LanguageViewFilter.getActive());
filters.put("lang_dfl", LanguageViewFilter.getLangDfl());
String filterQuery = GenerateSql.generateFilterQuery("language_view", filters);
if (pageNo > 0) {
sql = filterQuery + " LIMIT 30 OFFSET :Offset";
Query<LanguageView> query = session.createNativeQuery(sql, LanguageView.class);
query.setParameter("Offset", (pageNo - 1) * 30);
languageViewList = query.getResultList();
}
sql = "SELECT COUNT(*) FROM (" + filterQuery + ") As filteredRowsCount";
@SuppressWarnings("unchecked")
Query<BigInteger> query2 = session.createNativeQuery(sql);
long count = query2.getSingleResult().longValue();
if (pageNo <= 0 || languageViewList.isEmpty()) {
return new MultiplePages<LanguageView>(null, pageNo, (long)Math.ceil(count/30.0));
} else {
return new MultiplePages<LanguageView>(languageViewList, pageNo, (long)Math.ceil(count/30.0));
}
}
@Override
public Object getNextPK() {
Session session = sessionFactory.getCurrentSession();
String sql = "SELECT max(lang_no) + 1 FROM language_view";
@SuppressWarnings("unchecked")
Query<Object> query = session.createNativeQuery(sql);
Object nextPK = query.getSingleResult();
if (nextPK == null) nextPK = 1;
return nextPK;
}
@Override
public void addLanguage(Language language) {
Session session = sessionFactory.getCurrentSession();
session.save(language);
session.flush();
}
@Override
public void updateLanguage(Language language) {
Session session = sessionFactory.getCurrentSession();
Language DBLanguage = session.get(Language.class, language.getLangNo());
DBLanguage.setActive(language.getActive());
DBLanguage.setLangDfl(language.getLangDfl());
DBLanguage.setLangDir(language.getLangDir());
DBLanguage.setLangExt(language.getLangExt());
DBLanguage.setLangName(language.getLangName());
DBLanguage.setLangNo(language.getLangNo());
DBLanguage.setReportExt(language.getReportExt());
session.merge(DBLanguage);
session.flush();
}
@Override
public void deleteLanguage(Integer langNo) {
Session session = sessionFactory.getCurrentSession();
Language DBLanguage = session.get(Language.class, langNo);
session.delete(DBLanguage);
session.flush();
}
}
|
## Reference
homepage > DOCUMENTATION > API > Introduction > CLI > Learn more about the CLI!
## Base
```sh
$ npx webpack
```
## --entry, --output-path(-o)
after '--entry': the file which will be bundled
after '--output-path' or '-o': the directory where the bundled file will be saved
```sh
$ npx webpack --entry ./source/index.js -o ./public
```
The name of the bundled file will be 'main.js'.
## --watch(-w)
If there are changes in the file, it automatically bundles again.
```sh
$ npx webpack --entry ./source/index.js -o ./public -w
```
## --help
You can get the information about the CLI.
```
$ npx webpack --help
```
|
# Preprocesamiento de Imgenes #
## Requirements ##
* NodeJS
* NPM
* Firebase tools
* [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli)
## Instructions to run the app
1. Run command "$ npm install"
2. Run command "$ npm start"
## React Starter Kit — "[isomorphic](http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/)" web app boilerplate
> [React Starter Kit](https://www.reactstarterkit.com) is an opinionated
> boilerplate for web development built on top of [Node.js](https://nodejs.org/),
> [Express](http://expressjs.com/), [GraphQL](http://graphql.org/) and
> [React](https://facebook.github.io/react/), containing modern web development
> tools such as [Webpack](http://webpack.github.io/), [Babel](http://babeljs.io/)
> and [Browsersync](http://www.browsersync.io/). Helping you to stay productive
> following the best practices. A solid starting point for both professionals
> and newcomers to the industry.
**See** [getting started](./docs/getting-started.md) guide,
[demo](http://demo.reactstarterkit.com), [docs](https://github.com/kriasoft/react-starter-kit/tree/master/docs),
[to-do list](https://waffle.io/kriasoft/react-starter-kit) |
**Join** [#react-starter-kit](https://gitter.im/kriasoft/react-starter-kit) chat room to stay up to date |
**Visit our sponsors**:<br><br>
[](https://rollbar.com/?utm_source=reactstartkit(github)&utm_medium=link&utm_campaign=reactstartkit(github))
[](https://localizejs.com/?cid=802&utm_source=rsk)
### Getting Started
* Follow the [getting started guide](./docs/getting-started.md) to download and run the project
([node](https://nodejs.org/) >= 5,
**[node-gyp](https://github.com/nodejs/node-gyp#readme)**
and **[prerequisites](https://github.com/nodejs/node-gyp#installation)**)
* Check the [code recipes](./docs/recipes) used in this boilerplate, or share yours
### Customization
The `master` branch of React Starter Kit doesn't include a Flux implementation or any other
advanced integrations. Nevertheless, we have some integrations available to you in *feature*
branches that you can use either as a reference or merge into your project:
* [feature/redux](https://github.com/kriasoft/react-starter-kit/tree/feature/redux) — isomorphic
Redux by [Pavel Lang](https://github.com/langpavel)
(see [how to integrate Redux](./docs/recipes/how-to-integrate-redux.md)) (based on `master`)
* [feature/react-intl](https://github.com/kriasoft/react-starter-kit/tree/feature/react-intl) —
isomorphic Redux and React Intl by [Pavel Lang](https://github.com/langpavel)
(see [how to integrate React Intl](./docs/recipes/how-to-integrate-react-intl.md)) (based on `feature/redux`)
* [feature/bootstrap3](https://github.com/kriasoft/react-starter-kit/tree/feature/bootstrap3) —
Simplest possible integration of [react-bootstrap](https://react-bootstrap.github.io/)
by [Pavel Lang](https://github.com/langpavel) (based on `master`)
If you think that any of these features should be on `master`, or vice versa, some features should
removed from the `master` branch, please [let us know](https://gitter.im/kriasoft/react-starter-kit).
We love your feedback!
### Comparison
<table width="100%">
<tbody>
<tr>
<th> </th>
<th>
React Starter Kit
[](https://github.com/kriasoft/react-starter-kit) [](https://twitter.com/ReactStarter)</th>
<th>
React Static Boilerplate
[](https://github.com/kriasoft/react-static-boilerplate) [](https://twitter.com/ReactStatic)</th>
<th>
ASP.NET Core Starter Kit
[](https://github.com/kriasoft/aspnet-starter-kit) [](https://twitter.com/dotnetreact)</th>
</tr>
<tr>
<th align="right">App type</th>
<td align="center">[Isomorphic](http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/) (universal)</td>
<td align="center">[Single-page application](https://en.wikipedia.org/wiki/Single-page_application)</td>
<td align="center">[Single-page application](https://en.wikipedia.org/wiki/Single-page_application)</td>
</tr>
<tr>
<th colspan="4">Frontend</th>
</tr>
<tr>
<th align="right">Language</th>
<td align="center">JavaScript (ES2015+, JSX)</td>
<td align="center">JavaScript (ES2015+, JSX)</td>
<td align="center">JavaScript (ES2015+, JSX)</td>
</tr>
<tr>
<th align="right">Libraries</th>
<td align="center">[React](https://github.com/facebook/react), [History](https://github.com/ReactJSTraining/history), [Universal Router](https://github.com/kriasoft/universal-router)</td>
<td align="center">[React](https://github.com/facebook/react), [History](https://github.com/ReactJSTraining/history), [Redux](https://github.com/reactjs/redux)</td>
<td align="center">[React](https://github.com/facebook/react), [History](https://github.com/ReactJSTraining/history), [Redux](https://github.com/reactjs/redux)</td>
</tr>
<tr>
<th align="right">Routes</th>
<td align="center">Imperative (functional)</td>
<td align="center">Declarative</td>
<td align="center">Declarative, cross-stack</td>
</tr>
<tr>
<th colspan="4">Backend</th>
</tr>
<tr>
<th align="right">Language</th>
<td align="center">JavaScript (ES2015+, JSX)</td>
<td align="center">n/a</td>
<td align="center">C#, F#</td>
</tr>
<tr>
<th align="right">Libraries</th>
<td align="center">[Node.js](https://nodejs.org), [Express](http://expressjs.com/), [Sequelize](http://docs.sequelizejs.com/en/latest/),
[GraphQL](https://github.com/graphql/graphql-js)</td>
<td align="center">n/a</td>
<td align="center">[ASP.NET Core](https://docs.asp.net/en/latest/), [EF Core](https://ef.readthedocs.io/en/latest/),
[ASP.NET Identity](https://docs.asp.net/en/latest/security/authentication/identity.html)</td>
</tr>
<tr>
<th align="right">[SSR](https://www.quora.com/What-are-the-tradeoffs-of-client-side-rendering-vs-server-side-rendering)</th>
<td align="center">Yes</td>
<td align="center">n/a</td>
<td align="center">n/a</td>
</tr>
<tr>
<th align="right">Data API</th>
<td align="center">[GraphQL](http://graphql.org/)</td>
<td align="center">n/a</td>
<td align="center">[Web API](https://docs.asp.net/en/latest/tutorials/first-web-api.html)</td>
</tr>
</tbody>
</table>
### Backers
♥ React Starter Kit? Help us keep it alive by donating funds to cover project
expenses via [OpenCollective](https://opencollective.com/react-starter-kit) or
[Bountysource](https://salt.bountysource.com/teams/react-starter-kit)!
<a href="http://www.nekst.me/" target="_blank" title="lehneres">
<img src="https://github.com/lehneres.png?size=64" width="64" height="64" alt="lehneres">
</a>
<a href="http://www.vidpanel.com/" target="_blank" title="Tarkan Anlar">
<img src="https://github.com/tarkanlar.png?size=64" width="64" height="64" alt="Tarkan Anlar">
</a>
<a href="https://morten.olsen.io/" target="_blank" title="Morten Olsen">
<img src="https://github.com/mortenolsendk.png?size=64" width="64" height="64" alt="Morten Olsen">
</a>
<a href="https://twitter.com/adamthomann" target="_blank" title="Adam">
<img src="https://github.com/athomann.png?size=64" width="64" height="64" alt="Adam">
</a>
<a href="http://dsernst.com/" target="_blank" title="David Ernst">
<img src="https://github.com/dsernst.png?size=64" width="64" height="64" alt="David Ernst">
</a>
<a href="http://zanehitchcox.com/" target="_blank" title="Zane Hitchcox">
<img src="https://github.com/zwhitchcox.png?size=64" width="64" height="64" alt="Zane Hitchcox">
</a>
<a href="https://opencollective.com/react-starter-kit" target="_blank">
<img src="https://opencollective.com/static/images/become_backer.svg" width="64" height="64" alt="">
</a>
### How to Contribute
Anyone and everyone is welcome to [contribute](CONTRIBUTING.md) to this project. The best way to
start is by checking our [open issues](https://github.com/kriasoft/react-starter-kit/issues),
[submit a new issues](https://github.com/kriasoft/react-starter-kit/issues/new?labels=bug) or
[feature request](https://github.com/kriasoft/react-starter-kit/issues/new?labels=enhancement),
participate in discussions, upvote or downvote the issues you like or dislike, send [pull
requests](CONTRIBUTING.md#pull-requests).
### Learn More
* [Getting Started with React.js](http://facebook.github.io/react/)
* [Getting Started with GraphQL and Relay](https://quip.com/oLxzA1gTsJsE)
* [React.js Questions on StackOverflow](http://stackoverflow.com/questions/tagged/reactjs)
* [React.js Discussion Board](https://discuss.reactjs.org/)
* [Flux Architecture for Building User Interfaces](http://facebook.github.io/flux/)
* [Enzyme — JavaScript Testing utilities for React](http://airbnb.io/enzyme/)
* [Flow — A static type checker for JavaScript](http://flowtype.org/)
* [The Future of React](https://github.com/reactjs/react-future)
* [Learn ES6](https://babeljs.io/docs/learn-es6/), [ES6 Features](https://github.com/lukehoban/es6features#readme)
### Related Projects
* [Membership Database](https://github.com/membership/membership.db) — SQL schema boilerplate for user accounts, profiles, roles, and auth claims
* [Babel Starter Kit](https://github.com/kriasoft/babel-starter-kit) — Boilerplate for authoring JavaScript/React.js libraries
### Support
* [#react-starter-kit](http://stackoverflow.com/questions/tagged/react-starter-kit) on Stack Overflow — Questions and answers
* [#react-starter-kit](https://gitter.im/kriasoft/react-starter-kit) on Gitter — Watch announcements, share ideas and feedback
* [GitHub issues](https://github.com/kriasoft/react-starter-kit/issues), or [Scrum board](https://waffle.io/kriasoft/react-starter-kit) — File issues, send feature requests
* [appear.in/react](https://appear.in/react) — Open hours! Exchange ideas and experiences (React, GraphQL, startups and pet projects)
* [@koistya](https://twitter.com/koistya) on [Codementor](https://www.codementor.io/koistya), or [Skype](http://hatscripts.com/addskype?koistya) — Private consulting
### License
Copyright © 2014-2016 Kriasoft, LLC. This source code is licensed under the MIT
license found in the [LICENSE.txt](https://github.com/kriasoft/react-starter-kit/blob/master/LICENSE.txt)
file. The documentation to the project is licensed under the
[CC BY-SA 4.0](http://creativecommons.org/licenses/by-sa/4.0/) license.
---
Made with ♥ by Konstantin Tarkus ([@koistya](https://twitter.com/koistya)) and [contributors](https://github.com/kriasoft/react-starter-kit/graphs/contributors)
|
import React from "react";
import {ColumnShape} from "react-base-table";
import moment from "moment";
import {byteSizeFormat} from "@common/const/byte-size";
import StorageClass from "@common/models/storage-class";
import {getLang, translate} from "@renderer/modules/i18n";
import {FileItem} from "@renderer/modules/qiniu-client";
import {FileRowData} from "../../types";
import FileName, {FileNameCellCallbackProps} from "./file-name";
import FileCheckbox, {FileCheckboxCellProps, FileCheckboxHeader, FileCheckboxHeaderProps} from "./file-checkbox";
import FileOperations, {FileOperationsCellCallbackProps} from "./file-operations";
type GetFileTableColumnsProps = {
availableStorageClasses?: Record<string, StorageClass>,
bucketGrantedPermission?: "readonly" | "readwrite"
}
& FileNameCellCallbackProps
& FileCheckboxHeaderProps
& FileCheckboxCellProps
& FileOperationsCellCallbackProps;
export function getColumns({
availableStorageClasses,
isSelectedAll,
onToggleSelectAll,
onClickFile,
onDoubleClickFile,
onAction,
}: GetFileTableColumnsProps): ColumnShape<FileRowData>[] {
const currentLanguage = getLang();
const hasAvailableStorageClasses =
availableStorageClasses &&
Object.keys(availableStorageClasses).length;
const result: ColumnShape<FileRowData>[] = [
{
key: "__selection__",
headerRenderer: () => (
<FileCheckboxHeader
isSelectedAll={isSelectedAll}
onToggleSelectAll={onToggleSelectAll}
/>
),
dataKey: "isSelected",
width: 40,
flexShrink: 0,
cellRenderer: ({cellData, rowData}) => (
<FileCheckbox rowData={rowData} cellData={cellData}/>
),
},
{
key: "fileName",
title: translate("browse.fileTable.fileName"),
dataKey: "name",
width: 0,
resizable: true,
flexGrow: 10,
cellRenderer: ({cellData, rowData}) => (
<FileName
cellData={cellData}
rowData={rowData}
onClickFile={onClickFile}
onDoubleClickFile={onDoubleClickFile}
/>
),
},
{
key: "fileTypeOrSize",
title: translate("browse.fileTable.fileTypeOrSize"),
width: 100,
flexGrow: 1,
dataGetter: ({rowData: file}) =>
FileItem.isItemFile(file)
? byteSizeFormat(file.size)
: translate("common.directory"),
},
{
key: "fileModifyDate",
title: translate("browse.fileTable.fileModifyDate"),
width: 192,
flexGrow: 1,
dataGetter: ({rowData: file}) =>
FileItem.isItemFile(file)
? moment(file.lastModified).format("YYYY-MM-DD HH:mm:ss")
: "-"
},
{
key: "fileOperation",
title: translate("browse.fileTable.fileOperation"),
width: 150,
flexGrow: 1,
cellRenderer: ({rowData, cellData}) => (
<FileOperations
canChangeStorageClass={Boolean(hasAvailableStorageClasses)}
rowData={rowData}
cellData={cellData}
onAction={onAction}
/>
),
},
];
if (hasAvailableStorageClasses) {
// append storage class column after 3rd column
result.splice(3, 0, {
key: "fileStorageClass",
title: translate("browse.fileTable.fileStorageClass"),
width: 128,
flexGrow: 1,
dataGetter: ({rowData: file}) =>
FileItem.isItemFile(file)
? availableStorageClasses[file.storageClass].nameI18n[currentLanguage]
?? file.storageClass
: "-"
},
);
}
return result;
}
|
\documentclass[10pt,letterpaper,oneside]{article}
\usepackage{silence}
\usepackage{listings}
\WarningFilter{hyperref}{Token not allowed}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage[letterpaper,margin=2.5cm]{geometry}
\usepackage{amssymb,graphicx}
\usepackage[colorlinks=true,linkcolor=blue,citecolor=blue,filecolor=blue,urlcolor=blue]{hyperref}
\usepackage{etoolbox}
\makeatletter
\patchcmd{\chapter}{\if@openright\cleardoublepage\else\clearpage\fi}{}{}{}
\makeatother
\usepackage{parskip}
%%%%%%%%%%%%%%%%%%%%%%%Fonts%%%%%%%%%%%%%%%%%%%
\DeclareFontFamily{T1}{lmtt}{}
\DeclareFontShape{T1}{lmtt}{m}{n}{<-> ec-lmtl10}{}
\DeclareFontShape{T1}{lmtt}{m}{\itdefault}{<-> ec-lmtlo10}{}
\DeclareFontShape{T1}{lmtt}{\bfdefault}{n}{<-> ec-lmtk10}{}
\DeclareFontShape{T1}{lmtt}{\bfdefault}{\itdefault}{<-> ec-lmtko10}{}
%%%%%%%%%%%%%%%%%%%%%%%Abbreviations%%%%%%%%%%%%%%%%%%%
\newcommand{\bnmr}{$\beta$-\textsc{nmr}}
\newcommand{\bnmrg}{\texttt{BNMR}}
\newcommand{\bnqr}{$\beta$-\textsc{nqr}}
\newcommand{\triumf}{\textsc{triumf}}
\newcommand{\cmms}{\texttt{CMMS}}
\newcommand{\isac}{\textsc{isac}}
\newcommand{\nmr}{\textsc{nmr}}
\newcommand{\musr}{$\mu$\textsc{sr}}
%%%%%%%%%%%%%%%%%%%%%%%IT%%%%%%%%%%%%%%%%%%%
\newcommand{\cpp}{\texttt{C++}}
\newcommand{\qt}{\texttt{QT}}
\newcommand{\minuit}{\texttt{MINUIT}}
\newcommand{\mud}{\texttt{MUD}}
\newcommand{\xmgr}{\texttt{XMGR}}
\newcommand{\acegr}{\texttt{ACE/gr}}
\newcommand{\bof}{\texttt{BnmrOffice}}
\newcommand{\gsl}{\texttt{GSL}}
\newcommand{\qcp}{\texttt{QCustomPlot}}
\newcommand{\myemail}{\texttt{\href{mailto:saadaoui@triumf.ca}{saadaoui@triumf.ca}}}
%%%%%%%%%%%%%%%%%%%%%%%Text%%%%%%%%%%%%%%%%%%%%
\newcommand{\mycite}[6]{\bibitem{#1}#2 \etal, #3 {\bf {#4}}, {#5} ({#6}).}
\newcommand{\equ}[2]{\begin{equation}\label{#1}{#2}\end{equation}}
\newcommand{\meq}[2]{\begin{eqnarray}\label{#1}{#2}\end{eqnarray}}
\newcommand{\figs}[2]{Fig. \ref{#1}-(#2)}
\newcommand{\fig}[1]{Fig. \ref{#1}}
\newcommand{\etal}{{\it et al.}}
\newcommand{\ie}{{\it i.e.}}
\title{\bof\ Documentation}
\author{Hassan Saadaoui \\
\small{TRIUFM, 4004 Wesbrook mall, Vancouver, BC V6T~1Z4} \\
\small{\myemail}}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\noindent \normalsize
This document gives a description and tutorial of the \bof\ program. The graphical user interface (GUI) of the program is designed using Qt technology. Several well-tested packages are needed to perform necessary tasks such as minimization, reading and plotting data, and scientific calculations. Instructions about installation, structure of the code, and models of the program will be covered.
\end{abstract}
\pagebreak
\tableofcontents
\pagebreak
\section{Introduction}
\bof\ is used to search, view, and analyze ASCII and $\beta$-NMR (.msr) data. It can be extended by the user to read any type of data. The program does many other tasks such as simulations, database interface, and converting units. This program is developed by Hassan Saadaoui and is maintained as needed. It is open source and released under the General Public License (GPL). No warranty or guarantee of the results is implied. Please acknowledge the author if you are using this program in an offline data analysis. It is the least you can do to encourage future developments and maintenance of the program. For any questions, please email at \myemail.
\begin{figure}[h]
\includegraphics[width=\textwidth]{bnmroffice.png}
\caption{Regression page of the \bof\ graphical user interface.}
\label{fig-dep}
\end{figure}
\section{Requirements}
The program is developed in \cpp\ and \qt. The latter provides many excellent libraries for programming and building the graphical user interface. Many desktops of Linux OS are build using \qt, such as the KDE desktop. \qt\ is cross-platform, modern and well-maintained.
The \bof's core components are as shown in Fig. \ref{fig-dep}
\begin{itemize}
\item \qt: a \cpp\ framework for programming and developing GUI applications. Version 4.8.x or 5.x is needed.
\item \mud: a library to read the $\mu$SR data format (.msr) developed at \cmms\ in \triumf.
\item \minuit: a minimization routine for fitting data.
\item \xmgr: an application to plot and visualize data.
\item \qcp: to plot data directly onto the GUI (included within the package).
\item \gsl: (optional) for compiling few fitting functions.
\end{itemize}
In addition to the above requirements, and depending on your system, you may also need some dependency packages. The main packages are:
\begin{itemize}
\item \texttt{gcc} compiler
\item \texttt{automake}
\end{itemize}
\begin{figure}[h]
\includegraphics[width=\textwidth]{dependency.png}
\caption{External packages required by \bof.}
\label{fig-dep}
\end{figure}
\newpage
\section{Package Structure}
The package you download will have a structure as shown
in \fig{fig-str}. The main folder contains 4 sub-folders and 5 files.
\begin{itemize}
\item \verb+src/+: contains the source code. This has also
many sub-folders for each page and a \verb+main.cpp+,
\verb+mainwindow.(cpp,ui,h)+, \verb+plotting.(cpp,h)+, and
\verb+constants.h+ for some shared constants.
\item \verb+fct/+ contains the fitting functions and script \verb+./compile+
to execute the codes and create the libraries.
\item \verb+etc/+ for documentation, images, data, scripts
and templates, and the resources.qrc file needed by \qt.
\item \verb+bin/+ where the execution binary data is dumped.
\item \verb+bnmroffice.pro+ used to generate the makefile.
\item \verb+AUTHOR+ for authorship attributions.
\item \verb+LOG+ for keeping a log of the package changes over time.
\item \verb+COPYING+ supplies the GPL agreement.
\item \verb+README+ for installation instructions.
\end{itemize}
\begin{figure}[h]
\includegraphics[width=\textwidth]{structure.png}
\caption{Structure of the program. Upon execution, \bof\ calls main which calls mainwindow, plotting, and constants. The mainwindow in turn calls pages and menu bar options. In each page, you find three files; .cpp, and .h for the programming part, and .ui for the GUI part.}
\label{fig-str}
\end{figure}
\newpage
\section{Installation}
In addition to bnmroffice, you also need: \qt, \minuit, \mud, \xmgr, and \gsl.
\begin{enumerate}
\item It is likely that your system has \qt, and \xmgr\ pre-installed. In this case,
you only need to install \minuit\ and \mud\ libraries.
\item These instructions may seem long, but they are meant to give as much details for the less-experienced users. In most cases, a linux-experienced user may be able to install all libraries without help, except the instructions for installing \bof.
\item It is assumed for clarity, in all that follows, that you unpack your downloads to the home folder \verb+~/+ (done using
\verb+-C ~/+ or \verb+-d ~/+). That is optional, as you may unpack somewhere else like; \verb+~/programs+, \verb+~/downloads+.
Without \verb+-C+ or \verb+-d+ your unpacks will appear in your current directory.
\item Any line here preceded by the $\$$ sign, is a command line that you may copy and paste to your terminal.
\item These instructions are meant for Linux users only. Mac users may find them useful, and Windows is not supported yet.
\item Download the latest bnmroffice from local computers, sourceforge, or github.\\
\verb+$ wget https://sourceforge.net/projects/bnmroffice/files/bnmroffice.tar.gz/download+
\item Unpack it \\ \verb+$ctar -xvf bnmroffice.tar.gz -C ~/+
\end{enumerate}
\subsection{\qt}
It is the backbone of the GUI and programming. Download the \qt\ on-line installer from \url{http://www.qt.io/download-open-source/}. It is a light executable which downloads based on your system/selections. It provides all \qt\ 5.x binary and source packages and latest \qt\ creator.
\subsection{\minuit}
This package is used for minimization. It is developed at CERN originally in Fortran and later converted to \cpp. It is very powerful
and well tested. To compile, follow these steps.
\begin{enumerate}
\item Download latest Minuit2 located at\\
\url{http://seal.web.cern.ch/seal/snapshot/work-packages/mathlibs/minuit/release/download.html}
\item Unpack and cd\\
\\ \verb+$ tar -xvf minuit.tar.gz -C ~/+
\\ \verb+$ cd ~/minuit+
\item To install follow the instructions at
\\ \url{http://seal.web.cern.ch/seal/snapshot/work-packages/mathlibs/minuit/gettingStarted/autoconf.html}
\item Make SURE that the tests in the tutorial are running as described in the link \\ \url{http://seal.web.cern.ch/seal/snapshot/work-packages/mathlibs/minuit/gettingStarted/testOutput.html}
\item Copy (as superuser) the miniut libraries from
\verb+minuit/src/.lib/liblcg_Minuit.*+ to \verb+/usr/lib/+
\\ \\ \verb+$ sudo cp minuit/src/.lib/liblcg_Minuit.* /usr/lib/+
\item Update ldconfig
\\ \\ \verb+$ sudo ldconfig+
\end{enumerate}
{\bf Extra notes}: It is somewhat a challenge to compile Minuit2. These extra notes maybe useful.
\begin{itemize}
\item Depending on your system, you may need to modify few codes namely src/MnUserTransformation.cpp to add \verb+#include <cstdio>+ or \verb+#include <cstdio.h>+ just below \verb+#include <algorithm>+ and re-compile.
\item Locate where libraries and header files are, hopefully in
\verb+/usr/local/include/Minuit2+, and \verb+/usr/local/lib/+
\item Add the path \verb+/usr/local/lib/+ to \verb+/etc/ld.so.conf+ as described here
\url{http://stackoverflow.com/questions/1099981/why-cant-python-find-shared-objects-that-are-in-directories-in-sys-path}\\
\\ \verb+$ export LD_LIBRARY_PATH=/usr/local/lib+ \\ or
\\ \verb+$ export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH+
\item Run ldconfig
\\ \verb+$ sudo ldconfig+
\end{itemize}
\subsection{\mud}
This package is needed to read the TRIUMF .msr files.
\begin{enumerate}
\item Download the MUD library source archive mud.tar.gz from \url{http://musr.ca/mud}
\\ \verb+$ wget http://musr.ca/mud/mud.tar.gz+
\item Unpack and cd
\\ \verb+$ tar -zxvf mud.tar.gz -C ~/+
\\ \verb+$ cd ~/mud+
\item Run make with root access (read the install instructions withing the mud package)
\\ \verb+$ sudo make all+
\item Copy the files mud.h and libmud.a into \verb+/usr/lib/+ and
\verb+/usr/include/+
\\ \verb+$ sudo cp ./lib/libmud.a /usr/lib/+
\\ \verb+$ sudo cp ./src/mud.h /usr/include/+
\end{enumerate}
\subsection{\xmgr}
This is needed for plotting. It is an old but quick and robust GUI, and makes publication quality figures. Subsequent versions have been developed, however most of the user community still prefers an outdated version dating back to 1994. Recently, a resurrected version of the outdated program appeared on Github almost 20 years later! Please contact for other options if you are unable to install \xmgr.
\begin{enumerate}
\item downloand and Unpack xmgr from https://github.com/mlund/xmgr-resurrection
\\ \verb+$ wget https://github.com/mlund/xmgr-resurrection/archive/master.zip+
\\ \verb+$ unzip master.zip -d ~/+
\\ \verb+$ cd ~/xmgr-resurrection-master+
\item XMGR has a feature of displaying the copyright each time it starts from a terminal.
This can obscure the user from seen the error messages produced by bnmroffice.
To avoid this, comment the lines 107-111 in main.c and save.
\item Typically the following packages are required: libice-dev libx11-dev lesstif2-dev libxmu-dev libxpm-dev.
Install if not found in your OS. Try, on ubunto/related systems, get-all (or your system's alternative).
\\ \verb+$ sudo get-all install libice-dev libx11-dev lesstif2-dev libxmu-dev libxpm-dev+
\item Read README.md to compile the code. Each system is different; try these given steps:
\\ \verb+$ cmake . -DENABLE_NETCDF=on+
\\ \verb+$ cmake . -DCMAKE_INSTALL_PREFIX=/usr/local+
\\ \verb+$ make+
\\ \verb+$ sudo make install+
\item If all went well, open the executable \verb+xmgr+ located likely in \verb+src/+ or somewhere else within your folder.
\item You must locate this file and copy it to \verb+/usr/bin+ and \verb+/usr/local/bin/+ if it is not already there.
\\ \verb+$ sudo cp xmgr /usr/bin/+
\\ \verb+$ sudo cp xmgr /usr/local/bin/+
\end{enumerate}
\subsection{\gsl}
This package is optional. It is only needed to compile
few fitting functions in \verb+fct/+
\begin{enumerate}
\item download latest gsl from \url{http://gnu.mirror.iweb.com/gsl/}
\item Unpack and cd
\\ \verb+$ tar -xvf gsl-latest.tar.gz -C ~/+
\\ \verb+$ cd ~/gsl-latest+
\item Run configure
\\ \verb+$ ./configure+
\item Run make
\\ \verb+$ make+
\item Run make install as root
\\ \verb+$ sudo make install+
\item Update libraries cache
\\ \verb+$ sudo ldconfig+
\end{enumerate}
\subsection{\bof}
\begin{enumerate}
\item cd to the downloaded package
\\ \verb+$ cd ~/bnmroffice+
\item change the path to bnmr Data, and bnqr Data as defined in constants.h
\\ \verb+$ gedit src/constants.h+
\item If Qt binaries are not in your path, set the env (locate where qmake is)
\\ \verb+$ PATH=/usr/Qt/5.4/gcc_64/bin:$PATH + (change \verb+"/usr/Qt/5.4/gcc_64/bin"+ as per your system)
\\ \verb+$ export PATH+
\item Run qmake. [Optional: to modify the default install location use
\verb+$qmake PREFIX=/your.new.location/]+
\\ \verb+$ qmake+
\item Run make and make install
\\ \verb+$ make+
\\ \verb+$ sudo make install+ (needs root)
\item cd to directory \verb+fct/+ and compile all the libraries using the script compile
\\ \verb+$ cd fct+
\\ \verb+$ sudo ./compile+
\item To test the gui, invoke
\\ \verb+$ bnmroffice+ [or \verb+$ ./bnmroffice+ if not installed as root].
\end{enumerate}
\newpage
\newpage
\section{Description of the GUI}
The GUI has a menu bar at the very top and a tab widget below it.
This tab widget contains 6 tabs (pages): \verb+Search+, \verb+Analysis+, \verb+Results+, \verb+Database+, \verb+Simulations+, and \verb+Converter+. Each of these contains widgets that the user may change and push buttons for issuing signals. The menu bar and the pages functionalities will be described next.
\begin{figure}
\includegraphics[width=\textwidth]{menubar.png}
\caption{\bof\ menu bar and main pages.}
\label{fig-menu}
\end{figure}
\subsection{Menu bar}
\subsubsection{File}
This has 4 options; (i) invoke a new window, (ii) open an old version of \bof, (iii) clean \verb+temp.*+ data which removes all files that the program creates for plotting purposes, and (iv) quit/close the window.
\subsubsection{Edit}
It has editing options. For now, the user can overwrite the path variables of \bnmr\ and \bnqr\ archive predefined in \verb+constants.h+. Note that this is a temporary overwrite, and to make it permanent, one must modify the \verb+constants.h+ and re-compile.
\subsubsection{View}
It has the option of invoking a live/stream data window (see \ref{Streaming data}). Also, the user can change the view of the program widgets (default is \verb"fuse"), and the color of the GUI (default is \verb+"Green-white"+).
\subsubsection{Plotting}
Several check-boxes can be used for plotting purposes.
The \xmgr\ plots are closed by default after a new window is plotted to avoid the buildup of many \xmgr\ windows. To keep the old plots active one must check the box \verb+"Keep Plots"+. Also, in \xmgr, the plots are by default separated, to combine them in one plot the user could check the box \verb+"Combine Plots"+. At the moment, the GUI creates a lot of ASCII files in the background as needed by \xmgr. These files are deleted by default after the user signals are processed. If the user wants to keep copies of the ASCII file, the box \verb+"Keep ASCII files"+ must be checked.
\subsubsection{Help}
This contains the \verb+"About"+ dialog for authorship and version of the current GUI, \verb+"Tips"+ dialog which does nothing but remind the user that by hovering the mouse index onto labels one can get the tool-tips for each widget. \verb+"Tutorial"+ invokes an HTML page with these instructions.
\newpage
\subsection{Streaming data}\label{Streaming data}
This window is invoked from \verb+view/show streaming window+.
It streams data during regular intervals of time as defined by the user.
The user can choose the type of data (only \bnmrg\ is supported at the moment), run number, year, and settings for plotting options (bin, x min, x max).
The user must specify the update interval.
Upon clicking on Start, the GUI starts a counter (in seconds) and then
plots the data after each interval. The user can change the input variables without stopping the plotting as the GUI reads the input and plots the data again at the end of the end of each interval.
For \bnmrg\ data, at the moment, the GUI displays 4
plots and each contain 3 or 4 grouped curves. The first plot displays
the asymmetries of the experiment counters of polarized ${}^8$Li$^+$ beam. These are; the positive helicity asymmetry (defined as $\frac{counter_1 -counter_2}{counter_1+counter_2}$ during the + helicity of the laser), the negative helicity asymmetry, and the total asymmetry which is the difference of the first two. In the 2nd plot, similar asymmetries for the neutral beam are presented. In the 3rd plot, the counters of polarized ${}^8$Li$^+$ are shown, and the counts of beam monitors are shown in plot 4. An example is shown in \fig{fig-stream}
\begin{figure}[h]
\includegraphics[width=\textwidth]{stream.png}
\caption{Streaming window: it streams data at regular intervals. This could be useful for on-line experiments. }
\label{fig-stream}
\end{figure}
\newpage
\subsection{Search}
In this page, the user can find the data that corresponds to his search query. There are 9 fields that user can change. In the first line one finds, the title field (must be a string), experiment type (either \bnmr\ or \bnqr\ data at the moment), type of data (1f, 1n, 20, and 2e modes of \bnmrg\ data). In the 2nd line, the user can specify
the intervals of year, run number and elapsed time. In the 3rd line,
the user can specify the interval of independent variables of temperature, energy, and field. These are defined in \verb+tab_search.cpp+ code.
The user can start the search by clicking on the pushbutton \verb+Search+.
After sometime, the search results will be returned in a table with 9 columns. These are (1) check-box columns to choose which runs to send to the analysis page, (2) run number, (3) year, (4) type of experiment mode, (5) elapsed time in minutes, (6) temperature in K, (7) energy in keV, (8) field in Gauss, and (9) the run title.
The user can also display more columns by clicking on the pushbutton \verb+"More"+ which displays a dialog that contains more fields to display. These fields are pre-defined in a template file called \verb+bnmr-bnqr-logs.txt+ which contains 5 columns, (i) Labels, (ii) Symbols, (iii) Exp, (iv) Path, and (v) Unit. The user can change this file to add more fields or to update the previous ones. The program will read the file saved in the current working directory, and if not found, it reads the default file from \verb+resources.qrc+.
The user can select all runs by clicking on \verb+"Select"+ and send the selected runs to the next page for analysis by pushing the button \verb+"Next"+.
\begin{figure}[h]
\center
\includegraphics[width=0.8\textwidth]{search.png}
\caption{Searching the .msr files. More fields can be displayed after clicking on "More" and checking the desired fields. These fields are predefined in \texttt{"bnmr-bnqr-logs.txt"} which can be edited by pushing \texttt{"Edit"}.}
\label{fig-mag}
\end{figure}
\clearpage
\subsection{Regression}
This is the main page of the entire program and by far the most complicated to program. The network of background signals are large and may cause the program to crash unexpectedly. Please report these cases.
% \begin{figure}[h]
% \includegraphics[width=\textwidth]{analyze1}
% \caption{Regression analysis page}
% \label{fig-mag}
% \end{figure}
\subsubsection{Data input}
\begin{figure}[h]
\includegraphics[width=\textwidth]{analyze-bnmr.png}
\includegraphics[width=\textwidth]{analyze-ascii.png}
\caption{Options for data input}
\label{fig-mag}
\end{figure}
The user can choose to fit either ASCII text data or \verb+.msr+ files of the \cmms\ facility. The user can locate the data using the tool button next to Data for ASCII files. For \verb+.msr+ files, the user can only specify the run year and number and the program looks it up in the archive directory (defined in \verb+constants.h+ or \verb+Edit+).
For each of these types of data, there are three ways to specify the input data. For the \verb+.msr+ type follow these instructions;
\begin{enumerate}
\item Using run numbers directly:
\begin{itemize}
\item A year must always be specified.
\item "|" is used to separate runs of different years.
\item "," (coma) separates between run numbers.
\item "-" separates between two numbers, which defines a range of runs.
\item "(-)" is used to flip the asymmtry opposite to the original one, (either up or down).
\item No other characters or space are allowed.
\item Example 1: "2011:45012,45672,42333|2013:45333(-),40123"
\item Example 2: "2011:40100-40110"
\end{itemize}
\item Using \verb+.inf+ files:
\begin{itemize}
\item It is best to create \verb+.inf+ file out of \verb+temp.inf+ created by the program from a direct input method above.
\item The file \verb+temp.inf+ is found in the working directory.
\item Must follow the same template as of \verb+temp.inf+
\item The user can change the file and update the independent variables.
\end{itemize}
\item Using \verb+.list+ files
\begin{itemize}
\item The content of the file must follow the same instructions as run numbers.
\item Example: A file named \verb+"myfavoriteruns.list"+, contains a single line\\ \verb+2010:45012,45672,41223,45012,40072,42313|2014:45123(-),40003+.
\end{itemize}
\end{enumerate}
Reading/fitting ASCII files follows very similar instruction to above.
Files to fit should be either written in the lineEdit (separated by commas) or; in files of \verb+.list+ or \verb+.inf+ extension as above. The file must reside in the working directory, otherwise its full name with path should be given. Examples;
\begin{itemize}
\item Direct input: "file1.txt,file2.txt,file3.txt"
\item \verb+.list+ file: contains a single ascii line:\\ \verb+"file1.txt,file2.txt,file3.txt"+
\item \verb+.inf+ file: \verb+"myruns.inf"+, contains the columns\\
files year temp\\
file1.txt 2015 100\\
file2.txt 2014 200\\
file3.txt 2015 300\\
\end{itemize}
The format of \verb+.msr+ files to create are pre-defined as asymmetry or counts and are all in xydy format. The inner format of the ASCII file must be set in the field \verb+format+ and these must be columns with numbers and no other characters.
For the \verb+.msr+ files, there are several more options to tweak, such as the averaging of 1f runs, ignoring some bad 1f scans, and setting the type of 2e asymmetry. An experienced \bnmrg\ user must be familiar with these options.
The data can be binned and the limits of xmin and xmax values can be set in the options (settings) field. These must be numbers separated by commas.
\subsubsection{Fitting selection}
\begin{figure}[h]
\includegraphics[width=\textwidth]{analyze-fct.png}
\caption{Fitting functions input.}
\label{fig-mag}
\end{figure}
The user can select the function to use, the mode of fitting (single or global) and type of errors. The functions are defined in the folder \verb+fct/+ and the user can add new ones by invoking the selection \verb+"Create New"+ in the functions comboBox. The user must follow the instructions in the pop-up window and then select \verb+"Update"+ from the comboBox. This will add the newly defined function to the list.
For the global method the user can choose to show all parameters for each run or not. These settings can be changed by double clicking on the initial parameters tab-widget.
The errors are defined by \minuit\ routine, and are symmetric (Migrad) or asymmetric (Minos) errors. The latter are heavy to compute and the program may become unresponsive for sometime while the computation is going on. For further details read \url{http://seal.web.cern.ch/seal/documents/minuit/mnerror.pdf}.
\subsubsection{Results output}
\begin{figure}[h]
\includegraphics[width=\textwidth]{analyze-res.png}
\caption{Fitting results output.}
\label{fig-mag}
\end{figure}
The fitting results are written to this file. The user must specify a name, or browse for an old file. The results can be either appended
(using \verb+Append+) to the old file keeping its content (useful for doing run by run fitting), or the old file is overwritten using \verb+Rewrite+.
\subsubsection{Parameters input}\begin{figure}[h]
\center
\includegraphics[width=.75\textwidth]{analyze-table-s.png}
\includegraphics[width=.75\textwidth]{analyze-table-g.png}
\caption{Input parameters for (a) single and (b) global fits. (a) The fit starts from this table for each file, or from the results of the last file in the sequence enabled by double clicking on the \texttt{"initial parameters"}. (b) If a parameter is shared between files, only the parameter of the first run is active and the same parameter for other files becomes inactive. }
\label{fig-tables}
\end{figure}
The initial parameters are read from the function library.
The table contains 5 columns for the single method, and 6 columns for the global method. These columns are; (1) parameter name, (2) initial value of the parameter, (3) lower limit, (4) upper limit, (5) fix the parameter checkBox, and (6) share the parameter checkBox.
These parameters can be changed, and saved in a template for future use by right-clicking on the specific table and then choose \verb+"save as a template"+. This creates a text file template with a prefix \verb+".tab"+. The user can change this text file as required, and the template can be loaded later for a similar function.
\subsubsection{Parameters output}
\begin{figure}[h]
\center
\includegraphics[width=.75\textwidth]{analyze-res-g.png}
\caption{Results of a global fit where the shared parameter is Amplitude. }
\label{fig-tables}
\end{figure}
This prints out the output of the fit. The number of significant figures can be set by double-clicking on the results tab. One can also change the number of errors to show, and the way the filename is displayed.
\clearpage
\subsection{Results}
This page reads the files of fitting parameters created by the
analysis page. It displayed a table with two columns, the left column represents the x-axis and the right column the y-axis.
Each column contains all fields found in the specified file (as created during the fitting).
The user can check any of the fields, and a matrix of plots of y versus x will be displayed. The user can clear all choices using \verb+"Clear"+, and kill/delete the active table using \verb+"Purge"+.
The plots are made using \xmgr\ plotting program. Horizontal or vertical error bars are displayed if specified in the chosen parameter. The user can edit the \xmgr\ windows as he pleases and can make publication quality figures out of these results.
\begin{figure}[h]
\center
\includegraphics[width=\textwidth]{results1.png}
\caption{Results page.}
\label{fig-results}
\end{figure}
\newpage
\subsection{Database}
This page offers a user-friendly interface for databases, and
uses SQLite language \url{http://www.tutorialspoint.com/sqlite/sqlite_overview.htm}. At the start, the user must select a database by clicking on the toolButton next to \verb+"Database"+, or create a new one from the \verb+"Querry"+ lineEdit using SQL commands and hitting \verb+"Execute"+.
It is advised to use an SQL manager (like the friendly browser extension SQLite manager) to create databases and tables. Then, one can use this interface to add/delete rows and edit cells, interact with the content of the database. But an experienced user can do everything from this page as well by executing the \verb+"Querry"+ commands.
Te get familiar with the interface two databases are pre-made and come with the program and can be found in the folder \verb+"etc/sql/"+. These are called \verb+"bnmr.sqlite"+ and \verb+"physics.sqlite"+. Each contain several tables. The user can load any of these tables from the comboBox, and a model of the table will be displayed.
The user can execute any query to study the loaded table. Example;\\ \verb+SELECT * FROM table_of_constants where Unit="kg"+ will select all fields in the \verb+table_of_constants+ where the unit is in kg. The user must be familiar with SQL to execute from the Query field. Any table can be changed by adding or deleting rows. Also each cell can be edited, or displayed by clicking on \verb+"Open"+. This can be used to display a cell with a lot of text or view the cell as image if the full path of the image was given in that cell.
\begin{figure}[h]
\center
\includegraphics[width=0.8\textwidth]{database1.png}
\caption{Database interface loaded with a table of physical constants.}
\label{fig-mag}
\end{figure}
\clearpage
\subsection{Simulations}
\subsubsection{Van-Vleck second moment}
In this page, one computes the dipolar second moment using the Van-Vleck method [J. H. Van Vleck, Phys. Rev. 74, 1168 (1948)]. The user specifies the implanted ions, target material, and type of lattice, and then the coordinates of each site. The results will be plotted on the same page using \qcp\ libraries. The plots can be exported into .pdf, .png, and .bmp files. ASCII files of the computed are created in the working directory.
The simulation is tested against two published papers in (1) Lattice locations of 8Li in Cu, Hyperfine Interactions 120/121 (1999) 419-422. (2) Location of 12B in Al and Cu, Phys Rev B 13, 34 (1976). The source code of this calculation is originally written by Samir Tabara, and adapted for \bof.
\begin{figure}[h]
\center
\includegraphics[width=\textwidth]{sim-vv.png}
\caption{Van-Vleck calculation}
\label{fig-mag}
\end{figure}
\clearpage
\subsubsection{Superconducting energy gap}
This page performs calculation of the superconducting energy gap, for a given gap symmetry and parameters such as the penetration depth and coherence length. The definitions can be found in the papers
H. Saadaoui \etal, Phys. Rev. B 88, 094518 (2013), and
R. Prozorov and R. W. Giannetta, Supercond. Sci. Technol. 19, 41 (2006).
The simulation computes three functions, the second moment of the magnetic field distribution versus temperature (\verb+sigma_vs_temp+), the second moment of the magnetic field distribution versus field (\verb+sigma_vs_field+), and the penetration depth versus temperature (\verb+lambda_vs_temp+).
Four forms of the energy gap $\Delta(T,{\bf k})$ are pre-defined; the $s$-wave, $d$-wave, $s$-wave-dirty and $d$-wave non-monotonic. These are defined in Eqs. 17 and 18 in the Prozorov paper. Two empirical forms of the second moment of the magnetic field distribution versus field are specified, the Modified-London and Ginsburg-Landau forms. Please refer to the paper of H. Saadaoui \etal, Phys. Rev. B 88, 094518 (2013) for further details about these functions.
\begin{figure}[h]
\includegraphics[width=0.5\textwidth]{sim-eg-in.png}
\includegraphics[width=0.5\textwidth]{sim-eg-out.png}
\caption{Input and output of the energy-gap interface}
\label{fig-mag}
\end{figure}
\clearpage
\subsection{Converter}
This page is used to convert between several units useful for a \bnmrg\
user. The definitions are given in \verb+"tab_convert.cpp"+ file. The user can change any field and hit Enter, and the associated field will update.
\begin{itemize}
\item Magnetic Field (G) = Frequency (kHz)/0.63015
\item Magnetic Field (G) = 2.2131*Current(Amp) + 0.175
\item Pulse duration (ms) = 5*10000/$\pi$/Bandwidth(Hz)
\item Pulse duration (ms) = 1764.8/Bandwidth(Hz)
\item Magnetic Field (G) = Frequency (kHz)/85.16
\end{itemize}
\begin{figure}[h]
\center
\includegraphics[width=\textwidth]{converter.png}
\caption{Converter page.}
\label{fig-mag}
\end{figure}
\section{Fitting functions}
The user can write his own fitting functions in the directory \verb+fct/+.
A new function must be written in \cpp\ but requires minimal programming knowledge of this language.
At template of a typical function is as follows:
%\begin{verbatim}
\begin{lstlisting}[language=C++, keywordstyle=\color{red}]
#include <iostream>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <string.h>
#include <iostream>
using namespace std;
#include "parameters.h"
//Wrap in "C" for the compiler.
extern "C"
{
//The defalt initial parameters loaded to the table.
void defaultParameters(Parameters &defaults)
{
defaults.addParameter( "Amplitude" , 0.2, 0.001, 0.15, 1.0 );//par[0]
defaults.addParameter( "Rate" , 0.1, 0.001, 0.0, 1.0 );//par[1]
}
//This must have the same number of parameters as in the default parameters above.
double function(double x, const std::vector<double> par)
{
return par[0]*exp( - par[1]*x);//par[0] is amplitude and par[1] is rate.
}
}
\end{lstlisting}
%\end{verbatim}
The user must follow these instructions:
\begin{itemize}
\item Make a copy of the file \verb+newFunction.cpp+ found in \verb+etc/files+.
\item Rename the file (eg: newfct.cpp) and save it in the folder \verb+fct/+.
\item cd to the directory fct, and run the script \verb+./compile+ as root
\item \texttt{$\$$ sudo ./compile name} (eg: sudo ./compile newfct.cpp)
\item This compiles the library and puts a copy in the library functions folder (\verb+/opt/bnmroffice/lib/+).
\end{itemize}
% \section{Modifying the program}
\end{document}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEstudianteTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('estudiante', function (Blueprint $table) {
$table->increments('id');
$table->string('codigo');
$table->unsignedInteger('programa_id');
$table->unsignedInteger('persona_id');
$table->unsignedInteger('estado_id');
$table->foreign('persona_id')->references('id')->on('persona');
$table->foreign('programa_id')->references('id')->on('programa');
$table->foreign('estado_id')->references('id')->on('estado');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('estudiante');
}
}
|
import axios from 'axios';
import React, { useState } from 'react'
import { useHistory } from 'react-router-dom';
const AddUser = () => {
let history = useHistory()
const [user,setUser] = useState({
name: "",
username: "",
email: "",
phone: "",
website: ""
});
const { name, username, email, phone, website } = user;
const onInputChange = (e)=>{
setUser({...user,[e.target.name]: e.target.value})
console.log(e.target.value);
}
const onSubmit = async (e)=>{
e.preventDefault();
await axios.post("http://localhost:3003/users", user)
history.push("/")
}
return (
<div className='container' >
<div className='w-75 mx-auto shadow p-5' >
<h2 className='text-center mb-4' >Add A User</h2>
<form onSubmit={e => onSubmit(e)} >
<div className="form-group pb-2">
<input type="text"
className='form-control form-control-lg '
placeholder='Enter your Name'
name="name"
value={name}
onChange={(e)=> onInputChange(e)}
/>
</div>
<div className="form-group pb-2">
<input type="text"
className='form-control form-control-lg'
placeholder='Enter your Username'
name="username"
value={username}
onChange={(e)=> onInputChange(e)}
/>
</div>
<div className="form-group pb-2">
<input type="text"
className='form-control form-control-lg'
placeholder='Enter your E-mail Address'
name="email"
value={email}
onChange={(e)=> onInputChange(e)}
/>
</div>
<div className="form-group pb-2">
<input type="text"
className='form-control form-control-lg'
placeholder='Enter your Phone Number'
name="phone"
value={phone}
onChange={(e)=> onInputChange(e)}
/>
</div>
<div className="form-group pb-2">
<input type="text"
className='form-control form-control-lg'
placeholder='Enter your Website Name'
name="website"
value={website}
onChange={(e)=> onInputChange(e)}
/>
</div>
<button className="btn btn-primary btn-lg btn-block mt-4">Add User</button>
</form>
</div>
</div>
)
}
export default AddUser
|
import { FunctionComponent, useEffect } from "react";
import { Table, TableHead, TableBody, TableCell, TablePagination, TableRow, TextField, Paper, FormControlLabel, Switch, Fab } from '@mui/material';
import { Link, useNavigate } from "react-router-dom";
import "./workerList.scss";
import { Worker } from "../../../models/worker";
import { getWorkers } from "../../../services/api.service";
import AddIcon from '@mui/icons-material/Add';
import { selectWorkers, selectWorkersFilter, updateWorkerFilter, updateWorkers } from "../../../store/workers";
import { useAppDispatch, useAppSelector } from "../../../store/hooks";
interface WorkersProps { }
// Define the component
const WorkersList: FunctionComponent<WorkersProps> = () => {
// Get the navigation function and dispatcher from the store
const navigator = useNavigate();
const dispatcher = useAppDispatch();
// Get the workers and filters from the store
const workers = useAppSelector(selectWorkers);
const filter = useAppSelector(selectWorkersFilter);
// Load the workers when the component mounts or when the filter changes
useEffect(() => {
getWorkers(filter).then((data: Array<Worker> | undefined) => {
if (data) {
dispatcher(updateWorkers(data));
}
});
}, [dispatcher, filter]);
// Handle changes to the filter inputs
const handleFilterChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
dispatcher(updateWorkerFilter({ ...filter, [name]: value, page: 0 }));
};
// Handle toggling the "archived" filter
const handleArchivedToggle = () => {
dispatcher(updateWorkerFilter({ ...filter, isArchived: !filter.isArchived, page: 0 }));
};
// Handle changing the page number
const handlePageChange = (event: React.MouseEvent<HTMLButtonElement> | null, page: number) => {
dispatcher(updateWorkerFilter({ ...filter, page }));
};
// Handle changing the number of rows per page
const handleCountChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const count = parseInt(event.target.value);
dispatcher(updateWorkerFilter({ ...filter, count, page: 1 }));
};
// Handle clicking on a row
const handleRowClick = (Id: string) => {
navigator('/workers/' + Id);
}
return (
<>
<div className="main-container d-flex m-4">
<Paper elevation={3} className="filters-container d-flex flex-column align-items-stretch gap-4 p-5">
<h1>Filter</h1>
<TextField
label="First name"
name="firstName"
value={filter.firstName}
onChange={handleFilterChange}
/>
<TextField label="Last name" name="lastName" value={filter.lastName} onChange={handleFilterChange} />
<TextField label="Job title" name="jobTitle" value={filter.jobTitle} onChange={handleFilterChange} />
<FormControlLabel
control={
<Switch
checked={filter.isArchived}
onChange={handleArchivedToggle}
color="primary"
/>
}
label={filter.isArchived ? 'Show active' : 'Show archived'}
/>
</Paper>
<Paper elevation={3} className="d-flex flex-column justify-content-between">
<Table className="w-100">
<TableHead>
<TableRow>
<TableCell>First name</TableCell>
<TableCell>Last name</TableCell>
<TableCell>Job title</TableCell>
<TableCell>City</TableCell>
</TableRow>
</TableHead>
<TableBody>
{workers.length === 0 ? (
<TableRow>
<TableCell colSpan={5} align="center">
No rows available
</TableCell>
</TableRow>
) : (
workers.map((worker) => (
<TableRow hover key={worker.Id} onClick={() => handleRowClick(worker.Id)} className="table-row">
<TableCell>{worker.FirstName}</TableCell>
<TableCell>{worker.LastName}</TableCell>
<TableCell>{worker.JobTitle}</TableCell>
<TableCell>{worker.City}</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
<TablePagination
rowsPerPageOptions={[10, 20, 30]}
component="div"
count={999}
rowsPerPage={filter.count}
page={filter.page}
onPageChange={handlePageChange}
onRowsPerPageChange={handleCountChange}
/>
</Paper>
</div>
<Link to="/workers/edit">
<Fab color="primary" aria-label="add" className="add-fab" >
<AddIcon />
</Fab>
</Link>
</>
);
}
export default WorkersList;
|
package dev.pwar.freelocationprovider.framework
import dev.pwar.freelocationprovider.data.SensorDataModelDataSource
import dev.pwar.freelocationprovider.domain.SensorDataModel
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
class InMemorySensorDataModelDataSource(
private var sensorData: SensorDataModel = SensorDataModel.SENSOR_DATA_MODEL_DEFAULT,
private var sensorDataFlow: MutableSharedFlow<SensorDataModel> = MutableSharedFlow(
extraBufferCapacity=2,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
): SensorDataModelDataSource {
override suspend fun set(sensorData: SensorDataModel) {
this.sensorData = sensorData
this.sensorDataFlow.emit(sensorData)
}
override fun get(): SensorDataModel {
return this.sensorData
}
override fun getFlow(): SharedFlow<SensorDataModel> {
return this.sensorDataFlow.asSharedFlow()
}
}
|
//Methods to call the DB api from front end
//Code adapted from week 8 lab repository.js
import axios from "axios";
const API_HOST = "http://localhost:4000/api";
const USER_KEY = "users";
const POST_KEY = "posts";
const REACTION_KEY = "reactions";
const FOLLOW_KEY = "follows";
// --- User Methods ---------------------------------------------------------------------------------------
async function verifyUser(email, password) {
const response = await axios.get(API_HOST + `/${USER_KEY}/login`, {
params: { email, password },
});
const user = response.data;
return user;
}
async function findUser(id) {
const response = await axios.get(API_HOST + `/${USER_KEY}/select/${id}`);
return response.data;
}
async function createUser(user) {
const response = await axios.post(API_HOST + `/${USER_KEY}`, user);
return response.data;
}
async function findUserByEmail(email) {
const response = await axios.get(
API_HOST + `/${USER_KEY}/selectemail/${email}`
);
return response.data;
}
async function findUserByName(username) {
const response = await axios.get(
API_HOST + `/${USER_KEY}/selectname/${username}`
);
return response.data;
}
async function deleteUser(user) {
var posts = await getPostsByUser(user.id);
posts.forEach((post) => {
// keep posts made by user that is being deleted, otherwise replies will break
deletePost(post);
});
deleteUserReactions(user.id);
const response = await axios.delete(API_HOST + `/${USER_KEY}/${user.id}`);
return response.data;
}
async function editUser(user) {
const response = await axios.put(API_HOST + `/${USER_KEY}`, user);
return response.data;
}
async function getUsers() {
const response = await axios.get(API_HOST + `/${USER_KEY}`);
return response.data;
}
// --- Follow Methods -----------------------------------------------------------------------------------
async function getFollows() {
const response = await axios.get(API_HOST + `/${FOLLOW_KEY}`);
return response.data;
}
// Select the ids of every user a specific user is following. (For sorting posts)
async function findFollowedUsers(id) {
const response = await axios.get(API_HOST + `/${FOLLOW_KEY}/user/${id}`);
return response.data;
}
// Select the ids of every user that is following the specified user (For seeing who is following you)
async function findFollowingUsers(id) {
const response = await axios.get(
API_HOST + `/${FOLLOW_KEY}/user/followers/${id}`
);
return response.data;
}
async function createFollow(follow) {
const response = await axios.post(API_HOST + `/${FOLLOW_KEY}`, follow);
return response.data;
}
async function deleteFollow(id) {
const response = await axios.delete(API_HOST + `/${FOLLOW_KEY}/${id}`);
return response.data;
}
// --- Post Methods ---------------------------------------------------------------------------------------
async function createPost(post) {
const response = await axios.post(API_HOST + `/${POST_KEY}`, post);
return response.data;
}
async function getPosts() {
const response = await axios.get(API_HOST + `/${POST_KEY}`);
return response.data;
}
async function updatePost(post) {
const response = await axios.put(API_HOST + `/${POST_KEY}/`, post);
return response;
}
async function deletePost(postToDelete) {
// doesnt actually delete, updates content and image to [deleted], preserving any replies the post had
const post = postToDelete;
post.content = "[deleted]";
post.image = "";
post.userId = 1;
// id 1 is a special user that holds ALL deleted posts, this makes it much easier to render deleted posts,
// as the code that displays user name can remain unchanged
const response = await axios.put(API_HOST + `/${POST_KEY}/`, post);
return response;
}
async function getRepliesTo(postId) {
const response = await axios.get(API_HOST + `/${POST_KEY}/replies/${postId}`);
return response.data;
}
async function getPostsByUser(id) {
const response = await axios.get(API_HOST + `/${POST_KEY}/user/${id}`);
return response.data;
}
// --- Reaction Methods -----------------------------------------------------------------------------------
async function getReactions() {
const response = await axios.get(API_HOST + `/${REACTION_KEY}`);
return response.data;
}
async function createReaction(reaction) {
reaction.id = null;
const response = await axios.post(API_HOST + `/${REACTION_KEY}`, reaction);
return response.data;
}
async function updateReaction(reaction) {
const response = await axios.put(API_HOST + `/${REACTION_KEY}/`, reaction);
return response;
}
async function deleteReaction(reaction) {
const response = await axios.delete(
API_HOST + `/${REACTION_KEY}/${reaction.id}`
);
return response;
}
async function deleteUserReactions(id) {
const response = await axios.delete(API_HOST + `/${REACTION_KEY}/user/${id}`);
return response;
}
export {
verifyUser,
findUser,
createUser,
findUserByEmail,
findUserByName,
deleteUser,
editUser,
getUsers,
getFollows,
findFollowedUsers,
findFollowingUsers,
createFollow,
deleteFollow,
createPost,
getPosts,
updatePost,
deletePost,
getRepliesTo,
getPostsByUser,
getReactions,
createReaction,
updateReaction,
deleteReaction,
};
|
from django.db import models
class ClassRoom(models.Model):
name: str = models.CharField(max_length=100, verbose_name='강의실 이름')
total_capacity: int = models.PositiveIntegerField(verbose_name='최대 수용 인원')
remaining_capacity: int = models.PositiveIntegerField(verbose_name='남은 수용 인원')
class Meta:
db_table = 'classroom'
verbose_name = '강의실'
verbose_name_plural = '강의실 목록'
def __str__(self):
return self.name
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forms Practice</title>
<link rel="stylesheet" href="/css/main.css" />
</head>
<body class="px-2">
<div class="card bg-base-200 max-w-[700px] mx-auto p-5 mt-6">
<form method="post" action="/submit-urlencoded">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
<!-- Hidden -->
<input type="hidden" name="hiddenSample" value="Hidden Field Value" />
<!-- Input -->
<div class="form-control">
<label class="label">
<span class="label-text">Input</span>
</label>
<input type="text" name="inputSample" placeholder="Type here" class="input input-bordered" />
</div>
<!-- Select -->
<div class="form-control">
<label class="label">
<span class="label-text">Select</span>
</label>
<select name="selectSample" class="select select-bordered w-full">
<option disabled="disabled" selected="selected">Choose an option</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</div>
<!-- Select -->
<div class="form-control">
<label class="label">
<span class="label-text">Select Multiple</span>
</label>
<select name="select-multipleSample" size="3" multiple
class="select-multiple text-sm w-full p-4 rounded-lg border border-solid border-slate-300">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</div>
<!-- textarea -->
<div class="form-control">
<label class="label">
<span class="label-text">Textarea</span>
</label>
<textarea name="textareaSample" class="textarea textarea-bordered h-24"></textarea>
</div>
<!-- Checkbox -->
<div class="form-control">
<label class="cursor-pointer label w-0">
<input name="checkboxSample" type="checkbox" class="checkbox" />
<span class="label-text ml-2">Checkbox</span>
</label>
</div>
<!-- Radio -->
<div class="form-control">
<label class="cursor-pointer label w-0">
<input type="radio" class="radio" name="radioSample" value="Option 1" />
<span class="label-text ml-2">Option 1</span>
</label>
<label class="cursor-pointer label w-0">
<input type="radio" class="radio" name="radioSample" value="Option 2" />
<span class="label-text ml-2">Option 2</span>
</label>
<label class="cursor-pointer label w-0">
<input type="radio" class="radio" name="radioSample" value="Option 3" />
<span class="label-text ml-2">Option 3</span>
</label>
</div>
</div>
<div class="grid grid-cols-1">
<!-- Buttons -->
<div class="form-control mt-6">
<button class="btn btn-primary">Submit Urlencoded Form</button>
</div>
</div>
</form>
</div>
<br />
<div class="card bg-base-200 max-w-[700px] mx-auto p-5 mt-6">
<form method="post" action="/submit-multipart" enctype="multipart/form-data">
<div class="grid grid-cols-1">
<!-- Input -->
<div class="form-control">
<label class="label">
<span class="label-text">File Description</span>
</label>
<input type="text" name="fileDescription" placeholder="Type here" class="input input-bordered" />
</div>
<!-- File -->
<div class="form-control">
<label class="label">
<span class="label-text">File</span>
</label>
<input type="file" name="fileSample" />
</div>
<!-- Buttons -->
<div class="form-control mt-6">
<button class="btn btn-success">Submit Multipart Form</button>
</div>
</div>
</form>
</div>
</body>
</html>
|
//
// MainCell.swift
// WeatherApp
//
// Created by Alexandr Ananchenko on 08.06.2022.
//
import UIKit
struct WeatherCellProtocol {
var city: String
var temp: Double?
var description: String?
var maxTemp: Double?
var minTemp: Double?
init(city: String, temp: Double?, description: String?, maxTemp: Double?, minTemp: Double?) {
self.city = city
self.temp = temp
self.description = description
self.maxTemp = maxTemp
self.minTemp = minTemp
}
}
class WeatherCell: UICollectionViewCell {
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var maxTempLabel: UILabel!
func setupCell(data: WeatherCellProtocol) {
cityLabel.text = data.city
descriptionLabel.text = data.description
if let temp = data.temp {tempLabel.text = "\(Int(temp))°"}
if let maxTemp = data.maxTemp, let minTemp = data.minTemp {
maxTempLabel.text = "Макс.: \(Int(maxTemp))°, мін.: \(Int(minTemp))°"
}
}
}
|
import { Button, Popover, Typography } from "@mui/material";
import React from "react";
import "./popoverButton.css";
interface ButtonPopoverProps {
answer: string;
}
const ButtonPopover = (props: ButtonPopoverProps) => {
const [anchorEl, setAnchorEl] =
React.useState<HTMLButtonElement | null>(null);
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const open = Boolean(anchorEl);
const id = open ? "simple-popover" : undefined;
return (
<div className={"buttonContainer"}>
<Button
size={"small"}
sx={{
backgroundColor: "black",
"&.MuiButtonBase-root:hover": {
bgcolor: "gray",
},
}}
aria-describedby={id}
variant="contained"
onClick={handleClick}
>
Reveal Answer!
</Button>
<Popover
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
>
<Typography sx={{ p: 2 }}>{props.answer}</Typography>
</Popover>
</div>
);
};
export default ButtonPopover;
|
import React, { useContext, useState } from 'react';
import { Button, Container, Form } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { AuthContext } from '../../../contexts/AuthProvider/AuthProvider';
import { toast } from 'react-hot-toast';
const Register = () => {
const {createUser,updateUserProfile,verifyEmail}=useContext(AuthContext)
const [accepted, setAccepted] = useState(false);
const [error,setError]=useState('');
const handleRegister=(event)=>{
event.preventDefault();
const form=event.target;
const name=form.name.value;
const photo=form.photo.value;
const email=form.email.value;
const password=form.password.value;
createUser(email,password)
.then((result)=>{
const user=result.user;
console.log(user)
setError('');
handleUpdateUserProfile(name,photo)
handleEmailVerify()
toast.success('please! verify your email address')
form.reset()
})
.catch((error)=>{
const errorMessage = error.message;
setError(errorMessage)
})
}
const handleUpdateUserProfile=(name,photoURL)=>{
const profile={
displayName:name,
photoURL:photoURL
}
updateUserProfile(profile)
.then(result=>{})
.catch((error)=>console.log(error))
}
const handleEmailVerify=()=>{
verifyEmail()
.then(()=>{})
.catch((error)=>{
console.error(error)
})
}
const handleChecked=(event)=>{
setAccepted(event.target.checked)
}
return (
<Container>
<h3>Please register</h3>
<Form onSubmit={handleRegister}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Name</Form.Label>
<Form.Control type="text" name='name' placeholder="Your Name" required />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Photo URL</Form.Label>
<Form.Control type="text" name='photo' placeholder="Photo URL" required />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" name='email' placeholder="Enter email" required />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" name='password' placeholder="Password" required />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCheckbox">
<Form.Check
type="checkbox"
onClick={handleChecked}
name="accept"
label={<>Accept <Link to="/terms">Terms and Conditions</Link> </>} />
</Form.Group>
<Button variant="primary" type="submit" disabled={!accepted}>
Register
</Button>
<br />
<Form.Text className="text-success">
</Form.Text>
<Form.Text className="text-danger">
{error}
</Form.Text>
<br />
<Form.Text className="text-secondary">
Already Have an Account? <Link to="/login">Login</Link>
</Form.Text>
</Form>
</Container>
);
};
export default Register;
|
# 50. Pow(x, n)
# Solved
# Medium
# Topics
# Companies
# Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
# Example 1:
# Input: x = 2.00000, n = 10
# Output: 1024.00000
# Example 2:
# Input: x = 2.10000, n = 3
# Output: 9.26100
# Example 3:
# Input: x = 2.00000, n = -2
# Output: 0.25000
# Explanation: 2-2 = 1/22 = 1/4 = 0.25
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
# if n == 0:
# return 1
# if x == 0:
# return 0
# if n > 0:
# if n %2 == 0:
# return self.myPow(x,n//2) * self.myPow(x,n//2)
# else:
# return self.myPow(x,n//2) * self.myPow(x,n//2) * x
# elif n < 0:
# n = -n
# if n %2 == 0:
# return 1/(self.myPow(x,n//2) * self.myPow(x,n//2) )
# else:
# return 1/ (self.myPow(x,n//2) * self.myPow(x,n//2) * x)
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
if n > 0:
half_pow = self.myPow(x, n // 2)
return half_pow * half_pow if n % 2 == 0 else half_pow * half_pow * x
else: # n < 0
n = -n
half_pow = self.myPow(x, n // 2)
return 1 / (half_pow * half_pow) if n % 2 == 0 else 1 / (half_pow * half_pow * x)
|
import {
Location,
Provider,
Route,
RouteLocations,
PlaceType,
} from "@rapidroute/database-types"
import getLegacyData from "./getSheetData"
/**
* update string to be a valid firebase key
*
* can't contain ".", "#", "$", "[", "]", or "/" or "\"
* replace those with "_1", "_2", "_3", "_4", etc.
* also replace " " with "_" and "_" with "__"
*
* @param str
* @returns
*/
const makeKeySafe = (str: string) => {
return str
.replace(/_/g, "__")
.replace(/\./g, "_1")
.replace(/#/g, "_2")
.replace(/\$/g, "_3")
.replace(/\[/g, "_4")
.replace(/\]/g, "_5")
.replace(/\//g, "_6")
.replace(/\\/g, "_7")
.replace(/ /g, "_")
}
/**
* take the old data format (from RapidRoute 2) and convert it to the new format
*/
export default async function getConvertedData() {
const {
routes,
places,
providers,
aliases,
spawnWarps,
lightColors,
darkColors,
logos,
placeLocations,
} = await getLegacyData()
const routesToIgnore: string[] = []
const mappedRoutes: Route[] = routes
.map(route => {
const routeNumber = route.number || undefined
// first, we need an unique id for the route that will always be the same
const placeA = route.from > route.to ? route.to : route.from
const placeB = route.from > route.to ? route.from : route.to
const provider = route.provider ?? `unknown${route.from}${route.to}`
const routeId = makeKeySafe(
`${provider}-${routeNumber ?? placeA + placeB}`
)
// if we've already seen this route, ignore it the second time
if (routesToIgnore.includes(routeId)) {
return undefined
}
routesToIgnore.push(routeId)
// and collect locations and gate info for the route
const routesWithSameNumber = routes.filter(
y => y.number === route.number && y.provider === route.provider
)
let locations: RouteLocations = {}
const gates: Record<string, string> = {}
routesWithSameNumber.forEach(y => {
locations[makeKeySafe(y.from)] = y.fromGate ?? "none"
const fromGate = gates[y.from] || y.fromGate
if (fromGate) gates[y.from] = fromGate
const toGate = gates[y.to] || y.toGate
if (toGate) gates[y.to] = toGate
})
// with a fallback for MRT stations bc they're special
if (route.mode === "MRT") {
locations = {
[makeKeySafe(route.from)]: "none",
[makeKeySafe(route.to)]: "none",
}
}
const mappedRoute: Route = {
uniqueId: routeId,
autoGenerated: true,
name: undefined,
description: undefined,
locations,
provider: makeKeySafe(route.provider ?? ""),
type: route.mode,
number: routeNumber || undefined,
numGates: Object.keys(gates).length || undefined,
}
return mappedRoute
})
.flatMap(x => (x ? [x] : []))
const mappedLocations: Location[] = places.map(place => {
const locationFromMap = place.shortName
? placeLocations[place.shortName]
: undefined
let locationType: PlaceType = "Other"
if (place.type === "MRT") locationType = "MRT Station"
if (place.type === "airport") locationType = "Airport"
if (place.type === "town") locationType = "City"
const location: Location = {
uniqueId: makeKeySafe(place.id),
name:
place.displayName ??
place.longName ??
place.shortName ??
"Untitled Location",
shortName: place.shortName ?? place.id,
description: undefined,
enabled: true,
IATA: place.type === "airport" ? place.shortName || undefined : undefined,
location:
place.x && place.z
? {
x: locationFromMap?.x ?? place.x,
z: locationFromMap?.z ?? place.z,
y: locationFromMap?.y ?? undefined,
}
: undefined,
ownerPlayer: undefined,
keywords: place.keywords ?? undefined,
world: place.world,
autoGenerated: true,
isSpawnWarp: spawnWarps.includes(place.id),
type: locationType,
routes: routes
.filter(y => y.from === place.id || y.to === place.id)
.map(y => {
const placeA = y.from > y.to ? y.to : y.from
const placeB = y.from > y.to ? y.from : y.to
const provider = y.provider ?? `unknown${y.from}${y.to}`
const routeId = makeKeySafe(
`${provider}-${y.number ?? placeA + placeB}`
)
return routeId
})
.filter((value, index, self) => self.indexOf(value) === index),
}
return location
})
const mappedProviders: Provider[] = providers.map(provider => {
const newProvider: Provider = {
uniqueId: makeKeySafe(provider.name),
name: provider.displayName ?? provider.name,
alias: aliases
.filter(x => x.actualProvider === provider.name)
.map(x => ({
displayProvider: makeKeySafe(x.displayProvider),
numberRange: {
start: x.start,
end: x.end,
},
})),
color: {
light: lightColors[provider.name] ?? undefined,
dark: darkColors[provider.name] ?? undefined,
},
description: undefined,
logo: logos[provider.name] ?? undefined,
numberPrefix: provider.prefix ?? undefined,
ownerPlayer: undefined,
autoGenerated: true,
}
return newProvider
})
return {
routes: mappedRoutes,
locations: mappedLocations,
providers: mappedProviders,
}
}
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\User\StoreRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register', 'refresh']]);
}
public function register(StoreRequest $request): JsonResponse
{
try {
DB::beginTransaction();
$data = $request->validated();
if ($data['password'] != $data['repeatPassword']) {
throw new \Exception("Repeated password mismatch");
}
unset($data['repeatPassword']);
$data['role'] = 'USER';
$user = User::create($data);
DB::commit();
return response()->json(['message' => "{$user->name} was created"], 201);
} catch (\Exception $exception) {
DB::rollBack();
return response()->json(['error' => $exception->getMessage()], 401);
}
}
/**
* Get a JWT via given credentials.
*
* @return JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return JsonResponse
*/
public function me(): JsonResponse
{
$data = auth()->user();
unset($data['email'], $data['deleted_at'], $data['created_at'], $data['updated_at']);
return response()->json(['user' => $data]);
}
/**
* Log the user out (Invalidate the token).
*
* @return JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
|
use crate::tests_and_benchmarks::ozk::rust_shadows as tasm;
fn main() {
let i: u32 = tasm::tasmlib_io_read_stdin___bfe().value() as u32;
let a: u32 = {
let b: u32 = 100;
let c: u32 = 200;
let j: u32 = tasm::tasmlib_io_read_stdin___bfe().value() as u32;
let k: u32 = tasm::tasmlib_io_read_stdin___bfe().value() as u32;
let d: u32 = 400u32;
b + c + d + i + j * k
};
tasm::tasmlib_io_write_to_stdout___u32(a);
return;
}
#[cfg(test)]
mod test {
use tasm_lib::triton_vm::prelude::*;
use crate::tests_and_benchmarks::ozk::ozk_parsing::EntrypointLocation;
use crate::tests_and_benchmarks::ozk::rust_shadows;
use crate::tests_and_benchmarks::test_helpers::shared_test::*;
use super::*;
#[test]
fn returning_block_expr_u32_test() {
// Test function on host machine
let i: u32 = 15;
let j: u32 = 16;
let k: u32 = 32;
let stdin = vec![
BFieldElement::new(i as u64),
BFieldElement::new(j as u64),
BFieldElement::new(k as u64),
];
let non_determinism = NonDeterminism::new(vec![]);
let expected_output = vec![BFieldElement::new(100 + 200 + 400 + 15 + 16 * 32)];
let native_output =
rust_shadows::wrap_main_with_io(&main)(stdin.clone(), non_determinism.clone());
assert_eq!(native_output, expected_output);
// Test function in Triton VM
let entrypoint_location =
EntrypointLocation::disk("other", "returning_block_expr_u32", "main");
let parsed = entrypoint_location.extract_entrypoint();
let expected_stack_diff = 0;
let vm_output = execute_with_stack_and_ins_safe_lists(
&parsed,
vec![],
stdin,
NonDeterminism::new(vec![]),
expected_stack_diff,
)
.unwrap();
assert_eq!(expected_output, vm_output.public_output);
}
}
|
#!/usr/bin/env bash
#
# Based mostly on the Switchboard recipe. The training database is TED-LIUM,
# it consists of TED talks with cleaned automatic transcripts:
#
# https://lium.univ-lemans.fr/ted-lium3/
# http://www.openslr.org/resources (Mirror).
#
# The data is distributed under 'Creative Commons BY-NC-ND 3.0' license,
# which allow free non-commercial use, while only a citation is required.
#
# Copyright 2014 Nickolay V. Shmyrev
# 2014 Brno University of Technology (Author: Karel Vesely)
# 2016 Vincent Nguyen
# 2016 Johns Hopkins University (Author: Daniel Povey)
# 2018 François Hernandez
#
# Apache 2.0
#
# Project by Alexander Jermann (apj2125)
#
### Settings ###
. ./path.sh || exit 1
. ./cmd.sh || exit 1
set -e -o pipefail -u
nj=8
decode_nj=8
lm_order=3
stage=0
train_rnnlm=false
train_lm=true
. utils/parse_options.sh || exit 1
[[ $# -ge 1 ]] && { echo "Wrong arguments!"; exit 1; }
# delete MFCC
rm -rf exp data/miami/train/cmvn.scp data/miami/train/feats.scp data/miami/train/split8 data/miami/test/cmvn.scp data/miami/test/feats.scp data/miami/test/split8 data/local/lang data/lang data/local/tmp data/local/dict/lexiconp.txt
### Stages ###
echo
echo "===== PREPARING ACOUSTIC DATA ====="
echo
# Needs to be prepared by hand (or using self written scripts):
#
# spk2gender [<speaker-id> <gender>]
# wav.scp [<uterranceID> <full_path_to_audio_file>]
# text [<uterranceID> <text_transcription>]
# utt2spk [<uterranceID> <speakerID>]
# corpus.txt [<text_transcription>]
if [ $stage -le 0 ]; then
# ====== Download Miami =======
# local/download_miami_data.sh
# python3 local/process_miami_data.py
# python3 local/create_test_sets.py
# INSERT script to add absolute path to wav.scp
# local/download_miami_data_kaldi.sh
# local/fix_utt2spk.sh
# utils/utt2spk_to_spk2utt.pl data/miami/bangortalk/utt2spk > data/miami/bangortalk/spk2utt
# cat data/miami/bangortalk/text_cs data/miami/bangortalk/text_en data/miami/bangortalk/text_spa > data/miami/bangortalk/text
# sort -o data/miami/bangortalk/text data/miami/bangortalk/text
# local/make_train_test.sh
# Verify Data directory
utils/validate_data_dir.sh --no-feats data/miami/train || exit 1
utils/validate_data_dir.sh --no-feats data/miami/test || exit 1
# ==== Set-Up Commonvoice =====
#local/download_commonvoice.sh
fi
echo
echo "===== FEATURES EXTRACTION ====="
echo
if [ $stage -le 1 ]; then
for set in test train; do
dir=data/miami/$set
steps/make_mfcc.sh --nj $nj --cmd "$train_cmd" $dir
steps/compute_cmvn_stats.sh $dir
done
fi
echo
echo "===== PREPARING LANGUAGE DATA ====="
echo
# Needs to be prepared by hand (or using self written scripts):
#
# lexicon.txt [<word> <phone 1> <phone 2> ...]
# nonsilence_phones.txt [<phone>]
# silence_phones.txt [<phone>]
# optional_silence.txt [<phone>]
# Preparing language data
if [ $stage -le 2 ]; then
# local/prepare_dict.sh
# Check that data dirs are okay!
utils/validate_dict_dir.pl data/local/dict || exit 1
fi
if [ $stage -le 3 ]; then
utils/prepare_lang.sh data/local/dict "<unk>" data/local/lang data/lang
fi
echo
echo "===== TRAINING LM ====="
echo "===== MAKING lm.arpa ====="
echo
if [ $stage -le 4 ]; then
loc=`which ngram-count`;
if [ -z $loc ]; then
if uname -a | grep 64 >/dev/null; then
sdir=$KALDI_ROOT/tools/srilm/bin/i686-m64
else
sdir=$KALDI_ROOT/tools/srilm/bin/i686
fi
if [ -f $sdir/ngram-count ]; then
echo "Using SRILM language modelling tool from $sdir"
export PATH=$PATH:$sdir
else
echo "SRILM toolkit is probably not installed.
Instructions: tools/install_srilm.sh"
exit 1
fi
fi
local=data/local
mkdir $local/tmp
ngram-count -order $lm_order -write-vocab $local/tmp/vocab-full.txt -wbdiscount -text $local/corpus.txt -lm $local/tmp/lm.arpa
fi
echo
echo "===== MAKING G.fst ====="
echo
arpa2fst --disambig-symbol=#0 --read-symbol-table=data/lang/words.txt data/local/tmp/lm.arpa data/lang/G.fst
echo
echo "===== MONO TRAINING ====="
echo
steps/train_mono.sh --nj $nj --cmd "$train_cmd" data/miami/train data/lang exp/mono || exit 1
echo
echo "===== MONO DECODING ====="
echo
utils/mkgraph.sh --mono data/lang exp/mono exp/mono/graph || exit 1
steps/decode.sh --config conf/decode.config --nj $nj --cmd "$decode_cmd" exp/mono/graph data/miami/test exp/mono/decode
echo
echo "===== MONO ALIGNMENT ====="
echo
steps/align_si.sh --nj $nj --cmd "$train_cmd" data/miami/train data/lang exp/mono exp/mono_ali || exit 1
echo
echo "===== TRI1 (first triphone pass) TRAINING ====="
echo
steps/train_deltas.sh --cmd "$train_cmd" 2000 11000 data/miami/train data/lang exp/mono_ali exp/tri1 || exit 1
echo
echo "===== TRI1 (first triphone pass) DECODING ====="
echo
utils/mkgraph.sh data/lang exp/tri1 exp/tri1/graph || exit 1
steps/decode.sh --config conf/decode.config --nj $nj --cmd "$decode_cmd" exp/tri1/graph data/miami/test exp/tri1/decode
echo
echo "===== run.sh script is finished ====="
echo
echo "$0: success."
exit 0
|
---
title: MySQL笔记6-视图
date: 2023-07-18
sidebar: 'auto'
categories:
- 数据库
tags:
- MySql
---
[toc]
# MySQL笔记6-视图
视图(View)是一种虚拟存在的表,同真实表一样,视图也由列和行构成,但视图并不实际存在于数据库中。视图中行和列的数据来自于定义视图的SELECT查询语句,并且还是在使用视图时动态生成的。视图的本质是SELECT语句。
数据库中只存放了视图的定义,并没有存放视图中的数据,这些数据都存放在定义视图查询所引用的真实表中。使用视图查询数据时,数据库会从真实表中取出对应的数据。因此,视图中的数据是依赖于真实表中的数据的。一旦真实表中的数据发生改变,显示在视图中的数据也会发生改变。
> 视图与表的区别?
* 视图不是数据库中真实的表,而是一张虚拟表,其结构和数据是建立在对真实表的查询基础上的。
* 视图是数据的窗口,而表是内容。表是实际数据的存放单位,而视图只是以不同的显示方式展示数据,其数据来源还是实际表。
* 从安全的角度来看,视图的数据安全性更高,使用视图的用户不接触数据表,不知道表结构。
* 视图的建立和删除只影响视图本身,不影响对应的基本表。
> 视图的作用?
* 简化复杂的SQL操作。在编写查询后,可以方便的重用它而不必知道它的基本查询细节;使用表的组成部分而不是整个表;
* 保护数据。可以给用户授予表的特定部分的访问权限而不是整个表的访问权限;
* 更改数据格式和表示。视图可返回与底层表的表示和格式不同的数据
## 创建视图
```sql
# 语法如下
CREATE VIEW <视图名> AS <SELECT语句>
# 创建视图view_students,数据是年龄大于12的学生信息
CREATE VIEW view_students AS SELECT * FROM students where age > 12;
# 创建视图v_students_info,设置了视图中的字段
CREATE VIEW v_students_info (s_id,s_name,d_id,s_age,s_sex,s_height,s_date) AS SELECT id,name,dept_id,age,sex,height,login_date FROM tb_students_info;
# 使用视图view_students
select * from view_students;
```
## 查看视图
创建好视图后,可以通过查看视图的语句来查看视图的字段信息以及详细信息。
<font color="red">所有视图的定义都是存储在 information_schema 数据库下的 views 表中。</font>
```sql
# 语法如下
DESCRIBE 视图名;
# 或
DESC 视图名;
# 查询视频详细信息
SHOW CREATE VIEW 视图名;
# 查看视图v_studentinfo
mysql> DESC v_studentinfo;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
| score | decimal(4,2) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
# 查看视图v_studentinfo的详细信息
SHOW CREATE VIEW v_studentinfo;
```
## 修改视图
当表的某些字段发生变化时,可以通过修改视图来保持与表的一致性。
<font color="red">注意:对视图的修改只影响视图本身,不影响对应的基本表。</font>
```sql
# 语法如下
ALTER VIEW <视图名> AS <SELECT语句>
# 修改视图 view_students_info
ALTER VIEW view_students_info AS SELECT id,name,age FROM tb_students_info;
# 查询视图数据
SELECT * FROM view_students_info;
```
## 删除视图
对视图的删除只影响视图本身,不影响对应的基本表。
```sql
# 语法如下
DROP VIEW <视图名>
# 删除视图 view_students_info
DROP VIEW v_students_info;
```
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cheesus Crust Pizza</title>
<link rel="stylesheet" href="/public/style.css" />
<link rel="stylesheet" href="/public/menu-style.css" />
<link rel="stylesheet" href="/public/slideshow-style.css" />
<link rel="stylesheet" href="/public/pizza-cards-style.css" />
<link rel="stylesheet" href="/public/allergens-style.css" />
<link rel="stylesheet" href="/public/footer-style.css" />
<script src="/public/script.js"></script>
<script src="/public/slideshow-script.js"></script>
</head>
<body>
<nav>
<div class="menu-button-container">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
<h1 id="title">Cheesus Crust</h1>
<img
src="/public/shopping-cart.png"
alt="shopping cart"
id="shopping-cart"
/>
<ul id="menu-list" class="hide">
<li class="menu-list-item">
<a class="menu-link" href="#title">Welcome</a>
</li>
<li class="menu-list-item">
<a class="menu-link" href="#about">About</a>
</li>
<li class="menu-list-item">
<a class="menu-link" href="#menu">Our Menu</a>
</li>
<li class="menu-list-item">
<a class="menu-link" href="#our-story">Story</a>
</li>
<li class="menu-list-item">
<a class="menu-link" href="#contact">Contact</a>
</li>
</ul>
</nav>
<div class="hide" id="order-list">
<span class="total">Total Amount : 0</span>
<a id="order" href="/order">ORDER NOW</a>
</div>
<span id="number-of-products">0</span>
<!-- Slideshow container -->
<div id="welcome" class="slideshow-container">
<!-- Full-width images with number and caption text -->
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="/public/images/img1.jpg" style="width: 100%" />
<div class="text">Peperoni Pizza</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="/public/images/img2.jpg" style="width: 100%" />
<div class="text">Meat Pizza</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="/public/images/img3.jpg" style="width: 100%" />
<div class="text">Pizza Pie</div>
</div>
<!-- Next and previous buttons -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br />
<!-- The dots/circles -->
<div style="text-align: center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
<section id="about">
<h2>About</h2>
<img class="about" src="/public/images/img4.jpg" alt="about" />
</section>
<h2 id="menu">Menu</h2>
<div class="allergens-filter-button">Filter By Allergens</div>
<div class="hide allergens-container"></div>
<div id="root"></div>
<section id="our-story">
<h2>Our Story</h2>
<div>
<img
class="about"
src="/public/images/img5.jpg"
alt="pizza image"
/>
<div>
<h3>We make the best Pizza in your town</h3>
<p>
Cheesus Crust - is an American catering company.
Operates the world's largest chain of pizzerias. The
network, represented in 85 countries and including 15900
restaurants, sells more than 3 million pizzas per day.
The company owns 390 restaurants in the US, the rest are
franchised.
</p>
</div>
</div>
</section>
<footer id="contact">
<h2>Contact</h2>
<div class="footer-wrapper">
<h3>Cheesus Crust</h3>
<div class="footer-div">
<p><a class="footer-link" href="#title">Welcome</a></p>
<p><a class="footer-link" href="#menu">Our Menu</a></p>
<p><a class="footer-link" href="#about">About</a></p>
<p><a class="footer-link" href="#our-story">Story</a></p>
</div>
<p>Order & Information: 0741889876</p>
</div>
<p>Working mode: Daily in 11:00-20:30</p>
</footer>
</body>
</html>
|
import React, { useState, useContext } from "react";
import{Link } from 'react-router-dom'
import { LOGO_URL } from "../utills/contants";
import useOnlineStatus from "../utills/useOnlineStatus";
import UserContext from "../utills/UserContext";
const Header = () => {
const [logButton, setLogButton] = useState("Log In");
const onlineStatus = useOnlineStatus();
const {loggedinUser} = useContext(UserContext);
return (
<div className="flex justify-between px-8 shadow-md">
<div>
<img src={LOGO_URL} alt="Logo" className="w-24" />
</div>
<ul className="flex items-center ">
<li>Online Status : {onlineStatus ? "🟢":"🔴"}</li>
<li className="p-4 m-2"> <Link to="/">Home</Link></li>
<li className="p-4 m-2"> <Link to='/About'>About Us</Link></li>
<li className="p-4 m-2"><Link to= "/Contact">Contact Us</Link></li>
<li className="p-4 m-2"><Link to= "/grocery">Grocery</Link></li>
<li className="p-4 m-2">Cart</li>
<button
className="p-4 m-2"
onClick={() => {
logButton === "Log In"
? setLogButton("Log Out")
: setLogButton("Log In");
}}
>
{logButton}
</button>
<li className="p-4 m-2 font-bold"> User : {loggedinUser}</li>
</ul>
</div>
);
};
export default Header;
|
= Проект TaskManagerServer
Проект TaskManagerServer - это микросервис для обработки логики планирования и управления задачами.
== Использование
Для запуска приложения и базы данных выполните следующие шаги:
1) Установите Docker и Docker Compose.
2) Запустите контейнеры Docker с помощью команды `docker-compose up`.
3) Установите переменную окружения DB_CONN со значением postgresql://postgres:postgres@localhost:5433/test?sslmode=disable
4) Примените миграции базы данных с помощью утилиты Migrate
[source,shell]
----
migrate -path ./schema -database 'postgres://postgres:123321@localhost:5433/test?sslmode=disable' up
----
5) Запустите приложение, используя команду `go run cmd/taskmanagerserver/main.go`.
== API
API предоставляет следующие ресурсы:
=== Получение списка дел пользователя
Метод: `GET`
Путь: `/api/todos/:id`
Описание: Получает список дел пользователя по id пользователя.
Ответ:
- Код 200 (OK) со структурой `Todos []TodoJson` - список дел.
=== Создание новой задачи пользователя
Метод: `POST`
Путь: `/api/createtodo`
Описание: Создает новую задачу пользователя
Параметры:
- Тело запроса (тип: `rest.CreateTodoBody`)
Ответ:
- Код 200 (OK) со структурой `"message": "todo created"` - информация об успешном создании.
=== Удаление задачи пользователя
Метод: `DELETE`
Путь: `/api/deletetodo/:id`
Описание: Удаляет выбранную задачу пользователя по id задачи.
Ответ:
- Код 200 (OK) со структурой `"message": "todo deleted"` - информация об успешном удалении.
=== Обновление задачи пользователя
Метод: `PUT`
Путь: `"/api/changetodo"`
Описание: Обнвовляет данные задачи.
Параметры:
- Тело запроса (тип: `rest.ChangeTodoBody`).
Ответ:
- Код 200 (OK) со структурой `"message": "todo changed"` - информация об успешном измении.
|
---
version:
- Cloud
---
= CircleCI Free Plan
:page-layout: classic-docs
:page-liquid:
:page-description: This document describes the Free plan available to developers on CircleCI.
:icons: font
:toc: macro
:toc-title:
:orbs:
This document describes the Free plan available to developers.
== Free plan
As with the CircleCI legacy Container plan, CircleCI also supports a free-tier with the usage-based plan. By using the Free plan, you can take advantage of a large number of premium features that will allow your team to be more productive, efficient, and fast.
The Free usage-based plan offers a set amount of credits across a variety of resource classes, per month, which you can customize depending on your build configuration and execution environment. With this combination, a small number of credits are charged per minute and there is no limit on user seats.
The Free plan offers *unlimited users* - there is no limit to the number of users who can build and develop on CircleCI. This allows you to collaborate with different teams and groups within your organization (or open source) on multiple projects, increasing speed, productivity, and efficiency. With an unlimited number of users, you will have to manage your credit allotment accordingly, as there is a set amount of network and storage usage available.
Below are the features you can use on the Free plan. Refer to the https://circleci.com/pricing/[Pricing] page for more detailed information on credit amounts, included resource classes, key features, and support. Refer to the https://circleci.com/product/features/resource-classes/[Resource class features] page for details on CPU, memory, network and storage, and credit usage for compute type on execution environments.
NOTE: Please note, for the Free plan, resource classes on macOS are *coming soon*.
=== Available resource classes
A wide array of resource classes on Docker, Linux, Windows, and macOS are available to use. This flexibility helps ensure that you choose the right compute resources. To view examples, or find more information about these executors, please refer to the the <<executor-intro#,Executors and Images>> page.
{% include snippets/features-of-circleci.adoc %}
=== Support
Support is available through the https://discuss.circleci.com/[community forums], https://support.circleci.com/hc/en-us[support portal], and our https://support.circleci.com/hc/en-us/requests/new[global ticket-based system].
|
import { Avatar, Button, DialogActions, makeStyles } from '@material-ui/core'
import { connect } from 'react-redux'
import { useContext } from 'react'
import { Formik } from 'formik'
import DialogProgress from 'library/components/DialogProgress'
import UserContext from 'library/contexts/UserContext'
import devBuild from 'library/utilities/devBuild'
import Dialog from 'library/components/Dialog'
const useStyles = makeStyles((theme) => ({
uploadButton: {
marginLeft: theme.spacing(2),
width: 88
}
}))
function PasswordIconDialog({ id, dialog, closeDialog, setIcon, removeIcon }) {
const { open, payload: password } = dialog
const classes = useStyles()
const user = useContext(UserContext)
const iconURL = `https://aspire.icu/ss/${user.username}/icons/${password?.icon}`
const onSubmit = (values, { setSubmitting }) => {
setTimeout(() => {
if (values.icon === null) {
removeIcon({
id: password.id,
onSuccess: () => closeDialog(),
onFail: () => setSubmitting(false)
})
} else {
setIcon({
id: password.id,
icon: values.icon,
onSuccess: () => closeDialog(),
onFail: () => setSubmitting(false)
})
}
}, 500)
}
return (
<Dialog
open={open === id}
title='Change Icon'
marginBottom='12px'
onClose={closeDialog}
>
<Formik
initialValues={{ icon: password?.icon === null ? password?.icon : iconURL }}
onSubmit={onSubmit}
>
{({ submitForm, isSubmitting, values, setValues }) => (<>
<div style={{ display: 'flex', flexDirection: 'row' }}>
<input
style={{ display: 'none' }}
onChange={({ target }) => {
const fileReader = new FileReader()
fileReader.readAsDataURL(target.files[0])
fileReader.onload = (e) => setValues({ icon: e.target.result })
}}
id='icon-button'
accept='image/*'
type='file'
/>
{
values.icon === null ? (
<label htmlFor='icon-button' style={{ display: 'flex', flexDirection: 'row' }}>
<Avatar src={`https://aspire.icu:${devBuild ? '98' : '97'}/passwords/icon?site=${password?.site}`}>
{password?.site[0].toUpperCase()}
</Avatar>
<Button variant='outlined' component='span' className={classes.uploadButton}>
Upload
</Button>
</label>
) : (<>
<Avatar src={values.icon}>
{password?.site[0].toUpperCase()}
</Avatar>
<Button
onClick={() => setValues({ icon: null })}
variant='outlined'
component='span'
className={classes.uploadButton}
>
Reset
</Button>
</>)
}
</div>
<DialogProgress visible={isSubmitting} />
<DialogActions>
<Button variant='text' disabled={isSubmitting} onClick={closeDialog} color='primary'>Cancel</Button>
<Button variant='contained' type='submit' disabled={isSubmitting} onClick={submitForm} color='primary'>Confirm</Button>
</DialogActions>
</>)}
</Formik>
</Dialog>
)
}
const mapState = (state) => ({
dialog: state.dialog
})
const mapDispatch = (dispatch) => ({
closeDialog: dispatch.dialog.close,
setIcon: dispatch.passwords.setIcon,
removeIcon: dispatch.passwords.removeIcon
})
export default connect(mapState, mapDispatch)(PasswordIconDialog)
|
import Image from "next/image";
import SectionHeader from "./SectionHeader";
async function getData() {
const res = await fetch(process.env.BASE_URL + "api/TestimonialList");
if (!res.ok) {
throw new Error("Testimonial Data Calling Fail");
}
return res.json();
}
export default async function AllTestimonial() {
const data = await getData();
return (
<section className=" py-16">
<div className="container mx-auto px-6 md:px-0 lg:px-0">
<SectionHeader
sectionHeader={{
title: "Testimonial List",
desc: "Better Agency/SEO Solution At Your Fingertips",
}}
/>
<div className=" grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8 pt-10 lg:pt-14">
{data.map((item) => {
return (
<div
key={item["id"]}
className=" shadow-lg p-5 lg:p-7"
>
<div className=" rounded-lg overflow-hidden w-[100px] mx-auto">
<Image
src={item.image}
width={150}
height={150}
alt={item["name"]}
/>
</div>
<div className=" py-5">
<p className=" text-center text-neutral-500">
{item["msg"]}
</p>
</div>
<div className="text-center">
<h3 className=" text-2xl font-bold uppercase">
{item["name"]}
</h3>
<p className=" font-semibold pt-3">
{item["designation"]}
</p>
</div>
</div>
);
})}
</div>
</div>
</section>
);
}
|
package org.freakz.data.repository;
import lombok.extern.slf4j.Slf4j;
import org.freakz.common.model.dto.DataJsonSaveContainer;
import org.freakz.common.model.dto.DataNodeBase;
import org.freakz.common.model.dto.UserValuesJsonContainer;
import org.freakz.common.model.users.User;
import org.freakz.config.ConfigService;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@Slf4j
public class UsersRepositoryImpl extends RepositoryBaseImpl implements UsersRepository, DataSavingService {
private static final String USERS_FILE_NAME = "users.json";
public UsersRepositoryImpl(ConfigService configService) throws Exception {
super(configService);
initialize();
// createUsers();
}
public void initialize() throws Exception {
File dataFile = configService.getRuntimeDataFile(USERS_FILE_NAME);
if (dataFile.exists()) {
UserValuesJsonContainer dataValuesJson = mapper.readValue(dataFile, UserValuesJsonContainer.class);
this.dataValues.addAll(dataValuesJson.getData_values());
long highestId = -1;
for (DataNodeBase values : this.dataValues) {
if (values.getId() > highestId) {
highestId = values.getId();
}
}
this.highestId = highestId;
log.debug("Read dataValues, size: {} - highestId: {}", this.dataValues.size(), this.highestId);
} else {
log.debug("No saved dataValues found: {}", dataFile.getName());
}
}
private void createUsers() {
this.dataValues.add(getJohnDoeUser());
User user
= User.builder()
.isAdmin(true)
.name("Petri Airio")
.email("petri.j.airio@gmail.com")
.ircNick("_Pete_")
.discordId("265828694445129728")
.telegramId("138695441")
.build();
user.setId(++highestId);
this.dataValues.add(user);
isDirty = true;
}
public void saveDataValues() throws IOException {
synchronized (this.dataValues) {
String dataFileName = configService.getRuntimeDataFileName(USERS_FILE_NAME);
log.debug("synchronized start writing values: {}", dataFileName);
DataJsonSaveContainer container
= DataJsonSaveContainer.builder()
.data_values(this.dataValues)
.build();
container.setSaveTimes(container.getSaveTimes() + 1);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(container);
Files.writeString(Path.of(dataFileName), json, Charset.defaultCharset());
log.debug("synchronized block write done: {}", this.dataValues.size());
}
}
@Override
public void checkIsSavingNeeded() {
if (this.saveTrigger >= 0) {
this.saveTrigger = this.saveTrigger - 100;
}
if (isDirty) {
if (saveTrigger <= 0) {
try {
saveDataValues();
isDirty = false;
} catch (IOException e) {
log.error("Saving data values failed", e);
}
}
}
}
@Override
public DataSaverInfo getDataSaverInfo() {
DataSaverInfo info
= DataSaverInfo.builder()
.nodeCount(this.dataValues.size())
.name("UsersData")
.build();
return info;
}
private User getJohnDoeUser() {
User user = User.builder()
.isAdmin(false)
.name("John Doe")
.email("none@invalid")
.ircNick("none")
.telegramId("none")
.discordId("none")
.build();
user.setId(0L);
return user;
}
@Override
public List<? extends DataNodeBase> findAll() {
return this.dataValues;
}
}
|
var Car = require('./car.js');
class ParkingLot {
constructor () {
this.MAX_PARKING_SLOTS = 0; // maximum parking slots allowed
this.parkingSlots = new Array(); // array for parking slots
}
createParkingLot (input) {
this.MAX_PARKING_SLOTS = parseInt(input.split(' ')[1]);
if (this.MAX_PARKING_SLOTS <= 0) {
// minimum: 1 slot
throw new Error('Minimum one slot is required to create parking slot');
}
for (var i = 0; i < this.MAX_PARKING_SLOTS; i++) {
this.parkingSlots.push(null);
}
return this.MAX_PARKING_SLOTS;
}
parkCar (input) {
var len = this.parkingSlots.length;
if (this.MAX_PARKING_SLOTS > 0) {
var car, carNumber, carColor;
if (this.findNearestAvailableSlot(this.parkingSlots) == true) {
for (var i = 0; i < len; i++) {
if (this.parkingSlots[i] == null) {
carNumber = input.split(' ')[1];
carColor = input.split(' ')[2];
if (carNumber && carColor) {
car = new Car(carNumber, carColor);
this.parkingSlots[i] = car;
i = i + 1;
return i;
}
else {
throw new Error('Please provide registration number and color both');
}
}
}
}
else {
throw new Error('Sorry, parking lot is full');
}
}
else {
throw new Error('Minimum one slot is required to create parking slot');
}
}
leaveCar (input) {
if (this.MAX_PARKING_SLOTS > 0) {
var index = parseInt(input.split(' ')[1] - 1);
if (index >= this.MAX_PARKING_SLOTS) {
throw new Error(`Slot number ${index + 1} is not found`);
}
else if (this.parkingSlots[index] === null) {
throw new Error(`Slot number ${index + 1} is already free`);
}
else if (index > -1 && index <= this.parkingSlots.length) {
this.parkingSlots[index] = null;
index = index + 1;
return index;
}
}
else {
throw new Error('Sorry, parking lot is empty');
}
}
leaveCarByCarNumber (input) {
if (this.MAX_PARKING_SLOTS > 0) {
var carNumber = input.split(' ')[1];
for (var index = 0; index < this.MAX_PARKING_SLOTS; index++) {
if (this.parkingSlots[index].NUMBER === carNumber) {
this.parkingSlots[index] = null;
return index + 1;
}
}
}
else {
throw new Error('Sorry, car with given registration is not found');
}
}
getParkingStatus () {
var arr = new Array();
if (this.MAX_PARKING_SLOTS > 0) {
arr.push('Slot No. Registration No. Color ');
// use binary search here
for (var i = 0; i < this.parkingSlots.length; i++) {
if (this.parkingSlots[i] != null) {
var e = i + 1;
arr.push(e + '. ' + this.parkingSlots[i].NUMBER + ' ' + this.parkingSlots[i].COLOR);
}
}
return arr;
}
else {
throw new Error('Sorry, parking lot is empty');
}
}
getCarsWithSameColor (input) {
if (this.MAX_PARKING_SLOTS > 0) {
var sameColoredCarsArray = new Array();
for (var i = 0; i < this.parkingSlots.length; i++) {
if (this.parkingSlots[i] && this.parkingSlots[i].COLOR.toLowerCase() == input.split(' ')[1].toLowerCase()) {
sameColoredCarsArray.push(this.parkingSlots[i].NUMBER);
}
}
return sameColoredCarsArray.join(', ');
}
else {
return null;
}
}
getSlotsWithSameColorCar (input) {
if (this.MAX_PARKING_SLOTS > 0) {
var slotsWithSameColorCarArray = new Array();
for (var i = 0; i < this.parkingSlots.length; i++) {
if (this.parkingSlots[i] && this.parkingSlots[i].COLOR.toLowerCase() == input.split(' ')[1].toLowerCase()) {
slotsWithSameColorCarArray.push(i + 1);
}
}
return slotsWithSameColorCarArray.join(', ');
}
else {
return null;
}
}
getSlotByCarNumber (input) {
// TODO: What parking lot is empty
if (this.MAX_PARKING_SLOTS > 0) {
var ele = 'Not found';
for (var i = 0; i < this.parkingSlots.length; i++) {
if (this.parkingSlots[i] && this.parkingSlots[i].NUMBER == input.split(' ')[1]) {
ele = i + 1;
}
}
return ele;
}
else {
return null;
}
}
findAllAvailableSlots () {
if (this.MAX_PARKING_SLOTS > 0) {
var availableSlots = new Array();
for (var i = 0; i < this.parkingSlots.length; i++) {
if (!(this.parkingSlots[i] && this.parkingSlots[i].COLOR && this.parkingSlots[i].NUMBER)) {
availableSlots.push(i + 1);
}
}
return availableSlots.join(', ');
}
else {
return null;
}
}
findAllAllocatedSlots () {
if (this.MAX_PARKING_SLOTS > 0) {
var allocatedSlots = new Array();
for (var i = 0; i < this.parkingSlots.length; i++) {
if (this.parkingSlots[i] && this.parkingSlots[i].COLOR && this.parkingSlots[i].NUMBER) {
allocatedSlots.push(i + 1);
}
}
return allocatedSlots.join(', ');
}
else {
return null;
}
}
findNearestAvailableSlot () {
var ele = false;
for (var i = 0; i < this.parkingSlots.length; i++) {
if (this.parkingSlots[i] == null) {
ele = true;
}
}
return ele;
}
}
module.exports = ParkingLot;
|
# Online signatures for order confirmations
The Konvergo ERP *Sales* application provides customers with the ability to
confirm orders, via an online signature, directly on the sales order.
Once the sales order is electronically signed by the customer, the
salesperson attached to the sales order is instantly notified that the
order is confirmed.
## Activate online signatures
In order to have customers confirm orders with an online signature, the
*Online Signature* feature **must** be activated.
To activate the *Online Signature* feature, go to
`Sales app --> Configuration -->
Settings`, scroll to the `Quotations \& Orders` heading, and activate
the `Online Signature` feature by checking the box beside it.
<img src="get_signature_to_validate/signature-setting.png"
class="align-center"
alt="The Online Signature feature option in the Settings of the Konvergo ERP Sales application." />
Then, click the `Save` button in the top-left corner.
> [!NOTE]
> When making a quotation template, the online signature feature is the
> `Signature` option, located in the `Online confirmation` field of the
> quotation template form.
>
> <img
> src="get_signature_to_validate/signature-feature-quotation-template.png"
> class="align-center"
> alt="The Online confirmation signature option found on every quotation template in Konvergo ERP." />
>
> On standard quotations, the online signature feature is the
> `Signature` option, located under the `Other Info` tab of the
> quotation form.
>
> <img src="get_signature_to_validate/signature-other-info-tab.png"
> class="align-center"
> alt="The online signature feature option in the Other Info tab of a quotation form in Konvergo ERP." />
## Order confirmations with online signatures
When clients access quotations online through their customer portal,
there's a `Sign \&
Pay` button directly on the quotation.
<img src="get_signature_to_validate/sign-and-pay-button.png"
class="align-center"
alt="The Sign and Pay button present on online quotations in Konvergo ERP Sales." />
When clicked, a `Validate Order` pop-up window appears. In this pop-up
window, the `Full Name` field is auto-populated, based on the contact
information in the database.
<img src="get_signature_to_validate/validate-order-popup.png"
class="align-center"
alt="The Validate Order pop-up window for online signatures in Konvergo ERP Sales." />
Then, customers have the option to enter an online signature with any of
the following options: `Auto`, `Draw`, or `Load`.
`Auto` lets Konvergo ERP automatically generate an online signature based on the
information in the `Full Name` field. `Draw` lets the customer use the
cursor to create a custom signature directly on the pop-up window. And
`Load` lets the customer upload a previously-created signature file from
their computer.
After the customer has chosen any of the three previously mentioned
signature options (`Auto`, `Draw`, or `Load`), they will click the
`Accept \&
Sign` button.
When `Accept \& Sign` is clicked, the various payment method options
become available for them to choose from (if the *online payment* option
applies to this quotation).
Then, when the quotation is paid and confirmed, a delivery order is
automatically created (if the Konvergo ERP *Inventory* app is installed).
<div class="seealso">
\- `quote_template` - `get_paid_to_validate`
</div>
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ABOUT } from "../../../shared/constants";
import { faCircleCheck } from "@fortawesome/free-solid-svg-icons";
interface AboutItem {
title: string;
icon?: string ;
}
const AboutItem = ({title, icon}: AboutItem) => {
return(
<div className="w-1/2 flex gap-2 mb-4 items-center">
{/* <img src={icon} alt="icon" height={20} width={20} className="object-fill "></img> */}
<FontAwesomeIcon icon={faCircleCheck} className="text-green-500"/>
<p className="regular-14">{title}</p>
</div>
);
}
function About() {
return (
<div className="max-w-full mx-auto padding-container py-24 lg:py-20">
{/* First */}
<div className="flex flex-col gap-8 lg:flex-row pb-24">
{/* LEFT */}
<div className="flex flex-1 flex-col items-start justify-center">
<h1 className="bold-52 capitalize pb-4">
John Us in Exploring The Entire World
</h1>
<p className="mb-4">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab totam
nobis soluta tempora, adipisci cum accusamus hic. Blanditiis, id iure
natus repellendus, molestias iste veniam illum, reprehenderit
recusandae excepturi non?
</p>
<p className="mb-4">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab totam
nobis soluta tempora, adipisci cum accusamus hic. Blanditiis, id iure
natus repellendus, molestias iste veniam illum, reprehenderit
recusandae excepturi non?
</p>
<div className="flex flex-wrap mt-8">
{ABOUT.map((about) => {
return(
<AboutItem
title={about.Title}
icon={about.icon}
/>
);
})}
</div>
</div>
{/* Right */}
<div className="flex flex-1 gap-4 lg:gap-8">
<div className="w-1/2">
<img src="/src/assets/maldives3.jpg"
alt="about"
height={444}
width={333}
className="w-auto h-full rounded-lg border border-gray-100 mt-10 shadow-lg object-cover"/>
</div>
<div className="w-1/2">
<img src="/src/assets/maldives2.jpg"
alt="about"
height={444}
width={333}
className="w-auto h-full rounded-lg border border-gray-100 mt-5 shadow-lg object-cover"/>
</div>
</div>
</div>
{/* Second */}
<div className="flex flex-col gap-8 lg:flex-row pb-24">
{/* LEFT */}
<div className="flex flex-1 gap-4 lg:gap-8">
<div className="w-1/2">
<img src="/src/assets/keywest.jpg"
alt="about"
height={444}
width={333}
className="w-auto h-full rounded-lg border border-gray-100 mt-10 shadow-lg object-cover"/>
</div>
<div className="w-1/2">
<img src="/src/assets/borabora.jpg"
alt="about"
height={444}
width={333}
className="w-auto h-full rounded-lg border border-gray-100 mt-5 shadow-lg object-cover"/>
</div>
</div>
{/* Right */}
<div className="flex flex-1 flex-col items-start justify-center">
<h1 className="bold-52 capitalize pb-4">
John Us in Exploring The Entire World
</h1>
<p className="mb-4">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab totam
nobis soluta tempora, adipisci cum accusamus hic. Blanditiis, id iure
natus repellendus, molestias iste veniam illum, reprehenderit
recusandae excepturi non?
</p>
<p className="mb-4">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab totam
nobis soluta tempora, adipisci cum accusamus hic. Blanditiis, id iure
natus repellendus, molestias iste veniam illum, reprehenderit
recusandae excepturi non?
</p>
<div className="flex flex-wrap mt-8">
{ABOUT.map((about) => {
return(
<AboutItem
title={about.Title}
icon={about.icon}
/>
);
})}
</div>
</div>
</div>
</div>
);
}
export default About;
|
package com.example.elec390_proj_demo;
import java.util.HashMap;
import java.util.Map;
/**
* ELEC-390 Soil Sense
* Created by Evan Yu on 04/01/2023.
* @Plants.class
* Plants datamodel for importing/exporting from app/database
*/
public class Plants {
public String name, date, scientific_name, sunlight, watering_freq, plant_url;
public int watering_amount, target_moisture;
public int flag;
public Plants(String name, String date, int flag, int watering_amount, int target_moisture) {
this.name = name;
this.date = date;
this.flag = flag;
this.watering_amount = watering_amount;
this.target_moisture = target_moisture;
}
public Plants() {
this.name = "";
this.date = "";
this.flag = 0;
this.scientific_name = "";
this.watering_amount = 0;
this.target_moisture = 0;
this.sunlight = "";
this.watering_freq = "";
this.plant_url = "";
}
public Plants(String name, String date, int flag) {
this.name = name;
this.date = date;
this.flag = flag;
this.scientific_name = "";
this.watering_amount = 0;
this.target_moisture = 0;
this.sunlight = "";
this.watering_freq = "";
this.plant_url = "";
}
public Plants(String name, String date, String sun, String wf, String url, String nick) {
this.name = name;
this.date = date;
this.flag = 0;
this.scientific_name = nick;
this.watering_amount = 0;
this.target_moisture = 0;
this.sunlight = sun;
this.watering_freq = wf;
this.plant_url = url;
}
public String getScientific_name() {
return scientific_name;
}
public void setScientific_name(String scientific_name) {
this.scientific_name = scientific_name;
}
public String getSunlight() {
return sunlight;
}
public void setSunlight(String sunlight) {
this.sunlight = sunlight;
}
public String getWatering_freq() {
return watering_freq;
}
public void setWatering_freq(String watering_freq) {
this.watering_freq = watering_freq;
}
public String getPlant_url() {
return plant_url;
}
public void setPlant_url(String plant_url) {
this.plant_url = plant_url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getWatering_amount() {
return watering_amount;
}
public void setWatering_amount(int watering_amount) {
this.watering_amount = watering_amount;
}
public int getTarget_moisture() {
return target_moisture;
}
public void setTarget_moisture(int target_moisture) {
this.target_moisture = target_moisture;
}
public int calcCurrentMoisture() {
int rMoisture = this.target_moisture;
int result = 0;
if (rMoisture >= 656) {
// soil dry, needs watering
result = 1;
} else if (rMoisture < 656 && rMoisture >= 519) {
// soil somewhat watered
result = 2;
} else if (rMoisture < 519 && rMoisture >= 473) {
// soil moderately watered
result = 3;
} else if (rMoisture < 473 && rMoisture >= 420) {
// soil very well watered
result = 4;
} else if (rMoisture <= 356) {
//soil doesn't need watering
result = 5;
}
return result;
}
@Override
public String toString() {
return "Plants{" +
"name='" + name + '\'' +
", date='" + date + '\'' +
", scientific_name='" + scientific_name + '\'' +
", sunlight='" + sunlight + '\'' +
", watering_freq='" + watering_freq + '\'' +
", plant_url='" + plant_url + '\'' +
", watering_amount=" + watering_amount +
", target_moisture=" + target_moisture +
", flag=" + flag +
'}';
}
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("name", name);
result.put("date", date);
result.put("flag", flag);
result.put("scientific_name", scientific_name);
result.put("sunlight", sunlight);
result.put("watering_freq", watering_freq);
result.put("plant_url", plant_url);
result.put("watering_amount", watering_amount);
result.put("target_moisture", target_moisture);
return result;
}
}
|
//
// HourlyViewCellCell.swift
// MyWeather
//
// Created by Сергей Рудинский on 13.02.22.
//
import UIKit
final class HourlyViewCellCell: UICollectionViewCell {
// MARK: - Properties
static let identifare = "\(HourlyViewCellCell.self)"
private var timeLable: UILabel = {
let lable = UILabel()
lable.textAlignment = .center
lable.textColor = .white
return lable
}()
private var UIimageView: UIImageView = {
let image = UIImageView()
image.contentMode = .scaleAspectFit
return image
}()
private var tempLable: UILabel = {
let lable = UILabel()
lable.textAlignment = .center
lable.textColor = .white
return lable
}()
// MARK: - Setups
private func viewAddSubView(){
self.addSubview(timeLable)
self.addSubview(UIimageView)
self.addSubview(tempLable)
}
private func setupAnchors(){
timeLable.translatesAutoresizingMaskIntoConstraints = false
UIimageView.translatesAutoresizingMaskIntoConstraints = false
tempLable.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// timeLable
timeLable.topAnchor.constraint(equalTo: topAnchor),
timeLable.leftAnchor.constraint(equalTo: leftAnchor),
timeLable.rightAnchor.constraint(equalTo: rightAnchor),
timeLable.heightAnchor.constraint(equalTo: UIimageView.heightAnchor),
// UIimageView
UIimageView.topAnchor.constraint(equalTo: timeLable.bottomAnchor),
UIimageView.leftAnchor.constraint(equalTo: leftAnchor),
UIimageView.rightAnchor.constraint(equalTo: rightAnchor),
UIimageView.bottomAnchor.constraint(equalTo: tempLable.topAnchor),
UIimageView.heightAnchor.constraint(equalTo: tempLable.heightAnchor),
// tempLable
tempLable.leftAnchor.constraint(equalTo: leftAnchor),
tempLable.rightAnchor.constraint(equalTo: rightAnchor),
tempLable.bottomAnchor.constraint(equalTo: bottomAnchor),
tempLable.heightAnchor.constraint(equalTo: timeLable.heightAnchor)
])
}
// MARK: - Override Init
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .cellsBackColor
viewAddSubView()
setupAnchors()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - funcs
func updateAll(hourlyArray: CurrentCoreData){
if let icon = hourlyArray.icon{
timeLable.text = DateFormatter().getHourString(intervaleFrom1970: hourlyArray.date)
UIimageView.image = UIImage(named: icon)
tempLable.text = String(format: "%.1f°", hourlyArray.temp)
}
}
}
|
<?php
namespace App\Http\Requests;
use App\Models\Brands;
use App\Models\Category;
use App\Models\SubCategory;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateProductRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'name' => 'string|min:3|max:255',
'description' => 'string|min:3',
'images' => '',
'quantity' => 'numeric',
'price' => '',
'category_id' => [Rule::exists(Category::class, 'id')],
'subcategory_id' => [Rule::exists(SubCategory::class, 'id')],
'brand_id' => [Rule::exists(Brands::class, 'id')],
'attribute' => 'json',
];
}
}
|
function [g1, g2, g3, g4, g5, g6, g7, g8, g9] = read_iss_p_imu_file(filename, dataLines)
%% Input handling
% If dataLines is not specified, define defaults
if nargin < 2
dataLines = [1, Inf];
end
%% Setup the Import Options and import the data
opts = delimitedTextImportOptions("NumVariables", 9);
% Specify range and delimiter
opts.DataLines = dataLines;
opts.Delimiter = ",";
% Specify column names and types
%opts.VariableNames = ["gFx", "gFy", "gFz", "wx", "wy", "wz"];
opts.VariableTypes = ["double", "double", "double", "double", "double", "double", "double", "double", "double"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
% Import the data
tbl = readtable(filename, opts);
%% Convert to output type
g1 = tbl.Var1;
g2 = tbl.Var2;
g3 = tbl.Var3;
g4 = tbl.Var4;
g5 = tbl.Var5;
g6 = tbl.Var6;
g7 = tbl.Var7;
g8 = tbl.Var8;
g9 = tbl.Var9;
end
|
library("tidyverse")
library("ggplot2")
library("ggrepel")
library("ggcorrplot")
library("DT")
cases <- read_csv(".\\data\\COVID-19-20220207.csv")
cases
cases <- cases %>% mutate_if(is.character, factor)
dim(cases)
cases_TX <- cases %>% filter(state == "TX")
dim(cases_TX)
summary(cases_TX[,1:10])
# I would like to drill down into this graph to see what all is really in the big bin
ggplot(cases_TX, mapping = aes(confirmed_cases)) + geom_histogram(bins = 20)
ggsave(".\\charts\\1HistCountiesByCase20bins.pdf")
ggplot(filter(cases_TX, confirmed_cases < 100000), mapping=aes(confirmed_cases)) + geom_histogram(bins=20)
ggsave(".\\charts\\1HistCountiesByCase20bins-zoomed.pdf")
ggplot(filter(cases_TX, confirmed_cases > 100000), mapping=aes(confirmed_cases)) + geom_histogram(bins=40)
ggsave(".\\charts\\1HistCountiesByCase20bins-zoomed2.pdf")
ggplot(cases_TX, mapping = aes(x = confirmed_cases, y = deaths, label = county_name)) +
geom_smooth(method = lm) +
geom_point(mapping = aes(size = total_pop), color = "grey") +
geom_text_repel(data = subset(cases_TX, deaths >= 1000))
cases_TX_select <- cases_TX %>% filter(confirmed_cases > 100) %>%
arrange(desc(confirmed_cases)) %>%
select(county_name, confirmed_cases, deaths, total_pop, median_income)
cases_TX_select <- cases_TX_select %>% mutate(
cases_per_1000 = confirmed_cases/total_pop*1000,
deaths_per_1000 = deaths/total_pop*1000,
death_per_case = deaths/confirmed_cases)
head(cases_TX_select)
# Usable table
datatable(cases_TX_select) %>% formatRound(6:7, 4) %>% formatPercentage(8, 2)
ggplot(cases_TX_select, mapping = aes(x = cases_per_1000, y = deaths_per_1000, label = county_name)) +
geom_smooth(method = lm) +
geom_point(mapping = aes(size = total_pop), color = "grey") +
geom_text_repel(data = subset(cases_TX_select, deaths_per_1000 > quantile(deaths_per_1000, .95)))
# Does death per case depend on population?
ggplot(cases_TX_select, mapping = aes(x= total_pop, y = deaths_per_1000, label = county_name)) +
geom_smooth(method = lm) +
geom_point(mapping = aes(size = total_pop), color = "grey") +
geom_text_repel(data = subset(cases_TX_select, deaths_per_1000 > quantile(deaths_per_1000, .95)))
|
from flask import Flask
# from flask_migrate import Migrate
from db import db
from config import Config, ProdConfig
from blueprints.api import blueprint
def create_app(config_object: Config):
"""
An application factory, explained here:
https://flask.palletsprojects.com/en/3.0.x/patterns/appfactories/
"""
app = Flask(__name__.split('.')[0])
app.url_map.strict_slashes = False
app.config.from_object(config_object)
_register_extensions(app)
_register_blueprints(app)
return app
def _register_extensions(app: Flask):
"""Register Flask extensions."""
db.init_app(app)
# Migrate().init_app(app, db)
def _register_blueprints(app: Flask):
"""Register Flask blueprints."""
app.register_blueprint(blueprint)
|
import React from "react";
import { View, Text, TouchableOpacity } from "react-native";
// Assets
import { MaterialCommunityIcons, Ionicons } from "@expo/vector-icons";
import colors from "../config/colors";
import { Pressable } from "@react-native-material/core";
function TabBar({ state, descriptors, navigation }) {
return (
<View
style={{
flexDirection: "row",
justifyContent: "space-evenly",
alignItems: "center",
}}
>
{state.routes.map((route, index) => {
const { options } = descriptors[route.key];
const label =
options.tabBarLabel !== undefined
? options.tabBarLabel
: options.title !== undefined
? options.title
: route.name;
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: "tabPress",
target: route.key,
canPreventDefault: true,
});
if (!isFocused && !event.defaultPrevented) {
// The `merge: true` option makes sure that the params inside the tab screen are preserved
navigation.navigate({ name: route.name, merge: true });
}
};
const onLongPress = () => {
navigation.emit({
type: "tabLongPress",
target: route.key,
});
};
return (
<Pressable
accessibilityRole="button"
accessibilityState={isFocused ? { selected: true } : {}}
accessibilityLabel={options.tabBarAccessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
onLongPress={onLongPress}
pressEffectColor={colors.white}
style={{
position: "relative",
alignItems: "center",
justifyContent: "center",
flex: 1,
paddingVertical: "3%",
}}
key={route.key}
>
{route.name === "Today" ? (
<MaterialCommunityIcons
name="calendar"
size={24}
color={isFocused ? colors.primary : colors.secondary}
style={{ flex: 1 }}
/>
) : (
""
)}
{route.name === "Progress" ? (
<Ionicons
name="bar-chart"
size={24}
color={isFocused ? colors.primary : colors.secondary}
/>
) : (
""
)}
{route.name === "News Feed" ? (
<MaterialCommunityIcons
name="note-outline"
size={24}
color={isFocused ? colors.primary : colors.secondary}
/>
) : (
""
)}
{route.name === "Food Diary" ? (
<MaterialCommunityIcons
name="book-open-outline"
size={24}
color={isFocused ? colors.primary : colors.secondary}
/>
) : (
""
)}
{route.name === "Settings" ? (
<Ionicons
name="settings-outline"
size={24}
color={isFocused ? colors.primary : colors.secondary}
style={{ flex: 1 }}
/>
) : (
""
)}
<Text
style={{
color: isFocused ? "#673ab7" : "#222",
fontSize: 10,
textAlign: "center",
paddingTop: 10,
}}
>
{label}
</Text>
</Pressable>
);
})}
</View>
);
}
export default TabBar;
|
from pathlib import Path
from typing import List, Dict
from strictyaml import load
from pydantic import BaseModel
# Directory Management
PACKAGE_ROOT = Path(__file__).resolve().parent.parent
CONFIG_FILE_PATH = PACKAGE_ROOT / "config.yml"
DATA_DIR = PACKAGE_ROOT / "data"
MODEL_DIR = PACKAGE_ROOT / "model"
class ModelConfig(BaseModel):
"""
All configurations related to
Modelling
"""
# Data Processing
DATA: str
QUERY: str
TARGET_VARIABLE: str
CATEGORICAL_FEATURES: List[str]
NUMERICAL_FEATURES: List[str]
DROP_FEATURES: List[str]
IMPUTE_MEDIAN: List[str]
IMPUTE_MODE: List[str]
IMPUTE_REFERENCE: List[List[str]]
NUMERICAL: List[str]
NOMINAL_CATEGORICAL: List[str]
ORDINAL_CATEGORICAL: List[str]
# Training Model
MODEL_LIST: List[str]
MODEL_SELECTION: str
MODEL_VERSION: str
TEST_SIZE: float
VALIDATION_SIZE: float
SEED: int
# HYPERPARAMS
OPTIMIZE: bool
CV: int
# LGBM_MODEL
# TUNING_STR_GRID: Dict[str, List[str]]
LGBM_TUNING_INT_GRID: Dict[str, List[int]]
LGBM_TUNING_FLOAT_GRID: Dict[str, List[float]]
LGBM_STR_HPARAMS: Dict[str, str]
LGBM_INT_HPARAMS: Dict[str, int]
LGBM_FLOAT_HPARAMS: Dict[str, float]
# SVC_MODEL
SVC_TUNING_STR_GRID: Dict[str, List[str]]
SVC_TUNING_FLOAT_GRID: Dict[str, List[float]]
SVC_STR_HPARAMS: Dict[str, str]
SVC_FLOAT_HPARAMS: Dict[str, float]
# MLP_MODEL
MLP_TUNING_STR_GRID: Dict[str, List[str]]
MLP_TUNING_INT_GRID: Dict[str, List[int]]
MLP_TUNING_FLOAT_GRID: Dict[str, List[float]]
MLP_STR_HPARAMS: Dict[str, str]
MLP_INT_HPARAMS: Dict[str, int]
MLP_FLOAT_HPARAMS: Dict[str, float]
# LOG_REGRESSION_MODEL
LOG_TUNING_STR_GRID: Dict[str, List[str]]
LOG_TUNING_INT_GRID: Dict[str, List[int]]
LOG_TUNING_FLOAT_GRID: Dict[str, List[float]]
LOG_STR_HPARAMS: Dict[str, str]
LOG_INT_HPARAMS: Dict[str, int]
LOG_FLOAT_HPARAMS: Dict[str, float]
def fetch_config_from_yaml():
"""
Parse YAML containing the package configuration
"""
if CONFIG_FILE_PATH.is_file():
with open(CONFIG_FILE_PATH, "r") as conf_file:
parsed_config = load(conf_file.read())
return parsed_config
raise OSError(f"Config file not found at : {CONFIG_FILE_PATH}")
config = ModelConfig(**(fetch_config_from_yaml()).data)
if __name__ == "__main__":
print(config)
|
import axios from 'axios';
import Cookies from 'js-cookie';
import Box from '@mui/material/Box';
import { baseURL } from './APIconfig';
import Button from '@mui/material/Button';
import { Typography } from '@mui/material';
import { useParams } from 'react-router-dom';
import { useLoginStore } from './LoginState';
import AddIcon from '@mui/icons-material/Add';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import { useEffect, useRef, useState } from 'react';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import {
GridRowsProp,
GridRowModesModel,
GridRowModes,
DataGrid,
GridColDef,
GridToolbarContainer,
GridActionsCellItem,
GridEventListener,
GridRowId,
GridRowModel,
GridRowEditStopReasons,
} from '@mui/x-data-grid';
const initialRows: GridRowsProp = [];
interface EditToolbarProps {
setRows: (newRows: (oldRows: GridRowsProp) => GridRowsProp) => void;
setRowModesModel: (
newModel: (oldModel: GridRowModesModel) => GridRowModesModel,
) => void;
}
function EditToolbar(props: EditToolbarProps) {
const { setRows, setRowModesModel } = props;
const { id } = useParams();
const shopId = id;
const handleClick = () => {
axios
.post(baseURL + "coupon/seasoning", {
date: null,
shopId: shopId,
rate: 0.0,
})
.then((response) => {
const id = response.data.id;
setRows((oldRows) => [...oldRows, { id, name: '', discount: '', deadline: '', isNew: true }]);
setRowModesModel((oldModel) => ({
...oldModel,
[id]: { mode: GridRowModes.Edit, fieldToFocus: 'name' },
}));
})
.catch((error) => {
console.error(error);
});
};
return (
<GridToolbarContainer>
<Button color="primary" startIcon={<AddIcon />} onClick={handleClick}>
Add Coupon
</Button>
</GridToolbarContainer>
);
}
export default function SeasoningCoupon() {
const { id } = useParams();
const shopId = id;
const [rows, setRows] = useState(initialRows);
const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});
const initialized = useRef(false);
const { Login } = useLoginStore((state) => state);
useEffect(() => {
const newData = {
email: "",
name: "",
phoneNumber: "",
avatar: "",
address: "",
description: "",
background: "",
createrId: "",
deleterId: "",
deleted: false,
};
if (!initialized.current) {
initialized.current = true;
const fetchData = async () => {
if (shopId) {
try {
if (Cookies.get(shopId.toString()) === "false" || Cookies.get(shopId.toString()) === undefined) {
window.location.href = "/login";
} else {
const response = await axios.get(baseURL + "shop/" + shopId, {});
const info = response.data;
newData.email = info.email;
newData.name = info.name;
newData.phoneNumber = info.phoneNumber;
newData.address = info.address;
newData.description = info.description;
newData.avatar = info.avatar;
newData.background = info.background;
newData.createrId = info.createrId;
newData.deleterId = info.deleterId;
newData.deleted = info.deleted;
}
} catch (error) {
console.error(error);
}
}
};
const login = async () => {
await fetchData();
let loginInfo = {
id: shopId || '',
email: newData.email,
name: newData.name,
phoneNumber: newData.phoneNumber,
avatar: newData.avatar,
addresses: [newData.address],
deleted: newData.deleted,
}
Login(loginInfo);
};
login();
if (shopId) {
if (Cookies.get(shopId.toString()) === "false" || Cookies.get(shopId.toString()) === undefined) {
window.location.href = "/login";
}
}
const getAllShopProducts = async () => {
try {
const response = await axios.get(baseURL + "coupon/shop/" + shopId, {});
let seasoningCoupons = response.data.seasoningCoupons;
await getproductsInfo(seasoningCoupons);
} catch (error) {
console.log(error);
}
};
const getproductsInfo = async (data: any[] = []) => {
data.forEach((product: any) => {
const newRow = {
id: product.id,
name: product.rate,
discount: product.rate,
deadline: product.date,
};
setRows(oldRows => [...oldRows, newRow]);
});
};
getAllShopProducts();
}
});
const handleRowEditStop: GridEventListener<'rowEditStop'> = (params, event) => {
if (params.reason === GridRowEditStopReasons.rowFocusOut) {
event.defaultMuiPrevented = true;
}
};
const handleSaveClick = (id: GridRowId) => () => {
setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.View } });
};
const handleDeleteClick = (id: GridRowId) => () => {
setRows(rows.filter((row) => row.id !== id));
axios.delete(baseURL + "coupon/" + id, {})
};
const handleCancelClick = (id: GridRowId) => () => {
setRowModesModel({
...rowModesModel,
[id]: { mode: GridRowModes.View, ignoreModifications: true },
});
const editedRow = rows.find((row) => row.id === id);
if (editedRow!.isNew) {
setRows(rows.filter((row) => row.id !== id));
}
};
const processRowUpdate = (newRow: GridRowModel) => {
const updatedRow = { ...newRow, isNew: false };
setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
if (newRow.discount === undefined || newRow.discount === null || newRow.discount === "") {
confirm("Discount Rate cannot be empty.\nPlease add a new coupon with valid discount rate.");
axios.delete(baseURL + "coupon/" + newRow.id, {})
window.location.reload();
} else if (newRow.discount > 1 || newRow.discount < 0 || newRow.discount === 0) {
confirm("Discount Rate must be between 0 and 1.\nPlease add a new coupon with valid discount rate.");
axios.delete(baseURL + "coupon/" + newRow.id, {})
window.location.reload();
} else {
axios
.put(baseURL + "coupon/seasoning/" + newRow.id, {
"date": newRow.deadline,
"shopId": shopId,
"rate": newRow.discount,
})
.catch((error) => {
console.error(error);
});
return updatedRow;
}
};
const handleRowModesModelChange = (newRowModesModel: GridRowModesModel) => {
setRowModesModel(newRowModesModel);
};
const columns: GridColDef[] = [
{
field: 'actions',
type: 'actions',
headerName: 'Actions',
width: 120,
cellClassName: 'actions',
getActions: ({ id }) => {
const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;
if (isInEditMode) {
return [
<GridActionsCellItem
icon={<SaveIcon />}
label="Save"
sx={{
color: 'primary.main',
}}
onClick={handleSaveClick(id)}
/>,
<GridActionsCellItem
icon={<CancelIcon />}
label="Cancel"
className="textPrimary"
onClick={handleCancelClick(id)}
color="inherit"
/>,
];
}
return [
<GridActionsCellItem
icon={<DeleteIcon />}
label="Delete"
onClick={handleDeleteClick(id)}
color="inherit"
/>,
];
},
},
{
field: 'name',
headerName: 'Name',
width: 180,
editable: false,
flex: 1,
valueGetter(params) {
let num = (params.value * 100 ).toString().split(".")[0] as unknown as number;
console.log("num");
console.log(num);
if (params.row.discount === undefined || params.row.discount === null || params.row.discount === "" || params.row.discount === 0) {
return "Can not be edited";
}
if (num % 10 === 0) {
return `單筆訂單打${num / 10}折`;
}
return `單筆訂單打${num}折`;
},
},
{
field: 'discount',
headerName: 'Discount Rate',
width: 150,
editable: true,
type: 'number',
headerAlign: "center",
align: "center",
valueFormatter(params) {
if (params.value === undefined) {
params.value = "null";
}
console.log();
return `${(params.value * 100 ).toString().split(".")[0]} %`;
},
},
{
field: 'deadline',
headerName: 'Deadline',
headerAlign: "center",
align: "center",
type: 'date',
width: 180,
editable: true,
valueFormatter(params) {
if (params.value === undefined || params.value === null || params.value === "") {
return "Null";
}
const date = new Date(params.value);
return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
},
},
];
return (
<Box
sx={{
height: 450,
width: '90%',
margin: 'auto',
'& .actions': {
color: 'text.secondary',
},
'& .textPrimary': {
color: 'text.primary',
},
marginTop: '50px',
marginBottom: '100px',
}}
>
<Typography variant="h4">
Seasoning Coupon
</Typography>
<DataGrid
rows={rows}
columns={columns}
editMode="row"
rowModesModel={rowModesModel}
onRowModesModelChange={handleRowModesModelChange}
onRowEditStop={handleRowEditStop}
processRowUpdate={processRowUpdate}
isCellEditable={(params) => params.row.isNew === true && (params.field === 'deadline' || params.field === 'discount')}
slots={{
toolbar: EditToolbar,
}}
slotProps={{
toolbar: { setRows, setRowModesModel },
}}
hideFooter={true}
sx={{
"& .MuiDataGrid-cell": {
border: "1px solid #ccc",
},
"& .MuiDataGrid-columnHeader": {
border: "1px solid #ccc",
borderBottom: 0,
},
border: '1px solid #ccc',
}}
/>
</Box>
);
}
|
function histogramDiffDepths(Depth1, Depth2, n_bins, sp, blockEvents, recParams, sec_before_trigger, type_sequence, num_sequences)
%
% Function that plots x histograms from the first x blocks of a type of
% sequence (for example, first x spaced recordings) for each one of the k
% specified depths. For instance, k = 9 --> x*9 plots. They will show
% the sum of the number of spikes in all trials between specified depths.
%
% Inputs
% Depth1: int, from which depth you want to integrate the spikes.
% Depth2: int, to which depth you want to integrate the spikes.
% n_bins: num, number of bins for the histogram.
% sp: struct, contains information about the spikes.
% blockEvents: cell, contains all the triggers divided in their
% different sequences.
% recParams: struct, extracted from function recDataForSubject.
% sec_before_trigger: num, how many seconds before the triggers we want
% to see to perform the t-test.
% type_sequence: num, ID of which type of sequence you using.
% num_sequences: num, number of sequences of that type you want to show.
% Calculating the different depths in which we divide the plots.
k = 9; % # of depths in which we divided the limiting depths.
depths = round(Depth1:(Depth2-Depth1)/k:Depth2);
% Looking at how many protocols are from each type.
ISIs = recParams.ISITrial(1:num_sequences);
ISI_33 = ISIs > 0.3 & ISIs < 0.35;
ISI_10 = ISIs > 0.09 & ISIs < 0.11;
% Initializing the axes.
ax = gobjects(sum(ISI_33),k);
ax2 = gobjects(sum(ISI_10),k);
% Color coding for the histograms
color_hex_33=["d7e1ee", "cbd6e4", "bfcbdb", "b3bfd1", "a4a2a8", "df8879", "c86558", "b04238", "991f17"];
color_hex_10=["0000b3", "0010d9", "0020ff", "0040ff", "0060ff", "0080ff", "009fff", "00bfff", "00ffff"];
for i=1:k % k Times
% Counts of how many protocols we have from that ISI.
num_33 = 0;
num_10 = 0;
% Limit of the y axes.
ylimit = 1;
ylimit2 = 1;
for j=1:num_sequences % x Spaced sequences
% Choosing the index of the protocol and getting the data from that SOI.
idx_chosen = j;
[~, soi_trials, ~] = getDataFromSequence(sp, blockEvents, recParams, idx_chosen, sec_before_trigger);
% Checking whether they belong to the ISI_33 or ISI_10 category.
if ISI_33(idx_chosen)
num_33 = num_33+1;
% Selecting the color for each depth.
color = sscanf(color_hex_33(i),'%2x%2x%2x',[1 3])/255;
% Plotting and getting the maximum value of the histogram, for
% plotting purposes.
ax(num_33,k)= subplot(k,num_sequences,j+num_sequences*(i-1));
max_value = histSummedDepths(soi_trials.spTimes, soi_trials.spDepths, depths(i), depths(i+1), n_bins, recParams, idx_chosen, sec_before_trigger, type_sequence, color);
ylimit = max(ylimit, max_value);
else
num_10 = num_10+1;
% Selecting the color for each depth.
color = sscanf(color_hex_10(i),'%2x%2x%2x',[1 3])/255;
% Plotting and getting the maximum value of the histogram, for
% plotting purposes.
ax2(num_10,k)= subplot(k,num_sequences,j+num_sequences*(i-1));
max_value = histSummedDepths(soi_trials.spTimes, soi_trials.spDepths, depths(i), depths(i+1), n_bins, recParams, idx_chosen, sec_before_trigger, type_sequence, color);
ylimit2 = max(ylimit2, max_value);
end
% If we are at the last plot, set the limit of the axes of each
% category to the same y limits.
if num_33 == sum(ISI_33) && num_33>0 && ISI_33(idx_chosen)
linkaxes(ax(:,k), 'y')
ylimit = ylimit+ylimit/6;
ylim([0, ylimit])
end
if num_10 == sum(ISI_10) && num_10>0 && ISI_10(idx_chosen)
linkaxes(ax2(:,k), 'y')
ylimit2 = ylimit2+ylimit2/6;
ylim([0, ylimit2])
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.