text
stringlengths 184
4.48M
|
---|
import {AiFunctionEnhanced} from "../types";
import {utils} from "./utils.service";
const getInfoCompanyParameters = {
type: "object",
properties: {
company_name: {
type: "string",
description: "The name of the company and 4 possible variations based on a standard company name",
}
},
required: ["company_name"]
} as const
const getHtmlUniqueSelector = {
type: "object",
properties: {
selector: {
type: "string",
description: "The selector to use to get the information",
},
},
required: ["selector"]
} as const
export const functions: AiFunctionEnhanced[] = [
{
data: {
name: "getInfoCompany",
description: "get the info about a company",
parameters: getInfoCompanyParameters
},
exec: (args) => utils.getCompanyInfo(args)
},
{
data: {
name: "getHtmlUniqueSelector",
description: "get the most minimal unique selector of an element given his textual description",
parameters: getHtmlUniqueSelector
},
exec: (args) => utils.getHtmlUniqueSelector(args)
},
{
data: {
name: 'generateImage',
description: 'Generates an image from a text prompt',
parameters: {
type: 'object',
properties: {
prompt: {
type: 'string',
description: 'The text prompt to generate the image from'
}
},
required: ['prompt']
}
},
exec: (args) => utils.generateImage(args)
},
{
data: {
name: 'searchOnGoogle',
description: 'Generates a google search query',
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'The query to search on google'
},
},
required: ['query']
}
},
exec: (args) => utils.googleSearch(args)
},
{
data: {
name: 'searchOnGoogleWithTopic',
description: 'Generates a google search query',
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'The query to search on google'
},
topic: {
type: 'string',
description: 'The topic that the user is searching for (nws is for news)',
enum: ['nws']
}
},
required: ['query', 'topic']
}
},
exec: (query, topic) => utils.googleSearchWithTopic(query, topic)
}
] |
Copyright 2009 Jonathan Corbet <[email protected]>
Debugfs exists as a simple way for kernel developers to make information
available to user space. Unlike /proc, which is only meant for information
about a process, or sysfs, which has strict one-value-per-file rules,
debugfs has no rules at all. Developers can put any information they want
there. The debugfs filesystem is also intended to not serve as a stable
ABI to user space; in theory, there are no stability constraints placed on
files exported there. The real world is not always so simple, though [1];
even debugfs interfaces are best designed with the idea that they will need
to be maintained forever.
Debugfs is typically mounted with a command like:
mount -t debugfs none /sys/kernel/debug
(Or an equivalent /etc/fstab line).
The debugfs root directory is accessible by anyone by default. To
restrict access to the tree the "uid", "gid" and "mode" mount
options can be used.
Note that the debugfs API is exported GPL-only to modules.
Code using debugfs should include <linux/debugfs.h>. Then, the first order
of business will be to create at least one directory to hold a set of
debugfs files:
struct dentry *debugfs_create_dir(const char *name, struct dentry *parent);
This call, if successful, will make a directory called name underneath the
indicated parent directory. If parent is NULL, the directory will be
created in the debugfs root. On success, the return value is a struct
dentry pointer which can be used to create files in the directory (and to
clean it up at the end). A NULL return value indicates that something went
wrong. If ERR_PTR(-ENODEV) is returned, that is an indication that the
kernel has been built without debugfs support and none of the functions
described below will work.
The most general way to create a file within a debugfs directory is with:
struct dentry *debugfs_create_file(const char *name, umode_t mode,
struct dentry *parent, void *data,
const struct file_operations *fops);
Here, name is the name of the file to create, mode describes the access
permissions the file should have, parent indicates the directory which
should hold the file, data will be stored in the i_private field of the
resulting inode structure, and fops is a set of file operations which
implement the file's behavior. At a minimum, the read() and/or write()
operations should be provided; others can be included as needed. Again,
the return value will be a dentry pointer to the created file, NULL for
error, or ERR_PTR(-ENODEV) if debugfs support is missing.
In a number of cases, the creation of a set of file operations is not
actually necessary; the debugfs code provides a number of helper functions
for simple situations. Files containing a single integer value can be
created with any of:
struct dentry *debugfs_create_u8(const char *name, umode_t mode,
struct dentry *parent, u8 *value);
struct dentry *debugfs_create_u16(const char *name, umode_t mode,
struct dentry *parent, u16 *value);
struct dentry *debugfs_create_u32(const char *name, umode_t mode,
struct dentry *parent, u32 *value);
struct dentry *debugfs_create_u64(const char *name, umode_t mode,
struct dentry *parent, u64 *value);
These files support both reading and writing the given value; if a specific
file should not be written to, simply set the mode bits accordingly. The
values in these files are in decimal; if hexadecimal is more appropriate,
the following functions can be used instead:
struct dentry *debugfs_create_x8(const char *name, umode_t mode,
struct dentry *parent, u8 *value);
struct dentry *debugfs_create_x16(const char *name, umode_t mode,
struct dentry *parent, u16 *value);
struct dentry *debugfs_create_x32(const char *name, umode_t mode,
struct dentry *parent, u32 *value);
struct dentry *debugfs_create_x64(const char *name, umode_t mode,
struct dentry *parent, u64 *value);
These functions are useful as long as the developer knows the size of the
value to be exported. Some types can have different widths on different
architectures, though, complicating the situation somewhat. There is a
function meant to help out in one special case:
struct dentry *debugfs_create_size_t(const char *name, umode_t mode,
struct dentry *parent,
size_t *value);
As might be expected, this function will create a debugfs file to represent
a variable of type size_t.
Boolean values can be placed in debugfs with:
struct dentry *debugfs_create_bool(const char *name, umode_t mode,
struct dentry *parent, u32 *value);
A read on the resulting file will yield either Y (for non-zero values) or
N, followed by a newline. If written to, it will accept either upper- or
lower-case values, or 1 or 0. Any other input will be silently ignored.
Another option is exporting a block of arbitrary binary data, with
this structure and function:
struct debugfs_blob_wrapper {
void *data;
unsigned long size;
};
struct dentry *debugfs_create_blob(const char *name, umode_t mode,
struct dentry *parent,
struct debugfs_blob_wrapper *blob);
A read of this file will return the data pointed to by the
debugfs_blob_wrapper structure. Some drivers use "blobs" as a simple way
to return several lines of (static) formatted text output. This function
can be used to export binary information, but there does not appear to be
any code which does so in the mainline. Note that all files created with
debugfs_create_blob() are read-only.
If you want to dump a block of registers (something that happens quite
often during development, even if little such code reaches mainline.
Debugfs offers two functions: one to make a registers-only file, and
another to insert a register block in the middle of another sequential
file.
struct debugfs_reg32 {
char *name;
unsigned long offset;
};
struct debugfs_regset32 {
struct debugfs_reg32 *regs;
int nregs;
void __iomem *base;
};
struct dentry *debugfs_create_regset32(const char *name, umode_t mode,
struct dentry *parent,
struct debugfs_regset32 *regset);
int debugfs_print_regs32(struct seq_file *s, struct debugfs_reg32 *regs,
int nregs, void __iomem *base, char *prefix);
The "base" argument may be 0, but you may want to build the reg32 array
using __stringify, and a number of register names (macros) are actually
byte offsets over a base for the register block.
There are a couple of other directory-oriented helper functions:
struct dentry *debugfs_rename(struct dentry *old_dir,
struct dentry *old_dentry,
struct dentry *new_dir,
const char *new_name);
struct dentry *debugfs_create_symlink(const char *name,
struct dentry *parent,
const char *target);
A call to debugfs_rename() will give a new name to an existing debugfs
file, possibly in a different directory. The new_name must not exist prior
to the call; the return value is old_dentry with updated information.
Symbolic links can be created with debugfs_create_symlink().
There is one important thing that all debugfs users must take into account:
there is no automatic cleanup of any directories created in debugfs. If a
module is unloaded without explicitly removing debugfs entries, the result
will be a lot of stale pointers and no end of highly antisocial behavior.
So all debugfs users - at least those which can be built as modules - must
be prepared to remove all files and directories they create there. A file
can be removed with:
void debugfs_remove(struct dentry *dentry);
The dentry value can be NULL, in which case nothing will be removed.
Once upon a time, debugfs users were required to remember the dentry
pointer for every debugfs file they created so that all files could be
cleaned up. We live in more civilized times now, though, and debugfs users
can call:
void debugfs_remove_recursive(struct dentry *dentry);
If this function is passed a pointer for the dentry corresponding to the
top-level directory, the entire hierarchy below that directory will be
removed.
Notes:
[1] http://lwn.net/Articles/309298/ |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.camel.component.jms;
import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import static org.apache.camel.component.jms.JmsComponent.jmsComponentTransacted;
/**
* @version $Revision$
*/
public class JmsTransactedRouteTest extends ContextTestSupport {
public void testJmsRouteWithTextMessage() throws Exception {
MockEndpoint resultEndpoint = getMockEndpoint("mock:result");
String expectedBody = "Hello there!";
String expectedBody2 = "Goodbye!";
resultEndpoint.expectedBodiesReceived(expectedBody, expectedBody2);
resultEndpoint.message(0).header("cheese").isEqualTo(123);
template.sendBodyAndHeader("activemq:test.a", expectedBody, "cheese", 123);
template.sendBodyAndHeader("activemq:test.a", expectedBody2, "cheese", 124);
resultEndpoint.assertIsSatisfied();
}
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false&broker.useJmx=false");
JmsComponent component = jmsComponentTransacted(connectionFactory);
//component.getConfiguration().setCacheLevelName("CACHE_CONNECTION");
//component.getConfiguration().setCacheLevel(DefaultMessageListenerContainer.CACHE_CONNECTION);
camelContext.addComponent("activemq", component);
return camelContext;
}
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from("activemq:test.a").to("activemq:test.b");
from("activemq:test.b").to("mock:result");
}
};
}
} |
/*
* Copyright (C) 2001, 2005 Gérard Milmeister
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
package org.vetronauta.latrunculus.core.math.morphism;
import org.vetronauta.latrunculus.core.math.element.generic.ModuleElement;
import org.vetronauta.latrunculus.core.math.element.generic.RingElement;
import org.vetronauta.latrunculus.core.math.morphism.endo.Endomorphism;
/**
* Morphism that represents a translation in an arbitrary module.
*
* @author Gérard Milmeister
*/
public final class TranslationMorphism<A extends ModuleElement<A,RA>, RA extends RingElement<RA>> extends Endomorphism<A,RA> {
private final A translate;
public TranslationMorphism(A translate) {
super(translate.getModule());
this.translate = translate;
}
@Override
public A map(A x) {
return x.sum(translate);
}
@Override
public boolean isModuleHomomorphism() {
return true;
}
@Override
public boolean isRingHomomorphism() {
return getDomain().isRing() && translate.isZero();
}
@Override
public boolean isLinear() {
return translate.isZero();
}
@Override
public boolean isIdentity() {
return translate.isZero();
}
@Override
public IdentityMorphism<RA, RA> getRingMorphism() {
return ModuleMorphism.getIdentityMorphism(getDomain().getRing());
}
/**
* Returns the translate <i>t</i> of <i>h(x) = x+t</i>.
*/
public A getTranslate() {
return translate;
}
@Override
public int compareTo(ModuleMorphism object) {
if (object instanceof TranslationMorphism) {
TranslationMorphism<?,?> morphism = (TranslationMorphism<?,?>)object;
return translate.compareTo(morphism.translate);
}
return super.compareTo(object);
}
@Override
public boolean equals(Object object) {
if (object instanceof TranslationMorphism) {
TranslationMorphism<?,?> morphism = (TranslationMorphism<?,?>)object;
return translate.equals(morphism.translate);
}
else {
return false;
}
}
@Override
public String toString() {
return "TranslationMorphism["+translate+"]";
}
public String getElementTypeName() {
return "TranslationMorphism";
}
} |
/*
* A program to automatically trade cryptocurrencies.
* Copyright (C) 2020 Tomas Skalicky
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.skalicky.cryptobot.exchange.tradingplatform.connectorfacade.api.bo.enums;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.BDDAssertions.catchThrowable;
import static org.assertj.core.api.BDDAssertions.then;
public class CurrencyBoEnumUTest {
@Test
public void test_getByLabel_when_existingNonNullCurrencyLabel_then_enumValue() {
// When
final CurrencyBoEnum actual = CurrencyBoEnum.getByLabel("EUR");
// Then
then(actual).isEqualTo(CurrencyBoEnum.EUR);
}
@Test
public void test_getByLabel_when_null_then_others() {
// When
final CurrencyBoEnum actual = CurrencyBoEnum.getByLabel(null);
// Then
then(actual).isEqualTo(CurrencyBoEnum.OTHERS);
}
@Test
public void test_getByLabel_when_nonExistingCurrencyLabel_then_exception() {
// When
final Throwable caughtThrowable = catchThrowable(() -> CurrencyBoEnum.getByLabel("LTC"));
// Then
then(caughtThrowable)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unsupported label [LTC]");
}
} |
// Copyright (C) 2010-2012 INRIA
// Author(s): Kévin Charpentier, Vivien Mallet, Anne Tilloy
//
// This file is part of the data assimilation library Verdandi.
//
// Verdandi is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your option)
// any later version.
//
// Verdandi is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
// more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Verdandi. If not, see http://www.gnu.org/licenses/.
//
// For more information, visit the Verdandi web site:
// http://verdandi.gforge.inria.fr/
#ifndef VERDANDI_FILE_METHOD_TR1PERTURBATIONMANAGER_HXX
#define VERDANDI_FILE_METHOD_TR1PERTURBATIONMANAGER_HXX
#include "BasePerturbationManager.hxx"
#include <tr1/random>
namespace Verdandi
{
// TR1PERTURBATIONMANAGER //
//! This class generates random samples using C++ TR1 library.
class TR1PerturbationManager:
public BasePerturbationManager<TR1PerturbationManager>
{
protected:
typedef tr1::mt19937 engine;
typedef tr1::uniform_real<double> distribution_uniform;
typedef tr1::variate_generator<engine, distribution_uniform>
generator_uniform;
typedef tr1::normal_distribution<double> distribution_normal;
typedef tr1::variate_generator<engine, distribution_normal>
generator_normal;
//! Mersenne Twister random number generator.
engine* urng_;
//! Uniform distribution.
distribution_uniform* distribution_uniform_;
//! Uniform variate generator.
generator_uniform* variate_generator_uniform_;
//! Uniform distribution.
distribution_normal* distribution_normal_;
//! Uniform variate generator.
generator_normal* variate_generator_normal_;
public:
/*** Constructors and destructor ***/
TR1PerturbationManager();
TR1PerturbationManager(string configuration_file);
TR1PerturbationManager(const TR1PerturbationManager &);
~TR1PerturbationManager();
/*** Methods ***/
void Initialize(string configuration_file);
void Initialize(VerdandiOps& configuration_stream);
void Finalize();
double Normal(double mean, double variance,
Vector<double, VectFull>& parameter);
double LogNormal(double mean, double variance,
Vector<double, VectFull>& parameter);
double Uniform(double min, double max);
int UniformInt(int min, int max);
template <class T0, class T1,
class Prop0, class Allocator0>
void Normal(Matrix<T0, Prop0, RowSymPacked, Allocator0> variance,
Vector<double, VectFull>& parameter,
Vector<T1, VectFull, Allocator0>& sample);
template <class T0, class Prop0, class Allocator0,
class T1, class Allocator1>
void LogNormal(Matrix<T0, Prop0, RowSymPacked, Allocator0> variance,
Vector<double, VectFull>& parameter,
Vector<T1, VectFull, Allocator1>& output);
template <class T0,
class T1, class Allocator1>
void NormalHomogeneous(T0 variance,
Vector<double, VectFull>& parameter,
Vector<T1, VectFull, Allocator1>& output);
template <class T0,
class T1, class Allocator1>
void LogNormalHomogeneous(T0 variance,
Vector<double, VectFull>& parameter,
Vector<T1, VectFull, Allocator1>& output);
template <class T0,
class T1, class Allocator0>
bool NormalClipping(Vector<T0, VectFull>& diagonal,
Vector<double, VectFull>& parameter,
Vector<T1, VectFull, Allocator0>& output);
};
} // namespace Verdandi.
#endif |
Rules of the Wubi input method
Each key is assigned ...
1. Several roots.
2. A representative root (the first one in wubi-keys.jpg),
e.g. 月 for E.
3. A frequently used character (above the roots in wubi-keys.jpg),
e.g. 有 for E.
These should be learned by heart. There is a quasi-logical system:
- T-R-E-W-Q contain roots starting with a left-falling stroke
(with T-R-E corresponding to 1, 2 and 3 such strokes, respectively)
- Y-U-I-O-P contain roots starting with a right-falling stroke
(with Y-U-I-O corresponding to 1, 2, 3 and 4 such strokes, respectively)
- G-F-D-S-A contain roots starting with a horizontal stroke
(with G-F-D corresponding to 1, 2 and 3 such strokes, respectively)
- H-J-K-L-M(!) contain roots starting with a vertical stroke
(with H-J-K-L corresponding to 1, 2, 3 and 4 such strokes, respectively)
- N-B-V-C-X contain roots strating with a turning stroke
(with N-B-V corresponding to 1, 2 and 3 such strokes, respectively)
Also, the frequently used characters are mostly connected to the roots
on that key.
Each hanzi is written with at most 4 characters. There are various cases:
1. Frequent characters can be written just by typing the corresponding key.
(And an implementation defined conversion key, such as <space>.)
E.g. 不 : I
2. Representative roots can be written by typing the corresponding key 4 times.
E.g. 水 : IIII
3. All hanzi are written by pressing the roots building up the character.
3a. When it is a (non-representative) root, start by pressing the
corresponding key, then build up the character by its strokes,
using the keys T/Y/G/H/N.
E.g. 小 : IHTY (H, T & Y are its three strokes)
3a/1. When it is still less than 4 keys, press the conversion key.
E.g. 十 : FGH (G & H are its two strokes)
(In the rare case when it is still not isolated, the code is
augmented with 'L's, e.g. 乙 : NNL)
3a/2. When it is more than 4 keys, the last key should correspond
to its last stroke.
E.g. 用 : ETNH (T & N are the first 2 strokes, H the last)
3b. When it has at least 4 roots, type the codes for the first, second,
third and last one.
E.g. 馒 : QNJC (Q & N builds the left part, J the top-right,
C the bottom-right; the middle-right is not represented)
3c. When it has less than 4 roots,
3c/1. When it is a left-right character, type its last stroke
with the first key of each type (T/Y/G/H/N).
E.g. 悟 : NGKG (G represents the last horizontal stroke)
3c/2. When it is a top-bottom character, type its last stroke
with the second key of each type (R/U/F/J/B).
E.g. 岸 : MDFJ (J represents the last vertical stroke)
3c/3. In all other cases, type its last stroke
with the third key of each type (E/I/D/K/V).
E.g. 圆 : LKMI (I represents the last right-falling stroke)
4. Any key that is already isolated with fewer than 4 keys can be written
by pressing the conversion key.
5. In some implementations, the Z key can be used as a wildcard;
in others it is used for pinyin input.
In addition to the above, some frequently used (multi-character) words
and phrases can be written with one 4-key code:
1. Words of 2 characters are typed using the first 2 keys of each code.
E.g. 社会 : PYWF (社 PYFG + 会 WFCU)
2. Words of 3 characters are typed using the first key of the first two
characters, and the first 2 keys of the last character.
E.g. 电视剧 : JPND (电 JNV + 视 PYMQ + 剧 NDJH)
3. Words of 4+ characters are typed using the first key of first,
second, third and last character.
E.g. 中国共产党 : KLAI (中 KHK + 国 LGYI + 共 AWU + 党 IPKQ)
Efficiency
----------
Here's a table of all 606 characters that can be typed with at most 2 keys:
工 了 以 在 有 地 一 上 不 是 中 国 同 民 为 这 我 的 要 和 产 发 人 经 主
A B C D E F G H I J K L M N O P Q R S T U V W X Y
A 式 节 芭 基 菜 革 七 牙 东 划 或 功 贡 世 〇 芝 区 匠 苛 攻 燕 切 共 药 芳
B 陈 子 取 承 阴 际 卫 耻 孙 阳 职 阵 出 也 耿 辽 隐 孤 阿 降 联 限 队 陛 防
C 戏 邓 双 参 能 对 〇 〇 〇 〇 台 劝 观 马 〇 驼 允 牟 〇 矣 〇 艰 难 〇 驻
D 左 顾 友 大 胡 夺 三 丰 砂 百 右 历 面 成 灰 达 克 原 厅 帮 磁 肆 春 龙 太
E 肛 服 肥 〇 朋 肝 且 〇 膛 胆 肿 肋 肌 甩 〇 爱 胸 遥 采 用 胶 妥 脸 脂 及
F 载 地 支 城 圾 寺 二 直 示 进 吉 协 南 志 赤 过 无 垢 霜 才 增 雪 夫 〇 坟
G 开 屯 到 天 表 于 五 下 不 理 事 画 现 与 来 〇 列 珠 末 玫 平 妻 珍 互 玉
H 虎 〇 皮 睚 肯 睦 睛 止 步 旧 占 卤 贞 卢 眯 瞎 餐 〇 盯 睡 瞳 眼 具 此 眩
I 江 池 汉 尖 肖 法 汪 小 水 浊 澡 渐 没 沁 淡 学 光 泊 洒 少 洋 当 兴 涨 注
J 虹 最 紧 晨 明 时 量 早 晃 昌 蝇 曙 遇 电 显 晕 晚 蝗 果 昨 暗 归 蛤 昆 景
K 呀 啊 吧 顺 吸 叶 呈 中 吵 虽 吕 另 员 叫 〇 喧 史 听 呆 呼 啼 哪 只 哟 嘛
L 〇 囝 轻 因 胃 轩 车 四 〇 辊 加 男 轴 思 〇 边 罗 斩 困 力 较 轨 办 累 罚
M 曲 邮 凤 央 骨 财 同 由 峭 则 〇 崭 册 岂 〇 迪 风 贩 朵 几 赠 〇 内 嶷 凡
N 民 敢 怪 居 〇 导 怀 收 悄 慢 避 惭 届 忆 屡 忱 懈 怕 〇 必 习 恨 愉 尼 心
O 煤 籽 烃 类 粗 灶 业 粘 炒 烛 炽 烟 灿 断 炎 迷 炮 煌 灯 烽 料 娄 粉 〇 米
P 宽 字 〇 害 家 守 定 寂 宵 审 宫 军 宙 官 灾 之 宛 宾 宁 客 实 安 空 它 社
Q 氏 凶 色 然 角 针 钱 外 乐 旬 名 甸 负 包 炙 锭 多 铁 钉 儿 匀 争 欠 〇 久
R 找 报 反 拓 扔 持 后 年 朱 提 扣 押 抽 所 搂 近 换 折 打 手 拉 扫 失 批 扩
S 械 李 权 枯 极 村 本 相 档 查 可 楞 机 杨 杰 棕 构 析 林 格 样 要 检 楷 术
T 长 季 么 知 秀 行 生 处 秒 得 各 务 向 秘 秋 管 称 物 条 笔 科 委 答 第 入
U 并 闻 冯 关 前 半 闰 站 冰 间 部 曾 商 决 普 帝 交 瓣 亲 产 立 妆 闪 北 六
V 毁 好 妈 姑 奶 寻 姨 〇 录 旭 如 舅 妯 刀 灵 巡 婚 〇 杂 九 嫌 妇 〇 姆 妨
W 代 他 公 估 仍 会 全 个 偿 介 保 佃 仙 亿 伙 〇 你 伯 休 作 们 分 从 化 信
X 红 弛 经 顷 级 结 线 引 纱 旨 强 细 纲 纪 继 综 约 绵 〇 张 弱 绿 给 比 纺
Y 度 离 充 庆 衣 计 主 让 就 刘 训 为 高 记 变 这 义 诉 订 放 说 良 认 率 方
A B C D E F G H I J K L M N O P Q R S T U V W X Y
(There are 25 1-key characters, and 25x25 = 625 possible 2-key characters, but
33 of the latter do not exist (marked with a 〇), and 11 characters can be written
both with 1 or 2 keys, so 25 + 625 - 33 - 11 = 606.)
This contains 80 of the 100 most common characters, and the rest can
be typed with 3 keypresses, except for 日 (JJJJ) and 都 (FTJB).
In the database of this program, there are approx. 11,000 characters
(4-key sequences: ~6,000, 3-key sequences: ~4,400), and around 49,000
multi-character combinations (2 characters: ~37,000, 3 characters: ~6,000,
4+ characters: ~6,000).
Although almost all characters have different codes, there are a few
clashes, e.g. 去/云 (FCU), 风/冈 (MQI) or 喜/嘉 (FKUK). In the first
case, FC is already occupied by 支, so there is no way to distinguish
between the two alternatives. In the other two, MQ and FKU are not
assigned to different characters, so in theory this could be harnessed
to avoid ambiguity, but it is not done in practice. Instead, the less
frequent characters can be typed by choosing from a list, normally by
typing the number 2.
Standards
---------
As a final note, there are two standards, one from 1986 and one from 1998.
These differ in the interpretation of many characters, for example the
character 凹 is treated as MMGD in the '86 version (where the two 'M's
represent the first 2-2 strokes - note that the first M is "cheating",
as its 2nd stroke is Z-shaped), and as HNHG in the '98 version.
While the newer version is often more logical, the '86 variant seems to
be the more popular one.
Sources
-------
Joe Wicentowski's page "Wubizixing for Speakers of English" (1996). |
@(fields: List[models.Field])
@top.render()
<body>
<div class="mytab">
<div class="addbutton"> <input class="btn btn-primary" onclick="location.href='createfield'" type="button" value="+ ADD FIELD"></div>
<table class="table table-striped">
<tr>
<th>Label</th>
<th>Type</th>
<th>Required</th>
<th>Is Active</th>
<th></th>
<th></th>
<th></th>
</tr>
@if(fields.isEmpty) {
<h4>No fields yet</h4>
}
@for(field <- fields) {
<tr> <td>@field.getLabel</td>
<td>@field.getType.toString</td>
<td>
<input type="checkbox" disabled="disabled" @if(field.isRequired) {
checked="checked"}></td>
<td>
<input type="checkbox" disabled="disabled" @if(field.isActive) {
checked="checked"}> </td>
<td>
<td>
<form action="/deletefield" method="POST">
<input type="hidden" value="@field.getFieldId" id="confirm" name="delid">
<input class="btn btn-danger confirm" type="submit" value="Delete">
</form>
</td>
<td>
<a href="/[email protected]" class="btn btn-info">Update</a>
</td>
</tr>
}
</table>
</div>
</body>
<link rel="stylesheet" href="@routes.Assets.versioned("stylesheets/crfield.css")">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-2.0.3.min.js" data-semver="2.0.3" data-require="jquery"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="@routes.Assets.versioned("javascripts/bootbox.min.js")"></script>
<script src="@routes.Assets.versioned("javascripts/fieldspage.js")"></script> |
package com.example.jojosproject.Adapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import com.example.jojosproject.DataClass.Carte
import com.example.jojosproject.DataClass.Joueur
import com.example.jojosproject.R
import com.example.jojosproject.ViewHolder.ViewHolderJoueurPartie
class AdaptaterJoueurPartie (private val joueursEtCartes: Map<Joueur, Carte>) :
RecyclerView.Adapter<ViewHolderJoueurPartie>() {
override fun onBindViewHolder(holder: ViewHolderJoueurPartie, position: Int) {
val (joueur, carte) = joueursEtCartes.entries.elementAt(position)
// Mettez à jour les vues du ViewHolder avec les données du joueur et de la carte
holder.textViewNom.text = joueur.nom
holder.textViewRôle.text = carte.nom
holder.checkVivant.isChecked = false
// Afficher/masquer et configurer les vues spécifiques en fonction du nom de la carte
when (carte.nom) {
"Sorciere" -> {
holder.linearLayoutSpecificite.removeAllViews() // Supprimer les vues existantes
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
// Créer et ajouter le TextView "Vie"
val textViewVie = TextView(holder.linearLayoutSpecificite.context)
textViewVie.text = "Vie"
textViewVie.layoutParams = layoutParams
textViewVie.setTextColor(Color.WHITE) // Changer la couleur du texte en blanc
textViewVie.setBackgroundColor(Color.TRANSPARENT) // Définir un fond transparent
holder.linearLayoutSpecificite.addView(textViewVie)
// Créer et ajouter la CheckBox "Vie"
val checkBoxVie = CheckBox(holder.linearLayoutSpecificite.context)
checkBoxVie.layoutParams = layoutParams
checkBoxVie.isChecked = true
holder.linearLayoutSpecificite.addView(checkBoxVie)
// Créer et ajouter le TextView "Mort"
val textViewMort = TextView(holder.linearLayoutSpecificite.context)
textViewMort.text = "Mort"
textViewMort.layoutParams = layoutParams
textViewMort.setTextColor(Color.WHITE) // Changer la couleur du texte en blanc
textViewMort.setBackgroundColor(Color.TRANSPARENT) // Définir un fond transparent
holder.linearLayoutSpecificite.addView(textViewMort)
// Créer et ajouter la CheckBox "Mort"
val checkBoxMort = CheckBox(holder.linearLayoutSpecificite.context)
checkBoxMort.layoutParams = layoutParams
checkBoxMort.isChecked = true
holder.linearLayoutSpecificite.addView(checkBoxMort)
}
"Cupidon" -> {
holder.linearLayoutSpecificite.removeAllViews() // Supprimer les vues existantes
// Créer et ajouter les Spinners dynamiquement
val spinnerJoueur1 = Spinner(holder.linearLayoutSpecificite.context)
// Récupérer la liste des joueurs disponibles
val listeJoueursDisponibles = joueursEtCartes.keys.map { it.nom }
// Configurer les options du spinner en fonction des joueurs disponibles
val joueurAdapter1 = ArrayAdapter(
holder.linearLayoutSpecificite.context,
android.R.layout.simple_spinner_item,
listeJoueursDisponibles
)
spinnerJoueur1.adapter = joueurAdapter1
spinnerJoueur1.setBackgroundColor(Color.WHITE) // Changer la couleur du fond en blanc
holder.linearLayoutSpecificite.addView(spinnerJoueur1)
// Créer et ajouter le cœur
val heartTextView = TextView(holder.linearLayoutSpecificite.context)
heartTextView.text = "❤️"
holder.linearLayoutSpecificite.addView(heartTextView)
val spinnerJoueur2 = Spinner(holder.linearLayoutSpecificite.context)
// Configurer les options du spinner en fonction des joueurs disponibles
val joueurAdapter2 = ArrayAdapter(
holder.linearLayoutSpecificite.context,
android.R.layout.simple_spinner_item,
listeJoueursDisponibles
)
spinnerJoueur2.adapter = joueurAdapter2
spinnerJoueur2.setBackgroundColor(Color.WHITE) // Changer la couleur du fond en blanc
holder.linearLayoutSpecificite.addView(spinnerJoueur2)
}
else -> {
// Pour les autres cartes, masquer le LinearLayout
holder.linearLayoutSpecificite.visibility = View.INVISIBLE
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderJoueurPartie {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.joueur_en_partie, parent, false)
return ViewHolderJoueurPartie(view)
}
override fun getItemCount(): Int {
return joueursEtCartes.size
}
} |
import * as express from 'express';
import { NextFunction, Request, Response } from 'express';
import { handleAsync } from '../common/helpers';
import { AuthController } from '../controllers/authController';
import {
LoginDto,
UpdatePasswordDto,
UserRegistrationDto,
} from '../dtos/user.dto';
import {
userRegistrationSchema,
loginSchema,
updatePasswordSchema,
} from '../schemas';
import { validateRequest } from '../middleware/validateInput';
import { jwtValidator } from '../middleware/jwtValidator';
import { TRequestWithToken } from '../common/types/user.types';
const authController = new AuthController();
const AuthRouter = express.Router();
AuthRouter.post(
'/auth/register',
validateRequest(userRegistrationSchema),
handleAsync(async (req: Request, res: Response, next: NextFunction) => {
const data = req.body as UserRegistrationDto;
const result = await authController.register(data);
res.status(201).json(result);
}),
);
AuthRouter.post(
'/auth/login',
validateRequest(loginSchema),
handleAsync(async (req: Request, res: Response) => {
const loginDto = req.body as LoginDto;
const result = await authController.login(loginDto);
res.status(200).json(result);
}),
);
AuthRouter.put(
'/auth/password',
jwtValidator,
validateRequest(updatePasswordSchema),
handleAsync(
async (req: TRequestWithToken, res: Response, next: NextFunction) => {
const result = await authController.updatePassword(
req.user.userId,
req.body.oldPassword,
req.body.newPassword,
);
const { password, ...data } = result;
res.status(200).json(data);
},
),
);
export { AuthRouter }; |
package en.gregthegeek.gfactions.economy;
import java.util.HashMap;
import en.gregthegeek.gfactions.db.Datasource;
import en.gregthegeek.gfactions.faction.Faction;
import en.gregthegeek.util.Utils;
/**
* Represents an economy managed by gFactions.
*
* @author gregthegeek
*
*/
public class IntegratedEconomy implements Economy {
private final HashMap<String, Integer> players = new HashMap<String, Integer>(); // player name -> balance
private final HashMap<Integer, Integer> factions = new HashMap<Integer, Integer>(); // faction id -> balance
@Override
public void initPlayer(String player) {
if(!players.containsKey(player)) {
players.put(player, Utils.plugin.getDataSource().getBalance(player));
}
}
@Override
public void initFaction(int id) {
if(!factions.containsKey(id)) {
factions.put(id, Utils.plugin.getDataSource().getBalance(id));
}
}
@Override
public boolean modifyBalance(String player, int amount) {
assert players.containsKey(player);
int newAmt = players.get(player) + amount;
if(newAmt >= 0) {
players.put(player, newAmt);
if(Utils.plugin.getConfig().getSaveInterval() < 0) {
Utils.plugin.getDataSource().savePlayerBalances(players);
}
return true;
}
return false;
}
@Override
public int getBalance(String player) {
assert players.containsKey(player);
return players.get(player);
}
@Override
public boolean modifyBalance(Faction fac, int amount) {
int id = fac.getId();
assert factions.containsKey(id);
int newAmt = factions.get(id) + amount;
if(newAmt >= 0) {
factions.put(id, newAmt);
if(Utils.plugin.getConfig().getSaveInterval() < 0) {
Utils.plugin.getDataSource().saveFactionBalances(factions);
}
return true;
}
return false;
}
@Override
public int getBalance(Faction fac) {
assert factions.containsKey(fac.getId());
return factions.get(fac.getId());
}
@Override
public void save() {
Datasource ds = Utils.plugin.getDataSource();
ds.savePlayerBalances(players);
ds.saveFactionBalances(factions);
}
} |
.gf-button {
background: $colour-light-grey;
text-align: center;
align-items: center;
justify-content: center;
display: inline-flex;
border-radius: $default-button-border-radius;
text-transform: uppercase;
cursor: pointer;
box-sizing: border-box;
border: none;
font-family: $header-font;
font-weight: 700;
padding: 1em 3em;
border: none;
position: relative;
margin-right: 5px;
letter-spacing: 1px;
box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
}
// STATES
.gf-button {
&:focus {
outline: 0;
}
&:hover {
background: darken($colour-light-grey, 5%);
box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
}
&:active{
outline: 0;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}
}
// COLOURS
@each $name, $colour in $siteColours {
.gf-button--#{$name} {
background: $colour;
@if $name == white {
color: $colour-dark-grey;
} @else if $name == 'light-grey' {
color: $colour-dark-grey;
} @else {
color: $colour-white;
}
&:hover {
background: darken($colour, 5%);
}
}
}
// SIZES
@each $size, $value in $sizes {
.gf-button--#{$size} {
font-size: $value + em;
}
}
// VARIATION
.gf-button--hard {
border-radius: 2px;
}
.gf-button--fluid {
width: 100%;
}
// GRADIENTS
@each $name, $colour in $siteColours {
.gf-button--#{$name}-gradient {
background: $colour;
background: linear-gradient(to bottom, $colour 0%,darken($colour, 5%) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=$colour, endColorstr=darken($colour, 5%),GradientType=0 );
}
} |
import React, { useState, useEffect } from "react";
import axios from "axios";
import moment from "moment";
import { useParams } from "react-router-dom";
import StripeCheckout from "react-stripe-checkout";
import Swal from "sweetalert2";
import Loader from "../components/Loader";
import Error from "../components/Error";
import { api } from "../api";
function Bookingscreen() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [room, setRoom] = useState({});
const [totalAmount, setTotalAmount] = useState(0);
const [totalDays, setTotalDays] = useState(0);
const params = useParams();
console.log(params);
const fromdate = moment(params.fromdate, "DD-MM-YYYY");
const todate = moment(params.todate, "DD-MM-YYYY");
useEffect(() => {
const user = JSON.parse(localStorage.getItem("currentUser"));
if (!user) {
window.location.href = "/login";
}
async function fetchMyAPI() {
try {
setError("");
setLoading(true);
const res = await axios.post(`${api}/api/rooms/getroombyid`, {
roomid: params.roomid,
});
// console.log(res.data);
setRoom(res.data);
} catch (error) {
// console.log(error);
setError(error);
}
setLoading(false);
}
fetchMyAPI();
}, []);
useEffect(() => {
const totaldays = moment.duration(todate.diff(fromdate)).asDays() + 1;
setTotalDays(totaldays);
setTotalAmount(totalDays * room.rentperday);
}, [room]);
const onToken = async (token) => {
// console.log(token);
const bookingDetails = {
room,
userid: JSON.parse(localStorage.getItem("currentUser")).data._id,
fromdate,
todate,
totalAmount,
totaldays: totalDays,
token,
};
try {
setLoading(true);
const result = await axios.post(`${api}/api/bookings/bookroom`, bookingDetails);
// console.log(result);
setLoading(false);
Swal.fire(
"Congratulations",
"Your Room Booked Successfully",
"success"
).then((result) => {
window.location.href = "/home";
});
} catch (error) {
setError(error);
Swal.fire("Opps", "Error:" + error, "error");
}
setLoading(false);
};
return (
<div className="m-5">
{loading ? (
<Loader />
) : error.length > 0 ? (
<Error msg={error} />
) : (
<div className="row justify-content-center mt-5 bs">
<div className="col-md-6">
<h1>{room.name}</h1>
<img src={room.imageurls[0]} alt="" className="bigimg" />
</div>
<div className="col-md-6">
<div
// style={{ textAlign: "right" }}
>
<h1>Booking Details</h1>
<hr />
<b>
<p>
Name :{" "}
{JSON.parse(localStorage.getItem("currentUser")).data.name}
</p>
<p>
Location : {room.locality}
</p>
<p>From Date : {params.fromdate}</p>
<p>To Date : {params.todate}</p>
<p>Max People Allowed : {room.maxcount}</p>
</b>
</div>
<div
// style={{ textAlign: "right" }}
>
<h1>Amount</h1>
<hr />
<b>
<p>Total Days : {totalDays}</p>
<p>Rent per day : {room.rentperday}</p>
<p>Total Amount : {totalAmount}</p>
</b>
</div>
<div style={{ float: "right" }}>
<StripeCheckout
amount={totalAmount * 100}
currency="INR"
token={onToken}
stripeKey="pk_test_51LiJiNSFM2DZrNaCXsOJxV9xaaR3rBqrIZ6rQWtIYpOjnJGBwrZQVwwUlQiPmlfGnL2MxJJw8bpeEoJarTxhMLDc00l9sSTsRc"
>
<button className="btn btn-primary">Pay Now</button>
</StripeCheckout>
</div>
</div>
</div>
)}
</div>
);
}
export default Bookingscreen; |
package cronies.meeting.user.service.impl;
import cronies.meeting.user.service.InviteService;
import cronies.meeting.user.service.CommonService;
import cronies.meeting.user.service.PushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import select.spring.exquery.service.ExqueryService;
import java.util.HashMap;
import java.util.UUID;
@Service("InviteService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class InviteServiceImpl implements InviteService {
Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private ExqueryService exqueryService;
@Autowired
private CommonService commonService;
@Autowired
private PushService pushService;
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public HashMap<String, Object> getUserInviteCode(HashMap<String, Object> param) throws Exception {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
param.put("userId", param.get("ssUserId"));
resultMap = exqueryService.selectOne("cronies.app.invite.getUserInviteCode", param);
String nanoId = "";
Boolean isExist = false;
if(resultMap != null){
isExist = true;
resultMap.put("successYn", "Y");
}
while(!isExist){
// nanoId 생성
nanoId = commonService.getNanoId(6);
// nanoId 중복체크
param.put("nanoId", nanoId);
if(checkNanoId(param) == null){
try {
exqueryService.insert("cronies.app.invite.insertInviteInfo", param);
resultMap = exqueryService.selectOne("cronies.app.invite.getUserInviteCode", param);
resultMap.put("successYn", "Y");
} catch (Exception e) {
resultMap.put("successYn", "N");
resultMap.put("message", "초대코드 확인 중 오류가 발생하였습니다. 문의 부탁드립니다.");
}
isExist = true;
}
}
return resultMap;
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public HashMap<String, Object> saveTargetInviteCode(HashMap<String, Object> param) throws Exception {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
param.put("userId", param.get("ssUserId"));
// 초대코드 등록 여부 확인
if(exqueryService.selectOne("cronies.app.invite.checkInviteHis", param) == null){
// 초대코드가 유효한지 확인
resultMap = exqueryService.selectOne("cronies.app.invite.checkTargetUserInviteCode", param);
if(resultMap == null){
resultMap = new HashMap<String, Object>();
resultMap.put("successYn", "N");
resultMap.put("message", "유효하지 않은 상대방 코드입니다.");
} else {
try {
param.put("targetUserId", resultMap.get("userId"));
param.put("inviteUserId", param.get("userId"));
// 친구코드 등록
exqueryService.insert("cronies.app.invite.insertInviteCode", param);
exqueryService.insert("cronies.app.invite.insertInvitePointHis", param);
exqueryService.update("cronies.app.invite.updateInvitePoint", param);
// exqueryService.update("cronies.app.invite.updateInvitePoint2", param);
resultMap = exqueryService.selectOne("cronies.app.invite.getUserInviteCode", param);
resultMap.put("successYn", "Y");
resultMap.put("message", "초대코드 등록에 성공하였습니다!");
} catch (Exception e) {
resultMap.put("successYn", "N");
resultMap.put("message", "초대코드 등록 중 오류가 발생하였습니다. 문의 부탁드립니다.");
}
}
} else {
resultMap.put("successYn", "N");
resultMap.put("message", "이미 초대코드를 등록하셨습니다.");
}
return resultMap;
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public HashMap<String, Object> checkNanoId(HashMap<String, Object> param) throws Exception {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap = exqueryService.selectOne("cronies.app.invite.checkNanoId", param);
return resultMap;
}
} |
/***************************************************************************************
*@file dnxNode.h
*@author Steven D.Morrey ([email protected])
*@c (c)2008 Intellectual Reserve, Inc.
*
* The purpose of this file is to define a worker node instrumentation class.
***************************************************************************************/
#include "dnxTypes.h"
#ifndef DNXNODE
#define DNXNODE
enum
{
JOBS_DISPATCHED,
JOBS_HANDLED,
JOBS_REJECTED_OOM,
JOBS_REJECTED_NO_NODES,
JOBS_REQ_RECV,
JOBS_REQ_EXP,
HOSTNAME,
AFFINITY_FLAGS
};
/** DnxNodes are more than just simple structs for keeping track of IP addresses
* They are a linked list of worker nodes tied to relevant metrics
*/
typedef struct DnxNode
{
struct DnxNode* next; //!< Next Node
struct DnxNode* prev; //!< Previous Node
char* address; //!< IP address or URL of worker
char* hostname; //!< Hostname defined in dnxClient.cfg
unsigned long long int flags; //!< Affinity flags assigned during init
unsigned jobs_dispatched; //!< How many jobs have been sent to worker
unsigned jobs_handled; //!< How many jobs have been handled
unsigned jobs_rejected_oom; //!< How many jobs have been rejected due to memory
unsigned jobs_rejected_no_nodes; //!< How many jobs have been rejected due to no available nodes
unsigned jobs_req_recv; //!< How many job requests have been recieved from worker
unsigned jobs_req_exp; //!< How many job requests have expired
pthread_mutex_t mutex; //!< Thread locking control structure
} DnxNode;
/** Node Creation Function for DnxNodes
* Create a new node and add it to the end of the list
* @param address - IP address of the worker node
* @param pTopDnxNode - Pointer to the node you want to add to
* @return pDnxNode - Pointer to the newly created node
*
* NOTE: If a node already exists with that IP address, then
* we return the existing node instead of creating a new node
*/
DnxNode* dnxNodeListCreateNode(char *address, char *hostname);
/** Node Destruction Function
* This function can be used to remove the entire list
*/
void dnxNodeListDestroy();
/** Removal function for DnxNodes
* Remove and delete a node.
* Since all nodes are linked together in a list, this function will also heal the list
* by pointing prev at next and vice versa
* @param pDnxNode - A pointer to the node you want to remove
* @return - A pointer to the next node in the list
*/
DnxNode* dnxNodeListRemoveNode(DnxNode* pDnxNode);
/** Removal function for DnxNodes
* Remove and delete all nodes.
* Then recreate gTopNode
*/
void dnxNodeListReset();
/** Return a pointer to the end node
*/
DnxNode* dnxNodeListEnd();
/** Return a pointer to the beginning node
*/
DnxNode* dnxNodeListBegin();
/** Find a node by it's IP address
* @param address - The IP address of the node you want to find
* @return - A pointer to the node if found, if not found it returns NULL
*/
DnxNode* dnxNodeListFindNode(char* address);
/** Count the nodes
*/
int dnxNodeListCountNodes();
/** Count a given member value from all nodes
* Internal use function, use dnxNodeListCountX functions instead
*/
unsigned dnxNodeListCountValuesFromAllNodes(int member);
/** Return a member value from a single node
* Internal use function, use dnxNodeListCountX functions instead
*/
unsigned dnxNodeListGetMemberValue(DnxNode* pDnxNode, int member);
/** Place holder function to determine if we want values from all nodes or just one
* Internal use function, use dnxNodeListCountX functions instead
*/
unsigned dnxNodeListCount(char* address, int member);
unsigned dnxNodeListIncrementNodeMember(char* address,int member);
unsigned dnxNodeListSetNode(char* address, int member, void* value);
static void * dnxStatsRequestListener(void *vptr_args);
#endif |
import React, { Component } from 'react';
import styles from './style.scss';
import { Router, Route, Link } from 'react-router'
import AppBar from 'material-ui/lib/app-bar';
import IconButton from 'material-ui/lib/icon-button';
import NavigationClose from 'material-ui/lib/svg-icons/navigation/close';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
import MenuItem from 'material-ui/lib/menus/menu-item';
import FlatButton from 'material-ui/lib/flat-button';
import RaisedButton from 'material-ui/lib/raised-button';
import Avatar from 'material-ui/lib/avatar';
import DropDownMenu from 'material-ui/lib/DropDownMenu';
import LeftNav from 'material-ui/lib/left-nav';
import withStyles from '../../../decorators/withStyles';
@withStyles(styles)
class Header extends Component {
constructor(props) {
super(props);
this.state = {
showLeftNavigation: false
};
}
showLeftNavigation = () => {
this.setState({
showLeftNavigation: true
});
};
hideLeftNavigation = () => {
this.setState({
showLeftNavigation: false
});
};
handleRequestChange = (open) => {
this.setState({
showLeftNavigation: open
});
};
logout = async () => {
window.location.href = '/#/';
};
render() {
return (
<div>
<AppBar title="Pager" onLeftIconButtonTouchTap={this.showLeftNavigation}
iconElementRight={
window.isAuthenticated ?
<IconMenu
iconButtonElement={<IconButton><Avatar src={window.user.githubProfile._json.avatar_url} /></IconButton>}
>
<MenuItem primaryText="设置" />
<MenuItem primaryText="注销" onTouchTap={this.logout} />
</IconMenu>
:
<FlatButton label="登录" linkButton={true} href="/api/auth/login/github" />
}
/>
<LeftNav docked={false} width={200} open={this.state.showLeftNavigation} onRequestChange={this.handleRequestChange}>
<AppBar title="导航" onLeftIconButtonTouchTap={this.hideLeftNavigation}/>
<RaisedButton label="首页" fullWidth={true} linkButton={true} href="/#/" />
<RaisedButton label="项目列表" fullWidth={true} linkButton={true} href="/#/projects" />
<RaisedButton label="组件列表" fullWidth={true} linkButton={true} href="/#/components" />
<RaisedButton label="页面列表" fullWidth={true} linkButton={true} href="/#/pages" />
<RaisedButton label="用户列表" fullWidth={true} linkButton={true} href="/#/users" />
</LeftNav>
</div>
);
}
}
export default Header; |
@demo
Feature: Search
In order to see a word definition
As a website user
I need to be able to search for a word
Scenario: Searching for a page that does exist
Given I am on "https://www.wikipedia.org/wiki/Main_Page"
When I fill in "search" with "Behavior Driven Development"
And I press "searchButton"
Then I should see "agile software development"
Then I save screenshot
Scenario: Searching for a page that does NOT exist
Given I am on "https://www.wikipedia.org/wiki/Main_Page"
When I fill in "search" with "Glory Driven Development"
And I press "searchButton"
Then I should see "Search results"
Then I save screenshot |
<script>
import { defineComponent, ref, reactive, watch, nextTick, toRefs } from "vue"
/**
* Composable
*/
import { useOnOutsidePress } from "@/composable/onOutside"
export default defineComponent({
name: "Dropdown",
props: {
forceOpen: Boolean,
side: {
type: String,
default: "bottom",
},
},
emits: ["onClose"],
setup(props, context) {
const { side, forceOpen } = toRefs(props)
const trigger = ref(null)
const dropdown = ref(null)
const isOpen = ref(false)
watch(forceOpen, () => {
isOpen.value = forceOpen.value
})
const toggleDropdown = (event) => {
event.stopPropagation()
isOpen.value = !isOpen.value
}
const close = (event) => {
if (event) event.stopPropagation()
isOpen.value = false
context.emit("onClose")
}
const dropdownStyles = reactive({
top: `initial`,
right: 0,
bottom: `initial`,
})
let removeOutside
watch(isOpen, () => {
if (!isOpen.value) {
removeOutside()
document.removeEventListener("keydown", onKeydown)
} else {
document.addEventListener("keydown", onKeydown)
const triggerHeight =
trigger.value.getBoundingClientRect().height
if (side.value == "bottom") {
dropdownStyles.top = `${triggerHeight + 6}px`
}
if (side.value == "top") {
dropdownStyles.bottom = `${triggerHeight + 6}px`
}
nextTick(() => {
removeOutside = useOnOutsidePress(dropdown, close)
})
}
})
const onKeydown = (event) => {
if (event.key == "Escape") close()
}
return {
trigger,
dropdown,
isOpen,
toggleDropdown,
close,
dropdownStyles,
}
},
})
</script>
<template>
<div ref="dropdown" :class="$style.wrapper">
<div ref="trigger" @click="toggleDropdown" :class="$style.trigger">
<slot name="trigger" />
</div>
<transition name="popup">
<div v-if="isOpen" @click="close" :class="$style.dropdown" :style="dropdownStyles">
<slot name="dropdown" />
</div>
</transition>
</div>
</template>
<style module>
.wrapper {
position: relative;
}
.trigger {
cursor: pointer;
}
.dropdown {
position: absolute;
z-index: 1000;
padding: 8px 0;
border-radius: 8px;
background: var(--dropdown-bg);
}
</style> |
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { LoginComponent } from "./auth/login/login.component";
import { RegisterComponent } from "./auth/register/register.component";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { HttpClientModule } from "@angular/common/http";
import { CommonModule } from "@angular/common";
import { InicioComponent } from "./auth/inicio/inicio.component";
import { HeaderComponent } from "./auth/header/header.component";
import { AngularFirestore } from "angularfire2/firestore";
import { AngularFireModule, FirebaseOptionsToken } from "angularfire2";
import { environment } from "src/environments/environment";
import { AngularFireAuth } from "angularfire2/auth";
import { AngularFirestoreModule } from "angularfire2/firestore";
import { AngularFireStorageModule } from "angularfire2/storage";
import { StoreModule } from "@ngrx/store";
import { ImagenesService } from "./services/imagenes.service";
import { PeliculasComponent } from './auth/peliculas/peliculas.component';
import { PipesImgPipe } from './pipes/pipes-img.pipe';
import { SeriesPipe } from './pipes/series.pipe';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent,
InicioComponent,
HeaderComponent,
PeliculasComponent,
PipesImgPipe,
SeriesPipe,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
CommonModule,
ReactiveFormsModule,
AngularFireModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireStorageModule,
AngularFirestoreModule,
StoreModule.forRoot({}),
HttpClientModule,
],
providers: [AngularFirestore, AngularFireAuth],
bootstrap: [AppComponent],
})
export class AppModule {} |
import React, {useContext, useEffect, useState} from 'react'
import {FaArrowRight} from 'react-icons/fa'
import { SelectedInstancesContext } from '../App';
import { useNavigate } from 'react-router-dom';
import { LoadingComponent } from './LoadingComponent';
import { toast, ToastContainer } from 'react-toastify';
import "react-toastify/dist/ReactToastify.css";
import { CanteenApi } from '../Helpers/Service/CanteenService';
export const MenuComponent = () => {
let navigate = useNavigate();
const selectedInstancesContext = useContext(SelectedInstancesContext);
const [loading, setLoading] = useState(true);
const [categories, setCategories] = useState([]);
useEffect(() => {
CanteenApi.GetAllCategoriesWithPictures()
.then(res => setCategories(res))
.then(() => setLoading(false))
.catch(() => toast.error('S-a produs o eroare!'));
}, [])
return (
<div>
{loading === true &&
<LoadingComponent />
}
{loading === false &&
<>
<h1 style={{textAlign: 'center', color: '#01135d', fontSize: 36, marginTop: 50, marginBottom: 50}}>Meniu</h1>
<div style={{display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'center', rowGap: 50, columnGap: 100}}>
{categories.map(category => (
<div className='Menu-categoryContainer' style={{width: 700, height: 175, display: 'flex', justifyContent: 'space-between', alignItems: 'center', boxShadow: '0px 5px 10px 3px #CFE1F2', borderRadius: 20, paddingLeft: 50, color: '#01135d', cursor: 'pointer'}}
onClick={() => {
selectedInstancesContext.setSelectedCategoryName(category.categoryName);
selectedInstancesContext.setSelectedCategoryId(category.id);
navigate('/canteenId=' + selectedInstancesContext.selectedCanteenId + '/' + category.categoryName.toLowerCase());
}}
>
<h2>{category.categoryName}</h2>
<div style={{height: 175, width: 200, borderTopRightRadius: 20, borderBottomRightRadius: 20, backgroundImage: `url(${category.pictureURL})`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-end'}}>
<div className='Menu-goToCategory' style={{height: 60, width: 60, backgroundColor: 'white', borderBottomRightRadius: 20, borderTopLeftRadius: 50, display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
<FaArrowRight style={{height: 25, width: 25}}/>
</div>
</div>
</div>
))}
</div>
</>
}
<ToastContainer
position="top-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick={false}
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="light"
style={{marginTop: 50}}
/>
</div>
)
} |
//
// HomeViewController.swift
// EMovie
//
// Created by Nizar Elhraiech on 15/1/2022.
//
import UIKit
import Combine
@available(iOS 13.0, *)
class HomeViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
// MARK: Variable
var user : User?
var viewModel = HomeViewModel()
var bag = Set<AnyCancellable>()
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setViewModel(viewModel)
bindViewModel()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(true)
}
private func setViewModel(_ viewModel: HomeViewModel) {
self.viewModel = viewModel
}
private func bindViewModel() {
viewModel.errorFromServer.sink(receiveValue: {
isError in
if isError {
showError(errorDescription: NSLocalizedString("ErrorServer", comment: ""))
}
}).store(in: &bag)
viewModel.connexion.sink(receiveValue: {
isError in
if isError {
showError(errorDescription: NSLocalizedString("NoConnection", comment: ""))
}
}).store(in: &bag)
viewModel.user.sink(receiveValue: {
user in
self.user = user
print(user)
}).store(in: &bag)
}
// MARK: navigation Method
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
@IBAction func connectionAction(_ sender: Any) {
guard let email = emailTextField.text else {
return
}
guard let psswd = passwordTextField.text else {
return
}
viewModel.email.send(email)
viewModel.password.send(psswd)
viewModel.login()
}
} |
<html data-ng-app="chatApp">
<head>
<link href="css/app.css" rel="stylesheet"/>
<script src="lib/angular.js"></script>
</head>
<body data-ng-controller="chatController">
<div class="wrapper">
<div class="listview">
<div class="lv-header">
Awesome chat app
</div>
<div id="messages" class="lv-messages">
<div class="lv-body" data-ng-class="{'lv-right': message.me}" data-ng-repeat="message in messages" data-ng-cloak>
<div class="lv-message" data-ng-class="{'lv-me': message.me}">
{{message.text}}
</div>
</div>
</div>
<div class="lv-footer">
<form data-ng-submit="send()">
<input type="text" data-ng-model="text"/>
<button type="submit">Send</button>
</form>
</div>
</div>
</div>
<script src="lib/ng-websocket.js"></script>
<script type="application/javascript">
var chatApp = angular.module('chatApp', ['ngWebsocket']);
chatApp.controller('chatController', ['$scope', '$websocket', function ($scope, $websocket) {
$scope.messages = [];
$scope.addMessage = function (text, me) {
$scope.messages.push({
'text': text,
'me': me
})
};
$scope.send = function () {
if ($scope.text) {
$scope.websocket.$emit('message', {
'text': $scope.text
});
$scope.addMessage($scope.text, true);
$scope.text = "";
}
};
$scope.websocket = $websocket.$new('ws://localhost:8080/chat');
$scope.websocket.$on('message', function (data) {
$scope.addMessage(data.text, false);
$scope.$apply();
});
$scope.websocket.$on('$open', function () {
$scope.addMessage("Welcome to chat", false);
$scope.$apply();
});
}]);
</script>
</body>
</html> |
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/*
媒体查询类型 -- 响应式布局,根据不同屏幕宽度显示样式不同
- all 所有设备
- screen 电子屏幕,包括平板,手机,电脑
- print 打印机
- 一些废弃的
- 细节 https://developer.mozilla.org/zh-CN/docs/Web/CSS/@media
媒体特性
- width 视口宽度
- max-width 视口最大宽度
- min-width 视口最小宽度
- height 视口高度
- max-height 视口最大高度
- min-height 视口最小高度
- device-width 设备屏幕宽度
- max-device-width 设备屏幕的最大宽度
- min-device-width 设备屏幕的最小宽度
- orientation 视口的旋转方向,是否横屏。 1.portrait 纵向 高大于宽 2. landscape 横向 宽大于高
运算符
- and 并且
- , | or 或者
- not 否定
- only 肯定
常用阈值
- 超小 -- 768px -- 中等 -- 992px -- 大屏 -- 1200px -- 超大屏
对于不同的屏幕大小,引入不同的css
- <link rel="stylesheet" media="具体媒体查询" href="相应的css文件">
*/
.outer {
width: 100px;
height: 100px;
background-color: antiquewhite;
}
/* 打印时显示的样式,需要在打印开启背景才能看见背景 */
@media print {
.outer {
background-color: burlywood;
}
}
@media screen and (max-width: 768px) {
.outer {
background-color: #888;
}
}
@media screen and (min-width: 768px) and (max-width: 1200px) {
.outer {
background-color: orange;
}
}
</style>
</head>
<body>
<div class="outer">xxx</div>
</body>
</html> |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> arr;
TreeNode* node = root;
TreeNode* prev = nullptr;
TreeNode* tmp;
while(node || !st.empty())
{
while(node)
{
st.push(node);
node = node->left;
}
tmp = st.top();
if(tmp->right == nullptr || tmp->right == prev)
{
arr.push_back(tmp->val);
st.pop();
prev = tmp;
}
else
node = tmp->right;
}
return arr;
}
}; |
import React, { Component } from 'react'
import { BACKEND } from '../config'
import cookie from 'react-cookies'
import { Link } from 'react-router-dom'
import './header.css'
class Header extends Component {
constructor( props ) {
super( props );
this.state = {
id : cookie.load('user_id'),
username : '',
login : '',
logout : ''
};
this.logout = this.logout.bind( this );
}
componentDidMount() {
if ( this.state.id ) {
let url = BACKEND + 'user/' + this.state.id;
fetch( url ).then( res => {
return res.json();
}).then( data => {
this.setState( { username : data.username, logout : 'notShow', login : 'show' } );
});
} else {
this.setState( { username : '', login : 'notShow', logout : 'show' } );
}
}
logout = function() {
cookie.remove( 'user_id', { path : '/' } );
this.setState( { username : '', login : 'notShow', logout : 'show' } );
};
render() {
return (
<div className='header'>
<div className='left'>
<div className='menuItem'>
<Link to='/teamList'> TEAM </Link>
</div>
<div className='menuItem'>
<Link to='/player'> PLAYER </Link>
</div>
<div className='menuItem'>
<Link to='/game'> GAME </Link>
</div>
</div>
<div className='right'>
<div className={ this.state.login + ' menuItem'}> { this.state.username } </div>
<div className={ this.state.login + ' menuItem'} onClick={ this.logout }> logout </div>
<div className={ this.state.logout + ' menuItem'}> <Link to='/login'> login </Link> </div>
</div>
</div>
)
}
}
export default Header; |
import { CListGroup, CListGroupItem } from "@coreui/react";
import { React, useState } from "react";
import { useHistory } from "react-router-dom";
import Slider1 from "./slider";
import { userApi } from "../../../api/userApi";
import toast from "react-hot-toast";
import bg1 from '../../../images/background/bg1.jpg';
// day la component tren dau day
function OnlineCourses() {
const history = useHistory();
const [listCategory, setListCategory] = useState([]);
const [listSubject, setListSubject] = useState([]);
const getListCategory = async () => {
try {
const response = await userApi.getListCategoryPost();
setListCategory(response);
} catch (responseError) {
toast.error(responseError?.data?.message, {
duration: 2000,
});
}
};
const getAllSubject = async () => {
try {
const response = await userApi.getListAllSubject();
setListSubject(response.splice(0, 7))
} catch (responseError) {
toast.error(responseError?.data?.message, {
duration: 2000,
});
}
};
if (listCategory?.length === 0) {
getListCategory();
}
if (listSubject?.length === 0) {
getAllSubject();
}
let marginRoot = window.innerHeight - 80 - 445 - 60 >= 20 ? (window.innerHeight - 80 - 445 - 60) / 2 : 10;
return (
<div className="section-area bg-fix ovbl-dark" style={{ backgroundImage: "url(" + bg1 + ")", padding: marginRoot + "px 0px" }}>
<div className="container">
<div className="row">
<div className="col-md-3" >
<div
className="menu-links navbar-collapse"
id="menuDropdown"
>
<CListGroup className="nav navbar-nav d-flex element-home-left">
<CListGroupItem className="font-weight-bold list-homepage">
<div className="d-flex justify-content-between">
Kiến thức
<div>
<i className="fa fa-chevron-right"></i>
</div>
</div>
<ul className="sub-menu right">
{listCategory.map((category) => {
return (
<li key={category?.setting_id}>
<div
onClick={() => {
history.push("/blog", {
category: category.setting_id,
});
}}
>
{" "}
{category.setting_title}
</div>
</li>
);
})}
</ul>
</CListGroupItem>
<CListGroupItem
className="font-weight-bold list-homepage"
onClick={() => {
window.location.href = "/products";
}}
>
<div>Tất cả khóa học</div>
</CListGroupItem>
<CListGroupItem
className="font-weight-bold list-homepage"
onClick={() => {
window.location.href = "/combo";
}}
>
<div>Combo</div>
</CListGroupItem>
<CListGroupItem
className="font-weight-bold list-homepage"
onClick={() => {
window.location.href = "/lecturers";
}}
>
<div>Giảng viên</div>
</CListGroupItem>
{listSubject.map((elment) => {
return (
<CListGroupItem
key={elment?.id}
className="font-weight-bold list-homepage"
onClick={() => {
history.push("/products", {
category: elment?.id,
});
}}
>
<div>{elment?.name}</div>
</CListGroupItem>
);
})}
</CListGroup>
</div>
</div>
<div className="col-md-9 " style={{ padding: "0px 12px" }}>
<Slider1
></Slider1>
</div>
</div>
</div >
</div>
);
}
export default OnlineCourses; |
package dev.alexanastasyev.nirbackend.model;
import dev.alexanastasyev.nirbackend.util.lambda.DoubleGetter;
import dev.alexanastasyev.nirbackend.util.lambda.DoubleSetter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
public class CustomerClusteringModel {
private static final int EMPTY_VALUE = -1;
/**
* Идентификатор
*/
private long id;
/**
* Год рождения
*/
private double birthYear;
/**
* Образование
*/
private double education;
/**
* Семейный статус
*/
private double maritalStatus;
/**
* Доход
*/
private double income;
/**
* Количество детей
*/
private double childrenAmount;
/**
* Дата привлечения в компанию
*/
private double enrollmentDate;
/**
* Количество дней с момента последней покупки
*/
private double recency;
/**
* Есть ли жалобы за последние 2 года
*/
private double complains;
/**
* Потрачено на вино за последние 2 года
*/
private double wineAmount;
/**
* Потрачено на фрукты за последние 2 года
*/
private double fruitsAmount;
/**
* Потрачено на мясо за последние 2 года
*/
private double meatAmount;
/**
* Потрачено на рыбу за последние 2 года
*/
private double fishAmount;
/**
* Потрачено на сладкое за последние 2 года
*/
private double sweetAmount;
/**
* Потрачено на золото за последние 2 года
*/
private double goldAmount;
/**
* Покупок по скидкам
*/
private double discountPurchasesAmount;
/**
* Количество принятых рекламных кампаний
*/
private double acceptedCampaignsAmount;
/**
* Количество покупок через сайт
*/
private double webPurchasesAmount;
/**
* Количество покупок с помощью каталога
*/
private double catalogPurchasesAmount;
/**
* Количество покупок непосредственно в магазине
*/
private double storePurchasesAmount;
/**
* Посещений веб-сайта за последний месяц
*/
private double websiteVisitsAmount;
public CustomerClusteringModel() {
}
public CustomerClusteringModel(CustomerCSVModel csvModel) {
extractId(csvModel.getId());
extractBirthYear(csvModel.getBirthYear());
extractEducation(csvModel.getEducation());
extractMaritalStatus(csvModel.getMaritalStatus());
extractIncome(csvModel.getIncome());
extractChildrenAmount(csvModel.getKidsAmount(), csvModel.getTeensAmount());
extractEnrollmentDate(csvModel.getEnrollmentDate());
extractRecency(csvModel.getRecency());
extractComplains(csvModel.getComplains());
extractWineAmount(csvModel.getWineAmount());
extractFruitsAmount(csvModel.getFruitsAmount());
extractMeatAmount(csvModel.getMeatAmount());
extractFishAmount(csvModel.getFishAmount());
extractSweetAmount(csvModel.getSweetAmount());
extractGoldAmount(csvModel.getGoldAmount());
extractDiscountPurchasesAmount(csvModel.getDiscountPurchasesAmount());
extractAcceptedCampaignsAmount(csvModel.getAcceptedCampaign1(), csvModel.getAcceptedCampaign2(),
csvModel.getAcceptedCampaign3(), csvModel.getAcceptedCampaign4(), csvModel.getAcceptedCampaign5(),
csvModel.getResponse());
extractWebPurchasesAmount(csvModel.getWebPurchasesAmount());
extractCatalogPurchasesAmount(csvModel.getCatalogPurchasesAmount());
extractStorePurchasesAmount(csvModel.getStorePurchasesAmount());
extractWebsiteVisitsAmount(csvModel.getVisitsAmount());
}
public CustomerClusteringModel(CustomerClusteringModel clusteringModel) {
this.id = clusteringModel.getId();
this.birthYear = clusteringModel.getBirthYear();
this.education = clusteringModel.getEducation();
this.maritalStatus = clusteringModel.getMaritalStatus();
this.income = clusteringModel.getIncome();
this.childrenAmount = clusteringModel.getChildrenAmount();
this.enrollmentDate = clusteringModel.getEnrollmentDate();
this.recency = clusteringModel.getRecency();
this.complains = clusteringModel.getComplains();
this.wineAmount = clusteringModel.getWineAmount();
this.fruitsAmount = clusteringModel.getFruitsAmount();
this.meatAmount = clusteringModel.getMeatAmount();
this.fishAmount = clusteringModel.getFishAmount();
this.sweetAmount = clusteringModel.getSweetAmount();
this.goldAmount = clusteringModel.getGoldAmount();
this.discountPurchasesAmount = clusteringModel.getDiscountPurchasesAmount();
this.acceptedCampaignsAmount = clusteringModel.getAcceptedCampaignsAmount();
this.webPurchasesAmount = clusteringModel.getWebPurchasesAmount();
this.catalogPurchasesAmount = clusteringModel.getCatalogPurchasesAmount();
this.storePurchasesAmount = clusteringModel.getStorePurchasesAmount();
this.websiteVisitsAmount = clusteringModel.getWebsiteVisitsAmount();
}
public long getId() {
return id;
}
public double getBirthYear() {
return birthYear;
}
public void setBirthYear(double birthYear) {
this.birthYear = birthYear;
}
public double getEducation() {
return education;
}
public void setEducation(double education) {
this.education = education;
}
public double getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(double maritalStatus) {
this.maritalStatus = maritalStatus;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
public double getChildrenAmount() {
return childrenAmount;
}
public void setChildrenAmount(double childrenAmount) {
this.childrenAmount = childrenAmount;
}
public double getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(double enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
public double getRecency() {
return recency;
}
public void setRecency(double recency) {
this.recency = recency;
}
public double getComplains() {
return complains;
}
public void setComplains(double complains) {
this.complains = complains;
}
public double getWineAmount() {
return wineAmount;
}
public void setWineAmount(double wineAmount) {
this.wineAmount = wineAmount;
}
public double getFruitsAmount() {
return fruitsAmount;
}
public void setFruitsAmount(double fruitsAmount) {
this.fruitsAmount = fruitsAmount;
}
public double getMeatAmount() {
return meatAmount;
}
public void setMeatAmount(double meatAmount) {
this.meatAmount = meatAmount;
}
public double getFishAmount() {
return fishAmount;
}
public void setFishAmount(double fishAmount) {
this.fishAmount = fishAmount;
}
public double getSweetAmount() {
return sweetAmount;
}
public void setSweetAmount(double sweetAmount) {
this.sweetAmount = sweetAmount;
}
public double getGoldAmount() {
return goldAmount;
}
public void setGoldAmount(double goldAmount) {
this.goldAmount = goldAmount;
}
public double getDiscountPurchasesAmount() {
return discountPurchasesAmount;
}
public void setDiscountPurchasesAmount(double discountPurchasesAmount) {
this.discountPurchasesAmount = discountPurchasesAmount;
}
public double getAcceptedCampaignsAmount() {
return acceptedCampaignsAmount;
}
public void setAcceptedCampaignsAmount(double acceptedCampaignsAmount) {
this.acceptedCampaignsAmount = acceptedCampaignsAmount;
}
public double getWebPurchasesAmount() {
return webPurchasesAmount;
}
public void setWebPurchasesAmount(double webPurchasesAmount) {
this.webPurchasesAmount = webPurchasesAmount;
}
public double getCatalogPurchasesAmount() {
return catalogPurchasesAmount;
}
public void setCatalogPurchasesAmount(double catalogPurchasesAmount) {
this.catalogPurchasesAmount = catalogPurchasesAmount;
}
public double getStorePurchasesAmount() {
return storePurchasesAmount;
}
public void setStorePurchasesAmount(double storePurchasesAmount) {
this.storePurchasesAmount = storePurchasesAmount;
}
public double getWebsiteVisitsAmount() {
return websiteVisitsAmount;
}
public void setWebsiteVisitsAmount(double websiteVisitsAmount) {
this.websiteVisitsAmount = websiteVisitsAmount;
}
@Override
public String toString() {
return "CustomerClusteringModel{" +
"id=" + id +
", birthYear=" + birthYear +
", education=" + education +
", maritalStatus=" + maritalStatus +
", income=" + income +
", childrenAmount=" + childrenAmount +
", enrollmentDate=" + enrollmentDate +
", recency=" + recency +
", complains=" + complains +
", wineAmount=" + wineAmount +
", fruitsAmount=" + fruitsAmount +
", meatAmount=" + meatAmount +
", fishAmount=" + fishAmount +
", sweetAmount=" + sweetAmount +
", goldAmount=" + goldAmount +
", discountPurchasesAmount=" + discountPurchasesAmount +
", acceptedCampaignsAmount=" + acceptedCampaignsAmount +
", webPurchasesAmount=" + webPurchasesAmount +
", catalogPurchasesAmount=" + catalogPurchasesAmount +
", storePurchasesAmount=" + storePurchasesAmount +
", websiteVisitsAmount=" + websiteVisitsAmount +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomerClusteringModel that = (CustomerClusteringModel) o;
return id == that.id && Double.compare(that.birthYear, birthYear) == 0 && Double.compare(that.education, education) == 0 && Double.compare(that.maritalStatus, maritalStatus) == 0 && Double.compare(that.income, income) == 0 && Double.compare(that.childrenAmount, childrenAmount) == 0 && Double.compare(that.enrollmentDate, enrollmentDate) == 0 && Double.compare(that.recency, recency) == 0 && Double.compare(that.complains, complains) == 0 && Double.compare(that.wineAmount, wineAmount) == 0 && Double.compare(that.fruitsAmount, fruitsAmount) == 0 && Double.compare(that.meatAmount, meatAmount) == 0 && Double.compare(that.fishAmount, fishAmount) == 0 && Double.compare(that.sweetAmount, sweetAmount) == 0 && Double.compare(that.goldAmount, goldAmount) == 0 && Double.compare(that.discountPurchasesAmount, discountPurchasesAmount) == 0 && Double.compare(that.acceptedCampaignsAmount, acceptedCampaignsAmount) == 0 && Double.compare(that.webPurchasesAmount, webPurchasesAmount) == 0 && Double.compare(that.catalogPurchasesAmount, catalogPurchasesAmount) == 0 && Double.compare(that.storePurchasesAmount, storePurchasesAmount) == 0 && Double.compare(that.websiteVisitsAmount, websiteVisitsAmount) == 0;
}
@Override
public int hashCode() {
return Objects.hash(id, birthYear, education, maritalStatus, income, childrenAmount, enrollmentDate, recency, complains, wineAmount, fruitsAmount, meatAmount, fishAmount, sweetAmount, goldAmount, discountPurchasesAmount, acceptedCampaignsAmount, webPurchasesAmount, catalogPurchasesAmount, storePurchasesAmount, websiteVisitsAmount);
}
public CustomerClusteringModel copy() {
return new CustomerClusteringModel(this);
}
public void replaceEmptyFieldsWithAverage(CustomerClusteringModel average) {
replaceIfEmpty(this::getBirthYear, this::setBirthYear, average.getBirthYear());
replaceIfEmpty(this::getEducation, this::setEducation, average.getEducation());
replaceIfEmpty(this::getMaritalStatus, this::setMaritalStatus, average.getMaritalStatus());
replaceIfEmpty(this::getIncome, this::setIncome, average.getIncome());
replaceIfEmpty(this::getChildrenAmount, this::setChildrenAmount, average.getChildrenAmount());
replaceIfEmpty(this::getEnrollmentDate, this::setEnrollmentDate, average.getEnrollmentDate());
replaceIfEmpty(this::getRecency, this::setRecency, average.getRecency());
replaceIfEmpty(this::getComplains, this::setComplains, average.getComplains());
replaceIfEmpty(this::getWineAmount, this::setWineAmount, average.getWineAmount());
replaceIfEmpty(this::getFruitsAmount, this::setFruitsAmount, average.getFruitsAmount());
replaceIfEmpty(this::getMeatAmount, this::setMeatAmount, average.getMeatAmount());
replaceIfEmpty(this::getFishAmount, this::setFishAmount, average.getFishAmount());
replaceIfEmpty(this::getSweetAmount, this::setSweetAmount, average.getSweetAmount());
replaceIfEmpty(this::getGoldAmount, this::setGoldAmount, average.getGoldAmount());
replaceIfEmpty(this::getDiscountPurchasesAmount, this::setDiscountPurchasesAmount, average.getDiscountPurchasesAmount());
replaceIfEmpty(this::getAcceptedCampaignsAmount, this::setAcceptedCampaignsAmount, average.getAcceptedCampaignsAmount());
replaceIfEmpty(this::getWebPurchasesAmount, this::setWebPurchasesAmount, average.getWebPurchasesAmount());
replaceIfEmpty(this::getCatalogPurchasesAmount, this::setCatalogPurchasesAmount, average.getCatalogPurchasesAmount());
replaceIfEmpty(this::getStorePurchasesAmount, this::setStorePurchasesAmount, average.getStorePurchasesAmount());
replaceIfEmpty(this::getWebsiteVisitsAmount, this::setWebsiteVisitsAmount, average.getWebsiteVisitsAmount());
}
private void replaceIfEmpty(DoubleGetter getter, DoubleSetter setter, double value) {
if (getter.getValue() == EMPTY_VALUE) {
setter.setValue(value);
}
}
private void extractId(String id) {
if (id == null || id.isEmpty()) {
this.id = EMPTY_VALUE;
} else {
this.id = Integer.parseInt(id);
}
}
private void extractBirthYear(String birthYear) {
extractDoubleValue(birthYear, this::setBirthYear);
}
private void extractEducation(String education) {
if ("Graduation".equals(education)) {
this.education = 0.5;
} else if ("Basic".equals(education) || "2n Cycle".equals(education)) {
this.education = 0;
} else if ("Master".equals(education) || "PhD".equals(education)) {
this.education = 1;
} else {
this.education = EMPTY_VALUE;
}
}
private void extractMaritalStatus(String maritalStatus) {
if ("YOLO".equals(maritalStatus) || "Absurd".equals(maritalStatus)
|| "Alone".equals(maritalStatus) || "Widow".equals(maritalStatus)
|| "Divorced".equals(maritalStatus)) {
this.maritalStatus = 0;
} else if ("Together".equals(maritalStatus) || "Married".equals(maritalStatus)) {
this.maritalStatus = 1;
} else {
this.maritalStatus = EMPTY_VALUE;
}
}
private void extractIncome(String income) {
extractDoubleValue(income, this::setIncome);
}
private void extractChildrenAmount(String kidsAmount, String teensAmount) {
if (kidsAmount == null || kidsAmount.isEmpty() || teensAmount == null || teensAmount.isEmpty()) {
this.childrenAmount = EMPTY_VALUE;
} else {
this.childrenAmount = Double.parseDouble(kidsAmount) + Double.parseDouble(teensAmount);
}
}
private void extractEnrollmentDate(String enrollmentDate) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date parsedDate = dateFormat.parse(enrollmentDate);
this.enrollmentDate = parsedDate.getTime();
} catch (Exception e) {
this.enrollmentDate = EMPTY_VALUE;
}
}
private void extractRecency(String recency) {
extractDoubleValue(recency, this::setRecency);
}
private void extractComplains(String complains) {
extractDoubleValue(complains, this::setComplains);
}
private void extractWineAmount(String wineAmount) {
extractDoubleValue(wineAmount, this::setWineAmount);
}
private void extractFruitsAmount(String fruitsAmount) {
extractDoubleValue(fruitsAmount, this::setFruitsAmount);
}
private void extractMeatAmount(String meatAmount) {
extractDoubleValue(meatAmount, this::setMeatAmount);
}
private void extractFishAmount(String fishAmount) {
extractDoubleValue(fishAmount, this::setFishAmount);
}
private void extractSweetAmount(String sweetAmount) {
extractDoubleValue(sweetAmount, this::setSweetAmount);
}
private void extractGoldAmount(String goldAmount) {
extractDoubleValue(goldAmount, this::setGoldAmount);
}
private void extractDiscountPurchasesAmount(String discountPurchasesAmount) {
extractDoubleValue(discountPurchasesAmount, this::setDiscountPurchasesAmount);
}
private void extractAcceptedCampaignsAmount(String... acceptedCampaigns) {
boolean valid = true;
for (String campaign : acceptedCampaigns) {
if (campaign == null || campaign.isEmpty()) {
valid = false;
break;
}
}
if (valid) {
double result = 0;
for (String campaign : acceptedCampaigns) {
result += Double.parseDouble(campaign);
}
this.acceptedCampaignsAmount = result;
} else {
this.acceptedCampaignsAmount = EMPTY_VALUE;
}
}
private void extractWebPurchasesAmount(String webPurchasesAmount) {
extractDoubleValue(webPurchasesAmount, this::setWebPurchasesAmount);
}
private void extractCatalogPurchasesAmount(String catalogPurchasesAmount) {
extractDoubleValue(catalogPurchasesAmount, this::setCatalogPurchasesAmount);
}
private void extractStorePurchasesAmount(String storePurchasesAmount) {
extractDoubleValue(storePurchasesAmount, this::setStorePurchasesAmount);
}
private void extractWebsiteVisitsAmount(String websiteVisitsAmount) {
extractDoubleValue(websiteVisitsAmount, this::setWebsiteVisitsAmount);
}
private void extractDoubleValue(String value, DoubleSetter setter) {
if (value == null || value.isEmpty()) {
setter.setValue(EMPTY_VALUE);
} else {
setter.setValue(Double.parseDouble(value));
}
}
} |
import { doc, getDoc } from "firebase/firestore";
import { db } from "../../firebaseConfig";
// This is an asynchronous function that fetches a specific node ID for a given store in a specific mall from Firebase Firestore.
// Parameters:
// currentMall - The name of the mall where the store is located.
// storeName - The name of the store for which the node ID is to be fetched.
export default async function fetchNodeId(currentMall, storeName) {
// Format the store name to create a node identifier (lowercase, spaces replaced with dashes, appended with '-node').
const formattedStoreName = `${storeName
.replace(/[^\w\s]/g, "")
.replace(/\s/g, "-")
.toLowerCase()}-node`;
// Create a document ID by concatenating the lowercase mall ID and the formatted store name.
const documentID = `${currentMall.toLowerCase()}-${formattedStoreName}`;
// Get a reference to the specific document (node) in the Firestore collection.
const docRef = doc(db, "malls", currentMall, "nodes", documentID);
// Fetch the document.
const docSnap = await getDoc(docRef);
// If the document exists, return the document ID. This is the node ID for the specified store.
if (docSnap.exists()) {
return docSnap.id;
}
// If the document does not exist (i.e., if the store name is invalid), throw an error.
throw new Error("Invalid Store Name");
} |
# JavaScript ES6 - let, const, arrow functions e template literals
#### Conteúdo
Neste bloco e no próximo, você vai aprender sobre a mais nova versão do *JavaScript*, conhecida como *ES6*, *ECMAScript 6* ou *ES2015*.
Esses vários nomes podem gerar alguma dúvida, mas na verdade todos fazem referência à mesma linguagem. *JavaScript* é como nós chamamos a linguagem, só que esse nome é um **trademark** da Oracle. O nome oficial da linguagem é *ECMAScript*, e *ES* é apenas a abreviação (**E**CMA**S**cript).
Essa nova versão possui alguns objetivos:
* Ser uma linguagem melhor para construir aplicações complexas;
* Resolver problemas antigos do JavaScript;
* Facilitar o desenvolvimento de libraries.
Hoje você vai aprender quatro `features` do *ES6* que são muito importantes para que seu código fique limpo e bem escrito, além de resolverem alguns problemas da linguagem.
* `let`;
* `const`;
* `arrow functions`;
* `template literals`.
#### Objetivo
* Utilizar corretamente `let`;
* Utilizar corretamente `const`;
* Simplificar seu código com `arrow functions`;
* Simplificar a construção de strings com `template literals`. |
import { Box, Button, Container, TextField, Typography } from "@mui/material";
import { Link, useNavigate } from "react-router-dom";
import styles from "./style.module.css";
import { getApiUrl } from "utils/getApiUrl";
import axios from "axios";
import { getAuthorizedOptions } from "utils/getAuthorizedOptions";
import { useState } from "react";
const API_ENDPOINT = `${getApiUrl()}/user-auth/verify-otp`;
export const ResetPasswordOtp = () => {
const [isError, setError] = useState(false);
const navigate = useNavigate();
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
if (!localStorage.getItem("email")) {
navigate("/");
}
if(!formData.get("otp")){
setError(true)
return
}
const otp = formData.get("otp").toString();
const data = {
email: localStorage.getItem("email"),
otp_input: otp,
};
await axios
.post(API_ENDPOINT, data)
.then((res) => {
setError(false);
console.log(res);
navigate("/reset-password");
})
.catch((err) => {
console.error(err);
if(err.response.data === "OTP is not valid"){
setError(true);
}
else {
navigate("/");
}
});
};
return (
<Container className={styles.container}>
<Typography color="primary" variant="h5" style={{ fontWeight: "500" }}>
Reset Password
</Typography>
<Typography color="primary">We've sent you the OTP code. Insert your OTP code here</Typography>
<Box
component="form"
noValidate
className={styles.form}
onSubmit={handleSubmit}
>
<TextField
size="small"
label="OTP"
variant="outlined"
name="otp"
inputProps={{ maxLength: 6 }}
error={isError}
helperText={isError && "OTP is not valid."}
fullWidth
/>
<div className={styles.buttons}>
<Button variant="contained" color="secondary" type="submit">
Confirm
</Button>
</div>
</Box>
</Container>
);
}; |
Dot = class('Dot')
function Dot:initialize(x, y, angle, speed, mass, directions, super, gigantic, repel)
self.x = x
self.y = y
self.super = super or false -- if true, a large, immobile object
self.gigantic = gigantic or false -- if true for a super object, then it is even larger
self.directions = directions or 0 -- 0 means no restriction on angle of movement
self.repel = repel or false
self.lastX = x
self.lastY = y
if mass == 0 then
local sizeFactor = math.random(1, 500)
self.size = math.floor(sizeFactor/50)+5 * 2
self.mass = mass or sizeFactor
elseif self.super then
if gigantic then
local sizeFactor = math.random(20000, 1000000)
self.size = math.sqrt(math.floor(sizeFactor/100)) * 2
self.mass = mass or sizeFactor
else
local sizeFactor = math.random(5000, 10000)
self.size = (math.floor(sizeFactor/100)+5) * 2
self.mass = mass or sizeFactor
end
else
local sizeFactor = math.random(1, 2000)
self.size = (math.floor(sizeFactor/150)+5) * 2
self.mass = mass or sizeFactor
end
self.gx = 0
self.gy = 0
self.vx = 0
self.vy = 0
if not super then
self.angle = angle
self.speed = speed/50
self.vx = math.cos(self.angle)*self.speed
self.vy = math.sin(self.angle)*self.speed
end
self.color = {math.random(255), math.random(255), math.random(255)}
if self.super then -- a super object has translucency
self.color[4] = 150
end
self.destroy = false
end
function Dot:update(dt)
self.vx = self.vx + self.gx
self.vy = self.vy + self.gy
self.angle = math.angle(0, 0, self.vx, self.vy)
self.speed = math.sqrt(self.vx^2 + self.vy^2)
if self.directions > 0 then -- calculate angle if limited
self.angle = math.floor((self.angle/math.rad(360/self.directions)) + .5)*math.rad(360/self.directions)
end
-- used to disconnect the variables
local lastX = self.x
local lastY = self.y
self.lastX = lastX
self.lastY = lastY
if not self.super then -- super objects will not move
self.x = self.x + math.cos(self.angle)*self.speed
self.y = self.y + math.sin(self.angle)*self.speed
end
end
function Dot:draw()
local alpha = 150
if self.mass == 0 or self.gigantic then alpha = 255 end
love.graphics.setColor(self.color[1], self.color[2], self.color[3], alpha)
if self.super then
love.graphics.circle('fill', self.x, self.y, self.size)
end
if self.angle then
if not self.super then
local w = self.size
local h = self.speed -- the faster it is moving, the taller the object will be
love.graphics.polygon('fill', self.x + math.cos(self.angle - math.rad(90))*w, self.y + math.sin(self.angle - math.rad(90))*w,
self.x + math.cos(self.angle + math.rad(90))*w, self.y + math.sin(self.angle + math.rad(90))*w,
self.x + math.cos(self.angle)*h, self.y + math.sin(self.angle)*h)
end
end
end |
<h2></h2>
<h2> Solution </h2>
``` c++
// Time Complexity of everything O(N)
struct Node {
Node* links[26];
int cntPrefix=0;
int cntEndsWith=0;
bool containsKey(char ch)
{
return links[ch-'a']!=NULL;
}
void put(char ch,Node* node){
links[ch-'a']=node;
}
Node* get(char ch)
{
return links[ch-'a'];
}
//for checking if the word is completed or not
void increaseWordCnt()
{
cntEndsWith++;
}
void increasePrefix(){
cntPrefix++;
}
void deleteWord(){
cntEndsWith--;
}
void reducePrefixCnt(){
cntPrefix--;
}
};
class Trie{
Node* root;
public:
Trie(){
root= new Node();
}
void insert(string &word){
Node* node =root;
for(int i=0;i<word.length();i++)
{
if(!node->containsKey(word[i]))
{
node->put(word[i],new Node());
}
node =node->get(word[i]);
node->increasePrefix();
}
node->increaseWordCnt();
}
int countWordsEqualTo(string &word){
Node* node =root;
for(int i=0;i<word.length();i++)
{
if (node->containsKey(word[i]))
{
node = node->get(word[i]);
}
else
{
return 0;
}
}
return node->cntEndsWith;
}
int countWordsStartingWith(string &word){
Node* node =root;
for(int i=0;i<word.length();i++)
{
if (node->containsKey(word[i]))
{
node = node->get(word[i]);
}
else
{
return 0;
}
}
return node->cntPrefix;
}
void erase(string &word){
Node* node =root;
for(int i=0;i<word.length();i++){
if (node -> containsKey(word[i])){
node = node -> get(word[i]);
node -> reducePrefixCnt();
}else{
return;
}
}
node->deleteWord();
}
};
```
</div> |
import { useContext, useState } from 'react';
import { Alert, Image, StyleSheet, View } from 'react-native';
import { launchCameraAsync, useCameraPermissions, PermissionStatus } from 'expo-image-picker';
import { GlobalContext } from '../../store/GlobalProvider';
import { globalStyles } from '../../theme';
import { Button } from '../Buttons';
import { Text } from '../Text';
export const ImagePicker = () => {
const { theme } = useContext(GlobalContext);
const [cameraPermissionInfo, requestPermission] = useCameraPermissions();
const [pickedImage, setPickedImage] = useState(null);
const verifyPermission = async () => {
if (cameraPermissionInfo.status === PermissionStatus.UNDETERMINED) {
const permissionRes = await requestPermission();
return permissionRes.granted;
}
if (cameraPermissionInfo.status === PermissionStatus.DENIED) {
Alert.alert('Insufficient Permissions!', 'You need to grant camera permissions to use this app.');
return false;
}
return true;
};
const takeImageHandler = async () => {
const hasPermission = await verifyPermission();
if (!hasPermission) {
return;
}
const image = await launchCameraAsync({
allowsEditing: true,
aspect: [16, 9],
quality: 0.5,
});
setPickedImage(image);
};
return (
<>
<View style={[styles.imagePreview, { backgroundColor: globalStyles.colors[theme][100] }]}>
{!pickedImage?.uri ? (
<Text>No image taken yet.</Text>
) : (
<Image style={styles.image} source={{ uri: pickedImage?.uri }} />
)}
</View>
<Button variant="outlined" icon="camera" onPress={takeImageHandler}>
Take Image
</Button>
</>
);
};
const styles = StyleSheet.create({
imagePreview: {
width: '100%',
height: 200,
marginVertical: 8,
justifyContent: 'center',
alignItems: 'center',
borderRadius: globalStyles.borderRadius,
overflow: 'hidden',
},
image: {
width: '100%',
height: '100%',
},
}); |
import React from "react";
import s from './Post.module.css';
import userPhoto from "../../../../assets/img/user.png";
import {Button, Col, Divider, Row, Typography} from "antd";
import {LikeOutlined, LikeFilled, CloseOutlined} from "@ant-design/icons";
const {Text} = Typography
type PropsType = {
setLiked: (postId: number) => void
setUnLiked: (postId: number) => void
deletePost: (postId: number) => void
message: string
likesCount: number
isLiked: boolean
id: number
}
const Post: React.FC<PropsType> = (props) => {
return <div>
<Row className={s.item}>
<Col flex="60px">
<img src={userPhoto} alt=""/>
</Col>
<Col flex="310px">
<div className={s.messageText}>
<Text>{props.message}</Text>
</div>
<div>
{props.isLiked ? <Button size="small" shape="round"
icon={<LikeFilled className={s.likeUnlikeIcon}/>}
onClick={() => props.setUnLiked(props.id)}>
<span className={s.likesCount}>{props.likesCount}</span></Button>
: <Button size="small" shape="round"
icon={<LikeOutlined className={s.likeUnlikeIcon}/>}
onClick={() => props.setLiked(props.id)}>
<span className={s.likesCount}>{props.likesCount}</span></Button>}
</div>
</Col>
<Col>
<CloseOutlined className={s.removeIcon} onClick={() => props.deletePost(props.id)}/>
</Col>
</Row>
<Divider/>
</div>
}
export default Post; |
14154
www.ics.uci.edu/~dock/manuals/oechem/cplusprog/node41.html
4.4.3 Use of the conformers as first-class objects OEChem - C++ Theory Manual Version 1.3.1 Previous: 4.4.2 Use of the Up: 4.4 Properties of Multi-Conformer Next: 5. Traversing the Atoms, 4.4.3 Use of the conformers as first-class objects Alternatively, a programmer may wish to use the conformers as first class objects rather than via the state of the OEMCMolBase. This allows one to have multiple conformation objects at once and to treat the OEMCMolBase as a container of single-conformer molecules. The example below shows the use of the conformers as first class objects. Each conformer is represented by an OEConfBase which inherits from the OEMolBase object. Thus, each conformer can be treated as an independent molecule with respect to its coordinates as shown in the example code below. #include "oechem.h"
#include <iostream>
using namespace OEChem;
using namespace OESystem;
using namespace std;
float GetMaxX(const OEMolBase &mol)
{
OEIter<OEAtomBase> atom;
float xyz[3];
float maxX = 0.0f;
bool first = true;
for(atom = mol.GetAtoms();atom;++atom)
{
mol.GetCoords(atom,xyz);
if(first)
{
maxX = xyz[0];
first = false;
}
else
if(xyz[0] > maxX)
maxX = xyz[0];
}
return maxX;
}
int main(int, char ** argv)
{
OEIter<OEMCMolBase> mol;
OEIter<OEConfBase> conf;
oemolistream ims(argv[1]);
std::string maxconf;
float tmpx = 0.0f, maxX = 0.0f;
for (mol=ims.GetMCMolBases(); mol; ++mol)
{
for(conf = mol->GetConfs(); conf; ++conf)
{
tmpx = GetMaxX(*conf);
if(tmpx > maxX)
{
if(!maxconf.empty())
{
cerr << conf->GetTitle() << " has a larger value of x than " <<
maxconf << endl;
}
maxconf = conf->GetTitle();
maxX = tmpx;
}
}
}
return 0;
}
Download as text. In the listing above, the function GetMaxX returns the maximum x-coordinate of a molecule. The main routine loops over all of the conformers of each molecule and compares the maximum x-coordinate to a running maximum of the x-coordinate of every conformer. If there is a new maximum, the associated conformer is stored and the user is notified via cerr. OEChem - C++ Theory Manual Version 1.3.1 Previous: 4.4.2 Use of the Up: 4.4 Properties of Multi-Conformer Next: 5. Traversing the Atoms, Documentation released on July 30, 2004. |
//jshint esversion:6
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const mongoose = require('mongoose');
const app = new express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
mongoose.connect("mongodb://localhost:27017/userDB");
const userSchema = {
"email": String,
"password": String
}
const User = mongoose.model("User",userSchema);
app.set('view engine', 'ejs');
app.get('/',function(req,res){
res.render('home');
})
app.get('/register',function(req,res){
res.render('register');
})
app.get('/login',function(req,res){
res.render('login');
})
app.post('/register', function(req,res){
const email1 = req.body.username;
const password1 = req.body.password;
// console.log(email);
// console.log(password);
const newUser = new User({
email: email1,
password : password1
})
newUser.save(function(err){
if(err){
console.log(err);
}
else{
res.render("secrets");
}
})
})
app.post('/login', function(req,res){
const email1 = req.body.username;
const password1 = req.body.password;
// console.log(email);
// console.log(password);
User.findOne({email:email1},function(err,foundUser){
if(err){
console.log(err);
}
if(foundUser){
if(foundUser.password === password1){
res.render("secrets");
}
else{
res.render("Wrong-pass");
}
}
})
})
app.listen(3000,function(){
console.log("Server is running on port 3000");
}) |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css"/>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
crossorigin="anonymous"
/>
<title>Administration</title>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-person-circle" viewBox="0 0 16 16">
<path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0"/>
<path fill-rule="evenodd" d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8m8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1"/>
</svg>
</a>
<p class="m-auto fs-4 fw-medium text-center" th:text="${username}"></p>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" th:href="@{/home}">Home</a>
</li>
<li class="nav-item" th:switch="${role}">
<a class="nav-link active" th:case="'ROLE_ADMIN'" th:href="@{/admin}">Admin</a>
</li>
<li class="nav-item">
<form method="POST" th:action="@{/logout}">
<input class="nav-link active" type="submit" value="Logout"/>
</form>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid h-100">
<div class="row justify-content-center align-items-center h-100">
<div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
<form th:action="@{/admin/user-edit/save}" th:object="${user}" method="post" >
<input type="hidden" th:field="*{id}" />
<div class="m-3">
<h3 class="fw-normal pb-2">User edit:</h3>
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8 mb-2">
<input type="email" th:field="*{email}" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Username: </label>
<div class="col-8 mb-2">
<input type="text" th:field="*{username}" class="form-control" equired minlength="2" maxlength="20" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8 mb-2">
<input type="password" th:field="*{password}" class="form-control" required minlength="6" maxlength="10"/>
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Full Name: </label>
<div class="col-8 mb-2">
<input type="text" th:field="*{fullname}" class="form-control" required minlength="2" maxlength="20"/>
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Country: </label>
<div class="col-8 mb-2">
<input type="text" th:field="*{Country}" class="form-control" required minlength="2" maxlength="20" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">City: </label>
<div class="col-8 mb-2">
<input type="text" th:field="*{City}" class="form-control" required minlength="2" maxlength="20" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Phone number: </label>
<div class="col-8 mb-2">
<input type="text" th:field="*{phoneNumber}" class="form-control" required minlength="2" maxlength="20" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Roles: </label>
<div class="col-8 mb-2">
<th:block th:each="role: ${listRoles}">
<input type="checkbox" th:field="*{roles}"
th:text="${role.name}" th:value="${role.id}" class="m-2" />
</th:block>
</div>
</div>
<div class="mb-2 text-end">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous">
</script>
</body>
</html> |
import { cn } from '@/utils';
import { TouchableOpacity, View } from 'react-native';
import { Text } from './Text';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import React from 'react';
interface TableProps extends React.ComponentPropsWithoutRef<typeof View> {
header?: string;
headerClassName?: string;
children: React.ReactNode | React.ReactNode[];
}
const Table = ({
children,
className,
headerClassName,
...props
}: TableProps) => {
const enhancedChildren = React.Children.map(children, (child, i) => {
const isLastChild = i === React.Children.count(children) - 1;
if (React.isValidElement(child)) {
return React.cloneElement(child, {
// @ts-ignore
isLastChild,
});
}
return child;
});
return (
<>
{props.header && (
<Text
variant='subhead'
className={cn('text-muted-foreground mb-4', headerClassName)}
>
{props.header}
</Text>
)}
<View
className={cn('rounded-xl bg-muted py-2 px-4', className)}
{...props}
>
{enhancedChildren}
</View>
</>
);
};
// create type for TableRow omiting children and adding the following props: title, elementLeft, elementRight, description
interface TableRowProps
extends React.ComponentPropsWithoutRef<typeof TouchableOpacity> {
title: string;
elementLeft?: React.ReactNode;
elementRight?: React.ReactNode;
description?: string;
isLastChild?: boolean;
}
const TableRow = ({ className, isLastChild, ...props }: TableRowProps) => {
return (
<TouchableOpacity
{...props}
className={cn('flex flex-row items-center justify-between', className)}
>
{props.elementLeft && <View>{props.elementLeft}</View>}
<View
className={`p-2 flex-1 border-border flex flex-col justify-between row-content ${
!isLastChild && 'border-b'
}`}
>
<View>
<Text variant='headline' className='text-foreground'>
{props.title}
</Text>
</View>
{props.description && (
<View>
<Text variant='subhead' className='text-muted-foreground'>
{props.description}
</Text>
</View>
)}
</View>
{props.elementRight ? (
<View>{props.elementRight}</View>
) : (
<Text>
<MaterialCommunityIcons name='chevron-right' size={24} />
</Text>
)}
</TouchableOpacity>
);
};
export { Table, TableRow }; |
use axum::{http::StatusCode, response::IntoResponse};
use derive_more::From;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, From)]
pub enum Error {
#[from]
Custom(String),
#[from]
Zoho(crate::zoho::Error),
// -- Externals
#[from]
Io(std::io::Error), // as example
#[from]
Config(config::ConfigError),
#[from]
Sqlx(sqlx::Error),
#[from]
Reqwest(reqwest::Error),
#[from]
Chrono(chrono::ParseError),
#[from]
SerdeJson(serde_json::Error),
}
// region: --- Custom
impl Error {
pub fn custom(val: impl std::fmt::Display) -> Self {
Self::Custom(val.to_string())
}
}
impl From<&str> for Error {
fn from(val: &str) -> Self {
Self::Custom(val.to_string())
}
}
impl IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
tracing::error!("{self:?}");
tracing::error!("<-- 500");
(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").into_response()
}
}
// endregion: --- Custom
// region: --- Error Boilerplate
impl core::fmt::Display for Error {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
write!(fmt, "{self:?}")
}
}
impl std::error::Error for Error {}
// endregion: --- Error Boilerplate |
<?php
declare(strict_types=1);
namespace Intervention\Image;
use Error;
use Intervention\Image\Encoders\AvifEncoder;
use Intervention\Image\Encoders\BmpEncoder;
use Intervention\Image\Encoders\GifEncoder;
use Intervention\Image\Encoders\HeicEncoder;
use Intervention\Image\Encoders\Jpeg2000Encoder;
use Intervention\Image\Encoders\JpegEncoder;
use Intervention\Image\Encoders\PngEncoder;
use Intervention\Image\Encoders\TiffEncoder;
use Intervention\Image\Encoders\WebpEncoder;
use Intervention\Image\Exceptions\NotSupportedException;
use Intervention\Image\Interfaces\EncoderInterface;
enum Format
{
case AVIF;
case BMP;
case GIF;
case HEIC;
case JP2;
case JPEG;
case PNG;
case TIFF;
case WEBP;
/**
* Create format from given identifier
*
* @param string|Format|MediaType|FileExtension $identifier
* @throws NotSupportedException
* @return Format
*/
public static function create(string|self|MediaType|FileExtension $identifier): self
{
if ($identifier instanceof self) {
return $identifier;
}
if ($identifier instanceof MediaType) {
return $identifier->format();
}
if ($identifier instanceof FileExtension) {
return $identifier->format();
}
try {
$format = MediaType::from(strtolower($identifier))->format();
} catch (Error) {
try {
$format = FileExtension::from(strtolower($identifier))->format();
} catch (Error) {
throw new NotSupportedException('Unable to create format from "' . $identifier . '".');
}
}
return $format;
}
/**
* Return the possible media (MIME) types for the current format
*
* @return array
*/
public function mediaTypes(): array
{
return array_filter(MediaType::cases(), function ($mediaType) {
return $mediaType->format() === $this;
});
}
/**
* Return the possible file extension for the current format
*
* @return array
*/
public function fileExtensions(): array
{
return array_filter(FileExtension::cases(), function ($fileExtension) {
return $fileExtension->format() === $this;
});
}
/**
* Create an encoder instance that matches the format
*
* @param array $options
* @return EncoderInterface
*/
public function encoder(mixed ...$options): EncoderInterface
{
return match ($this) {
self::AVIF => new AvifEncoder(...$options),
self::BMP => new BmpEncoder(...$options),
self::GIF => new GifEncoder(...$options),
self::HEIC => new HeicEncoder(...$options),
self::JP2 => new Jpeg2000Encoder(...$options),
self::JPEG => new JpegEncoder(...$options),
self::PNG => new PngEncoder(...$options),
self::TIFF => new TiffEncoder(...$options),
self::WEBP => new WebpEncoder(...$options),
};
}
} |
import { screen, render } from '@testing-library/react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import Detail from './';
describe('Detail component', () => {
it('Should render the container', () => {
render(
<MemoryRouter initialEntries={['/books/test']}>
<Detail />
</MemoryRouter>
);
const container = screen.getByTestId('detail');
expect(container).toBeInTheDocument();
});
it('Should display the loading wheel when loading', () => {
render(
<MemoryRouter initialEntries={['/books/test']}>
<Detail />
</MemoryRouter>
);
const loadingWheel = screen.getByTestId('loading-wheel');
expect(loadingWheel).toBeInTheDocument();
});
it('Should display an error message if there is API error', async () => {
const server = setupServer(
rest.get('http://localhost:3001/books/test', (req, res, ctx) => {
return res(ctx.status(400));
})
);
server.listen();
render(
<MemoryRouter initialEntries={['/books/test']}>
<Routes>
<Route path='/books/:isbn' element={<Detail />} />
</Routes>
</MemoryRouter>
);
const error = await screen.findByText(/Failed to load book/);
expect(error).toBeInTheDocument();
server.close();
});
it('Should display API detail card information when API response is successful', async () => {
const server = setupServer(
rest.get('http://localhost:3001/books/test', (req, res, ctx) => {
return res(ctx.json({
author: 'test author',
publisher: 'test publisher',
city: 'test city',
format: 'test format',
year: 'test year',
isbn: 'test isbn',
title: 'test title',
type: 'fiction',
}));
}),
);
server.listen();
render(
<MemoryRouter initialEntries={['/books/test']}>
<Routes>
<Route path='/books/:isbn' element={<Detail />} />
</Routes>
</MemoryRouter>
);
const details = await screen.findAllByRole('heading');
expect(details[0]).toHaveTextContent('test title');
expect(details[1]).toHaveTextContent('AUTHOR');
expect(details[2]).toHaveTextContent('test author');
expect(details[3]).toHaveTextContent('PUBLISHER');
expect(details[4]).toHaveTextContent('test publisher');
expect(details[5]).toHaveTextContent('CITY');
expect(details[6]).toHaveTextContent('test city');
expect(details[7]).toHaveTextContent('FORMAT');
expect(details[8]).toHaveTextContent('test format');
expect(details[9]).toHaveTextContent('YEAR');
expect(details[10]).toHaveTextContent('test year');
expect(details[11]).toHaveTextContent('ISBN');
expect(details[12]).toHaveTextContent('test isbn');
server.close()
});
}); |
"""online_judge URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path,include
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('problem/',include('problem.urls')),
path('submission/',include('submissions.urls')),
### provides signup
path('accounts/',include('accounts.urls')),
### provides login,logout
path('accounts/',include('django.contrib.auth.urls')),
### profile links added
path('profile/', include('profiles.urls')),
### home page for the time being
path('',TemplateView.as_view(template_name='registration/home.html'),name='home'),
]
if settings.DEBUG :
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) |
from django.db import models
class Bb(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(null=True, blank=True)
price = models.FloatField(null=True, blank=True)
published = models.DateTimeField(auto_now_add=True, db_index=True)
rubric = models.ForeignKey('Rubric', null=True, on_delete=models.PROTECT, verbose_name='Рубрика')
class Meta:
verbose_name_plural = 'Объявления'
verbose_name = 'Объявление'
ordering = ['-published']
class Rubric(models.Model):
name = models.CharField(max_length=20, db_index=True,
verbose_name='Название')
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Рубрики'
verbose_name = 'Рубрика'
ordering = ['name'] |
'use strict';
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(value) {
const node = new Node(value);
if (!this.head) {
this.head = node;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
values() {
let values = [];
let current = this.head;
while (current) {
values.push(current.value);
current = current.next;
}
return values;
}
}
class Hashmap {
constructor(size) {
this.size = size;
this.map = new Array(size);
}
set(key, value) {
const asciiCodeSum = key.split("").reduce((sum, element) => {
return sum + element.charCodeAt();
}, 0);
const multiPrime = asciiCodeSum * 599;
const index = multiPrime % this.size;
// return index;
if (!this.map[index]) {
this.map[index] = new LinkedList();
}
this.map[index].append({
[key]: value
});
}
get(key) {
const idx = this.hash(key);
const bucket = this.map[idx];
// console.log(bucket);
if (bucket) {
let current = bucket.head;
while (current) {
if (current.value[key]) {
// console.log(current.value[key]);
return current.value[key];
}
current = current.next;
}
return null;
} else {
return null;
}
}
contains(key) {
const idx = this.hash(key);
const bucket = this.map[idx];
if (bucket) {
let current = bucket.head;
while (current) {
if (current.value[key]) {
// console.log(current.value[key]);
return true;
}
current = current.next;
}
return false;
} else {
return false;
}
}
keys() {
let keys = [];
this.map.map((e) => {
let current = e.head;
while (current) {
keys.push(Object.keys(current.value));
current = current.next;
}
});
return keys;
}
hash(key) {
const asciicodeSum = key.split('').reduce((acc, cur) => {
return acc + cur.charCodeAt(0);
}, 0);
const multiPrime = asciicodeSum * 599;
const index = multiPrime % this.size;
// console.log(index);
return index;
}
}
const myhashmap = new Hashmap(10);
myhashmap.set('esam', '401d15 student');
myhashmap.set('ahmad', '401d15 student');
myhashmap.set('mohamad', '401d15 student');
myhashmap.set('samah', '401d15 student');
myhashmap.set('laith', '401d15 student');
myhashmap.set('shihab', '401d15 student');
myhashmap.get('esam');
myhashmap.get('laith');
myhashmap.get('eee');
console.log(myhashmap.contains('laith'));
console.log(myhashmap.contains('eee'));
console.log('ppppppppppppppppp', myhashmap.get('esam'));
console.log('jjjjjjjjjjjjj', myhashmap.keys());
// console.log(myhashmap.map[8]);
// console.log(myhashmap.map[8].head.next);
// console.log(myhashmap);
// myhashmap.map.forEach((ll) => {
// console.log(ll.values());
// });
module.exports = Hashmap; |
// Submit this file with other files you created.
// Do not touch port declarations of the module 'CPU'.
// Guidelines
// 1. It is highly recommened to `define opcodes and something useful.
// 2. You can modify modules (except InstMemory, DataMemory, and RegisterFile)
// (e.g., port declarations, remove modules, define new modules, ...)
// 3. You might need to describe combinational logics to drive them into the module (e.g., mux, and, or, ...)
// 4. `include files if required
module CPU(input reset, // positive reset signal
input clk, // clock signal
output is_halted); // Whehther to finish simulation
/***** Wire declarations *****/
wire [31:0] next_pc;
wire [31:0] current_pc;
wire [31:0] inst;
wire [31:0] rd_din;
wire [31:0] rs1_dout;
wire [31:0] rs2_dout;
wire [31:0] imm_gen_out;
wire [31:0] alu_result;
wire [31:0] mem_dout;
wire alu_bcond; // TODO: will be used at control flow instruction feature
wire reg_write;
wire mem_read;
wire mem_write;
wire mem_to_reg;
wire pc_to_reg; // TODO: will be used at control flow instruction feature
wire is_ecall;
wire [3:0] alu_op;
wire alu_src;
wire stall;
wire [1:0] forward_a;
wire [1:0] forward_b;
wire [31:0] forwarded_rs2_data;
wire [31:0] alu_in_1;
wire [31:0] alu_in_2;
/***** Register declarations *****/
// You need to modify the width of registers
// In addition,
// 1. You might need other pipeline registers that are not described below
// 2. You might not need registers described below
/***** IF/ID pipeline registers *****/
reg [31:0] IF_ID_inst; // will be used in ID stage
/***** ID/EX pipeline registers *****/
// From the control unit
reg ID_EX_alu_src; // will be used in EX stage
reg ID_EX_mem_write; // will be used in MEM stage
reg ID_EX_mem_read; // will be used in MEM stage
reg ID_EX_mem_to_reg; // will be used in WB stage
reg ID_EX_reg_write; // will be used in WB stage
reg ID_EX_halt_cpu; // will be used in WB stage
// From others
reg [31:0] ID_EX_rs1_data;
reg [31:0] ID_EX_rs2_data;
reg [31:0] ID_EX_imm;
reg [31:0] ID_EX_ALU_ctrl_unit_input;
reg [4:0] ID_EX_rs1;
reg [4:0] ID_EX_rs2;
reg [4:0] ID_EX_rd;
/***** EX/MEM pipeline registers *****/
// From the control unit
reg EX_MEM_mem_write; // will be used in MEM stage
reg EX_MEM_mem_read; // will be used in MEM stage
reg EX_MEM_mem_to_reg; // will be used in WB stage
reg EX_MEM_reg_write; // will be used in WB stage
reg EX_MEM_halt_cpu; // will be used in WB stage
// From others
reg [31:0] EX_MEM_alu_out;
reg [31:0] EX_MEM_dmem_data;
reg [4:0] EX_MEM_rd;
/***** MEM/WB pipeline registers *****/
// From the control unit
reg MEM_WB_mem_to_reg; // will be used in WB stage
reg MEM_WB_reg_write; // will be used in WB stage
reg MEM_WB_halt_cpu; // will be used in WB stage
// From others
reg [31:0] MEM_WB_mem_to_reg_src_1;
reg [31:0] MEM_WB_mem_to_reg_src_2;
reg [4:0] MEM_WB_rd;
// TODO: should be change when control flow instruction implemented
Adder pc_adder (
.in1(current_pc),
.in2(32'd4),
.dout(next_pc)
);
// ---------- Update program counter ----------
// PC must be updated on the rising edge (positive edge) of the clock.
PC pc(
.reset(reset), // input (Use reset to initialize PC. Initial value must be 0)
.clk(clk), // input
.pc_write(!stall), // input
.next_pc(next_pc), // input
.current_pc(current_pc) // output
);
// ---------- Instruction Memory ----------
InstMemory imem(
.reset(reset), // input
.clk(clk), // input
.addr(current_pc), // input
.dout(inst) // output
);
// Update IF/ID pipeline registers here
always @(posedge clk) begin
if (reset) begin
IF_ID_inst <= 0;
end
else begin
if (!stall) begin
IF_ID_inst <= inst;
end
end
end
// ---------- Hazard Detection Unit ----------
HazardDetectionUnit hazard_detection_unit (
.reg_write_ex (ID_EX_reg_write), // input
.reg_write_mem (EX_MEM_reg_write), // input
.mem_read_ex (ID_EX_mem_read), // input
.opcode_id (IF_ID_inst[6:0]), // input
.rs1_id (is_ecall ? 5'b10001 : IF_ID_inst[19:15]), // input
.rs2_id (IF_ID_inst[24:20]), // input
.rd_ex (ID_EX_rd), // input
.rd_mem (EX_MEM_rd), // input
.stall (stall) // output
);
// ---------- Register File ----------
RegisterFile reg_file (
.reset (reset), // input
.clk (clk), // input
.rs1 (is_ecall ? 5'b10001 : IF_ID_inst[19:15]), // input
.rs2 (IF_ID_inst[24:20]), // input
.rd (MEM_WB_rd), // input
.rd_din (rd_din), // input
.write_enable (MEM_WB_reg_write), // input
.rs1_dout (rs1_dout), // output
.rs2_dout (rs2_dout) // output
);
// ---------- Control Unit ----------
ControlUnit ctrl_unit (
.part_of_inst(IF_ID_inst[6:0]), // input
.mem_read(mem_read), // output
.mem_to_reg(mem_to_reg), // output
.mem_write(mem_write), // output
.alu_src(alu_src), // output
.write_enable(reg_write), // output
.pc_to_reg(pc_to_reg), // output
.is_ecall(is_ecall) // output (ecall inst)
);
// ---------- Immediate Generator ----------
ImmediateGenerator imm_gen(
.inst(IF_ID_inst), // input
.imm_gen_out(imm_gen_out) // output
);
// Update ID/EX pipeline registers here
always @(posedge clk) begin
if (reset) begin
ID_EX_alu_src <= 0;
ID_EX_mem_write <= 0;
ID_EX_mem_read <= 0;
ID_EX_mem_to_reg <= 0;
ID_EX_reg_write <= 0;
ID_EX_halt_cpu <= 0;
ID_EX_rs1_data <= 0;
ID_EX_rs2_data <= 0;
ID_EX_imm <= 0;
ID_EX_ALU_ctrl_unit_input <= 0;
ID_EX_rd <= 0;
end
else begin
ID_EX_alu_src <= alu_src;
ID_EX_mem_write <= stall ? 0 : mem_write;
ID_EX_mem_read <= mem_read;
ID_EX_mem_to_reg <= mem_to_reg;
ID_EX_reg_write <= stall ? 0 : reg_write;
ID_EX_halt_cpu <= stall ? 0 : (is_ecall && rs1_dout == 10);
ID_EX_rs1_data <= rs1_dout;
ID_EX_rs2_data <= rs2_dout;
ID_EX_imm <= imm_gen_out;
ID_EX_ALU_ctrl_unit_input <= IF_ID_inst;
ID_EX_rs1 <= IF_ID_inst[19:15];
ID_EX_rs2 <= IF_ID_inst[24:20];
ID_EX_rd <= IF_ID_inst[11:7];
end
end
// Mux for alu_in_2
Mux2To1 alu_in_2_mux(
.din0(forwarded_rs2_data),
.din1(ID_EX_imm),
.sel(ID_EX_alu_src),
.dout(alu_in_2)
);
// Mux for rs1 data forwarding
Mux4To1 rs1_data_forward_mux(
.din0 (ID_EX_rs1_data),
.din1 (EX_MEM_alu_out),
.din2 (rd_din),
.din3 (32'b0),
.sel (forward_a),
.dout (alu_in_1)
);
// Mux for rs2 data forwarding
Mux4To1 rs2_data_forward_mux(
.din0 (ID_EX_rs2_data),
.din1 (EX_MEM_alu_out),
.din2 (rd_din),
.din3 (32'b0),
.sel (forward_b),
.dout (forwarded_rs2_data)
);
ForwardingUnit forwarding_unit (
.reg_write_mem (EX_MEM_reg_write), // input
.reg_write_wb (MEM_WB_reg_write), // input
.rs1_ex (ID_EX_rs1), // input
.rs2_ex (ID_EX_rs2), // input
.rd_mem (EX_MEM_rd), // input
.rd_wb (MEM_WB_rd), // input
.forward_a (forward_a), // output
.forward_b (forward_b) // output
);
// ---------- ALU Control Unit ----------
ALUControlUnit alu_ctrl_unit (
.inst(ID_EX_ALU_ctrl_unit_input), // input
.alu_op(alu_op) // output
);
// ---------- ALU ----------
ALU alu (
.alu_op(alu_op), // input
.alu_in_1(alu_in_1), // input
.alu_in_2(alu_in_2), // input
.alu_result(alu_result), // output
.alu_bcond(alu_bcond) // output
);
// Update EX/MEM pipeline registers here
always @(posedge clk) begin
if (reset) begin
EX_MEM_mem_write <= 0;
EX_MEM_mem_read <= 0;
EX_MEM_mem_to_reg <= 0;
EX_MEM_reg_write <= 0;
EX_MEM_halt_cpu <= 0;
EX_MEM_alu_out <= 0;
EX_MEM_dmem_data <= 0;
EX_MEM_rd <= 0;
end
else begin
EX_MEM_mem_write <= ID_EX_mem_write;
EX_MEM_mem_read <= ID_EX_mem_read;
EX_MEM_mem_to_reg <= ID_EX_mem_to_reg;
EX_MEM_reg_write <= ID_EX_reg_write;
EX_MEM_halt_cpu <= ID_EX_halt_cpu;
EX_MEM_alu_out <= alu_result;
EX_MEM_dmem_data <= forwarded_rs2_data;
EX_MEM_rd <= ID_EX_rd;
end
end
// ---------- Data Memory ----------
DataMemory dmem(
.reset (reset), // input
.clk (clk), // input
.addr (EX_MEM_alu_out), // input
.din (EX_MEM_dmem_data), // input
.mem_read (EX_MEM_mem_read), // input
.mem_write (EX_MEM_mem_write), // input
.dout (mem_dout) // output
);
// Update MEM/WB pipeline registers here
always @(posedge clk) begin
if (reset) begin
MEM_WB_mem_to_reg <= 0;
MEM_WB_reg_write <= 0;
MEM_WB_halt_cpu <= 0;
MEM_WB_mem_to_reg_src_1 <= 0;
MEM_WB_mem_to_reg_src_2 <= 0;
MEM_WB_rd <= 0;
end
else begin
MEM_WB_mem_to_reg <= EX_MEM_mem_to_reg;
MEM_WB_reg_write <= EX_MEM_reg_write;
MEM_WB_halt_cpu <= EX_MEM_halt_cpu;
MEM_WB_mem_to_reg_src_1 <= EX_MEM_alu_out;
MEM_WB_mem_to_reg_src_2 <= mem_dout;
MEM_WB_rd <= EX_MEM_rd;
end
end
// Mux for mem_to_reg
Mux2To1 mem_to_reg_mux(
.din0(MEM_WB_mem_to_reg_src_1),
.din1(MEM_WB_mem_to_reg_src_2),
.sel(MEM_WB_mem_to_reg),
.dout(rd_din)
);
assign is_halted = MEM_WB_halt_cpu;
endmodule |
import Link from 'next/link';
import { useState } from 'react';
import styles from './styles.module.scss';
import Image from 'next/image';
import registerImage from '../../../public/register-customer.jpg';
import Head from 'next/head';
import { fetchFromApi } from '../../lib/axios';
import { useRouter } from 'next/router';
import ValidateUsername from '../../components/ValidateUsername';
import ValidatePassword from '../../components/ValidatePassword';
export default function Register() {
const [user, setUser] = useState('');
const [password, setPassword] = useState('');
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const { data } = await fetchFromApi.post('/register', {
name: user,
password: password,
});
if (data.token) {
await fetch('/api/login', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
router.push('/');
}
} catch (error) {
console.error(error);
} finally {
setPassword('');
setUser('');
}
};
return (
<>
<Head>
<title>Registre-se | Faça a sua conta!</title>
</Head>
<section className={styles.container}>
<Image
src={registerImage}
quality={100}
alt='Login'
placeholder='blur'
blurDataURL='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mN0vQgAAWEBGHsgcxcAAAAASUVORK5CYII='
/>
<article>
<h1>Crie sua conta</h1>
<h3>Adicione um usuario e uma senha!</h3>
<form onSubmit={handleSubmit}>
<input
type='text'
placeholder='Usuario'
value={user}
required
onChange={(e) => setUser(e.target.value)}
/>
<ValidateUsername username={user} />
<input
type='password'
placeholder='Senha'
value={password}
required
onChange={(e) => setPassword(e.target.value)}
/>
<ValidatePassword password={password} />
<button type='submit'>Entrar</button>
</form>
<h3>
Já tem uma conta cadastrada?
</h3>
<Link href='/login'>Conecte-se</Link>
</article>
</section>
</>
);
} |
/** @format */
import React from "react";
import CustomerList from "../components/customer/CustomerList";
import EventList from "../components/rentalEvent/EventList";
import VehiclesList from "../components/vehicle/VehiclesList";
import { Switch, Route, Link } from "react-router-dom";
import Button from "react-bootstrap/Button";
import VehicleAdding from "../components/vehicle/VehicleAdding";
import CustomerAdding from "../components/customer/CustomerAdding";
import "./content.css";
import EventAdding from "../components/rentalEvent/EventAdding";
export default function Content() {
return (
<div>
<p className="intro-p">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Deserunt porro
sit iure culpa distinctio, vitae aliquid recusandae odio numquam
sapiente maxime adipisci laudantium dolor quisquam quis. Nobis
voluptates distinctio, impedit officia expedita ab maxime cum tenetur
itaque veritatis quibusdam qui eum dolorem unde corporis praesentium
eveniet, sunt reprehenderit? Asperiores hic delectus incidunt autem
explicabo mollitia ipsa qui voluptate totam voluptatem voluptatibus in,
minima quo maxime consequatur ipsam quaerat veritatis fuga rem
repudiandae, tempore odit, sequi officiis. Consectetur, eius ipsum qui
harum illo velit dolor facilis amet soluta dolorum assumenda delectus
iure repellendus architecto magni fugit tempora! Maxime, libero.
Molestias, incidunt!
</p>
<div className="content-btn-div">
<Link to="/vehicles">
<Button variant="secondary" className="content-btn">
Vehicles
</Button>{" "}
</Link>
<Link to="/customers">
<Button variant="secondary" className="content-btn">
Customers
</Button>{" "}
</Link>
<Link to="/events">
<Button variant="secondary" className="content-btn">
Rent Events
</Button>
</Link>
</div>
<Switch>
<Route path="/vehicles" component={VehiclesList} />
<Route path="/customers" component={CustomerList} />
<Route path="/events" component={EventList} />
<Route path="/addvehicle" component={VehicleAdding} />
<Route path="/addcustomer" component={CustomerAdding} />
<Route path="/addevent" component={EventAdding} />
</Switch>
</div>
);
} |
syntax = "proto3";
package library;
message Library {
string id = 1;
string title = 2;
string description = 3;
}
message GetLibraryRequest {
string library_id = 1;
}
message GetLibraryResponse {
Library library = 1;
}
message SearchLibrarysRequest {
string query = 1;
}
message SearchLibrarysResponse {
repeated Library librarys = 1;
}
message CreateLibraryRequest {
string library_id = 1;
string title = 2;
string description = 3;
}
message CreateLibraryResponse {
Library library = 1;
}
service LibraryService {
rpc GetLibrary(GetLibraryRequest) returns (GetLibraryResponse);
rpc SearchLibrarys(SearchLibrarysRequest) returns (SearchLibrarysResponse);
rpc CreateLibrary(CreateLibraryRequest) returns (CreateLibraryResponse);
} |
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import '../AdHelper/adshelper.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var count = 1;
var random_dice_no_1 = Random();
var random_dice_no_2 = Random();
var random_dice_no_3 = Random();
var random_dice_no_4 = Random();
var random_dice_no_5 = Random();
var random_dice_no_6 = Random();
var rnd_1 = 1;
var rnd_2 = 1;
var rnd_3 = 1;
var rnd_4 = 1;
var rnd_5 = 1;
var rnd_6 = 1;
var back = Colors.blue.shade100;
Future<void>? _launched;
late BannerAd _bannerAd;
bool _isBannerAdReady = false;
@override
void initState() {
// TODO: implement initState
super.initState();
_bannerAd = BannerAd(
adUnitId: AdHelper.bannerAdUnitIdOfHomeScreen,
request: AdRequest(),
size: AdSize.banner,
listener: BannerAdListener(
onAdLoaded: (_) {
setState(() {
_isBannerAdReady = true;
});
},
onAdFailedToLoad: (ad, err) {
print('Failed to load a banner ad: ${err.message}');
_isBannerAdReady = false;
ad.dispose();
},
),
);
_bannerAd.load();
}
@override
void dispose() {
super.dispose();
_bannerAd.dispose();
}
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
));
return GestureDetector(
onTap: () {
// back = Color((random_dice_no_1.nextDouble() * 0x00FFFFFF).toInt()).withOpacity(1);
setState(() {
rnd_1 = random_dice_no_1.nextInt(6)+1;
rnd_2 = random_dice_no_2.nextInt(6)+1;
rnd_3 = random_dice_no_3.nextInt(6)+1;
rnd_4 = random_dice_no_4.nextInt(6)+1;
rnd_5 = random_dice_no_5.nextInt(6)+1;
rnd_6 = random_dice_no_6.nextInt(6)+1;
});
},
child: Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
SizedBox(height: 20.0,),
Expanded(
flex: 1,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
count > 1 ? GestureDetector(
onTap: (){
if(count >= 2)
{
count_minus();
}
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(Icons.indeterminate_check_box_outlined,size: 60,),
),
) : Container(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"${count} Dice",
textAlign: TextAlign.center,
style: GoogleFonts.mochiyPopOne(textStyle: TextStyle(fontSize: 50,color: Colors.black,fontWeight: FontWeight.w600,))
),
),
GestureDetector(
onTap: (){
if(count < 6)
{
count_add();
}
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(Icons.add_box_outlined,size: 60,),
),
),
],
),
),
if (count == 1) ...[
Expanded(
flex: 3,
child: Center(
child: Image.asset('assets/images/$rnd_1-dice.png',
height: 280,
width: 280,
alignment: Alignment.center,),
),
),
]
else if (count == 2) ...[
Expanded(
flex: 3,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_1-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_2-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
],
),
),
]
else if (count == 3) ...[
Expanded(
flex: 3,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_1-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_2-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
],
),
Center(
child: Image.asset('assets/images/$rnd_3-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
],
),
),
]
else if (count == 4) ...[
Expanded(
flex: 3,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_1-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_2-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_3-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_4-dice.png',
height: 180,
width: 180,
alignment: Alignment.center,),
),
],
),
],
),
),
]
else if (count == 5) ...[
Expanded(
flex: 3,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_1-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_2-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_3-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_4-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
],
),
Center(
child: Image.asset('assets/images/$rnd_5-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
],
),
),
]
else if (count == 6) ...[
Expanded(
flex: 3,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_1-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_2-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_3-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_4-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset('assets/images/$rnd_5-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
Center(
child: Image.asset('assets/images/$rnd_6-dice.png',
height: 150,
width: 150,
alignment: Alignment.center,),
),
],
),
],
),
),
],
SizedBox(height: 10,),
Text(
"Tap to Roll..",
textAlign: TextAlign.center,
style: GoogleFonts.mochiyPopOne(textStyle: TextStyle(fontSize: 40,color: Colors.black,fontWeight: FontWeight.w600,))
),
SizedBox(height: 30,),
],
),
),
bottomNavigationBar: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_isBannerAdReady)
Container(
width: _bannerAd.size.width.toDouble(),
height: _bannerAd.size.height.toDouble(),
child: AdWidget(ad: _bannerAd),
),
],
),
),
);
}
void count_add() {
setState(() {
count = count + 1;
});
}
void count_minus() {
setState(() {
count = count - 1;
});
}
} |
var current_unit_index = 0;
function generate_new_unit_id(){
current_unit_index++;
return current_unit_index;
}
/*
var unit = {
defense: 1, // used to determine how much damage this unit can sustain before expiring
attack: 1, // used to determine how much damage to apply when attacking
move_range: 1, // used to determine how many tiles in a direction a unit can move
attack_range: 1, // used to determine how many tiles this unit can attack in
model: 0, // used to instaniate the visual aspect of this unit
unit_id: -1 // used to have a common referencable id between clients
}
*/
// CHARACTER MODEL INDICIES //
const unit_worker = 0;
const unit_soldier = 1;
const unit_sniper = 2;
const unit_tower = 3;
const worker_cost = 75;
const soldier_cost = 125;
const sniper_cost = 225;
const tower_cost = 500;
// for now just add 125 to the cost
const worker_resort_cost = 200;
const soldier_resort_cost = 250;
const sniper_resort_cost = 350;
const tower_resort_cost = 625;
function SERVER_CREATE_UNIT(type, position, player_id){
let new_unit = init_new_unit_object(type, position, player_id);
new_unit.unit_id = generate_new_unit_id();
return new_unit;
}
// CHARACTER STATS GENERATION //
function init_new_unit_object(type, position, owning_player_id){
let n_unit = stats_for_unit(type);
n_unit.pos = position;
n_unit.type = type;
n_unit.owner = owning_player_id;
return n_unit;
}
function stats_for_unit(type){
if (type == unit_worker) return create_worker();
else if (type == unit_soldier) return create_soldier();
else if (type == unit_sniper) return create_sniper();
else if (type == unit_tower) return create_tower();
return -1;
}
function create_soldier(){
return {
defense: 3,
attack: 2,
move_range: 3,
attack_range: 3,
vision_range: 3
};
}
function create_worker(){
return {
defense: 2,
attack: 2,
move_range: 2,
attack_range: 2,
vision_range: 4
};
}
function create_sniper(){
return {
defense: 2,
attack: 1,
move_range: 2,
attack_range: 5,
vision_range: 7
};
}
function create_tower(){
return {
defense: 10,
attack: 5,
move_range: 1,
attack_range: 3,
vision_range: 4
};
} |
#include<sys/socket.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<cstring>
int main()
{
// 参数一:IP 地址类型; AF_INET -> IPv4 AF_INET6 -> IPv6
// 参数二:数据传输方式; SOCK_STREAM 流格式,面向连接 -> TCP ,数据报格式,无连接 -> UPD
// 参数三:协议; 0 表示根据前面的两个参数自动推导协议类型:TCP/UDP
int sockfd = socket(AF_INET,SOCK_STREAM,0);
// 将套接字绑定到一个 IP 地址和端口上
struct sockaddr_in serv_addr;
bzero(&serv_addr,sizeof(serv_addr));
serv_addr.sin_family= AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_addr.sin_port = htons(8888);
// 将 socket 地址与文件描述符绑定
bind(sockfd, (sockaddr*)&serv_addr , sizeof(serv_addr));
// 监听 socket 端口;参数二:最大监听队列长度
listen(sockfd, SOMAXCONN);
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_len = sizeof(clnt_addr);
bzero(&clnt_addr,sizeof(clnt_addr));
// 接受客户端连接,accept 函数会阻塞当前程序,直到有一个客户端 socket 被接受程序后才会往下运行
int clnt_sockfd = accept(sockfd,(sockaddr*)&clnt_addr,&clnt_addr_len);
printf("new client fd %d! IP: %s Port: %d\n",clnt_sockfd, inet_ntoa(clnt_addr.sin_addr),ntohs(clnt_addr.sin_port));
return 0;
} |
import React, { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import CloseIcon from '@mui/icons-material/Close';
import warningAnimation from 'assets/warning.gif';
import { Button, Modal } from 'shared';
import useModal from 'hooks/useModal';
import useStyles from 'modules/Admin/components/Campaign/Modal/EditModal/styled.editModal';
function EditModal() {
const classes = useStyles();
const [state, setState] = useModal();
const navigate = useNavigate();
const handleExit = useCallback(() => {
setState({ ...state, modalName: '' });
navigate('/admin/campaign/view/:id');
}, [state]);
const handleClose = useCallback(() => {
setState({ ...state, modalName: '' });
}, [state]);
const handleEdit = useCallback(() => {
navigate('/admin/campaign/add-new');
});
return (
<Modal modalName="editModal">
<Grid container justifyContent="flex-end" className={classes.close}>
<Grid item>
<CloseIcon onClick={handleClose} />
</Grid>
</Grid>
<Box className={classes.copy}>
<img
src={warningAnimation}
alt="warning icon"
style={{ width: '20%' }}
/>
<Typography variant="h3">Are you sure you want to Edit!</Typography>
<Typography variant="body1">
You are about to edit the details of a campaign This changes the
campaign details.
</Typography>
</Box>
<Box className={classes.action}>
<Grid container justifyContent="flex-end" spacing={2}>
<Grid item>
<Button onClick={handleExit}>Cancel</Button>
</Grid>
<Grid item>
<Button variant="text" color="primary" onClick={handleEdit}>
Yes, Edit
</Button>
</Grid>
</Grid>
</Box>
</Modal>
);
}
export default EditModal; |
---
title: Diseño de Páginas Web para Centros de Estética en Castellón de la Plana
date: '2023-10-04'
tags: ['Diseño web', 'Centros de Estética', 'Castellón de la Plana']
draft: false
banner : diseño_paginas_web_centrosdeestética
fondoBanner : diseño_pagina_web_castellóndelaplana
summary: El diseño de páginas web para centros de estética en Castellón de la Plana es esencial para destacar en un sector tan competitivo. En un mundo cada vez más digitalizado, contar con una presencia online efectiva es clave para atraer a nuevos clientes y mantenerse relevante en el mercado.
---
import Cta from "../../../components/Cta.astro";
import CtaBot from "../../../components/CtaBot.astro";
import GifSeo from "../../../components/GifSeo.astro";
import Gmaps from "../../../components/Gmaps.astro";
import Video from "../../../components/Video.astro";
## Diseño de Páginas Web para Centros de Estética en Castellón de la Plana
El diseño de páginas web para centros de estética en Castellón de la Plana es esencial para destacar en un sector tan competitivo. En un mundo cada vez más digitalizado, contar con una presencia online efectiva es clave para atraer a nuevos clientes y mantenerse relevante en el mercado.
### Motivos por los que necesitan una página web en su profesión y en su ciudad:
1. **Aumentar la visibilidad:** Una página web optimizada les permitirá ser encontrados fácilmente por personas que buscan servicios de estética en Castellón de la Plana.
2. **Diferenciarse de la competencia:** Con una página web profesional y atractiva, podrán destacar entre otros centros de estética en la ciudad, mostrando su estilo único y los servicios que ofrecen.
3. **Mostrar su experiencia y servicios:** Una página web les brinda la oportunidad de presentar su experiencia en el sector, así como los diferentes servicios que ofrecen a sus clientes.
4. **Generar confianza:** Una página web bien diseñada y con contenido de calidad transmitirá profesionalidad y confianza a los visitantes, motivándolos a elegir su centro de estética.
### Beneficios del diseño web para su profesión y su ciudad:
1. **Mayor alcance:** Una página web les permitirá llegar a un público más amplio, incluso más allá de Castellón de la Plana. Podrán atraer a nuevos clientes de otras ciudades que estén buscando servicios de estética en la zona.
2. **Información actualizada:** A través de su página web, podrán mantener a sus clientes informados sobre las últimas novedades, promociones y servicios que ofrecen en su centro de estética.
3. **Facilidad de contacto:** Una página web les brinda la oportunidad de incluir formularios de contacto, facilitando a los visitantes el poder solicitar información o reservar citas sin tener que llamar por teléfono.
4. **Exposición de opiniones y testimonios:** Integrar reseñas y testimonios de clientes satisfechos en su página web ayudará a generar confianza en los visitantes y aumentar las posibilidades de que elijan su centro de estética.
5. **Aprovechar el crecimiento del sector:** El mercado de la estética en Castellón de la Plana está en constante crecimiento. Tener una presencia online sólida les permitirá aprovechar al máximo esta tendencia y atraer a más clientes interesados en sus servicios.
Con un diseño web efectivo diseñado por Élite Webs, su centro de estética en Castellón de la Plana podrá destacar y convertir las visitas en ventas. No pierdan la oportunidad de contar con una presencia online de calidad que los diferencie y les permita atraer a más clientes en esta ciudad tan cosmopolita y turística.
<GifSeo />
<Cta />
## Diseño de Página Web para Centros de Estética en Castellón de la Plana
En Élite Webs, somos expertos en el diseño y desarrollo de páginas web para centros de estética en Castellón de la Plana. Nuestro enfoque se centra en convertir las visitas en ventas, brindándote una presencia en línea atractiva y efectiva que impulse el crecimiento de tu negocio. A continuación, te explicamos los elementos clave que consideramos para lograr un diseño web exitoso y cómo nuestro servicio puede ayudarte.
## Elementos clave del diseño web exitoso
- **Diseño atractivo y profesional**: Creamos páginas web con un diseño visualmente atractivo y profesional, que refleje la estética y la imagen de tu centro. Utilizamos colores, tipografías y elementos gráficos que transmitan confianza y sofisticación.
- **Funcionalidad y navegación intuitiva**: Nos aseguramos de que tu página web sea fácil de usar y navegar. Implementamos una estructura clara de menús y submenús, junto con enlaces internos y externos relevantes, para facilitar la exploración de tus servicios y promociones.
- **Optimización para dispositivos móviles**: Dado que cada vez más personas acceden a internet desde sus teléfonos móviles, aseguramos que tu página web tenga un diseño y una experiencia de usuario adaptada a dispositivos móviles. Esto garantiza que tus clientes potenciales puedan visitarte y contactarte sin problemas desde sus smartphones.
- **Contenido relevante y persuasivo**: Creamos contenido persuasivo y relevante para captar la atención de tus visitantes. Destacamos los beneficios de tus servicios, compartimos testimonios de clientes satisfechos y te ayudamos a transmitir tus valores y ventajas competitivas.
- **Integración de herramientas de reserva y contacto**: Facilitamos a tus clientes potenciales la solicitud de citas, con la integración de herramientas de reserva en línea y formularios de contacto. Esto permite una comunicación fluida y rápida entre tu centro de estética y tus clientes.
## Cómo nuestro servicio de diseño web puede ayudar
Nuestro servicio de diseño web para centros de estética en Castellón de la Plana te brinda una solución completa para impulsar tu negocio en línea. Al elegirnos, beneficiarás de:
- Una página web personalizada y atractiva que refuerce tu imagen de marca.
- Un diseño web optimizado para SEO, lo que aumentará tu visibilidad en los motores de búsqueda y te ayudará a atraer más tráfico orgánico.
- La integración de herramientas de reserva en línea y formularios de contacto, lo que facilitará la comunicación con tus clientes potenciales.
- Un diseño responsive que se adapta a dispositivos móviles, para llegar a un público más amplio y mejorar la experiencia de usuario.
- Soporte técnico y actualizaciones regulares para mantener tu página web funcionando sin problemas y al día con las últimas tendencias del diseño web.
## Conclusión: Tu página web de calidad, nuestra especialidad
En el mundo digital de hoy, es fundamental para los centros de estética en Castellón de la Plana tener una página web de calidad. Una presencia en línea efectiva te ayudará a destacar entre tu competencia y atraer a más clientes. En Élite Webs, nos especializamos en el diseño y desarrollo de páginas web que convierten visitas en ventas. Nuestro enfoque en los elementos clave del diseño web exitoso y en ofrecer un servicio personalizado nos diferencia de la competencia.
No pierdas la oportunidad de llevar tu centro de estética al siguiente nivel. Contáctanos hoy mismo para discutir tus necesidades y descubre cómo podemos ayudarte a alcanzar el éxito en línea.
<Video />
<CtaBot job='Centros de Estética' city='Castellón de la Plana'/>
<Gmaps query='Castellón de la Plana+españa+maps' /> |
// https://jsonplaceholder.typicode.com/posts
// https://jsonplaceholder.typicode.com/posts?_limit=3&_page=2
const postContainer = document.getElementById('post-container');
const loading = document.querySelector('.loader');
const filter = document.getElementById('filter');
const allPostsFetched = document.getElementById('all-posts-fetched');
let limit =10;
let page = 1;
// Fetch Data
async function getPosts() {
console.log(`https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`);
const res = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`)
const data = await res.json();
return data;
}
// Show Posts in the DOM
async function showPosts() {
const posts = await getPosts();
posts.forEach(post => {
const postEl = document.createElement('div');
postEl.classList.add('post');
postEl.innerHTML = `
<div class="number">${post.id}</div>
<div class="post-info">
<h2 class="post-title">${post.title}</h2>
<p class="post-body">
${post.body}
</p>
</div>
`;
postContainer.appendChild(postEl);
});
};
// show loading and fetch more posts
function showLoading() {
console.log(page)
loading.classList.add('show');
setTimeout(()=> {
loading.classList.remove('show');
setTimeout(()=> {
page++;
showPosts();
},350)
}, 1000)
}
showPosts();
// Add window event listener
window.addEventListener('scroll', (e) => {
const { scrollTop, scrollHeight, clientHeight} = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5){
showLoading();
}
});
filter.addEventListener('input', e => {
const term = e.target.value.toLowerCase().trim();
const posts = document.querySelectorAll('.post');
posts.forEach(post => {
const title = post.querySelector('.post-title').innerText.toLowerCase();
// const body = post.querySelector('.post-body').innerText;
if (title.indexOf(term) > -1){
post.style.display = 'flex';
}else {
post.style.display = 'none';
}
})
}) |
/**
* You can specify the following actions in the `Action` element of an IAM policy statement
* @see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonec2imagebuilder.html
*/
export enum ImagebuilderAction {
/**
* Write - Grants permission to cancel an image creation
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CancelImageCreation.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*/
CancelImageCreation = "imagebuilder:CancelImageCreation",
/**
* Write - Grants permission to create a new component
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CreateComponent.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
* - {@link ImagebuilderResource.kmsKey `ImagebuilderResource.kmsKey`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
CreateComponent = "imagebuilder:CreateComponent",
/**
* Write - Grants permission to create a new Container Recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CreateContainerRecipe.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
CreateContainerRecipe = "imagebuilder:CreateContainerRecipe",
/**
* Write - Grants permission to create a new distribution configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CreateDistributionConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
CreateDistributionConfiguration = "imagebuilder:CreateDistributionConfiguration",
/**
* Write - Grants permission to create a new image
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CreateImage.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
CreateImage = "imagebuilder:CreateImage",
/**
* Write - Grants permission to create a new image pipeline
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CreateImagePipeline.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
CreateImagePipeline = "imagebuilder:CreateImagePipeline",
/**
* Write - Grants permission to create a new Image Recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CreateImageRecipe.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
CreateImageRecipe = "imagebuilder:CreateImageRecipe",
/**
* Write - Grants permission to create a new infrastructure configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_CreateInfrastructureConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
* - `imagebuilder:CreatedResourceTagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-createdresourcetagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
* - `imagebuilder:CreatedResourceTag/<key>`: Filters access by the tag key-value pairs attached to the resource created by Image Builder ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-createdresourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `imagebuilder:Ec2MetadataHttpTokens`: Filters access by the EC2 Instance Metadata HTTP Token Requirement specified in the request ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-ec2metadatahttptokens documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `imagebuilder:StatusTopicArn`: Filters access by the SNS Topic Arn in the request to which terminal state notifications will be published ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-statustopicarn documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
CreateInfrastructureConfiguration = "imagebuilder:CreateInfrastructureConfiguration",
/**
* Write - Grants permission to delete a component
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DeleteComponent.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
*/
DeleteComponent = "imagebuilder:DeleteComponent",
/**
* Write - Grants permission to delete a container recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DeleteContainerRecipe.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
*/
DeleteContainerRecipe = "imagebuilder:DeleteContainerRecipe",
/**
* Write - Grants permission to delete a distribution configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DeleteDistributionConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
*/
DeleteDistributionConfiguration = "imagebuilder:DeleteDistributionConfiguration",
/**
* Write - Grants permission to delete an image
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DeleteImage.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*/
DeleteImage = "imagebuilder:DeleteImage",
/**
* Write - Grants permission to delete an image pipeline
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DeleteImagePipeline.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
*/
DeleteImagePipeline = "imagebuilder:DeleteImagePipeline",
/**
* Write - Grants permission to delete an image recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DeleteImageRecipe.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
*/
DeleteImageRecipe = "imagebuilder:DeleteImageRecipe",
/**
* Write - Grants permission to delete an infrastructure configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DeleteInfrastructureConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
*/
DeleteInfrastructureConfiguration = "imagebuilder:DeleteInfrastructureConfiguration",
/**
* Read - Grants permission to view details about a component
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetComponent.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
*/
GetComponent = "imagebuilder:GetComponent",
/**
* Read - Grants permission to view the resource policy associated with a component
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetComponentPolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
*/
GetComponentPolicy = "imagebuilder:GetComponentPolicy",
/**
* Read - Grants permission to view details about a container recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetContainerRecipe.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
*/
GetContainerRecipe = "imagebuilder:GetContainerRecipe",
/**
* Read - Grants permission to view the resource policy associated with a container recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetContainerRecipePolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
*/
GetContainerRecipePolicy = "imagebuilder:GetContainerRecipePolicy",
/**
* Read - Grants permission to view details about a distribution configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetDistributionConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
*/
GetDistributionConfiguration = "imagebuilder:GetDistributionConfiguration",
/**
* Read - Grants permission to view details about an image
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetImage.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
GetImage = "imagebuilder:GetImage",
/**
* Read - Grants permission to view details about an image pipeline
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetImagePipeline.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
*/
GetImagePipeline = "imagebuilder:GetImagePipeline",
/**
* Read - Grants permission to view the resource policy associated with an image
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetImagePolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*/
GetImagePolicy = "imagebuilder:GetImagePolicy",
/**
* Read - Grants permission to view details about an image recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetImageRecipe.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
*/
GetImageRecipe = "imagebuilder:GetImageRecipe",
/**
* Read - Grants permission to view the resource policy associated with an image recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetImageRecipePolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
*/
GetImageRecipePolicy = "imagebuilder:GetImageRecipePolicy",
/**
* Read - Grants permission to view details about an infrastructure configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_GetInfrastructureConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
*/
GetInfrastructureConfiguration = "imagebuilder:GetInfrastructureConfiguration",
/**
* Write - Grants permission to import a new component
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ImportComponent.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
* - {@link ImagebuilderResource.kmsKey `ImagebuilderResource.kmsKey`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
ImportComponent = "imagebuilder:ImportComponent",
/**
* Write - Grants permission to import an image
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ImportVmImage.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
ImportVmImage = "imagebuilder:ImportVmImage",
/**
* List - Grants permission to list the component build versions in your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListComponentBuildVersions.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.componentVersion `ImagebuilderResource.componentVersion`}
*/
ListComponentBuildVersions = "imagebuilder:ListComponentBuildVersions",
/**
* List - Grants permission to list the component versions owned by or shared with your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListComponents.html
*/
ListComponents = "imagebuilder:ListComponents",
/**
* List - Grants permission to list the container recipes owned by or shared with your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListContainerRecipes.html
*/
ListContainerRecipes = "imagebuilder:ListContainerRecipes",
/**
* List - Grants permission to list the distribution configurations in your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListDistributionConfigurations.html
*/
ListDistributionConfigurations = "imagebuilder:ListDistributionConfigurations",
/**
* List - Grants permission to list the image build versions in your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListImageBuildVersions.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imageVersion `ImagebuilderResource.imageVersion`}
*/
ListImageBuildVersions = "imagebuilder:ListImageBuildVersions",
/**
* List - Grants permission to returns a list of packages installed on the specified image
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListImagePackages.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
ListImagePackages = "imagebuilder:ListImagePackages",
/**
* List - Grants permission to returns a list of images created by the specified pipeline
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListImagePipelineImages.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
*/
ListImagePipelineImages = "imagebuilder:ListImagePipelineImages",
/**
* List - Grants permission to list the image pipelines in your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListImagePipelines.html
*/
ListImagePipelines = "imagebuilder:ListImagePipelines",
/**
* List - Grants permission to list the image recipes owned by or shared with your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListImageRecipes.html
*/
ListImageRecipes = "imagebuilder:ListImageRecipes",
/**
* List - Grants permission to list the image versions owned by or shared with your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListImages.html
*/
ListImages = "imagebuilder:ListImages",
/**
* List - Grants permission to list the infrastructure configurations in your account
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListInfrastructureConfigurations.html
*/
ListInfrastructureConfigurations = "imagebuilder:ListInfrastructureConfigurations",
/**
* Read - Grants permission to list tag for an Image Builder resource
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ListTagsForResource.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
ListTagsForResource = "imagebuilder:ListTagsForResource",
/**
* PermissionsManagement - Grants permission to set the resource policy associated with a component
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_PutComponentPolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
*/
PutComponentPolicy = "imagebuilder:PutComponentPolicy",
/**
* PermissionsManagement - Grants permission to set the resource policy associated with a container recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_PutContainerRecipePolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
*/
PutContainerRecipePolicy = "imagebuilder:PutContainerRecipePolicy",
/**
* PermissionsManagement - Grants permission to set the resource policy associated with an image
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_PutImagePolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
*/
PutImagePolicy = "imagebuilder:PutImagePolicy",
/**
* PermissionsManagement - Grants permission to set the resource policy associated with an image recipe
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_PutImageRecipePolicy.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
*/
PutImageRecipePolicy = "imagebuilder:PutImageRecipePolicy",
/**
* Write - Grants permission to create a new image from a pipeline
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_StartImagePipelineExecution.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
*/
StartImagePipelineExecution = "imagebuilder:StartImagePipelineExecution",
/**
* Tagging - Grants permission to tag an Image Builder resource
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_TagResource.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
TagResource = "imagebuilder:TagResource",
/**
* Tagging - Grants permission to untag an Image Builder resource
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_UntagResource.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
*/
UntagResource = "imagebuilder:UntagResource",
/**
* Write - Grants permission to update an existing distribution configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_UpdateDistributionConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
*/
UpdateDistributionConfiguration = "imagebuilder:UpdateDistributionConfiguration",
/**
* Write - Grants permission to update an existing image pipeline
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_UpdateImagePipeline.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
*/
UpdateImagePipeline = "imagebuilder:UpdateImagePipeline",
/**
* Write - Grants permission to update an existing infrastructure configuration
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_UpdateInfrastructureConfiguration.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `imagebuilder:CreatedResourceTagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-createdresourcetagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
* - `imagebuilder:CreatedResourceTag/<key>`: Filters access by the tag key-value pairs attached to the resource created by Image Builder ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-createdresourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `imagebuilder:Ec2MetadataHttpTokens`: Filters access by the EC2 Instance Metadata HTTP Token Requirement specified in the request ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-ec2metadatahttptokens documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `imagebuilder:StatusTopicArn`: Filters access by the SNS Topic Arn in the request to which terminal state notifications will be published ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-statustopicarn documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
UpdateInfrastructureConfiguration = "imagebuilder:UpdateInfrastructureConfiguration",
/**
* * - Grant all imagebuilder permissions
* @see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonec2imagebuilder.html
*
* @remarks
*
* It can be used with the following resource types in the `Resource` element of IAM policy statements:
* - {@link ImagebuilderResource.image `ImagebuilderResource.image`}
* - {@link ImagebuilderResource.component `ImagebuilderResource.component`}
* - {@link ImagebuilderResource.kmsKey `ImagebuilderResource.kmsKey`}
* - {@link ImagebuilderResource.containerRecipe `ImagebuilderResource.containerRecipe`}
* - {@link ImagebuilderResource.distributionConfiguration `ImagebuilderResource.distributionConfiguration`}
* - {@link ImagebuilderResource.imagePipeline `ImagebuilderResource.imagePipeline`}
* - {@link ImagebuilderResource.imageRecipe `ImagebuilderResource.imageRecipe`}
* - {@link ImagebuilderResource.infrastructureConfiguration `ImagebuilderResource.infrastructureConfiguration`}
* - {@link ImagebuilderResource.componentVersion `ImagebuilderResource.componentVersion`}
* - {@link ImagebuilderResource.imageVersion `ImagebuilderResource.imageVersion`}
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:RequestTag/${TagKey}`: Filters access by the presence of tag key-value pairs in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:TagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
* - `imagebuilder:CreatedResourceTagKeys`: Filters access by the presence of tag keys in the request ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-createdresourcetagkeys documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ArrayOfString `ArrayOfString`})
* - `imagebuilder:CreatedResourceTag/<key>`: Filters access by the tag key-value pairs attached to the resource created by Image Builder ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-createdresourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `imagebuilder:Ec2MetadataHttpTokens`: Filters access by the EC2 Instance Metadata HTTP Token Requirement specified in the request ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-ec2metadatahttptokens documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `imagebuilder:StatusTopicArn`: Filters access by the SNS Topic Arn in the request to which terminal state notifications will be published ({@link https://docs.aws.amazon.com/imagebuilder/latest/userguide/security_iam_service-with-iam.html#image-builder-security-statustopicarn documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
All = "imagebuilder:*",
}
/**
* You can specify the following resources in the `Resource` element of an IAM policy statement
* @see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonec2imagebuilder.html
*/
export const ImagebuilderResource = {
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_Component.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
component: (options: Partial<{partition: string, region: string, account: string, componentName: string, componentVersion: string, componentBuildVersion: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:component/${options.componentName || '*'}/${options.componentVersion || '*'}/${options.componentBuildVersion || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ComponentVersion
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
componentVersion: (options: Partial<{partition: string, region: string, account: string, componentName: string, componentVersion: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:component/${options.componentName || '*'}/${options.componentVersion || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_DistributionConfiguration.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
distributionConfiguration: (options: Partial<{partition: string, region: string, account: string, distributionConfigurationName: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:distribution-configuration/${options.distributionConfigurationName || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_Image.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
image: (options: Partial<{partition: string, region: string, account: string, imageName: string, imageVersion: string, imageBuildVersion: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:image/${options.imageName || '*'}/${options.imageVersion || '*'}/${options.imageBuildVersion || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ImageVersion.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
imageVersion: (options: Partial<{partition: string, region: string, account: string, imageName: string, imageVersion: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:image/${options.imageName || '*'}/${options.imageVersion || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ImageRecipe.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
imageRecipe: (options: Partial<{partition: string, region: string, account: string, imageRecipeName: string, imageRecipeVersion: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:image-recipe/${options.imageRecipeName || '*'}/${options.imageRecipeVersion || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ContainerRecipe.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
containerRecipe: (options: Partial<{partition: string, region: string, account: string, containerRecipeName: string, containerRecipeVersion: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:container-recipe/${options.containerRecipeName || '*'}/${options.containerRecipeVersion || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_ImagePipeline.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
imagePipeline: (options: Partial<{partition: string, region: string, account: string, imagePipelineName: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:image-pipeline/${options.imagePipelineName || '*'}`,
/**
* @see https://docs.aws.amazon.com/imagebuilder/latest/APIReference/API_InfrastructureConfiguration.html
*
* @remarks
*
* It can be used with the following condition keys in the `Condition` element of an IAM policy statements:
* - `aws:ResourceTag/${TagKey}`: Filters access by tag key-value pairs attached to the resource ({@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag documentation}, type: {@link https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String `String`})
*/
infrastructureConfiguration: (options: Partial<{partition: string, region: string, account: string, resourceId: string}> = {}) => `arn:${options.partition || '*'}:imagebuilder:${options.region || '*'}:${options.account || '*'}:infrastructure-configuration/${options.resourceId || '*'}`,
/**
* @see https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys
*/
kmsKey: (options: Partial<{partition: string, region: string, account: string, keyId: string}> = {}) => `arn:${options.partition || '*'}:kms:${options.region || '*'}:${options.account || '*'}:key/${options.keyId || '*'}`,
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Shop_Dotnet2020.Models;
namespace Shop_Dotnet2020.Controllers
{
[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowOrigin")]
public class LogsController : ControllerBase
{
ShopDotnetContext _context = new ShopDotnetContext();
// GET: api/Logs
[HttpGet]
public async Task<ActionResult<IEnumerable<Log>>> GetLogs()
{
return await _context.Logs.ToListAsync();
}
// GET: api/Logs/5
[HttpGet("{id}")]
public async Task<ActionResult<Log>> GetLog(int id)
{
var log = await _context.Logs.FindAsync(id);
if (log == null)
{
return NotFound();
}
return log;
}
// PUT: api/Logs/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPut("{id}")]
public async Task<IActionResult> PutLog(int id, Log log)
{
if (id != log.Idlog)
{
return BadRequest();
}
_context.Entry(log).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!LogExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Logs
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
public async Task<ActionResult<Log>> PostLog(Log log)
{
_context.Logs.Add(log);
await _context.SaveChangesAsync();
return CreatedAtAction("GetLog", new { id = log.Idlog }, log);
}
// DELETE: api/Logs/5
[HttpDelete("{id}")]
public async Task<ActionResult<Log>> DeleteLog(int id)
{
var log = await _context.Logs.FindAsync(id);
if (log == null)
{
return NotFound();
}
_context.Logs.Remove(log);
await _context.SaveChangesAsync();
return log;
}
private bool LogExists(int id)
{
return _context.Logs.Any(e => e.Idlog == id);
}
}
} |
<!DOCTYPE html>
<html>
<head>
<title>Skevaron</title>
<script src="js/three.js"></script>
<!-- 性能检测器 -->
<script src="js/Stats.js"></script>
<!-- 创建菜单栏,控制场景中的各个参数调试场景 -->
<script src="../js/dat.gui.js"></script>
<style>
#canvas3d{
width: 100%;
height: 300px;
}
</style>
</head>
<body>
<canvas id="canvas">该浏览器不支持canvas,请升级或使用chrome浏览器</canvas>
<script>
var sun = new Image();
var moon = new Image();
var earth = new Image();
function init(){
sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
window.requestAnimationFrame(draw);
}
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
// clear canvas
ctx.clearRect(0,0,300,300);
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save();
ctx.translate(150,150);
// Earth
var time = new Date();
ctx.rotate( ((2 * Math.PI )/60) * time.getSeconds() + ((2 * Math.PI)/60000) * time.getMilliseconds() );
ctx.translate(105,0);
ctx.fillRect(0,-12,50,24); // Shadow
ctx.drawImage(earth,-12,-12);
// Moon
ctx.save();
ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );
ctx.translate(0,28.5);
ctx.drawImage(moon,-3.5,-3.5);
ctx.restore();
ctx.restore();
ctx.beginPath();
ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
ctx.stroke();
ctx.drawImage(sun,0,0,300,300);
window.requestAnimationFrame(draw);
}
init();
</script>
</body>
</html> |
package baekjoon_java.SilverIII;
import java.io.*;
import java.util.*;
public class boj_20920_영단어암기는괴로워 {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
StringBuilder sb = new StringBuilder();
List<Word> list = new ArrayList<>();
Map<String, Word> map = new HashMap<>();
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
for (int i = 0; i < n; i++) {
String cur = br.readLine();
if (cur.length() < m) continue;
if (map.containsKey(cur)) { // HashMap에 이미 존재한다면
map.get(cur).count(); // 카운팅만 해준다.
continue;
}
Word word = new Word(cur); // HashMap에 없다면 객체를 생성하고
list.add(word); // 리스트와
map.put(cur, word); // HashMap에 넣어준다
}
Collections.sort(list);
for (Word word : list) {
sb.append(word.name).append('\n');
}
System.out.print(sb);
}
static class Word implements Comparable<Word> {
String name;
int cnt;
public Word(String name) {
this.name = name;
cnt = 1;
}
public void count() {
this.cnt++;
}
@Override
public int compareTo(final Word o) {
if (this.cnt != o.cnt) { // 1. 자주 나오는 단어일수록 앞에 배치
return o.cnt - this.cnt;
}
if (this.name.length() != o.name.length()) { // 2. 해당 단어의 길이가 길수록 앞에 배치
return o.name.length() - this.name.length();
}
return this.name.compareTo(o.name); // 3. 알파벳 사전 순으로 앞에 있는 단어일수록 앞에 배치
}
}
} |
import { useDispatch, useSelector } from 'react-redux'
import { useTranslation } from 'react-i18next'
import React, { FC } from 'react'
import { Box, ButtonTypesConstants, TextView, VAButton, VAScrollView } from 'components'
import { NAMESPACE } from 'constants/namespaces'
import { getSupportedBiometricA11yLabel, getSupportedBiometricText, getSupportedBiometricTranslationTag, getTranslation } from 'utils/formattingUtils'
import { AuthState, setBiometricsPreference, setDisplayBiometricsPreferenceScreen } from 'store/slices'
import { RootState } from 'store'
import { testIdProps } from 'utils/accessibility'
import { useTheme } from 'utils/hooks'
export type SyncScreenProps = Record<string, unknown>
const BiometricsPreferenceScreen: FC<SyncScreenProps> = () => {
const theme = useTheme()
const dispatch = useDispatch()
const { t } = useTranslation(NAMESPACE.COMMON)
const { supportedBiometric } = useSelector<RootState, AuthState>((state) => state.auth)
const biometricsText = getSupportedBiometricText(supportedBiometric || '', t)
const biometricsA11yLabel = getSupportedBiometricA11yLabel(supportedBiometric || '', t)
const bodyText = getTranslation(`biometricsPreference.bodyText.${getSupportedBiometricTranslationTag(supportedBiometric || '')}`, t)
const onSkip = (): void => {
dispatch(setDisplayBiometricsPreferenceScreen(false))
}
const onUseBiometrics = (): void => {
dispatch(setBiometricsPreference(true))
dispatch(setDisplayBiometricsPreferenceScreen(false))
}
return (
<VAScrollView {...testIdProps('Biometrics-preference-page')}>
<Box mt={60} mb={theme.dimensions.contentMarginBottom} mx={theme.dimensions.gutter}>
<TextView variant="BitterBoldHeading" accessibilityRole="header" {...testIdProps(t('biometricsPreference.doYouWantToAllow.a11yLabel', { biometricsA11yLabel }))}>
{t('biometricsPreference.doYouWantToAllow', { biometricsText })}
</TextView>
<TextView paragraphSpacing={true} variant="MobileBody" mt={theme.dimensions.textAndButtonLargeMargin}>
{bodyText}
{t('biometricsPreference.youCanAlwaysChangeThis')}
</TextView>
<VAButton
onPress={onUseBiometrics}
label={t('biometricsPreference.useBiometric', { biometricsText })}
testID={t('biometricsPreference.useBiometric', { biometricsText })}
buttonType={ButtonTypesConstants.buttonPrimary}
a11yHint={t('biometricsPreference.useBiometricA11yHint')}
/>
<Box mt={theme.dimensions.standardMarginBetween}>
<VAButton
onPress={onSkip}
label={t('biometricsPreference.skip')}
testID={t('biometricsPreference.skip')}
buttonType={ButtonTypesConstants.buttonSecondary}
a11yHint={t('biometricsPreference.skipA11yHint')}
/>
</Box>
</Box>
</VAScrollView>
)
}
export default BiometricsPreferenceScreen |
import os
import base64
import streamlit as st
import pandas as pd
from nltk import tokenize
from bs4 import BeautifulSoup
from PyPDF2 import PdfReader
import requests
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet
from io import BytesIO
file_path =""
def extract_text_from_pdf(pdf_path):
with open(pdf_path, 'rb') as file:
# Buat objek PDFReader
pdf_reader = PdfReader(file)
# Inisialisasi string untuk menyimpan teks dari semua halaman
text = ""
# Iterasi melalui halaman-halaman PDF
for page_number in range(len(pdf_reader.pages)):
# Dapatkan objek halaman
page = pdf_reader.pages[page_number]
# Ekstrak teks dari halaman
text += page.extract_text()
return text
def get_sentences(text):
sentences = tokenize.sent_tokenize(text)
return sentences
def get_url(sentence):
base_url = 'https://www.google.com/search?q='
query = sentence
query = query.replace(' ', '+')
url = base_url + query
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
divs = soup.find_all('div', class_='yuRUbf')
urls = []
for div in divs:
a = div.find('a')
urls.append(a['href'])
if len(urls) == 0:
return None
elif "youtube" in urls[0]:
return None
else:
return urls[0]
def get_text(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
text = ' '.join(map(lambda p: p.text, soup.find_all('p')))
return text
def get_similarity(text1, text2):
text_list = [text1, text2]
cv = CountVectorizer()
count_matrix = cv.fit_transform(text_list)
similarity = cosine_similarity(count_matrix)[0][1]
return similarity
def get_similarity_list(text, url_list):
similarity_list = []
for url in url_list:
text2 = get_text(url)
similarity = get_similarity(text, text2)
similarity_list.append(similarity)
return similarity_list
def create_pdf(results_df, pdf_path):
doc = SimpleDocTemplate(pdf_path, pagesize=letter)
# Membuat list paragraf dari hasil deteksi
paragraphs = []
for index, row in results_df.iterrows():
similarity_percentage = row['Similarity'] * 100
paragraph_text = f"*Sentence {index + 1}:* {row['Sentence']}\n*URL:* {row['URL']}\n*Similarity:* {similarity_percentage:.0f}%\n\n"
paragraphs.append(Paragraph(paragraph_text, getSampleStyleSheet()['BodyText']))
# Membangun dokumen dengan list paragraf
doc.build(paragraphs)
def get_binary_file_downloader_html(buffer, file_name):
with open(file_name, 'wb') as f:
f.write(buffer.getbuffer())
href = f'<a href="data:application/octet-stream;base64,{base64.b64encode(buffer.getvalue()).decode()}" download="{file_name}">Download Results PDF</a>'
return href
st.set_page_config(page_title='Plagiarism Detection')
st.title('Plagiarism Detection')
st.write("""
### Enter the text to check for plagiarism
""")
uploaded_file = st.file_uploader("Upload PDF file", type=["pdf"])
if uploaded_file is not None:
# Simpan file di direktori yang sama dengan skrip
file_path = os.path.join(os.getcwd(), uploaded_file.name)
with open(file_path, "wb") as file:
file.write(uploaded_file.read())
st.success(f"File '{uploaded_file.name}' berhasil diunggah dan disimpan di {file_path}")
url = []
if st.button('Check for plagiarism'):
st.write(""
### Checking for plagiarism...
"")
text = extract_text_from_pdf(file_path)
sentences = get_sentences(text)
url = [get_url(sentence) for sentence in sentences]
if None in url:
st.write("""
### No plagiarism detected!
""")
st.stop()
similarity_list = get_similarity_list(text, url)
df = pd.DataFrame({'Sentence': sentences, 'URL': url, 'Similarity': similarity_list})
df = df.sort_values(by=['Similarity'], ascending=False)
df = df.reset_index(drop=True)
# Menampilkan hasil deteksi
st.table(df.style.format({'Similarity': '{:.0%}'}))
if file_path:
# Simpan hasil deteksi ke file PDF
buffer = BytesIO()
create_pdf(df, buffer)
st.markdown(get_binary_file_downloader_html(buffer, f"plagiarism_detection_{uploaded_file.name}"), unsafe_allow_html=True)
os.remove(file_path)
os.remove(os.path.join(f"plagiarism_detection_{uploaded_file.name}")) |
import ILeaderboard from '../interfaces/ILeaderboard';
import MatchesModel from '../database/models/MatchesModel';
import SortType from '../types/SortType';
import Leaderboard from '../middlewares/Leaderboard';
export default class LeaderboardService {
constructor(private _matchesModel = MatchesModel) {}
private static _sort(leaderboards: ILeaderboard[]): ILeaderboard[] {
return leaderboards.sort((a, b) =>
(b.totalVictories - a.totalVictories)
|| (b.totalPoints - a.totalPoints)
|| (b.goalsBalance - a.goalsBalance)
|| (b.goalsOwn - a.goalsOwn));
}
private static _getAllTeams(allMatches: MatchesModel[]): string[] {
return allMatches.map((match) => match.dataValues.teamHome.teamName)
.filter((value, index, self) => self.indexOf(value) === index);
}
private static _sortByTeam(
allMatches: MatchesModel[],
teams: string[],
sortType: string,
): MatchesModel[][] {
return teams.map((team) => allMatches
.filter((match) => match.dataValues[sortType].teamName === team));
}
private async _getAllMatches(sortType: SortType): Promise<MatchesModel[][]> {
const allMatches = await this._matchesModel.findAll({
where: { inProgress: false },
include: { all: true },
});
const allTeams = LeaderboardService._getAllTeams(allMatches);
const matchesSortedByTeam = LeaderboardService._sortByTeam(allMatches, allTeams, sortType);
return matchesSortedByTeam;
}
private static _concatLeaderboard(hTeam: ILeaderboard, aTeam: ILeaderboard): ILeaderboard {
const totalPoints = hTeam.totalPoints + aTeam.totalPoints;
const totalGames = hTeam.totalGames + aTeam.totalGames;
const efficiency = (((totalPoints / 3) / totalGames) * 100).toFixed(2);
return {
name: hTeam.name,
totalPoints,
totalGames,
totalVictories: hTeam.totalVictories + aTeam.totalVictories,
totalDraws: hTeam.totalDraws + aTeam.totalDraws,
totalLosses: hTeam.totalLosses + aTeam.totalLosses,
goalsFavor: hTeam.goalsFavor + aTeam.goalsFavor,
goalsOwn: hTeam.goalsOwn + aTeam.goalsOwn,
goalsBalance: hTeam.goalsBalance + aTeam.goalsBalance,
efficiency,
};
}
public async getMatches(sortType: SortType): Promise<ILeaderboard[]> {
const allMatches = await this._getAllMatches(sortType);
const matches = allMatches.map((team) => (
new Leaderboard(team, sortType).leaderboard
));
const orderedMatches = LeaderboardService._sort(matches);
return orderedMatches;
}
public async getGlobalMatches(): Promise<ILeaderboard[]> {
const homeLeaderboard = await this.getMatches('teamHome');
const awayLeaderboard = await this.getMatches('teamAway');
const globalLeaderboard = homeLeaderboard.map((hMatch) => {
const otherMatch = awayLeaderboard.filter((aMatch) => aMatch.name === hMatch.name)[0];
return LeaderboardService._concatLeaderboard(hMatch, otherMatch);
});
const sortedLeaderboard = LeaderboardService._sort(globalLeaderboard);
return sortedLeaderboard;
}
} |
package Instructions;
import Debugger.*;
import Expressions.Expression;
import java.util.ArrayList;
import java.util.HashMap;
import static java.lang.Character.isLowerCase;
/**
* This class is responsible for creating the 'skeleton' of a procedure, ie. holds the instructions to be
* invoked, the number of variables and whether any errors/exceptions will be triggered when declaring the procedure.
* On execute(), it will check whether the current scope contains a procedure of the same name, if so, throws an
* exception, otherwise, it is added to the hash map of procedures of the current scope (ie. block). If there is a
* procedure of the same name in a higher scope, it will be overshadowed by the new one.
*/
public class ProcedureDeclaration extends Instruction{
private final String DOUBLE_DECLARATION_PROCEDURE_EXCEPTION = "[Exception] This procedure has already been declared in this scope!";
private final String DOUBLE_PARAM_EXCEPTION = "[Exception] This parameter has already been declared in this procedure!";
private final String INVALID_NAME_EXCEPTION = "[Exception] This procedure cannot be named this way!";
private String name;
private BlockContext contextDeclared = null;
private boolean[] parameterPresent = new boolean[26];
private ArrayList<Character> parameters = new ArrayList<>();
private ArrayList<Instruction> instructions = new ArrayList<>();
private boolean doubleParameterDeclaration = false;
private boolean invalidName = false;
private ProcedureDeclaration(Builder builder) {
int i = 0;
while (i < builder.name.length() && isLowerCase(builder.name.charAt(i))) {
i++;
}
if (i != builder.name.length()) {
invalidName = true;
}
this.name = builder.name;
this.instructions.addAll(builder.variableDeclarations);
this.instructions.addAll(builder.instructions);
this.instructions.add(new EndBlockInstruction());
for (char parameter : builder.parameters) {
if (!parameterPresent[parameter - 'a']) {
parameterPresent[parameter - 'a'] = true;
parameters.add(parameter);
} else {
doubleParameterDeclaration = true;
parameters.add(parameter);
}
}
}
public BlockContext getContextDeclared() {
return this.contextDeclared;
}
@Override
public void execute(Debugger debugger) throws Exception {
if (doubleParameterDeclaration) {
throw new Exception(DOUBLE_PARAM_EXCEPTION);
}
if (invalidName) {
throw new Exception(INVALID_NAME_EXCEPTION);
}
this.contextDeclared = debugger.getTopContext();
ProcedureDeclaration procedure = debugger.getTopContext().getProcedure(name);
if (procedure == null) {
debugger.getTopContext().addProcedure(this);
} else if (procedure.getContextDeclared() != debugger.getTopContext()) {
debugger.getTopContext().removeProcedure(procedure);
debugger.getTopContext().addProcedure(this);
} else {
throw new Exception(DOUBLE_DECLARATION_PROCEDURE_EXCEPTION);
}
}
public String getName() {
return name;
}
public ArrayList<Character> getParameters() {
return this.parameters;
}
public ArrayList<Instruction> getInstructions() {
return this.instructions;
}
@Override
public void printName() {
System.out.println("Declare procedure called '" + name + "' with parameters " + parameters.toString() + ".");
}
public static class Builder {
private String name;
private final ArrayList<VariableDeclaration> variableDeclarations = new ArrayList<>();
private final ArrayList<Instruction> instructions = new ArrayList<>();
private ArrayList<Character> parameters = new ArrayList<>();
public Builder(String name, char... params) {
this.name = name;
for (char parameter : params) {
this.parameters.add(parameter);
}
}
public Builder condition(IfElseStatement ifElseStatement) {
this.instructions.add(ifElseStatement);
return this;
}
public Builder declareProcedure(ProcedureDeclaration procedure) {
instructions.add(procedure);
return this;
}
public Builder declareVariable(char name, Expression expression) {
variableDeclarations.add(new VariableDeclaration(name, expression));
return this;
}
public Builder forLoop(ForLoop forLoop) {
instructions.add(forLoop);
return this;
}
public Builder newBlock(Block block) {
instructions.add(block);
return this;
}
public Builder print(Expression expression) {
instructions.add(new Print(expression));
return this;
}
public Builder invoke(String name, Expression... parameters) {
instructions.add(new ProcedureInvoke(name, parameters));
return this;
}
public Builder assign(char name, Expression expression) {
instructions.add(new AssignVariableValue(name, expression));
return this;
}
public ProcedureDeclaration build() {
return new ProcedureDeclaration(this);
}
}
} |
/**
* <copyright>
* Copyright (c) 2010-2014 Henshin developers. All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* </copyright>
*/
package org.eclipse.emf.henshin.tests.basic;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.henshin.interpreter.Engine;
import org.eclipse.emf.henshin.interpreter.Match;
import org.eclipse.emf.henshin.tests.framework.HenshinTest;
import org.eclipse.emf.henshin.tests.framework.Matches;
import org.eclipse.emf.henshin.tests.framework.Rules;
import org.eclipse.emf.henshin.tests.framework.Tools;
import org.junit.Before;
import org.junit.Test;
/**
* Tests several engine options.
*
* @author Felix Rieger
* @author Stefan Jurack
* @author Christian Krause
*/
public class EngineOptionsTest extends HenshinTest {
@Before
public void setUp() throws Exception {
init("basic/rules/engineOptionsTests.henshin");
setEGraphPath("basic/models/engineOptionsTestsModels/", "testmodel");
}
@Test
public void testNonInjective1() {
/**
* graph:
*
* n1
* /
* n2
*/
loadEGraph("nonInjective1");
Collection<EObject> objGroup = new ArrayList<EObject>();
objGroup.add(Tools.getFirstOCLResult("self.nodename='n1'", htEGraph));
objGroup.add(Tools.getFirstOCLResult("self.nodename='n2'", htEGraph));
objGroup.add(Tools.getFirstOCLResult("self.nodename='n2'", htEGraph));
loadRule("non-injectiveMatching");
// Rule should have no match, as we're looking for a Node with
// two child nodes, but the graph contains just a Node with one child node.
Rules.assertRuleHasNoMatch(htRule, htEGraph, null, htEngine);
htEngine.getOptions().put(Engine.OPTION_INJECTIVE_MATCHING, false);
loadRule("non-injectiveMatching");
// Rule should have exactly 1 match.
Rules.assertRuleHasNMatches(htRule, htEGraph, null, htEngine, 1);
// This match should contain n1, n2, n2
Matches.assertOnlyGroupIsMatched(htRule, htEGraph, null, htEngine, objGroup);
}
@Test
public void testNonInjective2() {
/**
* graph:
*
* n1
* / \
* n2 n3
*/
loadEGraph("nonInjective2");
Collection<EObject> objGroup = new ArrayList<EObject>();
objGroup.add(Tools.getFirstOCLResult("self.nodename='n1'", htEGraph));
objGroup.add(Tools.getFirstOCLResult("self.nodename='n2'", htEGraph));
objGroup.add(Tools.getFirstOCLResult("self.nodename='n3'", htEGraph));
loadRule("non-injectiveMatching");
// assert Rule is correct for injective matching
// expected matches: n1 <-> (n2, n3) ; n1 <-> (n3, n2)
Rules.assertRuleHasNMatches(htRule, htEGraph, null, htEngine, 2);
Matches.assertOnlyGroupIsMatched(htRule, htEGraph, null, htEngine, objGroup);
// turn off injective matching and try again
Collection<EObject> ninjObjGroup1 = new ArrayList<EObject>();
ninjObjGroup1.add(Tools.getFirstOCLResult("self.nodename='n1'", htEGraph));
ninjObjGroup1.add(Tools.getFirstOCLResult("self.nodename='n2'", htEGraph));
ninjObjGroup1.add(Tools.getFirstOCLResult("self.nodename='n2'", htEGraph));
Collection<EObject> ninjObjGroup2 = new ArrayList<EObject>();
ninjObjGroup2.add(Tools.getFirstOCLResult("self.nodename='n1'", htEGraph));
ninjObjGroup2.add(Tools.getFirstOCLResult("self.nodename='n3'", htEGraph));
ninjObjGroup2.add(Tools.getFirstOCLResult("self.nodename='n3'", htEGraph));
htEngine.getOptions().put(Engine.OPTION_INJECTIVE_MATCHING, Boolean.FALSE);
loadRule("non-injectiveMatching");
// expected matches: n1 <-> (n2, n3) ; n1 <-> (n3, n2) ; n1 <-> (n2, n2) ; n1 <-> (n3, n3)
Rules.assertRuleHasNMatches(htRule, htEGraph, null, htEngine, 4);
for (Match ma : htEngine.findMatches(htRule, htEGraph, null)) {
if (ma.getNodeTargets().contains(Tools.getFirstOCLResult("self.nodename='n2'", htEGraph))) {
if (ma.getNodeTargets().contains(Tools.getFirstOCLResult("self.nodename='n3'", htEGraph))) {
Matches.assertMatchIsGroup(ma, objGroup);
} else {
Matches.assertMatchIsGroup(ma, ninjObjGroup1);
}
} else {
Matches.assertMatchIsGroup(ma, ninjObjGroup2);
}
}
}
} |
package com.duallab.iccprofileservice;
import com.duallab.iccprofileservice.dto.ICCProfileDTO;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.runners.Parameterized;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.test.context.TestContextManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.context.ContextConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
/**
* @version 1.00 11 Jan 2014
* @author Toldykin Vyacheslav
*/
@RunWith(Parameterized.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring/mvc-dispatcher-servlet.xml",
"classpath:spring/root-context.xml", "classpath:spring/data.xml"})
public class ParametrizedTest {
private static final String RESOURCES_DIR = ".\\src\\test\\resources\\";
private static final String PROFILES_ICC_SUBDIR = "iccprofiles\\";
private static final String PROFILES_JSON_SUBDIR = "json\\";
private MockMvc mockMvc;
private File profileFile_icc;
private File profileFile_json;
private String profileName;
private TestContextManager testContextManager;
private ICCProfileDTO iccProfileDTO;
@Autowired
protected WebApplicationContext wac;
public ParametrizedTest(String profileName) {
this.profileName = profileName;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
List parameters;
File[] profileFiles;
parameters = new ArrayList();
profileFiles = (new File(RESOURCES_DIR + PROFILES_ICC_SUBDIR)).listFiles();
for(File file : profileFiles) {
parameters.add(new Object[] {FilenameUtils.removeExtension(file.getName())});
}
return parameters;
}
@Before
public void setup() throws Exception {
initializeTestContext();
initializeResourceFiles();
initializeICCProfileObject();
}
@Test
public void uploadWithJsonResponseTest() throws Exception {
MockMultipartFile multipartFile;
multipartFile = new MockMultipartFile("profile", profileName + ".icc",
null, (new FileInputStream(profileFile_icc)));
mockMvc.perform(fileUpload("/iccprofiles").file(multipartFile)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$id").value(iccProfileDTO.getId()))
.andExpect(jsonPath("$type").value(iccProfileDTO.getType()))
.andExpect(jsonPath("$numComponents").value(iccProfileDTO.getNumComponents()));
}
@Test
public void uploadWithXmlResponseTest() throws Exception {
MockMultipartFile multipartFile;
multipartFile = new MockMultipartFile("profile", profileName + ".icc",
null, (new FileInputStream(profileFile_icc)));
mockMvc.perform(fileUpload("/iccprofiles").file(multipartFile)
.accept(MediaType.APPLICATION_XML))
.andExpect(status().isCreated())
.andExpect(xpath("/iccprofile/@id").string(iccProfileDTO.getId()))
.andExpect(xpath("/iccprofile/@type").string(iccProfileDTO.getType()))
.andExpect(xpath("/iccprofile/@numComponents").string(iccProfileDTO.getNumComponents().toString()))
.andExpect(xpath("/iccprofile/@description").string(iccProfileDTO.getDescription()));
}
@Test
public void getSpecificProfileTest() throws Exception {
mockMvc.perform(get("/iccprofiles/" + iccProfileDTO.getId() + "/")
.accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(xpath("/iccprofile/@id").string(iccProfileDTO.getId()))
.andExpect(xpath("/iccprofile/@type").string(iccProfileDTO.getType()))
.andExpect(xpath("/iccprofile/@numComponents").string(iccProfileDTO.getNumComponents().toString()))
.andExpect(xpath("/iccprofile/@description").string(iccProfileDTO.getDescription()));
}
private void initializeResourceFiles() {
profileFile_icc = new File(RESOURCES_DIR + PROFILES_ICC_SUBDIR + profileName + ".icc");
profileFile_json = new File(RESOURCES_DIR + PROFILES_JSON_SUBDIR + profileName + ".json");
}
private void initializeTestContext() throws Exception {
this.testContextManager = new TestContextManager(getClass());
this.testContextManager.prepareTestInstance(this);
this.mockMvc = webAppContextSetup(this.wac).build();
}
private void initializeICCProfileObject() throws IOException {
iccProfileDTO = (new ObjectMapper()).readValue(profileFile_json, ICCProfileDTO.class);
}
} |
import { IsNotEmpty, IsOptional, IsString } from "class-validator"
export class PutUserDTO {
@IsOptional()
@IsNotEmpty({ message: 'Não foi informado um login.'})
@IsString({ message: 'Valor invalido para Login!' })
login: string
@IsOptional()
@IsNotEmpty({ message: 'Não foi informado um password.'})
@IsString({ message: 'Valor invalido para Password!' })
password: string
@IsOptional()
@IsNotEmpty({ message: 'Não foi informado um E-mail.'})
@IsString({ message: 'Valor invalido para E-mail!' })
email: string
} |
import { Link, useNavigate } from 'react-router-dom'
import useAuth from '../hooks/useAuth'
import { useState } from 'react'
import Alerta from '../components/Alerta'
import clienteAxios from '../config/axios'
const Login = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [alerta, setAlerta] = useState({})
const navigate = useNavigate()
const { setAuth } = useAuth()
const handleSubmit = async (e) => {
e.preventDefault()
if ([email, password].includes('')) {
setAlerta({
msg: 'Por favor complete todos los campos',
error: true
});
return
}
try {
const { data } = await clienteAxios.post('/veterinarios/login', { email, password })
localStorage.setItem('token', data.token)
setAuth(data)
navigate('/admin') // cuando inicia sesion se redirecciona
} catch (error) {
setAlerta({
msg: error.response.data.msg,
error: true
})
}
}
const { msg } = alerta
return (
<>
<div>
<h1 className="text-indigo-600 font-black text-6xl">Inicia sesión y administra tus pacientes</h1>
</div>
<div className='mt-20 md:mt-5 shadow-lg px-5 py-10 rounded-xl bg-white'>
{msg && <Alerta
alerta={alerta}
/>}
<form
onSubmit={handleSubmit}
>
<div className="my-5">
<label
className="uppercase text-gray-600 block text-xl font-bold rounded-xl"
>
Email
</label>
<input
type="email"
placeholder="Email de registro"
className="border w-full p-3 mt-3 bg-gray-50"
value={email}
onChange={e => setEmail(e.target.value)}
/>
</div>
<div className="my-5">
<label
className="uppercase text-gray-600 block text-xl font-bold rounded-xl"
>
Contraseña
</label>
<input
type="password"
placeholder="Ingrese contraseña"
className="border w-full p-3 mt-3 bg-gray-50"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</div>
<input
type="submit"
value="Iniciar Sesión"
className="bg-indigo-700 w-full py-3 px-10 rounded-xl text-white uppercase font-bold mt-5 hover:cursor-pointer hover:bg-indigo-800 md:w-auto"
/>
</form>
<nav className='mt-10 lg:flex lg:justify-between'>
<Link
to="/registrar"
className='block text-center my-5 text-gray-500'
>
No tienes una cuenta? Regístrate!
</Link>
<Link
to="/olvide-password"
className='block text-center my-5 text-gray-500'
>
Olvidaste tu contraseña?
</Link>
</nav>
</div>
</>
)
}
export default Login |
# clone helper - functions to aid in cloning and copying ADO repos
# Get a Project Id
function Get-ProjectId {
Param (
[Parameter(Mandatory = $true)]
[string]$projectNameSupplied,
[Parameter(Mandatory = $true)]
[string]$organizationToGet
)
$projectId = ""
# Azure DevOps REST API endpoint for listing repositories
$uri = "https://dev.azure.com/$organizationToGet/_apis/projects?api-version=7.0"
$escapedUrl = [uri]::EscapeUriString($uri)
if (Test-Endpoint $escapedUrl) {
# Make the REST API call to list repositories
$response = Invoke-RestMethod -Uri $escapedUrl -Headers @{
Authorization = ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($pat)")))
}
$projectList = $response
# Output the list of Ids
if ($response.value.Count -gt 0) {
Write-Host "$($response.value.Count) Projects found in $($organizationToGet):" -ForegroundColor Yellow
$projectList.value | ForEach-Object {
if ($_.name -eq $projectNameSupplied) {
$projectId = $_.id
}
}
if ([string]::IsNullOrEmpty($projectId)) {
Write-Host "No Id found for $($projectNameSupplied)" -ForegroundColor Red
Write-Host
return -1
}
else {
Write-Host "Project Id found!" -ForegroundColor Green
return $projectId
}
}
else {
else {
Write-Host "No Projects found in $($organizationToGet)." -ForegroundColor Red
return -1
}
}
}
else {
Write-Host "Cannot reach endpoint $($escapedUrl)" - -ForegroundColor Red
return -1
}
}
# Get Repo Id
function Get-RepoId {
Param (
[Parameter(Mandatory = $true)]
[string]$projectNameSupplied,
[Parameter(Mandatory = $true)]
[string]$organizationToGet,
[Parameter(Mandatory = $true)]
[string]$repoToGet
)
$repoId = ""
# Azure DevOps REST API endpoint for listing repositories
$uri = "https://dev.azure.com/$organizationToGet/_apis/git/repositories?api-version=7.0"
if (-not [string]::IsNullOrEmpty($projectNameSupplied)) {
$uri = "https://dev.azure.com/$organizationToGet/$projectNameSupplied/_apis/git/repositories?api-version=7.0"
}
$escapedUrl = [uri]::EscapeUriString($uri)
# Write-Host "Endpoint to get repo Ids is $($escapedUrl)" -ForegroundColor Yellow
if (Test-Endpoint -suppliedUrl $escapedUrl) {
# Make the REST API call to list repositories
$response = Invoke-RestMethod -Uri $escapedUrl -Headers @{
Authorization = ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($pat)")))
}
# Output the list of repositories
if ($response.value.Count -gt 0) {
# Write-Host "$($response.value.Count) Repositories found in $($organizationToGet) - $($projectNameSupplied):"
$response.value | ForEach-Object {
# Write-Host $_.name
if ($_.name -eq $repoToGet) {
$repoId = $_.id
}
}
Write-Host
if ([string]::IsNullOrEmpty($repoId)) {
Write-Host "No Repository Id found for $($repoToGet) in $($projectNameSupplied)" -ForegroundColor Red
return -1
}
else {
Write-Host "Repository Id found!" -ForegroundColor Green
return $repoId
}
}
else {
Write-Host "No repositories found in $organization $($project)." -ForegroundColor Red
return -1
}
}
else {
Write-Host "Failed to get Repository Id Endpoint."
return -1
}
}
# Test Created Endpoints
function Test-Endpoint {
param(
# Parameter help description
[Parameter(Mandatory)]
[string]$suppliedUrl
)
$valid = $false
$times = 0
# $escapedUrl = [uri]::EscapeUriString($suppliedUrl)
# Write-Host "Endpoint to test: $($suppliedUrl)"
while (($false -eq $valid) -and ($times -lt 5)) {
try {
$checkedUrl = Invoke-WebRequest -Uri $suppliedUrl -Method Get -UseBasicParsing
}
catch {
Write-Host "Endpoint not available"
}
# Write-Host $checkedUrl.StatusCode
if (($checkedUrl.StatusCode -gt 199) -and ($checkedUrl.StatusCode -lt 300)) {
# Write-Host "We got a good response $($checked.StatusDescription)"
$valid = $true
}
else {
Write-Host "Failed to get Endpoint. Trying again." -ForegroundColor Yellow
Start-Sleep -Seconds 2
}
$times ++
}
if ($times -gt 1) {
Write-Host "No response after $($times) tries. Connection or site may be down. Check supplied values" -ForegroundColor Red
}
return $valid
}
# Get Values for Repo from Json Object
function Test-RepoValues([object]$repoToCheck) {
if ([string]::IsNullOrEmpty($repoToCheck.sourceOrganization)) {
Write-Host "Values for Source Organization MUST be supplied" -ForegroundColor Red
return -1
}
if ([string]::IsNullOrEmpty($repoToCheck.sourceProject)) {
Write-Host "Values for Source Project MUST be supplied" -ForegroundColor Red
return -1
}
if ([string]::IsNullOrEmpty($repoToCheck.sourceRepo)) {
Write-Host "Values for Source Repository MUST be supplied" -ForegroundColor Red
return -1
}
if ([string]::IsNullOrEmpty($repoToCheck.destinationOrganization)) {
$repoToCheck.destinationOrganization = $repoToCheck.sourceOrganization
Write-Host "Values for Destination Organization not supplied"
Write-Host "Source Organization value, $($repoToCheck.sourceOrganization), will be used." -ForegroundColor Yellow
}
if ([string]::IsNullOrEmpty($repoToCheck.destinationProject)) {
if ($repoToCheck.sourceOrganization -eq $repoToCheck.destinationOrganization) {
$repoToCheck.destinationProject = $repoToCheck.sourceProject
Write-Host "Values for Destination Project not supplied"
Write-Host "Source Organization value, $($repoToCheck.sourceProject), will be used." -ForegroundColor Yellow
}
else {
Write-Host "No value for the destination project has been supplied"
Write-Host "Source and Destination Organizations do not match..."
Write-Host "I do not know where to put the repo."
return -1
}
}
if ([string]::IsNullOrEmpty($repoToCheck.destinationRepo)) {
Write-Host "Values for intended destination (aka new repository name) MUST be supplied"
return -1
}
if (($repoToCheck.sourceOrganization -eq $repoToCheck.destinationOrganization) -and ($repoToCheck.sourceProject -eq $repoToCheck.destinationProject) -and ($repoToCheck.sourceRepo -eq $repoToCheck.destinationRepo)) {
Write-Host "Source and Destination values are the same. You are trying to clone a repository into the same repository." -ForegroundColor Red
return -1
}
return $repoToCheck
}
# Package Json Payload
function Convert-ToJsonPayload {
Param (
[Parameter(Mandatory = $true)]
[string]$destinationRepo,
[Parameter(Mandatory = $true)]
[string]$destinationProjectId,
[Parameter(Mandatory = $true)]
[string]$sourceRepo,
[Parameter(Mandatory = $true)]
[string]$sourceRepoId,
[Parameter(Mandatory = $true)]
[string]$sourceProjectId
)
$destinationId = [PSCustomObject]@{
id = $destinationProjectId
}
$sourceProject = [PSCustomObject]@{
id = $sourceProjectId
}
$parentRepository = [PSCustomObject]@{
name = $sourceRepo
id = $sourceRepoId
project = $sourceProject
}
$complete = [PSCustomObject]@{
name = $destinationRepo
project = $destinationId
parentRepository = $parentRepository
}
$converted = $complete | ConvertTo-Json
return $converted
} |
import {
describe, expect, it, vi,
} from 'vitest';
import { ApiError } from './api-error';
import { ApiService, HttpMethod } from './api-service';
const mockGet = vi.fn();
const mockPost = vi.fn();
const mockPut = vi.fn();
const mockPatch = vi.fn();
const mockDelete = vi.fn();
const mockDictionary = {
get: mockGet,
post: mockPost,
put: mockPut,
patch: mockPatch,
delete: mockDelete,
};
vi.mock('axios', () => ({
default: {
create: () => ({
get: () => mockGet(),
post: () => mockPost(),
put: () => mockPut(),
patch: () => mockPatch(),
delete: () => mockDelete(),
}),
},
}));
describe('ApiService', () => {
const sharedExamples = (method: HttpMethod) => {
const url = 'domain.com/path/to/resource';
const networkError = {
response: {
data: {
code: 1001,
message: 'error message',
},
},
};
const setupTest = () => ApiService[method](url);
it(`calls the '${method}' method of axios`, async () => {
await setupTest();
expect(mockDictionary[method]).toHaveBeenCalledTimes(1);
});
it('creates an ApiError when a network error is raised', async () => {
mockDictionary[method].mockRejectedValueOnce(networkError);
try {
await setupTest();
} catch (error) {
expect(error).toBeInstanceOf(ApiError);
return;
}
throw new Error('Error was not caught');
});
};
Object.values(HttpMethod).forEach(sharedExamples);
}); |
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import { Link } from "react-router-dom";
import { v4 as uuid } from "uuid";
import { axiosclient } from "../../../api";
import { AdminLayout } from "../../../layouts";
const ContructionSites = () => {
const [contructionsites, setContructionSites] = useState([]);
useEffect(() => {
axiosclient
.get("/api/contructionSites")
.then((res) => {
setContructionSites(res.data);
console.log(contructionsites);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<AdminLayout>
<div className="dark:bg-gray-900 h-full p-10 overflow-x-auto">
<div className="flex justify-end gap-2">
<Link to="/constructionsite/new">
<button
type="button"
class="h-10 focus:outline-none text-white bg-[#ffb300] hover:bg-orange-600 font-medium rounded text-sm px-5 py-2.5"
>
Add a Contruction Site
</button>
</Link>
</div>
<h2 class="text-2xl text-gray-900 my-4 font-extrabold font-primary dark:text-white">
ContructionSites
</h2>
<div class="overflow-x-auto relative shadow-md sm:rounded-lg">
<table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
<thead class="text-xs text-white uppercase bg-[#ffb300] dark:bg-gray-700 dark:text-gray-400">
<tr>
<th scope="col" class="py-3 px-6">
ID
</th>
<th scope="col" class="py-3 px-6">
Site Name
</th>
<th scope="col" class="py-3 px-6">
Site Address
</th>
<th scope="col" class="py-3 px-6">
Site Budget
</th>
<th scope="col" class="py-3 px-6">
Site Manager
</th>
</tr>
</thead>
<tbody>
{contructionsites.map((contructionSite) => (
<tr
key={uuid()}
class="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
>
<th
scope="row"
class="py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white"
>
{contructionSite._id}
</th>
<td class="py-4 px-6 cursor-pointer">
{contructionSite.siteName}
</td>
<td class="py-4 px-6 cursor-pointer">
{contructionSite.siteAddress}
</td>
<td class="py-4 px-6 cursor-pointer">
{contructionSite.siteBudjet}
</td>
<td class="py-4 px-6 cursor-pointer">
{contructionSite.siteManager}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</AdminLayout>
);
};
export default ContructionSites; |
package dao;
import modele.Equipe;
import modele.Poule;
import modele.Tournoi;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class DaoPoule implements Dao<Poule, Object> {
private Connexion connexion;
private DaoTournoi daotournoi;
public DaoPoule(Connexion connexion) {
this.connexion = connexion;
this.daotournoi = new DaoTournoi(connexion);
}
/**
* Crée la table Poule
*
* @param connexion
* @throws SQLException
*/
public static void createTable(Connexion connexion) throws SQLException {
String createTableSql = "CREATE TABLE Poule ("
+ "Annee INT,"
+ "Nom_Tournoi VARCHAR(50),"
+ "Libelle VARCHAR(1),"
+ "PRIMARY KEY(Annee, Nom_Tournoi, Libelle),"
+ "FOREIGN KEY(Annee, Nom_Tournoi) REFERENCES Tournoi(Annee, Nom_Tournoi))";
try (Statement createTable = connexion.getConnection().createStatement()) {
createTable.execute(createTableSql);
System.out.println("Table 'Poule' créée avec succès");
}
}
/**
* Supprime la table Poule
*
* @param connexion
* @return
* @throws SQLException
*/
public static boolean dropTable(Connexion connexion) throws SQLException {
try (Statement deleteTable = connexion.getConnection().createStatement()) {
System.out.println("Table 'Poule' supprimée avec succès");
return deleteTable.execute("drop table Poule");
}
}
/**
* Renvoie toutes les poules existantes
*/
@Override
public List<Poule> getAll() throws Exception {
try (Statement getAll = connexion.getConnection().createStatement()) {
ResultSet resultat = getAll.executeQuery("SELECT * FROM Poule");
List<Poule> sortie = new ArrayList<>();
while (resultat.next()) {
Poule poule = new Poule(
daotournoi.getById(resultat.getInt("Annee"), resultat.getString("Nom_tournoi")).get(),
resultat.getString("Libelle").charAt(0));
sortie.add(poule);
}
return sortie;
}
}
/**
* Renvoie une poule précise
* Les paramètres sont placés dans cet ordre : Annee (INTEGER), Nom_tournoi (STRING), Libelle_poule (STRING)
*/
@Override
public Optional<Poule> getById(Object... value) throws Exception {
try (PreparedStatement getById = connexion.getConnection().prepareStatement("SELECT * FROM Poule WHERE Annee = ? AND Nom_Tournoi = ? AND Libelle = ?")) {
getById.setInt(1, (Integer) value[0]);
getById.setString(2, (String) value[1]);
getById.setString(3, (String) value[2]);
ResultSet resultat = getById.executeQuery();
Poule poule = null;
if (resultat.next()) {
poule = new Poule(
daotournoi.getById(resultat.getInt("Annee"), resultat.getString("Nom_tournoi")).get(),
resultat.getString("Libelle").charAt(0));
}
return Optional.ofNullable(poule);
}
}
/**
* Ajoute une poule à la table poule à partir d'un objet poule
*/
@Override
public boolean add(Poule value) throws Exception {
try (PreparedStatement add = connexion.getConnection().prepareStatement(
"INSERT INTO Poule(Annee,Nom_tournoi,Libelle) values (?,?,?)")) {
add.setInt(1, value.getTournoi().getSaison().getAnnee());
add.setString(2, value.getTournoi().getNom());
add.setString(3, value.getLibelle().toString());
return add.execute();
}
}
/**
* ne pas utiliser
*/
@Override
public boolean update(Poule value) throws Exception {
return false;
}
/**
* Supprime une poule
* Les paramètres sont placés dans cet ordre : Annee (INTEGER), Nom_tournoi (STRING), Libelle (STRING)
*/
@Override
public boolean delete(Object... value) throws Exception {
try (PreparedStatement delete = connexion.getConnection().prepareStatement(
"DELETE FROM Poule where Annee = ? AND Nom_tournoi = ? AND Libelle = ?")) {
delete.setInt(1, (Integer) value[0]);
delete.setString(2, (String) value[1]);
Character c = (Character) value[2];
String libelle = c.toString();
delete.setString(3, libelle);
List<Equipe> equipes = FactoryDAO.getDaoAppartenance(connexion).getEquipeByPoule(value[1], value[0], value[2]);
for (Equipe e : equipes) {
FactoryDAO.getDaoAppartenance(connexion).delete(
e.getNom(),
value[0],
value[1],
value[2]
);
}
return delete.execute();
}
}
public List<Poule> getPouleByTournoi(Tournoi tournoi) throws Exception {
try (PreparedStatement getPouleByTournoi = connexion.getConnection().prepareStatement(""
+ "SELECT * "
+ "FROM Poule "
+ "WHERE Annee = ? "
+ "AND Nom_tournoi = ?")) {
getPouleByTournoi.setInt(1, tournoi.getSaison().getAnnee());
getPouleByTournoi.setString(2, tournoi.getNom());
ResultSet resultat = getPouleByTournoi.executeQuery();
List<Poule> sortie = new ArrayList<>();
while (resultat.next()) {
Poule poule = new Poule(
daotournoi.getById(resultat.getInt("Annee"), resultat.getString("Nom_tournoi")).get(),
resultat.getString("Libelle").charAt(0));
sortie.add(poule);
}
return sortie;
}
}
@Override
public String visualizeTable() throws Exception {
String s = "_______________Poule_______________________" + "\n";
List<Poule> l = this.getAll();
for (Poule a : l) {
s += a.toString() + "\n";
}
s += "\n\n\n";
return s;
}
} |
import 'package:flutter/material.dart';
import 'package:swifty_companion/models/user.dart';
import 'package:timeago/timeago.dart' as timeago;
class Projects extends StatelessWidget {
Projects({super.key, required this.projects, required this.grade});
final List<Project> projects;
final String grade;
final ScrollController _controller = ScrollController();
@override
Widget build(BuildContext context) {
return projects.isEmpty
? const SizedBox(
height: 150,
child: Center(child: Text('No Projects data available')))
: Container(
color: Theme.of(context).colorScheme.primary,
height: 250,
child: ListView.builder(
itemCount: projects.length,
controller: _controller,
itemBuilder: (context, index) {
if (projects[index].cursusIds == 21) {
return Card(
color: Theme.of(context).colorScheme.background,
child: ListTile(
title: Text(projects[index].name),
subtitle: timeAgo(projects[index].markedAt),
trailing: projDetail(index),
),
);
} else if (projects[index].cursusIds != 21 &&
grade == "Novice") {
return Card(
color: Theme.of(context).colorScheme.background,
child: ListTile(
title: Text(projects[index].name),
trailing: projDetail(index),
),
);
}
return null;
},
));
}
Text timeAgo(String markedAt) {
if (markedAt != "Unavailable") {
return Text(timeago.format(DateTime.parse(markedAt)));
} else {
return const Text('');
}
}
Text projDetail(int index) {
if (projects[index].status == "finished") {
return Text(
'${projects[index].finalMark.toString()}%',
style: TextStyle(
color: projects[index].validated
? Colors.green.shade800
: Colors.red.shade800),
);
} else {
return Text(
"In progress",
style: TextStyle(color: Colors.green.shade800),
);
}
}
} |
from sly import Parser
from lexer import SciDataVizLexer
import BuiltInFunc
from error import Error
from view_table import TableView
import numpy as np
import numpy.core._exceptions as np_exceptions
import pandas as pd
import os
import sys
import re
class SciDataVizParser(Parser):
# Get the token list from the lexer (required)
precedence = (
('nonassoc', ASSIGN),
('right', UMINUS, UPLUS),
('left', AND, OR),
('left', EQ, NE, GT, LT, GE, LE),
('left', PLUS, MINUS),
('left', TIMES, DIVIDE, MOD, FLRDIV, POWER, MATMUL),
('right', NOT),
('left', PIPE),
('left', LSQB, RSQB),
)
debugfile = 'debug.txt'
tokens = SciDataVizLexer.tokens
def __init__(self, terminal, notebook, workspace) -> None:
self.values = {"i":complex(0,1), "j": complex(0,1), "e":np.e, "pi":np.pi, "nan":np.nan, "inf":np.inf, "True":True, "False":False}
self.terminal = terminal
self.notebook = notebook
self.workspace = workspace
self.workspaceMap = {}
def error(self, token):
'''
Default error handling function. This may be subclassed.
'''
err = Error("SyntaxError")
if isinstance(token, Error):
err = token
elif token:
lineno = getattr(token, 'lineno', 0)
if lineno:
err.message = f"line {lineno} at '{token.value}'"
else:
err.message = f"'{token.value}'"
else:
err.message = 'at EOF'
self.terminal.insert("end",f'{err}')
self.terminal.tag_add("error", "end-1l", "end-1c")
self.terminal.insert("end", "\n")
# Grammar rules and actions
@_('statements')
def s(self, p):
return p.statements
@_('statement')
def statements(self, p):
return p.statement
@_('statement ";" statements')
def statements(self, p):
if isinstance(p.statement, Error):
return p.statement
return p.statements
@_('empty')
def statements(self, p):
return None
@_('value')
def statement(self, p):
return p.value
@_('')
def empty(self, p):
pass
@_('value PLUS term')
def value(self, p):
if isinstance(p.value, Error):
return p.value
if isinstance(p.term, Error):
return p.term
try:
return np.add(p.value, p.term)
except (ValueError,np_exceptions.UFuncTypeError, TypeError) as e:
if isinstance(e,ValueError):
return Error("ValueError", "Matrices are not aligned")
elif isinstance(e,TypeError):
return Error("TypeError", f"You can't add a {self.dataTypes[type(p.value)]} and a {self.dataTypes[type(p.term)]}")
elif isinstance(e,np_exceptions.UFuncTypeError):
return Error("TypeError", "You can only do element wise addition between two arrays of the same data type")
else:
return Error("TypeError", "You can only do element wise addition between two arrays of the same data type")
@_('value MINUS term')
def value(self, p):
if isinstance(p.value, Error):
return p.value
if isinstance(p.term, Error):
return p.term
try:
return np.subtract(p.value, p.term)
except (ValueError,np_exceptions.UFuncTypeError, TypeError) as e:
if isinstance(e,ValueError):
return Error("ValueError", "Matrices are not aligned")
elif isinstance(e,TypeError):
return Error("TypeError", f"You can't subtract a {self.dataTypes[type(p.value)]} and a {self.dataTypes[type(p.term)]}")
elif isinstance(e,np_exceptions.UFuncTypeError):
return Error("TypeError", "You can only do element wise subtraction between two arrays of the same data type")
else:
return Error("TypeError", "You can only do element wise subtraction between two arrays of the same data type")
@_('MINUS factor %prec UMINUS')
def factor(self, p):
if isinstance(p.factor, Error):
return p.factor
return -p.factor
@_('PLUS factor %prec UPLUS')
def factor(self, p):
if isinstance(p.factor, Error):
return p.factor
return p.factor
@_('term')
def value(self, p):
return p.term
@_('term TIMES factor')
def term(self, p):
if isinstance(p.term, Error):
return p.term
if isinstance(p.factor, Error):
return p.factor
if self.areDigits(p.term, p.factor):
return p.term * p.factor
if isinstance(p.term, np.ndarray) and isinstance(p.factor, np.ndarray):
if p.term.dtype == p.factor.dtype:
try:
return np.multiply(p.term, p.factor)
except:
return Error("ValueError", "Matrices are not aligned")
else:
return Error("TypeError", "You can only do element wise multiplication between two arrays of the same data type")
try:
return np.multiply(p.term, p.factor)
except:
return Error("TypeError", f"Multiplication between {self.dataTypes[type(p.term)]} and {self.dataTypes[type(p.factor)]} is not allowed")
@_('term MATMUL factor')
def term(self, p):
if isinstance(p.term, Error):
return p.term
if isinstance(p.factor, Error):
return p.factor
if isinstance(p.term, np.ndarray) and isinstance(p.factor, np.ndarray):
try:
return np.matmul(p.term, p.factor)
except:
return Error("ValueError", "Matrices are not aligned")
else:
return Error("TypeError", "You can only do matrix maltiplication between two arrays")
@_('term MOD factor')
def term(self, p):
if isinstance(p.term, Error):
return p.term
if isinstance(p.factor, Error):
return p.factor
if self.areDigits(p.term, p.factor):
return p.term % p.factor
else:
try:
return np.mod(p.term, p.factor)
except (ValueError, TypeError, np_exceptions.UFuncTypeError) as e:
if isinstance(e,ValueError):
return Error("ValueError", "Matrices are not aligned")
elif isinstance(e,TypeError):
return Error("TypeError", f"You can't mod a {self.dataTypes[type(p.term)]} and a {self.dataTypes[type(p.factor)]}")
elif isinstance(e,np_exceptions.UFuncTypeError):
return Error("TypeError", "You can only do element wise mod between two arrays of the same data type")
else:
return Error("TypeError", "You can only do element wise mod between two arrays of the same data type")
@_('term DIVIDE factor')
def term(self, p):
if isinstance(p.term, Error):
return p.term
if isinstance(p.factor, Error):
return p.factor
if self.areDigits(p.term, p.factor):
try:
return p.term / p.factor
except ZeroDivisionError:
return Error("ZeroDivisionError", "Division by zero")
if isinstance(p.term, np.ndarray) and isinstance(p.factor, np.ndarray):
if p.term.dtype == p.factor.dtype:
try:
return np.divide(p.term, p.factor)
except ValueError:
return Error("ValueError", "Matrices are not aligned")
else:
return Error("TypeError", "You can only do element wise multiplication between two arrays of the same data type")
try:
return np.divide(p.term, p.factor)
except ValueError:
return Error("TypeError", f"Multiplication between {self.dataTypes[type(p.term)]} and {self.dataTypes[type(p.factor)]} is not allowed")
@_('term FLRDIV factor')
def term(self, p):
if isinstance(p.term, Error):
return p.term
if isinstance(p.factor, Error):
return p.factor
if self.areDigits(p.term, p.factor):
try:
return p.term // p.factor
except ZeroDivisionError:
return Error("ZeroDivisionError", "Division by zero")
else:
try:
return np.floor_divide(p.term, p.factor)
except (ValueError, TypeError, np_exceptions.UFuncTypeError) as e:
if isinstance(e,ValueError):
return Error("ValueError", "Matrices are not aligned")
elif isinstance(e,TypeError):
return Error("TypeError", f"You can't floor divide a {self.dataTypes[type(p.term)]} and a {self.dataTypes[type(p.factor)]}")
elif isinstance(e,np_exceptions.UFuncTypeError):
return Error("TypeError", "You can only do element wise floor division between two arrays of the same data type")
else:
return Error("TypeError", "You can only do element wise floor division between two arrays of the same data type")
@_('term POWER factor')
def term(self, p):
if isinstance(p.term, Error):
return p.term
if isinstance(p.factor, Error):
return p.factor
else:
try:
return np.power(p.term, p.factor)
except (ValueError, TypeError, np_exceptions.UFuncTypeError) as e:
if isinstance(e,ValueError):
return Error("ValueError", "Matrices are not aligned")
elif isinstance(e,TypeError):
return Error("TypeError", f"You can't power a {self.dataTypes[type(p.term)]} and a {self.dataTypes[type(p.factor)]}")
elif isinstance(e,np_exceptions.UFuncTypeError):
return Error("TypeError", "You can only do element wise power between two arrays of the same data type")
else:
return Error("TypeError", "You can only do element wise power between two arrays of the same data type")
@_('factor')
def term(self, p):
return p.factor
@_('NUMBER')
def factor(self, p):
return p.NUMBER
@_('STRLT')
def factor(self, p):
return p.STRLT
@_('LPAREN value RPAREN')
def factor(self, p):
return p.value
@_('ID ASSIGN value')
def statement(self, p):
if isinstance(p.value, Error):
return p.value
else:
if p.ID in self.workspaceMap:
self.workspace.changeValue(self.workspaceMap[p.ID], p.value)
else:
self.workspaceMap[p.ID] = self.workspace.addVariable(p.ID, p.value)
self.values[p.ID] = p.value
return None
@_('ID')
def factor(self, p):
return self.getValue(p.ID)
@_('array')
def factor(self,p):
return p.array
@_('LSQB elements RSQB')
def array(self, p):
return np.array(p.elements)
@_('empty')
def elements(self, p):
return []
@_('value')
def elements(self, p):
if isinstance(p.value, Error):
return p.value
return [p.value]
@_('value "," elements')
def elements(self, p):
if isinstance(p.value, Error):
return p.value
return [p.value] + p.elements
@_('value GT value', 'value LT value', 'value GE value', 'value LE value', 'value EQ value', 'value NE value')
def factor(self, p):
if isinstance(p.value0, Error):
return p.value0
if isinstance(p.value1, Error):
return p.value1
try:
match p[1]:
case ">":
return p.value0 > p.value1
case "<":
return p.value0 < p.value1
case ">=":
return p.value0 >= p.value1
case "<=":
return p.value0 <= p.value1
case "==":
return p.value0 == p.value1
case "!=":
return p.value0 != p.value1
except Exception as e:
return Error("TypeError", f"Comparison between {self.dataTypes[type(p.value0)]} and {self.dataTypes[type(p.value1)]} is not allowed")
@_('value AND value', 'value OR value')
def factor(self, p):
if isinstance(p.value0, Error):
return p.value0
if isinstance(p.value1, Error):
return p.value1
try:
match p[1]:
case "and":
return np.logical_and(p.value0, p.value1)
case "or":
return np.logical_or(p.value0, p.value1)
except Exception as e:
return Error("TypeError", f"Comparison between {self.dataTypes[type(p.value0)]} and {self.dataTypes[type(p.value1)]} is not allowed")
@_('NOT value')
def factor(self, p):
if isinstance(p.value, Error):
return p.value
try:
return np.logical_not(p.value)
except Exception as e:
return Error("TypeError", f"Comparison between {self.dataTypes[type(p.value)]} and {self.dataTypes[type(p.value)]} is not allowed")
@_('QUIT')
def statement(self, p):
sys.exit()
@_('CLEAR')
def statement(self, p):
self.terminal.delete("1.0","end")
return None
@_('LS')
def statement(self, p):
if len(self.values) == 0:
self.termianl.insert("end", "No variables declared")
else:
self.terminal.insert("end", "Variable\tValue\n")
for variable, value in self.values.items():
value_lines = str(value).splitlines()
self.terminal.insert("end", f"{variable}\t{value_lines[0]}\n")
for line in value_lines[1:]:
self.terminal.insert("end", f"\t{line}\n")
return None
@_('vector')
def factor(self, p):
return p.vector
@_('LPAREN elements RPAREN')
def vector(self, p):
if isinstance(p.elements, Error):
return p.elements
return tuple(p.elements)
def getValue(self, index):
try:
return self.values[index]
except KeyError:
return Error("NameError", f"variable {index} have no value")
def areDigits(self, value1, value2):
if(type(value1) in [float, int, complex] and type(value2) in [float, int, complex]):
return True
else:
return False
def change_value(self, item_id, new_value):
# Get the current values of the item
current_values = self.workspace.workspace.item(item_id, "values")
# Modify the desired value
current_values = list(current_values)
current_values[1] = new_value
# Update the item with the modified values
self.workspace.workspace.item(item_id, values=current_values)
def isiterable(self, value1):
if (type(value1) in (tuple,np.ndarray, str)):
return True
else:
return False
@_('ID vector')
def func(self, p):
if isinstance(p.vector, Error):
return p.vector
return BuiltInFunc.getFunction(p.ID, p.vector)
@_('func')
def factor(self, p):
if isinstance(p.func, Error):
return p.func
func = p.func
if func.name == "View" and len(func.arguments) == 1 and isinstance(func.arguments[0], pd.DataFrame):
Table = TableView(self.notebook, func.arguments[0])
Table.name = self.get_DataFrame_name(func.arguments[0])
current_tab = self.notebook.select()
current_frame = self.notebook.nametowidget(current_tab)
if any (re.match(r".!frame\d+.!label", child) for child in map(str, current_frame.winfo_children())):
self.notebook.forget(current_tab)
self.notebook.add(Table.frame, text=Table.name)
self.notebook.select(Table.frame)
return None
elif func.name == "View" and len(func.arguments) == 1 and not isinstance(func.arguments[0], np.ndarray):
return Error("ArgumentTypeError", "View function only accepts DataFrames")
elif func.name == "View" and len(func.arguments) != 1:
return Error("ArgumentNumberError", "View function only accepts one argument")
if func.name == "write":
s = ""
for argument in func.arguments:
s += str(argument) + "\n"
s = s[:-1]
self.terminal.insert("end", s)
return None
return p.func.exec()
@_('READ')
def value(self,p):
return input()
@_('value PIPE func')
def factor(self, p):
if isinstance(p.value, Error):
return p.value
if isinstance(p.func, Error):
return p.func
p.func.addArgument(p.value)
return p.func.exec()
@_('json')
def value(self, p):
return p.json
@_('LQB members RQB')
def json(self, p):
if isinstance(p.members, Error):
return p.members
return {key: value for key, value in p.members}
@_('pair')
def members(self, p):
if isinstance(p.pair, Error):
return p.pair
return [p.pair]
@_('pair "," members')
def members(self, p):
if isinstance(p.pair, Error):
return p.pair
if isinstance(p.members, Error):
return p.members
return [p.pair] + p.members
@_('value ":" value')
def pair(self, p):
if isinstance(p.value0, Error):
return p.value0
if isinstance(p.value1, Error):
return p.value1
if isinstance(p.value0, (dict, np.ndarray)):
value0 = tuple(p.value0)
else:
value0 = p.value0
if isinstance(p.value1, (dict, np.ndarray)):
value1 = tuple(p.value1)
else:
value1 = p.value1
return value0, value1
@_('value LSQB value RSQB')
def factor(self,p):
if isinstance(p.value0, Error):
return p.value0
if isinstance(p.value1, Error):
return p.value1
if self.isiterable(p.value0):
lenght = len(p.value0)
if self.isiterable(p.value1) and len(p.value0) == len(p.value1):
return p.value0[p.value1]
if p.value1 in range(-lenght, lenght):
return p.value0[p.value1]
else:
return Error("IndexError", f"{self.dataTypes[type(p.value)]} Index out of range")
elif isinstance(p.value0,(dict)):
if p.value1 in p.value0:
return p.value0[p.value1]
else:
return Error("KeyError", f"KeyError: {p.value1}")
elif isinstance(p.value0,(pd.DataFrame)):
try:
return p.value0[p.value1]
except KeyError:
return Error("KeyError", f"Column {p.value1} not found")
else:
return Error("TypeError", f"{self.dataTypes[type(p.value0)]} not subscriptable")
@_('value LSQB value ":" value RSQB')
def factor(self,p):
if isinstance(p.value0, Error):
return p.value0
if isinstance(p.value1, Error):
return p.value1
if isinstance(p.value2, Error):
return p.value2
if self.isiterable(p.value0):
return p.value0[p.value1 : p.value2]
else:
return Error("TypeError", f"{self.dataTypes[type(p.value0)]} not subscriptable")
@_('ID LSQB value RSQB ASSIGN value')
def statement(self,p):
varibale = self.getValue(p.ID)
if isinstance(varibale, Error):
return varibale
if isinstance(p.value0, Error):
return p.value0
if isinstance(p.value1, Error):
return p.value1
if self.isiterable(varibale):
lenght = len(varibale)
if self.isiterable(p.value0) and len(p.value0) == len(p.value1):
varibale[p.value0] = p.value1
return None
if p.value0 in range(-lenght, lenght):
varibale[p.value0] = p.value1
return None
else:
return Error("IndexError", f"{self.dataTypes[type(p.value)]} Index out of range")
elif isinstance(varibale,dict):
varibale[p.value0] = p.value1
return None
if isinstance(varibale, (pd.DataFrame,pd.Series)):
try:
varibale[p.value0] = p.value1
return None
except KeyError:
return Error("KeyError", f"Column {p.value0} not found")
else:
return Error("TypeError", f"{self.dataTypes[type(p.value0)]} not subscriptable")
# if isinstance(p.value0, Error):
# return p.value0
# if isinstance(p.value1, Error):
# return p.value1
# if isinstance(p.value2, Error):
# return p.value2
# if self.isiterable(p.value0):
# if isinstance(p.value0, tuple):
# return Error("TypeError", "can't modify Vector")
# lenght = len(p.value0)
# if p.value1 in range(-lenght, lenght):
# p.value0[p.value1] = p.value2
# return None
# else:
# return Error("IndexError", f"{self.dataTypes[type(p.value0)]} Index out of range")
# elif isinstance(p.value0,dict):
# p.value0[p.value1] = p.value2
# return None
# if isinstance(p.value0, pd.DataFrame):
# try:
# p.value0[p.value1] = p.value2
# return None
# except KeyError:
# return Error("KeyError", f"Column {p.value1} not found")
# else:
# return Error("TypeError", f"{self.dataTypes[type(p.value0)]} not subscriptable")
@_('FALSE')
def value(self, p):
return False
@_('TRUE')
def value(self,p):
return True
def get_DataFrame_name(self, value):
for variable, val in self.values.items():
if isinstance(val, pd.DataFrame) and val.equals(value):
return variable
if __name__ == '__main__':
lexer = SciDataVizLexer()
parser = SciDataVizParser()
# os.system('clear')
while True:
try:
text = input('SciDataViz > ')
if ( text == ''):
continue
result = parser.parse(lexer.tokenize(text))
if not isinstance(result, type(None)):
print(result)
except EOFError:
break |
package com.yuanhao.modules.system.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yuanhao.modules.system.domain.Menu;
import com.yuanhao.modules.system.repository.MenuRepository;
import com.yuanhao.modules.system.repository.UserRepository;
import com.yuanhao.modules.system.service.MenuService;
import com.yuanhao.modules.system.service.RoleService;
import com.yuanhao.modules.system.service.dto.MenuDto;
import com.yuanhao.modules.system.service.dto.RoleSmallDto;
import com.yuanhao.modules.system.service.dto.vo.MenuMetaVo;
import com.yuanhao.modules.system.service.dto.vo.MenuVo;
import com.yuanhao.modules.system.service.mapstruct.MenuMapper;
import com.yuanhao.utils.RedisUtils;
import com.yuanhao.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Yuanhao
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "menu")
public class MenuServiceImpl implements MenuService {
private final MenuRepository menuRepository;
private final UserRepository userRepository;
private final MenuMapper menuMapper;
private final RoleService roleService;
private final RedisUtils redisUtils;
/**
* 用户角色改变时需清理缓存
*
* @param currentUserId /
* @return /
*/
@Override
@Cacheable(key = "'user:' + #p0")
public List<MenuDto> findByUser(Long currentUserId) {
List<RoleSmallDto> roles = roleService.findByUsersId(currentUserId);
Set<Long> roleIds = roles.stream().map(RoleSmallDto::getId).collect(Collectors.toSet());
LinkedHashSet<Menu> menus = menuRepository.findByRoleIdsAndTypeNot(roleIds, 2);
return menus.stream().map(menuMapper::toDto).collect(Collectors.toList());
}
@Override
public List<MenuDto> buildTree(List<MenuDto> menuDtos) {
// 父级 pid 为 null, 子级 pid 为父级 id, 以此创建菜单
List<MenuDto> trees = new ArrayList<>();
Set<Long> ids = new HashSet<>();
for (MenuDto menuDTO : menuDtos) {
// 上级菜单
if (menuDTO.getPid() == null) {
trees.add(menuDTO);
}
for (MenuDto it : menuDtos) {
// 根据 pid 和 id 是否相等添加子菜单
if (menuDTO.getId().equals(it.getPid())) {
if (menuDTO.getChildren() == null) {
menuDTO.setChildren(new ArrayList<>());
}
menuDTO.getChildren().add(it);
ids.add(it.getId());
}
}
}
// 如果树的大小为 0, 那么传回子菜单
if (trees.size() == 0) {
trees = menuDtos.stream().filter(s -> !ids.contains(s.getId())).collect(Collectors.toList());
}
return trees;
}
@Override
public List<MenuVo> buildMenus(List<MenuDto> menuDtos) {
List<MenuVo> list = new LinkedList<>();
menuDtos.forEach(menuDTO -> {
if (menuDTO != null) {
List<MenuDto> menuDtoList = menuDTO.getChildren();
MenuVo menuVo = new MenuVo();
menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getTitle());
// 一级目录需要加斜杠,不然会报警告
menuVo.setPath(menuDTO.getPid() == null ? "/" + menuDTO.getPath() : menuDTO.getPath());
menuVo.setHidden(menuDTO.getHidden());
// 如果不是外链
if (!menuDTO.getIFrame()) {
if (menuDTO.getPid() == null) {
menuVo.setComponent(StringUtils.isEmpty(menuDTO.getComponent()) ? "Layout" : menuDTO.getComponent());
// 如果不是一级菜单,并且菜单类型为目录,则代表是多级菜单
} else if (menuDTO.getType() == 0) {
menuVo.setComponent(StringUtils.isEmpty(menuDTO.getComponent()) ? "ParentView" : menuDTO.getComponent());
} else if (StringUtils.isNoneBlank(menuDTO.getComponent())) {
menuVo.setComponent(menuDTO.getComponent());
}
}
menuVo.setMeta(new MenuMetaVo(menuDTO.getTitle(), menuDTO.getIcon(), !menuDTO.getCache()));
if (CollectionUtil.isNotEmpty(menuDtoList)) {
menuVo.setAlwaysShow(true);
menuVo.setRedirect("noredirect");
menuVo.setChildren(buildMenus(menuDtoList));
// 处理是一级菜单并且没有子菜单的情况
} else if (menuDTO.getPid() == null) {
MenuVo menuVo1 = new MenuVo();
menuVo1.setMeta(menuVo.getMeta());
// 非外链
if (!menuDTO.getIFrame()) {
menuVo1.setPath("index");
menuVo1.setName(menuVo.getName());
menuVo1.setComponent(menuVo.getComponent());
} else {
menuVo1.setPath(menuDTO.getPath());
}
menuVo.setName(null);
menuVo.setMeta(null);
menuVo.setComponent("Layout");
List<MenuVo> list1 = new ArrayList<>();
list1.add(menuVo1);
menuVo.setChildren(list1);
}
list.add(menuVo);
}
}
);
return list;
}
} |
import React, { useState } from "react";
import axios from "axios";
import * as S from "./styled";
import { useHistory } from "react-router-dom";
import github from "../../components/github.png";
export default function Home(props) {
const history = useHistory();
const [usuario, setUsuario] = useState("");
const [erro, setErro] = useState(false);
function handlePesquisar() {
axios
.get(`https://api.github.com/users/${usuario}/repos`)
.then((response) => {
const repositories = response.data;
const repositoriesName = [];
repositories.forEach((repository) => {
repositoriesName.push(repository.name);
});
localStorage.setItem(
"repositoriesName",
JSON.stringify(repositoriesName)
);
setErro(false);
history.push("/repositories");
})
.catch((err) => {
setErro(true);
});
}
return (
<S.Container>
<S.ImgGitHub src={github} />
<S.Content>
<S.Input
autoFocus
value={usuario}
className="usuarioInput"
placeholder="Usuário"
onChange={(e) => setUsuario(e.target.value)}
/>
<S.Button onClick={handlePesquisar} type="button">
Pesquisar
</S.Button>
</S.Content>
{erro ? (
<S.ErroMessage>Ocorreu um erro, tente novamente!</S.ErroMessage>
) : (
""
)}
</S.Container>
);
} |
import Excepciones.ExPolinomio;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.*;
import java.util.HashMap;
import java.util.Map;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
import org.jfree.chart.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.*;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class CalculadoraPolinomios extends JFrame implements ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CalculadoraPolinomios().setVisible(true);
}
});
}
private JTextField txtPolinomio1, txtPolinomio2, txtResultado;
private JButton btnSumar, btnRestar, btnMultiplicar, btnEvaluar, btnMultiplicarEscalar, btnGraficar;
public CalculadoraPolinomios() {
setTitle("Calculadora de Polinomios");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setLayout(new GridLayout(7, 2));
JLabel lblPolinomio1 = new JLabel("Polinomio 1:");
txtPolinomio1 = new JTextField();
JLabel lblPolinomio2 = new JLabel("Polinomio 2:");
txtPolinomio2 = new JTextField();
JLabel lblResultado = new JLabel("Resultado:");
txtResultado = new JTextField();
txtResultado.setEditable(false);
btnSumar = new JButton("Sumar (+)");
btnRestar = new JButton("Restar (-)");
btnMultiplicar = new JButton("Multiplicar (*)");
btnEvaluar = new JButton("Evaluar");
btnMultiplicarEscalar = new JButton("Multiplicar por Escalar");
btnGraficar = new JButton("Graficar");
btnSumar.addActionListener(this);
btnRestar.addActionListener(this);
btnMultiplicar.addActionListener(this);
btnEvaluar.addActionListener(this);
btnMultiplicarEscalar.addActionListener(this);
btnGraficar.addActionListener(this);
add(lblPolinomio1);
add(txtPolinomio1);
add(lblPolinomio2);
add(txtPolinomio2);
add(lblResultado);
add(txtResultado);
add(btnSumar);
add(btnRestar);
add(btnMultiplicar);
add(btnEvaluar);
add(btnMultiplicarEscalar);
add(btnGraficar);
}
public void actionPerformed(ActionEvent e) {
String polinomio1 = txtPolinomio1.getText();
String polinomio2 = txtPolinomio2.getText();
String resultado = "Hola";
double numeric =0.0;
ExPolinomio validacion = new ExPolinomio();
if (e.getSource() == btnSumar) {
// Lógica para sumar los polinomios
polinomio1=validacion.revision(polinomio1);
polinomio2=validacion.revision(polinomio2);
txtPolinomio1.setText(polinomio1);
txtPolinomio2.setText(polinomio2);
resultado = sumarPolinomios(polinomio1, polinomio2);
txtResultado.setText(resultado);
} else if (e.getSource() == btnRestar) {
// Lógica para restar los polinomios
polinomio1=validacion.revision(polinomio1);
polinomio2=validacion.revision(polinomio2);
txtPolinomio1.setText(polinomio1);
txtPolinomio2.setText(polinomio2);
resultado = restarPolinomios(polinomio1, polinomio2);
txtResultado.setText(resultado);
} else if (e.getSource() == btnMultiplicar) {
// Lógica para multiplicar los polinomios
polinomio1=validacion.revision(polinomio1);
polinomio2=validacion.revision(polinomio2);
txtPolinomio1.setText(polinomio1);
txtPolinomio2.setText(polinomio2);
resultado = multiplicarPolinomios(polinomio1, polinomio2);
txtResultado.setText(resultado);
} else if (e.getSource() == btnEvaluar) {
String valorStr = JOptionPane.showInputDialog("Ingrese el valor a evaluar:");
double valor = Double.parseDouble(valorStr);
// Lógica para evaluar el polinomio en el valor dado
numeric = evaluarPolinomio(polinomio1, valor);
txtResultado.setText(Double.toString(numeric));
} else if (e.getSource() == btnMultiplicarEscalar) {
//validar formato:
polinomio1=validacion.revision(polinomio1);
txtPolinomio1.setText(polinomio1);
String escalarStr = JOptionPane.showInputDialog("Ingrese el escalar:");
double escalar = Double.parseDouble(escalarStr);
// Lógica para multiplicar el polinomio por un escalar
resultado = multiplicarPorEscalar(polinomio1, escalar);
txtResultado.setText(resultado);
} else if (e.getSource() == btnGraficar) {
// Lógica para graficar el polinomio
graficarPolinomio(polinomio1,polinomio2);
}
}
private String sumarPolinomios(String polinomio1, String polinomio2) {
// Convierte los polinomios en arreglos de términos
String[] terminos1 = polinomio1.split("\\s*\\+\\s*");
String[] terminos2 = polinomio2.split("\\s*\\+\\s*");
// Crea un mapa para almacenar los coeficientes de cada grado
Map<Integer, Integer> coeficientes = new HashMap<>();
// Suma los coeficientes de los términos del primer polinomio
for (String termino : terminos1) {
String[] partes = termino.split("x\\^");
int coeficiente = Integer.parseInt(partes[0]);
int grado = Integer.parseInt(partes[1]);
coeficientes.put(grado, coeficientes.getOrDefault(grado, 0) + coeficiente);
}
// Suma los coeficientes de los términos del segundo polinomio
for (String termino : terminos2) {
String[] partes = termino.split("x\\^");
int coeficiente = Integer.parseInt(partes[0]);
int grado = Integer.parseInt(partes[1]);
coeficientes.put(grado, coeficientes.getOrDefault(grado, 0) + coeficiente);
}
// Construye la cadena del polinomio resultante
StringBuilder resultado = new StringBuilder();
boolean primerTermino = true;
for (Map.Entry<Integer, Integer> entry : coeficientes.entrySet()) {
int grado = entry.getKey();
int coeficiente = entry.getValue();
if (coeficiente != 0) {
// Agrega el signo "+" si no es el primer término
if (!primerTermino && coeficiente > 0) {
resultado.append(" + ");
}
// Agrega el coeficiente y el grado del término
resultado.append(coeficiente);
if (grado > 0) {
resultado.append("x^").append(grado);
}
primerTermino = false;
}
}
return acomodarPolinomio(resultado.toString());
}
// Implementa la lógica para restar los polinomios y retorna el resultado como string pero ya con la operacion matematica
private String restarPolinomios(String polinomio1, String polinomio2) {
// Convierte los polinomios en arreglos de términos
String[] terminos1 = polinomio1.split("\\s*\\+\\s*");
String[] terminos2 = polinomio2.split("\\s*\\+\\s*");
// Crea un mapa para almacenar los coeficientes de cada grado
Map<Integer, Integer> coeficientes = new HashMap<>();
// Resta los coeficientes de los términos del primer polinomio
for (String termino : terminos1) {
String[] partes = termino.split("x\\^");
int coeficiente = Integer.parseInt(partes[0]);
int grado = Integer.parseInt(partes[1]);
coeficientes.put(grado, coeficientes.getOrDefault(grado, 0) + coeficiente);
}
// Resta los coeficientes de los términos del segundo polinomio
for (String termino : terminos2) {
String[] partes = termino.split("x\\^");
int coeficiente = Integer.parseInt(partes[0]);
int grado = Integer.parseInt(partes[1]);
coeficientes.put(grado, coeficientes.getOrDefault(grado, 0) - coeficiente);
}
// Construye la cadena del polinomio resultante
StringBuilder resultado = new StringBuilder();
boolean primerTermino = true;
for (Map.Entry<Integer, Integer> entry : coeficientes.entrySet()) {
int grado = entry.getKey();
int coeficiente = entry.getValue();
if (coeficiente != 0) {
// Agrega el signo "+" si no es el primer término
if (!primerTermino && coeficiente > 0) {
resultado.append(" + ");
} else if (coeficiente < 0) {
resultado.append(" - ");
coeficiente = Math.abs(coeficiente);
}
// Agrega el coeficiente y el grado del término
resultado.append(coeficiente);
if (grado > 0) {
resultado.append("x^").append(grado);
}
primerTermino = false;
}
}
return acomodarPolinomio(resultado.toString());
}
private String multiplicarPolinomios(String polinomio1, String polinomio2) {
// Convierte los polinomios en arreglos de términos
String[] terminos1 = polinomio1.split("\\s*\\+\\s*");
String[] terminos2 = polinomio2.split("\\s*\\+\\s*");
// Crea un mapa para almacenar los coeficientes de cada grado
Map<Integer, Integer> coeficientes = new HashMap<>();
// Multiplica los coeficientes de los términos de los polinomios
for (String termino1 : terminos1) {
String[] partes1 = termino1.split("x\\^");
int coeficiente1 = Integer.parseInt(partes1[0]);
int grado1 = Integer.parseInt(partes1[1]);
for (String termino2 : terminos2) {
String[] partes2 = termino2.split("x\\^");
int coeficiente2 = Integer.parseInt(partes2[0]);
int grado2 = Integer.parseInt(partes2[1]);
int nuevoCoeficiente = coeficiente1 * coeficiente2;
int nuevoGrado = grado1 + grado2;
coeficientes.put(nuevoGrado, coeficientes.getOrDefault(nuevoGrado, 0) + nuevoCoeficiente);
}
}
// Construye la cadena del polinomio resultante
StringBuilder resultado = new StringBuilder("");
boolean primerTermino = true;
for (Map.Entry<Integer, Integer> entry : coeficientes.entrySet()) {
int grado = entry.getKey();
int coeficiente = entry.getValue();
if (coeficiente != 0) {
// Agrega el signo "+" si no es el primer término
if (!primerTermino && coeficiente > 0) {
resultado.append(" + ");
} else if (coeficiente < 0) {
resultado.append(" - ");
coeficiente = Math.abs(coeficiente);
}
// Agrega el coeficiente y el grado del término
resultado.append(coeficiente);
if (grado > 0) {
resultado.append("x^").append(grado);
}
primerTermino = false;
}
}
return acomodarPolinomio(resultado.toString());
}
private double evaluarPolinomio(String polinomio, double valor) {
// Convierte el polinomio en un arreglo de términos
String[] terminos = polinomio.split("\\s*\\+\\s*");
// Realiza la evaluación del polinomio en el valor dado
double resultado = 0.0;
for (String termino : terminos) {
String[] partes = termino.split("x\\^");
double coeficiente = Double.parseDouble(partes[0]);
int grado = Integer.parseInt(partes[1]);
resultado += coeficiente * Math.pow(valor, grado);
}
return resultado;
}
// Implementa la lógica para multiplicar el polinomio por un escalar y retorna el resultado como string pero ya con la operacion matematica
private String multiplicarPorEscalar(String polinomio, double escalar) {
// Convierte el polinomio en un arreglo de términos
String[] terminos = polinomio.split("\\s*\\+\\s*");
// Realiza la multiplicación por el escalar en cada término
StringBuilder resultado = new StringBuilder("");
resultado.append(escalar).append(": ");
boolean primerTermino = true;
for (String termino : terminos) {
String[] partes = termino.split("x\\^");
double coeficiente = Double.parseDouble(partes[0]);
int grado = Integer.parseInt(partes[1]);
double nuevoCoeficiente = coeficiente * escalar;
// Agrega el signo "+" si no es el primer término
if (!primerTermino && nuevoCoeficiente > 0) {
resultado.append(" + ");
}
// Agrega el coeficiente y el grado del término
resultado.append(nuevoCoeficiente);
if (grado > 0) {
resultado.append("x^").append(grado);
}
primerTermino = false;
}
return acomodarPolinomio(resultado.toString());
}
private void graficarPolinomio(String polinomio, String polinomio2) {
// Implementa la lógica para graficar el polinomio
JOptionPane.showMessageDialog(this, "Gráfica del polinomio: ");
Grafica grafica = new Grafica(polinomio,polinomio2);
grafica.run(polinomio,polinomio2);
}
private String acomodarPolinomio(String polinomio) {
// Verifica si la cadena contiene el signo "+"
if (!polinomio.contains("+")) {
return polinomio; // Devuelve la cadena original sin cambios
}
// Convierte los términos del polinomio en un arreglo
String[] terminos = polinomio.split("\\s*\\+\\s*");
// Crea un mapa para almacenar los coeficientes de cada grado
Map<Integer, Integer> coeficientes = new HashMap<>();
// Procesa cada término del polinomio
for (String termino : terminos) {
String[] partes = termino.split("x\\^");
int coeficiente = Integer.parseInt(partes[0]);
int grado = Integer.parseInt(partes[1]);
coeficientes.put(grado, coeficiente);
}
// Obtén una lista de las entradas del mapa y ordénalas en orden descendente según el grado
ArrayList<Map.Entry<Integer, Integer>> listaCoeficientes = new ArrayList<>(coeficientes.entrySet());
listaCoeficientes.sort((a, b) -> b.getKey().compareTo(a.getKey()));
// Construye la cadena del polinomio acomodado
StringBuilder resultado = new StringBuilder();
boolean primerTermino = true;
for (Map.Entry<Integer, Integer> entry : listaCoeficientes) {
int grado = entry.getKey();
int coeficiente = entry.getValue();
// Agrega el signo "+" si no es el primer término
if (!primerTermino && coeficiente >= 0) {
resultado.append(" + ");
}
// Agrega el coeficiente y el grado del término
resultado.append(coeficiente);
if (grado > 0) {
resultado.append("x^").append(grado);
}
primerTermino = false;
}
return resultado.toString();
}
}
class Grafica extends javax.swing.JFrame {
public Grafica(String polinomio,String polinomio2) {
initComponents(polinomio,polinomio2);
}
private void initComponents(String polinomio,String polinomio2) {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Gráfico del polinomio");
setSize(500, 500);
setLocationRelativeTo(null);
JButton btnGraficar = new JButton();
btnGraficar.setText("Graficar");
btnGraficar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGraficarActionPerformed(evt,polinomio,polinomio2);
}
}
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(200, 200, 200)
.addComponent(btnGraficar)
.addContainerGap(200, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(200, 200, 200)
.addComponent(btnGraficar)
.addContainerGap(200, Short.MAX_VALUE))
);
pack();
}
private void btnGraficarActionPerformed(java.awt.event.ActionEvent evt,String polinomio,String polinomio2) {
//String funcion = JOptionPane.showInputDialog(this, "Ingrese la función:");
String funcion = polinomio;
String funcion2 = polinomio2;
if (funcion != null && !funcion.isEmpty()) {
graficarFunciones(funcion,funcion2);
}
}
private void graficarFunciones(String funcion1, String funcion2) {
// Crea dos series de datos XY para representar las funciones
XYSeries serie1 = new XYSeries("Función 1");
XYSeries serie2 = new XYSeries("Función 2");
// Evalúa las funciones para diferentes valores de x y agrega los puntos a las series
for (double x = -10.0; x <= 10.0; x += 0.1) {
double y1 = evaluarFuncion(funcion1, x);
double y2 = evaluarFuncion(funcion2, x);
serie1.add(x, y1);
serie2.add(x, y2);
}
// Crea un conjunto de datos XY y agrega las series
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(serie1);
dataset.addSeries(serie2);
// Crea el gráfico de líneas
JFreeChart chart = ChartFactory.createXYLineChart(
"Gráfica de polinomios", // Título del gráfico
"x", // Etiqueta del eje X
"y", // Etiqueta del eje Y
dataset, // Datos a mostrar en el gráfico
PlotOrientation.VERTICAL, // Orientación del gráfico
true, // Incluir leyenda
true, // Incluir tooltips
false // No incluir URLs
);
// Crea el marco del gráfico y lo muestra
ChartFrame frame = new ChartFrame("Gráfica de polinomios", chart);
frame.pack();
frame.setVisible(true);
}
private double evaluarFuncion(String funcion, double x) {
double resultado= evaluarPolinomio(funcion,x);
// Retornar el resultado
return resultado;
}
public void run(String polinomio,String polinomio2) {
new Grafica(polinomio,polinomio2).setVisible(true);
}
private double evaluarPolinomio(String polinomio, double valor) {
// Convierte el polinomio en un arreglo de términos
String[] terminos = polinomio.split("\\s*\\+\\s*");
// Realiza la evaluación del polinomio en el valor dado
double resultado = 0.0;
for (String termino : terminos) {
String[] partes = termino.split("x\\^");
double coeficiente = Double.parseDouble(partes[0]);
int grado = Integer.parseInt(partes[1]);
resultado += coeficiente * Math.pow(valor, grado);
}
return resultado;
}
} |
---
title: "What is the canvas?"
type: docs
weight: 20
aliases: ["/classrooms/algorithm-design/lesson/78", "/algorithm-design/the-algorithm-design-canvas"]
---
The Algorithm Design Canvas captures our process for tackling algorithm design problems.
It is a convenient way to represent algorithmic thinking. Every algorithmic problem, big or small, easy or hard, should eventually end up as a completed canvas.
### The 5 areas of the Canvas
<a href="/files/the-algorithm-design-canvas.pdf" target="_blank" ><img alt="" src="/images/the-algorithm-design-canvas.png" style="width: 80%;" /></a>
The Canvas contains 5 major areas: [Constraints](/algorithms/algorithm-design-canvas/task-constraints/), [Ideas](/algorithms/algorithm-design-canvas/idea-generation/), [Complexities](/algorithms/algorithm-design-canvas/complexity/), [Code](/algorithms/algorithm-design-canvas/writing-the-code/), and [Tests](/algorithms/algorithm-design-canvas/testing-your-code/). Taken together, they capture everything you need to worry about when it comes to algorithm design problems. In further sections, we’re going to cover what each area represents, as well as many tips and tricks about filling them in. We’ll also work through some examples that let you see the Canvas in action.
### Area #1: Constraints
The Constraints area is where you fill in all constraints of the problem. This includes things like how large the input array can be, can the input string contain unicode characters, is the robot allowed to make diagonal moves in the maze, can the graph have negative edges, etc.
Your very first task when analyzing an algorithm design problem is to uncover all its relevant constraints and write them down in this area. Learn more about constraints [here](/algorithms/algorithm-design-canvas/task-constraints/).
### Area #2: Ideas
After you've identified all constraints, you go into idea generation. Typically during an interview you discuss 1 to 3 ideas. Often times you start with one, explain it to the interviewer, and then move on to a better idea.
Your next goal is to fill in a succinct description of your idea: short and sweet so that any interviewer is able to understand it. Start learning more about idea generation [here](/algorithms/algorithm-design-canvas/idea-generation/).
### Area #3: Complexities
Each idea has two corresponding Complexity areas: Time and Memory. For every algorithm you describe, you will need to be able to estimate its time and memory complexity. Further in this course we will talk about the Time vs Memory trade-off and why it's key to any algorithm design problem.
Learn how to analyze algorithm complexities [here](/algorithms/algorithm-design-canvas/complexity/).
### Area #4: Code
After you've identified the problem's constraints, discussed a few ideas, analyzed their complexities, and found one that both you and your interviewer think is worth being implemented, you finally go into writing code.
Writing code at interviews is fundamentally different from writing code in your IDE. To understand why and to learn how to approach writing code at interviews, go [here](/algorithms/algorithm-design-canvas/writing-the-code/).
### Area #5: Tests
Finally, you move on to writing test cases and testing your code. Many people completely ignore this step. This is not smart at all.
Learn more about what differs good tests from bad tests [here](/algorithms/algorithm-design-canvas/testing-your-code/).
### That's it.
By diligently following this process both during your preparation and at the interview, you will be way ahead of most candidates. Instead of freezing up and wondering what to do next, you are now equipped with the blueprint of a process that you can follow to solve any problem.
### Now go ahead and print some Canvases!
The best thing to do at this point is to print a bunch of copies of the Canvas: they’ll come in handy as you prepare for your technical interview.
[Print the Algorithm Design Canvas](/files/the-algorithm-design-canvas.pdf)
We hope you find the Canvas as indispensable as we’ve found it over the years. Use it wisely, and use it often!
### Example
To illustrate all this, throughout the next sections we will be using [the Zig-Zag problem from TopCoder](https://community.topcoder.com/stat?c=problem_statement&pm=1259&rd=4493&rm=&cr=107835). Below is a video introducing ZigZag.
<div class="text-center">
<iframe allowfullscreen="" frameborder="0" height="400" id="zigzag-introduction" mozallowfullscreen="" src="//player.vimeo.com/video/80556398?api=1&player_id=zigzag-introduction" webkitallowfullscreen="" width="600px"></iframe>
</div>
### What's next?
Let's continue to the first Canvas area: the often overlooked topic of identifying all constraints of a problem! |
import { flattenArray, compose, curry } from "./utils/index.ts";
import { data, DataFactory, Person } from "./data/index.ts";
const map = curry((fn, outerArray) => outerArray.map(fn));
const flatten = (innerArray) => flattenArray(innerArray);
function buildObject(data: (string | number)[]): Person {
return data.reduce(
(acc: any, curr: string | number, index: number) => {
switch (index % 6) {
case 0:
acc.name = <string>curr;
break;
case 1:
acc.age = <number>curr;
break;
case 2:
acc.address = { ...acc.address, street: <string>curr };
break;
case 3:
acc.address = { ...acc.address, city: <string>curr };
break;
// ...
case 4:
acc.address = {
...acc.address,
coordinates: [<number>curr, undefined],
};
break;
case 5:
acc.address = {
...acc.address,
coordinates: [acc.address.coordinates[0], <number>curr],
};
break;
}
return acc;
},
{ name: "", age: 0, address: { street: "", city: "", coordinates: [0, 0] } }
);
}
// const pipe = compose(map(flatten), map(buildObject));
// console.log(pipe(data));
const flatArrays = map(flatten)(data);
const output = map(buildObject)(flatArrays);
console.log(output); |
import {Component, EventEmitter, OnInit} from 'angular2/core';
import { CORE_DIRECTIVES } from 'angular2/common';
import {UserService} from '../services/users.services';
import {RouteParams, RouterLink, Router} from 'angular2/router';
import {Validators, FormBuilder, Control} from 'angular2/common';
@Component({
selector: 'edit_user',
providers: [UserService],
directives: [CORE_DIRECTIVES],
template: `
<div class="page-data">
<form #f="ngForm" (ngSubmit)="onSubmit()">
<table cellpadding="11">
<tr>
<div class="label"> User Name </div>
<input type="text" [value]="user?.USERNAME" [(ngModel)]="data.USERNAME">
<br>
<br>
<div class="label"> Password</div>
<input type="text" [value]="user?.PASSWORD" [(ngModel)]="data.PASSWORD">
<br>
<br>
<div class="label"> Active Flag</div>
<label *ngFor="#item of radioOptions">
<input type="radio" name="ACTIVE_FLAG" (click)="changeActiveValue(item)"
[checked]="item === active_flags" [value]="active_flags" [(ngModel)]="data.ACTIVE_FLAG">
{{item}}
</label>
<br>
<br>
</tr>
<p>
<button type="submit">Submit</button>
</p>
</table>
</form>
</div>`
})
export class UserEdit implements OnInit{
radioOptions = 'Y N'.split(' ');
jwt: any;
user: any;
active_flags: string;
params: any;
data: Object = {};
data.USERNAME: string;
data.PASSWORD: string;
data.ACTIVE_FLAG: string;
constructor(private _userService: UserService, private router: Router, params:RouteParams){
this.params = params.get('id');
this.jwt = localStorage.getItem('jwt');
};
ngOnInit(){
this.getEditUser(this.jwt, this.params);
};
getEditUser(jwt, id){
this._userService.getEditUser(jwt, id).subscribe(user_edit =>
{this.user = user_edit.data[0],
this.active_flags = user_edit.data[0].ACTIVE_FLAG,
this.data.USERNAME = user_edit.data[0].USERNAME,
this.data.PASSWORD = user_edit.data[0].PASSWORD,
this.data.ACTIVE_FLAG = user_edit.data[0].ACTIVE_FLAG},
error => {
console.log('error logged:');
console.log(error);
}
);
};
changeActiveValue(item){
this.active_flags = item;
this.data.ACTIVE_FLAG = item;
}
onSubmit() {
this._userService.saveEditUser(this.jwt, this.params, this.data).subscribe();
this.router.navigate(['UserList']);
}
} |
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2024 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\ORM\Query\Part\Where;
use Espo\ORM\Query\Part\WhereClause;
use Espo\ORM\Query\Part\WhereItem;
/**
* AND-group. Immutable.
*
* @immutable
*/
class AndGroup implements WhereItem
{
/** @var array<string|int, mixed> */
private $rawValue = [];
/**
* @return array<string|int, mixed>
*/
public function getRaw(): array
{
return ['AND' => $this->getRawValue()];
}
public function getRawKey(): string
{
return 'AND';
}
/**
* @return array<string|int, mixed>
*/
public function getRawValue(): array
{
return $this->rawValue;
}
/**
* Get a number of items.
*/
public function getItemCount(): int
{
return count($this->rawValue);
}
/**
* @param array<string|int, mixed> $whereClause
* @return self
*/
public static function fromRaw(array $whereClause): self
{
if (count($whereClause) === 1 && array_keys($whereClause)[0] === 0) {
$whereClause = $whereClause[0];
}
// Do not refactor.
$obj = static::class === WhereClause::class ?
new WhereClause() :
new self();
$obj->rawValue = $whereClause;
return $obj;
}
public static function create(WhereItem ...$itemList): self
{
$builder = self::createBuilder();
foreach ($itemList as $item) {
$builder->add($item);
}
return $builder->build();
}
public static function createBuilder(): AndGroupBuilder
{
return new AndGroupBuilder();
}
} |
import React, { useCallback, useMemo } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import "./App.css";
import Header from "../common/Header.jsx";
import Journey from "./Journey.jsx";
import HighSpeed from "./HighSpeed.jsx";
import DepartDate from "./DepartDate.jsx";
import Submit from "./Submit.jsx";
import CitySelector from "../common/CitySelector.jsx";
import DateSelector from "../common/DateSelector.jsx";
import { h0 } from "../common/fp";
// action creater,返回的是纯对象的action,需要把返回值传递给dispatch
import {
exchangeFromTo,
showCitySelector,
hideCitySelector,
fetchCityData,
setSelectedCity,
showDateSelector,
hideDateSelector,
setDepartDate,
toggleHighSpeed,
} from "./actions";
function App(props) {
const {
dispatch,
from,
to,
isCitySelectorVisible,
isDateSelectorVisible,
isLoadingCityData,
cityData,
departDate,
highSpeed,
} = props;
// 向子组件传入callback函数,onBack每次都是新的句柄,Header组件就会一直渲染,所以用useCallback
// App每次渲染,onBack都是同一个句柄
const onBack = useCallback(() => {
window.history.back();
}, []);
// bindActionCreator:将ActionCreator 和 dispatch绑定在一起,但是bindActionCreator每次返回的是新的函数集合,和useCallback的目标冲突
// 触发了action
const cbs = useMemo(() => {
return bindActionCreators(
{
exchangeFromTo,
showCitySelector,
},
dispatch
);
}, [dispatch]);
const citySelectorCbs = useMemo(() => {
return bindActionCreators(
{
onBack: hideCitySelector,
fetchCityData,
onSelect: setSelectedCity,
},
dispatch
);
}, [dispatch]);
const departDateCbs = useMemo(() => {
return bindActionCreators(
{
onClick: showDateSelector,
},
dispatch
);
}, [dispatch]);
const dateSelectorCbs = useMemo(() => {
return bindActionCreators(
{
onBack: hideDateSelector,
},
dispatch
);
}, [dispatch]);
const highSpeedCbs = useMemo(() => {
return bindActionCreators(
{
toggle: toggleHighSpeed,
},
dispatch
);
}, [dispatch]);
const onSelectDate = useCallback(
(day) => {
if (!day) {
return;
}
if (day < h0()) {
return;
}
dispatch(setDepartDate(day));
dispatch(hideDateSelector());
},
[dispatch]
);
return (
<div>
<div className="header-wrapper">
<Header title="火车票" onBack={onBack} />
</div>
<form className="form" action="./query.html">
<Journey from={from} to={to} {...cbs} />
<DepartDate time={departDate} {...departDateCbs} />
<HighSpeed highSpeed={highSpeed} {...highSpeedCbs} />
<Submit />
</form>
<CitySelector
show={isCitySelectorVisible}
cityData={cityData}
isLoading={isLoadingCityData}
{...citySelectorCbs}
/>
<DateSelector
show={isDateSelectorVisible}
{...dateSelectorCbs}
onSelect={onSelectDate}
/>
</div>
);
}
// 被connect包装后的新组件
export default connect(
function mapStateToProps(state) {
return state;
},
function mapDispatchToProps(dispatch) {
return { dispatch };
}
)(App); |
from unittest.mock import Mock
import pytest
from epsilion_wars_mmorpg_automation.game.state.grinding import is_died_state
@pytest.mark.parametrize('button_text,expected', [
('Непонятная кнопка', False),
('💀 Принять участь', True),
('В город', False),
])
def test_is_died_state_by_button(button_text: str, expected: bool):
button = Mock()
button.text = button_text
event_mock = Mock()
event_mock.message.message = ''
event_mock.message.button_count = 1
event_mock.message.buttons = [[button]]
result = is_died_state(event_mock)
assert result is expected
@pytest.mark.parametrize('message_text,expected', [
('Тебя убил: ☠️ Гигантский скелет 🔸14\n\nТы был отправлен восстанавливаться в город', True),
('📍 🧟♂️ Ник 🔸14 убивает 🧟♂️ ВторойНик 🔸14 💔🏵 Потеряно славы: 10\n\n Ты отправляешься в ближайший город на восстановление', True),
('любое другое сообщение', False),
])
def test_is_died_state_without_button(message_text: str, expected: bool):
event_mock = Mock()
event_mock.message.message = message_text
event_mock.message.button_count = 0
event_mock.message.buttons = []
result = is_died_state(event_mock)
assert result is expected
def test_is_died_state_after_escape():
button = Mock()
button.text = 'В город'
event_mock = Mock()
event_mock.message.message = '🧟♂️ FHFHF 🔸12 попытался сбежать от 🪶 🧝♂️ OEOEOE 🔸14, но попытка была провалена'
event_mock.message.button_count = 1
event_mock.message.buttons = [[button]]
result = is_died_state(event_mock)
assert result is True |
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#define MAX_VELICINA_DATOTEKE 100000
void main( void )
{
char datoteka[100]; /* naziv datoteke koju otvaramo */
char broj; /* broj blanko karaktera koji zelimo da umetnemo*/
/* Pomocne promenljive */
char ch;
int i, br;
/* mesto za privremeno smestanje korigovane datoteke */
char prostor[ MAX_VELICINA_DATOTEKE ];
FILE *p_datoteka; /* pokazivac na datoteku koju otvaramo */
/* unosi se ime datoteke, i to max do 100 karaktera */
printf( "Upisi naziv datoteke:" );
scanf( "%s", datoteka );
fflush( stdin );
/* otvaramo datoteku za citanje */
p_datoteka = fopen( datoteka, "r" );
if ( p_datoteka == NULL ) /* ako je doslo do neke greske */
{
printf( "Uneto ime datoteke ne postoji ili ne moze da se otvori!\n" );
return; /* izadji iz programa*/
}
/* unosi slovo koje ce mo da ispitujemo */
do
{
printf( "Upisi broj blanko karaktera za zamenu tabulatora:" );
scanf( "%c", &broj );
fflush( stdin );
} /* ako nismo uneli slovo, vraca nas ponovo na unos */
while ( isdigit( broj ) == 0 );
/* inicijalizujemo brojac na NULU */
br = 0;
/* Radi dok god ne dosegnemo kraj datoteke */
while ( ( ch = fgetc( p_datoteka ) ) != EOF )
{
/* Ako smo naisli na znak za tabulator... */
if ( ch == '\t' )
for ( i = 1; i <= broj - '0'; i++ ) prostor[ ++br ] = ' ';
else /* a ako nismo... */
prostor[ ++br ] = ch;
}
/* zatvori datoteku */
fclose( p_datoteka );
/* inicijalizujemo pointer na NULU za svaki slucaj */
/* jer ce mo ponovo otvarati datoteku */
p_datoteka = NULL;
/* otvaramo datoteku ali ovoga puta za pisanje */
p_datoteka = fopen( datoteka, "w" );
if ( p_datoteka == NULL ) /* ako je doslo do neke greske */
{
printf( "Datoteke ne moze da se otvori za pisanje!\n" );
return; /* izadji iz programa*/
}
/* upisi u datoteku zeljene izmene... */
for ( i=1; i<=br; i++ )
fprintf( p_datoteka, "%c", prostor[i] );
/* zatvori datoteku */
fclose( p_datoteka );
} |
import React, { useState } from "react";
import "../componentscss/Modal.css";
import htmlIcon from "../assets/html.svg";
import rightArrowIcon from "../assets/right-arrow.svg";
const Modal = ({
modal,
setModal,
rank,
setRank,
percentile,
setPercentile,
score,
setScore,
}) => {
return (
<div className="modal">
<div className={modal ? "confirm show" : "confirm"}>
<div className="modal-header">
<h3>Update Scores</h3>
<img src={htmlIcon} alt="html-icon" />
</div>
<div className="input-container">
<div className="input-items">
<div className="input-item-left">
<div className="count-box">1</div>
<p>
Update your <span>rank</span>
</p>
</div>
<div className="input-item-right">
<input
type="number"
name=""
id=""
value={rank}
onChange={(e) => setRank(e.target.value)}
/>
</div>
</div>
<div className="input-items">
<div className="input-item-left">
<div className="count-box">2</div>
<p>
Update your <span>percentile</span>
</p>
</div>
<div className="input-item-right">
<input
type="number"
name=""
id=""
value={percentile}
onChange={(e) => setPercentile(e.target.value)}
/>
</div>
</div>
<div className="input-items">
<div className="input-item-left">
<div className="count-box">3</div>
<p>
Update your <span>current score (out of 15)</span>
</p>
</div>
<div className="input-item-right">
<input
type="number"
name=""
id=""
value={score}
onChange={(e) => setScore(e.target.value)}
/>
</div>
</div>
</div>
<div className="modal-footer">
<button className="cancel-btn" onClick={() => setModal(false)}>
Cancel
</button>
<button className="save-btn" onClick={() => setModal(false)}>
Save <img src={rightArrowIcon} alt="" />
</button>
</div>
</div>
<div className="overlay" onClick={() => setModal(false)} />
</div>
);
};
export default Modal; |
import BaseSchema from '@ioc:Adonis/Lucid/Schema'
export default class extends BaseSchema {
protected tableName = 'usuarios'
public async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id').notNullable()
//referencia al id del rol es una foreign key
table.string('nombre', 60).notNullable()
table.string('correo', 254).notNullable().unique()
table.string('contrasena', 256).notNullable()
/**
* Uses timestamptz for PostgreSQL and DATETIME2 for MSSQL
*/
table.timestamp('created_at', { useTz: true })
table.timestamp('updated_at', { useTz: true })
})
}
public async down() {
this.schema.dropTable(this.tableName)
}
} |
<template>
<div class="box">
<div class="title">
{{ props.title }}
</div>
<div class="main-content">
<div class="content-left">
<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" />
</div>
<div class="content-right">
<div class="ipt-item">
<div>所属班级:</div>
<div><el-input disabled v-model="iptdata.calss" /></div>
</div>
<div class="ipt-item" v-show=props.showcreate>
<div>新建班级:</div>
<div><el-input v-model="iptdata.createclass" /></div>
</div>
<div class="ipt-item" v-show=props.showrevise>
<div>修改班级:</div>
<div><el-input v-model="iptdata.revise" /></div>
</div>
<div class="ipt-item" v-show=props.showdel>
<div>删除班级:</div>
<div><el-input disabled v-model="iptdata.del" /></div>
</div>
<button @click="send" class="btn">{{ props.btnname }}</button>
</div>
</div>
</div>
</template>
<script lang='ts' setup>
import { reactive } from 'vue'
// 表单数据
const iptdata = reactive(
{
calss: "",
createclass: "",
revise: "",
del: ""
}
)
// props
const props = defineProps({
// 左侧下拉数据
treeselect: {
type: Array,
default: ""
},
// 按钮名字
btnname: {
type: String,
default: "点击"
},
// 标题
title: {
type: String,
default: ""
},
// 显示新建班级
showcreate: {
type: Boolean,
default: true
},
// 显示修改班级
showrevise: {
type: Boolean,
default: false
},
// 显示删除班级
showdel: {
tyoe: Boolean,
default: false
}
})
// 左侧下拉数据
const data = props.treeselect
const defaultProps = {
children: 'children',
label: 'label',
}
const handleNodeClick = (data: any) => {
iptdata.calss = data.label
iptdata.del = data.label
}
const emit = defineEmits(['sendclick'])
const send = () => {
emit('sendclick', iptdata)
}
</script>
<style lang='scss' scoped>
.title {
font-size: 36px;
font-weight: bold;
padding: 4% 3%;
padding-bottom: 2%;
}
.main-content {
padding: 0.5% 10%;
padding-right: 8%;
display: flex;
overflow: hidden;
.content-left {
width: 40%;
height: 600px;
border: 2px solid #3c9595;
border-radius: 3%;
padding: 2%;
overflow: scroll;
.el-tree {
font-size: 24px;
color: #3d3d3d;
font-weight: bold;
background-color: transparent;
:deep(.el-tree-node__content) {
&:hover {
background-color: #e9f4f4;
}
}
:deep(el-icon el-tree-node__expand-icon) {
font-size: 32px;
}
:deep(.el-tree-node.is-current > .el-tree-node__content) {
background-color: #e9f5f5 !important;
}
}
}
.content-right {
margin-left: 10%;
display: flex;
flex-direction: column;
align-items: center;
.ipt-item,
.ipt-select {
font-size: 24px;
padding: 25px 20px;
padding-top: 0;
display: flex;
align-items: center;
flex-wrap: nowrap;
}
.el-input {
width: 250px;
height: 40px;
}
:deep(.el-input__wrapper.is-focus) {
box-shadow: 0 0 0 1px #479e9c inset;
}
.btn {
width: 120px;
height: 50px;
font-size: 20px;
font-weight: bold;
border-radius: 10px;
border: none;
color: white;
background-color: #137f7f;
cursor: pointer;
}
}
}
</style> |
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme
class ProfileScreen : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
profileScren()
}
}
}
}
@Preview(showBackground = true)
@Composable
fun profileScren(){
val checkedState = remember { mutableStateOf(true) }
Column {
profileContent()
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
){
Row(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
verticalAlignment = Alignment.CenterVertically
){
Box(
modifier = Modifier
.width(90.dp)
.height(100.dp)
.padding(10.dp),
contentAlignment = Alignment.Center
){
profileIcon(myPainter = painterResource(id = R.drawable.usericon))
}
Text("Edit Profile", fontSize = 18.sp, modifier = Modifier.padding(end = 100.dp))
profileIconButton()
}
}
divider()
//Second option
Box(
modifier = Modifier
.fillMaxWidth()
.height(90.dp)
){
Row(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
verticalAlignment = Alignment.CenterVertically
){
Box(
modifier = Modifier
.width(90.dp)
.height(90.dp)
.padding(10.dp),
contentAlignment = Alignment.Center
){
profileIcon(myPainter = painterResource(id = R.drawable.padlock))
}
Text("Reset Password", fontSize = 18.sp, modifier = Modifier.padding(end =60.dp))
profileIconButton()
}
}
//Third option - Edit profile
Box(
modifier = Modifier
.fillMaxWidth()
.height(90.dp)
){
Row(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
verticalAlignment = Alignment.CenterVertically
){
Box(
modifier = Modifier
.width(90.dp)
.height(90.dp)
.padding(10.dp),
contentAlignment = Alignment.Center
){
profileIcon(myPainter = painterResource(id = R.drawable.usericon))
}
Text("Show Notifications", fontSize = 18.sp, modifier = Modifier.padding(end = 60.dp))
Switch(
checked = checkedState.value,
onCheckedChange = { checkedState.value = it },
modifier = Modifier
.padding(0.dp),)
}
}
divider()
//fourth option
Box(
modifier = Modifier
.fillMaxWidth()
.height(90.dp)
){
Row(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
verticalAlignment = Alignment.CenterVertically
){
Box(
modifier = Modifier
.width(90.dp)
.height(90.dp)
.padding(10.dp),
contentAlignment = Alignment.Center
){
profileIcon(myPainter = painterResource(id = R.drawable.iconstar))
}
Text("Favorites", fontSize = 18.sp, modifier = Modifier.padding(end = 110.dp))
profileIconButton()
}
}
}
}
@Composable
fun profileContent(){
Box(
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
.background(Color.Red),
contentAlignment = Alignment.Center
){
Image(
painter = painterResource(id = R.drawable.profilecoverpage),
contentDescription = null,
contentScale = ContentScale.Crop
)
imageProfile()
}
}
@Composable
fun imageProfile(){
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(modifier = Modifier
.width(150.dp)
.height(150.dp)
.background(Color.White, shape = CircleShape.also {})
){
Image(
modifier = Modifier
.size(150.dp)
.clip(CircleShape),
painter = painterResource(id = R.drawable.elrubius),
contentDescription = null,
contentScale = ContentScale.Crop
)
}
Text(
text = "EL RUBIUS" ,
fontSize = 24.sp,
color = Color.White,
modifier = Modifier.padding(10.dp)
)
}
}
@Composable fun profileIcon(myPainter: Painter){
Icon(
modifier = Modifier
.height(30.dp)
.width(30.dp),
painter = myPainter,
contentDescription = null
)
}
@Composable
fun profileIconButton(){
IconButton(
onClick = { /*TODO*/ },
modifier = Modifier
.width(100.dp)
.height(100.dp)
)
{
Icon(
modifier = Modifier
.width(20.dp)
.height(20.dp),
painter = painterResource(id = R.drawable.icontriangle),
contentDescription = null
)
}
}
@Composable
fun divider(){
Box(
modifier = Modifier
.fillMaxWidth()
.height(1.dp)
.background(Color(0xFFD8d8d8))
){
}
} |
<?php
/*declare(strict_types=1);*/
namespace Hleb\Reference;
use Hleb\Constructor\Attributes\Accessible;
use Hleb\Constructor\Attributes\AvailableAsParent;
use Hleb\Constructor\Data\DynamicParams;
use Hleb\Constructor\Data\SystemSettings;
use Hleb\Main\Insert\ContainerUniqueItem;
use Hleb\Static\Request;
use Hleb\Static\Session;
/**
*
* Provides methods for accessing the framework's system settings.
* Wrapper class over:
*
* Предоставляет методы для обращения к системным параметрам фреймворка.
* Класс-обёртка над:
*
* @see SystemSettings
* @see DynamicParams
*/
#[Accessible] #[AvailableAsParent]
class SettingReference extends ContainerUniqueItem implements SettingInterface, Interface\Setting
{
/** @inheritDoc */
#[\Override]
public function isStandardMode(): bool
{
return SystemSettings::isStandardMode();
}
/** @inheritDoc */
#[\Override]
public function isAsync(): bool
{
return SystemSettings::isAsync();
}
/** @inheritDoc */
#[\Override]
public function isCli(): bool
{
return SystemSettings::isCli();
}
/** @inheritDoc */
#[\Override]
public function isDebug(): bool
{
return DynamicParams::isDebug();
}
/** @inheritDoc */
#[\Override]
public function getRealPath(string $keyOrPath): false|string
{
return SystemSettings::getRealPath($keyOrPath);
}
/** @inheritDoc */
#[\Override]
public function getPath(string $keyOrPath): false|string
{
return SystemSettings::getPath($keyOrPath);
}
/** @inheritDoc */
#[\Override]
public function isEndingUrl(): bool
{
return DynamicParams::isEndingUrl();
}
/** @inheritDoc */
#[\Override]
public function getParam(string $name, string $key): mixed
{
return SystemSettings::getValue($name, $key);
}
/** @inheritDoc */
#[\Override]
public function common(string $key): mixed
{
return $this->getParam('common', $key);
}
/** @inheritDoc */
#[\Override]
public function main(string $key): mixed
{
return $this->getParam('main', $key);
}
/** @inheritDoc */
#[\Override]
public function database(string $key): mixed
{
return $this->getParam('database', $key);
}
/** @inheritDoc */
#[\Override]
public function system(string $key): mixed
{
return $this->getParam('system', $key);
}
/** @inheritDoc */
#[\Override]
public function getModuleName(): ?string
{
return DynamicParams::getModuleName();
}
/** @inheritDoc */
#[\Override]
public function getControllerMethodName(): ?string
{
return DynamicParams::getControllerMethodName();
}
/** @inheritDoc */
#[\Override]
public function getDefaultLang(): string
{
return SystemSettings::getValue('main', 'default.lang');
}
/** @inheritDoc */
#[\Override]
public function getAutodetectLang(): string
{
$allowed = self::getAllowedLanguages();
$search = static function ($lang) use ($allowed): bool {
return $lang && \in_array(\strtolower($lang), $allowed);
};
if ($search($lang = \explode('/', \trim(Request::getUri()->getPath(), '/'))[0])) {
return $lang;
}
if ($search($lang = Request::param('lang')->value)) {
return $lang;
}
if ($search($lang = Request::get('lang')->value)) {
return $lang;
}
if ($search($lang = Request::post('lang')->value)) {
return $lang;
}
if ($search($lang = Session::get('LANG'))) {
return $lang;
}
return $this->getDefaultLang();
}
/** @inheritDoc */
#[\Override]
public function getAllowedLanguages(): array
{
return $this->getParam('main', 'allowed.languages');
}
/** @inheritDoc */
#[\Override]
public function getInitialRequest(): object
{
return DynamicParams::getDynamicOriginRequest();
}
} |
import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import InputCyan from "../../components/variants/InputCyan";
import { BACKEND } from "../VariableBck";
export const ConfirmarCorreo = () => {
const [email, setEmail] = useState("");
const [consultando, setConsultando] = useState(false);
const navigate = useNavigate();
const Swal = require("sweetalert2");
const errorAlert = () => {
Swal.fire({
icon: "error",
title: "Oops...",
text: "Algo salio mal",
});
};
const bienAlert = () => {
Swal.fire({
icon: "success",
title: "Correcto!!",
text: "Se envio un mensaje a tu correo",
showConfirmButton: false,
timer: 2000,
});
};
const ressetP = async (e) => {
e.preventDefault();
setConsultando(true);
try {
await axios.post(
BACKEND + "/api/v1/forgot-password",
{ email },
{ headers: { accept: "application/json" } }
);
bienAlert();
} catch (error) {
errorAlert();
console.log(error.response.data.errors, "error");
setEmail("");
}
setConsultando(false);
};
return (
<>
<div className="flex justify-center ">
<div className="block p-3 rounded-[5px] shadow-xl shadow-cyan-500/80 max-w-sm bg-white py-13 ">
<div className="flex min-h-full items-center justify-center pt-5 pb-5 px-4 sm:px-6 lg:px-8">
<div className="w-full max-w-md space-y-8">
<div>
<img
className="mx-auto h-40 w-min"
src="https://cdn-icons-png.flaticon.com/512/6807/6807018.png"
alt="Your Company"
/>
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">
Ingresa tu correo de confirmación
</h2>
</div>
<form className="mt-8 space-y-6" onSubmit={ressetP}>
<input type="hidden" name="remember" defaultValue="true" />
<div className="-space-y-px rounded-md shadow-sm">
<div>
<label htmlFor="email" className="sr-only">
Correo
</label>
<InputCyan
id="email"
name="email"
type="email"
required
value={email}
setvalue={setEmail}
placeholder="Correo"
minLength={5}
/>
</div>
</div>
<div className="flex flex-row justify-center space-x-4">
<div>
<button
type="submit"
id="EnviarCorreo"
disabled={consultando}
className="bg-sky-700 hover:bg-sky-900 text-white font-medium py-1 px-3 rounded-[3px] mr-1"
>
{consultando ? "Enviando..." : "Enviar"}
</button>
</div>
<button
onClick={() => {
navigate("/");
}}
disabled={consultando}
className="bg-sky-700 hover:bg-sky-900 text-white font-medium py-1 px-3 rounded-[3px]"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
className="w-5 h-5"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M11.25 9l-3 3m0 0l3 3m-3-3h7.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</>
);
}; |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Register</title>
<!--/*/ <th:block th:include="fragments/header:: head"></th:block> /*/-->
</head>
<body>
<div class="container">
<h2 th:text="#{reg.header}"></h2>
<a href="?lang=en" th:text="#{lang.eng}"></a> | <a href="?lang=ru" th:text="#{lang.rus}"></a>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" th:text="#{reg.title}"></h3>
</div>
<div class="panel-body">
<ul>
<li th:each="err : ${#fields.errors('*')}" th:text="${err}" />
</ul>
<form th:action="@{/register}" th:object="${userForm}" method="post">
<div class="form-group">
<label for="username" th:text="#{reg.username}"></label>
<input type="text" class="form-control" id="username" th:placeholder="#{reg.username}" th:field="*{username}" th:required="required"/>
<div th:if="${#fields.hasErrors('username')}" th:errors="*{username}" class="alert alert-danger" role="alert"></div>
</div>
<div class="form-group">
<label for="email" th:text="#{reg.email}">Email</label>
<input type="email" class="form-control" id="email" th:placeholder="#{reg.email}" th:field="*{email}" th:required="required"/>
<div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="alert alert-danger" role="alert"></div>
</div>
<div class="form-group">
<label for="password" th:text="#{reg.password}"></label>
<input type="password" class="form-control" id="password" th:placeholder="#{reg.password}" th:field="*{password}" th:required="required"/>
<div th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="alert alert-danger" role="alert"></div>
</div>
<div class="form-group">
<label for="matchingPassword" th:text="#{reg.passConfirm}"></label>
<input type="password" class="form-control" id="matchingPassword" th:placeholder="#{reg.passConfirm}" th:field="*{matchingPassword}" th:required="required"/>
<div th:if="${#fields.hasErrors('matchingPassword')}" th:errors="*{matchingPassword}" class="alert alert-danger" role="alert"></div>
</div>
<div class="btn-group" role="group">
<button type="submit" class="btn btn-default" th:text="#{reg.button}"></button>
<button type="button" class="btn btn-default" th:text="#{login.button}" onclick="location.href='/login';" ></button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html> |
package _02_control_statement;
import java.util.ArrayList;
import java.util.List;
// import = ctrl + alt + O
public class Loop {
public static void main(String[] args) {
// 기본 for문
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
int i = 1;
System.out.println("while문");
while (i <= 10) {
System.out.println(i);
i++;
}
// do-while문
// 적어도 한 번은 실행되는 반복문
System.out.println("do while문");
int j = 1;
// 일단 do를 실행
do {
System.out.println(j);
j++;
}
// 조건 검사를 나중에
while (j <= 10);
// ///// 배열과 for문 작성
// for ~each 문
String[] arr = {"A", "B", "C"}; // string 타입의 배열
// for(변수 선언: 배열){실행문}
for (String str : arr) {
System.out.println("str: " + str);
}
// arrayList
List<String> list = new ArrayList<String>(); // 리스트 중에 array list
list.add("A"); // arrayList에 추가하는 법: add() 사용
list.add("B");
list.add("C"); // list = ["A","B","C"]
for (String str : list) {
System.out.println("list str: " + str);
}
// for each with lamda(익명함수! ()->{} )
// 알아서 type 추론
list.forEach(data -> System.out.println("data: " + data));
}
} |
<!DOCTYPE html>
<html lang="ru">
<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>WebStudio</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css"
integrity="sha512-wpPYUAdjBVSE4KJnH1VR1HeZfpl1ub8YT/NKx4PuQ5NmX2tKuGu6U/JRp5y+Y8XG2tV+wKQpNHVUX03MfMFn9Q=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<header class="header">
<div class="container">
<nav class="navigation">
<a class="logo-img link" href=""
><span class="logo-accent">Web</span>Studio</a
>
<ul class="nav-list list">
<li class="nav-list-item">
<a class="nav-link link current" href="./index.html">Студия</a>
</li>
<li class="nav-list-item">
<a class="nav-link link" href="./portfolio.html">Портфолио</a>
</li>
<li class="nav-list-item">
<a class="nav-link link" href="">Контакты</a>
</li>
</ul>
</nav>
<ul class="contact-list list">
<li class="contact-list-item">
<a
class="contact-mail contacts link"
href="mailto:[email protected]"
>[email protected]</a
>
</li>
<li class="contact-list-item">
<a class="contact-number contacts link" href="tel:+380961111111"
>+38 096 111 11 11</a
>
</li>
</ul>
</div>
</header>
<main>
<!-- Hero -->
<section class="hero">
<div class="container">
<h1 class="hero-title">
Эффективные решения <br>для вашего бизнеса </rb>
</h1>
<button class="modal-btn btn" type="button">Заказать услугу</button>
</div>
</section>
<!--Особенности-->
<section class="specifics">
<div class="container">
<h2 class="section-title">Особенности</h2>
<ul class="section-list list">
<li class="item">
<h3 class="section-subtitle">Внимание к деталям</h3>
<p class="section-description">
Идейные соображения, а также начало повседневной работы по
формированию позиции.
</p>
</li>
<li class="item">
<h3 class="section-subtitle">Пунктуальность</h3>
<p class="section-description">
Задача организации, в особенности же рамки и место обучения
кадров влечет за собой.
</p>
</li>
<li class="item">
<h3 class="section-subtitle">Планирование</h3>
<p class="section-description">
Равным образом консультация с широким активом в значительной
степени обуславливает.
</p>
</li>
<li class="item">
<h3 class="section-subtitle">Современные технологии</h3>
<p class="section-description">
Значимость этих проблем настолько очевидна, что реализация
плановых заданий.
</p>
</li>
</ul>
</section>
<!-- Чем мы занимаемся -->
<section class="work">
<div class="container">
<h2 class="section-title">Чем мы занимаемся</h2>
<ul class="section-list list">
<li class="item">
<img src="./images/code.jpg" width="370" alt="Пишем сайты" />
</li>
<li class="item">
<img
src="./images/design.jpg"
width="370"
alt="Составляем дизайн"
/>
</li>
<li class="item">
<img
src="./images/applications.jpg"
width="370"
alt="Создаем приложения"
/>
</li>
</ul>
</div>
</section>
<!--Наша команда-->
<section class="team">
<div class="container">
<h2 class="section-title">Наша команда</h2>
<ul class="team-list list">
<li class="team-list-item">
<img src="./images/team1.jpg" width="270" alt="Игорь Демьяненко" />
<div class="team-content">
<h3 class="team-subtitle">Игорь Демьяненко</h3>
<p class="team-description" lang="en">Product Designer</p>
</div>
</li>
<li class="team-list-item">
<img src="./images/team2.jpg" width="270" alt="Ольга Репина" />
<div class="team-content">
<h3 class="team-subtitle">Ольга Репина</h3>
<p class="team-description" lang="en">Frontend Developer</p>
</div>
</li>
<li class="team-list-item">
<img src="./images/team3.jpg" width="270" alt="Николай Тарасов" />
<div class="team-content">
<h3 class="team-subtitle">Николай Тарасов</h3>
<p class="team-description" lang="en">Marketing</p>
</div>
</li>
<li class="team-list-item">
<img src="./images/team4.jpg" width="270" alt="Михаил Ермаков" />
<div class="team-content">
<h3 class="team-subtitle">Михаил Ермаков</h3>
<p class="team-description" lang="en">UI Designer</p>
</div>
</li>
</ul>
</div>
</section>
</main>
<footer class="footer">
<div class="container">
<a class="footer-logo-img link" href=""
><span class="logo-accent">Web</span>Studio</a
>
<address class="footer-addres">г. Киев, пр-т Леси Украинки, 26</address>
<a class="footer-contact link" href="mailto:[email protected]"
>[email protected]</a
>
<a class="footer-contact link" href="tel:+380961111111"
>+38 096 111 11 11</a
>
</div>
</footer>
</body>
</html> |
/*
* Copyright 2014 Hogeschool Leiden.
*
* 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 nl.hsleiden.webapi.util;
import java.util.List;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import nl.hsleiden.webapi.model.Employees;
import nl.hsleiden.webapi.model.Persons;
import nl.hsleiden.webapi.model.Students;
import nl.hsleiden.webapi.model.UpdatedGradeStudent;
/**
*
* @author hl
*/
@XmlRootElement(name="results")
@XmlSeeAlso({Students.class, Employees.class, UpdatedGradeStudent.class, Persons.class})
public class Result<T> {
private List<T> results;
private String previous;
private String next;
private String total;
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
@XmlMixed
public List<T> getResults() {
return results;
}
public void setResults(List<T> results) {
this.results = results;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
} |
//packages needed throughout the code
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';
//main - runs the app
void main() {
runApp(const MyApp());
}
// This widget is the home page of my application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
//creates the header of the page
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
//get day and format it using the provided function from the package
DateTime now = new DateTime.now();
String formattedDate = DateFormat('EEEE, d MMMM yyyy').format(now);
//title
return MaterialApp(
title: 'DailyLou',
//theme of the page
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
//Formatted date and puts at the top of the page
home: MyHomePage(title: formattedDate),
);
}
}
//formats the home page
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
//app bar title
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
//the body - cals MyWidget after creating a padding for visual aesthetic
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(10),
height: MediaQuery.of(context).size.height,
child: MyWidget(),
),
),
);
}
}
//main widget which calls the big widget of YourWidget
class MyWidget extends StatefulWidget {
@override
_YourWidgetState createState() => _YourWidgetState();
}
//class that deals with the bulk of the news
class _YourWidgetState extends State<MyWidget> {
List<Map<String, dynamic>> articleList = [];
//puts articles in when app is initiallly loaded
@override
void initState() {
super.initState();
// Fetch news data when the widget is created
fetchNews();
}
//function to refreshNews
Future<void> _refreshNews() async {
// Clear current list so it resets each time that this is called
articleList.clear();
//waits for fetchnews to run
await fetchNews();
}
//this displays the news
@override
Widget build(BuildContext context) {
return Scaffold(
//this deals with refreshing the page by scrolling up
resizeToAvoidBottomInset: false,
body: RefreshIndicator(
onRefresh: _refreshNews,
//content of the page
child: Column(
children: [
//if the article is empty show the centered loading symbol
if (articleList.isEmpty)
Center(
child: CircularProgressIndicator(),
)
//else, display the articles
else
Container(
//the height of displaying the articles
height: MediaQuery.of(context).size.height * 0.8,
//the actual displaying of the articles in a List View form
child: ListView.builder(
itemCount: articleList.length,
itemBuilder: (context, index) {
final article = articleList[index];
//return the ListTile so that app can see when user wants to open the url
return ListTile(
title: GestureDetector(
onTap: () {
launch(article[
'url']); // Uses the url from the article to launch a URL
},
//text of the title of the article with hyperlink (designs hyperlink to appear as hyperlinks usually do)
child: Text(
article['title'] ?? '',
style: TextStyle(
decoration: TextDecoration
.underline, // Underline the text to indicate it's clickable
color: Colors
.blue, // Set the color to blue for a typical hyperlink color
// fontWeight: FontWeight.bold,
),
),
),
subtitle: Text(article['content'] ?? ''),
);
},
),
),
],
),
),
);
}
//creates the list of articles to be printed
Future<void> fetchNews() async {
//clears current list so it resets each time that this is called
articleList.clear();
//api key and apiurl
final String apiKey = '9584d63c6dac4bb39619866cc53402fc';
final String apiUrl =
'https://newsapi.org/v2/top-headlines?country=us&apiKey=$apiKey';
//searches for the api
try {
final response = await http.get(Uri.parse(apiUrl));
if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
// If there are articles, Extract and process up to 8 articles
if (data.containsKey('articles')) {
final List<dynamic> articles = data['articles'];
// Shuffle the list of articles so they aren't ordered
articles.shuffle();
// Take the first 8 articles (randomly shuffled)
final List<dynamic> randomArticles = articles.take(8).toList();
//for loop going through the articles to add them to articleList
for (var article in randomArticles) {
final String title = article['title'];
final String source = article['source']['name'];
final String url = article['url'];
//only add article to the list if there is content
if (title != "[Removed]" &&
source != "[Removed]" &&
url != "[Removed]") {
articleList.add(article);
}
}
//sets state so the app knows to update
setState(() {});
}
//else print error
else {
print('No articles key in the response.');
}
}
//else print error
else {
print('Error: ${response.statusCode} - ${response.body}');
}
}
//this catches the error if the try did not work
catch (e) {
print('An error occurred: $e');
}
}
} |
import 'package:dundaser/models/categories.dart';
import 'package:dundaser/screens/filters.dart';
import 'package:dundaser/widgets/app_bar.dart';
import 'package:dundaser/widgets/drinks_list.dart';
import 'package:dundaser/widgets/main_drawer.dart';
import 'package:flutter/material.dart';
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
@override
State<MainScreen> createState() => _MainScreenState();
}
//This is the homepage of the app where user can navigate to other screens
//or add a new drink review
class _MainScreenState extends State<MainScreen> {
List<Categories>? _selectedCategories;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
// floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
// floatingActionButton: IconButton(
// color: Theme.of(context).colorScheme.primary,
// iconSize: 50,
// onPressed: () {
// Navigator.of(context).push(
// MaterialPageRoute(builder: (ctx) => const AddDrinkScreen()));
// },
// icon: const Icon(Icons.add),
// ),
drawer: const MainDrawer(),
appBar: const CustomAppBar(
title: 'Home Page',
),
body: DrinksList(selectedCategories: _selectedCategories),
floatingActionButton: FloatingActionButton(
onPressed: () async {
var selectedCategories = await Navigator.of(context).push<List<Categories>?>(
MaterialPageRoute(
builder: (ctx) => FilterScreen(
selectedCategories: _selectedCategories,
onApplyFilters: (selectedCategories) {
setState(() {
_selectedCategories = selectedCategories;
});
},
),
),
);
if (selectedCategories != null) {
setState(() {
selectedCategories = selectedCategories;
});
}
},
child: const Icon(Icons.filter_list),
),
);
}
} |
#include "src/FreeRTOS/Arduino_FreeRTOS.h"
// Commands
/*
string -> "ABC"
A: D -> digital
A -> analógico
T -> período de refrescado (delay loop)
A D T
B: A -> A0 D0 10ms
B -> A1 D1 50ms
C -> A2 D2 100ms
D -> A3 D3 200ms
E -> A4 D4 300ms
F -> A5 D5 400ms
G -> A6 D6 500ms
H -> A7 D7 600ms
I -> --- D8 700ms
J -> --- D9 800ms
K -> --- D10 900ms
L -> --- D11 1000ms
M -> --- D12 1200ms
N -> --- D13 1500ms
O -> --- --- 1700ms
P -> --- --- 2000ms
Q -> --- --- 3000ms
R -> --- --- 4000ms
S -> --- --- 5000ms
T -> --- --- 7000ms
U -> --- --- 10000ms
V -> --- --- 15000ms
W -> --- --- 20000ms
X -> --- --- 30000ms
Y -> --- --- 60000ms
Z -> --- --- 120000ms
Digital:
C: 0 -> poner en bajo
1 -> poner en alto
3 -> configurar como entrada
4 -> configurar como salida
5 -> poner en estado bajo con confirmación
6 -> poner en estado alto con confirmación
Analógico:
0 -> desactivar lectura del analógico
1 -> activar lectura del analógico
*/
// JSON
int const SIZE_STROUT = 200;
char strout[] = "{\"A0\":%d,\
\"A1\":%d,\
\"A2\":%d,\
\"A3\":%d,\
\"A4\":%d,\
\"A5\":%d,\
\"A6\":%d,\
\"A7\":%d,\
\"D2\":%d,\
\"D3\":%d,\
\"D4\":%d,\
\"D5\":%d,\
\"D6\":%d,\
\"D7\":%d,\
\"D8\":%d,\
\"D9\":%d,\
\"D10\":%d,\
\"D11\":%d,\
\"D12\":%d,\
\"D13\":%d}";
char strout_s[SIZE_STROUT] = "";
/* ARDUINO STATUS */
uint8_t vD[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // valor del pin digital
int vA[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // valor del conversor analógico
uint8_t vA_active[8] = {0, 0, 0, 0, 0, 0, 0, 0}; // ADC activos
uint8_t const N_vA_POINT = 10; // número de mediciones de los conversores a promediar
int vA_point[8][N_vA_POINT]; // mediciones de los conversores
bool status_changed = false; // True si ha cambiado el valor del estado del arduino
bool status_force_send = false; // Forzar enviar el estado del Arduino por puerto serie
uint8_t confirm_cycles[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // ciclos restantes de confirmación por pin digital
uint8_t confirm_cycles_max = 15; // Máximo número de ciclos de confirmación
int pin;
unsigned long delay_loop = 1000; // Tiempo de retardo del loopRefresh.
/*TASK MEMORY CONFIGURATION*/
#define STACK_SIZE_SEND_STATUS 100
StaticTask_t xTaskBufferSendStatus;
StackType_t xStackSendStatus[ STACK_SIZE_SEND_STATUS ];
#define STACK_SIZE_LOOP_REFRESH 40
StaticTask_t xTaskBufferLoopRefresh;
StackType_t xStackLoopRefresh[ STACK_SIZE_LOOP_REFRESH ];
#define STACK_SIZE_UPDATE_DIGITAL 40
StaticTask_t xTaskBufferUpdateDigital;
StackType_t xStackUpdateDigital[ STACK_SIZE_UPDATE_DIGITAL ];
#define STACK_SIZE_UPDATE_ANALOGIC 56
StaticTask_t xTaskBufferUpdateAnalogic;
StackType_t xStackUpdateAnalogic[ STACK_SIZE_UPDATE_ANALOGIC ];
#define STACK_SIZE_CHECK_SERIAL 56
StaticTask_t xTaskBufferCheckSerial;
StackType_t xStackCheckSerial[ STACK_SIZE_CHECK_SERIAL ];
void setup() {
Serial.begin(9600); // Configuración del puerto serie
analogReference(INTERNAL); // 1.1 volt
// Create task that publish data in the queue if it was created.
xTaskCreateStatic(updateDigitalPort, // Task function
"UpdateDigital", // Task name
STACK_SIZE_UPDATE_DIGITAL, // Stack size
NULL,
1, // Priority
xStackUpdateDigital,
&xTaskBufferUpdateDigital);
xTaskCreateStatic(updateAnalogicPort, // Task function
"UpdateAnalogic", // Task name
STACK_SIZE_UPDATE_ANALOGIC, // Stack size
NULL,
1, // Priority
xStackUpdateAnalogic,
&xTaskBufferUpdateAnalogic);
xTaskCreateStatic(loopRefresh, // Task function
"LoopRefresh", // Task name
STACK_SIZE_LOOP_REFRESH, // Stack size
NULL,
1, // Priority
xStackLoopRefresh,
&xTaskBufferLoopRefresh);
xTaskCreateStatic(sendStatus, // Task function
"SendStatus", // Task name
STACK_SIZE_SEND_STATUS, // Stack size
NULL,
1, // Priority
xStackSendStatus,
&xTaskBufferSendStatus);
xTaskCreateStatic(checkSerial, // Task function
"CheckSerial", // Task name
STACK_SIZE_CHECK_SERIAL, // Stack size
NULL,
1, // Priority
xStackCheckSerial,
&xTaskBufferCheckSerial);
}
void loop() {}
void updateDigitalPort(void *pvParameters) {
/*
* Leer todos los puertos digitales y si se han modificados notificar
* para que sean enviado por puerto serie.
*/
int pin;
for (;;) {
for (uint8_t i = 2; i < 14; i++){
pin = digitalRead(i);
if (vD[i] != pin){
vD[i] = pin;
status_changed = true;
}
}
vTaskDelay(1);
}
}
void updateAnalogicPort(void *pvParameters) {
/*
* Leer constantemente los puertos analógicos marcados como activos.
*/
for (uint8_t i_port = 0; i_port < 8; i_port++){
for (uint8_t i_point = 0; i_point < N_vA_POINT; i_point++){
vA_point[i_port][i_point] = analogRead(A0 + i_port);
}
}
uint8_t i_buff = 0;
int sum = 0;
for (;;) {
i_buff ++;
if (i_buff == N_vA_POINT)
i_buff = 0;
int sum = 0;
int average;
for (uint8_t i = 0; i < 8; i++){
if (!vA_active[i]){
vA[i] = -1;
continue;
}
vA_point[i][i_buff] = analogRead(A0 + i);
// average of analogic port i
for (uint8_t i_ave = 0; i_ave < N_vA_POINT; i_ave ++)
sum += vA_point[i][i_ave];
vA[i] = sum / N_vA_POINT;
}
vTaskDelay(10);
}
}
void loopRefresh(void *pvParameters) {
/*
* Ejecutar algunos procedimientos periódicamente:
* - Forzar el envío del estado de los puertos del Arduino
* - Refrescar la rutina de verificación de los pines digitales
* que necesitan confirmación para mantener su estado.
*
* NOTA: El período que se ejecuta el refrescado es configurable
* a por comandos por puerto serie.
*/
for (;;) {
// Forzar el envío del estado del Arduino.
if (!status_force_send){
status_force_send = true;
}
// Verificar los pines con confirmación
for (int i = 2; i < 14; i++){
if (confirm_cycles[i]){
confirm_cycles[i]--;
if (confirm_cycles[i])
continue;
// Invertir estado del pin
if (digitalRead(i))
digitalWrite(i, LOW);
else
digitalWrite(i, HIGH);
}
}
vTaskDelay( delay_loop / portTICK_PERIOD_MS );
}
}
void sendStatus(void *pvParameters) {
/*
* Enviar por puerto serie el estado de los puertos del Arduino
* Se envía periódicamente marcado por la función loopRefresh o cuando un puerto digital cambia su estado.
*/
for (;;)
{
while (!status_changed && !status_force_send) {
vTaskDelay(3);
}
sprintf(strout_s, strout, vA[0], vA[1], vA[2], vA[3], vA[4], vA[5], vA[6], vA[7], vD[2], vD[3], vD[4], vD[5], vD[6], vD[7], vD[8], vD[9], vD[10], vD[11], vD[12], vD[13]);
Serial.println(strout_s);
status_changed = false;
status_force_send = false;
}
}
void checkSerial(void *pvParameters) {
/*
* Chequear el puerto serie.
* Capturar el comando y ejecutar el comando.
*/
char incomingString[5];
for (;;) {
//Capturar los 4 caracteres de comando por el puerto serie
for ( uint8_t i = 0; i < 4; i++) {
while (Serial.available() == 0) {
vTaskDelay(6);
}
Serial.readBytes(&incomingString[i], 1);
if (incomingString[i] == '\n')
break;
}
if (incomingString[3] != '\n')
continue;
incomingString[3] = '-';
// Analógico
if (incomingString[0] == 'A' || incomingString[0] == 'a'){
if (incomingString[2] == '1')
activeAnalogic(incomingString[1], 1);
if (incomingString[2] == '0')
activeAnalogic(incomingString[1], 0);
}
// Digital
if (incomingString[0] == 'D' || incomingString[0] == 'd'){
// Poner en bajo
if (incomingString[2] == '0'){
pin = str2pin(incomingString[1]);
digitalWrite(pin, LOW);
confirm_cycles[pin] = 0;
}
// Poner en alto
if (incomingString[2] == '1'){
pin = str2pin(incomingString[1]);
digitalWrite(pin, HIGH);
confirm_cycles[pin] = 0;
}
// Poner en estado bajo con confirmación
if (incomingString[2] == '5'){
pin = str2pin(incomingString[1]);
digitalWrite(pin, LOW);
confirm_cycles[pin] = confirm_cycles_max;
}
// Poner en estado alto con confirmación
if (incomingString[2] == '6'){
pin = str2pin(incomingString[1]);
digitalWrite(pin, HIGH);
confirm_cycles[pin] = confirm_cycles_max;
}
// Poner como entrada
if (incomingString[2] == '3')
pinMode(str2pin(incomingString[1]), INPUT);
// Poner como salida
if (incomingString[2] == '4')
pinMode(str2pin(incomingString[1]), OUTPUT);
}
// Período
if (incomingString[0] == 'T' || incomingString[0] == 't'){
// Ajustar el período
delay_loop = str2delay_time(incomingString[1]);
}
vTaskDelay(5);
}
}
void activeAnalogic(char an, uint8_t active){
/*
Activa o desactiva la lectura del puento analógico
Parámetros:
-----------
an : char
Pin analógico a desactivar ('A', 'B', ...)
active : uint8_t
Activar o desactivar el puerto. 1: activar, 0: desactivar
*/
switch (an) {
case 'A':
vA_active[0] = active;
break;
case 'B':
vA_active[1] = active;
break;
case 'C':
vA_active[2] = active;
break;
case 'D':
vA_active[3] = active;
break;
case 'E':
vA_active[4] = active;
break;
case 'F':
vA_active[5] = active;
break;
case 'G':
vA_active[6] = active;
break;
case 'H':
vA_active[7] = active;
break;
}
}
int str2pin(char c){
switch (c) {
case 'A': case 'a':
return 0;
break;
case 'B': case 'b':
return 1;
break;
case 'C': case 'c':
return 2;
break;
case 'D': case 'd':
return 3;
break;
case 'E': case 'e':
return 4;
break;
case 'F': case 'f':
return 5;
break;
case 'G': case 'g':
return 6;
break;
case 'H': case 'h':
return 7;
break;
case 'I': case 'i':
return 8;
break;
case 'J': case 'j':
return 9;
break;
case 'K': case 'k':
return 10;
break;
case 'L': case 'l':
return 11;
break;
case 'M': case 'm':
return 12;
break;
case 'N': case 'n':
return 13;
break;
}
}
int str2delay_time(char c){
switch (c) {
case 'A': case 'a':
return 10;
break;
case 'B': case 'b':
return 50;
break;
case 'C': case 'c':
return 100;
break;
case 'D': case 'd':
return 200;
break;
case 'E': case 'e':
return 300;
break;
case 'F': case 'f':
return 400;
break;
case 'G': case 'g':
return 500;
break;
case 'H': case 'h':
return 600;
break;
case 'I': case 'i':
return 700;
break;
case 'J': case 'j':
return 800;
break;
case 'K': case 'k':
return 900;
break;
case 'L': case 'l':
return 1000;
break;
case 'M': case 'm':
return 1200;
break;
case 'N': case 'n':
return 1500;
break;
case 'O': case 'o':
return 1700;
break;
case 'P': case 'p':
return 2000;
break;
case 'Q': case 'q':
return 3000;
break;
case 'R': case 'r':
return 4000;
break;
case 'S': case 's':
return 5000;
break;
case 'T': case 't':
return 7000;
break;
case 'U': case 'u':
return 10000;
break;
case 'V': case 'v':
return 15000;
break;
case 'W': case 'w':
return 20000;
break;
case 'X': case 'x':
return 30000;
break;
case 'Y': case 'y':
return 60000;
break;
case 'Z': case 'z':
return 120000;
break;
}
} |
#!/usr/bin/env python3
"""Firaol Tulu Task 12: Type Checking
"""
from typing import List, Tuple
def zoom_array(lst: Tuple, factor: int = 2) -> List:
"""This Function Creates multiple copies of items in a tuple."""
zoomed_in: List = [item for item in lst for i in range(factor)]
return zoomed_in
array = (12, 72, 91)
zoom_2x = zoom_array(array)
zoom_3x = zoom_array(array, 3) |
import 'package:flutter/material.dart';
import 'package:kridaverse_e_commerce/APIS/apis.dart';
import 'package:kridaverse_e_commerce/Custom%20Widgets/eleveted_button.dart';
import 'package:kridaverse_e_commerce/Theme/appColor.dart';
import 'package:kridaverse_e_commerce/main.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: AppColor().darkGrey,
title: Text(
'Perfile',
style: TextStyle(color: AppColor().white),
),
),
body: Container(
height: mq.height * 1,
width: mq.width * 1,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
height: mq.height * .25,
width: mq.width * 1,
color: AppColor().blue,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
CircleAvatar(
radius: mq.width * 0.16,
backgroundImage: NetworkImage(Apis.me.img),
)
],
)),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Name',
style: TextStyle(color: AppColor().purple, fontSize: 18),
),
Text(
Apis.me.name,
style: TextStyle(color: AppColor().black, fontSize: 22),
)
],
),
),
SizedBox(
height: mq.height * .03,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Email',
style: TextStyle(color: AppColor().purple, fontSize: 18),
),
Text(
Apis.me.email,
style: TextStyle(color: AppColor().black, fontSize: 22),
)
],
),
),
SizedBox(
height: mq.height * .03,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Phone',
style: TextStyle(color: AppColor().purple, fontSize: 18),
),
Text(
Apis.me.phone == null ? Apis.me.phone : 'N/A',
style: TextStyle(color: AppColor().black, fontSize: 22),
)
],
),
),
SizedBox(
height: mq.height * .2,
),
Container(
padding: EdgeInsets.symmetric(horizontal: 20),
width: mq.width * 0.4,
child: ElevatedButton(
onPressed: () async {
await Apis().logoutFromDevice(context);
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(AppColor().black),
shape: MaterialStatePropertyAll(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)))),
child: Text(
'Logout',
style: TextStyle(color: AppColor().white),
),
),
)
],
),
),
);
}
} |
import React from 'react';
import { useState } from 'react';
import './App.css';
function App() {
const [todos,setToDos] = useState([])
const [todo,setToDo] = useState('')
return (
<div className="app">
<div className="mainHeading">
<h1>ToDo List</h1>
</div>
<div className="subHeading">
<br />
<h2>Whoop, it's Wednesday 🌝 ☕ </h2>
</div>
<div className="input">
<input value={todo} onChange={(e)=>setToDo(e.target.value)} type="text" placeholder="🖊️ Add item..." />
<i onClick={()=>setToDos([...todos,{id:Date.now(),text:todo,status:false}])} className="fas fa-plus"></i>
</div>
<div className="todos">
{ todos.map((obj)=>{
return (<div className="todo">
<div className="left">
<input onChange={(e)=>{
console.log(e.target.checked)
console.log(obj)
setToDos(todos.filter(obj2=>{
if(obj2.id===obj.id)
{
obj2.status=e.target.checked
}
return obj2
}))
}} value = {obj.status} type="checkbox" name="" id="" />
<p>{obj.text}</p>
</div>
<div className="right">
<i id={obj.id} className="fas fa-times" onClick={(e)=>{
let index= todos.findIndex(obj=>{return obj.id==e.target.id})
if (index !== -1) {
todos.splice(index, 1);
setToDos([...todos]);
}
}}>
</i>
</div>
</div>)
}) }
//to print active to dos
{todos.map((obj)=>{
if(obj.status)
{
return(<h1>{obj.text}</h1>)
}
return null
})}
</div>
</div>
);
}
export default App; |
import React, { createContext, useContext, useState } from "react"
const ResultContext = createContext();
const baseUrl = 'https://google-search3.p.rapidapi.com/api/v1'
export const ResultContextProvider = ({ children }) => {
const [results, setResults] = useState([])
const [isLoading, setIsLoading] = useState(false)
const [searchTerm, setSearchTerm] = useState('Elon musk')
const getResult = async (type) => {
setIsLoading(true)
const response = await fetch(`${baseUrl}${type}`, {
method: 'GET',
headers: {
'X-User-Agent': 'desktop',
'X-Proxy-Location': 'EU',
'X-RapidAPI-Host': 'google-search3.p.rapidapi.com',
'X-RapidAPI-Key': process.env.my_api_key
}
})
const data = await response.json()
if(type.includes("/news")){
setResults(data.entries)
} else if(type.includes("/image")){
setResults(data.image_results)
} else {
setResults(data.results)
}
setIsLoading(false)
}
return (
<ResultContext.Provider value={{ getResult, results, setSearchTerm, searchTerm, isLoading }}>
{children}
</ResultContext.Provider>
)
}
export const useResultContext = () => useContext(ResultContext); |
import { makeAutoObservable } from 'mobx';
import { RootStore } from '.';
import { FiltersRequest } from '../api';
export type FilterStatePreset = {
name: string;
filter: FiltersRequest['filters'];
};
export class PresetStore {
rootStore: RootStore;
showSaveFilterModal = false;
presetInputValue = '';
presetError?: string;
presets: FilterStatePreset[] = [];
activePreset?: string;
showAllPresets = false;
constructor(rootStore: RootStore) {
makeAutoObservable(this);
this.rootStore = rootStore;
}
setShowSaveFilterModal(value: boolean) {
this.showSaveFilterModal = value;
if (!value) {
this.presetInputValue = '';
this.presetError = undefined;
}
}
setPresetInputValue(value: string) {
this.presetInputValue = value;
this.presetError = undefined;
}
setShowAllPresets(value: boolean) {
this.showAllPresets = value;
}
loadPresets() {
this.presets = JSON.parse(localStorage.getItem('savedFilters__roads') || '[]');
}
savePresets() {
localStorage.setItem('savedFilters__roads', JSON.stringify(this.presets));
}
addPreset() {
const name = this.presetInputValue;
if (name.length < 1) {
this.presetError = 'Введите название для фильтрации';
return;
}
if (this.presets.some((preset) => preset.name === name)) {
this.presetError = 'Фильтрация с таким названием уже существует';
return;
}
// const newPresets = [{ name, filter: request.filters }, ...this.presets];
// localStorage.setItem('savedFilters__roads', JSON.stringify(newPresets));
this.presets.unshift({ name, filter: this.rootStore.roadsStore.requestFilters });
this.savePresets();
// this.setPresets(newPresets);
// this.setShowSaveFilterModal(false);
// this.setActivePreset(name);
// this.presets = newPresets;
this.showSaveFilterModal = false;
this.activePreset = name;
}
activatePreset(name: string) {
const preset = this.presets.find((preset) => preset.name === name);
if (!preset?.filter) return;
this.activePreset = name;
this.rootStore.roadsStore.stateFilters = preset.filter;
this.rootStore.roadsStore.loadFilter();
}
removeActivePreset(name?: string) {
name ||= this.activePreset;
if (name === undefined) return;
const index = this.presets.findIndex((preset) => preset.name === name);
// const newPresets = [...this.presets.slice(0, index), ...this.presets.slice(index + 1)];
// localStorage.setItem('savedFilters__roads', JSON.stringify(newPresets));
this.presets.splice(index, 1);
this.savePresets();
// this.setPresets(newPresets);
// this.setActivePreset();
// this.presets = newPresets;
this.activePreset = undefined;
this.rootStore.roadsStore.clearFilter();
}
get showPresets() {
return this.showAllPresets || this.presets.length < 5 ? this.presets : this.presets.slice(0, 3);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.