instruction stringlengths 0 30k ⌀ |
|---|
```
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<title>Game Cards App</title>
<link rel="icon" type="image/png" href="https://cdn1.iconfinder.com/data/icons/entertainment-events-hobbies/24/card-game-cards-hold-512.png">
<style>
.card-partially-visible {
pointer-events: none;
}
#main-content {
display: none;
}
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-flow: column wrap;
background: radial-gradient(circle, rgba(7, 50, 22, 255) 0%, rgba(0, 0, 0, 255) 100%);
animation: shine 4s linear infinite;
color: white;
font-family: "Lato";
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
ul {
margin: 0;
padding: 0;
list-style-type: none;
max-width: 800px;
width: 100%;
margin: 0 auto;
padding: 15px;
text-align: center;
overflow-x: hidden;
}
.card {
float: left;
position: relative;
width: calc(33.33% - 30px + 9.999px);
height: 340px;
margin: 0 30px 30px 0;
perspective: 1000;
}
.card:first-child .card__front {
background:#5271C2;
}
.card__front img {
width: 100%;
height: 100%;
object-fit: cover;
}
.card:first-child .card__num {
text-shadow: 1px 1px rgba(52, 78, 147, 0.8)
}
.card:nth-child(2) .card__front {
background:#35a541;
}
.card:nth-child(2) .card__num {
text-shadow: 1px 1px rgba(34, 107, 42, 0.8);
}
.card:nth-child(3) {
margin-right: 0;
}
.card:nth-child(3) .card__front {
background: #bdb235;
}
.card:nth-child(3) .card__num {
text-shadow: 1px 1px rgba(129, 122, 36, 0.8);
}
.card:nth-child(4) .card__front {
background: #db6623;
}
.card:nth-child(4) .card__num {
text-shadow: 1px 1px rgba(153, 71, 24, 0.8);
}
.card:nth-child(5) .card__front {
background: #3e5eb3;
}
.card:nth-child(5) .card__num {
text-shadow: 1px 1px rgba(42, 64, 122, 0.8);
}
.card:nth-child(6) .card__front {
background: #aa9e5c;
}
.card:nth-child(6) .card__num {
text-shadow: 1px 1px rgba(122, 113, 64, 0.8);
}
.card:last-child {
margin-right: 0;
}
.card__flipper {
cursor: pointer;
transform-style: preserve-3d;
transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);
border: 3.5px solid rgba(255, 215, 0, 0.6);
background-image: linear-gradient(45deg, rgba(255, 215, 0, 0.5), transparent, rgba(255, 215, 0, 0.5));
}
.card__front, .card__back {
position: absolute;
backface-visibility: hidden;
top: 0;
left: 0;
width: 100%;
height: 340px;
}
.card__front {
transform: rotateY(0);
z-index: 2;
overflow: hidden;
}
.card__back {
transform: rotateY(180deg) scale(1.1);
background: linear-gradient(45deg, #483D8B, #301934, #483D8B, #301934);
display: flex;
flex-flow: column wrap;
align-items: center;
justify-content: center;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.card__back span {
font-weight: bold; /* Metni kalın yap */
color: white; /* Beyaz renk */
font-size: 16px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.card__name {
font-size: 32px;
line-height: 0.9;
font-weight: 700;
}
.card__name span {
font-size: 14px;
}
.card__num {
font-size: 100px;
margin: 0 8px 0 0;
font-weight: 700;
}
@media (max-width: 700px) {
.card__num {
font-size: 70px;
}
}
@media (max-width: 700px) {
.card {
width: 100%;
height: 290px;
margin-right: 0;
float: none;
}
.card .card__front,
.card .card__back {
height: 290px;
overflow: hidden;
}
}
/* Demo */
main {
text-align: center;
}
main h1, main p {
margin: 0 0 12px 0;
}
main h1 {
margin-top: 12px;
font-weight: 300;
}
.fa-github {
color: white;
font-size: 50px;
margin-top: 8px;
}
.tm-container {
display: flex;
justify-content: center;
align-items: center;
}
.tm-letter {
display:inline-block;
font-size:30px;
margin: 0 5px;
margin-top: 10px;
opacity: 0;
transform: translateY(0);
animation: letter-animation 6s ease-in-out infinite;
}
@keyframes letter-animation {
0%, 100% {
opacity: 1;
transform: translateY(0);
}
10%, 40%, 60%, 90% {
opacity: 1;
transform: translateY(-10px);
}
20%, 80% {
opacity: 1;
transform: translateY(0);
}
}
#m-letter {
animation-delay: 1.5s;
}
a {
position: relative;
display: inline-block;
padding: 0px;
}
a::before {
content: '';
position: absolute;
top: 50%; /* Orta konumu */
left: 50%; /* Orta konumu */
transform: translate(-50%, -50%);
width: 50px;
height: 45px;
border-radius: 50%; /* Eğer bir daire şeklinde efekt isteniyorsa */
box-shadow: 0 0 8px 4px rgba(110, 110, 110, 0.8);
filter: blur(4px) brightness(1.5); /
opacity: 0;
transition: opacity 0.3s ease, transform 0.3s ease;
z-index: -1;
}
a:hover::before {
opacity: 1;
}
body.hoverEffect {
background: radial-gradient(circle at center, #000000, #000033, #000066, #1a1a1a);
}
#gameCard {
width: 300px;
height: 450px;
margin: 50px auto;
padding: 20px;
border-radius: 15px;
box-shadow:
0 0 50px 10px #FFD700,
0 0 100px 20px #0000FF,
0 0 150px 30px #000033;
background: rgba(0,0,0,0.7);
color:#FFD700;
text-align: center;
border: 3px solid #FFD700;
}
#gameCardLink span {
font-size: 18px;
margin-right: 5px;
font-weight: bold;
}
#gameCardLink span:last-child {
font-size: 0.79em;
vertical-align: super;
opacity: 0.9;
font-weight: bold;
text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
}
#loading-animation {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image:url('data:image/jpeg;base64,/);
background-repeat: no-repeat;
background-size: cover ;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.loader {
border-top: 9px solid #00a2ed;
border-radius: 80%;
width: 12vw;
height: 12vw;
animation: spin 2s linear infinite;
position: absolute;
left: 44%;
top: 46%; /
transform: translate(-50%, -50%) rotate(0deg); /* Yuvarlak halkanın tam ortasında olması için bu dönüşümü kullanın. */
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div id="loading-animation">
<div class="loader"></div>
</div>
<div id="main-content">
<div class="tm-container">
<div class="tm-letter" id="t-letter">T</div>
<div class="tm-letter" id="m-letter">M</div>
</div>
<audio id="flipSound" preload="auto">
<source src="https://cdn.freesound.org/previews/321/321114_2776777-lq.ogg" type="audio/wav">
</audio>
<main>
<div id="gameCardLink">
<span>G</span>
<span>a</span>
<span>m</span>
<span>e</span>
<span> </span> <!-- Boşluk eklemek için span ekledik -->
<span> </span>
<span>C</span>
<span> </span>
<span>a</span>
<span> </span>
<span>r</span>
<span> </span>
<span>d</span>
<span> </span>
<span>s</span>
<span>®</span>
</div>
<p><a href="https://github.com/murattasci06"><i class="fab fa-github"></i></a></p>
</main>
<ul>
<li class="card" >
<div class="card__flipper">
<div class="card__front">
<img src="https://gecbunlari.com/wp-content/uploads/2021/12/Spiderman-No-Way-Home.jpg" alt="Spiderman">
<p class="card__name"><span>Marvel</span><br>Spiderman</p>
<p class="card__num">1</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/JfVOs4VSpmA?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#514d9b" stroke-width="35" />
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>1.89 Bil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://i.pinimg.com/736x/1e/f1/3d/1ef13dfa4b7b8c131302e242d1ec48d7.jpg" alt="Batman">
<p class="card__name"><span>DC</span><br>Batman</p>
<p class="card__num">2</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/mqqft2x_Aa4?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#35a541" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>771 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://wallpapercave.com/wp/wp12279011.jpg" alt="Guardians_of_the_Galaxy_Vol_3">
<p class="card__name"><span>Marvel</span><br>Guardians_of_the_Galaxy_Vol_3</p>
<p class="card__num">3</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/u3V5KDHRQvk?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#bdb235" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>845.4 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://wallpaperaccess.com/full/8940499.jpg" alt="Shazam">
<p class="card__name"><span>DC</span><br>Shazam2</p>
<p class="card__num">4</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/AIc671o9yCI?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#db6623" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>462.5 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src="https://images2.alphacoders.com/131/1316679.jpeg" alt="Flash">
<p class="card__name"><span>DC</span><br>Flash</p>
<p class="card__num">5</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/hebWYacbdvc?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#3e5eb3" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>560.2 Mil. $</span>
</div>
</div>
</li>
<li class="card">
<div class="card__flipper">
<div class="card__front">
<img src=" https://images3.alphacoders.com/121/1213553.jpg" alt="Dr_Strange_2">
<p class="card__name"><span>Marvel</span><br>Dr_Strange_2</p>
<p class="card__num">6</p>
</div>
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/aWzlQ2N6qqg?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
<div class="card__back">
<svg height="180" width="180">
<circle cx="90" cy="90" r="65" stroke="#aa9e5c" stroke-width="35"/>
<!-- Dış dairenin kenarı (yeşil) -->
<circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" />
</svg>
<span>955.8 Mil. $</span>
</div>
</div>
</li>
</ul>
</div>
</body>
<script>
var Flipper = (function() {
var card = $('.card');
var flipper = card.find('.card__flipper');
var win = $(window);
var flip = function() {
var thisCard = $(this);
var thisFlipper = thisCard.find('.card__flipper');
var offset = thisCard.offset();
var xc = win.width() / 2;
var yc = win.height() / 2;
var docScroll = $(document).scrollTop();
var cardW = thisCard.outerWidth() / 2;
var cardH = thisCard.height() / 2;
var transX = xc - offset.left - cardW;
var transY = docScroll + yc - offset.top - cardH;
// if (offset.top > card.height()) transY = docScroll - offset.top + cardH;
if (win.width() <= 700) transY = 0;
if (card.hasClass('active')) unflip();
thisCard.css({'z-index': '3'}).addClass('active');
thisFlipper.css({
'transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)',
'-webkit-transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)',
'-ms-transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)'
}).addClass('active');
return false;
};
var unflip = function(e) {
card.css({'z-index': '1'}).removeClass('active');
flipper.css({
'transform': 'none',
'-webkit-transform': 'none',
'-ms-transform': 'none'
}).removeClass('active');
};
var bindActions = function() {
card.on('click', flip);
win.on('click', unflip);
}
var init = function() {
bindActions();
};
return {
init: init
};
}());
Flipper.init();
</script>
<script>
<!-- HOOVER FOR TRAILER -->
let hoverTimeout;
$('.card').hover(function() {
const currentCard = $(this); // Store the current card element in a variable
hoverTimeout = setTimeout(() => {
currentCard.find('.card__front').hide();
currentCard.find('.iframe').show();
var src = currentCard.find('.iframe').attr("src");
currentCard.find('.iframe').attr("src", src);
// Add fullscreen functionality
currentCard.find('.iframe').on('click', function() {
$(this).requestFullscreen();
});
}, 5000); // 5000 milliseconds (5 seconds)
}, function() {
clearTimeout(hoverTimeout); // Clear the timeout to prevent actions if the user moves away before 5 seconds
$(this).find('.card__front').show();
$(this).find('.iframe').hide();
var src = $(this).find('.iframe').attr("src");
if (src) {
$(this).find('.iframe').attr("src", src.replace('?autoplay=1', ''));
}
});
</script>
<script>
var cardFlags = {};
$(document).ready(function() {
var flipSound = document.getElementById("flipSound");
// Sesin yalnızca kartın ön yüzüne tıklandığında çalmasını sağlayın.
$(".card__front").click(function() {
console.log('Kart önüne tıklandı', event.target);
flipSound.currentTime = 0;
flipSound.play();
console.log('dönüş sesi çalındı', event.target);
});
$(".card").click(function() {
var card = $(this);
var cardId = card.find(".card__num").text();
console.log(cardId);
// Check if the card is not already flipping to avoid multiple flips
if (!card.hasClass('flipping')) {
card.addClass('flipping');
// Check if the front side is facing the viewer
if (!card.hasClass("flipped")) {
console.log("is card flag true or false", cardId);
if (!cardFlags[cardId]) {
startAnimation(div);
console.log("started");
cardFlags[cardId] = true;
card.addClass("flipped");
}
// Adding canvas to back-side
var div = document.querySelector('.flipped .card__flipper.active .card__back');
var canvas = document.getElementsByClassName('p5Canvas')[0];
if (div && canvas) {
div.appendChild(canvas);
canvas.style.position = 'absolute';
}
} else {
console.log("stopped");
card.removeClass("flipped");
}
setTimeout(function() {
card.removeClass('flipping');
}, 1000);
}
});
// Prevent sound on back side click
$(".card__back").click(function(e) {
e.stopPropagation();
});
});
</script>
<script>
// Body's hoover effect
document.getElementById("gameCardLink").addEventListener("mouseover", function() {
document.body.classList.add("hoverEffect");
});
document.getElementById("gameCardLink").addEventListener("mouseout", function() {
document.body.classList.remove("hoverEffect");
});
</script>
<script>
// Portal effect
var p5Instance;
function startAnimation(div) {
// adding canvas to back-side
var canvas = document.getElementsByClassName('p5Canvas')[0];
if (div && canvas) {
div.appendChild(canvas);
canvas.style.position = 'absolute';
}
const sketch = (p) => {
const createParticleSystem = (location) => {
const origin = location.copy();
const particles = [];
const addParticle = velocity => {
const rand = p.random(0, 1);
if (rand <= .3) {
particles.push(createSparkParticle(origin, velocity.copy()));
} else {
particles.push(createParticle(origin, velocity.copy()));
}
};
const applyForce = force => {
particles.forEach(particle => {
particle.applyForce(force);
});
};
const run = () => {
particles.forEach((particle, index) => {
particle.move();
particle.draw();
if (particle.isDead()) {
particles.splice(index, 1);
}
});
};
return {
origin,
addParticle,
run,
applyForce
};
};
const createSparkParticle = (locationP, velocity) => {
const particle = createParticle(locationP, velocity);
let fade = 255;
const draw = () => {
p.colorMode(p.HSB);
p.stroke(16, 62, 100, fade);
const arrow = velocity.copy().normalize().mult(p.random(2, 4));
const direction = p5.Vector.add(particle.location, arrow);
p.line(particle.location.x, particle.location.y, direction.x, direction.y);
};
const move = () => {
particle.applyForce(p.createVector(p.random(-.2, .2), p.random(-0.1, -0.4)));
particle.velocity.add(particle.acc);
particle.location.add(particle.velocity.copy().normalize().mult(p.random(2, 4)));
particle.acc.mult(0);
fade -= 5;
};
return {
...particle,
draw,
move
}
}
const createParticle = (locationP, velocity) => {
const acc = p.createVector(0, 0);
const location = locationP.copy();
let fade = 255;
const fadeMinus = p.randomGaussian(15, 2);
let ligther = 100;
let situate = 62;
const draw = () => {
p.colorMode(p.HSB)
p.stroke(16, p.constrain(situate, 62, 92), p.constrain(ligther, 60, 100), fade);
const arrow = velocity.copy().mult(2);
const direction = p5.Vector.add(location, arrow);
p.line(location.x, location.y, direction.x, direction.y);
};
const move = () => {
velocity.add(acc);
location.add(velocity.copy().div(p.map(velocity.mag(), 18, 0, 5, 1)));
acc.mult(0);
fade -= fadeMinus;
ligther -= 8;
situate += 8;
};
const applyForce = force => {
acc.add(force);
};
const isDead = () => {
if (fade < 0 || location.x < 0 || location.x > p.width || location.y > p.height) {
return true;
} else {
return false;
}
};
return {
draw,
move,
applyForce,
isDead,
velocity,
location,
acc
};
};
const createMover = () => {
const location = p.createVector(p.width / 2, p.height / 2);
const velocity = p.createVector(0, 0);
const acc = p.createVector(0, 0);
const mass = 10;
let angle = 0;
let angleVelocity = 0;
let angleAcc = 0;
let len = 100;
const particleSystems = [
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location),
createParticleSystem(location)
];
const getGotoVector = angle => {
const radius = p.map(angleVelocity, 0, 0.3, 0, 80);
const goToVector = p.createVector(
location.x + radius * p.cos(angle),
location.y + radius * p.sin(angle)
);
return goToVector;
};
const draw = () => {
const goToVector = getGotoVector(angle);
particleSystems.forEach(particleSystem => {
particleSystem.run();
});
};
const renderParticleSystem = () => {
particleSystems.forEach(particleSystem => {
const goToVector = getGotoVector(angle - p.random(0, p.TWO_PI));
const prepencular = p.createVector(
(goToVector.y - location.y)*-1,
(goToVector.x - location.x)
);
prepencular.normalize();
prepencular.mult(angleVelocity * 70);
particleSystem.origin.set(goToVector);
particleSystem.addParticle(prepencular);
const gravity = p.createVector(0, 0.3);
particleSystem.applyForce(gravity);
});
};
const move = () => {
angleAcc = 0.005;
angleVelocity = p.constrain(angleVelocity + angleAcc, 0, 0.32);
angle += angleVelocity;
angleAcc = 0;
renderParticleSystem();
};
return {
draw,
move
};
};
let mover;
p.setup = function() {
p.createCanvas(230, 320);
p.clear();
mover = createMover();
}
p.draw = function() {
p.clear();
mover.move();
mover.draw();
}
};
p5Instance = new p5(sketch);
}
</script>
<script>
// hiding and showing loading animation
function hideLoadingAnimation() {
console.log("Yükleme animasyonu gizleniyor, ana içerik gösteriliyor");
var loadingAnimation = document.getElementById("loading-animation");
var mainContent = document.getElementById("main-content");
loadingAnimation.style.display = "none";
mainContent.style.display = "block";
}
window.onload = function() {
console.log("Sayfa tamamen yüklendi");
hideLoadingAnimation();
};
</script>
</html>
```
Hello friends, In the picture on the issue, there is a purple card turned upside down in the middle. There are 2 cards above and below that overlap with this card. While the cards overlap each other front and back, how can I easily ensure that the bottom side of the cards, whose front side is half visible, does not play trailers with hoover (**mouse events will not work in this case**)? with css? I am trying to solve this problem with very simple approaches.
card-partially-visible {
pointer-events: none;
}
Does something like this make sense? If so, how should you determine if it is partially visible?
Could there be a ready-made function that will detect it automatically?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/6kFhI.png |
## The wrong approach
If you serialise the object before returning it, using `json.dumps()` (as shown in your example), for instance:
```python
import json
@app.get('/user')
async def get_user():
return json.dumps(some_dict, indent=4, default=str)
```
the JSON object that is returned **will end up being serialised twice**, as FastAPI will *automatically* serialise the return value behind the scenes. Hence, the reason for the output string you ended up with:
```json
"[\n {\n \"User\": \"aaa\",\n \"date\": \"2022-09-26\",\n ...
```
# Solutions
Have a look at the available solutions, as well as the explanation given below as to how FastAPI/Starlette works under the hood.
## Option 1
The first option is to return data (such as `dict`, `list`, etc.) as usual— i.e., using, for example, `return some_dict`—and FastAPI, behind the scenes, [will automatically convert that return value into JSON][1], after first converting the data into JSON-compatible data, using the [`jsonable_encoder`][2]. The `jsonable_encoder` **ensures** that objects that are not serializable, such as [`datetime`][3] objects, are converted to a `str`. Then, FastAPI will put that JSON-compatible data inside of a [`JSONResponse`][4], which will return an `application/json` encoded response to the client (this is also explained in Option 1 of [this answer][5]). The `JSONResponse`, as can be seen in Starlette's source code [here][6], will use the Python standard `json.dumps()` to serialise the `dict` (for alternatvie/faster JSON encoders, see [this answer][7] and [this answer][8]).
#### Example
```python
from datetime import date
d = [
{"User": "a", "date": date.today(), "count": 1},
{"User": "b", "date": date.today(), "count": 2},
]
@app.get('/')
async def main():
return d
```
The above is **equivalent** to:
```python
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
@app.get('/')
async def main():
return JSONResponse(content=jsonable_encoder(d))
```
**Output:**
```json
[{"User":"a","date":"2022-10-21","count":1},{"User":"b","date":"2022-10-21","count":2}]
```
\
Returning a `JSONResponse` or a custom `Response` directly (it is demonstrated in Option 2 below), as well as any other response class that inherits from `Response` (see FastAPI's documentation [here][9], as well as Starlette's documentation [here][10] and responses' implementation [here][11]), would also allow one to specify a **custom** `status_code`, if they will. The implementation of FastAPI/Starlette's `JSONResponse` class can be found [here][12], as well as a list of HTTP codes that one may use (instead of passing the [HTTP response status code][13] as an `int` directly) can be seen [here][14]. Example:
```python
from fastapi import status
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
@app.get('/')
async def main():
return JSONResponse(content=jsonable_encoder(d), status_code=status.HTTP_201_CREATED)
```
## Option 2
If, for any reason (e.g., trying to force some custom JSON format), you have to serialise the object before returning it, you can then [return a custom `Response` directly][15], as described in [this answer][16]. As per the [documentation][17]:
> When you return a `Response` directly its data is **not** validated,
> converted (serialized), nor documented automatically.
Additionally, as described [here][18]:
> FastAPI (actually Starlette) will automatically include a
> Content-Length header. It will also include a Content-Type header,
> based on the `media_type` and appending a charset for text types.
Hence, you can also set the `media_type` to whatever type you are expecting the data to be; in this case, that is `application/json`. Example is given below.
**Note 1**: The JSON outputs posted in this answer (in both Options 1 & 2) are the result of accessing the API endpoint through the browser directly (i.e., by typing the URL in the address bar of the browser and then hitting the enter key). If you tested the endpoint through Swagger UI at `/docs` instead, you would see that the indentation differs (in both options). This is due to how Swagger UI formats `application/json` responses. If you needed to force your custom indentation on Swagger UI as well, you could avoid specifying the `media_type` for the `Response` in the example below. This would result in displaying the content as *text*, as the `Content-Type` header would be missing from the response, and hence, Swagger UI couldn't recognise the type of the data, in order to custom-format them (in case of `application/json` responses).
**Note 2**: Setting the `default` argument to `str` in [`json.dumps()`][19] is what makes it possible to serialise the `date` object, otherwise if it wasn't set, you would get: `TypeError: Object of type date is not JSON serializable`. The `default` is a function that gets called for objects that can't otherwise be serialized. It should return a JSON-encodable version of the object. In this case it is `str`, meaning that every object that is not serializable, it is converted to string. You could also use a custom function or `JSONEncoder` subclass, as demosntrated [here][20], if you would like to serialise an object in a custom way. Additionally, as mentioned in Option 1 earlier, one could instead use alternative JSON encoders, such as `orjson`, that might improve the application's performance compared to the standard `json` library (see [this answer][7] and [this answer][8]).
**Note 3**: FastAPI/Starlette's [`Response`][21] accepts as a `content` argument either a `str` or `bytes` object. As shown in the implementation [here][22], if you don't pass a `bytes` object, Starlette will try to encode it using `content.encode(self.charset)`. Hence, if, for instance, you passed a `dict`, you would get: `AttributeError: 'dict' object has no attribute 'encode'`. In the example below, a JSON `str` is passed, which will later be encoded into `bytes` (you could alternatively encode it yourself before passing it to the `Response` object).
#### Example
```python
from fastapi import Response
from datetime import date
import json
d = [
{"User": "a", "date": date.today(), "count": 1},
{"User": "b", "date": date.today(), "count": 2},
]
@app.get('/')
async def main():
json_str = json.dumps(d, indent=4, default=str)
return Response(content=json_str, media_type='application/json')
```
**Output:**
```json
[
{
"User": "a",
"date": "2022-10-21",
"count": 1
},
{
"User": "b",
"date": "2022-10-21",
"count": 2
}
]
```
[1]: https://fastapi.tiangolo.com/advanced/response-directly/
[2]: https://fastapi.tiangolo.com/tutorial/encoder/
[3]: https://docs.python.org/3/library/datetime.html
[4]: https://fastapi.tiangolo.com/advanced/custom-response/?h=jsonresp#jsonresponse
[5]: https://stackoverflow.com/a/71205127/17865804
[6]: https://github.com/encode/starlette/blob/858629f5188bc79d452600b1eb90eaa0045f6454/starlette/responses.py#L181
[7]: https://stackoverflow.com/a/73580096/17865804
[8]: https://stackoverflow.com/a/74173023/17865804
[9]: https://fastapi.tiangolo.com/advanced/custom-response/
[10]: https://www.starlette.io/responses/
[11]: https://github.com/encode/starlette/blob/master/starlette/responses.py
[12]: https://github.com/encode/starlette/blob/da7adf246de5495b154b45e32d6fa95e181993d8/starlette/responses.py#L185
[13]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
[14]: https://github.com/encode/starlette/blob/da7adf246de5495b154b45e32d6fa95e181993d8/starlette/status.py#L11
[15]: https://fastapi.tiangolo.com/advanced/response-directly/#returning-a-custom-response
[16]: https://stackoverflow.com/a/72246260/17865804
[17]: https://fastapi.tiangolo.com/advanced/response-directly/#notes
[18]: https://fastapi.tiangolo.com/advanced/custom-response/?h=jsonresp#response
[19]: https://docs.python.org/3/library/json.html#json.dumps
[20]: https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable
[21]: https://github.com/encode/starlette/blob/858629f5188bc79d452600b1eb90eaa0045f6454/starlette/responses.py#L38
[22]: https://github.com/encode/starlette/blob/858629f5188bc79d452600b1eb90eaa0045f6454/starlette/responses.py#L60 |
|android|android-emulator|android-ide| |
While on the transaction in parallel situation, prisma throw error like that message
so i wanna know why it error occured, and how to resolove it,
ERROR MESSAGE
```
[Nest] 43187 - 2024. 03. 17. 오후 4:14:56 ERROR [ExceptionsHandler] Transaction API error: Transaction not found. Transaction ID is invalid, refers to an old closed transaction Prisma doesn't have information about anymore, or was obtained before disconnecting.
PrismaClientKnownRequestError: Transaction API error: Transaction not found. Transaction ID is invalid, refers to an old closed transaction Prisma doesn't have information about anymore, or was obtained before disconnecting.
at xt.transaction (/src/node_modules/.pnpm/@prisma+client@5.11.0(prisma@5.11.0)/node_modules/@prisma/client/runtime/library.js:111:12322)
at Proxy._transactionWithCallback (/src/node_modules/.pnpm/@prisma+client@5.11.0(prisma@5.11.0)/node_modules/@prisma/client/runtime/library.js:127:9568)
at AccountService.recharge (/src/src/account/charge.service.ts:34:5)
at /src/node_modules/.pnpm/@nestjs+core@10.3.3(@nestjs+common@10.3.3)(@nestjs+platform-express@10.3.3)(reflect-metadata@0.2.1)(rxjs@7.8.1)/node_modules/@nestjs/core/router/router-execution-context.js:46:28
at /src/node_modules/.pnpm/@nestjs+core@10.3.3(@nestjs+common@10.3.3)(@nestjs+platform-express@10.3.3)(reflect-metadata@0.2.1)(rxjs@7.8.1)/node_modules/@nestjs/core/router/router-proxy.js:9:17
```
TEST CODE
```
const willChargeAmount = Array.from({ length: 20 }, () =>
randomIntByRange(1000, 5000),
);
console.log(willChargeAmount);
console.log('-------------------------------------------------');
const responses = await Promise.all(
willChargeAmount.map((amount) =>
request(app.getHttpServer())
.post(`/users/${foundUser?.user_id}/recharge`)
.set('Authorization', `Bearer ${jwt}`)
.send({ amount }),
),
);
console.log('-------------------------------------------------');
```
charge.service.ts
```
public async recharge(rechargeRequest: chrageDatas) {
await this.accountRepository.recharge(rechargeRequest);
}
```
accountRepository.ts
```
public async recharge(
rechargeRequest: chrageDatas,
) {
return this.prismaService.prisma.$transaction(async (tx) => {
const amounts = await tx.accounts.findMany({
where: {
AND: [
{ user_id: rechargeRequest.user.userId }
],
},
});
const points = amounts.filter(
(amount) => amount.type === PERMANENT,
);
if (points.length >= 1) {
return tx.accounts.update({
where: {
account_id: points[0].account_id,
},
data: {
amount: rechargeRequest.amount,
},
});
}
return tx.accounts.create({
data: {
users: {
connect: {
user_id: rechargeRequest.user.userId,
},
},
type: PERMANENT,
amount: rechargeRequest.amount,
},
});
});
}
```
prisma.service.ts
```
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class PrismaService implements OnModuleInit, OnModuleDestroy {
public prisma: PrismaClient;
constructor(private readonly configService: ConfigService) {
//
}
public async onModuleDestroy() {
await this.prisma.$disconnect();
}
public async onModuleInit() {
this.prisma = new PrismaClient({
datasourceUrl: this.configService.getOrThrow('DATABASE_URL'),
log: [
'error',
'info',
'query',
'warn',
],
});
await this.prisma.$connect();
}
}
```
and prisma connected on booting and destory at "OnModuleDestroy"
i'm expection nothing error occured, and finish transcation successfully |
How to integrate form in Dialogflow CX? |
|dialogflow-es|dialogflow-cx| |
null |
I can't understand why the list of list elements doesn't change between the iterations of a for loop inside the Jinja template.
For example, playbook:
```yaml
- name: Create Config Files
hosts: localhost
gather_facts: false
vars:
conf_elements:
# Hostname|Octet|Mgmt|Location
- ["host-s01","100","10","999"]
- ["host-s02","100","20","999"]
- ["host-s03","100","30","999"]
- ["host-s04","100","40","999"]
tasks:
- name: Creata a New config file
ansible.builtin.template:
src: config-template_v0.1.j2
dest: "./CNFG/{{item.0}}.txt"
loop: "{{ conf_elements }}"
```
and the template (redacted):
```
{% for hostname, octet, mgmtip, id in conf_elements %}
!
conf t
hostname {{ hostname }}
mgmt 10.{{ octet }}.10.10
ip address 10.{{ octet }}.10.{{ mgmtip }}
descr location {{ id }}
!
{% endfor %}
```
What I'm expecting here in ```CNFG``` directory 4 files named respectively same as the hostnames (first list element in each list). Which actually works, but all 4 files are populated with the variables from the first list element basically all 4 files are the same and I can't understand why the past list variables are not used in Jinja.
Thanks for reading! |
null |
We are migrating our TFS server 2017 to DevOps Server 2022 but when we migrate our databases to the devops server our connection from visual studio 2012 and 2010 is not working while on Visual studio 2017 and 2019 the same connection is working fine on same machines. I need a solution so that we can access the DevOps Server on VS2012 and VS2010.
I tried the URL on Web and On VS 2017 and 2019 it is working fine on that the only problem I am getting is when connecting DevOps from VS 2010 and VS.
getting below error.
[enter image description here](https://i.stack.imgur.com/kG1oJ.png) |
DevOps 2022 Server not connecting on VS 2012 and VS 2010 |
|visual-studio|visual-studio-2010|azure-devops|tfs|devops| |
null |
I'm working on a .NET MAUI Blazor app and have implemented a notification service using **Microsoft.Toolkit.Uwp.Notifications** with **ToastContentBuilder**. (Only for windows platfrom) I want to handle the click event on the notification so that when a user clicks on it, the MAUI Blazor application opens on a specific page (Blazor page) that is determined by the argument passed in the notification.
I followed an article on handling activation (user click on notification),
[Handling activation](https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/send-local-toast?tabs=uwp)
which suggested overriding the OnActivated() method in the App.xaml.cs file. However, when I attempt to override this method, I encounter an error stating that the method is not suitable for overriding.
Here's the error I'm getting:
method is not suitable to override
Has anyone successfully implemented a notification click event handler in a .NET MAUI Blazor app that opens a specific page? How can I properly override the OnActivated() method, or is there another approach I should take?
This is my NotficationService class
```
#if WINDOWS
using MAUIDemo.Services;
using Microsoft.Toolkit.Uwp.Notifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MAUIDemo.PlatformServices.Windows
{
public class NotificationService : INotificationService
{
public void ShowNotification(string title, string body)
{
new ToastContentBuilder()
.AddToastActivationInfo(null, ToastActivationType.Foreground)
.AddAppLogoOverride(new Uri("ms-appx:///Assets/dotnet_bot.png"))
.AddText(title, hintStyle: AdaptiveTextStyle.Header)
.AddText(body, hintStyle: AdaptiveTextStyle.Body)
.AddButton(new ToastButton()
.SetContent("See more details")
.AddArgument("action", "viewDetails"))
.AddButton(new ToastButton()
.SetContent("Remind me later")
.AddArgument("action", "remindLater"))
.Show();
}
}
}
#endif
```
|
null |
Formkit autoanimate doesn't work on my list.
My main.js:
```js
import { createApp } from 'vue';
import App from './App.vue';
import './styles/app.css';
import components from '@/components/UI';
import router from '@/router/index.js';
import store from '@/store';
import { autoAnimatePlugin } from '@formkit/auto-animate/vue'
const app = createApp(App)
components.forEach(component => {
app.component(component.name, component)
})
app
.use(autoAnimatePlugin)
.use(router)
.use(store)
.mount('#app');
```
List:
```html
<div v-auto-animate>
<HospitalItem
v-for="hospital in hospitals"
:key="hospital._id"
:hospital="hospital"
@delete-hospital="deleteEmit"
>
</HospitalItem>
</div>
```
Please help me fix this |
Formkit autoanimate doesn't work on my list |
You are after a 16-byte, universally unique, chronologically sortable unique identifier.
SQL Server already has that: `uniqueidentifier`.
Many people are under the mistaken impression that a `uniqueidentifer` is a random value, and that its use as a clusting key is bad because it causes I/O to be scattered all over the place, torn pages, and poor temporaral locality.
That is only true for "random" uuids - known as a "type 4" uuids.
Sequential sortable UUIDs
-------------------
But there are other types of UUIDs:
- [**Type 1**][1]: stuffs <kbd>MAC address</kbd>+<kbd>datetime</kbd> into 128 bits
- **Type 3**: stuffs an <kbd>MD5 hash</kbd> into 128 bits
- **Type 4**: stuffs <kbd>random data</kbd> into 128 bits
- **Type 5**: stuffs an <kbd>SHA1</kbd> hash into 128 bits
- **Type 6**: [*sequential sortable UUIDs*](https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format)
Rather than being built from random data, or an MD5 hash, or an SHA1 hash, we can use a hash based on a **timestamp** , with a resolution of `100 ns` (i.e. `0.0001 ms`).
And similarly to how you can default a uniqueidentifier colunm to a "type 4 random uuid":
CustomerUUID uniqueidentifier DEFAULT newid()
SQL Server also supports sequential type-1 UUIDs:
CustomerUUID uniqueidentifier DEFAULT newsequentialid()
And those uuids sort chronologically - as long as they're created on the same machine
NodeID, MAC address, and Multiple Machines
------------------------
There is the issue that the type-1 UUID contains a 6-byte `nodeID`, which is the client's MAC address.
<kbd>00112233</kbd>-<kbd>4455</kbd>-<kbd>6677</kbd>-<kbd>8899</kbd>-<kbd>AABBCCDDEEFF</kbd>
| Timestamp-High | Timestamp-Mid | Timestamp-Low | Sequence | NodeID |
|----------------|---------------|---------------|--------|--------|
| <kbd>00112233</kbd> | <kbd>4455</kbd> | <kbd>6677</kbd> | <kbd>8899</kbd> | <kbd>AABBCCDDEEFF</kbd> |
And SQL Server, for whatever reason, decided to sort UUIDs by the `nodeID` first.
SQL Server sorts guids first by f, then e, then d, c, b, a, 9, ..., 2, 1, 0:
{00112233-4455-6677-9988-ffeeddccbbaa}
In other words, it sorts by:
- `Node[0]`
- `Node[1]`
- `Node[2]`
- `Node[3]`
- `Node[4]`
- `Node[5]`
- `UInt16 Sequence` *(**little** endian)*
- `UInt16 TimestampLow` *(big endian)*
- `UInt16 TimestampMid` *(big endian)*
- `UInt32 TimestampHigh` *(big endian)*
Which means:
- if all the UUIDs are generated by the same machine (whether it be the database server itself, or a web web-server) then the UUIDs will be sequential based on the timestamp
- but if the UUIDs are generated on different clients, with different `nodeIDs` (i.e. **MAC address**) then you'll have them sorted first by node, and **then** by timestamp
That may or may not be an issue for you. But if it is, the solution is to shuffle around the bytes of the uniqueidentifier/UUID so that:
- if SQL Server is gonna sort the 6-byte NodeID first
- then i'll just put the timestamp there
- and move the `nodeID` to where the timestamp was
In C# we use the following class to generate an "SQL Server sortable UUID". Other databases may sort UUIDs/uniqueidentifiers differently.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
/// <summary>
/// Summary description for SortableGuid
/// </summary>
public class SortableGuid
{
//UUID timestamps are 100ns ticks starting from October 15, 1582 (date we switched to Gregorian calendar)
//Windows FILETIME is 100ns ticks starting from January 1, 1601 (the date of the start of the first 400-year cycle of the Gregorian calendar)
private static readonly Int64 guidEpochOffset = -5748192000000000; //6653 days --> 159672 hours --> 9580320 minutes --> 574819200 seconds -> 574819200000 ms -> 574819200000000 us --> 5748192000000000 ticks
private static Int64 _lastTick = DateTime.UtcNow.Ticks + guidEpochOffset;
/// <summary>
///
/// </summary>
/// <param name="location">The destination, whose value is compared with comparand and possibly replaced.</param>
/// <param name="comparison">The value that is compared to the value at location1.</param>
/// <param name="newValue">The value that replaces the destination value if the comparison results in equality.</param>
/// <returns>true if comparand was greater than location, and location was updated to newValue.
/// Otherwise false.</returns>
public static Boolean InterlockedExchangeIfGreaterThan(ref Int64 location, Int64 newValue, Int64 comparand)
{
//Thank you Raymond Chen: https://stackoverflow.com/a/13056904/12597
Int64 currentValue;
do
{
currentValue = Interlocked.Read(ref location); //a read of a 64-bit location is not atomic on x86. If location was 32-bit you could get away with just "currentValue = location;"
if (currentValue >= comparand) return false;
}
while (System.Threading.Interlocked.CompareExchange(ref location, newValue, currentValue) != currentValue);
return true;
}
/// <summary>
/// Returns a new sortable guid. These guid's are suitable as clustering keys in SQL Server.
/// </summary>
/// <returns></returns>
public static Guid NewGuid()
{
/*
Blatently borrowed from Entity Framework.
https://github.com/dotnet/efcore/blob/master/src/EFCore/ValueGeneration/SequentialGuidValueGenerator.cs
Except with two differences:
- they start with an initial timetime, generated statically once - and keep increasing that.
That causes the "timestamp" to drift further and further from reality.
We generate a timestamp each time, and only rely on incrementing if we're not greater than the last timestamp.
A CPU is capable of generating ~200k GUIDs per 100ns tick - so it's not like we can ignore the duplciate ticks problem.
- UUID timestamp ticks start at October 15, 1582 (date of gregorian calendar).
Windows, and DateTime.Ticks returns number of ticks since January 1, 1601 (the date of the first 400 year Gregorian cycle).
We'll offset the timestamp to match the UUID spec.
- We place the version number type-7: Sortable by SQL Server with a timestamp.
SQL Server sorts first by the NodeID (i.e. the final 6-bytes):
16-byte guid Microsoft clsid string representation
===========--=====--=====--=====--================= ======================================
33 22 11 00 55 44 77 66 99 88 ff ee dd cc bb aa ==> {00112233-4455-6677-9988-ffeeddccbbaa}
\_______________________/ \___/ \_______________/
Timestamp and Version ^ Clk Node ID
The goal is to create a sequential uuid (e.g. UuidCreateSequential), but without having to rely on a MAC address.
(i.e. Does an Azure web-site even **have** a MAC address?
We certainly can't P/Invoke out to UuidCreateSequental when we're not running on Windows)
So we conceptually move the 8-byte timestamp to it's new location in NodeID+ClockSequence
And what used to be Timestamp+Version becomes random.
And, like type-4 Uuids being called Type-4 to help reduce the chances of collisions between types,
we call this new version type-7 (sortable by SQL Server with a timestamp).
*/
//Start from a new random (type 4) uuid.
Byte[] guidBytes = Guid.NewGuid().ToByteArray();
//Generate 8-byte timestamp
Int64 currentTicks = DateTime.UtcNow.Ticks + guidEpochOffset;
//Make sure that currentTicks is greater than the last tick count (in case they're generating guids faster than 100ns apart)
Int64 last;
do
{
last = Interlocked.Read(ref _lastTick); //a read of a 64-bit value isn't atomic; so it has to be interlocked.
if (currentTicks <= last)
currentTicks = last + 1;
} while (Interlocked.CompareExchange(ref _lastTick, currentTicks, last) != last);
Byte[] counterBytes = BitConverter.GetBytes(currentTicks);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(counterBytes);
}
//This Guid started it's life as a Type 4 (Random) guid, but the final 8 bytes were changed to contain a sequential counter.
//I want to tag this as a different kind of Uuid algorithm. In Delphi we already called this a Type 7 uuid.
guidBytes[07] = (Byte)(0x70 | (guidBytes[07] & 0x0f));
//Put the timestamp in place - in the proper SQL Server sorting order.
guidBytes[08] = counterBytes[1];
guidBytes[09] = counterBytes[0];
guidBytes[10] = counterBytes[7];
guidBytes[11] = counterBytes[6];
guidBytes[12] = counterBytes[5];
guidBytes[13] = counterBytes[4];
guidBytes[14] = counterBytes[3];
guidBytes[15] = counterBytes[2];
Guid result = new Guid(guidBytes);
return result;
}
}
```
[1]: https://en.wikipedia.org/wiki/Universally_unique_identifier |
I am new here and not a tech-savy guy (coding) so please don't be too harsh with me.
I am trying to add an extra field in the products backend, but struggle a lot because I don't understand the coding. I got help from ChatGPT and it works 50%.
What I am trying to accomplish is to have an extra field similar to the SKU field. It has to show in (BACKEND) the product page and in quick edit, for every product. It has to be searchable (in BACKEND) when I search for products.
Right now, my boss is using the SKU field to write the position where the product physically is. So when customers ordering we get printet the order and first description of every product is the SKU field what we have used for the position instead a real SKU number.
It works ... but not ideal. Every time we get a new product or we need to change the position where to physically find the product, we have to edit the SKU.
I would love to make it much easier by having an extra field that behaves like SKU field in terms of editing, searchable and so on.
It is NOT visible for customers on the shop page, but it is on the order we print out.
I would like to show the code ChatGPT got me and some pictures I made because I think it's better to understand then, but I am new here and don't know the rules if it's allowed for a newbie. So thanks in advance and hope to hear from you.
I tried Reddit WooCommerce group and ChatGPT.
I would hope someone could help with the code I got, which doesn't work properly. |
```
n=input('Enter a number:')
F=factor(n);
if F==n
disp('Prime number.')
else
disp('Not a prime number.')
end
``` |
ive tried to just add another fetch to see if it would work but it hasn't. can anyone explain this issue so i get something out of this.
```
<ul className="">
{ async function fetchURL() {
const res = await ability.ability.url;
const data = res.data;
setabilityDes(data)
pokedata.abilities.map( async (ability, index) => (
<li key={index} className="inline px-3" > {ability.ability.name}
<p>{data.effect}</p>
</li>
))}}
</ul>
```
this is the error i am getting
'Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
ul
div
div
div
div
PokemonData@http://localhost:5173/src/pages/PokemonData.jsx?t=1711809411667:23:20
RenderedRoute@http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=45fa90fa:3563:7
Routes@http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=45fa90fa:3997:7
Router@http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=45fa90fa:3945:7
BrowserRouter@http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=45fa90fa:4682:7
App'
ive also tried make a new component for just the ability section but i kept running into errors so i thought this would be more efficient |
I'm not sure what's causing this, but using a `GeometryReader` instead of `.infinity` seems to fix the problem.
GeometryReader { g in
ZStack {
Color(.red)
.aspectRatio(contentMode: .fill)
.frame(width: g.size.width, height: g.size.height)
NavigationLink(destination: ContentView()) {
Text("HI")
.foregroundStyle(.black)
}
.frame(maxWidth: g.size.width, maxHeight: g.size.height, alignment: .topTrailing)
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/vzVpPl.png |
Remove the parenthesis in the line 26. It works alright after removal
WebButton = Button(gui, text="Take Me There!",font="arial, 21",command=WebOpen) |
**DON'T use BuildContext across asynchronous gaps**. If have a linter configured in your project, you should probably have a [warning message][1] indicating that problem.
You can modify your code to get the BLoC before pushing your route:
```dart
class _Exercise extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
return ListTile(
...
onTap: () async {
// Get the BLoC from the context.
final bloc = context.read<TrainerExerciseListBloc>();
// Push the screen
context.pushNamed(ScreenNavigationKey.exerciseDetails).then((_) {
bloc.add(TrainerExerciseListEvent.fetchExercises(_clientId, _date);
}
);
},
...
```
This however could not always be triggered, since depending on your routing strategy (declarative vs imperative routing) the route which contains your `_Exercise` widget may no longer exists.
[1]: https://dart.dev/tools/linter-rules/use_build_context_synchronously |
One possibility is to use a function factory. This allows you to save some state information, in this case a remainder, which is helpful for your computation. The iteration comes from within `map_dbl`, but this is not a vectorized answer:
```r
library(purrr)
library(dplyr)
incr_cap <- function(incr) {
force(incr)
remainder <- NULL
function(curv) {
val <- if (is.null(remainder)) curv else curv + remainder
if (val > incr) {
remainder <<- val - incr
return(incr)
} else if (val > 0) {
remainder <<- 0
return(val)
} else {
remainder <<- 0
return(0)
}
}
}
df |>
mutate(b = map_dbl(a, incr_cap(1.5)))
# a b
# 30 6.0 1.5
# 31 0.0 1.5
# 32 0.0 1.5
# 33 2.5 1.5
# 34 0.0 1.5
# 35 0.0 1.0
# 36 0.0 0.0
# 37 0.0 0.0
# 38 1.0 1.0
# 39 0.0 0.0
```
---
## Benchmark
### Set up
```r
library(purrr)
library(dplyr)
set.seed(4)
incr <- 1.5
df <- data.frame(a = rep(0,100),b=rep(0,100))
df$a[c(30,33,38)] = c(6,2.5,1)
dat <- df[30:39,1, drop = FALSE]
rownames(dat) <- NULL
df <- dat[sample(seq_len(nrow(dat)), 1E5, replace = TRUE), , drop = FALSE]
Rcpp::cppFunction(
"
NumericVector iterate_to_cumsum(NumericVector v1, double incr) {
int x = v1.size();
NumericVector v2(x);
for (int i =0; i < x; ++i) {
v2[i] = std::max(0.0, std::min(incr, sum(v1[Rcpp::Range(0, i)]) - sum(v2)));
}
return v2;
}
"
)
incr_cap <- function(incr) {
force(incr)
remainder <- NULL
function(curv) {
val <- if (is.null(remainder)) curv else curv + remainder
if (val > incr) {
remainder <<- val - incr
return(incr)
} else if (val > 0) {
remainder <<- 0
return(val)
} else {
remainder <<- 0
return(0)
}
}
}
# @Andy Baxter
cpp <- function(){
df |>
mutate(b = iterate_to_cumsum(a, incr))
}
# @LMc
fun_factory <- function(){
df |>
mutate(b = map_dbl(a, incr_cap(1.5)))
}
# @benson23
for_loop <- function() {
for (i in 1:nrow(df)) {
if (i == 1 & df$a[[1]] < incr) {
df$b[i] <- df$a[[1]]
} else if (sum(df$a[1:i]) - sum(df$b[1:i]) > incr) {
df$b[i] <- incr
} else {
df$b[i] <- sum(df$a[1:i]) - sum(df$b[1:i])
}
}
return(df)
}
```
## Results
```r
bench::mark(
cpp(),
fun_factory(),
for_loop()
)
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time
# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list>
# 1 cpp() 17.63s 17.63s 0.0567 785KB 0 1 0 17.63s <df> <Rprofmem> <bench_tm>
# 2 fun_factory() 104.23ms 111.51ms 8.62 783KB 3.45 5 2 579.93ms <df> <Rprofmem> <bench_tm>
# 3 for_loop() 1.55m 1.55m 0.0107 201GB 17.6 1 1636 1.55m <df> <Rprofmem> <bench_tm>
```
Note: the row-wise solution was excluded from this benchmark since this operation is notoriously slow on even modestly sized data frames. |
```py
interval_ranges = [df['A'].iloc[0]] + df['B'].tolist()
(
df2.assign(interval=pd.cut(df2['Point'], interval_ranges))
.merge(
df.assign(interval=pd.cut(df['B'], interval_ranges))
)
.assign(Returned_Data=lambda x: x['A'] + x['B'])
)
Point interval A B Returned_Data
0 11.5 (10, 20] 11 20 31
1 18.3 (10, 20] 11 20 31
2 31.3 (30, 40] 31 40 71
3 41.2 (40, 50] 41 50 91
4 51.5 (50, 60] 51 60 111
5 66.6 (60, 70] 61 70 131
6 34.7 (30, 40] 31 40 71
7 12.1 (10, 20] 11 20 31
8 14.4 (10, 20] 11 20 31
9 56.8 (50, 60] 51 60 111
10 54.3 (50, 60] 51 60 111
```
```py
In [5]: interval_ranges = [df['A'].iloc[0]] + df['B'].tolist()
In [6]: df.assign(interval=pd.cut(df['B'], interval_ranges))
Out[6]:
A B interval
0 0 10 (0, 10]
1 11 20 (10, 20]
2 21 30 (20, 30]
3 31 40 (30, 40]
4 41 50 (40, 50]
5 51 60 (50, 60]
6 61 70 (60, 70]
In [7]: df2.assign(interval=pd.cut(df2['Point'], interval_ranges))
Out[7]:
Point interval
0 11.5 (10, 20]
1 18.3 (10, 20]
2 31.3 (30, 40]
3 41.2 (40, 50]
4 51.5 (50, 60]
5 66.6 (60, 70]
6 34.7 (30, 40]
7 12.1 (10, 20]
8 14.4 (10, 20]
9 56.8 (50, 60]
10 54.3 (50, 60]
In [8]: df2.assign(interval=pd.cut(df2['Point'], interval_ranges)).merge(df.assign(interval=pd.cut(df['B'], interval_r
...: anges)))
Out[183]:
Point interval A B
0 11.5 (10, 20] 11 20
1 18.3 (10, 20] 11 20
2 31.3 (30, 40] 31 40
3 41.2 (40, 50] 41 50
4 51.5 (50, 60] 51 60
5 66.6 (60, 70] 61 70
6 34.7 (30, 40] 31 40
7 12.1 (10, 20] 11 20
8 14.4 (10, 20] 11 20
9 56.8 (50, 60] 51 60
10 54.3 (50, 60] 51 60
In [9]: df2.assign(interval=pd.cut(df2['Point'], interval_ranges)).merge(df.assign(interval=pd.cut(df['B'], interval_r
...: anges))).assign(Returned_Data=lambda x: x['A'] + x['B'])
Out[184]:
Point interval A B Returned_Data
0 11.5 (10, 20] 11 20 31
1 18.3 (10, 20] 11 20 31
2 31.3 (30, 40] 31 40 71
3 41.2 (40, 50] 41 50 91
4 51.5 (50, 60] 51 60 111
5 66.6 (60, 70] 61 70 131
6 34.7 (30, 40] 31 40 71
7 12.1 (10, 20] 11 20 31
8 14.4 (10, 20] 11 20 31
9 56.8 (50, 60] 51 60 111
10 54.3 (50, 60] 51 60 111
```
1. create the bins - `interval_ranges = [df['A'].iloc[0]] + df['B'].tolist()`
2. create your join column in both dfs using `pd.cut(df['B'], interval_ranges)` and `pd.cut(df2['Point'], interval_ranges)`
3. merge both dfs on this join column
4. create your `Returned_Data` column by adding the `A` and `B` columns
5. optionally drop the extra columns using `.drop(columns=['interval', 'A', 'B'])`
|
Any Activity you created in App and not declared in the manifest can cause this Issue
To declare the Activity in Manifest <`activity`> tag is used inside `<application>` tag
In `<activity>` tag `android:name` attribute is used and value of name should include the package detail like com.example.MainActivity / .MainActivity
<activity
android:name=".MainActivity">
</activity>
OR
<activity
android:name=".xyz.MainActivity">
</activity> |
Within Pivot table
Click on Design (after “Pivot Table Analyze” menu group)
Click on Report Layout
Click on Show in Tabular Form |
I have a handful of data objects floating around my code which have a large number of fields of the same type:
```
struct AsStruct{
mass: i32,
height: i32,
energy: i32,
age: i32,
radioactivity: i32,
}
```
(actual examples would have more fields - like 20+).
Sometimes but not always, I'm dealing with these fields in a collective way, and it would be better to have something like a `Map<String, i32>`
```
pub const ALL_STATS: [&str; 5] = ["mass", "height", "energy", "age", "radioactivity"];
struct AsMap{
data : HashMap<String, i32>,
}
```
This latter model lets me treat some things in a neat programmatic way. For instance, below are functions to generate random versions of each:
```
pub fn generate_map() -> AsMap {
let mut map = HashMap::new();
for s in ALL_STATS.iter() {
map.insert(s.to_string(), rand::random::<i32>() % 10);
}
AsMap{data: map}
}
pub fn generate_struct() -> AsStruct {
AsStruct{
mass: rand::random::<i32>() % 10,
height: rand::random::<i32>() % 10,
energy: rand::random::<i32>() % 10,
age: rand::random::<i32>() % 10,
radioactivity: rand::random::<i32>() % 10,
}
}
```
Obviously, the "Map" version will scale much more easily, and require less refactoring as stats change. On the other hand, there's also times when it's preferable to have the stricter `AsStruct` definition, which can be accessed by more concise syntax and doesn't need extra code to handle missing keys, etc.
I can write translations between the two, or put some set of getters and setters on the `AsStruct` one to allow fields to be treated as keys. This would involve a great deal of boiler plate, however, and feels like a worthy use case for something like a `derive` macro. I can also imagine a lot of additional nice-to-have features that could be added to such a solution, such as typed keys, support for structs with fields of different types, etc.
So my question is : Has this already been solved? Is there a reason this is a bad idea and I should go with one or the other? Is there a standard pattern for having my cake and eating it too in such situations?
|
I'm trying to parse some commands-like string/file content into a Dict output and I learned about pyparsing.
So let's say I have the following input:
str = "p1 start a, {alias = b, for : 30}; c, d stop e"
and to parse it, I'm using this:
import pyparsing as pp
grammar = pp.Forward()
SEP = pp.one_of(", ;")
EQ = pp.Suppress(pp.one_of(': ='))
LBRACE, RBRACE = map(pp.Suppress,"{}")
CMD_KEYWORD = (pp.CaselessKeyword("start") | pp.CaselessKeyword("stop") | pp.CaselessKeyword("resume"))
platform = pp.one_of("p1 p2 p3")("platform")
alias = pp.Word(pp.alphanums)
prop = pp.Word(pp.alphanums)
value = pp.Word(pp.alphanums)
prop_value = pp.Dict(pp.Group(prop + EQ + value))
task_config = LBRACE + pp.delimitedList(prop_value, delim = SEP) + RBRACE
command = CMD_KEYWORD + pp.Group(pp.delimitedList(task_config | alias, delim = SEP))("tasks")
expr = platform + command[1, ...]("commands")
grammar <<= expr
res = grammar.parse_string(str)
print(res.as_dict())
print(res.as_list())
which results in the following Dict and List
{'platform': 'p1', 'tasks': ['e'], 'commands': ['start', {'alias': 'b', 'for': '30'}, 'stop', ['e']]}
['p1', 'start', ['a', ['alias', 'b'], ['for', '30'], 'c', 'd'], 'stop', ['e']]
While what I was(still) trying to achieve, is to get the output in a specific Dict format, something like this:
{
[
{
'platform': 'p1',
'commands': [
{'cmd': 'start', 'tasks': [{'alias': 'a'}, {'alias': 'b', 'for': '30'}, {'alias': 'c'}, {'alias': 'd'}]},
{'cmd': 'stop', 'tasks': [{'alias': 'e'}]}
],
}
]
}
**Edit:**
After some trial and errors I managed to (almost) achieve what I'm aiming for after making some changes to my parser grammar:
import pyparsing as pp
def set_alias(t):
return {"alias": t[0]}
grammar = pp.Forward()
SEP = pp.one_of(", ;")
EQ = pp.Suppress(pp.one_of(': ='))
LBRACE, RBRACE = map(pp.Suppress,"{}")
OPT_SEP = pp.Suppress(pp.Opt(SEP))
CMD_KEYWORD = (pp.CaselessKeyword("start") | pp.CaselessKeyword("stop") | pp.CaselessKeyword("resume"))("cmd")
platform = pp.one_of("p1 p2 p3")("platform")
alias = ~(CMD_KEYWORD | platform) + pp.Word(pp.alphanums)
prop = pp.Word(pp.alphanums)
value = pp.Word(pp.alphanums)
prop_value = pp.Dict(pp.Group(prop + EQ + value))
task_config = LBRACE + pp.Group(pp.delimitedList(prop_value, delim = SEP)) + RBRACE
command = pp.Group(CMD_KEYWORD + pp.Group(pp.OneOrMore((task_config | alias.set_parse_action(set_alias)) + OPT_SEP))("tasks"))
expr = platform + command[1, ...]("commands")
grammar <<= pp.OneOrMore(expr + OPT_SEP)
print(res.as_dict())
print(res.as_list())
But when I'm testing it with the following input:
p1 start a, {alias = b, for : 30}; c, d stop e p2 resume f
I get:
{'platform': 'p2', 'commands': [{'cmd': 'resume', 'tasks': [{'alias': 'f'}]}]}
['p1', ['start', [{'alias': 'a'}, [['alias', 'b'], ['for', '30']], {'alias': 'c'}, {'alias': 'd'}]], ['stop', [{'alias': 'e'}]], 'p2', ['resume', [{'alias': 'f'}]]]
And as you can see the **res.as_list()** returns all the expected tokens, but the **res.as_dict()** only returns the **'platform': 'p2'** part missing the **'platfrom': 'p1'** one and I can't figure out the reason for it. |
Chain multiple ajax requests in website to show more pages and get full list in single page |
|python|beautifulsoup|python-requests| |
Based on [this answer](https://stackoverflow.com/a/73506241/11635), I arrived at:
```fsharp
open System.Linq.Expressions
let expandExpr find replace =
{ new ExpressionVisitor() with
override _.Visit node =
if node = find then replace
else base.Visit node }
// We want to generate a projection statement of the shape: VALUE {"sn": root["p"], "snap": root["u"][0].["d"]}
// In C#, one could `.Select(x => new { sn = x.p, snap = x.u[0].d })`
// However the Cosmos SDK does not support F# (or C#) records yet https://github.com/Azure/azure-cosmos-dotnet-v3/issues/3728
type SnAndSnap<'State>() =
member val sn: FsCodec.StreamName = Unchecked.defaultof<_> with get, set
member val snap: 'State = Unchecked.defaultof<_> with get, set
// This hack generates an expression equivalent to the
static member FromItemExpr<'I>(u: Expression<System.Func<Item<'I>, 'I>>) =
let t = typedefof<SnAndSnap<'I>>
let param = Expression.Parameter(typedefof<Item<'I>>, "x")
let dummy = Unchecked.defaultof<SnAndSnap<'I>>
let etagProp = t.GetMember(nameof dummy.sn)[0]
let unfoldProp = t.GetMember(nameof dummy.snap)[0]
let ux = (Query.expandExpr u.Parameters[0] param).Visit(u.Body)
Expression.Lambda<System.Func<Item<'I>, SnAndSnap<'State>>>(
Expression.MemberInit(
Expression.New(t.GetConstructor [||]),
[| Expression.Bind(etagProp, Expression.PropertyOrField(param, nameof Unchecked.defaultof<Item<'I>>.p)) :> MemberBinding
Expression.Bind(unfoldProp, ux) |]),
[| param |])
```
Used like this:
```
q.Select(Indexed.SnAndSnap<'S>.FromItemExpr(fun x -> x.u[0].d))
``` |
I use a COUNTIF function to count and increment the number of instances of an ID in excel.
Id_Treatment_Count ID
1 769334
1 769345
2 769345
1 769376
3 769345
In Excel, I would get the above using `=COUNTIF($B$2:B2,B2)` and then I would drag down (Id_treatment_count being column A and ID being column B).
How can I get the Id_treatment_Count in Power BI using DAX? |
The program was written using version Qt 6.4.3
**CMakeLists.txt** file:
```
cmake_minimum_required(VERSION 3.16)
project(youtube_video VERSION 0.1 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 6.4 REQUIRED COMPONENTS Quick WebEngineQuick)
qt_standard_project_setup()
qt_add_executable(appyoutube_video
main.cpp
)
qt_add_qml_module(appyoutube_video
URI youtube_video
VERSION 1.0
QML_FILES Main.qml
)
# Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1.
# If you are developing for iOS or macOS you should consider setting an
# explicit, fixed bundle identifier manually though.
set_target_properties(appyoutube_video PROPERTIES
# MACOSX_BUNDLE_GUI_IDENTIFIER com.example.appyoutube_video
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
target_link_libraries(appyoutube_video
PRIVATE Qt6::Quick Qt6::WebEngineQuick
)
include(GNUInstallDirs)
install(TARGETS appyoutube_video
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
```
**main.cpp** file:
```
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtWebEngineQuick/qtwebenginequickglobal.h>
int main(int argc, char *argv[]) {
QtWebEngineQuick::initialize();
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(u"qrc:/youtube_video/Main.qml"_qs);
QObject::connect(
&engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() { QCoreApplication::exit(-1); }, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
```
**Main.qml** file:
```
import QtQuick
import QtQuick.Controls
import QtQuick.Window
import QtWebEngine
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
WebEngineView {
anchors.fill: parent
url: "https://www.youtube.com/embed/cabBXCq7_P8"
}
}
```
Shows a preview after launch:
[enter image description here](https://i.stack.imgur.com/rsuHE.png)
But trying to play the video results in an error:
[enter image description here](https://i.stack.imgur.com/RB2eI.png)
Can anyone tell me what the error is and how to fix it?
As a result, the video is expected to play |
Do not save the players in columns like `squad_leader` and `player1` to `player5`. Instead save the player enlistment in a new 1-to-N table. The tables should look like this:
CREATE TABLE team
(
Id INT AUTO_INCREMENT PRIMARY KEY,
...
);
CREATE TABLE enlistment
(
Id INT AUTO_INCREMENT PRIMARY KEY,
TeamId INT,
PlayerId INT,
IsActive BOOL,
IsLeader BOOL,
FOREIGN KEY(TeamId) REFERENCES Team(Id);
);
That way you create a new row for each player of a team in the `enlistment` table. And if the player shouldn't be part of that team anymore, delete the row. |
I m using below code to upload files from Android mobile to Google Drive. This code is written in Async task.
public Object loadInBackground() {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(mycontext);
assert account != null;
mDriveServiceHelper = new DriveServiceHelper(getGoogleDriveService(mycontext, account, "E Aid"));
mDriveServiceHelper.searchFile(file.getName(), "*/*").addOnSuccessListener(new OnSuccessListener<List<GoogleDriveFileHolder>>() {
@Override
public void onSuccess(List<GoogleDriveFileHolder> googleDriveFileHolders) {
Gson gson = new Gson();
try {
JSONArray jsonArray = new JSONArray(gson.toJson(googleDriveFileHolders));
// Log.i(TAG, jsonArray.toString());
if (jsonArray.length() != 0) {
HyperLog.i(TAG, file.getName() + " found at GD");
//Duplicate File, Delete at Local Level
} else {
HyperLog.i(TAG, "Check " + file.getName() + " Not Found ");
mDriveServiceHelper.uploadFile(file, "*/*", folderId, mycontext);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
return null;
}
Here is code for uploadfile method.
public Task<GoogleDriveFileHolder> uploadFile(final java.io.File localFile, final String mimeType, @Nullable final String folderId, final Context context) {
return Tasks.call(mExecutor, new Callable<GoogleDriveFileHolder>() {
@Override
public GoogleDriveFileHolder call() throws Exception {
// Retrieve the metadata as a File object.
Log.i(TAG, "Special Check Inside Upload Function");
List<String> root;
if (folderId == null) {
root = Collections.singletonList("root");
} else {
root = Collections.singletonList(folderId);
}
File metadata = new File()
.setParents(root)
.setMimeType(mimeType)
.setName(localFile.getName());
FileContent fileContent = new FileContent(mimeType, localFile);
File fileMeta = mDriveService.files().create(metadata, fileContent).execute();
GoogleDriveFileHolder googleDriveFileHolder = new GoogleDriveFileHolder();
googleDriveFileHolder.setId(fileMeta.getId());
googleDriveFileHolder.setName(fileMeta.getName());
if (googleDriveFileHolder.getId() != null) {
Log.i(TAG, localFile.getAbsolutePath() + " has uploaded Successfully ");
}
return googleDriveFileHolder;
}
});
}
both codes are working fine for uploading files upto 5 to 6 Mbs. As soon as file size increased like 30 Mb, the file is being uploading but gets corrupted and can not be open after downloading from google drive.
Can someone help to fix this, what is missing which can be added here. |
I am getting this error and my code is below
- (void)viewWillAppear:(BOOL)animated {
NSLog(@"self.inter eve reload cl %@", self.interstitial);
DebugAssert(index != NSNotFound);
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
if (!didPurchaseAds) {
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"Interstitial ad loaded %ld", (long)index);
if ((index % 2 == 0)) {
NSLog(@"Interstitial ad loaded for even num %ld", (long)index);
if (self.interstitial) {
NSLog(@"Show InterstitialAd %@", self.interstitial);
[self.interstitial presentFromRootViewController:self];
[self.interstitial presentFromRootViewController:self];
} else {
NSLog(@"Ad wasn't ready event");
}
}
});
}
}
- (void)viewDidLoad{
[super viewDidLoad];
[self loadInterstitial];
}
- (void)loadInterstitial {
GADRequest *request = [GADRequest request];
[GADInterstitialAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/4411468910"
request:request
completionHandler:^(GADInterstitialAd *ad, NSError *error) {
if (error) {
NSLog(@"Failed to load interstitial ad with error: %@", [error localizedDescription]);
return;
}
self.interstitial = ad;
self.interstitial.fullScreenContentDelegate = self;
}];
}
- (void)ad:(nonnull id<GADFullScreenPresentingAd>)ad
didFailToPresentFullScreenContentWithError:(nonnull NSError *)error {
NSLog(@"Ad did fail to present full screen content.");
}
/// Tells the delegate that the ad will present full screen content.
- (void)adWillPresentFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
NSLog(@"Ad will present full screen content.");
}
/// Tells the delegate that the ad dismissed full screen content.
- (void)adDidDismissFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
NSLog(@"Ad did dismiss full screen content.");
}
|
Ad did fail to present full screen content while showing Interstitial Google ads shows the error for me in iOS objective -C |
|ios|objective-c|google-ads-api| |
(Almost Solved) Output as a specific Dict |
I have an issue with node fs.unlink
I have a function that writes files to disk storage extracts data from the these files then deletes the files
```js
const parseShpFile = async ({
cpgFile,
dbfFile,
prjFile,
qmdFile,
shpFile,
shxFile,
}) => {
// saving binary files to local machine
const dbfPath = await saveBinaryToLocalMachine(dbfFile);
const shpPath = await saveBinaryToLocalMachine(shpFile);
//reading files from local machine using shapefile
const shpParsedData = await shapefile
.open(shpPath, dbfPath)
.then((src) => src.read())
.then(async (data) => {
await deleteFilesFromLocal([shpPath, dbfPath]);
return data;
})
.catch((e) => {
console.log("Error", e);
});
return shpParsedData;
};
```
the delete function is
```js
const deleteFilesFromLocal = async (filePaths) => {
for (const filePath of filePaths) {
try {
await fsP.unlink(path.resolve(filePath));
} catch (e) {
console.log("error in deleting file", filePath);
}
}
// log after delete finishes
console.log("DELETED")
return;
};
```
the write function is
```js
const saveBinaryToLocalMachine = async (binaryFile) => {
const name = binaryFile.name.split("/")[2];
const binary = await binaryFile.async("nodebuffer");
const writePath = path.resolve(`./db/tmp/${name}`);
try {
await fsP.writeFile(writePath, binary);
// Log after the file is saved
console.log("file saved");
return writePath;
} catch (e) {
console.log(e);
}
};
```
The issue is when I run this code the files are not removed from the desk until the server restarts or shutdowns.
Before server restart or shutdown
[![enter image description here][1]][1]
After the server restarted.
[![enter image description here][2]][2]
Logs
[![enter image description here][3]][3]
Issue when API called for 2nd Time
[![enter image description here][4]][4]
[1]: https://i.stack.imgur.com/2shE3.png
[2]: https://i.stack.imgur.com/GRxkJ.png
[3]: https://i.stack.imgur.com/rvjcw.png
[4]: https://i.stack.imgur.com/uBoTW.png |
Larger Audio Files Getting Corrupted after upload to Google Drive |
|java|android|google-drive-api| |
This is my query:
```
DROP TABLE `tab`;
CREATE TABLE tab (
`id` INTEGER,
`user` VARCHAR(15),
`userid` INTEGER,
`user_id` INTEGER,
`ipaddr` VARCHAR(7)
);
INSERT INTO tab
(`id`, `user`, `userid`, `user_id`, `ipaddr`)
VALUES
('1', 'Client', '10', '0', '1.1.1.1'),
('2', 'admin1', '1', '0', '2.2.2.2'),
('3', 'Client', '3', '0', '1.1.1.1'),
('4', 'admin2', '5', '0', '3.3.3.3'),
('5', 'Client', '12', '0', '4.4.4.4'),
('6', 'admin1', '1', '0', '2.2.2.2'),
('7', 'Client', '21', '0', '4.4.4.4'),
('8', 'Client', '25', '0', '6.6.6.6'),
('9', 'Sub-Client 20', '35', '0', '4.4.4.4'),
('9', 'Sub-Client 20', '35', '0', '4.4.4.4'),
('9', 'Sub-Client 20', '35', '0', '1.1.1.1'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'Client', '25', '0', '6.6.6.6'),
('8', 'user1@gmail.com', '30', '0', '7.7.7.7'),
('8', 'user1@gmail.com', '30', '0', '7.7.7.7');
SELECT
COUNT(ipaddr), `ipaddr`, GROUP_CONCAT(`userid` ORDER BY `userid` DESC ) userid
FROM tab
WHERE `user` = 'Client' OR `user` LIKE 'Sub-Client%' OR `user` LIKE '%@%'
GROUP BY `ipaddr`, `userid`
HAVING COUNT(*) > 0
ORDER By COUNT(ipaddr) DESC
```
This is the result:
```
COUNT(ipaddr) ipaddr userid
2 7.7.7.7 30,30
9 6.6.6.6 25,25,25,25,25,25,25,25,25
1 4.4.4.4 12
1 4.4.4.4 21
2 4.4.4.4 35,35
1 1.1.1.1 3
1 1.1.1.1 10
1 1.1.1.1 35
```
You may see it live: https://dbfiddle.uk/N8PO_qTN
The issue is:
1. The `userid` in the output has duplicated (like 30 and 25)
1. One IP is repeated multiple times (like 1.1.1.1)
What I'm going to have this as the expected output:
```
COUNT(ipaddr) ipaddr userid
9 6.6.6.6 25
4 4.4.4.4 12, 21, 35
3 1.1.1.1 3, 10, 35
2 7.7.7.7 30
1 4.4.4.4 12
``` |
I have a textarea where users can paste text from the clipboard.
The text pasted `clipboarddata.getData('text')` gets modified.
However, I need a switch that if pressing <kbd>CTRL</kbd> <kbd>SHIFT</kbd> <kbd>V</kbd> instead of <kbd>CTRL</kbd> <kbd>V</kbd> the pasted text does not get modified.
I tried to catch the shift key with keydown/keyup:
```
$('textarea').on('keyup', function(e)
{
shiftkey_down = e.shiftKey;
});
```
and then try to read the boolean variable in the paste event handler:
```
$('textarea').on('paste', function(e)
{
if (shiftkey_down)
{
// ...
}
});
```
but the `paste` event comes after keydown and keyup. So I cannot read what key has been pressed. And `shiftkey_down` is always `false` inside the paste handler.
What would be the right way to handle this?
The only idea I got is to save the last key combination pressed inside the keydown event and then check the last one pressed inside the paste handler. But it does not seem to work either.
<br>
**Update:**
I tried to use a tiny timeout so the keydown boolean variable is not overwritten immediately:
```
var shiftkey_paste = false;
$('textarea').on('keydown', function(e)
{
if (!shiftkey_paste)
{
shiftkey_paste = e.shiftKey && e.ctrlKey;
console.log('> '+shiftkey_paste);
setTimeout( function()
{
// set false again after timeout so paste event has chance to pick up a true value
shiftkey_paste = false;
}, 10);
}
console.log('>> ' + shiftkey_paste);
});
```
And inside the paste handler, I print the value with `console.log('>>> ' + shiftkey_paste);`.
Result:
```
> false
>> false
> true
>> true
> false
>> false
>>> false
```
Also `false` even though the timeout should have helped.
<br>
**Update 2:**
✔️ Wow, it works with a timeout of 100ms instead of 10ms (!)
|
The solution did not work for me. I got it working like this:
@code {
private DateOnly? _geboortedatum;
private string GeboortedatumFormatted
{
get => _geboortedatum?.ToString("dd-MM-yyyy") ?? "";
set
{
if (DateOnly.TryParse(value, out var newDate))
{
_geboortedatum = newDate;
}
}
}
}
<div class="col-3">
<div class="form-floating mb-3">
<InputDate @bind-Value="_geboortedatum" class="form-control d-none" />
<InputText @bind-Value="GeboortedatumFormatted" class="form-control" id="geboorte-datum" placeholder="Geef geboortedatum." />
<label for="geboorte-datum" class="form-label">Geboortedatum</label>
<ValidationMessage For="() => _geboortedatum" class="text-danger" />
</div>
</div>
|
i have string:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
i want search word "Jack" only, but if Jack contain # character, its say true mean match.
i try like:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
const regexpWords = /Jack(?=,|#)/g;
console.log(text.match(regexpWords));
result say: `Array ["Jack", "Jack", "Jack"]`
My expected output is: `Array ["Jack#", "Jack#aNyWord", "Jack", "Jack"]`
except word "Jack,"
how can i do with this |
The technique described in the answer to [Is it possible to detect which View currently falls under the location of a DragGesture?](https://stackoverflow.com/q/77796978/20386264) can be used to detect, which of the squares is closest to the drag position (it was my answer).
`matchedGeometryEffect` then provides a convenient way to match the position of the blue rectangle to the identified square.
Like this:
```swift
@State private var dragLocation = CGPoint.zero
@State private var indexForDragLocation = 0
@Namespace private var ns
let spacing: CGFloat = 50
var body: some View {
HStack(spacing: spacing) {
ForEach(0...4, id: \.self) { index in
Color(white: 0.2)
.frame(width: 20, height: 20)
.matchedGeometryEffect(id: index, in: ns, isSource: index == indexForDragLocation)
.background {
GeometryReader { proxy in
let width = proxy.size.width
let midX = proxy.frame(in: .global).midX
let dx = abs(midX - dragLocation.x)
let isClosest = dx < (width + spacing) / 2
Color.clear
.onChange(of: isClosest) { oldVal, newVal in
if isClosest {
indexForDragLocation = index
}
}
}
}
}
}
.background {
RoundedRectangle(cornerRadius: 4)
.fill(.blue)
.frame(width: 40, height: 80)
.matchedGeometryEffect(
id: indexForDragLocation,
in: ns,
properties: .position,
isSource: false
)
.animation(.spring, value: indexForDragLocation)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(UIColor.systemBackground))
.gesture(
DragGesture(coordinateSpace: .global)
.onChanged { val in
dragLocation = val.location
}
)
}
```
 |
Handling Notification Click Event to Open Specific Page in .NET MAUI Blazor App (Only for windows platfrom) |
|.net|push-notification|notifications|maui|maui-blazor| |
null |
```
{
"epapconfig": {
"suffix": "Enter Choice: ",
"Display":{
"suffix": "Press return to continue..."
},
"Security":{
"suffix": "Enter Choice: ",
"Timeout":{
"suffix": "Enter Choice: ",
"Display" : {
"suffix" : "Press return to continue..."
}
}
}
},
"epapdev": {
"suffix": "]$ "
},
"su": {
"suffix": "Password: "
},
"root": {
"suffix": "]# "
}
}
```
I am importing above json file as 'json_map' in python. Now I am able to access json_map\['epapconfig'\]. but I am unable to access json_map\['epapconfig'\]\['Display'\]. . It is giving error as "'int' object is not subscriptable" . Any help will be appreciated
I want to access 'suffix' of 'Display' |
Unable to access object inside json file |
|python|json| |
null |
In **theory**, whatever you have said makes sense. It means following things are true:
- Custom elements have [**transparent**][1] content model as per specification.
- As per specification, when transparent elements are nested in each other, the process has to be applied iteratively.
So, it means that you should be allowed to create completely custom lists. So, this should work:
```html
<script>
class MyList extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `
<ul aria-label="Custom List">
<slot></slot>
</ul>
`;
}
}
class MyListItem extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `
<li>
<slot></slot>
</li>
`;
}
}
customElements.define('my-list', MyList);
customElements.define('my-list-item', MyListItem);
</script>
<my-list aria-label="Custom Wrapper">
<my-list-item>Item 1</my-list-item>
<my-list-item>Item 2</my-list-item>
</my-list>
```
In this case, the `<ul>` lives a different shadow root than those of `<li>` elements. For this above definition, the browser ends up generating the following accessibility tree (from the Chrome browser):
[![Accessibility Tree][2]][2]
So, as per specs, the browser is properly generating the accessibility tree which is was most of the tools should see. My best guess is that `axe-core` is relying on the same specs for this given test. But there in practice, things are different.
- Many assistive have custom parser which break and/or make assumption about the HTML structure (ShadowRoot is a common hindrance)
- Even the [W3C validator][3] doesn't recognize the custom elements.
- Although, the custom elements spec officially consider custom elements with transparent content model, the specs for [`<ul>`][4] and `<ol>` still explicitly restrict them to have only `<li>`, `<script>` and `<template>`. (This should be addressed in future).
So, as per spec, you are good to have custom list elements within your custom list in a completely different Shadow DOM, however in practice, the accessibility will still take a hit. If possible, better to rely on classical `ul > li` or `ol > li` hierarchy.
[1]: https://html.spec.whatwg.org/multipage/dom.html#transparent
[2]: https://i.stack.imgur.com/PKytu.png
[3]: https://validator.w3.org/
[4]: https://html.spec.whatwg.org/multipage/grouping-content.html#the-ul-element |
The problem is that Konva uses x/y coordinate system, while Mapbox uses geo coordinates. |
Is there a way to sync Mapbox canvas and Konva canvas coordinate system |
|javascript|mapbox|konvajs| |
If you want the `#` **in** the match, then you don't want a lookahead (`(?=___)`) because lookahead and lookbehind aren't included in matches. You haven't said what should be valid following the `#`, but if I assume any letter or number, then:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const text = "A Jack# Jack#aNyWord Jack, Jack";
const regexpWords = /Jack(?:#[a-zA-Z0-9]*)?/g;
console.log(text.match(regexpWords));
<!-- end snippet -->
That says
* Match `Jack`
* *Optionally* match `#` followed by any number of `[a-zA-Z0-9]`. I do that by wrapping `#[a-zA-Z0-9]*` in a non-capturing group (`(?:___)`) and then making the group optional with `?`
I've used `[a-zA-Z0-9]*` for the letters following the `#` because the expression doesn't have the `i` flag (case-insensitive matching, would match `jack`). You could use `[a-z0-9]*` if you're going to add the `i` flag. (You might also use `\w`, but it allows `_` which you may or may not want.)
MDN's regular expressions documentation is quite good: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
|
I create a file using `nano file.txt` . I typed in `Hello` hit enter and then typed `mate` so the input file looks like this:
Hello
mate
How do I replace the linefeed character in this file with `\\n` so that I can substitute this value later when I build valid json data, i.e. the expected output would be:
{"output":"Hello\\nmate"}
Right now this is my bash script
```
#!/bin/bash
expected_output=$(<file.txt)
expected_output=${expected_output//\\/\\\\}
JSON_FMT='{"output":"%s"}'
printf "%s" "$expected_output" >> aaa.txt
```
the file `aaa.txt` is being read by a different programming language where I decode the json. |
We have an iOS native project, and we are opening some Flutter screens following the official [documentation][1]. After integration, we noticed that some users are experiencing crashes in the Flutter framework. These crashes are not being reported to Crashlytics, although we can see them in the Apple Feedback Crashes tool.
Attached is the stack trace of one of the crashes that we personally encountered and submitted to the Apple Feedback tool, but we didn't observe it in Firebase Crashlytics.
Incident Identifier: 3CE97C56-4B18-4ED3-BC6D-1CCE93618492
Hardware Model: iPhone15,3
Process: MyNativeApp [29650]
Path: /private/var/containers/Bundle/Application/F2506398-CA6C-4466-AF8E-A58F87560C67/MyNativeApp.app/MyNativeApp
Identifier: com.MyNativeApp.ios.MyNativeAppapp
Version: 1.0.0 (1)
AppStoreTools: 15C5500a
AppVariant: 1:iPhone15,3:17
Beta: YES
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: com.MyNativeApp.ios.production.MyNativeAppapp [4331]
Date/Time: 2024-01-09 16:50:58.9132 +0300
Launch Time: 2024-01-09 16:47:45.9748 +0300
OS Version: iPhone OS 17.1.1 (21B91)
Release Type: User
Baseband Version: 2.0.03
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Triggered by Thread: 11
Kernel Triage:
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
Thread 0:
0 libsystem_kernel.dylib 0x00000001ed738b7c __psynch_cvwait + 8 (:-1)
1 libsystem_pthread.dylib 0x000000020fc84fd4 _pthread_cond_wait + 1228 (pthread_cond.c:862)
2 Flutter 0x000000010800ef40 std::_LIBCPP_ABI_NAMESPACE::condition_variable::wait(std::_LIBCPP_ABI_NAMESPACE::unique_lock<std::_LIBCPP_ABI_NAMESPACE::mutex>&) + 20 (condition_variable.cpp:47)
3 Flutter 0x000000010829f60c fml::AutoResetWaitableEvent::Wait() + 56 (waitable_event.cc:0)
4 Flutter 0x00000001083c495c flutter::Shell::Screenshot(flutter::Rasterizer::ScreenshotType, bool) + 344 (shell.cc:2137)
5 Flutter 0x0000000107fe34c8 -[FlutterView drawLayer:inContext:] + 100 (FlutterView.mm:151)
6 QuartzCore 0x00000001a7ab1768 -[CALayer _renderForegroundInContext:] + 1712 (CALayer.mm:9633)
7 QuartzCore 0x00000001a7ab2ae8 -[CALayer renderInContext:] + 1200 (CALayer.mm:9153)
8 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
9 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
10 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
11 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
12 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
13 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
14 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
15 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
16 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
17 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
18 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
19 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
20 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
21 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
22 QuartzCore 0x00000001a7ab1050 -[CALayer _renderSublayersInContext:] + 332 (CALayer.mm:9677)
23 QuartzCore 0x00000001a7ab2af4 -[CALayer renderInContext:] + 1212 (CALayer.mm:9154)
24 MyNativeApp 0x00000001013c5bd0 -[UXViewVideoHandler renderLayer:inContent:] + 52
25 libdispatch.dylib 0x00000001ae1e9300 _dispatch_client_callout + 20 (object.m:561)
26 libdispatch.dylib 0x00000001ae1f878c _dispatch_async_and_wait_invoke + 92 (queue.c:1570)
27 libdispatch.dylib 0x00000001ae1e9300 _dispatch_client_callout + 20 (object.m:561)
28 libdispatch.dylib 0x00000001ae1f7998 _dispatch_main_queue_drain + 984 (queue.c:7813)
29 libdispatch.dylib 0x00000001ae1f75b0 _dispatch_main_queue_callback_4CF + 44 (queue.c:7973)
30 CoreFoundation 0x00000001a626320c __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1780)
31 CoreFoundation 0x00000001a625ff18 __CFRunLoopRun + 1996 (CFRunLoop.c:3149)
32 CoreFoundation 0x00000001a625f668 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420)
33 GraphicsServices 0x00000001e962a5ec GSEventRunModal + 164 (GSEvent.c:2196)
34 UIKitCore 0x00000001a867c2b4 -[UIApplication _run] + 888 (UIApplication.m:3685)
35 UIKitCore 0x00000001a867b8f0 UIApplicationMain + 340 (UIApplication.m:5270)
36 MyNativeApp 0x0000000100502da4 main + 176 (main.swift:11)
37 dyld 0x00000001c8cb2dcc start + 2240 (dyldMain.cpp:1269)
Thread 1:
0 libsystem_pthread.dylib 0x000000020fc859fc start_wqthread + 0 (:-1)
Thread 2:
0 libsystem_kernel.dylib 0x00000001ed7381d8 mach_msg2_trap + 8 (:-1)
1 libsystem_kernel.dylib 0x00000001ed737f70 mach_msg2_internal + 80 (mach_msg.c:201)
2 libsystem_kernel.dylib 0x00000001ed737e88 mach_msg_overwrite + 436 (mach_msg.c:0)
3 libsystem_kernel.dylib 0x00000001ed737cc8 mach_msg + 24 (mach_msg.c:323)
4 CoreFoundation 0x00000001a6261d0c __CFRunLoopServiceMachPort + 160 (CFRunLoop.c:2624)
5 CoreFoundation 0x00000001a625fc04 __CFRunLoopRun + 1208 (CFRunLoop.c:3007)
6 CoreFoundation 0x00000001a625f668 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420)
7 Foundation 0x00000001a51f854c -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212 (NSRunLoop.m:373)
8 Foundation 0x00000001a522627c -[NSRunLoop(NSRunLoop) runUntilDate:] + 64 (NSRunLoop.m:420)
9 UIKitCore 0x00000001a85ddfc8 -[UIEventFetcher threadMain] + 420 (UIEventFetcher.m:1208)
10 Foundation 0x00000001a527d184 __NSThread__start__ + 732 (NSThread.m:991)
11 libsystem_pthread.dylib 0x000000020fc864d4 _pthread_start + 136 (pthread.c:904)
12 libsystem_pthread.dylib 0x000000020fc85a10 thread_start + 8 (:-1)
Thread 11 Crashed:
0 libsystem_kernel.dylib 0x00000001ed74101c __pthread_kill + 8 (:-1)
1 libsystem_pthread.dylib 0x000000020fc89680 pthread_kill + 268 (pthread.c:1681)
2 libsystem_c.dylib 0x00000001ae2a1b90 abort + 180 (abort.c:118)
3 Flutter 0x000000010829c688 fml::LogMessage::~LogMessage() + 0 (logging.cc:100)
4 Flutter 0x000000010829c854 fml::FileMapping::CreateReadOnly(std::_LIBCPP_ABI_NAMESPACE::basic_string<char, std::_LIBCPP_ABI_NAMESPACE::char_traits<char>, std::_LIBCPP_ABI_NAMESPACE::allocator<char>> const&) + 0 (mapping.cc:21)
5 Flutter 0x000000010830e878 flutter::DlSkCanvasDispatcher::drawTextFrame(std::_LIBCPP_ABI_NAMESPACE::shared_ptr<impeller::TextFrame> const&, float, float) + 56 (dl_sk_dispatcher.cc:278)
6 Flutter 0x00000001082f8c88 flutter::DisplayList::Dispatch(flutter::DlOpReceiver&, unsigned char*, unsigned char*, flutter::Culler&) const + 3068 (display_list.cc:197)
7 Flutter 0x000000010830b1c0 flutter::DlSkCanvasAdapter::DrawDisplayList(sk_sp<flutter::DisplayList>, float) + 324 (dl_sk_canvas.cc:0)
8 Flutter 0x000000010845e928 flutter::DisplayListLayer::Paint(flutter::PaintContext&) const + 2128 (display_list_layer.cc:160)
9 Flutter 0x000000010845d138 flutter::ContainerLayer::PaintChildren(flutter::PaintContext&) const + 88 (container_layer.cc:0)
10 Flutter 0x000000010845b884 flutter::ClipShapeLayer<SkRect>::Paint(flutter::PaintContext&) const + 756 (clip_shape_layer.h:100)
11 Flutter 0x000000010845d138 flutter::ContainerLayer::PaintChildren(flutter::PaintContext&) const + 88 (container_layer.cc:0)
12 Flutter 0x0000000108467180 flutter::TransformLayer::Paint(flutter::PaintContext&) const + 84 (transform_layer.cc:75)
13 Flutter 0x000000010845d138 flutter::ContainerLayer::PaintChildren(flutter::PaintContext&) const + 88 (container_layer.cc:0)
14 Flutter 0x0000000108467180 flutter::TransformLayer::Paint(flutter::PaintContext&) const + 84 (transform_layer.cc:75)
15 Flutter 0x000000010845d138 flutter::ContainerLayer::PaintChildren(flutter::PaintContext&) const + 88 (container_layer.cc:0)
16 Flutter 0x0000000108467180 flutter::TransformLayer::Paint(flutter::PaintContext&) const + 84 (transform_layer.cc:75)
17 Flutter 0x000000010845d138 flutter::ContainerLayer::PaintChildren(flutter::PaintContext&) const + 88 (container_layer.cc:0)
18 Flutter 0x000000010845b884 flutter::ClipShapeLayer<SkRect>::Paint(flutter::PaintContext&) const + 756 (clip_shape_layer.h:100)
19 Flutter 0x000000010845d138 flutter::ContainerLayer::PaintChildren(flutter::PaintContext&) const + 88 (container_layer.cc:0)
20 Flutter 0x0000000108467180 flutter::TransformLayer::Paint(flutter::PaintContext&) const + 84 (transform_layer.cc:75)
21 Flutter 0x000000010845d138 flutter::ContainerLayer::PaintChildren(flutter::PaintContext&) const + 88 (container_layer.cc:0)
22 Flutter 0x0000000108463ef0 flutter::LayerTree::Paint(flutter::CompositorContext::ScopedFrame&, bool) const + 1308 (layer_tree.cc:0)
23 Flutter 0x000000010845860c flutter::CompositorContext::ScopedFrame::Raster(flutter::LayerTree&, bool, flutter::FrameDamage*) + 3684 (compositor_context.cc:154)
24 Flutter 0x00000001083a6ec0 flutter::Rasterizer::ScreenshotLayerTreeAsImage(flutter::LayerTree*, flutter::CompositorContext&, GrDirectContext*, bool) + 276 (rasterizer.cc:755)
25 Flutter 0x00000001083a5800 flutter::Rasterizer::ScreenshotLastLayerTree(flutter::Rasterizer::ScreenshotType, bool) + 868 (rasterizer.cc:0)
26 Flutter 0x00000001083c4ba0 std::_LIBCPP_ABI_NAMESPACE::__function::__func<flutter::Shell::Screenshot(flutter::Rasterizer::ScreenshotType, bool)::$_0, std::_LIBCPP_ABI_NAMESPACE::allocator<flutter::Shell::Screenshot(flutter::Rasterizer::ScreenshotType, bool)::$_0>, void ()>::operator()() + 64 (function.h:359)
27 Flutter 0x000000010829db9c fml::MessageLoopImpl::FlushTasks(fml::FlushType) + 568 (message_loop_impl.cc:128)
28 Flutter 0x00000001082a1330 fml::MessageLoopDarwin::OnTimerFire(__CFRunLoopTimer*, fml::MessageLoopDarwin*) + 32 (message_loop_darwin.mm:86)
29 CoreFoundation 0x00000001a62d95d0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 32 (CFRunLoop.c:1797)
30 CoreFoundation 0x00000001a62d9278 __CFRunLoopDoTimer + 1004 (CFRunLoop.c:2404)
31 CoreFoundation 0x00000001a6262e74 __CFRunLoopDoTimers + 288 (CFRunLoop.c:2562)
32 CoreFoundation 0x00000001a625fe8c __CFRunLoopRun + 1856 (CFRunLoop.c:3122)
33 CoreFoundation 0x00000001a625f668 CFRunLoopRunSpecific + 608 (CFRunLoop.c:3420)
34 Flutter 0x00000001082a141c fml::MessageLoopDarwin::Run() + 88 (message_loop_darwin.mm:52)
35 Flutter 0x00000001082a0a90 void* std::_LIBCPP_ABI_NAMESPACE::__thread_proxy[abi:v15000]<std::_LIBCPP_ABI_NAMESPACE::tuple<std::_LIBCPP_ABI_NAMESPACE::unique_ptr<std::_LIBCPP_ABI_NAMESPACE::__thread_struct, std::_LIBCPP_ABI_NAMESPACE::default_delete<std::_LIBCPP_ABI_NAMESPACE::__thread_struct>>, fml::Thread::Thread(std::_LIBCPP_ABI_NAMESPACE::function<void (fml::Thread::ThreadConfig const&)> const&, fml::Thread::ThreadConfig const&)::$_0>>(void*) + 208 (thread:295)
36 libsystem_pthread.dylib 0x000000020fc864d4 _pthread_start + 136 (pthread.c:904)
37 libsystem_pthread.dylib 0x000000020fc85a10 thread_start + 8 (:-1)
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.16.1, on macOS 14.2 23C64 darwin-arm64, locale en-SA)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 15.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] VS Code (version 1.85.1)
[✓] VS Code (version 1.74.3)
[✓] Connected device (4 available)
! Error: Browsing on the local area network for Ali’s iPhone. Ensure the device is unlocked and attached with a cable or associated with the same local area network as this Mac.
The device must be opted into Developer Mode to connect wirelessly. (code -27)
[✓] Network resources
• No issues found!
QTYPFWXD6G:FlutterDesktop a.ali15$ flutter --version
Flutter 3.16.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7f20e5d18c (7 weeks ago) • 2023-11-27 09:47:30 -0800
Engine • revision 22b600f240
Tools • Dart 3.2.1 • DevTools 2.28.3
QTYPFWXD6G:FlutterDesktop a.ali15$
[1]: https://docs.flutter.dev/add-to-app/ios/add-flutter-screen?tab=no-engine-vc-uikit-swift-tab
[2]: https://i.stack.imgur.com/4r7VM.png
[3]: https://i.stack.imgur.com/Jg9jD.png
|
I have created a 3D plot using Plotly in Python to visualize the orbits of Earth and Mars around the Sun. The plot displays the orbits of Earth and Mars as lines, and their positions as markers. There is also a slider to animate the positions of Earth and Mars over time.
The problem I'm facing is that when I initially load the plot, I can see the orbits of Earth and Mars, and everything looks fine. However, as soon as I touch the slider to animate the positions, the orbits of Earth and Mars disappear. I want to keep both the orbits and the positions of Earth and Mars visible when using the slider.
I've shared the relevant code below:
```
import numpy as np
import plotly.graph_objects as go
from astropy.time import Time
from astropy.coordinates import get_body_barycentric
def plot_earth_and_mars_orbit(start_date, end_date):
# Convert start and end dates to Julian Dates
jd_start = start_date.jd
jd_end = end_date.jd
# Define the range of dates
jd_range = np.linspace(jd_start, jd_end, 365)
dates = Time(jd_range, format='jd')
# Get the position of Earth and Mars relative to the Solar System barycenter
earth_positions = [get_body_barycentric('earth', date).xyz.to_value('au') for date in dates]
mars_positions = [get_body_barycentric('mars', date).xyz.to_value('au') for date in dates]
# Extract X, Y, and Z components for Earth and Mars
x_earth, y_earth, z_earth = np.array(earth_positions).T
x_mars, y_mars, z_mars = np.array(mars_positions).T
# Create a 3D plot
fig = go.Figure()
# Add Earth's and Mars' orbit as lines
fig.add_trace(go.Scatter3d(x=x_earth, y=y_earth, z=z_earth, mode='lines', name='Earth Orbit'))
fig.add_trace(go.Scatter3d(x=x_mars, y=y_mars, z=z_mars, mode='lines', name='Mars Orbit'))
# Add initial position of Earth and Mars as markers
fig.add_trace(go.Scatter3d(x=[x_earth[0]], y=[y_earth[0]], z=[z_earth[0]], mode='markers', marker=dict(size=5, color='blue'), name='Earth'))
fig.add_trace(go.Scatter3d(x=[x_mars[0]], y=[y_mars[0]], z=[z_mars[0]], mode='markers', marker=dict(size=5, color='red'), name='Mars'))
# Add the Sun at the origin (Solar System barycenter)
fig.add_trace(go.Scatter3d(x=[0], y=[0], z=[0], mode='markers', marker=dict(size=10, color='yellow'), name='Sun'))
# Define steps for the slider
steps = []
for i, date in enumerate(dates):
step = dict(
method="update",
args=[{
# Update only the positions of Earth and Mars
"x": [[], [], [x_earth[i]], [x_mars[i]], [0]], # Update Earth and Mars x positions
"y": [[], [], [y_earth[i]], [y_mars[i]], [0]], # Update Earth and Mars y positions
"z": [[], [], [z_earth[i]], [z_mars[i]], [0]], # Update Earth and Mars z positions
}, {
"title": f"Date: {date.iso}" # Update the plot title to show the current date
}],
label=date.datetime.strftime('%Y-%m-%d')
)
steps.append(step)
# Create the sliders using the steps
sliders = [dict(
active=0,
currentvalue={"prefix": "Date: "},
pad={"t": 50},
steps=steps
)]
# Update the layout of the plot
fig.update_layout(
title='Earth and Mars Orbit around the Sun',
sliders=sliders,
scene=dict(
xaxis_title='X (AU)', yaxis_title='Y (AU)', zaxis_title='Z (AU)',
xaxis=dict(range=[-2.5, 2.5]), yaxis=dict(range=[-2.5, 2.5]), zaxis=dict(range=[-2.5, 2.5]),
aspectmode='cube'
)
)
fig.show()
start_date = Time('2021-01-01')
end_date = Time('2024-12-31')
plot_earth_and_mars_orbit(start_date, end_date)
```
Why do the orbits of Earth and Mars disappear when I use the slider?
How can I modify my code to ensure that the orbits of Earth and Mars remain visible while updating the positions of Earth and Mars with the slider?
Any insights or suggestions would be greatly appreciated. I am also open for a completely different approach. Thank you! |
Orbits of Earth and Mars Disappear When Slider is Used in 3D Plotly Graph |
|python|plotly| |
If your input looks like this:
$ cat file
Hello
mate
and you want to replace all LineFeeds except the last one (assuming it's a valid POSIX text file) with `\\n` then you could do the following using any awk:
$ awk '{rec=rec sep $0; sep="\\\\n"} END{printf "{\"output\":\"%s\"}\n", rec}' file
{"output":"Hello\\nmate"}
---------
Original answer when the OP said their input looked like:
$ cat file
Hello\nmate
Using any sed:
$ sed 's/\\/\\\\/' file
Hello\\nmate
$ sed 's/\(.*\)\\\(.*\)/{"output":"\1\\\\\2"}/' file
{"output":"Hello\\nmate"}
|
Am trying to automate one of my application using web driver sampler with JMeter but getting error (please check below). Tried with Chrome, Chromium & Gecko driver.
Version of Tool:
1. JMeter : 5.3
2. Java Version : java version "17.0.6" 2023-01-17 LTS
3. Chrome driver : 120 as the chrome version of the system is 120.0 (driver catalog : https://googlechromelabs.github.io/chrome-for-testing/#stable)
4. Web Driver Version : 4.13.0
Sample Code inside the web driver sampler with scripting language (beanshell although tried with JAVA and Groovy, observed same error):
var driverHandler = JavaImporter(org.openqa.selenium, org.openqa.selenium.support.ui);
var sleepSynchronizer = new driverHandler.WebDriverWait(WDS.browser, 5000);
driverHandler.sampleResult.sampleStart();
//Render the home Page
WDS.browser.get('<application URL>');
sleepSynchronizer.until(driverHandler.ExpectedConditions.elementToBeClickable(sleepSynchronizer.By.id('details-button')));
//Handling Cookies
var sessionCOOKIES = WDS.browser.manage().getCookies();
WDS.vars.putObject('cookies', sessionCOOKIES)
java.lang.Thread.sleep(6000);
**Error while using Chrome Driver:**
2024-01-13 19:55:24,522 ERROR o.a.j.JMeter: Uncaught exception in thread Thread[Thread Group 1-1,6,main]
java.lang.NoClassDefFoundError: Could not initialize class org.openqa.selenium.remote.http.netty.NettyClient
at org.openqa.selenium.remote.http.netty.NettyClient$Factory.createClient(NettyClient.java:124) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:115) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:92) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:89) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.chromium.ChromiumDriverCommandExecutor.<init>(ChromiumDriverCommandExecutor.java:43) ~[selenium-chromium-driver-4.13.0.jar:?]
**Error while using Firefox(Gecko) Driver:**
2024-01-13 19:37:27,069 ERROR o.a.j.JMeter: Uncaught exception in thread Thread[Thread Group 1-1,6,main]
java.lang.NoClassDefFoundError: Could not initialize class org.openqa.selenium.remote.http.netty.NettyClient
at org.openqa.selenium.remote.http.netty.NettyClient$Factory.createClient(NettyClient.java:124) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:115) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:92) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:89) ~[selenium-remote-driver-4.13.0.jar:?]
at org.openqa.selenium.firefox.FirefoxDriver$FirefoxDriverCommandExecutor.<init>(FirefoxDriver.java:415) ~[selenium-firefox-driver-4.13.0.jar:?]
at org.openqa.selenium.firefox.FirefoxDriver.generateExecutor(FirefoxDriver.java:147) ~[selenium-firefox-driver-4.13.0.jar:?]
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:132) ~[selenium-firefox-driver-4.13.0.jar:?]
**Error while using Chromium Driver:**
*Note:* In chromium the browser is launching with the following error,
2024-01-13 19:38:16,709 ERROR o.a.j.t.JMeterThread: Error calling threadStarted
org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '4.13.0', revision: 'ba948ece5b*'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.6'
Driver info: driver.version: unknown
at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:248) ~[selenium-remote-driver-4.13.0.jar:?]
at com.googlecode.jmeter.plugins.webdriver.config.ChromeDriverConfig.getThreadService(ChromeDriverConfig.java:47) ~[jmeter-plugins-webdriver-4.13.0.0.jar:?]
at com.googlecode.jmeter.plugins.webdriver.config.ChromeDriverConfig.createBrowser(ChromeDriverConfig.java:26) ~[jmeter-plugins-webdriver-4.13.0.0.jar:?]
at com.googlecode.jmeter.plugins.webdriver.config.ChromeDriverConfig.createBrowser(ChromeDriverConfig.java:14) ~[jmeter-plugins-webdriver-4.13.0.0.jar:?]
at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.getPreparedBrowser(WebDriverConfig.java:221) ~[jmeter-plugins-webdriver-4.13.0.0.jar:?]
at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.threadStarted(WebDriverConfig.java:152) ~[jmeter-plugins-webdriver-4.13.0.0.jar:?]
at org.apache.jmeter.threads.JMeterThread$ThreadListenerTraverser.addNode(JMeterThread.java:769) [ApacheJMeter_core.jar:5.3]
Is there any way to fix this issue ? |
Webdriver Sampler not working with JMeter |
An example to add permission
```
/** @type {import("@expo/config-plugins").ConfigPlugin} */
const defineConfig = (config) => {
const { AndroidConfig, withAndroidManifest } = require('@expo/config-plugins');
config = withAndroidManifest(config, (config) => {
let androidManifest = config.modResults.manifest;
const permissions = androidManifest["uses-permission"] || [];
androidManifest["uses-permission"] = [...permissions, {
$: {
'android:name': 'android.permission.WAKE_LOCK',
}
}]
return config
})
return config
}
module.exports = defineConfig;
``` |
No, it is not because of the cache's max size (you would get the same results with `maxsize=3`). You get these statistics because you make life easier for the call to `fib(9)` by already having made the call to `fib(8)` before the loop. Realize also that these statistics are not only about *one* of your calls, but of *all* your calls thus far. `fib(9)` does not make as many hits as you suggest. It just has a hit for `fib(8)` and for `fib(7)` and that's it.
If you would not have made the call to `fib(8)` before the loop, you would get one less hit in the statistics in the first iteration of the loop. This is expected.
In your version, you made one more call to `fib(8)` in total: by the time you make the call `fib(9)`, there is an extra hit counted for `fib(8)`, while if you would not have made `fib(8)` before the loop, then it is not a hit when `fib(9)` is called.
This effect is similar when you go to the next iteration of the loop: since the previous iteration already cached the result for an argument that is one less, the current call will have a hit in its first recursive call. |
I have a simple static HTML page using MarkMap. I link to two required libraries to enable the functionality. I don't quite know why I can render the mindmap AND the default Toolbar, but no clicks on the toolbar perform the corresponding actions (e.g., Zoom In, Zoom Out, Recenter, etc.). Any help is greatly appreciated.
`Code` and Stackblitz link follow:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Markmap</title>
<style>
svg.markmap {
width: 100%;
height: 100vh;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/markmap-autoloader@0.16"></script>
<script src="https://cdn.jsdelivr.net/npm/markmap-toolbar@0.16.0"></script>
</head>
<body>
<div id="container">
<div id="mm" class="markmap">
<script type="text/template">
---
markmap:
maxWidth: 300
colorFreezeLevel: 2
---
# markmap
## Links
- <https://markmap.js.org/>
- [GitHub](https://github.com/markmap/markmap)
## Related
- [coc-markmap](https://github.com/markmap/coc-markmap)
- [gatsby-remark-markmap](https://github.com/markmap/gatsby-remark-markmap)
## Features
- links
- **inline** ~~text~~ *styles*
- multiline
text
- `inline code`
- Katex - $x = {-b \pm \sqrt{b^2-4ac} \over 2a}$
- This is a very very very very very very very very very very very very very very very long line.
</script>
<script>
const { markmap } = window;
const { Toolbar } = markmap;
const { el } = Toolbar.create(mm);
el.style.position = 'absolute';
el.style.bottom = '0.5rem';
el.style.right = '0.5rem';
// `container` could be the element that contains both the markmap and the toolbar
container.append(el);
</script>
</div>
</div>
</body>
</html>
```
[StackBlitz working demo here](https://stackblitz.com/edit/markmap-autoloader-hqtg4z?file=index.html) |
Calling `await` blocks until the promise is resolved or rejected, so that means that calling `controller.abort()` rigth after the loop has started won't be effective until the promise has resolved and the loop starts over.
Adding an event listener (if you're working with nodejs you can use event emitters) to your cancellable async function might do the trick, maybe this example helps you to achieve what you want:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function myCancellableFunction (signal) {
return new Promise((res,rej) => {
if (signal.aborted) return rej();
const cancellableHandler = () => {
// you may also want to perform a clean up here
// like removing the timeout from your timeouts list
signal.removeEventListener("abort",cancellableHandler);
rej();
}
signal.addEventListener("abort",cancellableHandler);
setTimeout(res,2000);
})
}
async function myLoopSignalFunction (signal) {
while (true) {
console.log("While loop beginning");
// You can stop the while loop catching the error and breaking
try {
console.time("Cancellable elapsed time");
await myCancellableFunction(signal);
console.log("Cancellable function has been executed");
console.timeEnd("Cancellable elapsed time");
} catch(e) {
console.log("Function has been canceled");
break;
}
}
}
async function main () {
let controller = new AbortController();
myLoopSignalFunction(controller.signal);
setTimeout(() => {
controller.abort();
setTimeout(() => {
controller = new AbortController()
controller.abort()
myLoopSignalFunction(controller.signal); // The controller is already aborted, nothing to do
},1000);
},10000);
}
main()
<!-- end snippet -->
|
We are facing the following issue with the following API `Locale.isoRegionCodes` which has been deprecated from iOS >= 16. The new API is the following `Locale.Region.isoRegions` but when doing a mapping like the following the `region.identifier` returns the code 001.
if #available(iOS 16, *) {
let CountryCodeWithNewApi = Locale.Region.isoRegions.map { region in
CustomCountry(value: "", key: region.identifier)
}.sorted(by: { $0.value < $1.value })
} else {
// Fallback on earlier versions
}
How do we get the old country codes of 2 letters by deriving it from this code? is it possible or we are required to do a manual mapping of the ISO-3166-alpha 2 codes to be able to display all the country codes to the user? |
Getting country code (ISO-3166-alpha2 standard) for iOS >= 16 after deprecated Locale.isoRegionCodes API? |
|ios|swift|iphone|iso-3166| |
If you look at the page, the borders overlap and thicken due to the detail section. Why doesn't the following work? I tried removing all the borders of the details class with CSS, but it didn't work. The bottem border is always there and overlaps. I'll be happy if you can help me.
[enter image description here][1]
td colspan="100%" class="details"style="padding: 0 !important; border-bottom: none !important;"
it does not work.
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap Bundle JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<style>
.list-group {
max-height: 320px;
/* veya istediğiniz başka bir değer */
overflow-y: auto;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 ps-0 pe-0">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th scope="col">Kitap</th>
<th scope="col">Poz No</th>
<th scope="col">Eski Poz No</th>
<th scope="col">Tanım</th>
<th scope="col">Tür</th>
<th scope="col">Birim</th>
<th scope="col">Güncel Fiyat</th>
<th scope="col">Detay</th>
</tr>
</thead>
<tbody id="table-content">
<tr>
<td>Karayolları 2012 ve Sonrası</td>
<td>01.001</td>
<td>10.100.1001</td>
<td>Pist Beton Kaplama Ustası (Hava Meydanları İnş.İçin) </td>
<td>Rayiç</td>
<td>Kg</td>
<td>1415.00 TL</td>
<td><b type="button" class="collapse-button" data-bs-toggle="collapse"
data-bs-target="#details_251" aria-expanded="false" aria-controls="details_251"
onclick="toggleCaret('details_251')">
Detay
<i class="ph-bold ph-caret-down caret-icon"></i>
</b></td>
</tr>
<tr class="tr-detail" data-id="251">
<td colspan="100%" class="details"
style="padding: 0 !important; border-bottom: none !important;">
<div id="details_251" class="collapse table-details">
<div class="container-fluid">
<li class="list-group-item">
<div class="d-flex align-items-center">
<a href="#" download style="background-color: #efe81d; padding: 6px 15px; color: #0b0b0b; text-decoration: none; border-radius: 4px; margin-left: 20px;
transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#eff81d';"
onmouseout="this.style.backgroundColor='#efe81d';">
<i class="fa-solid fa-circle-info pe-2"></i><strong>Detay
Sayfasına Git</strong>
</a>
<a href="#" download style="background-color: #1D6F42; padding: 5px 15px; color: #fff; text-decoration: none; border-radius: 4px; margin-left: 20px;
transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#1DaF42';"
onmouseout="this.style.backgroundColor='#1D6F42';">
<i class="fa-regular fa-file-excel pe-1"></i>Analizi İndir
</a>
</div>
</li>
<div class="col-md-12">
<div class="row">
<div class="col-md-9 mt-4 d-flex flex-column">
<h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyat Tarifi
</h4>
<div class="d-flex flex-column border rounded bg-white"
style="overflow-y: auto; flex-grow: 1; padding: 0;">
<p style="flex-grow: 1; padding: 15px; margin: 0;">Lorem
ipsum dolor sit amet consectetur
adipisicing elit. Qui ratione, magni iusto voluptates
esse dolorem, deleniti accusamus, ipsa
corrupti saepe hic vitae porro voluptatum earum soluta
maiores molestiae rem officia? Quos
veritatis eum amet ipsa saepe recusandae vel ad
excepturi obcaecati optio culpa quae
assumenda perspiciatis possimus iste numquam ducimus
enim nostrum sit, perferendis, harum
distinctio. Ratione magnam provident fuga? At harum,
voluptate dignissimos ex unde fugiat
sit voluptatem ipsa ipsum reiciendis numquam! Natus
obcaecati praesentium, in quaerat
dolorum ullam magni omnis veritatis, numquam amet, sint
voluptatum modi odit culpa?
Voluptatem ducimus nisi consequatur consequuntur non
quidem quod repudiandae labore saepe
amet nulla minima, consectetur ex rerum nam
necessitatibus officiis? Voluptatibus recusandae
reprehenderit voluptas voluptate architecto illum? Eos,
consequuntur molestiae.</p>
</div>
</div>
<div class="col-md-3 mt-4 d-flex flex-column">
<h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyatlar</h4>
<ul class="list-group flex-grow-1">
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<!-- Include other years here -->
</ul>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td>Karayolları 2012 ve Sonrası</td>
<td>01.001</td>
<td>10.100.1001</td>
<td>Pist Beton Kaplama Ustası (Hava Meydanları İnş.İçin) </td>
<td>Rayiç</td>
<td>Kg</td>
<td>1415.00 TL</td>
<td><b type="button" class="collapse-button" data-bs-toggle="collapse"
data-bs-target="#details_252" aria-expanded="false" aria-controls="details_252"
onclick="toggleCaret('details_252')">
Detay
<i class="ph-bold ph-caret-down caret-icon"></i>
</b></td>
</tr>
<tr class="tr-detail" data-id="252">
<td colspan="100%" class="details"
style="padding: 0 !important; border-bottom: none !important;">
<div id="details_252" class="collapse table-details">
<div class="container-fluid">
<li class="list-group-item">
<div class="d-flex align-items-center">
<a href="#" download style="background-color: #efe81d; padding: 6px 15px; color: #0b0b0b; text-decoration: none; border-radius: 4px; margin-left: 20px;
transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#eff81d';"
onmouseout="this.style.backgroundColor='#efe81d';">
<i class="fa-solid fa-circle-info pe-2"></i><strong>Detay
Sayfasına Git</strong>
</a>
<a href="#" download style="background-color: #1D6F42; padding: 5px 15px; color: #fff; text-decoration: none; border-radius: 4px; margin-left: 20px;
transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#1DaF42';"
onmouseout="this.style.backgroundColor='#1D6F42';">
<i class="fa-regular fa-file-excel pe-1"></i>Analizi İndir
</a>
</div>
</li>
<div class="col-md-12">
<div class="row">
<div class="col-md-9 mt-4 d-flex flex-column">
<h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyat Tarifi
</h4>
<div class="d-flex flex-column border rounded bg-white"
style="overflow-y: auto; flex-grow: 1; padding: 0;">
<p style="flex-grow: 1; padding: 15px; margin: 0;">Lorem
ipsum dolor sit amet consectetur
adipisicing elit. Qui ratione, magni iusto voluptates
esse dolorem, deleniti accusamus, ipsa
corrupti saepe hic vitae porro voluptatum earum soluta
maiores molestiae rem officia? Quos
veritatis eum amet ipsa saepe recusandae vel ad
excepturi obcaecati optio culpa quae
assumenda perspiciatis possimus iste numquam ducimus
enim nostrum sit, perferendis, harum
distinctio. Ratione magnam provident fuga? At harum,
voluptate dignissimos ex unde fugiat
sit voluptatem ipsa ipsum reiciendis numquam! Natus
obcaecati praesentium, in quaerat
dolorum ullam magni omnis veritatis, numquam amet, sint
voluptatum modi odit culpa?
Voluptatem ducimus nisi consequatur consequuntur non
quidem quod repudiandae labore saepe
amet nulla minima, consectetur ex rerum nam
necessitatibus officiis? Voluptatibus recusandae
reprehenderit voluptas voluptate architecto illum? Eos,
consequuntur molestiae.</p>
</div>
</div>
<div class="col-md-3 mt-4 d-flex flex-column">
<h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyatlar</h4>
<ul class="list-group flex-grow-1">
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<li
class="list-group-item d-flex justify-content-between align-items-center">
2014
<span class="badge-custom"
style="font-size: 0.9em;">4.152,21</span>
</li>
<!-- Include other years here -->
</ul>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
```
<td colspan="100%" class="details"style="padding: 0 !important; border-bottom: none !important;"> it does not work.
[1]: https://i.stack.imgur.com/SHxW7.png |
@lundin be calm. you both tell me where is chatgpt can be useful ? |
QML WebEngineView doesn't play YouTube video if the video hasn't 480p quality |
|youtube|qml|qwebengineview| |
null |
I have the following code :
```cs
List<MyComplexObject> listInMemory = new List<MyComplexObject>
{
new MyComplexObject { Id1 = 1, Id2 = 2, Name = "Name1" },
new MyComplexObject { Id1 = 3, Id2 = 4, Name = "Name2" }
};
// And a DbSet in your DbContext
public DbSet<MyEntity> MyEntities { get; set; }
// You can join them like this
var result = MyEntities
.Join(listInMemory,
entity => new { entity.Id1, entity.Id2 },
complexObject => new { complexObject.Id1, complexObject.Id2 },
(entity, complexObject) => entity);
```
I'm trying to verify a list of elements that exist in memory against something in my database, but I get this error:
> resultSelector: (entity, complexObject) => entity)' could not be translated |
How can I perform a join operation between an in-memory list and a SQL database table using EF Core |
I'm creating an EKS cluster with Pulumi Crosswalk:
```go
// vpc creation skipped
cluster, err := eks.NewCluster(ctx, ClusterName, &eks.ClusterArgs{
Name: pulumi.String(ClusterName),
VpcId: vpc.VpcId,
PublicSubnetIds: vpc.PublicSubnetIds,
PrivateSubnetIds: vpc.PrivateSubnetIds,
NodeAssociatePublicIpAddress: pulumi.BoolRef(false),
CreateOidcProvider: pulumi.BoolPtr(true),
})
if err != nil {
return err
}
```
this works as expected.
Now I want to add some EKS addons:
```go
_, err = peks.NewAddon(ctx, "csiEbsAddon", &peks.AddonArgs{
ClusterName: cluster.Core.ApplyT(
func(core eks.CoreData) pulumi.StringOutput {
return core.Cluster.Name
},
).(pulumi.StringOutput),
AddonName: pulumi.String("aws-ebs-csi-driver"),
})
```
this doesn't work, and I don't understand the error nor what I am doing wrong:
Error:
```
Diagnostics:
pulumi:pulumi:Stack (infrastructure-dev):
error: an unhandled error occurred: program failed:
waiting for RPCs: marshaling properties: awaiting input property "clusterName": expected a eks.Cluster, got a resource of type eks.Cluster
```
any help appreciated! |
I am newbie to prometheus and grafana. In Prometheus I have SysUptime.0 values from all my network nodes.
Now, I am trying to write formula in Grafana which will calculate node availability over time using SysUptime.0 snmp variable vaule ,which is collected through snmp_exporter in Prometheus.
I tried to use rate function but doesn't work because SysUptime.0 is not counter type ,it is timeticks.
is there any way how can i do that?
thx in advance for your answers!
BR,
Marijana
I tried to use rate function but doesn't work because SysUptime.0 is not counter type ,it is timeticks. |
calculating availability of node using SysUpTime.0 variable collcted in prometheus and exposing to grafana |
|prometheus|grafana|snmp|availability| |
MarkMap Toolbar renders but doesn't attach to the embedded script |
|javascript|markdown| |
How to loop through all html elements that contain a certain class name using Delphi in TMS WEB Core |
I'm using a [CDN](https://unpkg.com/vue) to run some vue code in my `index.html`. I'm just learning from a tutorial and this is my first time i use vue.
This is index.html
```html
<!DOCTYPE html> <html>
<head>
<title>THE TITLE</title>
</head>
<body>
<div id="app">
{{ greeting }}
<input v-model="greeting"/> <hr />
</div>
<div v-if="isVisible" class="box"></div>
<script src='https://unpkg.com/vue'></script>
<script src="vue.js"></script>
</body>
</html>
```
And this is vue.js
```js
let app = Vue.createApp({
data: function() {
return {
greeting: "Hello vue3!",
isVisible: false
}
}
});
app.mount("#app");
```
I am sure that vue cdn is working because v-model is working properly, but somehow v-if is not.
Also i asked chatGPT and it said I'm not importing CDN properly and edited my `vue.js` file completely. |
Vue CDN of html working but v-if not working |
|vue.js| |
null |
I ran into a problem importing js files (these are libraries). I am using NextJS 14.1.3 and ReactJS 18.2.0.
Here is the path to these files
[Here is the path to these files](https://i.stack.imgur.com/ahwjZ.png)
Project structure
[Project structure](https://i.stack.imgur.com/tuOo1.png)
This is the way I imported the files
```
import Script from 'next/script';
render() {
const {Component, pageProps}: any = this.props;
// During SSR, this will create new store instances so having `initialData` is crucial.
// During the client-side hydration, same applies.
// From then on, calls to `getStores()` return existing instances.
const stores = getStores();
return (
<StoreProvider value={stores}>
<Script
src='/public/js/LunaPass.1.6.8.js'
strategy="beforeInteractive"
/>
<Script
src='/public/js/LPMessageRenderer.1.6.8.js'
strategy="beforeInteractive"
/>
<Component {...pageProps} />
</StoreProvider>
);
}
```
Error itself
[Error in console](https://i.stack.imgur.com/hvq6d.png)
Has anyone encountered such a problem?
My expectation of my actions is to import js files and then use them in other pages. |
Not found js files in project (NextJs and ReactJs) |
|javascript|reactjs|next.js| |
null |
```
**auth.action.js**
import axios from "axios"
import { API_BASE_URL } from "../../config/api"
import { LOGIN_FAILURE, LOGIN_REQUEST, LOGIN_SUCCESS, REGISTER_FAILURE, REGISTER_REQUEST, REGISTER_SUCCESS } from "./authenticationType"
export const loginUserAction = (loginData) => async (dispatch) => {
dispatch({ type: LOGIN_REQUEST })
try {
const { data } = await axios.post(`${API_BASE_URL}/auth/signin`, loginData.data)
if (data.jwt) {
localStorage.setItem("jwt", data.jwt)
}
console.log("login", data)
dispatch({ type: LOGIN_SUCCESS, payload: data.jwt })
} catch (error) {
console.log("--------", error)
dispatch({ type: LOGIN_FAILURE, payload: error })
}
}
export const registerUserAction = (loginData) => async (dispatch) => {
dispatch({ type: REGISTER_REQUEST })
try {
const { data } = await axios.post(`${API_BASE_URL}/auth/signup`, loginData.data);
if (data.jwt) {
localStorage.setItem("jwt", data.jwt);
}
console.log("register------", data);
dispatch({ type: REGISTER_SUCCESS, payload: data.jwt });
} catch (error) {
console.log("--------", error);
dispatch({ type: REGISTER_FAILURE, payload: error });
}
};
**authenticationType.js**
export const LOGIN_REQUEST = "LOGIN_REQUEST";
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAILURE = "LOGIN_FAILURE";
export const REGISTER_REQUEST = "REGISTER_REQUEST";
export const REGISTER_SUCCESS = "REGISTER_SUCCESS";
export const REGISTER_FAILURE = "REGISTER_FAILURE";
authReducer.js
import { LOGIN_FAILURE, LOGIN_REQUEST, LOGIN_SUCCESS, REGISTER_FAILURE, REGISTER_REQUEST, REGISTER_SUCCESS } from "./authenticationType";
const initialState = {
jwt: null,
error: null,
loading: false
}
export const authReducer = (state = initialState, action) => {
switch (action.type) {
case LOGIN_REQUEST:
case REGISTER_REQUEST:
return { ...state, loading: true, error: null }
case LOGIN_SUCCESS:
case REGISTER_SUCCESS:
return { ...state, jwt: action.payload, loading: false, error: null }
case LOGIN_FAILURE:
case REGISTER_FAILURE:
return { ...state, loading: false, error: action.payload }
default:
return state;
}
}
**index.js**
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { store } from './Redux/store';
import { Provider } from 'react-redux'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
**Login.jsx**
import React, { useState } from "react";
import { ErrorMessage, Field, Form, Formik } from "formik";
import * as Yup from "yup";
import { Button, TextField } from "@mui/material";
import { loginUserAction } from "../../Redux/Auth/auth.action";
import { useDispatch } from 'react-redux';
const initialValues = { email: "", password: "" };
const validationSchema = Yup.object().shape({
email: Yup.string().email("Invalid email").required("Email is required"),
password: Yup.string().min(6, "Password must be at least 6 characters").required("Password is required")
});
const Login = () => {
const dispatch = useDispatch();
const handleSubmit = (values) => {
console.log("handle submit", values);
dispatch(loginUserAction({ data: values }));
};
return (
<div>
<h1>Login</h1>
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
{({ dirty, isValid }) => (
<Form>
<div>
<Field
type="email"
name="email"
label="Email"
as={TextField}
/>
<ErrorMessage name="email" component="div" />
</div>
<div>
<Field
type="password"
name="password"
label="Password"
as={TextField}
/>
<ErrorMessage name="password" component="div" />
</div>
<Button type="submit" disabled={!dirty || !isValid}>Submit</Button>
</Form>
)}
</Formik>
</div>
);
};
export default Login;
```
**Problem:**
> Uncaught (in promise) Error: Actions may not have an undefined "type" property. You may have misspelled an action type string constant.
> at dispatch (createStore.ts:206:1)
> at redux-thunk.mjs:9:1
> at dispatch (applyMiddleware.ts:54:1)
> at auth.action.js:6:1
> at redux-thunk.mjs:7:1
> at handleSubmit (Login.jsx:19:1)
> at Formik.tsx:862:1
> at Formik.tsx:1216:1
> at Formik.tsx:768:1 |
Actions may not have an undefined "type" property. Login page |