row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
40,357
How do i modify the div in my swiperslide to use the cardcontiner with in the following example: "use client"; import Image from "next/image"; import React from "react"; import { CardBody, CardContainer, CardItem } from "../ui/3d-card"; export function ThreeDCardDemo() { return ( <CardContainer className="inter-var"> <CardBody className="bg-gray-50 relative group/card dark:hover:shadow-2xl dark:hover:shadow-emerald-500/[0.1] dark:bg-black dark:border-white/[0.2] border-black/[0.1] w-auto sm:w-[30rem] h-auto rounded-xl p-6 border "> <CardItem translateZ="50" className="text-xl font-bold text-neutral-600 dark:text-white" > Make things float in air </CardItem> <CardItem as="p" translateZ="60" className="text-neutral-500 text-sm max-w-sm mt-2 dark:text-neutral-300" > Hover over this card to unleash the power of CSS perspective </CardItem> <CardItem translateZ="100" className="w-full mt-4"> <Image src="https://images.unsplash.com/photo-1441974231531-c6227db76b6e?q=80&w=2560&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" height="1000" width="1000" className="h-60 w-full object-cover rounded-xl group-hover/card:shadow-xl" alt="thumbnail" /> </CardItem> <div className="flex justify-between items-center mt-20"> <CardItem translateZ={20} as="button" className="px-4 py-2 rounded-xl text-xs font-normal dark:text-white" > Try now → </CardItem> <CardItem translateZ={20} as="button" className="px-4 py-2 rounded-xl bg-black dark:bg-white dark:text-black text-white text-xs font-bold" > Sign up </CardItem> </div> </CardBody> </CardContainer> ); } My actual code : import Image from "next/image"; import Link from "next/link"; import { BsArrowRight } from "react-icons/bs"; import { Pagination, Navigation } from "swiper"; import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; import "swiper/css/free-mode"; import "swiper/css/pagination"; import "swiper/css/navigation"; const workSlides = { slides: [ { images: [ { title: "Contact Website", path: "/contact.png", link: "https://contactvyc.netlify.app", }, { title: "SEO Website", path: "/seo.png", link: "https://seovyc.netlify.app", }, { title: "Porfolio Website", path: "/portfolio.png", link: "https://portfoliovyc.netlify.app", }, { title: "Podcast Website", path: "/pod.png", link: "https://podcastvyc.netlify.app", }, { title: "NFT Website", path: "/nft.png", link: "https://nftvyc.netlify.app", }, { title: "Gaming Website", path: "/gaming.png", link: "https://gamingvyc.netlify.app", }, ], }, { images: [ { title: "Personal Blog", path: "/brief.png", link: "https://biovyc.netlify.app", }, { title: "Dashboard Design", path: "/dashboard.png", link: "https://dashboardvyc.netlify.app", }, { title: "Cyrptocurrency Website", path: "/crypto.png", link: "https://crytpovyc.netlify.app", }, { title: "Ecommerce Website", path: "/ecommerce.png", link: "https://ecommercevyc.netlify.app", }, { title: "Ageny Website", path: "/agency.png", link: "https://agencyvyc.netlify.app", }, { title: "Blog Website", path: "/blogy.png", link: "https://blogyvyc.netlify.app", }, ], }, { images: [ { title: "3D Portfolio", path: "/3d-portfolio.png", link: "https://threejs-3-d-portfolio.vercel.app/", }, { title: "3D Product", path: "/3d-product.png", link: "https://3d-product-page.netlify.app/", }, { title: "Personal Blog", path: "/brief.png", link: "https://biovyc.netlify.app", }, ], }, ], }; const WorkSlider = () => { return ( <Swiper spaceBetween={10} pagination={{ clickable: true, }} modules={[Pagination, Navigation]} className="h-[100%] sm:h-[110%]" style={{ "--swiper-pagination-color": "#FFBA08", "--swiper-pagination-bullet-inactive-color": "#999999", "--swiper-pagination-bullet-inactive-opacity": "0.3", "--swiper-pagination-bullet-size": "15px", "--swiper-pagination-bullet-horizontal-gap": "6px", }} > {workSlides.slides.map((slide, i) => ( <SwiperSlide key={i}> <div className="grid grid-cols-2 grid-rows-3 gap-4"> {slide.images.map((image, imageI) => ( <div className="relative rounded-2xl overflow-hidden flex items-center justify-center group" key={imageI} > <div className="flex items-center justify-center relative overflow-hidden group"> {/* image */} <Image src={image.path} alt={image.title} width={500} height={300} /> {/* overlay gradient */} <div className="absolute inset-0 bg-gradient-to-l from-transparent via-[#000] to-[#f13024] opacity-0 group-hover:opacity-80 transition-all duration-700" aria-hidden /> {/* title */} <div className="absolute rounded-3xl bottom-0 translate-y-full group-hover:-translate-y-10 group-hover:xl:-translate-y-20 transition-all duration-300"> <Link href={image.link} target="_blank" rel="noreferrer noopener" className="flex items-center gap-x-2 text-[13px] tracking-[0.2em]" > <div className="projContainer"> <div className="projContainer1"> <div className="delay-1 text-xl">{image.title}</div> </div> <div className="projContainer2" style={{ color: '#f13024', fontWeight: 'bold' }}> <div className="delay-100 text-lg font-bold">LIVE</div> {/* title part 2 */} <div className="translate-y-[500%] group-hover:translate-y-0 transition-all duration-300 delay-150 text-lg font-bold"> PREVIEW </div> {/* icon */} <div className="text-xl translate-y-[500%] group-hover:translate-y-0 transition-all duration-300 delay-150"> </div> </div> </div> </Link> </div> </div> </div> ))} </div> </SwiperSlide> ))} </Swiper> ); }; export default WorkSlider;
386b45abc4bbe8992c621820318346db
{ "intermediate": 0.372296005487442, "beginner": 0.3747178912162781, "expert": 0.2529861032962799 }
40,358
Does this work for the distance formula in js return Math.sqrt(((y2 - y1) * (y2 - y1)) + ((x2 - x1) * (x2 - x1)));
e7e55a149e9e8c00dc4c9b22933cde51
{ "intermediate": 0.45694833993911743, "beginner": 0.31644943356513977, "expert": 0.2266021966934204 }
40,359
This makes calculateRoute run twice. const [loaded, setLoaded] = useState(false); useEffect(() => { if(loaded) return; setLoaded(true); calculateRoute(); });
08f0043c80b749e1646778d673d76676
{ "intermediate": 0.34252089262008667, "beginner": 0.5037203431129456, "expert": 0.15375882387161255 }
40,360
Is this the correct way to make calculateRoute run just once const [loaded, setLoaded] = useState(false); useEffect(() => { if(!loaded) { setLoaded(true); calculateRoute(); } }, [loaded]);
354f0ca4622594a6d4092e02c92048e3
{ "intermediate": 0.33180850744247437, "beginner": 0.5299493670463562, "expert": 0.13824214041233063 }
40,361
is this a good implementation of sliding window for my time series forecasting?
c3137e803b8c9133039cf616b118e3b4
{ "intermediate": 0.5199389457702637, "beginner": 0.14206047356128693, "expert": 0.3380005955696106 }
40,362
привет, я хочу обновить DDoS защиту для своего вебсайта. я использую платформу Cloudflare, раздел WAF(Custom Rules). Вот пример одного из моих правил, для отражения DDoS атак: ((any(http.request.headers["sec-ch-ua"][*] contains "(Not(A:Brand")) and (not any(http.request.headers["sec-ch-ua-platform"][*] contains "Linux"))) or (((lower(http.user_agent) contains "chrome/") and (any(http.request.headers.names[*] == "sec-ch-ua-mobile"))) and not any(http.request.headers.names[*] == "sec-gpc")) and (not any(http.request.headers["sec-ch-ua"][*] contains "Chromium") and not lower(http.user_agent) contains "samsungbrowser" and not lower(http.user_agent) contains "mobile safari/" and not lower(http.user_agent) contains "smart tv") or (not any(http.request.headers.names[*] == "accept-encoding") and ssl and http.request.uri.path eq "/auth/login" and http.request.uri.path eq "/" and http.request.uri.path eq "/auth") or ((any(http.request.headers["sec-ch-ua-platform"][*] eq "Android")) and (any(http.request.headers["sec-ch-ua-mobile"][*] ne "?1") and not ((any(http.request.headers["sec-ch-ua"][*] contains "Tenta"))) and (not http.user_agent contains "; Android "))) or (any(http.request.headers.names[*] == "x-original-host")) or (any(http.request.headers.names[*] == "x-forwarder-for")) or (any(http.request.headers.names[*] == "x-remote-addr")) or (any(http.request.headers.names[*] == "x-server")) or (any(http.request.headers.names[*] == "x-remote-ip")) or (any(http.request.headers.names[*] == "x-cluster-ip")) or (any(http.request.headers.names[*] == "x-true-client")) or (any(http.request.headers.names[*] == "x-originating-ip")) or (any(http.request.headers.names[*] == "x-client-ip")) or (any(http.request.headers.names[*] == "x-forwarded-https")) or (any(http.request.headers.names[*] == "x-forwarded-https")) or (any(http.request.headers.names[*] contains "x-ref-fe")) or (any(http.request.headers.names[*] contains "X-Req-Ip-")) or (cf.threat_score eq 1 and ip.geoip.country ne "T1") or (cf.threat_score gt 1 and ip.geoip.country ne "T1") or (not http.request.version in {"HTTP/1.1" "HTTP/1.2" "HTTP/2" "HTTP/3"}) or (any(http.request.headers["host"][*] contains ":")) or (http.request.uri.path eq "//") or (http.request.uri.path eq "///") or (not http.request.method in {"GET" "POST"}) or (http.x_forwarded_for ne "") or (http.user_agent contains "HuaweiBrowser" and any(http.request.headers["sec-ch-ua-mobile"][*] eq "?0")) or (http.user_agent eq "SamsungBrowser" and any(http.request.headers["sec-ch-ua-mobile"][*] eq "?0")) or (any(http.request.headers["sec-ch-ua"][*] eq "")) or (any(http.request.headers["sec-ch-ua-platform"][*] eq "")) or (http.user_agent contains "VenusBrowser" and any(http.request.headers["sec-ch-ua-mobile"][*] eq "?0")) or (http.user_agent contains "Android" and any(http.request.headers["sec-ch-ua-mobile"][*] eq "?0")) or (http.user_agent contains "iPhone" and any(http.request.headers["sec-ch-ua-mobile"][*] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][*] eq "\"Windows\"") and any(http.request.headers["sec-ch-ua-mobile"][*] eq "?1")) or (http.user_agent contains "MobileExplorer/3.00 (Mozilla/1.22; compatible; MMEF300; Microsoft; Windows; GenericLarge)" and any(http.request.headers["sec-ch-ua-platform"][*] eq "?0")) or (http.user_agent contains "UP.Browser" and any(http.request.headers["sec-ch-ua-platform"][*] eq "?0")) or (http.user_agent contains "IEMobile" and any(http.request.headers["sec-ch-ua-platform"][*] eq "?0")) or (http.user_agent contains "MIUI" and any(http.request.headers["sec-ch-ua-platform"][*] eq "?0")) or (http.user_agent contains "FxiOS" and any(http.request.headers["sec-ch-ua-platform"][*] eq "?0")) or (http.user_agent contains "OnePlusBrowser" and any(http.request.headers["sec-ch-ua-platform"][*] eq "?0")) or (http.user_agent contains "SogouMobileBrowser" and any(http.request.headers["sec-ch-ua-platform"][*] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][*] eq "\"Windows\"") and http.user_agent contains "Linux") or (http.user_agent eq "CheckHost (https://check-host.net/)") or (not http.user_agent contains "Mozilla/5.0") я хочу, чтобы используя все доступные источники ты сделал мне ещё 1 такое правило, для отражения DDoS атак с помощью Cloudflare WAF.
8d04f6ab25cd3ebd342ec186de1dd978
{ "intermediate": 0.23188172280788422, "beginner": 0.5816829204559326, "expert": 0.186435267329216 }
40,363
If 13 people play football, 4-2-4-2 is the most ideal formation, but in reality where 11 people play, how should I change 4-2-4-2?
945879f4f1549f6b5343b1b38311ded7
{ "intermediate": 0.3249237537384033, "beginner": 0.354778915643692, "expert": 0.32029733061790466 }
40,364
Im trying to call this in my JS app but im getting a CORS error Access to fetch at 'https://maps.googleapis.com/maps/api/directions/json?destination=39.132802,%20-84.496547&origin=39.1322941,-84.4970675&mode=WALKING&key=AIzaSyBKWpGumTcpzlMADzmAPHp8jySEuqGTcPY' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
e76724a57b19567c0e74a05e7a0c03a1
{ "intermediate": 0.5036948323249817, "beginner": 0.26760682463645935, "expert": 0.22869832813739777 }
40,365
If I want more than just ID (like long and lat) what would I change here app.post('/classes/:id', (req, res) => { let data = req.body; const { id } = req.params; if(!data) res.status(400).send("You need to supply a JSON object"); else { db.query(`INSERT INTO user_classes (user_id, classes) VALUES ('${id}', '${JSON.stringify(data)}') ON DUPLICATE KEY UPDATE classes=VALUES(classes)`, (err, results) => { console.log(err); if(err) res.status(400).send(err); else res.status(200).send(results); }); } });
90854e32db2b6c99f6438ec2fe2c5728
{ "intermediate": 0.43438518047332764, "beginner": 0.38933634757995605, "expert": 0.17627845704555511 }
40,366
I have a java program with class Main and method main where the program is supposed to begin. Within the Main class I have defined another class Edge. I am trying create an instance of class Edge within the main method but I am getting an error saying a "non-static variable cannot be referenced in a static context". How do I create an instance of my Edge class then>
b5f55ce27b4b7b0d75159cc5de7a4eeb
{ "intermediate": 0.5208830237388611, "beginner": 0.37091028690338135, "expert": 0.10820669680833817 }
40,367
Hey
1ef44c989b6ee0b8b3975e8ca73e5cbb
{ "intermediate": 0.3360580503940582, "beginner": 0.274208664894104, "expert": 0.38973328471183777 }
40,368
hello there!
164d9839c9491f6ca6cb37bcc1eb7121
{ "intermediate": 0.33348941802978516, "beginner": 0.27571380138397217, "expert": 0.3907967805862427 }
40,369
Develop a website. Title: »NKOTB Tour 2024«, map: OSM-map with all dates and places. Map should sign all places with blue dots. All shows are connected via a blue line according to the dates. HOvering with mouse over should show a Tooltip with date, city and venue. Map should fill dynamicalle the whole website. Here are the List of shows: »June 14, 2024 Cuyahoga Falls, OH Blossom Music Center June 15, 2024 Tinley Park, IL Credit Union 1 Amphitheatre June 18, 2024 Clarkston, MI Pine Knob Music Theatre June 19, 2024 Burgettstown, PA The Pavilion at Star Lake June 21, 2024 Cincinnati, OH Riverbend Music Center June 22, 2024 Maryland Heights, MO Hollywood Casino Amphitheatre – St. Louis June 23, 2024 Prior Lake, MN Mystic Amphitheater June 25, 2024 Kansas City, MO Starlight Theatre June 26, 2024 Rogers, AR Walmart AMP June 28, 2024 Denver, CO Ball Arena June 29, 2024 Salt Lake City, UT USANA Amphitheatre July 1, 2024 Highland, CA Yaamava’ Theater ** July 2, 2024 Wheatland, CA Toyota Amphitheatre July 3, 2024 Mountain View, CA Shoreline Amphitheatre July 5, 2024 Inglewood, CA Kia Forum July 6, 2024 Palm Desert, CA Acrisure Arena July 7, 2024 Chula Vista, CA North Island Credit Union Amphitheatre July 9, 2024 Phoenix, AZ Talking Stick Resort Amphitheatre July 10, 2024 Albuquerque, NM Isleta Amphitheater July 12, 2024 Austin, TX Germania Insurance Amphitheater July 13, 2024 The Woodlands, TX Cynthia Woods Mitchell Pavilion Presented by Huntsman July 14, 2024 Dallas, TX Dos Equis Pavilion July 16, 2024 Franklin, TN FirstBank Amphitheater July 17, 2024 Franklin, TN FirstBank Amphitheater July 19, 2024 Tampa, FL MIDFLORIDA Credit Union Amphitheatre July 20, 2024 West Palm Beach, FL iTHINK Financial Amphitheatre July 21, 2024 Jacksonville, FL Daily’s Place July 25, 2024 Charleston, SC Credit One Stadium July 26, 2024 Alpharetta, GA Ameris Bank Amphitheatre July 27, 2024 Charlotte, NC PNC Music Pavilion July 28, 2024 Raleigh, NC Coastal Credit Union Music Park August 1, 2024 Virginia Beach, VA Veterans United Home Loans Amphitheater at Virginia Beach August 2, 2024 Hartford, CT XFINITY Theatre August 3, 2024 Hershey, PA Hersheypark Stadium August 4, 2024 Wantagh, NY Northwell Health at Jones Beach Theater August 8, 2024 Holmdel, NJ PNC Bank Arts Center August 9, 2024 Gilford, NH BankNH Pavilion August 10, 2024 Mansfield, MA Xfinity Center August 11, 2024 Saratoga Springs, NY Broadview Stage at SPAC August 15, 2024 Philadelphia, PA TD Pavilion at the Mann August 16, 2024 Columbia, MD Merriweather Post Pavilion August 17, 2024 Toronto, ON Budweiser Stage August 22, 2024 Darien Center, NY Darien Lake Amphitheater August 23, 2024 Columbus, OH Nationwide Arena August 24, 2024 Milwaukee, WI American Family Insurance Amphitheater August 25, 2024 Noblesville, IN Ruoff Music Center«
a05dd613e228c1200a4d114eef4bb889
{ "intermediate": 0.4309101402759552, "beginner": 0.3021509349346161, "expert": 0.26693886518478394 }
40,370
7 a) To Develop an ALP to generate a square wave of frequency 5kHz on P2.3, assume that XTAL=11.052 MHz b) To Develop an ALP to generate a square wave of frequency 5kHz with ON time on P2.3 and OFF time on P3.3. Assume that XTAL=11.052 MHz
de99f6bb439e936e6c11608561e7522f
{ "intermediate": 0.2624889612197876, "beginner": 0.18735617399215698, "expert": 0.5501548647880554 }
40,371
(Тебе надо написать именно правила, а не идеи.)привет, на мой сайт идёт DDoS атака. Атакующий использует легитимные юзер-агенты веббраузера Google Chrome и хеадеры этого же браузера. Твоя задача придумать для меня 10 правил для Cloudflare WAF, чтобы отражать подобные атаки. Тебе надо написать именно правила, а не идеи. Ниже я могу предоставить тебе пример моего правила: ((any(http.request.headers["sec-ch-ua"][] contains "(Not(A ")) and (not any(http.request.headers["sec-ch-ua-platform"][] contains "Linux"))) or (((lower(http.user_agent) contains "chrome/") and (any(http.request.headers.names[] == "sec-ch-ua-mobile"))) and not any(http.request.headers.names[] == "sec-gpc")) and (not any(http.request.headers["sec-ch-ua"][] contains "Chromium") and not lower(http.user_agent) contains "samsungbrowser" and not lower(http.user_agent) contains "mobile safari/" and not lower(http.user_agent) contains "smart tv") or (not any(http.request.headers.names[] == "accept-encoding") and ssl and http.request.uri.path eq "/auth/login" and http.request.uri.path eq "/" and http.request.uri.path eq "/auth") or ((any(http.request.headers["sec-ch-ua-platform"][] eq "Android")) and (any(http.request.headers["sec-ch-ua-mobile"][] ne "?1") and not ((any(http.request.headers["sec-ch-ua"][] contains "Tenta"))) and (not http.user_agent contains "; Android "))) or (any(http.request.headers.names[] == "x-original-host")) or (any(http.request.headers.names[] == "x-forwarder-for")) or (any(http.request.headers.names[] == "x-remote-addr")) or (any(http.request.headers.names[] == "x-server")) or (any(http.request.headers.names[] == "x-remote-ip")) or (any(http.request.headers.names[] == "x-cluster-ip")) or (any(http.request.headers.names[] == "x-true-client")) or (any(http.request.headers.names[] == "x-originating-ip")) or (any(http.request.headers.names[] == "x-client-ip")) or (any(http.request.headers.names[] == "x-forwarded-https")) or (any(http.request.headers.names[] == "x-forwarded-https")) or (any(http.request.headers.names[] contains "x-ref-fe")) or (any(http.request.headers.names[] contains "X-Req-Ip-")) or (cf.threat_score eq 1 and ip.geoip.country ne "T1") or (cf.threat_score gt 1 and ip.geoip.country ne "T1") or (not http.request.version in {"HTTP/1.1" "HTTP/1.2" "HTTP/2" "HTTP/3"}) or (any(http.request.headers["host"][] contains ":")) or (http.request.uri.path eq "//") or (http.request.uri.path eq "///") or (not http.request.method in {"GET" "POST"}) or (http.x_forwarded_for ne "") or (http.user_agent contains "HuaweiBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent eq "SamsungBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (any(http.request.headers["sec-ch-ua"][] eq "")) or (any(http.request.headers["sec-ch-ua-platform"][] eq "")) or (http.user_agent contains "VenusBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent contains "Android" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent contains "iPhone" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][] eq ""Windows"") and any(http.request.headers["sec-ch-ua-mobile"][] eq "?1")) or (http.user_agent contains "MobileExplorer/3.00 (Mozilla/1.22; compatible; MMEF300; Microsoft; Windows; GenericLarge)" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "UP.Browser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "IEMobile" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "MIUI" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "FxiOS" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "OnePlusBrowser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "SogouMobileBrowser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][] eq ""Windows"") and http.user_agent contains "Linux") or (http.user_agent eq "CheckHost (https://check-host.net/)") or (not http.user_agent contains "Mozilla/5.0")
80ad7b826c77cf3ff2043306b9491da9
{ "intermediate": 0.19751101732254028, "beginner": 0.545903742313385, "expert": 0.2565852999687195 }
40,372
(Тебе надо написать именно правила, а не идеи.)привет, на мой сайт идёт DDoS атака. Атакующий использует легитимные юзер-агенты веббраузера Google Chrome и хеадеры этого же браузера. Твоя задача придумать для меня 10 правил для Cloudflare WAF, чтобы отражать подобные атаки. Тебе надо написать именно правила, а не идеи. Ниже я могу предоставить тебе пример моего правила: ((any(http.request.headers["sec-ch-ua"][] contains "(Not(A ")) and (not any(http.request.headers["sec-ch-ua-platform"][] contains "Linux"))) or (((lower(http.user_agent) contains "chrome/") and (any(http.request.headers.names[] == "sec-ch-ua-mobile"))) and not any(http.request.headers.names[] == "sec-gpc")) and (not any(http.request.headers["sec-ch-ua"][] contains "Chromium") and not lower(http.user_agent) contains "samsungbrowser" and not lower(http.user_agent) contains "mobile safari/" and not lower(http.user_agent) contains "smart tv") or (not any(http.request.headers.names[] == "accept-encoding") and ssl and http.request.uri.path eq "/auth/login" and http.request.uri.path eq "/" and http.request.uri.path eq "/auth") or ((any(http.request.headers["sec-ch-ua-platform"][] eq "Android")) and (any(http.request.headers["sec-ch-ua-mobile"][] ne "?1") and not ((any(http.request.headers["sec-ch-ua"][] contains "Tenta"))) and (not http.user_agent contains "; Android "))) or (any(http.request.headers.names[] == "x-original-host")) or (any(http.request.headers.names[] == "x-forwarder-for")) or (any(http.request.headers.names[] == "x-remote-addr")) or (any(http.request.headers.names[] == "x-server")) or (any(http.request.headers.names[] == "x-remote-ip")) or (any(http.request.headers.names[] == "x-cluster-ip")) or (any(http.request.headers.names[] == "x-true-client")) or (any(http.request.headers.names[] == "x-originating-ip")) or (any(http.request.headers.names[] == "x-client-ip")) or (any(http.request.headers.names[] == "x-forwarded-https")) or (any(http.request.headers.names[] == "x-forwarded-https")) or (any(http.request.headers.names[] contains "x-ref-fe")) or (any(http.request.headers.names[] contains "X-Req-Ip-")) or (cf.threat_score eq 1 and ip.geoip.country ne "T1") or (cf.threat_score gt 1 and ip.geoip.country ne "T1") or (not http.request.version in {"HTTP/1.1" "HTTP/1.2" "HTTP/2" "HTTP/3"}) or (any(http.request.headers["host"][] contains ":")) or (http.request.uri.path eq "//") or (http.request.uri.path eq "///") or (not http.request.method in {"GET" "POST"}) or (http.x_forwarded_for ne "") or (http.user_agent contains "HuaweiBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent eq "SamsungBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (any(http.request.headers["sec-ch-ua"][] eq "")) or (any(http.request.headers["sec-ch-ua-platform"][] eq "")) or (http.user_agent contains "VenusBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent contains "Android" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent contains "iPhone" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][] eq ""Windows"") and any(http.request.headers["sec-ch-ua-mobile"][] eq "?1")) or (http.user_agent contains "MobileExplorer/3.00 (Mozilla/1.22; compatible; MMEF300; Microsoft; Windows; GenericLarge)" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "UP.Browser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "IEMobile" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "MIUI" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "FxiOS" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "OnePlusBrowser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "SogouMobileBrowser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][] eq ""Windows"") and http.user_agent contains "Linux") or (http.user_agent eq "CheckHost (https://check-host.net/)") or (not http.user_agent contains "Mozilla/5.0")
3fae1d5a195747cff26378dbc396113d
{ "intermediate": 0.19751101732254028, "beginner": 0.545903742313385, "expert": 0.2565852999687195 }
40,373
#include <iostream> #include <cstdint> #include <Windows.h> #include <TlHelp32.h> static DWORD get_process_id(const wchar_t* process_name) { DWORD procId = 0; HANDLE snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (snapShot == INVALID_HANDLE_VALUE) return procId; PROCESSENTRY32 entry = {}; entry.dwSize = sizeof(decltype(entry)); if (Process32FirstW(snapShot, &entry) == TRUE) { if (_wcsicmp(process_name, entry.szExeFile) == 0) procId = entry.th32ProcessID; else { while (Process32NextW(snapShot, &entry) == TRUE) { if (_wcsicmp(process_name, entry.szExeFile) == 0) { procId = entry.th32ProcessID; break; } } } } CloseHandle(snapShot); return procId; } static std::uintptr_t get_module_base(const DWORD pid, const wchar_t* module_name) { std::uintptr_t mod_base = 0; HANDLE snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, NULL); if (snapShot == INVALID_HANDLE_VALUE) return mod_base; MODULEENTRY32 entry = {}; entry.dwSize = sizeof(decltype(entry)); if (Module32FirstW(snapShot, &entry) == TRUE) { if (_wcsicmp(module_name, entry.szModule) == 0) mod_base = (uintptr_t)entry.modBaseAddr; else { while (Module32FirstW(snapShot, &entry) == TRUE) { if (_wcsicmp(module_name, entry.szModule) == 0) { mod_base = (uintptr_t)entry.modBaseAddr; break; } } } } CloseHandle(snapShot); return mod_base; } namespace driver { namespace codes { constexpr ULONG attach = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x696, METHOD_BUFFERED, FILE_SPECIAL_ACCESS); constexpr ULONG read = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x697, METHOD_BUFFERED, FILE_SPECIAL_ACCESS); constexpr ULONG write = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x698, METHOD_BUFFERED, FILE_SPECIAL_ACCESS); } struct Request { HANDLE process_id; PVOID target; PVOID buffer; SIZE_T size; SIZE_T return_size; }; bool attach_to_process(HANDLE driver_handle, const DWORD pid) { Request r; r.process_id = (HANDLE)pid; return DeviceIoControl(driver_handle, codes::attach, &r, sizeof(r), &r, sizeof(r), nullptr, nullptr); } template <class T> T read(HANDLE driver_handle, const std::uintptr_t addr) { T temp = {}; Request r; r.target = (PVOID)addr; r.buffer = &temp; r.size = sizeof(T); DeviceIoControl(driver_handle, codes::read, &r, sizeof(r), &r, sizeof(r), nullptr, nullptr); return temp; } template <class T> void write(HANDLE driver_handle, const std::uintptr_t addr, const T& val) { Request r; r.target = reinterpret_cast<PVOID>(addr); r.buffer = (PVOID)&val; r.size = sizeof(T); DeviceIoControl(driver_handle, codes::write, &r, sizeof(r), &r, sizeof(r), nullptr, nullptr); } } int main() { const DWORD pid = get_process_id(L"notepad.exe"); if (pid == 0) { std::cout << "Failed to find cs2.exe. \n"; std::cin.get(); return 1; } std::cout << pid << "\n"; const HANDLE driver = CreateFileW(L"\\\\.\\KernelMode", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (driver == INVALID_HANDLE_VALUE) { std::cout << "Failed to create driver handle. \n"; std::cin.get(); return 1; } driver::attach_to_process(driver, pid); std::cout << "Value at address 0x7FFB2F7183D0: " << driver::read<long>(driver, 0x7FFB2F7183D0) << std::endl; if (driver::attach_to_process(driver, pid)) { std::cout << "Attachment complete. \n"; std::cout << "Value at address 0x7FFB2F7183D0: " << driver::read<long>(driver, 0x7FFB2F7183D0) << std::endl; // Lire la valeur à partir de l'adresse 0x2722096F590 en tant que chaîne de caractères int value = driver::read<int>(driver, 0x7FFB2F7183D0); std::cout << "Value at address 0x7FFB2F7183D0: " << driver::read<long>(driver, 0x7FFB2F7183D0) << std::endl; } else { std::cout << "Failed to attach to process. \n"; } CloseHandle(driver); std::cin.get(); return 0; } c'est quoi le probleme avec ce code quand je run il me dit que la valeur de mon adress
99189d368a16c55ceac425590f367f45
{ "intermediate": 0.38156846165657043, "beginner": 0.4178975522518158, "expert": 0.2005339413881302 }
40,374
What is the melody of the dr who theme (llillypond syntax)?
fdae3d984c753a88461a834ce4c5de2b
{ "intermediate": 0.38440123200416565, "beginner": 0.3904006779193878, "expert": 0.22519806027412415 }
40,375
Can you write pine script code
0e465db87c4a9fe728fbe3c9bd8c2289
{ "intermediate": 0.281814843416214, "beginner": 0.5087790489196777, "expert": 0.20940612256526947 }
40,376
-- Сторона клиента -- Создаем переменные для хранения координат маркеров и их ID local marker1 = {x = 1262.9248046875, y = -2025.0537109375, z = 59.336345672607, id = "infoaboutserver"} local marker2 = {x = 1271.0048828125, y = -2025.578125, z = 59.095985412598, id = "infoaboutwork"} -- Создаем маркеры на карте с помощью функции createMarker local marker1Element = createMarker(marker1.x, marker1.y, marker1.z, "cylinder", 1.5, 255, 0, 0, 150) local marker2Element = createMarker(marker2.x, marker2.y, marker2.z, "cylinder", 1.5, 255, 0, 0, 150) -- Создаем переменные для хранения текста, который будет отображаться в окне DxGUI local marker1Text = "Добро пожаловать на наш увлекательный сервер жанра выживания в зомби-апокалипсисе, сейчас мы начнём небольшое обучение тому, как играть здесь и выживать, что самое главное" local marker2Text = "Это заброшенная деревня, здесь вы можете найти множество интересных и важных артефактов, скрытых персональных заданий и получить большой опыт. Но будьте осторожны, опасность подстерегает вас за каждым углом" -- Создаем переменную для хранения текущего маркера, с которым взаимодействует игрок local currentMarker = nil -- Создаем функцию для отрисовки окна DxGUI с информацией о маркере local function drawMarkerInfo() -- Проверяем, что текущий маркер существует if currentMarker then -- Проверяем, что локальный игрок существует if isElement(localPlayer) then -- Получаем размеры экрана local screenWidth, screenHeight = guiGetScreenSize() -- Вычисляем размеры и координаты окна DxGUI local windowWidth = screenWidth * 0.5 -- 50% от ширины экрана local windowHeight = screenHeight * 0.3 -- 30% от высоты экрана local windowX = (screenWidth - windowWidth) / 2 -- центрируем по горизонтали local windowY = (screenHeight - windowHeight) / 2 -- центрируем по вертикали -- Вычисляем размеры и координаты текста local textWidth = windowWidth * 0.9 -- 90% от ширины окна local textHeight = windowHeight * 0.7 -- 70% от высоты окна local textX = windowX + (windowWidth - textWidth) / 2 -- центрируем по горизонтали local textY = windowY + (windowHeight - textHeight) / 2 -- центрируем по вертикали -- Вычисляем размеры и координаты кнопки local buttonWidth = windowWidth * 0.2 -- 20% от ширины окна local buttonHeight = windowHeight * 0.1 -- 10% от высоты окна local buttonX = windowX + (windowWidth - buttonWidth) / 2 -- центрируем по горизонтали local buttonY = windowY + windowHeight * 0.8 -- располагаем внизу окна -- Рисуем окно DxGUI с помощью функции dxDrawRectangle dxDrawRectangle(windowX, windowY, windowWidth, windowHeight, tocolor(0, 0, 0, 200)) -- черный цвет с прозрачностью 200 -- Рисуем текст с помощью функции dxDrawText dxDrawText(currentMarker.text, textX, textY, textX + textWidth, textY + textHeight, tocolor(255, 255, 255, 255), 1, "default", "center", "center", true, true) -- белый цвет, размер 1, шрифт по умолчанию, выравнивание по центру, перенос по словам, клиппинг -- Рисуем кнопку с помощью функции dxDrawRectangle dxDrawRectangle(buttonX, buttonY, buttonWidth, buttonHeight, tocolor(255, 0, 0, 200)) -- красный цвет с прозрачностью 200 -- Рисуем текст на кнопке с помощью функции dxDrawText dxDrawText("Ознакомился", buttonX, buttonY, buttonX + buttonWidth, buttonY + buttonHeight, tocolor(255, 255, 255, 255), 1, "default", "center", "center") -- белый цвет, размер 1, шрифт по умолчанию, выравнивание по центру end end end -- Создаем функцию для обработки события onClientMarkerHit, когда игрок входит в маркер local function onMarkerHit(hitElement, matchingDimension) -- Проверяем, что элемент, вошедший в маркер, это игрок и он находится в том же измерении, что и маркер if hitElement == localPlayer and matchingDimension then -- Проверяем, что игрок не находится в транспортном средстве if not isPedInVehicle(localPlayer) then -- Проверяем, какой маркер был активирован if source == marker1Element then -- Устанавливаем текущий маркер равным первому маркеру currentMarker = marker1 elseif source == marker2Element then -- Устанавливаем текущий маркер равным второму маркеру currentMarker = marker2 end -- Добавляем текст к текущему маркеру в зависимости от его ID if currentMarker.id == "infoaboutserver" then currentMarker.text = marker1Text elseif currentMarker.id == "infoaboutwork" then currentMarker.text = marker2Text end -- Добавляем обработчик события onClientRender, чтобы отрисовывать окно DxGUI addEventHandler("onClientRender", root, drawMarkerInfo) -- Включаем курсор мыши showCursor(true) end end end -- Создаем функцию для обработки события onClientMarkerLeave, когда игрок выходит из маркера local function onMarkerLeave(leaveElement, matchingDimension) -- Проверяем, что элемент, вышедший из маркера, это игрок и он находился в том же измерении, что и маркер if leaveElement == localPlayer and matchingDimension then -- Проверяем, что игрок не находится в транспортном средстве if not isPedInVehicle(localPlayer) then -- Удаляем обработчик события onClientRender, чтобы перестать отрисовывать окно DxGUI removeEventHandler("onClientRender", root, drawMarkerInfo) -- Удаляем обработчик события onClientClick, чтобы перестать обрабатывать нажатие на кнопку removeEventHandler("onClientClick", root, onClick) -- Выключаем курсор мыши showCursor(false) -- Обнуляем текущий маркер currentMarker = nil end end end -- Создаем функцию для обработки события onClientClick, когда игрок нажимает на кнопку мыши local function onClick(button, state, absoluteX, absoluteY, buttonX, buttonY, buttonWidth, buttonHeight) outputChatBox("Button clicked!", 255, 255, 255) -- Проверяем, что кнопка мыши это левая и состояние это нажатие if button == "left" and state == "down" then -- Проверяем, что текущий маркер существует if currentMarker then -- Проверяем, что координаты клика мыши попадают в область кнопки, используя координаты окна DxGUI, переданные через аргументы if absoluteX >= buttonX and absoluteX <= buttonX + buttonWidth and absoluteY >= buttonY and absoluteY <= buttonY + buttonHeight then outputChatBox("Вы нажали на кнопку", localPlayer, 255, 255, 255) -- Удаляем обработчик события onClientRender, чтобы перестать отрисовывать окно DxGUI removeEventHandler("onClientRender", root, drawMarkerInfo) -- Удаляем обработчик события onClientClick, чтобы перестать обрабатывать нажатие на кнопку removeEventHandler("onClientClick", root, onClick) -- Выключаем курсор мыши showCursor(false) -- Обнуляем текущий маркер currentMarker = nil end end end end -- Добавляем обработчики событий для маркеров addEventHandler("onClientMarkerHit", marker1Element, onMarkerHit) addEventHandler("onClientMarkerHit", marker2Element, onMarkerHit) addEventHandler("onClientMarkerLeave", marker1Element, onMarkerLeave) addEventHandler("onClientMarkerLeave", marker2Element, onMarkerLeave) Кнопка local function onClick не срабатывает по нажатию, вообще нет реакции
6478aee09668e732366a4e9c9000361a
{ "intermediate": 0.3761155605316162, "beginner": 0.4012448489665985, "expert": 0.22263960540294647 }
40,377
On Vim, how do I jump to a line containing a string but keeping the cursor on the current column, i.e., not moving it to the string?
995694e0d167a6d442b3ef8401cf3c8d
{ "intermediate": 0.4312877357006073, "beginner": 0.2743529677391052, "expert": 0.2943592667579651 }
40,378
-- Сторона клиента -- Создаем переменные для хранения координат маркеров и их ID local marker1 = {x = 1262.9248046875, y = -2025.0537109375, z = 59.336345672607, id = "infoaboutserver"} local marker2 = {x = 1271.0048828125, y = -2025.578125, z = 59.095985412598, id = "infoaboutwork"} -- Создаем маркеры на карте с помощью функции createMarker local marker1Element = createMarker(marker1.x, marker1.y, marker1.z, "cylinder", 1.5, 255, 0, 0, 150) local marker2Element = createMarker(marker2.x, marker2.y, marker2.z, "cylinder", 1.5, 255, 0, 0, 150) -- Создаем переменные для хранения текста, который будет отображаться в окне DxGUI local marker1Text = "Добро пожаловать на наш увлекательный сервер жанра выживания в зомби-апокалипсисе, сейчас мы начнём небольшое обучение тому, как играть здесь и выживать, что самое главное" local marker2Text = "Это заброшенная деревня, здесь вы можете найти множество интересных и важных артефактов, скрытых персональных заданий и получить большой опыт. Но будьте осторожны, опасность подстерегает вас за каждым углом" -- Создаем переменную для хранения текущего маркера, с которым взаимодействует игрок local currentMarker = nil -- Создаем функцию для отрисовки окна DxGUI с информацией о маркере local function drawMarkerInfo() -- Проверяем, что текущий маркер существует if currentMarker then -- Проверяем, что локальный игрок существует if isElement(localPlayer) then -- Получаем размеры экрана local screenWidth, screenHeight = guiGetScreenSize() -- Вычисляем размеры и координаты окна DxGUI local windowWidth = screenWidth * 0.5 -- 50% от ширины экрана local windowHeight = screenHeight * 0.3 -- 30% от высоты экрана local windowX = (screenWidth - windowWidth) / 2 -- центрируем по горизонтали local windowY = (screenHeight - windowHeight) / 2 -- центрируем по вертикали -- Вычисляем размеры и координаты текста local textWidth = windowWidth * 0.9 -- 90% от ширины окна local textHeight = windowHeight * 0.7 -- 70% от высоты окна local textX = windowX + (windowWidth - textWidth) / 2 -- центрируем по горизонтали local textY = windowY + (windowHeight - textHeight) / 2 -- центрируем по вертикали -- Вычисляем размеры и координаты кнопки local buttonWidth = windowWidth * 0.2 -- 20% от ширины окна local buttonHeight = windowHeight * 0.1 -- 10% от высоты окна local buttonX = windowX + (windowWidth - buttonWidth) / 2 -- центрируем по горизонтали local buttonY = windowY + windowHeight * 0.8 -- располагаем внизу окна -- Рисуем окно DxGUI с помощью функции dxDrawRectangle dxDrawRectangle(windowX, windowY, windowWidth, windowHeight, tocolor(0, 0, 0, 200)) -- черный цвет с прозрачностью 200 -- Рисуем текст с помощью функции dxDrawText dxDrawText(currentMarker.text, textX, textY, textX + textWidth, textY + textHeight, tocolor(255, 255, 255, 255), 1, "default", "center", "center", true, true) -- белый цвет, размер 1, шрифт по умолчанию, выравнивание по центру, перенос по словам, клиппинг -- Рисуем кнопку с помощью функции dxDrawRectangle dxDrawRectangle(buttonX, buttonY, buttonWidth, buttonHeight, tocolor(255, 0, 0, 200)) -- красный цвет с прозрачностью 200 -- Рисуем текст на кнопке с помощью функции dxDrawText dxDrawText("Ознакомился", buttonX, buttonY, buttonX + buttonWidth, buttonY + buttonHeight, tocolor(255, 255, 255, 255), 1, "default", "center", "center") -- белый цвет, размер 1, шрифт по умолчанию, выравнивание по центру -- Добавляем обработчик события onClientClick, чтобы обрабатывать нажатие на кнопку, и передаем ему координаты кнопки addEventHandler("onClientClick", root, onClick, false, "high", buttonX, buttonY, buttonWidth, buttonHeight) end end end -- Создаем функцию для обработки события onClientMarkerHit, когда игрок входит в маркер local function onMarkerHit(hitElement, matchingDimension) -- Проверяем, что элемент, вошедший в маркер, это игрок и он находится в том же измерении, что и маркер if hitElement == localPlayer and matchingDimension then -- Проверяем, что игрок не находится в транспортном средстве if not isPedInVehicle(localPlayer) then -- Проверяем, какой маркер был активирован if source == marker1Element then -- Устанавливаем текущий маркер равным первому маркеру currentMarker = marker1 elseif source == marker2Element then -- Устанавливаем текущий маркер равным второму маркеру currentMarker = marker2 end -- Добавляем текст к текущему маркеру в зависимости от его ID if currentMarker.id == "infoaboutserver" then currentMarker.text = marker1Text elseif currentMarker.id == "infoaboutwork" then currentMarker.text = marker2Text end -- Добавляем текст к текущему маркеру в зависимости от его ID if currentMarker.id == "infoaboutserver" then currentMarker.text = marker1Text elseif currentMarker.id == "infoaboutwork" then currentMarker.text = marker2Text end -- Добавляем обработчик события onClientRender, чтобы отрисовывать окно DxGUI addEventHandler("onClientRender", root, drawMarkerInfo) -- Включаем курсор мыши showCursor(true) end end end -- Создаем функцию для обработки события onClientMarkerLeave, когда игрок выходит из маркера local function onMarkerLeave(leaveElement, matchingDimension) -- Проверяем, что элемент, вышедший из маркера, это игрок и он находился в том же измерении, что и маркер if leaveElement == localPlayer and matchingDimension then -- Проверяем, что игрок не находится в транспортном средстве if not isPedInVehicle(localPlayer) then -- Удаляем обработчик события onClientRender, чтобы перестать отрисовывать окно DxGUI removeEventHandler("onClientRender", root, drawMarkerInfo) -- Удаляем обработчик события onClientClick, чтобы перестать обрабатывать нажатие на кнопку removeEventHandler("onClientClick", root, onClick) -- Выключаем курсор мыши showCursor(false) -- Обнуляем текущий маркер currentMarker = nil end end end -- Создаем функцию для обработки события onClientClick, когда игрок нажимает на кнопку мыши local function onClick(button, state, absoluteX, absoluteY, buttonX, buttonY, buttonWidth, buttonHeight) -- Проверяем, что кнопка мыши это левая и состояние это нажатие if button == "left" and state == "down" then -- Проверяем, что текущий маркер существует if currentMarker then -- Проверяем, что координаты клика мыши попадают в область кнопки, используя координаты окна DxGUI, переданные через аргументы if absoluteX >= buttonX and absoluteX <= buttonX + buttonWidth and absoluteY >= buttonY and absoluteY <= buttonY + buttonHeight then outputChatBox("Вы нажали на кнопку", localPlayer, 255, 255, 255) -- Удаляем обработчик события onClientRender, чтобы перестать отрисовывать окно DxGUI removeEventHandler("onClientRender", root, drawMarkerInfo) -- Удаляем обработчик события onClientClick, чтобы перестать обрабатывать нажатие на кнопку removeEventHandler("onClientClick", root, onClick) -- Выключаем курсор мыши showCursor(false) -- Обнуляем текущий маркер currentMarker = nil end end end end -- Добавляем обработчики событий для маркеров addEventHandler("onClientMarkerHit", marker1Element, onMarkerHit) addEventHandler("onClientMarkerHit", marker2Element, onMarkerHit) addEventHandler("onClientMarkerLeave", marker1Element, onMarkerLeave) addEventHandler("onClientMarkerLeave", marker2Element, onMarkerLeave) СОЗДАЙ КНОПКУ, КОТОРАЯ БУДЕТ ЗАКРЫВАТЬ DXGUI
efe134842455f565a6f5f7a7f3859150
{ "intermediate": 0.3761155605316162, "beginner": 0.4012448489665985, "expert": 0.22263960540294647 }
40,379
-- Сторона клиента -- Создаем переменные для хранения координат маркеров и их ID local marker1 = {x = 1262.9248046875, y = -2025.0537109375, z = 59.336345672607, id = "infoaboutserver"} local marker2 = {x = 1271.0048828125, y = -2025.578125, z = 59.095985412598, id = "infoaboutwork"} -- Создаем маркеры на карте с помощью функции createMarker local marker1Element = createMarker(marker1.x, marker1.y, marker1.z, "cylinder", 1.5, 255, 0, 0, 150) local marker2Element = createMarker(marker2.x, marker2.y, marker2.z, "cylinder", 1.5, 255, 0, 0, 150) -- Создаем переменные для хранения текста, который будет отображаться в окне DxGUI local marker1Text = "Добро пожаловать на наш увлекательный сервер жанра выживания в зомби-апокалипсисе, сейчас мы начнём небольшое обучение тому, как играть здесь и выживать, что самое главное" local marker2Text = "Это заброшенная деревня, здесь вы можете найти множество интересных и важных артефактов, скрытых персональных заданий и получить большой опыт. Но будьте осторожны, опасность подстерегает вас за каждым углом" -- Создаем переменную для хранения текущего маркера, с которым взаимодействует игрок local currentMarker = nil -- Создаем функцию для отрисовки окна DxGUI с информацией о маркере local function drawMarkerInfo() -- Проверяем, что текущий маркер существует if currentMarker then -- Проверяем, что локальный игрок существует if isElement(localPlayer) then -- Получаем размеры экрана local screenWidth, screenHeight = guiGetScreenSize() -- Вычисляем размеры и координаты окна DxGUI local windowWidth = screenWidth * 0.5 -- 50% от ширины экрана local windowHeight = screenHeight * 0.3 -- 30% от высоты экрана local windowX = (screenWidth - windowWidth) / 2 -- центрируем по горизонтали local windowY = (screenHeight - windowHeight) / 2 -- центрируем по вертикали -- Вычисляем размеры и координаты текста local textWidth = windowWidth * 0.9 -- 90% от ширины окна local textHeight = windowHeight * 0.7 -- 70% от высоты окна local textX = windowX + (windowWidth - textWidth) / 2 -- центрируем по горизонтали local textY = windowY + (windowHeight - textHeight) / 2 -- центрируем по вертикали -- Вычисляем размеры и координаты кнопки local buttonWidth = windowWidth * 0.2 -- 20% от ширины окна local buttonHeight = windowHeight * 0.1 -- 10% от высоты окна local buttonX = windowX + (windowWidth - buttonWidth) / 2 -- центрируем по горизонтали local buttonY = windowY + windowHeight * 0.8 -- располагаем внизу окна -- Рисуем окно DxGUI с помощью функции dxDrawRectangle dxDrawRectangle(windowX, windowY, windowWidth, windowHeight, tocolor(0, 0, 0, 200)) -- черный цвет с прозрачностью 200 -- Рисуем текст с помощью функции dxDrawText dxDrawText(currentMarker.text, textX, textY, textX + textWidth, textY + textHeight, tocolor(255, 255, 255, 255), 1, "default", "center", "center", true, true) -- белый цвет, размер 1, шрифт по умолчанию, выравнивание по центру, перенос по словам, клиппинг -- Рисуем кнопку с помощью функции dxDrawRectangle dxDrawRectangle(buttonX, buttonY, buttonWidth, buttonHeight, tocolor(255, 0, 0, 200)) -- красный цвет с прозрачностью 200 -- Рисуем текст на кнопке с помощью функции dxDrawText dxDrawText("Понял" buttonX, buttonY, buttonX + buttonWidth, buttonY + buttonHeight, tocolor(255, 255, 255, 255), 1, "default", "center", "center") -- белый цвет, размер 1, шрифт по умолчанию, выравнивание по центру -- Добавляем обработчик события onClientClick, чтобы обрабатывать нажатие на кнопку, и передаем ему координаты кнопки addEventHandler("onClientClick", root, onClick, false, "high", buttonX, buttonY, buttonWidth, buttonHeight) end end end -- Создаем функцию для обработки события onClientMarkerHit, когда игрок входит в маркер local function onMarkerHit(hitElement, matchingDimension) -- Проверяем, что элемент, вошедший в маркер, это игрок и он находится в том же измерении, что и маркер if hitElement == localPlayer and matchingDimension then -- Проверяем, что игрок не находится в транспортном средстве if not isPedInVehicle(localPlayer) then -- Проверяем, какой маркер был активирован if source == marker1Element then -- Устанавливаем текущий маркер равным первому маркеру currentMarker = marker1 elseif source == marker2Element then -- Устанавливаем текущий маркер равным второму маркеру currentMarker = marker2 end -- Добавляем текст к текущему маркеру в зависимости от его ID if currentMarker.id == "infoaboutserver" then currentMarker.text = marker1Text elseif currentMarker.id == "infoaboutwork" then currentMarker.text = marker2Text end -- Добавляем текст к текущему маркеру в зависимости от его ID if currentMarker.id == "infoaboutserver" then currentMarker.text = marker1Text elseif currentMarker.id == "infoaboutwork" then currentMarker.text = marker2Text end -- Добавляем обработчик события onClientRender, чтобы отрисовывать окно DxGUI addEventHandler("onClientRender", root, drawMarkerInfo) -- Включаем курсор мыши showCursor(true) end end end -- Создаем функцию для обработки события onClientMarkerLeave, когда игрок выходит из маркера local function onMarkerLeave(leaveElement, matchingDimension) -- Проверяем, что элемент, вышедший из маркера, это игрок и он находился в том же измерении, что и маркер if leaveElement == localPlayer and matchingDimension then -- Проверяем, что игрок не находится в транспортном средстве if not isPedInVehicle(localPlayer) then -- Удаляем обработчик события onClientRender, чтобы перестать отрисовывать окно DxGUI removeEventHandler("onClientRender", root, drawMarkerInfo) -- Удаляем обработчик события onClientClick, чтобы перестать обрабатывать нажатие на кнопку removeEventHandler("onClientClick", root, onClick) -- Выключаем курсор мыши showCursor(false) -- Обнуляем текущий маркер currentMarker = nil end end end -- Создаем функцию для обработки события onClientClick, когда игрок нажимает на кнопку мыши local function onClick(button, state, absoluteX, absoluteY, buttonX, buttonY, buttonWidth, buttonHeight) -- Проверяем, что кнопка мыши это левая и состояние это нажатие if button == "left" and state == "down" then -- Проверяем, что текущий маркер существует if currentMarker then -- Проверяем, что координаты клика мыши попадают в область кнопки, используя координаты окна DxGUI, переданные через аргументы if absoluteX >= buttonX and absoluteX <= buttonX + buttonWidth and absoluteY >= buttonY and absoluteY <= buttonY + buttonHeight then outputChatBox("Вы нажали на кнопку", localPlayer, 255, 255, 255) -- Удаляем обработчик события onClientRender, чтобы перестать отрисовывать окно DxGUI removeEventHandler("onClientRender", root, drawMarkerInfo) -- Удаляем обработчик события onClientClick, чтобы перестать обрабатывать нажатие на кнопку removeEventHandler("onClientClick", root, onClick) -- Выключаем курсор мыши showCursor(false) -- Обнуляем текущий маркер currentMarker = nil end end end end -- Добавляем обработчики событий для маркеров addEventHandler("onClientMarkerHit", marker1Element, onMarkerHit) addEventHandler("onClientMarkerHit", marker2Element, onMarkerHit) addEventHandler("onClientMarkerLeave", marker1Element, onMarkerLeave) addEventHandler("onClientMarkerLeave", marker2Element, onMarkerLeave) ПЕРЕПИШИ КОД ТАК, ЧТОБЫ ПО НАЖАТИЮ НА КНОПКУ "Понял" GUI ПОЛНОСТЬЮ ЗАКРЫВАЛСЯ
26b3b0ae4aa140791d684dee6a5ad35a
{ "intermediate": 0.3761155605316162, "beginner": 0.4012448489665985, "expert": 0.22263960540294647 }
40,380
Hii
31301804450c3046d83c9af558f16c50
{ "intermediate": 0.34221765398979187, "beginner": 0.29373040795326233, "expert": 0.3640519380569458 }
40,381
Learning php
47471c29774316350997e189f49f9ccf
{ "intermediate": 0.20048201084136963, "beginner": 0.41256967186927795, "expert": 0.38694828748703003 }
40,382
Well how good are AI face from blurry image generators
50271289409ff6047fa7c0d276bb952b
{ "intermediate": 0.1167517751455307, "beginner": 0.1419978141784668, "expert": 0.7412504553794861 }
40,383
#include <iostream> #include <cstdint> #include <Windows.h> #include <TlHelp32.h> static DWORD get_process_id(const wchar_t* process_name) { DWORD procId = 0; HANDLE snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (snapShot == INVALID_HANDLE_VALUE) return procId; PROCESSENTRY32 entry = {}; entry.dwSize = sizeof(decltype(entry)); if (Process32FirstW(snapShot, &entry) == TRUE) { if (_wcsicmp(process_name, entry.szExeFile) == 0) procId = entry.th32ProcessID; else { while (Process32NextW(snapShot, &entry) == TRUE) { if (_wcsicmp(process_name, entry.szExeFile) == 0) { procId = entry.th32ProcessID; break; } } } } CloseHandle(snapShot); return procId; } static std::uintptr_t get_module_base(const DWORD pid, const wchar_t* module_name) { std::uintptr_t mod_base = 0; HANDLE snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, NULL); if (snapShot == INVALID_HANDLE_VALUE) return mod_base; MODULEENTRY32 entry = {}; entry.dwSize = sizeof(decltype(entry)); if (Module32FirstW(snapShot, &entry) == TRUE) { if (_wcsicmp(module_name, entry.szModule) == 0) mod_base = (uintptr_t)entry.modBaseAddr; else { while (Module32FirstW(snapShot, &entry) == TRUE) { if (_wcsicmp(module_name, entry.szModule) == 0) { mod_base = (uintptr_t)entry.modBaseAddr; break; } } } } CloseHandle(snapShot); return mod_base; } namespace driver { namespace codes { constexpr ULONG attach = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x696, METHOD_BUFFERED, FILE_SPECIAL_ACCESS); constexpr ULONG read = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x697, METHOD_BUFFERED, FILE_SPECIAL_ACCESS); constexpr ULONG write = CTL_CODE(FILE_DEVICE_UNKNOWN, 0x698, METHOD_BUFFERED, FILE_SPECIAL_ACCESS); } struct Request { HANDLE process_id; PVOID target; PVOID buffer; SIZE_T size; SIZE_T return_size; }; bool attach_to_process(HANDLE driver_handle, const DWORD pid) { Request r; r.process_id = (HANDLE)pid; return DeviceIoControl(driver_handle, codes::attach, &r, sizeof(r), &r, sizeof(r), nullptr, nullptr); } template <class T> T read(HANDLE driver_handle, const std::uintptr_t addr) { T temp = {}; Request r; r.target = (PVOID)addr; r.buffer = &temp; r.size = sizeof(T); DeviceIoControl(driver_handle, codes::read, &r, sizeof(r), &r, sizeof(r), nullptr, nullptr); return temp; } template <class T> void write(HANDLE driver_handle, const std::uintptr_t addr, const T& val) { Request r; r.target = reinterpret_cast<PVOID(addr); r.buffer = (PVOID)&val; r.size = sizeof(T); DeviceIoControl(driver_handle, codes::write, &r, sizeof(r), &r, sizeof(r), nullptr, nullptr); } } int main() { const DWORD pid = get_process_id(L"notepad.exe"); if (pid == 0) { std::cout << "Failed to find cs2.exe. \n"; std::cin.get(); return 1; } std::cout << pid << "\n"; const HANDLE driver = CreateFileW(L"\\\\.\\FunnyDriver", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (driver == INVALID_HANDLE_VALUE) { std::cout << "Failed to create driver handle. \n"; std::cin.get(); return 1; } if (driver::attach_to_process(driver, pid)) { std::cout << "Attachment complete. \n"; } CloseHandle(driver); std::cin.get(); return 0; } Read a vavlue from the process notepadd using my code
86b7f29d864eeb8c8b7315df00c21915
{ "intermediate": 0.38156846165657043, "beginner": 0.4178975522518158, "expert": 0.2005339413881302 }
40,384
DWORD getModuleAddress(DWORD processID, const char* moduleName) { DWORD_PTR dwModuleBaseAddress = 0; DWORD result = 0; HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, processID); if (hSnapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 ModuleEntry32; ModuleEntry32.dwSize = sizeof(MODULEENTRY32); if (Module32First(hSnapshot, &ModuleEntry32)) { do { std::string moduleNameString(moduleName); std::string moduleNameWideString(moduleNameString.begin(), moduleNameString.end()); if (_tcsicmp(ModuleEntry32.szModule, moduleNameWideString.c_str()) == 0) { dwModuleBaseAddress = (DWORD_PTR)ModuleEntry32.modBaseAddr; result = dwModuleBaseAddress; break; } } while (Module32Next(hSnapshot, &ModuleEntry32)); } CloseHandle(hSnapshot); } return result; error Severity Code Description Project File Line Suppression State Details Error C2664 'int wcscmp(const wchar_t *,const wchar_t *)': cannot convert argument 2 from 'const _Elem *' to 'const wchar_t *' with [ _Elem=char ] Usermode C:\Users\nio\Desktop\SourceCode\Usermode\functions.cpp 27
7a2c082ba87e6bf693024dc01e278589
{ "intermediate": 0.4049033522605896, "beginner": 0.34810391068458557, "expert": 0.24699273705482483 }
40,385
Make a Minecraft give command for shulkerbox kit
56052d403847ddc565540059de487638
{ "intermediate": 0.45069602131843567, "beginner": 0.2634091377258301, "expert": 0.28589484095573425 }
40,386
Why keepalive option is disabled by default on Linux? Does it have a significant negative impact on performance?
4bc71ab389386623230870af16320baf
{ "intermediate": 0.28870144486427307, "beginner": 0.2137451469898224, "expert": 0.49755343794822693 }
40,387
Make a python script. The script takes 1 argument - 'filename'. It iterates subdirectories of the current directory with names '1', ..., '12' and opens text files with name equal to the input value 'filename' for read (if file is not found, then it shows an error). In each opened file it reads the first line, and looks for a string "Konto" in a list of strings separated by ';' symbol. It prints the index of Konto and proceeds to the next subdirectory.
65731f45be7c1e9711fb84f16ac561ff
{ "intermediate": 0.39682188630104065, "beginner": 0.17701368033885956, "expert": 0.4261644184589386 }
40,388
vod
0a1f8e8c0177965309fdf906e25fdb6a
{ "intermediate": 0.32456010580062866, "beginner": 0.2704116702079773, "expert": 0.40502816438674927 }
40,389
hi
000de7ac199d40df8d53d93bd8fa687d
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
40,390
Implement a program which can add together some number of pairs of vectors having arbitrary size. The program must be implemented in either C. Specifically, when submitting a zip file which will unpack into a prj2-sol directory which will minimally contain two shell scripts: prj2-sol/make.sh Running this script from any directory should build your program. prj2-sol/run.sh When run from any directory, this program should run the program built by make.sh. It should require two positive integer arguments: N_OPS The number of additions to be performed. N_ENTRIES The number of entries in each vector. The program should read N_OPS pairs of vectors from standard input. Each vector is specified as N_ENTRIES numbers separated by whitespace. After each pair of vectors is read, the program should write the pairwise sum of the two vectors on standard output as follows: Each entry in the sum vector is followed by a single space ' ' character. The output for each sum vector is followed by two newline '\n' characters. The program should terminate after performing N_OPS of these additions. [It follows that the program will read a total of N_OPS * 2 * N_ENTRIES from standard input and will write out a total 2 * N_OPS lines to standard output with each non-empty line containing N_ENTRIES numbers, each followed by a single space ' ']. Your program is subject to the following implementation restrictions: Your program must allocate memory for the two addend vectors and the sum vector on the heap. (The use of C's variable-length arrays VLAs is not acceptable). All memory dynamically allocated by your code must be explicitly released before program termination. The sum must first be computed into the sum vector before being written to standard output. Your program should not assume any maximum limits on N_ENTRIES beyond those dictated by available memory.
bc4075cee48a260341315d14d66cb8ee
{ "intermediate": 0.48450544476509094, "beginner": 0.18775522708892822, "expert": 0.32773929834365845 }
40,391
Implement a program which can add together some number of pairs of vectors having arbitrary size. The program must be implemented in either C. Specifically, when submitting a zip file which will unpack into a prj2-sol directory which will minimally contain two shell scripts: prj2-sol/make.sh Running this script from any directory should build your program. prj2-sol/run.sh When run from any directory, this program should run the program built by make.sh. It should require two positive integer arguments: N_OPS The number of additions to be performed. N_ENTRIES The number of entries in each vector. The program should read N_OPS pairs of vectors from standard input. Each vector is specified as N_ENTRIES numbers separated by whitespace. After each pair of vectors is read, the program should write the pairwise sum of the two vectors on standard output as follows: Each entry in the sum vector is followed by a single space ’ ’ character. The output for each sum vector is followed by two newline ‘\n’ characters. The program should terminate after performing N_OPS of these additions. [It follows that the program will read a total of N_OPS * 2 * N_ENTRIES from standard input and will write out a total 2 * N_OPS lines to standard output with each non-empty line containing N_ENTRIES numbers, each followed by a single space ’ ']. Your program is subject to the following implementation restrictions: Your program must allocate memory for the two addend vectors and the sum vector on the heap. (The use of C’s variable-length arrays VLAs is not acceptable). All memory dynamically allocated by your code must be explicitly released before program termination. The sum must first be computed into the sum vector before being written to standard output. Your program should not assume any maximum limits on N_ENTRIES beyond those dictated by available memory.
21b911f7ccb0a790e8e9f5c03e4d20d4
{ "intermediate": 0.45683592557907104, "beginner": 0.1906832605600357, "expert": 0.35248082876205444 }
40,392
look at my ensemble code again, from statsforecast import StatsForecast from statsforecast.models import AutoARIMA, AutoETS, DynamicOptimizedTheta from statsforecast.utils import ConformalIntervals import numpy as np import polars as pl # Polars option to display all rows pl.Config.set_tbl_rows(None) # Initialize the models models = [ AutoARIMA(season_length=12), AutoETS(season_length=12), DynamicOptimizedTheta(season_length=12) ] # Initialize the StatsForecast model sf = StatsForecast(models=models, freq=‘1w’, n_jobs=-1) # Perform cross-validation with a step size of 1 to mimic an expanding window crossvalidation_df = sf.cross_validation(df=y_cl4_filtered, h=1, step_size=1, n_windows=8, sort_df=True) # Calculate the ensemble mean ensemble = crossvalidation_df[[‘AutoARIMA’, ‘AutoETS’, ‘DynamicOptimizedTheta’]].mean(axis=1) # Create a Series for the ensemble mean ensemble_series = pl.Series(‘Ensemble’, ensemble) # Add the ensemble mean as a new column to the DataFrame crossvalidation_df = crossvalidation_df.with_columns(ensemble_series) def wmape(y_true, y_pred): return np.abs(y_true - y_pred).sum() / np.abs(y_true).sum() # Calculate the WMAPE for the ensemble model wmape_value = wmape(crossvalidation_df[‘y’], crossvalidation_df[‘Ensemble’]) print('Average WMAPE for Ensemble: ', round(wmape_value, 4)) # Calculate the errors for the ensemble model errors = crossvalidation_df[‘y’] - crossvalidation_df[‘Ensemble’] # For an individual forecast individual_accuracy = 1 - (abs(crossvalidation_df[‘y’] - crossvalidation_df[‘Ensemble’]) / crossvalidation_df[‘y’]) individual_bias = (crossvalidation_df[‘Ensemble’] / crossvalidation_df[‘y’]) - 1 # Add these calculations as new columns to DataFrame crossvalidation_df = crossvalidation_df.with_columns([ individual_accuracy.alias(“individual_accuracy”), individual_bias.alias(“individual_bias”) ]) # Print the individual accuracy and bias for each week for row in crossvalidation_df.to_dicts(): id = row[‘unique_id’] date = row[‘ds’] accuracy = row[‘individual_accuracy’] bias = row[‘individual_bias’] print(f"{id}, {date}, Individual Accuracy: {accuracy:.4f}, Individual Bias: {bias:.4f}") # For groups of forecasts group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df[‘y’].sum()) group_bias = (crossvalidation_df[‘Ensemble’].sum() / crossvalidation_df[‘y’].sum()) - 1 # Print the average group accuracy and group bias over all folds for the ensemble model print('Average Group Accuracy: ', round(group_accuracy, 4)) print(‘Average Group Bias: ‘, round(group_bias, 4)) # Fit the models on the entire dataset sf.fit(y_cl4_fit_1) # Instantiate the ConformalIntervals class prediction_intervals = ConformalIntervals() # Generate 24 months forecasts forecasts_df = sf.forecast(h=52*2, prediction_intervals=prediction_intervals, level=[95], id_col=‘unique_id’, sort_df=True) # Apply the non-negative constraint to the forecasts of individual models forecasts_df = forecasts_df.with_columns([ pl.when(pl.col(‘AutoARIMA’) < 0).then(0).otherwise(pl.col(‘AutoARIMA’)).alias(‘AutoARIMA’), pl.when(pl.col(‘AutoETS’) < 0).then(0).otherwise(pl.col(‘AutoETS’)).alias(‘AutoETS’), pl.when(pl.col(‘DynamicOptimizedTheta’) < 0).then(0).otherwise(pl.col(‘DynamicOptimizedTheta’)).alias(‘DynamicOptimizedTheta’), ]) # Calculate the ensemble forecast ensemble_forecast = forecasts_df[[‘AutoARIMA’, ‘AutoETS’, ‘DynamicOptimizedTheta’]].mean(axis=1) # Calculate the lower and upper prediction intervals for the ensemble forecast ensemble_lo_95 = forecasts_df.select( [ pl.when(pl.col(‘AutoARIMA-lo-95’) < 0).then(0).otherwise(pl.col(‘AutoARIMA-lo-95’)).alias(‘AutoARIMA-lo-95’), pl.when(pl.col(‘AutoETS-lo-95’) < 0).then(0).otherwise(pl.col(‘AutoETS-lo-95’)).alias(‘AutoETS-lo-95’), pl.when(pl.col(‘DynamicOptimizedTheta-lo-95’) < 0).then(0).otherwise(pl.col(‘DynamicOptimizedTheta-lo-95’)).alias(‘DynamicOptimizedTheta-lo-95’), ] ).mean(axis=1) ensemble_hi_95 = forecasts_df[[‘AutoARIMA-hi-95’, ‘AutoETS-hi-95’, ‘DynamicOptimizedTheta-hi-95’]].mean(axis=1) # Create Series for the ensemble forecast and its prediction intervals ensemble_forecast_series = pl.Series(‘EnsembleForecast’, ensemble_forecast) ensemble_lo_95_series = pl.Series(‘Ensemble-lo-95’, ensemble_lo_95) ensemble_hi_95_series = pl.Series(‘Ensemble-hi-95’, ensemble_hi_95) # Add the ensemble forecast and its prediction intervals as new columns to the DataFrame forecasts_df = forecasts_df.with_columns([ensemble_forecast_series, ensemble_lo_95_series, ensemble_hi_95_series]) # Round the ensemble forecast and prediction intervals and convert to integer forecasts_df = forecasts_df.with_columns([ pl.col(“EnsembleForecast”).round().cast(pl.Int32), pl.col(“Ensemble-lo-95”).round().cast(pl.Int32), pl.col(“Ensemble-hi-95”).round().cast(pl.Int32) ]) # Reorder the columns forecasts_df = forecasts_df.select([ “unique_id”, “ds”, “EnsembleForecast”, “Ensemble-lo-95”, “Ensemble-hi-95”, “AutoARIMA”, “AutoARIMA-lo-95”, “AutoARIMA-hi-95”, “AutoETS”, “AutoETS-lo-95”, “AutoETS-hi-95”, “DynamicOptimizedTheta”, “DynamicOptimizedTheta-lo-95”, “DynamicOptimizedTheta-hi-95” ]) # Create an empty list forecasts_list = [] # Append each row to the list for row in forecasts_df.to_dicts(): forecasts_list.append(row) # Print the list for forecast in forecasts_list: print(forecast) you could see taht unique id was created using 4 columns concat # Concatenate ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, ‘CL4’ to a new column ‘unique_id’ y_cl4 = y_cl4.with_columns( pl.concat_str([pl.col(‘MaterialID’), pl.col(‘SalesOrg’), pl.col(‘DistrChan’), pl.col(‘CL4’)], separator=’_’).alias(‘unique_id’) ) # Drop the original columns y_cl4 = y_cl4.drop([‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, ‘CL4’]) y_cl4 = y_cl4.rename({‘WeekDate’: ‘ds’, ‘OrderQuantity’: ‘y’}), some of the output {‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 9, 22, 0, 0), ‘EnsembleForecast’: 5691, ‘Ensemble-lo-95’: 3171, ‘Ensemble-hi-95’: 8212, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5528.330078125, ‘AutoETS-lo-95’: 4238.36279296875, ‘AutoETS-hi-95’: 6818.29736328125, ‘CES’: 6107.98779296875, ‘CES-lo-95’: 2193.064208984375, ‘CES-hi-95’: 10022.9111328125, ‘DynamicOptimizedTheta’: 5567.36328125, ‘DynamicOptimizedTheta-lo-95’: 3139.6455078125, ‘DynamicOptimizedTheta-hi-95’: 7995.0810546875} {‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 9, 29, 0, 0), ‘EnsembleForecast’: 5260, ‘Ensemble-lo-95’: 2739, ‘Ensemble-hi-95’: 7780, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5528.716796875, ‘AutoETS-lo-95’: 4238.74951171875, ‘AutoETS-hi-95’: 6818.68408203125, ‘CES’: 4380.20947265625, ‘CES-lo-95’: 465.2858581542969, ‘CES-hi-95’: 8295.1328125, ‘DynamicOptimizedTheta’: 5567.37158203125, ‘DynamicOptimizedTheta-lo-95’: 3139.65380859375, ‘DynamicOptimizedTheta-hi-95’: 7995.08935546875} {‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 10, 6, 0, 0), ‘EnsembleForecast’: 5238, ‘Ensemble-lo-95’: 2717, ‘Ensemble-hi-95’: 7758, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5529.08837890625, ‘AutoETS-lo-95’: 4239.12109375, ‘AutoETS-hi-95’: 6819.0556640625, ‘CES’: 4292.49072265625, ‘CES-lo-95’: 377.5670166015625, ‘CES-hi-95’: 8207.4140625, ‘DynamicOptimizedTheta’: 5567.3798828125, ‘DynamicOptimizedTheta-lo-95’: 3139.662109375, ‘DynamicOptimizedTheta-hi-95’: 7995.09765625} {‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 10, 13, 0, 0), ‘EnsembleForecast’: 5165, ‘Ensemble-lo-95’: 2645, ‘Ensemble-hi-95’: 7685, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5529.4462890625, ‘AutoETS-lo-95’: 4239.47900390625, ‘AutoETS-hi-95’: 6819.41357421875, ‘CES’: 4001.488037109375, ‘CES-lo-95’: 86.56428527832031, ‘CES-hi-95’: 7916.41162109375, ‘DynamicOptimizedTheta’: 5567.38818359375, ‘DynamicOptimizedTheta-lo-95’: 3139.67041015625, ‘DynamicOptimizedTheta-hi-95’: 7995.10595703125} is there a way to break the unqiue id in the 4 columns in the output again? so instead of ‘unique_id’: …, it would be material_id: …, sales_org:. …, distrchan: …, cl4: …, and also the ‘ds’ be rename back to ‘WeekDate’
e362a7b474cb50c1e6b451b12bf70f89
{ "intermediate": 0.24507586658000946, "beginner": 0.4521588683128357, "expert": 0.30276522040367126 }
40,393
Is this code correct? Why doesn't it loop through the database and display on the page? <tbody> <!-- TODO: Loop through the database entries to display them in this table --> {% for name in name %} <tr> <td>{{ registrant.name }}</td> <td>{{ registrant.sport }}</td> <td> <form action="/deregister" method="post"> <input name="id" type="hidden" value="{{ registrant.id }}"> <button type="submit">Deregister</button> </form> </td> </tr> {% endfor %} </tbody>
df4daa0e0c27929629bb380e28f82d28
{ "intermediate": 0.23866772651672363, "beginner": 0.6245225071907043, "expert": 0.1368098109960556 }
40,394
help me write a vue code?
4c29029644c973096954b1ddfd3ea8ae
{ "intermediate": 0.4641972482204437, "beginner": 0.20043335855007172, "expert": 0.33536937832832336 }
40,395
change apk package id (Defold engine)
50709499305efc2989efee13c4a578b1
{ "intermediate": 0.4166785478591919, "beginner": 0.18641366064548492, "expert": 0.39690783619880676 }
40,396
Please fix the following code base for a flask app. Here is index.html <!DOCTYPE html> <html lang="en"> <head> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet"> <link href="/static/styles.css" rel="stylesheet"> <title>Birthdays</title> </head> <body> <div class="header"> <h1>Birthdays</h1> </div> <div class="container"> <div class="section"> <h2>Add a Birthday</h2> <!-- TODO: Create a form for users to submit a name, a month, and a day --> <form action="/" method="post"> <label for="name">First and Last Name</label><br> <input type="text" id="name" name="name"><br> <label for="month">In what month were you born?</label><br> <input type="text" id="month" name="month"><br> <label for="day">What day were you born?</label><br> <input type="text" id="day" name="day"><br><br> <input type="submit" value="Submit"> </form> </div> <div class="section"> <h2>All Birthdays</h2> <table> <thead> <tr> <th>Name</th> <th>Day</th> <th>Month</th> </tr> </thead> <tbody> <!-- TODO: Loop through the database entries to display them in this table --> {% for registrant in registrants %} <tr> <td>{{ registrant.name }}</td> <td>{{ registrant.sport }}</td> <td> <form action="/deregister" method="post"> <input name="id" type="hidden" value="{{ registrant.id }}"> <button type="submit">Deregister</button> </form> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </body> </html> And here is app.py import os from cs50 import SQL from flask import Flask, flash, jsonify, redirect, render_template, request, session # Configure application app = Flask(__name__) # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True # Configure CS50 Library to use SQLite database db = SQL("sqlite:///birthdays.db") @app.after_request def after_request(response): """Ensure responses aren't cached""" response.headers["Cache-Control"] = "no-cache, no-store, must-revflaskdate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response # @app.route("/deregister", methods=["POST"]) # def deregister(): # # Forget registrant # id = request.form.get("id") # if id: # db.execute("DELETE FROM registrants WHERE id = ?", id) # return redirect("/registrants") @app.route("/", methods=["GET", "POST"]) def index(): if request.method == "POST": # TODO: Add the user's entry into the database return redirect("/") else: # TODO: Display the entries in the database on index.html return render_template("index.html")
75011c33d1e621510c48e5d80b1cdc00
{ "intermediate": 0.33034616708755493, "beginner": 0.5533572435379028, "expert": 0.11629651486873627 }
40,397
Please provide detailed comments for the following flask app import os from cs50 import SQL from flask import Flask, flash, jsonify, redirect, render_template, request, session from flask import Flask, redirect, render_template, request, session from flask_session import Session from werkzeug.security import check_password_hash, generate_password_hash # Configure application app = Flask(__name__) # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True # Configure CS50 Library to use SQLite database db = SQL("sqlite:///birthdays.db") app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": username = request.form.get("username") password = request.form.get("password") if not username or not password: return "Missing username or password", 400 user = db.execute("SELECT * FROM users WHERE username = ?", username) if len(user) != 1 or not check_password_hash(user[0]["hash"], password): return "Invalid username and/or password", 403 session["user_id"] = user[0]["id"] return redirect("/") else: return render_template("login.html") @app.route("/logout") def logout(): session.clear() return redirect("/") @app.after_request def after_request(response): """Ensure responses aren't cached""" response.headers["Cache-Control"] = "no-cache, no-store, must-revflaskdate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response @app.route("/deregister", methods=["POST"]) def deregister(): if not session.get("user_id"): return "Unauthorized", 403 id = request.form.get("id") if id: db.execute("DELETE FROM birthdays WHERE id = ?", id) return redirect("/") @app.route("/", methods=["GET", "POST"]) def index(): if request.method == "POST": # TODO: Add the user's entry into the database name = request.form.get("name") month = request.form.get("month") day = request.form.get("day") if not name or not month or not day: return "Missing fields", 400 db.execute("INSERT INTO birthdays (name, month, day) VALUES (?, ?, ?)", name, month, day) return redirect("/") else: birthdays = db.execute("SELECT * FROM birthdays") return render_template("index.html", birthdays=birthdays)
aac208f8923bf71e7ab49de642e84d56
{ "intermediate": 0.3604528605937958, "beginner": 0.36350658535957336, "expert": 0.2760404944419861 }
40,398
Привет, можешь реализовать следующий код без создания new_bitmap?: std::vector<std::vector<unsigned char>> new_bitmap; for (const auto& row : bitmap) { std::vector<unsigned char> new_row; for (size_t j = 0; j < row.size(); j += 3) { RgbQuad color(row[j], row[j + 1], row[j + 2], 0); int minDiff = std::numeric_limits<int>::max(); int bestMatchIndex = 0; for (size_t k = 0; k < palette.size(); ++k) { int diff = colorDifference(color, palette[k]); if (diff < minDiff) { minDiff = diff; bestMatchIndex = k; } } new_row.push_back(bestMatchIndex); } new_bitmap.push_back(new_row); } bitmap = new_bitmap;
956b7f93fdc679baa60c246884e4142e
{ "intermediate": 0.455278605222702, "beginner": 0.28644269704818726, "expert": 0.2582787275314331 }
40,399
I have a java spring project with hibernate. I currently have many classes (models), one of which is Journal. Journal contains Patient, Doctor objects and etc. I want to exclude unnecesary fields inside those objects for different controller methods. For example, when I make a request for any kind of journal list, I dont need anything besides date and patient/doctor data, inside those objects I dont want to send anything besides id and name fields. Is there any annotation that allows such functionality?
66e022f64e6de1c97c1cb6e54ddd7afb
{ "intermediate": 0.5501039624214172, "beginner": 0.3239455819129944, "expert": 0.12595047056674957 }
40,400
Write a fictional, detailed and accurate CableLabs Video-On-Demand Content Specification XML code of "Christmas is Here Again" (including ondemand.spectrum.com, twondemand.com and indemand.com data).
cb6ecf3fef7ff3e2cc6e9881791f965b
{ "intermediate": 0.37627914547920227, "beginner": 0.317283034324646, "expert": 0.3064378499984741 }
40,401
Write a fictional, detailed and accurate CableLabs Video-On-Demand Content Specification XML code of "SpongeBob SquarePants: The Thing/Hocus Pocus" (including ondemand.spectrum.com, twondemand.com and indemand.com data).
ca2f012ec6a9c84fffed664e40e1326a
{ "intermediate": 0.3964252471923828, "beginner": 0.33194684982299805, "expert": 0.27162790298461914 }
40,402
Write a fictional, detailed and accurate CableLabs Video-On-Demand Content Specification XML code of "SpongeBob SquarePants: Krabby Land/The Camping Episode" (including ondemand.spectrum.com, twondemand.com and indemand.com data).
f6d405480084e64e4cc2bb36d920773d
{ "intermediate": 0.40223243832588196, "beginner": 0.317914754152298, "expert": 0.27985283732414246 }
40,403
Write a fictional, detailed and accurate CableLabs Video-On-Demand Content Specification XML code of "SpongeBob SquarePants: The Great Snail Race/Mid-Life Crustacean” (including ondemand.spectrum.com, twondemand.com and indemand.com data).
c0a21ad22a0cd3ba1157acbc0864279f
{ "intermediate": 0.37316906452178955, "beginner": 0.351173996925354, "expert": 0.27565690875053406 }
40,404
Write a fictional, detailed and accurate CableLabs Video-On-Demand Content Specification XML code of "SpongeBob SquarePants: Bubblestand/Ripped Pants” (including ondemand.spectrum.com, twondemand.com and indemand.com data).
43804326138d0d701b6464214a21415c
{ "intermediate": 0.388998806476593, "beginner": 0.3440689444541931, "expert": 0.2669321894645691 }
40,405
how to extract all my twitter followers using python?
5c0c27230352c170e455f7352e0699a8
{ "intermediate": 0.43580588698387146, "beginner": 0.14782388508319855, "expert": 0.4163702428340912 }
40,406
in burp suite when we intercept request and change host server will response 200 OK host header injection how to prevent this on IIS level
04cb1e4b329b5db169fd3bad612c39c8
{ "intermediate": 0.458381712436676, "beginner": 0.2292279601097107, "expert": 0.3123903274536133 }
40,407
#define RGB_IMAGE(member) (rgb_image_hdmi.member)here what mean by member . there is no member variable present in the RGB_IMAGE struct. where actully this member is came from
c2ed44d1a816b4f06a57a40e4e67448f
{ "intermediate": 0.28063786029815674, "beginner": 0.4860316812992096, "expert": 0.23333056271076202 }
40,408
How to get date added of a DICOM study in orthanc?
6f49fc1daa046838742b5c6ea51cc54f
{ "intermediate": 0.2413560003042221, "beginner": 0.16423523426055908, "expert": 0.5944087505340576 }
40,409
i need you to alter the below python code, here the generated random values within the specified bounds are need to be round off with two decimal points for the variables 'L1', 'L3', 'L5', 'L6', 'L7', 'W1', 'W3', 'W5', 'W6', 'W7', 'CP' and with one decimal point for the variable 'VCM' and without any decimal point for the variable 'Io'. if __name__ == "__main__": # Define bounds and number of samples bounds = {'L1': (0.18e-6, 1e-6), 'L3': (0.18e-6, 1e-6), 'L5': (0.18e-6, 1e-6), 'L6': (0.18e-6, 1e-6), 'L7': (0.18e-6, 1e-6), 'W1': (1e-6, 12e-6), 'W3': (2.52e-6, 28e-6), 'W5': (2.16e-6, 24e-6), 'W6': (32e-6, 100e-6), 'W7': (13.5e-6, 100e-6), 'Io': (15e-6, 30e-6), 'CP': (0.44e-12, 3e-12), 'VCM': (0.8, 1.4)} num_samples = 50 # Adjust the number of samples as needed # Generate input_data input_data_list = generate_input_data(bounds, num_samples) # Function to generate input_data def generate_input_data(bounds, num_samples): input_data_set = set() while len(input_data_set) < num_samples: input_data = [random.uniform(bounds[key][0], bounds[key][1]) for key in bounds] input_data_tuple = tuple(input_data) input_data_set.add(input_data_tuple) return list(input_data_set)
768054cf241f8b4316342b57c05d245a
{ "intermediate": 0.3886326849460602, "beginner": 0.25893914699554443, "expert": 0.3524281680583954 }
40,410
HI!
344e5a34d52b76c76fb7f88ede336db5
{ "intermediate": 0.3374777138233185, "beginner": 0.2601830065250397, "expert": 0.40233927965164185 }
40,411
An automated cutting machine is used to cut rods into segments. The cutting machine can only hold a rod of minLength or more. A rod is marked with the necessary cuts and their lengths are given as an array in the order they are marked. Determine if it is possible to plan the cuts so the last cut is from a rod at least minLength units long. Example lengths = [4, 3, 2] minLength = 7 The rod is initially sum(lengths) = 4 +3 +2 = 9 units long. First cut off the segment of length 4 7 leaving a rod 9-7=2. Then check that the length 7 rod can be cut into segments of lengths 4 and 3. Since 7 is greater than or equal to minLength = 7, the final cut can be made. Return "Possible". Example lengths = [4, 2, 3] minLength = 7 The rod is initially sum(lengths) =4 +2 +3= 9 units long. In this case, the initial cut can be of length 40r 4 +2 = 6. Regardless of the length of the first cut, the remaining piece will be shorter than minLength. Because n - 1 = 2 cuts cannot be made, the answer is " Impossible. " Function Description Complete the function cutThemAll: cutThemAll has the following parameter(s): int lengths[n]: the lengths of the segments, in order. int minLength: the minimum length the machine can accept Returns string: "Possible" if all n-1 cuts can be made. Otherwise, return the string "Impossible". boiler plate code: string cutThemAII (vector < long> lengths, long minLength) { } Write C++ code for the problem
0c724bed2e3e8af2700682e9c3963816
{ "intermediate": 0.36070767045021057, "beginner": 0.33047744631767273, "expert": 0.3088148534297943 }
40,412
I want you to act as a full stack developer providing production ready code for backend as well as front end. I will ask you to develop the code for the backend and font end and provide it to me. My first request is "I want to develop a production ready font end for login and sign up"
97085703aee024cabbf1932bd73e4efa
{ "intermediate": 0.6676363945007324, "beginner": 0.2057623267173767, "expert": 0.12660126388072968 }
40,413
how to get raw response data using python requests
905104f47e06f3ee2a87ba4f405100e5
{ "intermediate": 0.5288169980049133, "beginner": 0.21711896359920502, "expert": 0.2540641129016876 }
40,414
I have this js code in react inside Promise. if ( $currentAppeal.getState() == null || appealId !== $currentAppeal.getState().id ) { reject({ status: 400, statusText: 'Id обращения неравен Id активного обращения', }); return; } Currently I have a TypeScript error stating that 'Object is possibly 'null'.' regarding $currentAppeal.getState(). How to fix this problem
757a2483bed451d409ff11df9e3091d4
{ "intermediate": 0.6125187277793884, "beginner": 0.29877686500549316, "expert": 0.08870436996221542 }
40,415
I have a windows batch file and at the end of script I would like to run an After Effects Script (script name is "after_effects_script.jsx". How can I achieve this?
9eb90607ec2ae2060ca5d0a0c1d1e87c
{ "intermediate": 0.4353893995285034, "beginner": 0.3588569462299347, "expert": 0.2057536244392395 }
40,416
circle progress bar show the number the remaining in queue , angular
712c9d287e529c9415b96192d62d3e5a
{ "intermediate": 0.41974952816963196, "beginner": 0.189690962433815, "expert": 0.39055952429771423 }
40,417
from statsforecast import StatsForecast from statsforecast.models import AutoARIMA, SimpleExponentialSmoothing, HistoricAverage, Naive, RandomWalkWithDrift, SeasonalNaive from statsforecast.utils import ConformalIntervals import numpy as np import polars as pl # Polars option to display all rows pl.Config.set_tbl_rows(None) # Initialize the models models = [ AutoARIMA(season_length=12), SimpleExponentialSmoothing(alpha=0.8), HistoricAverage(), Naive(), RandomWalkWithDrift(), SeasonalNaive(season_length=12) ] # Initialize the StatsForecast model sf = StatsForecast(models=models, freq='1w', n_jobs=-1) # Perform cross-validation with a step size of 1 to mimic an expanding window crossvalidation_df = sf.cross_validation(df=y_cl4_filtered, h=2, step_size=1, n_windows=8, sort_df=True) # Calculate the ensemble mean ensemble = crossvalidation_df[['AutoARIMA', 'SimpleExponentialSmoothing', 'HistoricAverage', 'Naive', 'RandomWalkWithDrift', 'SeasonalNaive']].mean(axis=1) # Create a Series for the ensemble mean ensemble_series = pl.Series('Ensemble', ensemble) # Add the ensemble mean as a new column to the DataFrame crossvalidation_df = crossvalidation_df.with_columns(ensemble_series) def wmape(y_true, y_pred): return np.abs(y_true - y_pred).sum() / np.abs(y_true).sum() # Calculate the WMAPE for the ensemble model wmape_value = wmape(crossvalidation_df['y'], crossvalidation_df['Ensemble']) print('Average WMAPE for Ensemble: ', round(wmape_value, 4)) # Calculate the errors for the ensemble model errors = crossvalidation_df['y'] - crossvalidation_df['Ensemble'] # For an individual forecast individual_accuracy = 1 - (abs(crossvalidation_df['y'] - crossvalidation_df['Ensemble']) / crossvalidation_df['y']) individual_bias = (crossvalidation_df['Ensemble'] / crossvalidation_df['y']) - 1 # Add these calculations as new columns to DataFrame crossvalidation_df = crossvalidation_df.with_columns([ individual_accuracy.alias("individual_accuracy"), individual_bias.alias("individual_bias") ]) # Print the individual accuracy and bias for each week for row in crossvalidation_df.to_dicts(): id = row['unique_id'] date = row['ds'] accuracy = row['individual_accuracy'] bias = row['individual_bias'] print(f"{id}, {date}, Individual Accuracy: {accuracy:.4f}, Individual Bias: {bias:.4f}") # For groups of forecasts group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df['y'].sum()) group_bias = (crossvalidation_df['Ensemble'].sum() / crossvalidation_df['y'].sum()) - 1 # Print the average group accuracy and group bias over all folds for the ensemble model print('Average Group Accuracy: ', round(group_accuracy, 4)) print('Average Group Bias: ', round(group_bias, 4)) -------------------------------------------------------------------------- ColumnNotFoundError Traceback (most recent call last) /var/folders/fb/wc6gnylj4cl033fkktj66zrc0000gn/T/ipykernel_11107/154608881.py in ?() 23 # Perform cross-validation with a step size of 1 to mimic an expanding window 24 crossvalidation_df = sf.cross_validation(df=y_cl4_filtered, h=2, step_size=1, n_windows=8, sort_df=True) 25 26 # Calculate the ensemble mean ---> 27 ensemble = crossvalidation_df[['AutoARIMA', 'SimpleExponentialSmoothing', 'HistoricAverage', 'Naive', 'RandomWalkWithDrift', 'SeasonalNaive']].mean(axis=1) 28 29 # Create a Series for the ensemble mean 30 ensemble_series = pl.Series('Ensemble', ensemble) ~/anaconda3/lib/python3.10/site-packages/polars/dataframe/frame.py in ?(self, item) 1738 1739 if is_str_sequence(item, allow_str=False): 1740 # select multiple columns 1741 # df[["foo", "bar"]] -> 1742 return self._from_pydf(self._df.select(item)) 1743 elif is_int_sequence(item): 1744 item = pl.Series("", item) # fall through to next if isinstance 1745 ColumnNotFoundError: SimpleExponentialSmoothing
d4b89fbbb20715bcd934317396b393cd
{ "intermediate": 0.2922683358192444, "beginner": 0.44214385747909546, "expert": 0.26558783650398254 }
40,418
write me a script with gui for mac to show the devices on my network updating every minute
b04678469ad253c1b28de7e4eee3b776
{ "intermediate": 0.5096166133880615, "beginner": 0.1377851366996765, "expert": 0.3525982201099396 }
40,419
how do i remove li { list-style: none } at the for the contents of <?php echo $selBlogRow['content']; ?> in : <?php include("../conn.php"); $Id = $_GET['id']; ?> <!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"> <!-- - primary meta tags --> <title>NUXLES Blog</title> <meta name="title" content="NUXLES Blog Website"> <meta name="description" content="This is a compilation of guides, articles and news from NUXLES"> <!-- - favicon --> <link rel="shortcut icon" type="png" href="/images/icon/favicon.png"> <!-- - google font link --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css?family=Quicksand:400,600,700&display=swap" rel="stylesheet"> <!-- - custom css link --> <link rel="stylesheet" href="./assets/css/blog.css"> <!-- - preload images --> <link rel="preload" as="image" href="./assets/images/hero-banner.png"> <link rel="preload" as="image" href="./assets/images/pattern-2.svg"> <link rel="preload" as="image" href="./assets/images/pattern-3.svg"> </head> <body id="top"> <!-- - #HEADER --> <header class="header" data-header> <div class="container"> <a href="#" class="logo"> <img src="/images/icon/logo2.png" width="150" height="49" alt="NUXLES logo"> </a> <nav class="navbar" data-navbar> <div class="navbar-top"> <a href="#" class="logo"> <img src="/images/icon/logo2.png" width="150" height="49" alt="NUXLES logo"> </a> <button class="nav-close-btn" aria-label="close menu" data-nav-toggler> <ion-icon name="close-outline" aria-hidden="true"></ion-icon> </button> </div> <ul class="navbar-list"> <li> <a href="index.php" class="navbar-link hover-1" data-nav-toggler>Home</a> </li> <li> <a href="index.php#categories" class="navbar-link hover-1" data-nav-toggler>Categories</a> </li> <li> <a href="index.php#featured" class="navbar-link hover-1" data-nav-toggler>Featured Post</a> </li> <li> <a href="index.php#recent" class="navbar-link hover-1" data-nav-toggler>Recent Post</a> </li> <li> <a href="/index.php#contactus_section" class="navbar-link hover-1" data-nav-toggler>Contact</a> </li> </ul> <p class="copyright-text"> Copyright 2023 © NUXLES - Educational Blog </p> </nav> <a href="https://nuxles.com/" class="btn btn-primary">Nuxles School</a> <button class="nav-open-btn" aria-label="open menu" data-nav-toggler> <ion-icon name="menu-outline" aria-hidden="true"></ion-icon> </button> </div> </header> <main> <article> <style> .profile-card .profile-banner { border-radius: 15px; width: 68px; height: 68px; } .card-title { color: #ff2e97 !important; font-weight: 800; } .card-subtitle { color: #00acbe !important; font-weight: 600; } a { display: inline-block !important; } </style> <!-- - #HERO --> <section class="section recent-post" id="recent" aria-labelledby="recent-label"> <div class="container"> <div class="post-main"> <?php $selBlog = $conn->query("SELECT * FROM blogs WHERE id='$Id' "); while ($selBlogRow = $selBlog->fetch(PDO::FETCH_ASSOC)) { ?> <img src="<?php echo $selBlogRow['thumbnail']; ?>" alt="post_image" class="img-fluid"> <h2 class="headline headline-3 section-title"> <span class="span"><?php echo $selBlogRow['title']; ?></span> </h2> <div class="profile-card"> <img src="<?php echo $selBlogRow['author_image']; ?>" width="48" height="48" loading="lazy" alt="<?php echo $selBlogRow['author_image']; ?>" class="profile-banner"> <div> <p class="card-title"><?php echo $selBlogRow['author']; ?></p> <p class="card-subtitle"><?php echo $selBlogRow['publish_date']; ?></p> </div> </div> <p class="hero-text"> <?php echo $selBlogRow['content']; ?> </p> </div> <?php } ?> <div class="post-aside grid-lists"> <div class="card aside-card"> <h3 class="headline headline-2 aside-title"> <span class="span">Popular Posts</span> </h3> <ul class="popular-list"> <?php $selPopularPost = $conn->query("SELECT * FROM blogs WHERE editors=1 "); while ($selPopularPostRow= $selPopularPost->fetch(PDO::FETCH_ASSOC)) { ?> <li> <div class="popular-card"> <figure class="card-banner img-holder" style="--width: 64; --height: 64;"> <img src="<?php echo $selPopularPostRow['thumbnail']; ?>" width="64" height="64" loading="lazy" alt="<?php echo $selPopularPostRow['title']; ?>" class="img-cover"> </figure> <div class="card-content"> <h4 class="headline headline-4 card-title"> <a href="blog.php?id=<?php echo $selPopularPostRow['id']; ?>" class="link hover-2"><?php echo $selPopularPostRow['title']; ?></a> </h4> <div class="warpper"> <p class="card-subtitle"><?php echo $selPopularPostRow['duration']; ?> min read</p> <time class="publish-date"><?php echo $selPopularPostRow['publish_date']; ?></time> </div> </div> </div> </li> <?php } ?> </ul> </div> <div class="card aside-card insta-card"> <a href="#" class="logo"> <img src="/images/icon/logo2.png" width="150" height="49" loading="lazy" alt="NUXLES logo"> </a> <p class="card-text"> Join the conversation on facebook </p> <ul class="insta-list"> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-1.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-2.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-3.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-4.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-5.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-6.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-7.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-8.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> <li> <a href="https://m.facebook.com/groups/704989174718376/" class="insta-post img-holder" style="--width: 276; --height: 277;"> <img src="./assets/images/insta-post-9.png" width="276" height="277" loading="lazy" alt="insta post" class="img-cover"> </a> </li> </ul> </div> </div> </div> </section> <section class="section recent-post" id="recent" aria-labelledby="recent-label"> <div class="container"> <div class="post-aside grid-list"> <div class="card aside-card" id="disqus_thread"> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://vycta-com.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> <div class="card aside-card"> <h3 class="headline headline-2 aside-title"> <span class="span">Recent Posts</span> </h3> <ul class="popular-list"> <?php $selRecentPost = $conn->query("SELECT * FROM blogs ORDER BY id DESC "); while ($selRecentPostRow = $selRecentPost->fetch(PDO::FETCH_ASSOC)) { ?> <li> <div class="popular-card"> <figure class="card-banner img-holder" style="--width: 64; --height: 64;"> <img src="<?php echo $selRecentPostRow['thumbnail']; ?>" width="64" height="64" loading="lazy" alt="<?php echo $selRecentPostRow['title']; ?>" class="img-cover"> </figure> <div class="card-content"> <h4 class="headline headline-4 card-title"> <a href="blog.php?id=<?php echo $selRecentPostRow['id']; ?>" class="link hover-2"><?php echo $selRecentPostRow['title']; ?></a> </h4> <div class="warpper"> <p class="card-subtitle"><?php echo $selRecentPostRow['duration']; ?> min read</p> <time class="publish-date"><?php echo $selRecentPostRow['publish_date']; ?></time> </div> </div> </div> </li> <?php } ?> </ul> </div> </div> </div> </section> </article> </main> <!-- - #FOOTER --> <footer> <div class="container"> <div class="card footer"> <div class="section footer-top"> <div class="footer-brand"> <a href="#" class="logo"> <img src="/images/icon/logo2.png" width="129" height="47" loading="lazy" alt="NUXLES logo"> </a> <p class="footer-text"> Our prep courses, articles and study guides are written by industry experts, with the primary focus of empowering the medical professionals of the future with all the skills necessary to begin their career. </p> <p class="footer-list-title">Contact</p> <address class="footer-text address"> <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> </address> </div> <div class="footer-list"> <p class="footer-list-title">Categories</p> <ul> <?php // Loop through the categories query result and output each category as a button $selAllCategories = $conn->query("SELECT * FROM blog_categories ORDER BY id DESC"); while ($selAllCategoriesRow = $selAllCategories->fetch(PDO::FETCH_ASSOC)) { ?> <li> <a href="#" class="footer-link hover-2"> <?php echo $selAllCategoriesRow['category']; ?> </a> </li> <?php } ?> </ul> </div> <div class="footer-list"> <p class="footer-list-title">Newsletter</p> <p class="footer-text"> Sign up to be first to receive the latest stories inspiring us, case studies, and industry news. </p> <div class="input-wrapper"> <input type="text" name="name" placeholder="Your name" required class="input-field" autocomplete="off"> <ion-icon name="person-outline" aria-hidden="true"></ion-icon> </div> <div class="input-wrapper"> <input type="email" name="email_address" placeholder="Emaill address" required class="input-field" autocomplete="off"> <ion-icon name="mail-outline" aria-hidden="true"></ion-icon> </div> <a href="#" class="btn btn-primary"> <span class="span">Subscribe</span> <ion-icon name="arrow-forward" aria-hidden="true"></ion-icon> </a> </div> </div> <div class="footer-bottom"> <p class="copyright"> Copyright &copy; 2023 <a href="https://nuxles.com" class="copyright-link">NUXLES, INC.</a> All RIGHTS RESERVED. </p> <ul class="social-list"> <li> <a href="#" class="social-link"> <ion-icon name="logo-twitter"></ion-icon> <span class="span">Twitter</span> </a> </li> <li> <a href="#" class="social-link"> <ion-icon name="logo-linkedin"></ion-icon> <span class="span">LinkedIn</span> </a> </li> <li> <a href="#" class="social-link"> <ion-icon name="logo-instagram"></ion-icon> <span class="span">Instagram</span> </a> </li> </ul> </div> </div> </div> </footer> <!-- - #BACK TO TOP --> <a href="#top" class="back-top-btn" aria-label="back to top" data-back-top-btn> <ion-icon name="arrow-up-outline" aria-hidden="true"></ion-icon> </a> <!-- - custom js link --> <script src="./assets/js/script.js"></script> <!-- - ionicon link --> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> </body> </html>
9d9cfef9efd82e8feeba34298c86a968
{ "intermediate": 0.3728918135166168, "beginner": 0.35405123233795166, "expert": 0.2730569839477539 }
40,420
Can a number of bytes of a read buffer exceed the third value of net.ipv4.tcp_rmem for a single connection on Linux?
db07d6fbab29bd793b0ce93354b02052
{ "intermediate": 0.4524804651737213, "beginner": 0.20616354048252106, "expert": 0.34135594964027405 }
40,421
conversations.txt
5586eb84ae27261ef06e3e563c08bb46
{ "intermediate": 0.3432164192199707, "beginner": 0.23828989267349243, "expert": 0.41849368810653687 }
40,422
привет, на мой сайт идёт DDoS атака. Атакующий использует легитимные юзер-агенты веббраузера Google Chrome и хеадеры этого же браузера. Твоя задача придумать для меня 10 правил для Cloudflare WAF, чтобы отражать подобные атаки. Ниже я могу предоставить тебе пример моего правила: ((any(http.request.headers["sec-ch-ua"][] contains "(Not(A ")) and (not any(http.request.headers["sec-ch-ua-platform"][] contains "Linux"))) or (((lower(http.user_agent) contains "chrome/") and (any(http.request.headers.names[] == "sec-ch-ua-mobile"))) and not any(http.request.headers.names[] == "sec-gpc")) and (not any(http.request.headers["sec-ch-ua"][] contains "Chromium") and not lower(http.user_agent) contains "samsungbrowser" and not lower(http.user_agent) contains "mobile safari/" and not lower(http.user_agent) contains "smart tv") or (not any(http.request.headers.names[] == "accept-encoding") and ssl and http.request.uri.path eq "/auth/login" and http.request.uri.path eq "/" and http.request.uri.path eq "/auth") or ((any(http.request.headers["sec-ch-ua-platform"][] eq "Android")) and (any(http.request.headers["sec-ch-ua-mobile"][] ne "?1") and not ((any(http.request.headers["sec-ch-ua"][] contains "Tenta"))) and (not http.user_agent contains "; Android "))) or (any(http.request.headers.names[] == "x-original-host")) or (any(http.request.headers.names[] == "x-forwarder-for")) or (any(http.request.headers.names[] == "x-remote-addr")) or (any(http.request.headers.names[] == "x-server")) or (any(http.request.headers.names[] == "x-remote-ip")) or (any(http.request.headers.names[] == "x-cluster-ip")) or (any(http.request.headers.names[] == "x-true-client")) or (any(http.request.headers.names[] == "x-originating-ip")) or (any(http.request.headers.names[] == "x-client-ip")) or (any(http.request.headers.names[] == "x-forwarded-https")) or (any(http.request.headers.names[] == "x-forwarded-https")) or (any(http.request.headers.names[] contains "x-ref-fe")) or (any(http.request.headers.names[] contains "X-Req-Ip-")) or (cf.threat_score eq 1 and ip.geoip.country ne "T1") or (cf.threat_score gt 1 and ip.geoip.country ne "T1") or (not http.request.version in {"HTTP/1.1" "HTTP/1.2" "HTTP/2" "HTTP/3"}) or (any(http.request.headers["host"][] contains ":")) or (http.request.uri.path eq "//") or (http.request.uri.path eq "///") or (not http.request.method in {"GET" "POST"}) or (http.x_forwarded_for ne "") or (http.user_agent contains "HuaweiBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent eq "SamsungBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (any(http.request.headers["sec-ch-ua"][] eq "")) or (any(http.request.headers["sec-ch-ua-platform"][] eq "")) or (http.user_agent contains "VenusBrowser" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent contains "Android" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (http.user_agent contains "iPhone" and any(http.request.headers["sec-ch-ua-mobile"][] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][] eq ""Windows"") and any(http.request.headers["sec-ch-ua-mobile"][] eq "?1")) or (http.user_agent contains "MobileExplorer/3.00 (Mozilla/1.22; compatible; MMEF300; Microsoft; Windows; GenericLarge)" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "UP.Browser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "IEMobile" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "MIUI" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "FxiOS" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "OnePlusBrowser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (http.user_agent contains "SogouMobileBrowser" and any(http.request.headers["sec-ch-ua-platform"][] eq "?0")) or (any(http.request.headers["sec-ch-ua-platform"][] eq ""Windows"") and http.user_agent contains "Linux") or (http.user_agent eq "CheckHost (https://check-host.net/)") or (not http.user_agent contains "Mozilla/5.0")
5ddc0fdae5a7c2330a3aec9b0c99f862
{ "intermediate": 0.2364528328180313, "beginner": 0.5747986435890198, "expert": 0.1887485831975937 }
40,423
necesito que en este codigo, me cambies la etiqueta <section> por otra: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Camper Cafe Menu</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="menu"> <header> <h1>CAMPER CAFE</h1> <p class="established">Nop. 2023</p> </header> <hr> <section> <header> <h2>Setas</h2> <img src="taza.png" width="50px" height="50px"> </header> <div class="item"> <p class="flavor">Boletus Vanilla</p><p class="price">3.00</p> </div> <div class="item"> <p class="flavor">Boleuts 2</p><p class="price">3.75</p> </div> <div class="item"> <p class="flavor">Boleuts Spice</p><p class="price">3.50</p> </div> <div class="item"> <p class="flavor">Boleuts 3</p><p class="price">4.00</p> </div> <div class="item"> <p class="flavor">Boleuts x</p><p class="price">4.50</p> </div> </section> <section> <header> <h2>Postres</h2> <img src="tarta.png" width="50px" height="50px"> </header> <div class="item"> <p class="dessert">Donut de Boleuts</p><p class="price">1.50</p> </div> <div class="item"> <p class="dessert">Boleuts Pie</p><p class="price">2.75</p> </div> <div class="item"> <p class="dessert">Boleuts solo</p><p class="price">3.00</p> </div> <div class="item"> <p class="dessert">Boleuts Roll</p><p class="price">2.50</p> </div> </section> <hr class="bottom-line"> <footer> <p> <a href="https://youtu.be/dQw4w9WgXcQ?feature=shared" target="_blank">Visit our website</a> </p> <p class="address">123 La Seta Dos</p> </footer> </div> </body> </html>
5fec3b2ad5b08d00f524983ecf9efc90
{ "intermediate": 0.2659124433994293, "beginner": 0.5340691208839417, "expert": 0.20001845061779022 }
40,424
Hi
62d3af5995644516af6e807acd47b5eb
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
40,425
what is datastream
f8339ea487dbe82fc8f0276e6f86bdf8
{ "intermediate": 0.3119302988052368, "beginner": 0.2423883080482483, "expert": 0.4456814229488373 }
40,426
interface.py: from typing import Optional from .genius_api import GeniusApi from utils.models import ManualEnum, ModuleInformation, ModuleController, ModuleModes, TrackInfo, LyricsInfo, \ SearchResult, DownloadTypeEnum module_information = ModuleInformation( service_name='Genius', module_supported_modes=ModuleModes.lyrics, login_behaviour=ManualEnum.manual ) class ModuleInterface: def __init__(self, module_controller: ModuleController): self.genius = GeniusApi() self.exception = module_controller.module_error def search(self, query_type: DownloadTypeEnum, query: str, track_info: TrackInfo = None): track_id = None if track_info: # search by track name search_results = self.genius.get_search(f'{track_info.artists[0]} {track_info.name}') for result_data in search_results: result = result_data.get('result') # check if the artist and track name match, ignoring the case # TODO: check if that is enough, or if the full track name should be checked if (track_info.name.casefold() in result.get('title').casefold() or track_info.name.casefold() in result.get('title_with_featured').casefold()) \ and track_info.artists[0].casefold() in result.get('artist_names').casefold(): track_id = result.get('id') break if track_id: return [SearchResult(result_id=track_id)] return [] def get_track_lyrics(self, track_id: str) -> Optional[LyricsInfo]: track_data = self.genius.get_song_by_id(track_id) return LyricsInfo( embedded=track_data.get('lyrics').get('plain') if track_data.get('lyrics') else None, synced=None ) genius_api.py: import requests from requests.adapters import HTTPAdapter from urllib3 import Retry class GeniusApi: def __init__(self): self.API_URL = "https://api.genius.com/" self.access_token = 'ZTejoT_ojOEasIkT9WrMBhBQOz6eYKK5QULCMECmOhvwqjRZ6WbpamFe3geHnvp3' # anon Android app token self.s = requests.Session() retries = Retry(total=10, backoff_factor=0.4, status_forcelist=[429, 500, 502, 503, 504]) self.s.mount('http://', HTTPAdapter(max_retries=retries)) self.s.mount('https://', HTTPAdapter(max_retries=retries)) def headers(self, use_access_token=True): return { 'x-genius-app-background-request': '0', 'user-agent': 'okhttp/4.9.1', 'authorization': f'Bearer {self.access_token}' if use_access_token else None, 'x-genius-logged-out': 'true', 'x-genius-android-version': '5.8.0' } def _get(self, url: str, params: dict = None): r = self.s.get(f'{self.API_URL}{url}', params=params, headers=self.headers()) if r.status_code not in [200, 201, 202]: raise ConnectionError(r.text) r = r.json() if r['meta']['status'] != 200: return None return r['response'] def get_search(self, query: str): return self._get('search', {'q': query})['hits'] def get_search_by_songs(self, query: str, page: int = 1): return self._get('search/songs', {'q': query, 'page': page})['sections'][0]['hits'] def get_song_by_id(self, song_id: str, text_format: str = 'plain'): # check if text_format is valid valid = {'plain', 'dom', 'html'} if text_format not in valid: raise ValueError('text_format must be one of %r' % valid) return self._get(f'songs/{song_id}', {'text_format': text_format})['song'] this are references create a module of lyricsnf.py according to this code: to identify the lyrics of the local file using artist name and song name accordingly code:import acrcloud import os import eyed3 import requests import json from acrcloud.recognizer import ACRCloudRecognizer from bs4 import BeautifulSoup # ACRCloud API credentials ACR_HOST = "" ACR_ACCESS_KEY = "" ACR_ACCESS_SECRET = "" # ACR Cloud setup config = { 'host': ACR_HOST, 'access_key': ACR_ACCESS_KEY, 'access_secret': ACR_ACCESS_SECRET, 'timeout': 10 # seconds } dir(acrcloud) # Initialize the ACRCloud recognizer recognizer = ACRCloudRecognizer(config) # Function to recognize the song from an audio file def recognize_song(audio_file_path): buffer = open(audio_file_path, 'rb').read() result = recognizer.recognize_by_filebuffer(buffer, 0) try: result_dict = json.loads(result) # Parse the JSON string into a dictionary return result_dict['metadata']['music'][0] except (KeyError, IndexError, json.JSONDecodeError) as e: print(f"Error while parsing result: {e}") return None # Function to set ID3 tags def set_id3_tags_mp3(audio_file_path, tags): audio_file = eyed3.load(audio_file_path) if not audio_file.tag: audio_file.initTag() audio_file.tag.artist = tags.get('artists')[0].get('name') audio_file.tag.album = tags.get('album').get('name') audio_file.tag.album_artist = tags.get('artists')[0].get('name') audio_file.tag.title = tags.get('title') # Set the release year (if available) release_date = tags.get('release_date') if release_date and len(release_date) >= 4: # Check if release_date contains at least the year year_string = release_date[:4] try: year = int(year_string) # Some versions of eyeD3 require a Date object if available if hasattr(eyed3.id3.tag, 'Date'): audio_file.tag.recording_date = eyed3.id3.tag.Date(year) else: # Otherwise, set it as text_frame audio_file.tag.setTextFrame("TDRC", year_string) except ValueError: print(f"Invalid date format in the tag: {release_date}") # Add more tags here audio_file.tag.genre = tags.get('genres')[0].get('name') # Assuming there's at least one genre audio_file.tag.publisher = "Karthik" # Publisher tag set as 'karthik' # To save the copyright label: audio_file.tag.copyright = tags.get('label', '') # To save the album cover page, you would need to download the image from a source # and then do something like this: # with open("path_to_cover_image.jpg", "rb") as album_art: # audio_file.tag.images.set(3, album_art.read(), "image/jpeg", u"Description") # Example of setting explicit tag in the comments (if you have explicit info): audio_file.tag.comments.set(u"Explicit: Yes") audio_file.tag.save(version=eyed3.id3.ID3_V2_3) audio_file.tag.save() # Replace 'path_to_your_audio_file.mp3' with the actual file path of the unknown song if __name__ == "__main__": audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' song_tags = recognize_song(audio_file_path) if song_tags: print(f'Song identified: {song_tags}') set_id3_tags_mp3(audio_file_path, song_tags) if artist_name and song_title: new_file_name = f"{artist_name} - {song_title}.mp3" new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name) os.rename(audio_file_path, new_file_path) print(f"File has been renamed to: {new_file_name}") else: print('Could not identify the song.')
a5041c41a2aa5516576bbee4c1d512d8
{ "intermediate": 0.44225361943244934, "beginner": 0.4594399929046631, "expert": 0.09830638766288757 }
40,427
%lld vs %ld in sscanf, C?
e4f63b3815369ab27edb0a3ba459a6ce
{ "intermediate": 0.2724143862724304, "beginner": 0.43830522894859314, "expert": 0.2892804443836212 }
40,428
def upsert_predefined_cards(df, table_name, username, password, host, database): try: # 创建数据库连接 engine = sa.create_engine(f"mysql+pymysql://{username}:{password}@{host}/{database}") Session = sessionmaker(bind=engine) session = Session() inspector = sa.inspect(engine) tables_in_database = inspector.get_table_names() if table_name not in tables_in_database: df.to_sql(table_name, engine, if_exists='fail', index=False) else: primary_key_column = 'name' updated_fields = [col for col in df.columns if col not in [primary_key_column, 'id']] pass except Exception as e: # 如果数据库操作出错,将数据存储为本地Excel文件 print("Database operation error: ", str(e)) save_to_local_excel(df) pass 判断 df 的name 字段 是否在数据库里面存在,不存在则全部插入,如果存在则更新 ,更新使用 update_card_attr_query = sa.text(f""" UPDATE cards INNER JOIN cards_skill_links ON cards.id = cards_skill_links.card_id INNER JOIN skills ON skills.id = cards_skill_links.skill_id SET cards.Cost = skills.Cost, cards.Attack = skills.Attack, cards.Health = skills.Health, cards.card_class = skills.card_class, cards.Type = skills.Type, cards.Description = skills.effect_desc """) 来更新
b1ac3ea82e8247486a00bf6ec473d5ae
{ "intermediate": 0.2276718020439148, "beginner": 0.6511389017105103, "expert": 0.12118930369615555 }
40,429
i need question, answer, one line each, for both. for the basics of math remove the Q: and A: and blank lines and expand
8da0afbe02113d51d12ac139f482f377
{ "intermediate": 0.2723413407802582, "beginner": 0.3992862105369568, "expert": 0.3283724784851074 }
40,430
from this code for question generation task # Split the data into train, test, and validation sets train_data, test_data = train_test_split(df[:100000], test_size=0.2, random_state=42) train_data, val_data = train_test_split(train_data, test_size=0.1, random_state=42) ​ # Convert the DataFrames to Hugging Face Datasets train_dataset = Dataset.from_pandas(train_data) val_dataset = Dataset.from_pandas(val_data) test_dataset = Dataset.from_pandas(test_data) add Codeadd Markdown # Tokenizer for sequence-to-sequence models #tokenizer = AutoTokenizer.from_pretrained("t5-small") # Load model directly from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM from transformers import GPT2Tokenizer, GPT2LMHeadModel ​ tokenizer = GPT2Tokenizer.from_pretrained("aubmindlab/aragpt2-base") tokenizer.pad_token = tokenizer.eos_token # Set EOS token as the padding token model = GPT2LMHeadModel.from_pretrained("aubmindlab/aragpt2-base") #tokenizer = AutoTokenizer.from_pretrained("UBC-NLP/AraT5-base")#flax-community/arabic-t5-small") #model = AutoModelForSeq2SeqLM.from_pretrained("UBC-NLP/AraT5-base")#flax-community/arabic-t5-small") add Codeadd Markdown # Load model directly #from transformers import AutoTokenizer, AutoModelForSeq2SeqLM ​ #tokenizer = AutoTokenizer.from_pretrained("MIIB-NLP/Arabic-question-generation") #model = AutoModelForSeq2SeqLM.from_pretrained("MIIB-NLP/Arabic-question-generation") add Codeadd Markdown # # Define a preprocess function for the question generation task def preprocess_function(examples): inputs = tokenizer( examples["positive"], max_length=128, truncation=True, padding="max_length", #return_offsets_mapping=True, ) targets = tokenizer( examples["query"], max_length=64, # Adjust as needed truncation=True, padding="max_length", #return_offsets_mapping=True, ) ​ inputs["labels"] = targets["input_ids"] inputs["decoder_attention_mask"] = targets["attention_mask"] return inputs add Codeadd Markdown # Apply preprocess function to train, val, and test datasets tokenized_train_dataset = train_dataset.map(preprocess_function, batched=True) tokenized_val_dataset = val_dataset.map(preprocess_function, batched=True) tokenized_test_dataset = test_dataset.map(preprocess_function, batched=True) 100% 72/72 [01:20<00:00, 1.01ba/s] 100% 8/8 [00:07<00:00, 1.04ba/s] 100% 20/20 [00:19<00:00, 1.04ba/s] add Codeadd Markdown # Define data collator for sequence-to-sequence models #data_collator = DataCollatorForSeq2Seq(tokenizer)#, model_type="t5" from transformers import DataCollatorForLanguageModeling ​ data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=False # Set mlm to True if you are doing masked language modeling ) ​ add Codeadd Markdown from transformers import GPT2LMHeadModel, GPT2Tokenizer, GPT2Config from transformers import Trainer, TrainingArguments from transformers import EarlyStoppingCallback from torch.nn import CrossEntropyLoss ​ # Assuming you have defined your model, tokenizer, datasets, and data_collator ​ # Define your TrainingArguments training_args = TrainingArguments( output_dir="./question_generation_model_aragpt_8", num_train_epochs=2, per_device_train_batch_size=8, per_device_eval_batch_size=8, save_total_limit=1, # Save only the last checkpoint #learning_rate=5e-5, evaluation_strategy="epoch", # Change evaluation strategy to "steps" report_to=[], # Set report_to to an empty list to disable wandb logging ) ​ # Create the EarlyStoppingCallback # early_stopping = EarlyStoppingCallback(early_stopping_patience=3, early_stopping_threshold=0.005) ​ # Model trainer trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_train_dataset, eval_dataset=tokenized_val_dataset, tokenizer=tokenizer, data_collator=data_collator, # callbacks=[early_stopping], # Add the EarlyStoppingCallback if needed ) ​ add Codeadd Markdown # Training loop without explicit train_step for epoch in range(training_args.num_train_epochs): print(f"Epoch {epoch + 1}/{training_args.num_train_epochs}") for step, inputs in enumerate(trainer.get_train_dataloader()): print( f"Step {step}, Input Shape: {inputs['input_ids'].shape}, Target Shape: {inputs['labels'].shape}" ) # Rest of your training code trainer.train() ​ # Finally, trigger evaluation after the training loop if needed results = trainer.evaluate() Epoch 1/2 Step 0, Input Shape: torch.Size([8, 128]), Target Shape: torch.Size([8, 128]) i get this result [17193/18000 53:54 < 02:31, 5.31 it/s, Epoch 1.91/2] Epoch Training Loss Validation Loss 1 4.295300 3.948071 how to enhance result
46e0afe1791bd332c9e97a7b27a511f3
{ "intermediate": 0.3641935884952545, "beginner": 0.3364681899547577, "expert": 0.29933828115463257 }
40,431
import acrcloud import os import eyed3 import requests import json from acrcloud.recognizer import ACRCloudRecognizer from bs4 import BeautifulSoup # ACRCloud API credentials ACR_HOST = "" ACR_ACCESS_KEY = "" ACR_ACCESS_SECRET = "" # ACR Cloud setup config = { 'host': ACR_HOST, 'access_key': ACR_ACCESS_KEY, 'access_secret': ACR_ACCESS_SECRET, 'timeout': 10 # seconds } dir(acrcloud) # Initialize the ACRCloud recognizer recognizer = ACRCloudRecognizer(config) # Function to recognize the song from an audio file def recognize_song(audio_file_path): buffer = open(audio_file_path, 'rb').read() result = recognizer.recognize_by_filebuffer(buffer, 0) try: result_dict = json.loads(result) # Parse the JSON string into a dictionary return result_dict['metadata']['music'][0] except (KeyError, IndexError, json.JSONDecodeError) as e: print(f"Error while parsing result: {e}") return None # Function to set ID3 tags def set_id3_tags_mp3(audio_file_path, tags): audio_file = eyed3.load(audio_file_path) if not audio_file.tag: audio_file.initTag() audio_file.tag.artist = tags.get('artists')[0].get('name') audio_file.tag.album = tags.get('album').get('name') audio_file.tag.album_artist = tags.get('artists')[0].get('name') audio_file.tag.title = tags.get('title') # Set the release year (if available) release_date = tags.get('release_date') if release_date and len(release_date) >= 4: # Check if release_date contains at least the year year_string = release_date[:4] try: year = int(year_string) # Some versions of eyeD3 require a Date object if available if hasattr(eyed3.id3.tag, 'Date'): audio_file.tag.recording_date = eyed3.id3.tag.Date(year) else: # Otherwise, set it as text_frame audio_file.tag.setTextFrame("TDRC", year_string) except ValueError: print(f"Invalid date format in the tag: {release_date}") # Add more tags here audio_file.tag.genre = tags.get('genres')[0].get('name') # Assuming there's at least one genre audio_file.tag.publisher = "Karthik" # Publisher tag set as 'karthik' # To save the copyright label: audio_file.tag.copyright = tags.get('label', '') # To save the album cover page, you would need to download the image from a source # and then do something like this: # with open("path_to_cover_image.jpg", "rb") as album_art: # audio_file.tag.images.set(3, album_art.read(), "image/jpeg", u"Description") # Example of setting explicit tag in the comments (if you have explicit info): audio_file.tag.comments.set(u"Explicit: Yes") audio_file.tag.save(version=eyed3.id3.ID3_V2_3) audio_file.tag.save() # Replace 'path_to_your_audio_file.mp3' with the actual file path of the unknown song if __name__ == "__main__": audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' song_tags = recognize_song(audio_file_path) if song_tags: print(f'Song identified: {song_tags}') set_id3_tags_mp3(audio_file_path, song_tags) genius_api.py : import requests from requests.adapters import HTTPAdapter from urllib3 import Retry class GeniusApi: def __init__(self): self.API_URL = "https://api.genius.com/" self.access_token = 'ZTejoT_ojOEasIkT9WrMBhBQOz6eYKK5QULCMECmOhvwqjRZ6WbpamFe3geHnvp3' # anon Android app token self.s = requests.Session() retries = Retry(total=10, backoff_factor=0.4, status_forcelist=[429, 500, 502, 503, 504]) self.s.mount('http://', HTTPAdapter(max_retries=retries)) self.s.mount('https://', HTTPAdapter(max_retries=retries)) def headers(self, use_access_token=True): return { 'x-genius-app-background-request': '0', 'user-agent': 'okhttp/4.9.1', 'authorization': f'Bearer {self.access_token}' if use_access_token else None, 'x-genius-logged-out': 'true', 'x-genius-android-version': '5.8.0' } def _get(self, url: str, params: dict = None): r = self.s.get(f'{self.API_URL}{url}', params=params, headers=self.headers()) if r.status_code not in [200, 201, 202]: raise ConnectionError(r.text) r = r.json() if r['meta']['status'] != 200: return None return r['response'] def get_search(self, query: str): return self._get('search', {'q': query})['hits'] def get_search_by_songs(self, query: str, page: int = 1): return self._get('search/songs', {'q': query, 'page': page})['sections'][0]['hits'] def get_song_by_id(self, song_id: str, text_format: str = 'plain'): # check if text_format is valid valid = {'plain', 'dom', 'html'} if text_format not in valid: raise ValueError('text_format must be one of %r' % valid) return self._get(f'songs/{song_id}', {'text_format': text_format})['song'] if artist_name and song_title: new_file_name = f"{artist_name} - {song_title}.mp3" new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name) os.rename(audio_file_path, new_file_path) print(f"File has been renamed to: {new_file_name}") else: print('Could not identify the song.') give me python code to integrate genius and recognise song using acr cloud and get lyrics using artist name, song name
2ec27c0b4d099e1e4eeedbf89af014a6
{ "intermediate": 0.42603716254234314, "beginner": 0.3594376742839813, "expert": 0.21452516317367554 }
40,432
net.ipv4.tcp_rmem is for ipv4, what's ipv6 alternative?
9d33ec0ca4153cab5c7931f4d98b4567
{ "intermediate": 0.3975348174571991, "beginner": 0.31349673867225647, "expert": 0.2889684736728668 }
40,433
How to create GPO which will change Wi-Fi settings on windows 10 machines. It needs to delete old network and add a new one
3d4f8ea9c849909ffaac3ea4152ebcff
{ "intermediate": 0.3072027564048767, "beginner": 0.17428171634674072, "expert": 0.5185155868530273 }
40,434
i need python code to take a file and cut the first 500 lines to another file.
697c9d54b2dffb3c577a3bd35f5bd668
{ "intermediate": 0.38854801654815674, "beginner": 0.2315421998500824, "expert": 0.37990984320640564 }
40,435
I have this js code in react inside Promise. if ( currentAppeal.getState() == null || appealId !==currentAppeal.getState().id ) { reject({ status: 400, statusText: ‘Id обращения неравен Id активного обращения’, }); return; } Currently I have a TypeScript error stating that ‘Object is possibly ‘null’.’ regarding $currentAppeal.getState(). How to fix this problem
62a34f65613bdff524e4c5aa80176d63
{ "intermediate": 0.6020194888114929, "beginner": 0.2886153757572174, "expert": 0.10936512053012848 }
40,436
<input type="text" placeholder="Customer MSISDN" formControlName="msisdn" class="form-control" maxlength="10" (change)="" required /> perform function in (change) if length of input is 10 characters
3cf804573e20dc95fcce620e5226ee4a
{ "intermediate": 0.24478696286678314, "beginner": 0.5781940221786499, "expert": 0.17701900005340576 }
40,437
User How can I make it so checkJS no longer outputs the error "Property doesn't exist on websocket" then?
d4229b139ed21f35f3c03f36e191417f
{ "intermediate": 0.7623320817947388, "beginner": 0.14128702878952026, "expert": 0.09638094902038574 }
40,438
decodeEntityUpdate(buffer) { let tick = buffer.readUint32(); let removedEntityCount = buffer.readVarint32(); const entityUpdateData = {}; entityUpdateData.tick = tick; entityUpdateData.entities = new Map(); let rE = Object.keys(this.removedEntities); for (let i = 0; i < rE.length; i++) { delete this.removedEntities[rE[i]]; } for (let i = 0; i < removedEntityCount; i++) { var uid = buffer.readUint32(); this.removedEntities[uid] = 1; } let brandNewEntityTypeCount = buffer.readVarint32(); for (let i = 0; i < brandNewEntityTypeCount; i++) { var brandNewEntityCountForThisType = buffer.readVarint32(); var brandNewEntityType = buffer.readUint32(); for (var j = 0; j < brandNewEntityCountForThisType; j++) { var brandNewEntityUid = buffer.readUint32(); this.sortedUidsByType[brandNewEntityType].push(brandNewEntityUid); } } let SUBT = Object.keys(this.sortedUidsByType); for (let i = 0; i < SUBT.length; i++) { let table = this.sortedUidsByType[SUBT[i]]; let newEntityTable = []; for (let j = 0; j < table.length; j++) { let uid = table[j]; if (!(uid in this.removedEntities)) { newEntityTable.push(uid); } } newEntityTable.sort((a, b) => a - b); this.sortedUidsByType[SUBT[i]] = newEntityTable; } while (buffer.remaining()) { let entityType = buffer.readUint32(); if (!(entityType in this.attributeMaps)) { throw new Error('Entity type is not in attribute map: ' + entityType); } let absentEntitiesFlagsLength = Math.floor((this.sortedUidsByType[entityType].length + 7) / 8); this.absentEntitiesFlags.length = 0; for (let i = 0; i < absentEntitiesFlagsLength; i++) { this.absentEntitiesFlags.push(buffer.readUint8()); } let attributeMap = this.attributeMaps[entityType]; for (let tableIndex = 0; tableIndex < this.sortedUidsByType[entityType].length; tableIndex++) { let uid = this.sortedUidsByType[entityType][tableIndex]; if ((this.absentEntitiesFlags[Math.floor(tableIndex / 8)] & (1 << (tableIndex % 8))) !== 0) { entityUpdateData.entities.set(uid, true); continue; } var player = { uid: uid }; this.updatedEntityFlags.length = 0; for (let j = 0; j < Math.ceil(attributeMap.length / 8); j++) { this.updatedEntityFlags.push(buffer.readUint8()); } for (let j = 0; j < attributeMap.length; j++) { let attribute = attributeMap[j]; let flagIndex = Math.floor(j / 8); let bitIndex = j % 8; let count = void 0; let v = []; if (this.updatedEntityFlags[flagIndex] & (1 << bitIndex)) { switch (attribute.type) { case e_AttributeType.Uint32: player[attribute.name] = buffer.readUint32(); break; case e_AttributeType.Int32: player[attribute.name] = buffer.readInt32(); break; case e_AttributeType.Float: player[attribute.name] = buffer.readInt32() / 100; break; case e_AttributeType.String: player[attribute.name] = this.safeReadVString(buffer); break; case e_AttributeType.Vector2: let x = buffer.readInt32() / 100; let y = buffer.readInt32() / 100; player[attribute.name] = { x: x, y: y }; break; case e_AttributeType.ArrayVector2: count = buffer.readInt32(); v = []; for (let i = 0; i < count; i++) { let x_1 = buffer.readInt32() / 100; let y_1 = buffer.readInt32() / 100; v.push({ x: x_1, y: y_1 }); } player[attribute.name] = v; break; case e_AttributeType.ArrayUint32: count = buffer.readInt32(); v = []; for (let i = 0; i < count; i++) { let element = buffer.readInt32(); v.push(element); } player[attribute.name] = v; break; case e_AttributeType.Uint16: player[attribute.name] = buffer.readUint16(); break; case e_AttributeType.Uint8: player[attribute.name] = buffer.readUint8(); break; case e_AttributeType.Int16: player[attribute.name] = buffer.readInt16(); break; case e_AttributeType.Int8: player[attribute.name] = buffer.readInt8(); break; case e_AttributeType.Uint64: player[attribute.name] = buffer.readUint32() + buffer.readUint32() * 4294967296; break; case e_AttributeType.Int64: let s64 = buffer.readUint32(); let s642 = buffer.readInt32(); if (s642 < 0) { s64 *= -1; } s64 += s642 * 4294967296; player[attribute.name] = s64; break; case e_AttributeType.Double: let s64d = buffer.readUint32(); let s64d2 = buffer.readInt32(); if (s64d2 < 0) { s64d *= -1; } s64d += s64d2 * 4294967296; s64d = s64d / 100; player[attribute.name] = s64d; break; default: throw new Error('Unsupported attribute type: ' + attribute.type); } } } entityUpdateData.entities.set(player.uid, player); } } entityUpdateData.byteSize = buffer.capacity(); return entityUpdateData; } Improve this code and reduce complexity
b183fa29a3cf46750302771dd4630825
{ "intermediate": 0.39317476749420166, "beginner": 0.3921244740486145, "expert": 0.21470074355602264 }
40,439
import datetime as dt my_date = datetime.date(2019, 12, 31) WARNING: This program has a bug, or error. So let's debug it!
52f10e52da4d0e169d865bfaec9f5781
{ "intermediate": 0.7182458639144897, "beginner": 0.13681481778621674, "expert": 0.1449393779039383 }
40,440
Is real values of proc/sys/net/ipv4/tcp_rmem twice less than specified?
dab310b94ee2dea9719115f613e68b05
{ "intermediate": 0.4004664123058319, "beginner": 0.3078407645225525, "expert": 0.2916928231716156 }
40,441
decodeEntityUpdate(buffer) { let tick = buffer.readUint32(); let removedEntityCount = buffer.readVarint32(); const entityUpdateData = {}; entityUpdateData.tick = tick; entityUpdateData.entities = new Map(); let rE = Object.keys(this.removedEntities); for (let i = 0; i < rE.length; i++) { delete this.removedEntities[rE[i]]; } for (let i = 0; i < removedEntityCount; i++) { var uid = buffer.readUint32(); this.removedEntities[uid] = 1; } let brandNewEntityTypeCount = buffer.readVarint32(); for (let i = 0; i < brandNewEntityTypeCount; i++) { var brandNewEntityCountForThisType = buffer.readVarint32(); var brandNewEntityType = buffer.readUint32(); for (var j = 0; j < brandNewEntityCountForThisType; j++) { var brandNewEntityUid = buffer.readUint32(); this.sortedUidsByType[brandNewEntityType].push(brandNewEntityUid); } } let SUBT = Object.keys(this.sortedUidsByType); for (let i = 0; i < SUBT.length; i++) { let table = this.sortedUidsByType[SUBT[i]]; let newEntityTable = []; for (let j = 0; j < table.length; j++) { let uid = table[j]; if (!(uid in this.removedEntities)) { newEntityTable.push(uid); } } newEntityTable.sort((a, b) => a - b); this.sortedUidsByType[SUBT[i]] = newEntityTable; } while (buffer.remaining()) { let entityType = buffer.readUint32(); if (!(entityType in this.attributeMaps)) { throw new Error('Entity type is not in attribute map: ' + entityType); } let absentEntitiesFlagsLength = Math.floor((this.sortedUidsByType[entityType].length + 7) / 8); this.absentEntitiesFlags.length = 0; for (let i = 0; i < absentEntitiesFlagsLength; i++) { this.absentEntitiesFlags.push(buffer.readUint8()); } let attributeMap = this.attributeMaps[entityType]; for (let tableIndex = 0; tableIndex < this.sortedUidsByType[entityType].length; tableIndex++) { let uid = this.sortedUidsByType[entityType][tableIndex]; if ((this.absentEntitiesFlags[Math.floor(tableIndex / 8)] & (1 << (tableIndex % 8))) !== 0) { entityUpdateData.entities.set(uid, true); continue; } var player = { uid: uid }; this.updatedEntityFlags.length = 0; for (let j = 0; j < Math.ceil(attributeMap.length / 8); j++) { this.updatedEntityFlags.push(buffer.readUint8()); } for (let j = 0; j < attributeMap.length; j++) { let attribute = attributeMap[j]; let flagIndex = Math.floor(j / 8); let bitIndex = j % 8; let count = void 0; let v = []; if (this.updatedEntityFlags[flagIndex] & (1 << bitIndex)) { switch (attribute.type) { case e_AttributeType.Uint32: player[attribute.name] = buffer.readUint32(); break; case e_AttributeType.Int32: player[attribute.name] = buffer.readInt32(); break; case e_AttributeType.Float: player[attribute.name] = buffer.readInt32() / 100; break; case e_AttributeType.String: player[attribute.name] = this.safeReadVString(buffer); break; case e_AttributeType.Vector2: let x = buffer.readInt32() / 100; let y = buffer.readInt32() / 100; player[attribute.name] = { x: x, y: y }; break; case e_AttributeType.ArrayVector2: count = buffer.readInt32(); v = []; for (let i = 0; i < count; i++) { let x_1 = buffer.readInt32() / 100; let y_1 = buffer.readInt32() / 100; v.push({ x: x_1, y: y_1 }); } player[attribute.name] = v; break; case e_AttributeType.ArrayUint32: count = buffer.readInt32(); v = []; for (let i = 0; i < count; i++) { let element = buffer.readInt32(); v.push(element); } player[attribute.name] = v; break; case e_AttributeType.Uint16: player[attribute.name] = buffer.readUint16(); break; case e_AttributeType.Uint8: player[attribute.name] = buffer.readUint8(); break; case e_AttributeType.Int16: player[attribute.name] = buffer.readInt16(); break; case e_AttributeType.Int8: player[attribute.name] = buffer.readInt8(); break; case e_AttributeType.Uint64: player[attribute.name] = buffer.readUint32() + buffer.readUint32() * 4294967296; break; case e_AttributeType.Int64: let s64 = buffer.readUint32(); let s642 = buffer.readInt32(); if (s642 < 0) { s64 *= -1; } s64 += s642 * 4294967296; player[attribute.name] = s64; break; case e_AttributeType.Double: let s64d = buffer.readUint32(); let s64d2 = buffer.readInt32(); if (s64d2 < 0) { s64d *= -1; } s64d += s64d2 * 4294967296; s64d = s64d / 100; player[attribute.name] = s64d; break; default: throw new Error('Unsupported attribute type: ' + attribute.type); } } } entityUpdateData.entities.set(player.uid, player); } } entityUpdateData.byteSize = buffer.capacity(); return entityUpdateData; } Improve this code and reduce complexity
7683ef7cb79df93912ed0a994b024eae
{ "intermediate": 0.39317476749420166, "beginner": 0.3921244740486145, "expert": 0.21470074355602264 }
40,442
Discuss the role of Bayes risk in inferences procedures
b23f2ba3d9aba8ea0bbde56c1036c7aa
{ "intermediate": 0.20523443818092346, "beginner": 0.162001833319664, "expert": 0.6327637434005737 }
40,443
в чем проблема? "C:\Program Files\Java\jdk-11.0.17\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 241.13688.18\lib\idea_rt.jar=56534:C:\Program Files\JetBrains\IntelliJ IDEA 241.13688.18\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\Владимир\IdeaProjects\untitled\target\classes org.example.Main 1316247.1478228716 Process finished with exit code 0
340fa75c7aaba34b77de60995dfb6108
{ "intermediate": 0.39992696046829224, "beginner": 0.23727813363075256, "expert": 0.3627949059009552 }
40,444
Make an 100x100 size in processing 4, fill it with squares with size 10, in a grid of 10x10. then make it so if your mouse hovers over 1 square it will highlight THAT specific square
2cc669fba903cf7fb17df2b83959820f
{ "intermediate": 0.31062060594558716, "beginner": 0.19727882742881775, "expert": 0.4921005070209503 }
40,445
User this.rpcMaps.push(rpc); this.rpcMapsByName[rpcName] = rpc; console.log(this.rpcMaps) I want rpcMaps to be turned into a nicely styled txt file that shows all of the rpcs in rpcMaps and displaying all its properties Here's how something from rpcMaps looks JoinParty : index : 22 isArray : false name : "JoinParty" parameters is an object and hsould be formatted like this parameters: [ name: "Name" :: type: Number
bfa058e809ed3ae5e45ec72fc39a5dd8
{ "intermediate": 0.45713725686073303, "beginner": 0.2575397491455078, "expert": 0.28532299399375916 }
40,446
I want my domain to redirect to youtube.com/hi. How do I do this on the domain settings admin panel
13a6cdfb033e62cf0205b3006c4da577
{ "intermediate": 0.3298638164997101, "beginner": 0.30164337158203125, "expert": 0.36849284172058105 }
40,447
VL_Chat
03b5169457f979cbef47e96b716de764
{ "intermediate": 0.35287559032440186, "beginner": 0.2662270963191986, "expert": 0.3808973431587219 }
40,448
Convert this into text: x\longleftarrow0 for\:i\:\longleftarrow\:2\sqrt{n}\:to\:2n\frac{}{} for\:j\:\longleftarrow\:1\:to\:n^2 for\:k\:\longleftarrow\:2\:to\:3\lfloor\log_2i^2\rfloor \:\:\:\:\:\:\:x\:\longleftarrow\:x-i-j end end end return(x)
b4b2b9c30ecefabc3f02c1e4420515ca
{ "intermediate": 0.3379279673099518, "beginner": 0.3676786422729492, "expert": 0.2943933606147766 }
40,449
data start end_x word end_y speaker 0 0.00 1.18 Good 4.219015 SPEAKER_01 1 1.18 1.58 afternoon, 4.219015 SPEAKER_01 2 1.60 1.96 welcome 4.219015 SPEAKER_01 3 1.96 2.20 to 4.219015 SPEAKER_01 4 2.20 2.52 Samsung. 4.219015 SPEAKER_01 5 2.78 2.78 My 4.219015 SPEAKER_01 6 2.78 2.90 name 4.219015 SPEAKER_01 7 2.90 3.12 is 4.219015 SPEAKER_01 8 3.12 3.50 Navneet, 4.219015 SPEAKER_01 9 3.56 3.64 how 4.219015 SPEAKER_01 10 3.64 3.80 may 4.219015 SPEAKER_01 11 3.80 3.80 I 4.219015 SPEAKER_01 12 3.80 4.08 help 4.219015 SPEAKER_01 13 4.08 4.76 you? 4.219015 SPEAKER_01 14 5.22 5.42 Well, 7.512733 SPEAKER_00 15 5.42 5.62 this 7.512733 SPEAKER_00 16 5.62 5.84 is 7.512733 SPEAKER_00 17 5.84 6.26 concerning 7.512733 SPEAKER_00 18 6.26 6.72 my 7.512733 SPEAKER_00 19 6.72 7.36 refrigerator. 7.512733 SPEAKER_00 20 7.90 8.38 Yes. 8.174873 SPEAKER_01 21 9.40 9.60 So, 11.230900 SPEAKER_00 22 9.62 9.78 I 11.230900 SPEAKER_00 23 9.78 10.00 want 11.230900 SPEAKER_00 24 10.00 10.14 to 11.230900 SPEAKER_00 25 10.14 10.26 put 11.230900 SPEAKER_00 26 10.26 10.44 a 11.230900 SPEAKER_00 27 10.44 10.76 complaint 11.230900 SPEAKER_00 I want to write a code such that, first, we look into the speaker column and see if the speaker is same then join the word column till next speaker appears also, set the start values as the first start of this group and end as last end_y of this group. Then continue with the next Speaker value and do the same. If the penultimate speaker appears again then repeat the process without grouping it with the previous speaker. Look the below output example for the provided data - Start End Speaker Text 0.00 4.29015 SPEAKER_01 Good afternoon, welcome to Samsung. My name is Navneet, how may I help you? 5.22 7.512733 SPEAKER_00 Well, this is concerning my refrigerator 7.90 8.174873 SPEAKER_01 Yes. 9.40 11.230900 SPEAKER_00 So, I want to put a complaint
b9b861be5b7a7a21523bc4521a5baa7e
{ "intermediate": 0.2968519926071167, "beginner": 0.3594413697719574, "expert": 0.3437066674232483 }
40,450
import json import os import requests from acrcloud.recognizer import ACRCloudRecognizer from genius_api import GeniusApi # Assume genius_api.py is in the same directory and contains the GeniusApi class # ACRCloud API credentials ACR_HOST = "" ACR_ACCESS_KEY = "" ACR_ACCESS_SECRET = "" # ACR Cloud configuration (update with your credentials) config = { 'host': ACR_HOST, 'access_key': ACR_ACCESS_KEY, 'access_secret': ACR_ACCESS_SECRET, 'timeout': 10 # seconds } # Initialize the ACRCloud recognizer recognizer = ACRCloudRecognizer(config) # Initialize the Genius API genius_api = GeniusApi() # Function to recognize a song using ACRCloud def recognize_song(audio_file_path): buffer = open(audio_file_path, 'rb').read() result = recognizer.recognize_by_filebuffer(buffer, 0) try: result_dict = json.loads(result) return result_dict['metadata']['music'][0] except (KeyError, IndexError, json.JSONDecodeError) as e: print(f"Error while parsing result: {e}") return None # Function to fetch lyrics from Genius def get_lyrics_from_genius(artist_name, song_title): # Search for the song on Genius results = genius_api.get_search_by_songs(f"{artist_name} {song_title}") if results: song_info = results[0]['result'] # Take the most relevant result song_id = str(song_info['id']) song_details = genius_api.get_song_by_id(song_id, text_format='plain') return song_details.get('lyrics', "Lyrics not available.") return "Song not found on Genius." def save_lyrics_to_lrc(lyrics, lrc_path): with open(lrc_path, 'w', encoding='utf-8') as lrc_file: lrc_file.write(lyrics) # Main program to recognize a song and fetch its lyrics if __name__ == "__main__": audio_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.mp3' # Replace with the actual file path lrc_file_path = 'C:/Users/ILEG-i5-11/Downloads/Music/Unknown_file.lrc' # Output LRC file path song_tags = recognize_song(audio_file_path) if song_tags: artist_name = song_tags['artists'][0]['name'] song_title = song_tags['title'] print(f"Identified Song: {artist_name} - {song_title}") lyrics = get_lyrics_from_genius(artist_name, song_title) if 'plain' in lyrics: lyrics_plain_text = lyrics['plain'] print("Lyrics:\n", lyrics_plain_text) save_lyrics_to_lrc(lyrics_plain_text, lrc_file_path) print(f"Lyrics saved to: {lrc_file_path}") else: print("No lyrics available to save.") else: print("Could not identify the song.") this code is only giving me only lrc lyrics . I need lrc with timestamps to be played with the audio file
d42ebbfc7df8a0012bb65198951ddf28
{ "intermediate": 0.36122721433639526, "beginner": 0.556525468826294, "expert": 0.0822472870349884 }
40,451
Write summations to represent the running time of the following algorithm. Find the upper bound, showing your work. The log must be simplified. x ← 0 for i ← 2√n to 2n do for j ← 1 to n^2 do for k ← 2 to 3⌊log_2(i^2)⌋ do x ← x - i - j end for end for end for return(x) DO not write many steps. Keep work minimal
235cd4dfc56c2f00e7c83e90bc06f410
{ "intermediate": 0.21485169231891632, "beginner": 0.13696911931037903, "expert": 0.6481791734695435 }
40,452
A logo for the syndicate of a company called GAPCO. The company's field is petroleum exploration and extraction
4f97ed412506bf07203a1ff2ca999489
{ "intermediate": 0.38057491183280945, "beginner": 0.23134677112102509, "expert": 0.3880783021450043 }
40,453
I'm trying to customize a linux distribution. And there is this file: #!/bin/sh # # Desktop session init script. # Author: T.Jokiel <http://porteus-kiosk.org> # Setup variables: . /etc/profile.d/variables.sh PTH=/usr/share/icons/oxygen/22x22 [ -x /opt/google/chrome/chrome ] && chrome=yes wget="wget --no-http-keep-alive --no-cache --no-check-certificate" # Check if correct kernel version is used: [ `lsmod | wc -l` -lt 3 ] && { dunstify -u critical -i /usr/share/icons/oxygen/48x48/status/dialog-warning.png "Kernel version: `uname -r` does not match the modules version: `ls /lib/modules/ | tr '\n' ' '`\nPerhaps the system was booted from usb stick while older kiosk installation exist on the hard drive.\nTo force booting from removable device please install the system with following parameter added to kiosk config: 'kernel_parameters=boot_from_usb'."; sleep 60; init 0; } # Load snd-usb-audio so USB audio devices are always on the last sound card slot: modprobe snd-usb-audio # Start battery polling: battery=`ls -1 /sys/class/power_supply/*/capacity 2>/dev/null | head -n1 | cut -d/ -f5` [ "$battery" ] && sh /opt/scripts/battery_polling $battery & # Disable input devices or configure them: #disable_input=yes if [ "$disable_input" ]; then xinput | egrep -v 'Virtual core| Button' | cut -d= -f2 | cut -d[ -f1 | while read line; do xinput --disable $line 2>/dev/null; done else # Set keyboard mapping: setxkbmap -layout us,lay2 -variant ,var2 2>/dev/null # Enable numlock: xdotool key Num_Lock # Autohide mouse pointer after X seconds of inactivity: ( sleep 5; #hhpc -i 5 & ) & # Disable right mouse click: xmodmap -e "pointer = 1 2 32 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 3" # Disable middle and right mouse clicks: #xmodmap -e "pointer = 1 31 32 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 2 3" # Set custom mouse speed: #xset m 20/10 # Calibrate touchscreen: #. /opt/scripts/calibrate.sh # Force touch gestures for Chrome: #[ "$chrome" ] && id=`xinput_calibrator --list | cut -s -d= -f2-`; [ "$id" ] && { for x in $id; do tdev="$x,$tdev"; done; tdev=`echo $tdev | sed 's/,$//'`; grep -q touch-devices $chflags || echo -e "--touch-devices=$tdev\n--enable-pinch" >> $chflags; } fi # Screen setup: #parse=yes if [ "$parse" ]; then /opt/scripts/screen-setup-parse "$parse" else # Rotate screen: #for display in `xrandr | grep -w connected | cut -d" " -f1`; do xrandr --output $display --rotate normal; done # Rotate touch input: #rtouch=yes [ "$rtouch" ] && ( sleep 4; /opt/scripts/rotate-touch $rtouch; ) & # Set custom screen resolution/refresh rate: #/opt/scripts/set-resolution-rate cres crate # Set brightness: for x in `ls -1 /sys/class/backlight`; do echo $((`cat /sys/class/backlight/$x/max_brightness`*100/100)) > /sys/class/backlight/$x/brightness; done # Scale screens: /opt/scripts/scale-screen fi # Set wallpaper according to current screen size: hsetroot -fill /usr/share/wallpapers/default.jpg # Enable real transparency: #xcompmgr & # Disable DPMS Xorg features and builtin screen-saver: xset -dpms; xset s 0 # Freeze/standby/suspend/shutdown system in case when no activity is detected: #FREEZEIDLE=300 #STANDBYIDLE=300 #SUSPENDIDLE=300 #SHUTDOWNIDLE=300 if [ "$FREEZEIDLE" ]; then /opt/scripts/freeze-idle-watcher & elif [ "$STANDBYIDLE" ]; then /opt/scripts/standby-idle-watcher & elif [ "$SUSPENDIDLE" ]; then /opt/scripts/suspend-idle-watcher & elif [ "$SHUTDOWNIDLE" ]; then /opt/scripts/shutdown-idle-watcher & fi # Restrict access for guest to sensitive directories/files: chmod 700 /etc/rc.d /etc/X11 /etc/xdg /lib/modules /opt/scripts /root 2>/dev/null chmod 600 /etc/inittab /etc/shadow /etc/wpa_supplicant.conf /etc/ssh/sshd_config 2>/dev/null chmod 640 /var/log/Xorg.0.log* # Set sound level: /etc/rc.d/rc.sound & # We are in the GUI - this is good, lets keep the PC running infinitely. Network issues can be resolved by 'run_command=': [ -e /dev/watchdog ] && /usr/sbin/wd_keepalive # Launch first-run wizard: [ -e /opt/scripts/first-run ] && su -c /opt/scripts/first-run # Wait on network connection before proceeding (skip gateway check for dialup connections): GTW=`route -n | grep -c " UG "`; [ `route -n | grep -c -w ppp0` = 1 ] && GTW=1 if [ $GTW -lt 1 ]; then SLEEP=120 while [ $GTW -lt 1 -a $SLEEP -gt 0 ]; do [ $SLEEP = 60 ] && sh /etc/rc.d/rc.inet1; sleep 1; let SLEEP=SLEEP-1; GTW=`route -n | grep -c " UG "`; done fi [ "$GTW" -lt 1 ] && dunstify -u normal -i $PTH/status/dialog-warning.png "Gateway is not set - network may be not available." # Pull time from NTP server and set hardware clock to system time: ( while true; do ntpdate pool.ntp.org && hwclock --utc -w; sleep 24h; done; ) & # Setup proxy auto configuration: #proxypac= if [ "$proxypac" ]; then pkget $proxypac /opt/scripts/proxy.pac # Default to first IP in case multiple proxies are returned: proxy=`pactester -p /opt/scripts/proxy.pac -u http://porteus-kiosk.org 2>/dev/null | tr -s ' ' | cut -d" " -f2 | sed 's/[^0-9a-zA-Z.:]*//g'` [ -n "$proxy" -a "$proxy" != DIRECT ] && sed -i 's_^proxy=DIRECT_proxy='$proxy'_g' /etc/profile.d/proxy.sh . /etc/profile.d/proxy.sh fi # Perform kiosk auto reconfiguration: [ -e /opt/scripts/update-config ] && su -c /opt/scripts/update-config # Perform kiosk auto update (paid subscription is required): [ -e /opt/scripts/update ] && su -c /opt/scripts/update # Start SSH daemon: #ssh=yes [ "$ssh" ] && /etc/rc.d/rc.sshd & # Start VNC daemon: #vnc=yes [ "$vnc" ] && { killall -9 x11vnc; /etc/rc.d/rc.vncd & } # Start tunnelling daemon providing direct access to kiosk from Porteus Kiosk Server: #tunnel=yes [ "$tunnel" ] && /usr/sbin/pktunnel & # Run local commands which depends on the network availability: for script in `ls -1 /etc/rc.d/local_net.d`; do . /etc/rc.d/local_net.d/$script; done # Initialize printing: #model=yes if [ "$model" ]; then if [ -z "`pidof cupsd`" ]; then ( cupsd #share_printer=yes [ "$share_printer" ] && cupsctl --share-printers sleep 3 if echo "$model" | grep -q 'Raw Queue'; then # Keep space after URI: lpadmin -p kiosk-printer -E -v URI elif echo "$model" | grep -q ' Foomatic/'; then /usr/libexec/cups/driver/foomatic cat `grep "$model" /opt/scripts/files/wizard/printers.d/foomatic | cut -d'"' -f1 | head -n1` > /usr/share/ppd/kiosk.ppd lpadmin -p kiosk-printer -E -v URI -m lsb/usr/kiosk.ppd else lpadmin -p kiosk-printer -E -v URI -m `lpinfo --make-and-model "$model" -m | cut -d" " -f1 | head -n1` fi # Set kiosk-printer as default (needed for Chrome): lpoptions -d kiosk-printer # Default paper size: #paper_size=default [ "$paper_size" ] && sed -e 's|^*DefaultPageSize:.*|*DefaultPageSize: '"$paper_size"'|' -e 's|^*DefaultPageRegion:.*|*DefaultPageRegion: '"$paper_size"'|' -e 's|^*DefaultImageableArea:.*|*DefaultImageableArea: '"$paper_size"'|' -e 's|^*DefaultPaperDimension:.*|*DefaultPaperDimension: '"$paper_size"'|' -i /etc/cups/ppd/*.ppd ) & fi fi # Scheduled actions: [ -x /opt/scripts/scheduled-action ] && /opt/scripts/scheduled-action & # RTC wake: [ -x /opt/scripts/rtc-wake ] && /opt/scripts/rtc-wake & # Enable Wake-On-LAN: #ethtool -s `route -n | grep " UG " | head -n1 | rev | cut -d" " -f1 | rev` wol g # Power saving tweaks: if ! egrep -q -v '^Filename|^/dev/zram' /proc/swaps; then /opt/scripts/power_saver fi # Append MAC/hostname/PCID to the homepage: #homepage_append=yes if [ "$homepage_append" ]; then if [ "$homepage_append" = mac ]; then # Make sure the gateway is set so MAC address of the NIC used for network connection can be determined: GTW=`route -n | grep -c " UG "`; [ `route -n | grep -c -w ppp0` = 1 ] && GTW=1 while [ $GTW -lt 1 ]; do sleep 1; GTW=`route -n | grep -c " UG "`; done MAC="$(cat /sys/class/net/`route -n | grep " UG " | head -n1 | rev | cut -d" " -f1 | rev`/address | sed s/://g | tr [a-z] [A-Z])" [ "$chrome" ] && { sed -i 's/?kiosk=mac/?kiosk='$MAC'/g' $json; sed -i 's/\&kiosk=mac/\&kiosk='$MAC'/g' $json; } || { sed -i 's/?kiosk=mac/?kiosk='$MAC'/g' $profile/prefs.js; sed -i 's/\&kiosk=mac/\&kiosk='$MAC'/g' $profile/prefs.js; } elif [ "$homepage_append" = hostname ]; then [ "$chrome" ] && { sed -i 's/?kiosk=hostname/?kiosk='`hostname`'/g' $json; sed -i 's/\&kiosk=hostname/\&kiosk='`hostname`'/g' $json; } || { sed -i 's/?kiosk=hostname/?kiosk='`hostname`'/g' $profile/prefs.js; sed -i 's/\&kiosk=hostname/\&kiosk='`hostname`'/g' $profile/prefs.js; } elif [ "$homepage_append" = pcid ]; then [ "$chrome" ] && { sed -i 's/?kiosk=pcid/?kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $json; sed -i 's/\&kiosk=pcid/\&kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $json; } || { sed -i 's/?kiosk=pcid/?kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $profile/prefs.js; sed -i 's/\&kiosk=pcid/\&kiosk='`grep ^ID: /etc/version | cut -d' ' -f2`'/g' $profile/prefs.js; } fi fi # Homepage availability check: #hcheck=yes if [ "$hcheck" ]; then restart_net() { dunstify -u normal -i $PTH/status/dialog-warning.png "Restarting network service ..." killall dhcpcd wpa_supplicant 2>/dev/null for nic in `ls -1 /sys/class/net | grep -v ^lo`; do ifconfig $nic down; done killall dhcpcd wpa_supplicant 2>/dev/null sleep 3 for nic in `ls -1 /sys/class/net | grep -v ^lo`; do ifconfig $nic up; done /etc/rc.d/rc.inet1; sleep 15 } [ "$chrome" ] && hpage="`grep HomepageLocation $json | cut -d'"' -f4`" || hpage="`grep '"browser.startup.homepage"' $profile/prefs.js | cut -d'"' -f4 | cut -d'|' -f1`" CNUM=0 while true; do test -e $hpage && break; dunstify -C 100 2>/dev/null if $wget -q -U Mozilla --spider -T20 -t1 "$hpage"; then break else let CNUM=CNUM+1; dunstify -r 100 -u critical -i $PTH/status/dialog-warning.png "$hcheck" [ "$CNUM" = 60 ] && { restart_net; CNUM=0; } sleep 9 fi done fi # Managed bookmarks: #bookmarks=yes [ "$bookmarks" ] && /opt/scripts/managed-bookmarks # Import certificates: #icert=yes if [ "$icert" ]; then /opt/scripts/import-certificates $icert fi # Screensaver slideshow: #slideshow=yes [ "$slideshow" ] && /opt/scripts/screensaver-slideshow "$slideshow" # Browser preferences: #brpref=yes if [ "$brpref" ]; then # Setup proxy: if [ -e /opt/scripts/proxy.pac ]; then proxyc=`pactester -p /opt/scripts/proxy.pac -u $brpref | cut -d" " -f2-` [ "$proxyc" = DIRECT ] && unset http_proxy https_proxy ftp_proxy || export http_proxy="http://$proxyc" https_proxy="http://$proxyc" ftp_proxy="http://$proxyc" fi pkget $brpref /tmp/pref # Allow alphanumeric characters only: fromdos /tmp/pref 2>/dev/null; fromdos /tmp/pref 2>/dev/null; fromdos /tmp/pref 2>/dev/null; tr -dc "[:alnum:][:space:][:punct:]" < /tmp/pref > /tmp/prefs # Update browser preferences: if [ "$chrome" ]; then # Do not double preferences if session is restarted: test -e /opt/scripts/files/chrome.json && cp -a /opt/scripts/files/chrome.json $json || cp -a $json /opt/scripts/files tac $json 2>/dev/null | sed -n '/"/,$p' | tac > /tmp/json cat /tmp/prefs >> /tmp/json echo '}' >> /tmp/json mv -f /tmp/json $json else # Do not double preferences if session is restarted: test -e /opt/scripts/files/user.js && { cp -a /opt/scripts/files/user.js $profile; cp -a /opt/scripts/files/user.js $pprofile; } || cp -a $profile/user.js /opt/scripts/files 2>/dev/null cat /tmp/prefs >> $profile/user.js; cat /tmp/prefs >> $pprofile/user.js 2>/dev/null fi rm -f /tmp/pref /tmp/prefs fi # Enable support for removable devices: #removable=yes [ "$removable" ] && mv /sbin/udev-automount-disabled /sbin/udev-automount # Toggle browser tabs: #ttabs=yes if [ "$ttabs" ]; then ( sleep 20 # Wait till the browser is fully started toglec=$((`echo "$ttabs" | tr -dc '|' | wc -c`+2)) toggle() { sleep `echo "$ttabs" | cut -d"=" -f2- | cut -d'|' -f $1`; xdotool key Ctrl+Tab; } while true; do RETRY=1 while [ $RETRY -lt $toglec ]; do toggle $RETRY; let RETRY=RETRY+1; done done ) & fi # Refresh webpage: #rpage=5 [ "$rpage" ] && ( while true; do sleep $rpage; xdotool key F5; done; ) & # Delete unneeded utilities and logs: rm -rf /tmp/log # Preserve home directory: cp -a /home/guest /opt/scripts # Enable screensaver in case when no activity is detected: #SSIDLE=300 [ "$SSIDLE" ] && /opt/scripts/screensaver-idle-watcher & # Restart browser/session in case when no activity is detected: #SIDLE=300 [ "$SIDLE" ] && /opt/scripts/session-idle-watcher & # Booting is finished - start application: /opt/scripts/gui-app & It is mentioned inside variables.sh as autostart that looks like this: export \ autostart=/etc/xdg/openbox/autostart \ scripts=/opt/scripts \ profile=/home/guest/.mozilla/firefox/c3pp43bg.default \ pprofile=/opt/scripts/guest/.mozilla/firefox/c3pp43bg.default \ json=/etc/opt/chrome/policies/managed/chrome.json \ chflags=/opt/google/chrome/chrome-flags.conf \ DISPLAY=:0 Currently when I boot up, it opens Google Chrome fullscreen with Skype Online. I want to change it to open skypeforlinux instead of chrome. It (not in this version I've pasted, but in my other try) does so, but when I start a call in Skype, it freezes. I think it's pretty similar as it was allowing only one activity, and forces it to the foreground. But I'd only need to open the Skype app, then make if fullscreen, and allow anything
dd4f6b89d5cbae1c0aa5a41c4fae6b97
{ "intermediate": 0.2682703733444214, "beginner": 0.42556411027908325, "expert": 0.30616551637649536 }
40,454
I am making a fetch request that returns json data of the form {"id": 69, "name": "John Smith", "amount": 69.420}. In typescript, this will initially be of type any. How do I write a function that validates the data is in the correct form and have type safety?
52bd253c22ec2cb32f79ba916880d063
{ "intermediate": 0.5534699559211731, "beginner": 0.26866626739501953, "expert": 0.17786377668380737 }
40,455
#!/bin/sh # # Start kiosk application in a loop. # Author: T.Jokiel <http://porteus-kiosk.org> # Disable backup of the /home folder (just in case the session is restarted): sed -i 's_^cp -a /home/guest_#cp -a /home/guest_g' /etc/xdg/openbox/autostart # Start application in a loop: while true; do rm -rf /home/guest /tmp/*; cp -a /opt/scripts/guest /home; sync # Session manager: #/opt/scripts/session-manager # Bottom panel: #/opt/scripts/start-panel su - guest -c "firefox" sync done
ebb45099ce0e9dd8cad9fa36702d23b2
{ "intermediate": 0.21887081861495972, "beginner": 0.6475441455841064, "expert": 0.13358503580093384 }
40,456
network.cookie.staleThreshold
f2ba6125ce72a8e85c91aa288199a291
{ "intermediate": 0.3021293580532074, "beginner": 0.2838367819786072, "expert": 0.4140339195728302 }