Que fórmula posso usar em regras que podem realizar o seguinte:
Se houver texto em AA5 e Y5 estiver EM BRANCO, então a célula correspondente de (D5 a I14) ao número na célula W5 será destacada em verde
Semelhante a:
=(AA5<>"")*(Y5="")
Tenho um monte de sobrecargas de funções, consistindo principalmente em duas assinaturas:
void func(const my_type1&);
void func(const my_type2&, hash_t);
e uma função que tenta chamar func com base na existência da função:
template <typename T>
void func_imp(const T& t, hash_t hash){
if constexpr (has_func_with_2nd_param_v<T>){
func(t, hash);
}else{
func(t);
}
}
mas estou tendo problemas de conversão que acabam chamando a sobrecarga 'errada':
#include <type_traits>
#include <cstdio>
struct hash_t{
};
struct my_type1{
my_type1() {}
};
struct my_type2{
my_type2() {}
my_type2(const my_type1&){}
};
void func(const my_type1&){
printf("no hash\n");
}
void func(const my_type2&, hash_t=hash_t()){
printf("hash\n");
}
template<typename T, typename = void>
struct has_func_with_2nd_param : std::false_type {};
template<typename T>
struct has_func_with_2nd_param<T, std::void_t<decltype(func(std::declval<T>(), std::declval<hash_t>()))>> : std::true_type {};
template<typename T>
constexpr bool has_func_with_2nd_param_v = has_func_with_2nd_param<T>::value;
// I want to route to the appropriate function without conversion routing to the wrong func
template <typename T>
void func_imp(const T& t, hash_t hash){
if constexpr (has_func_with_2nd_param_v<T>){
func(t, hash);
}else{
func(t);
}
}
int main()
{
// this is true as expected
static_assert(has_func_with_2nd_param_v<my_type2>);
// this is also true, since my_type2 is constructable from my_type1 and then finds finds func(my_type2, hash_t)
static_assert(has_func_with_2nd_param_v<my_type1>);
func_imp(my_type1(), hash_t()); // prints "hash", but wanting it to call the "no hash" version
func_imp(my_type2(), hash_t()); // prints "hash"
return 0;
}
Estou com dificuldades para encontrar a metafunção correta para obter o comportamento desejado. Alguém tem alguma ideia?
godbolt aqui
Tenho duas caixas Rust lib1
e lib2
, para as quais uso pyo3
para gerar ligações. Importo a caixa lib1
em lib2
.
Em um crape separado lib1-py
, crio uma classe python MyClass
e, em lib2
, tento usar MyClass
como parâmetro para uma função Python, usando:
fn foo(param: PyRef<MyClass>)
Eu uso separadamente maturin
para construir ambos lib1-py
no lib2
mesmo ambiente.
Quando tento executar o código python:
import lib1
import lib2
param = lib1.MyClass()
lib2.foo(param)
Eu obtenho o erro TypeError: argument 'param': 'MyClass' object cannot be converted to ‘MyClass’
.
Suponho que o sistema de caixas do Rust tenta ser seguro, tratando tipos de caixas diferentes como entidades separadas, mesmo que sejam idênticas. Como eu poderia resolver esse problema?
Um problema para o qual procurei e procurei uma solução, sem sucesso. Instalei o módulo discord.py através do prompt de comando usando o comando
py -3 -m pip install -U discord.py
Executar novamente me dá a mensagem de que as dependências já foram satisfeitas. Verifiquei a versão do pip e a versão do python no prompt de comando para ver onde estão sendo instaladas e no terminal do VS Code, e ambas confirmam a versão 3.13.3 do Python.
Correndo:
> python
>>> help
>>> modules
exibe a lista de módulos, incluindo discord
o que está entre dis
e doctest
. Executar help> discord
exibe:
Help on package discord:
NAME
discord
DESCRIPTION
Discord API Wrapper
~~~~~~~~~~~~~~~~~~~
A basic wrapper for the Discord API.
:copyright: (c) 2015-present Rapptz
:license: MIT, see LICENSE for more details.
PACKAGE CONTENTS
(a comprehensive list of all the modules, I've checked)
SUBMODULES
async_
sync
DATA
__annotations__ = {'version_info': <class 'discord.VersionInfo'>}
__copyright__ = 'Copyright 2015-present Rapptz'
__license__ = 'MIT'
__title__ = 'discord'
version_info = VersionInfo(major=2, minor=5, micro=2, releaselevel='fi...
VERSION
2.5.2
AUTHOR
Rapptz
FILE
c:\users\MYUSER\appdata\local\programs\python\python313\lib\site-packages\discord\__init__.py
Correndo > pip show discord.py
ou > pip3 show discord.py
ambos cuspindo:
Name: discord.py
Version: 2.5.2
Summary: A Python wrapper for the Discord API
Home-page:
Author: Rapptz
Author-email:
License: The MIT License (MIT)
Copyright (c) 2015-present Rapptz
(large portion of legal text ommitted for ease of reading)
Location: C:\Users\MYUSER\AppData\Local\Programs\Python\Python313\Lib\site-packages
Requires: aiohttp, audioop-lts
Required-by:
Eu realmente tentei o que considero ser de tudo. Mas, independentemente do que aconteça, qualquer arquivo .py que eu crie sublinha em amarelo a discord
parte da linha import discord
com o erro: Import "discord" could not be resolvedPylance(reportMissingImports)
. Executar o arquivo python no VS Code gera o erro:
Traceback (most recent call last):
File "c:\Users\MYUSER\OneDrive\Documents\FOLDER_NAME\FOLDER_NAME\FILENAME.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
Se alguém tiver alguma dica sobre como resolver o problema, agradeceria muito. Agradeço desde já!
EDIT: Para adicionar uma captura de tela do IDE, aparentemente não consigo incorporar ainda, então aqui
Não consigo fazer funcionar um aplicativo Elastic Beanstalk com um ELB público, mas instâncias EC2 privadas.
Criei uma configuração básica do eb com eb init
. O resultado foi a seguinte configuração:
branch-defaults:
default:
environment: test3
group_suffix: null
global:
application_name: test
branch: null
default_ec2_keyname: null
default_platform: Node.js
default_region: us-east-1
include_git_submodules: true
instance_profile: null
platform_name: null
platform_version: null
profile: null
repository: null
sc: null
workspace_type: Application
Eu uso a VPC padrão, mas com duas sub-redes públicas personalizadas (para evitar conflitos de CIDR de peering com outra conta e um banco de dados externo).
Agora tento implantar o aplicativo eb com as seguintes opções:
# powershell
eb create --profile dev `
--sample `
--vpc.id vpc-123abc
--vpc.ec2subnets "subnet-123,subnet-456" `
--vpc.elbsubnets "subnet-123,subnet-456" `
-sr arn:aws:iam::<account>:role/service-role/aws-elasticbeanstalk-service-role `
--vpc.elbpublic `
test8
Isso não funciona. A instância inicial nunca passa nas verificações de integridade e a criação do ambiente EB é considerada uma falha após cerca de 15 minutos. Ele nunca é acessível pela internet.
NO ENTANTO, adicionar a opção --vpc.publicip
faz com que funcione! -- Consigo acessar a página da web sem problemas pela internet usando o endereço do ambiente EB. Mas não preciso de IPs públicos em cada instância. Então, o que estou perdendo?
Executei ambos os comandos com nomes de ambiente diferentes e comparei seus grupos de segurança, configurações do ELB, etc. Não encontrei nenhuma diferença. Por que essas instâncias precisam de IPs públicos para passar nas verificações de integridade e se conectar ao ELB?
Estou desenvolvendo um site de portfólio eletrônico, enquanto o construo e chego às etapas finais. Encontrei um problema com a seção do campo de entrada, onde ofereço aos empregadores a oportunidade de se conectarem comigo pelo site. No entanto, enquanto o codificava, continuo recebendo um pop-up de "e-mail inválido", mas não sei o porquê. Abaixo, forneci um trecho do código, bem como uma captura de tela da mensagem de erro de e-mail inválido, embora com meu endereço de e-mail real marcado.
import { useState, useEffect } from "react"
import "./style.css"
import BackgroundLines from "../BackgroundLines"
import ParaWriting from "../ParaWriting"
import { motion, useAnimation } from "framer-motion"
import ArrowUpRightIcon from "../../assets/Icon/arrow-up-right.svg"
import { useInView } from "react-intersection-observer"
import Button from "../Button"
import Time from "../Time"
// emailjs
import emailjs from "@emailjs/browser"
// JSON
import emailjsconfig from "../../constants/emailjs.json"
import Alert from "../Alert"
export default function Footer() {
const controls = useAnimation()
const [ref, inView] = useInView()
const [isSending, setIsSending] = useState(false)
const [sendStatus, setSendStatus] = useState({ processed: false, message: "", variant: "success" })
const [hasAnimated, setHasAnimated] = useState(false)
const [fieldValues, setFieldValues] = useState({
name: false,
email: false,
message: false,
})
const handleComplete = () => {
setHasAnimated(true)
}
useEffect(() => {
// Start animation when the component is in view
if (inView && !hasAnimated) {
controls.start("visible")
}
}, [inView, controls])
const opacityVariant = {
hidden: { opacity: 0 },
visible: { opacity: 1 },
}
const inputFieldLineVariant = {
hidden: { width: "0%" },
visible: {
width: "100%",
},
}
const inputFields = [
{
label: "Name",
type: "text",
id: "name",
placeholder: "Enter name",
stateKey: "name",
},
{
label: "Email",
type: "email",
id: "email",
placeholder: "[email protected]",
stateKey: "email",
},
{
label: "Message",
type: "textarea",
id: "message",
placeholder: "Your message",
rows: "8",
wrap: "soft",
stateKey: "message",
},
]
const handleInputClick = (stateKey) => {
setFieldValues({
...fieldValues,
[stateKey]: true,
})
}
const timeoutAlert = () =>
setTimeout(() => {
setSendStatus({ ...sendStatus, processed: false })
}, 5000)
const sendEmail = async () => {
const requiredFields = ["name", "email", "message"]
const missingFields = requiredFields.filter((field) => !fieldValues[field])
if (missingFields.length > 0) {
setSendStatus({ processed: true, variant: "error", message: "Not all fields were filled" })
timeoutAlert()
return
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(fieldValues.email)) {
setSendStatus({ processed: true, variant: "error", message: "Invalid email" })
return
}
setIsSending(true)
try {
const { serviceId, templateid, publicKey } = emailjsconfig
console.log("trigger")
const templateParams = {
name: fieldValues.name,
email: fieldValues.email,
message: fieldValues.message,
}
const response = await emailjs.send(serviceId, templateid, templateParams, publicKey)
console.log("Email sent successfully:", response)
setIsSending(false)
setSendStatus({ processed: true, variant: "success", message: "Success!" })
} catch (error) {
console.error("Error sending email:", error)
setIsSending(false)
setSendStatus({ processed: true, variant: "error", message: "Error" })
}
timeoutAlert()
}
return (
<footer ref={ref} className="footer" id="contact">
<BackgroundLines />
<div className="footer--grid">
<div className="footer--grid--heading">
<h2>
<ParaWriting stagger={0.08} text={"Get in "} sec={"touch"} />
</h2>
</div>
<div className="footer--grid--form">
{inputFields.map((field, index) => (
<motion.div key={index} initial="hidden" animate={controls} variants={opacityVariant} transition={{ duration: 1, delay: 0.5 * (index + 1) }} className="input--div">
<label htmlFor={field.id}>{field.label}</label>
{field.type === "textarea" ? <textarea name={field.id} id={field.id} placeholder={field.placeholder} rows={field.rows} wrap={field.wrap} onFocus={() => handleInputClick(field.stateKey)}></textarea> : <input type={field.type} name={field.id} id={field.id} placeholder={field.placeholder} onClick={() => handleInputClick(field.stateKey)} />}
<motion.div
initial="hidden"
animate={controls}
variants={inputFieldLineVariant}
transition={{
type: "spring",
stiffness: 20,
duration: 1,
delay: 0.5 * (index + 1),
}}
className="input--div--line"
>
<motion.div
initial="hidden"
animate={fieldValues[field.stateKey] && "visible"}
variants={inputFieldLineVariant}
transition={{
type: "spring",
stiffness: 20,
duration: 1,
}}
></motion.div>
</motion.div>
</motion.div>
))}
<motion.div initial="hidden" animate={controls} variants={opacityVariant} transition={{ duration: 1, delay: 2 }} className="footer--grid--form--btn">
<Button label={`${isSending ? "Sending it through" : "SEND MESSAGE"}`} icon={ArrowUpRightIcon} onClick={sendEmail} />
</motion.div>
</div>
</div>
<motion.div initial="hidden" animate={controls} variants={opacityVariant} transition={{ duration: 1, delay: 2.5 }} className="footer--bottom" onAnimationComplete={() => handleComplete()}>
<p>Copyright © {new Date().getFullYear()} Cameron Watkins</p>
<p>
<Time delay={3} />
</p>
<p></p>
</motion.div>
<Alert isVisible={sendStatus.processed} text={sendStatus.message} variant={sendStatus.variant} />
</footer>
)
}
Caso precise de mais informações, ficarei feliz em fornecer o repositório do GitHub. Agradeço desde já.
A fórmula que eu concateno é: Como ter a mesma informação usando Indireto?
=CONCAT('2101'!C2," - ",'2101'!C3," - ",'2101'!C4," - Admit: ",'2101'!C5)
É isso que eu uso quando não é CONCAT, mas não consegui combinar várias células com Indireto.
=IF(ISBLANK(INDIRECT("'"&B2&"'!"&"C8")),"",INDIRECT("'"&B2&"'!"&"C8"))
1) Execute o seguinte código no aplicativo Excel .
Sub Macro1()
'Delete all shapes if exists
For i = ActiveSheet.Shapes.Count To 1 Step -1
ActiveSheet.Shapes(i).Delete
Next i
'Add a Rectangle
With ActiveSheet.Shapes.AddShape(Type:=msoShapeRectangle, Left:=20, Top:=20, Width:=200, Height:=120)
.Name = "myRectangle"
End With
'Make some formatting to the myRectangle
With ActiveSheet.Shapes("myRectangle")
.Line.Visible = msoTrue
.Line.ForeColor.RGB = vbBlue
.Line.Weight = 5
.Fill.UserPicture "https://upload.wikimedia.org/wikipedia/en/b/ba/Flag_of_Germany.svg"
End With
End Sub
2) Verifique se você obteve o seguinte retângulo em sua planilha do Excel .
3) Estou procurando uma macro que me dê a seguinte imagem.
Como você pode entender, eu quero fazer algumas margens entre as bordas e a bandeira .
DateTimeFormatter
falha em Instant
s válidos. Como formatar os valores abaixo e acima LocalDateTime.MIN
e LocalDateTime.MAX
? Manualmente?
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC).format(Instant.MAX)
Primeiro, aqui está um bloco de código que reproduz o problema:
import SwiftUI
struct CustomAnimation: ViewModifier {
@State private var isAnimated: Bool = false
func body(content: Content) -> some View {
content
.phaseAnimator([true, false], trigger: self.isAnimated) { view, phase in
view
.scaleEffect(phase ? 1 : 1.2)
}
.onTapGesture {
self.isAnimated.toggle()
}
}
}
#Preview {
@Previewable @State var isPresented: Bool = true
VStack {
Button {
isPresented = true
} label: {
Text("show sheet")
}
}
.sheet(isPresented: $isPresented) {
VStack {
Spacer()
Text("my animated text")
.modifier(CustomAnimation())
}
}
}
O problema é que o texto animado, colocado na parte inferior da tela com um espaçador, fica instável (e volta ao seu lugar) quando arrasto a planilha para cima, depois que a visualização foi animada pelo menos uma vez.
O problema é visível somente se a visualização animada estiver fixada na parte inferior da tela (por exemplo, com um espaçador) e somente após uma animação.
Tentei depurar com engates de instrumentos, mas sou novo nisso e não entendo muito bem como obter informações.
O problema aparece ao criar em um dispositivo, mas também em pré-visualizações. Percebi que, se eu colocasse o aplicativo em segundo plano, era como se a animação não tivesse acontecido e o problema desaparecia, até eu ativar outra animação.