row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
17,682
почему этот код зависает #include <arpa/inet.h> #include <fcntl.h> #include <netinet/in.h> /* sockaddr_in{} and other Internet defns */ #include <strings.h> #include <unistd.h> #include <array> #include <cstdarg> #include <cstdio> #include <cstdlib> constexpr auto MAXLINE = 4096; /* max text line length */ void err_quit(const char* fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); exit(EXIT_FAILURE); } void err_sys(const char* x) { perror(x); exit(1); } int main(int argc, char** argv) { int sockfd{}; int n{}; char recvline[MAXLINE + 1]; struct sockaddr_in servaddr { }; if (argc != 2) err_quit("usage: test.out <IPaddress>"); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) err_sys("socket error"); bzero(&servaddr, sizeof servaddr); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(80); if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) err_quit("inet_pton error for %s", argv[1]); if (connect(sockfd, reinterpret_cast<sockaddr*>(&servaddr), sizeof servaddr) < 0) err_sys("connect error"); while ((n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = '\0'; if (fputs(recvline, stdout) == EOF) err_sys("fputs error"); } if (n < 0) err_sys("read error"); exit(0); }
d1404a47335580d205ccb6d54a1aa093
{ "intermediate": 0.2851329445838928, "beginner": 0.5417818427085876, "expert": 0.17308521270751953 }
17,683
fine tuning python code to make processing faster, shall we give the code so you can parse and give us fine tuning
6cf84e53f0808f1e3465f74d4314e639
{ "intermediate": 0.3429892361164093, "beginner": 0.18734169006347656, "expert": 0.46966904401779175 }
17,684
package main import ( "fmt" "strings" "github.com/gliderlabs/ssh" "golang.org/x/crypto/ssh/terminal" "os" ) var users = map[string]string{ "alice": "password1", "bob": "password2", "charlie": "password3", } func main() { ssh.Handle(handleSSH) err := ssh.ListenAndServe(":2222", nil) if err != nil { fmt.Println("Error starting SSH server:", err) } } func handleSSH(s ssh.Session) { fmt.Fprint(s, "Welcome to cartel!\n\n") if !login(s) { fmt.Fprint(s, "Login failed. Goodbye!\n") return } username := s.User() fmt.Fprintf(s, "Welcome, %s!\n\n", username) cmdChan := make(chan string) go readInput(cmdChan) for { fmt.Fprintf(s, "[%s@cartel]~$ ", username) select { case cmd := <-cmdChan: cmd = strings.TrimSpace(cmd) switch cmd { case "help": showHelp(s) case "whoami": showUsername(s, username) case "clear": clearScreen(s) case "exit": return default: fmt.Fprintf(s, "Command not found. Type ‘help’ for available commands.\n") } case <-s.Context().Done(): return } } } func login(s ssh.Session) bool { fmt.Fprint(s, "Please enter your username: ") var username string fmt.Fscan(s, &username) fmt.Fprintln(s) fmt.Fprint(s, "Please enter your password: ") password, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return false } fmt.Fprintln(s) storedPassword, found := users[strings.TrimSpace(username)] if found && storedPassword == string(password) { return true } return false } func readInput(cmdChan chan<- string) { var line string for { fmt.Scanln(&line) cmdChan <- line } } func showHelp(s ssh.Session) { helpText := `Available commands: help - I forgor whoami - display your username clear - clear the screen` fmt.Fprint(s, helpText) } func showUsername(s ssh.Session, username string) { fmt.Fprintf(s, "You are logged in as: %s\n", username) } func clearScreen(s ssh.Session) { fmt.Fprint(s, "\033[H\033[2J") } Whenever I enter my password and press enter nothing happens, please fix the error without c hangin too much
d1c6cba4b00ce715f31c6e94da8e51db
{ "intermediate": 0.28155583143234253, "beginner": 0.5558670163154602, "expert": 0.16257718205451965 }
17,685
hi
17dced5348d56a318ae4a4f1c652ab21
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
17,686
fix the code: errors: # command-line-arguments .\main.go:8:5: "os" imported and not used .\main.go:28:26: undefined: ssh.ServerConfig .\main.go:33:26: undefined: Asset .\main.go:40:25: undefined: ssh.ParsePrivateKey .\main.go:48:14: undefined: ssh.NewChanIdiom .\main.go:48:27: undefined: s .\main.go:57:32: undefined: ssh.ConnMetadata .\main.go:110:56: rw.ReadCh undefined (type io.ReadWriter has no field or method ReadCh) .\main.go:128:24: rw.ReadCh undefined (type io.ReadWriter has no field or method ReadCh) code: package main import ( "fmt" "strings" "github.com/gliderlabs/ssh" "golang.org/x/crypto/ssh/terminal" "os" "io" ) var ( users = map[string]string{ "alice": "password1", "bob": "password2", "charlie": "password3", } // Create a custom ReadWriter rw io.ReadWriter ) func main() { // Attach the sessionHandler to the SSH server ssh.Handle(sessionHandler) // Set up server configuration serverConfig := &ssh.ServerConfig{ PasswordCallback: passwordCallback, } // Generate private key and check for errors privateBytes, err := Asset("private_key.pem") if err != nil { fmt.Println("Failed to load private key:", err) return } // Add the private key to the server’s configuration private, err := ssh.ParsePrivateKey(privateBytes) if err != nil { fmt.Println("Failed to parse private key:", err) return } serverConfig.AddHostKey(private) // Create a custom ReadWriter using the session’s channel rw = ssh.NewChanIdiom(s) // Start the SSH server err = ssh.ListenAndServe(":2222", nil, serverConfig) if err != nil { fmt.Println("Error starting SSH server:", err) } } func passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) { username := conn.User() storedPassword, found := users[strings.TrimSpace(username)] if found && storedPassword == string(password) { return nil, nil } return nil, fmt.Errorf("login failed") } func sessionHandler(s ssh.Session) { fmt.Fprint(s, "Welcome to cartel!\n\n") if !login(s) { fmt.Fprintln(s, "Login failed. Goodbye!") return } username := s.User() fmt.Fprintf(s, "Welcome, %s!\n\n", username) cmdChan := make(chan string) go readInput(s, cmdChan) for { fmt.Fprintf(s, "[%s@cartel]~$ ", username) select { case cmd := <-cmdChan: cmd = strings.TrimSpace(cmd) switch cmd { case "help": showHelp(s) case "whoami": showUsername(s, username) case "clear": clearScreen(s) case "exit": return default: fmt.Fprintf(s, "Command not found. Type ‘help’ for available commands.\n") } case <-s.Context().Done(): return } } } func login(s ssh.Session) bool { fmt.Fprint(s, "Please enter your username: ") var username string fmt.Fscan(s, &username) fmt.Fprintln(s) fmt.Fprint(s, "Please enter your password: ") passwordBytes, err := terminal.ReadPassword(int(rw.ReadCh().ReadByte())) if err != nil { return false } fmt.Fprintln(s) password := string(passwordBytes) storedPassword, found := users[strings.TrimSpace(username)] if found && storedPassword == password { return true } return false } func readInput(s ssh.Session, cmdChan chan<- string) { var line string for { fmt.Fscanln(rw.ReadCh(), &line) cmdChan <- line } } func showHelp(s ssh.Session) { helpText := `Available commands: help - I forgor whoami - display your username clear - clear the screen` fmt.Fprintln(s, helpText) } func showUsername(s ssh.Session, username string) { fmt.Fprintf(s, "You are logged in as: %s\n", username) } func clearScreen(s ssh.Session) { fmt.Fprint(s, "\033[H\033[2J") } # command-line-arguments .\main.go:8:5: "os" imported and not used .\main.go:28:26: undefined: ssh.ServerConfig .\main.go:33:26: undefined: Asset .\main.go:40:25: undefined: ssh.ParsePrivateKey .\main.go:48:14: undefined: ssh.NewChanIdiom .\main.go:48:27: undefined: s .\main.go:57:32: undefined: ssh.ConnMetadata .\main.go:110:56: rw.ReadCh undefined (type io.ReadWriter has no field or method ReadCh) .\main.go:128:24: rw.ReadCh undefined (type io.ReadWriter has no field or method ReadCh)
10c913a20b0bffef6760223155e5d4c3
{ "intermediate": 0.2692192792892456, "beginner": 0.5066559910774231, "expert": 0.2241247147321701 }
17,687
make code of psuedo elements
5b989ee960c9b3b930480c19b912a4b9
{ "intermediate": 0.29442358016967773, "beginner": 0.32350701093673706, "expert": 0.38206934928894043 }
17,688
nbsp;<span class=\"atid\" style=\"color: rgba(83, 113, 243, 1);\" id=\"1432552\" contenteditable=\"false\" onclick=\"clickTopic(1691649854895)\">@大帅比呀</span>&nbsp; 设置contenteditable=\"false\" 时,删除时光标跳动
c9f6815b10240be34268956ed947e97e
{ "intermediate": 0.2979373633861542, "beginner": 0.3160932660102844, "expert": 0.385969340801239 }
17,689
def city_country(city, country): formatted_country = f"{city}, {country}" return formatted_country.title() city_country('la paz', 'bolivia') city_country('passaic', 'united states') city_country('paris', 'france)') Why doesnt this work in python
851d84f1b478cd1068ec2337a412f4a6
{ "intermediate": 0.42749133706092834, "beginner": 0.3739733397960663, "expert": 0.19853535294532776 }
17,690
LTC2942 is a gas gauge IC and can be used to calculate the current consumption. Can you provide the C language codes to drive it and read the value? Assume the battery capacity is 14400mAh and the external resistor is 10mohm.
fa5e0f428da41af96ab1bda5734fe55a
{ "intermediate": 0.3292449414730072, "beginner": 0.44022393226623535, "expert": 0.23053114116191864 }
17,691
I have columns Date, Payer, SKU, A, B, C. Create DAX expression for calculated measure ROI=(A-B)/C if required to have rows with same values of ROI for unique combination of Payer, SKU, month and year component.
2d018557896b9097797876481d50d9ac
{ "intermediate": 0.36564213037490845, "beginner": 0.23288209736347198, "expert": 0.401475727558136 }
17,692
напиши настройку Sentry performanse для spring boot приложения, чтобы можно было мониторить запросы
209407d8331c4423e28ebc1c0eafd77e
{ "intermediate": 0.4222456216812134, "beginner": 0.20661859214305878, "expert": 0.37113577127456665 }
17,693
difference between <div> and <span> in html
55eb11145c37f31eaa8a3d354dad623a
{ "intermediate": 0.4080547094345093, "beginner": 0.3556901514530182, "expert": 0.23625518381595612 }
17,694
I have a web form, when the user click the "enter", it will trigger the button "submit".
2919d5a05ec3992223283dc25dcee0e5
{ "intermediate": 0.2204699069261551, "beginner": 0.295612633228302, "expert": 0.4839174449443817 }
17,695
using github.com/gliderlabs/ssh and io libraries make a simple ssh app that has a login prompt and a correct user:pass combo. it will check if it matches and then greet the person using t heir username, the username being in a purple color "Welcome {user} to the cartel."
e506665c649c96588e4004554b106bff
{ "intermediate": 0.5605970621109009, "beginner": 0.1445380449295044, "expert": 0.2948649227619171 }
17,696
import {useDispatch, useSelector} from "react-redux"; import {AppState} from "../../../store/store"; import React, {useCallback, useEffect, useRef, useState} from "react"; import useComponentResizeListener from "../../../hooks/componentResizeListener"; import styles from "./Cup.module.css"; import cupDrawer from "./Cup.drawer"; import cupTools from "./Cup.tools"; import cupOptions from "./Cup.options"; import {CupItem} from "../../../hooks/rustWsServer"; import { Box, Checkbox, Dialog, DialogContent, DialogTitle, FormControlLabel, IconButton, TextField, Typography, useTheme, } from "@mui/material"; import {AddRounded, RemoveRounded, SettingsRounded} from "@mui/icons-material"; import {setCupParams} from "../../../store/cupSlice"; import {CupProps} from "./Cup.props"; export interface CanvasSize { width: number; height: number; } const Cup = ({workerRef}: CupProps) => { const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const cupParams = useSelector((state: AppState) => state.cupSlice); const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio)); const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0}); const containerRef = useRef<HTMLDivElement|null>(null); const canvasRef = useRef<HTMLCanvasElement|null>(null); const [zoom, setZoom] = useState(1); const [isLoaded, setIsLoaded] = useState(false); const [settings, setSettings] = useState({ timeout: "40", maxVolume: window.localStorage.getItem(`cup-volume-${symbol}`) || "1000", isFixedVolume: null !== window.localStorage.getItem(`cup-volume-${symbol}`), }); const [showSettings, setShowSettings] = useState(false); const size = useComponentResizeListener(canvasRef); const darkMode = useTheme().palette.mode === "dark"; const dispatch = useDispatch(); const cupSubscribe = useCallback(async(pair: string, zoom: number) => { workerRef.current?.postMessage(JSON.stringify({type: "subscribe", pair, zoom})); }, []); const cupUnsubscribe = useCallback(async(pair: string) => { workerRef.current?.postMessage(JSON.stringify({type: "unsubscribe", pair})); }, []); const sendSettings = () => { workerRef.current?.postMessage(JSON.stringify({ type: "change_max_volume", isFixed: settings.isFixedVolume, maxVolume: parseInt(settings.maxVolume || "0") < 0 ? 1 : parseInt(settings.maxVolume), })); workerRef.current?.postMessage(JSON.stringify({ type: "change_publisher_timeout", value: parseInt(settings.timeout || "0") < 40 ? 40 : parseInt(settings.timeout), })); }; const wheelHandler = (e: WheelEvent) => { e.preventDefault(); workerRef.current?.postMessage(JSON.stringify({type: e.deltaY < 0 ? "camera_up" : "camera_down"})); }; const zoomAdd = () => { let newZoom; if (zoom >= 1 && zoom < 10) { newZoom = zoom + 1; } else if (zoom >= 10 && zoom < 30) { newZoom = zoom + 5; } else if (zoom >= 30 && zoom < 100) { newZoom = zoom + 10; } else { newZoom = zoom; } setZoom(newZoom); }; const zoomSub = () => { let newZoom; if (zoom > 1 && zoom <= 10) { newZoom = zoom - 1; } else if (zoom > 10 && zoom <= 30) { newZoom = zoom - 5; } else if (zoom > 30 && zoom <= 100) { newZoom = zoom - 10; } else { newZoom = zoom; } setZoom(newZoom); }; useEffect(() => { workerRef.current = new Worker(new URL("/workers/cup-builder.ts", import.meta.url)); canvasRef.current?.addEventListener("wheel", wheelHandler, {passive: false}); sendSettings(); return () => { workerRef.current?.terminate(); canvasRef.current?.removeEventListener("wheel", wheelHandler); }; }, []); useEffect(() => { if (!workerRef.current) return; let animationFrameId: number|null = null; workerRef.current.onmessage = (event: MessageEvent<{ type: string, camera: number, aggregation: number, bestBidPrice: number, bestAskPrice: number, maxVolume: number, pricePrecision: number, quantityPrecision: number, priceStep: number, cup: {[key: number]: CupItem}, rowsCount: number, }>) => { if (event?.data?.type === "update_cup") { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } animationFrameId = requestAnimationFrame(() => { const context = canvasRef.current?.getContext("2d"); const zoomedTickSize = event.data.priceStep * event.data.aggregation; if (context) { const rowsOnScreenCount = cupTools.getRowsCountOnScreen( canvasSize.height, cupOptions().cell.defaultHeight * dpiScale, ); const realCellHeight = parseInt((canvasSize.height / rowsOnScreenCount).toFixed(0)); if (event.data.rowsCount !== rowsOnScreenCount) { workerRef.current?.postMessage(JSON.stringify({type: "change_rows_count", value: rowsOnScreenCount})); } cupDrawer.clear(context, canvasSize); if (cupParams.rowCount !== rowsOnScreenCount || cupParams.cellHeight !== realCellHeight || cupParams.aggregation !== event.data.aggregation ) { dispatch(setCupParams({ aggregation: event.data.aggregation, rowCount: rowsOnScreenCount, cellHeight: realCellHeight, pricePrecision: event.data.pricePrecision, priceStep: event.data.priceStep, quantityPrecision: event.data.quantityPrecision, })); } if (event.data.camera === 0 && isLoaded) { setIsLoaded(false); } if (event.data.camera > 0 && !isLoaded) { setIsLoaded(true); } if (event.data.camera !== 0) { cupDrawer.draw( context, canvasSize, dpiScale, event.data.bestBidPrice, event.data.bestAskPrice, event.data.maxVolume, event.data.pricePrecision, event.data.quantityPrecision, event.data.priceStep, event.data.aggregation, rowsOnScreenCount, event.data.camera, realCellHeight, { buy: parseInt((Math.floor(event.data.bestBidPrice / zoomedTickSize) * zoomedTickSize).toFixed(0)), sell: parseInt((Math.ceil(event.data.bestAskPrice / zoomedTickSize) * zoomedTickSize).toFixed(0)), }, darkMode, event.data.cup, ); } } }); } }; return () => { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } }; }, [workerRef.current, canvasSize, darkMode, dpiScale, isLoaded]); useEffect(() => { setDpiScale(Math.ceil(window.devicePixelRatio)); }, [window.devicePixelRatio]); useEffect(() => { if (!size) { return; } setCanvasSize({ width: Math.floor(size.width) * dpiScale, height: Math.floor(size.height) * dpiScale, }); }, [dpiScale, size]); useEffect(() => { cupSubscribe(symbol.toUpperCase(), zoom); return () => { cupUnsubscribe(symbol.toUpperCase()); }; }, [symbol, zoom]); useEffect(() => { setSettings({ ...settings, maxVolume: window.localStorage.getItem(`cup-volume-${symbol}`) || "1000", isFixedVolume: null !== window.localStorage.getItem(`cup-volume-${symbol}`), }); }, [symbol]); useEffect(() => { if (settings.isFixedVolume) { window.localStorage.setItem(`cup-volume-${symbol}`, settings.maxVolume); } else { window.localStorage.removeItem(`cup-volume-${symbol}`); } sendSettings(); }, [settings]); return <div ref={containerRef} className={styles.canvasWrapper}> <div className={styles.controls}> <IconButton onClick={zoomSub} size="small" disabled={!isLoaded}> <RemoveRounded /> </IconButton> <span>x{zoom}</span> <IconButton onClick={zoomAdd} size="small" disabled={!isLoaded}> <AddRounded /> </IconButton> <IconButton onClick={() => setShowSettings(true)} size="small"> <SettingsRounded // @ts-ignore fontSize="xx-small" /> </IconButton> </div> <canvas ref={canvasRef} className={[styles.canvas, isLoaded ? "" : styles.loading].join(" ")} width={canvasSize?.width} height={canvasSize?.height} /> <Dialog open={showSettings} onClose={() => setShowSettings(false)} fullWidth maxWidth="xs"> <DialogTitle>Настройки стакана</DialogTitle> <DialogContent dividers> <Box component="form" autoComplete="off" onSubmit={() => {}} > <TextField fullWidth label="Таймаут обновления стакана, мс." variant="standard" margin="normal" value={settings.timeout} onChange={e => { setSettings({...settings, timeout: e.target.value}); }} /> <Typography fontSize="xx-small">Минимальный таймаут - 40 мс.</Typography> <FormControlLabel control={<Checkbox value="isFixedVolume" checked={settings.isFixedVolume} color="primary" />} label="Фиксированный объем." onChange={() => setSettings({...settings, isFixedVolume: !settings.isFixedVolume})} /> {settings.isFixedVolume && ( <TextField fullWidth label="Объем стакана." variant="standard" margin="normal" value={settings.maxVolume} onChange={e => { setSettings({...settings, maxVolume: e.target.value}); }} /> )} </Box> </DialogContent> </Dialog> </div>; }; export default Cup; const OrderFeed = ({workerRef}: OrderFeedProps) => { const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const cupParams = useSelector((state: AppState) => state.cupSlice); const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio)); const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0}); const containerRef = useRef<HTMLDivElement|null>(null); const canvasRef = useRef<HTMLCanvasElement|null>(null); const [settings, setSettings] = useState({ timeout: "40", aggregation: true, minQuantity: window.localStorage.getItem(`order-feed-min-qty-${symbol}`) || "0", }); const [showSettings, setShowSettings] = useState(false); const size = useComponentResizeListener(canvasRef); const theme = useTheme(); const draw = (trades: TradeItem[], camera: number) => { if (null === canvasRef || !Array.isArray(trades)) return; const context = canvasRef.current?.getContext("2d"); if (context) { orderFeedDrawer.clear(context, canvasSize); orderFeedDrawer.drawLine( context, canvasSize, trades, camera, cupParams.aggregatedPriceStep, cupParams.cellHeight, cupParams.quantityDivider, !settings.minQuantity ? 0 : parseFloat(settings.minQuantity), dpiScale, theme, ); orderFeedDrawer.drawChain( context, canvasSize, trades, camera, cupParams.aggregatedPriceStep, cupParams.cellHeight, cupParams.quantityDivider, !settings.minQuantity ? 0 : parseFloat(settings.minQuantity), dpiScale, theme, ); } }; const wheelHandler = (event: WheelEvent) => { event.preventDefault(); const scrollAmount = event.deltaY; if (containerRef.current) { containerRef.current.scrollLeft += scrollAmount; } }; const tradeSubscribe = useCallback(async(symbol: string) => { workerRef.current?.postMessage(JSON.stringify({type: "subscribe", symbol})); }, []); const tradeUnsubscribe = useCallback(async(symbol: string) => { workerRef.current?.postMessage(JSON.stringify({type: "unsubscribe", symbol})); }, []); useEffect(() => { if (!workerRef.current) return; let animationFrameId: number|null = null; workerRef.current.onmessage = (event: MessageEvent<any>) => { if (event.data.type === "update_trades") { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } animationFrameId = requestAnimationFrame(() => draw(event.data.trades, event.data.camera)); } }; return () => { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } }; }, [workerRef.current, canvasRef.current, canvasSize, symbol, cupParams, theme, settings.minQuantity]); useEffect(() => { setDpiScale(Math.ceil(window.devicePixelRatio)); }, [window.devicePixelRatio]); useEffect(() => { if (!size) { return; } setCanvasSize({ width: Math.floor(size.width) * dpiScale, height: Math.floor(size.height) * dpiScale, }); }, [dpiScale, size]); useEffect(() => { tradeSubscribe(symbol); setSettings(state => ({ ...state, minQuantity: window.localStorage.getItem(`order-feed-min-qty-${symbol}`) || "0", })); return () => { tradeUnsubscribe(symbol); }; }, [symbol, workerRef.current]); useEffect(() => { containerRef.current?.scroll(800, 0); containerRef.current?.addEventListener("wheel", wheelHandler, {passive: false}); workerRef.current = new Worker(new URL("/workers/order-feed-builder.ts", import.meta.url)); return () => { containerRef.current?.removeEventListener("wheel", wheelHandler); workerRef.current?.terminate(); }; }, []); useEffect(() => { workerRef.current?.postMessage(JSON.stringify({ type: "change_publisher_timeout", value: parseInt(settings.timeout || "0") < 40 ? 40 : parseInt(settings.timeout), })); workerRef.current?.postMessage(JSON.stringify({ type: "change_aggregation", value: settings.aggregation, })); window.localStorage.setItem(`order-feed-min-qty-${symbol}`, settings.minQuantity); }, [settings]); return <Box ref={containerRef} sx={{ scrollbarWidth: "thin", "&::-webkit-scrollbar-track": { background: theme => theme.palette.background.paper, }, "&::-webkit-scrollbar-thumb": { backgroundColor: theme => theme.palette.grey[300], border: theme => `3px solid ${theme.palette.white.main}`, }, }} className={`${styles.canvasWrapper} scroll-block`}> <div className={styles.controls}> <IconButton onClick={() => setShowSettings(true)} size="small"> <SettingsRounded // @ts-ignore fontSize="xx-small" /> </IconButton> </div> <canvas ref={canvasRef} className={styles.canvas} width={canvasSize?.width} height={canvasSize?.height} /> <Dialog open={showSettings} onClose={() => setShowSettings(false)} fullWidth maxWidth="xs"> <DialogTitle>Настройки списка ордеров</DialogTitle> <DialogContent dividers> <Box component="form" autoComplete="off" onSubmit={() => {}} > <TextField fullWidth label="Минимальный отображаемый объем" variant="standard" margin="normal" value={settings.minQuantity} onChange={e => { setSettings({...settings, minQuantity: e.target.value}); }} /> <TextField fullWidth label="Таймаут обновления стакана, мс." variant="standard" margin="normal" value={settings.timeout} onChange={e => { setSettings({...settings, timeout: e.target.value}); }} /> <Typography fontSize="xx-small">Минимальный таймаут - 40 мс.</Typography> <FormControlLabel control={<Checkbox value="isFixedVolume" checked={settings.aggregation} color="primary" />} label="Агрегация сделок." onChange={() => setSettings({...settings, aggregation: !settings.aggregation})} /> </Box> </DialogContent> </Dialog> </Box>; }; export default OrderFeed; const TradingCup = () => { const cupWorkerRef = useRef<Worker>(); const orderFeedWorkerRef = useRef<Worker>(); useEffect(() => { const channel = new MessageChannel(); cupWorkerRef.current?.postMessage({type: "set_port", port: channel.port1}, [channel.port1]); orderFeedWorkerRef.current?.postMessage({type: "set_port", port: channel.port2}, [channel.port2]); }, []); return <Stack direction="row" height="100%"> <div className={styles.OfferFeed}> <OrderFeed workerRef={orderFeedWorkerRef} /> </div> <div className={styles.Cup}> <Cup workerRef={cupWorkerRef} /> </div> </Stack>; }; export default TradingCup; нужно настройки OrderFeed и Cup объединить в одно окно и кнопку. Нужно вынести этот попап в TradingCup компонент. Оттуда есть доступ к обоим воркерам.
86ac72a2738f52d8c5d743e18ade71c4
{ "intermediate": 0.30949488282203674, "beginner": 0.41813740134239197, "expert": 0.2723677158355713 }
17,697
for this same app write a function to read a file by filename and print it out via ssh also suggest a simple logging library and introduce me to it package main import ( "fmt" //"io" //"io/ioutil" "github.com/gliderlabs/ssh" "golang.org/x/crypto/ssh/terminal" ) type UserCredentials struct { Username string Password string } func isValidCredentials(username, password string) bool { // Define valid username-password combinations validCredentials := []UserCredentials{ {"user1", "pass1"}, {"user2", "pass2"}, } // Check if the provided credentials match for _, credentials := range validCredentials { if credentials.Username == username && credentials.Password == password { return true } } return false } func handleSession(s ssh.Session) { // Disable terminal modes term := terminal.NewTerminal(s, "> ") term.Write([]byte("Welcome to the SSH Cartel App!\n\n")) // Read username and password term.Write([]byte("Username: ")) username, _ := term.ReadLine() term.Write([]byte("Password: ")) password, _ := term.ReadLine() term.Write([]byte("\n")) // Validate credentials if isValidCredentials(username, string(password)) { // Send greeting message with colored username greeting := fmt.Sprintf("Welcome \033[1;35m%s\033[0m to the cartel.\n", username) term.Write([]byte(greeting)) // Start command execution loop for { term.Write([]byte("$ ")) // Read the command entered by the user cmd, err := term.ReadLine() if err != nil { break } switch cmd { case "command1": term.Write([]byte("Executing command 1…\n")) // Implement the logic for command 1 case "command2": term.Write([]byte("Executing command 2…\n")) // Implement the logic for command 2 case "command3": term.Write([]byte("Executing command 3…\n")) // Implement the logic for command 3 case "exit": term.Write([]byte("Exiting…\n")) return default: term.Write([]byte("Invalid command.\n")) } } } else { term.Write([]byte("Invalid username or password.\n")) } s.Close() } func main() { ssh.Handle(func(s ssh.Session) { handleSession(s) }) fmt.Println("Starting SSH server on port 22…") err := ssh.ListenAndServe(":22", nil) if err != nil { fmt.Println("Failed to start SSH server:", err) } }
25a3e83c1a480a52a0c87d620d7175cb
{ "intermediate": 0.29332423210144043, "beginner": 0.5279937982559204, "expert": 0.17868193984031677 }
17,698
write java tests for a dao pattern
7750234cb4d1d35cad554d6b6db90720
{ "intermediate": 0.41995060443878174, "beginner": 0.23751579225063324, "expert": 0.34253358840942383 }
17,699
export interface CanvasSize { width: number; height: number; } const Cup = ({workerRef}: CupProps) => { const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const cupParams = useSelector((state: AppState) => state.cupSlice); const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio)); const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0}); const containerRef = useRef<HTMLDivElement|null>(null); const canvasRef = useRef<HTMLCanvasElement|null>(null); const [zoom, setZoom] = useState(1); const [isLoaded, setIsLoaded] = useState(false); const [settings, setSettings] = useState({ timeout: “40”, maxVolume: window.localStorage.getItem(cup-volume-${symbol}) || “1000”, isFixedVolume: null !== window.localStorage.getItem(cup-volume-${symbol}), }); const [showSettings, setShowSettings] = useState(false); const size = useComponentResizeListener(canvasRef); const darkMode = useTheme().palette.mode === “dark”; const dispatch = useDispatch(); const cupSubscribe = useCallback(async(pair: string, zoom: number) => { workerRef.current?.postMessage(JSON.stringify({type: “subscribe”, pair, zoom})); }, []); const cupUnsubscribe = useCallback(async(pair: string) => { workerRef.current?.postMessage(JSON.stringify({type: “unsubscribe”, pair})); }, []); const sendSettings = () => { workerRef.current?.postMessage(JSON.stringify({ type: “change_max_volume”, isFixed: settings.isFixedVolume, maxVolume: parseInt(settings.maxVolume || “0”) < 0 ? 1 : parseInt(settings.maxVolume), })); workerRef.current?.postMessage(JSON.stringify({ type: “change_publisher_timeout”, value: parseInt(settings.timeout || “0”) < 40 ? 40 : parseInt(settings.timeout), })); }; const wheelHandler = (e: WheelEvent) => { e.preventDefault(); workerRef.current?.postMessage(JSON.stringify({type: e.deltaY < 0 ? “camera_up” : “camera_down”})); }; const zoomAdd = () =>setZoom(newZoom); const zoomSub = () => setZoom(-10); useEffect(() => { workerRef.current = new Worker(new URL(“/workers/cup-builder.ts”, import.meta.url)); canvasRef.current?.addEventListener(“wheel”, wheelHandler, {passive: false}); sendSettings(); return () => { workerRef.current?.terminate(); canvasRef.current?.removeEventListener(“wheel”, wheelHandler); }; }, []); useEffect(() => { if (!workerRef.current) return; let animationFrameId: number|null = null; workerRef.current.onmessage = (event: MessageEvent< {...... return () => { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } }; }, [workerRef.current, canvasSize, darkMode, dpiScale, isLoaded]); useEffect(() => { setDpiScale(Math.ceil(window.devicePixelRatio)); }, [window.devicePixelRatio]); useEffect(() => { if (!size) { return; } setCanvasSize({ width: Math.floor(size.width) * dpiScale, height: Math.floor(size.height) * dpiScale, }); }, [dpiScale, size]); useEffect(() => { cupSubscribe(symbol.toUpperCase(), zoom); return () => { cupUnsubscribe(symbol.toUpperCase()); }; }, [symbol, zoom]); useEffect(() => { setSettings({ …settings, maxVolume: window.localStorage.getItem(cup-volume-${symbol}) || “1000”, isFixedVolume: null !== window.localStorage.getItem(cup-volume-${symbol}), }); }, [symbol]); useEffect(() => { if (settings.isFixedVolume) { window.localStorage.setItem(cup-volume-${symbol}, settings.maxVolume); } else { window.localStorage.removeItem(cup-volume-${symbol}); } sendSettings(); }, [settings]); return <div ref={containerRef} className={styles.canvasWrapper}> <canvas ref={canvasRef} className={[styles.canvas, isLoaded ? “” : styles.loading].join(" “)} width={canvasSize?.width} height={canvasSize?.height} /> <Dialog open={showSettings} onClose={() => setShowSettings(false)} fullWidth maxWidth=“xs”> <DialogTitle>Настройки стакана</DialogTitle> <DialogContent dividers> <Box component=“form” autoComplete=“off” onSubmit={() => {}} > <TextField fullWidth label=“Таймаут обновления стакана, мс.” variant=“standard” margin=“normal” value={settings.timeout} onChange={e => { setSettings({…settings, timeout: e.target.value}); }} /> <Typography fontSize=“xx-small”>Минимальный таймаут - 40 мс.</Typography> <FormControlLabel control={<Checkbox value=“isFixedVolume” checked={settings.isFixedVolume} color=“primary” />} label=“Фиксированный объем.” onChange={() => setSettings({…settings, isFixedVolume: !settings.isFixedVolume})} /> {settings.isFixedVolume && ( <TextField fullWidth label=“Объем стакана.” variant=“standard” margin=“normal” value={settings.maxVolume} onChange={e => { setSettings({…settings, maxVolume: e.target.value}); }} /> )} </Box> </DialogContent> </Dialog> </div>; }; export default Cup; const OrderFeed = ({workerRef}: OrderFeedProps) => { const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const cupParams = useSelector((state: AppState) => state.cupSlice); const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio)); const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0}); const containerRef = useRef<HTMLDivElement|null>(null); const canvasRef = useRef<HTMLCanvasElement|null>(null); const [settings, setSettings] = useState({ timeout: “40”, aggregation: true, minQuantity: window.localStorage.getItem(order-feed-min-qty-${symbol}) || “0”, }); const [showSettings, setShowSettings] = useState(false); const size = useComponentResizeListener(canvasRef); const theme = useTheme(); const draw = (trades: TradeItem[], camera: number) => { if (null === canvasRef || !Array.isArray(trades)) return; const context = canvasRef.current?.getContext(“2d”); if (context) { orderFeedDrawer.clear(context, canvasSize); orderFeedDrawer.drawLine( context, canvasSize, trades, camera, cupParams.aggregatedPriceStep, cupParams.cellHeight, cupParams.quantityDivider, !settings.minQuantity ? 0 : parseFloat(settings.minQuantity), dpiScale, theme, ); orderFeedDrawer.drawChain( context, canvasSize, trades, camera, cupParams.aggregatedPriceStep, cupParams.cellHeight, cupParams.quantityDivider, !settings.minQuantity ? 0 : parseFloat(settings.minQuantity), dpiScale, theme, ); } }; const wheelHandler = (event: WheelEvent) => { event.preventDefault(); const scrollAmount = event.deltaY; if (containerRef.current) { containerRef.current.scrollLeft += scrollAmount; } }; const tradeSubscribe = useCallback(async(symbol: string) => { workerRef.current?.postMessage(JSON.stringify({type: “subscribe”, symbol})); }, []); const tradeUnsubscribe = useCallback(async(symbol: string) => { workerRef.current?.postMessage(JSON.stringify({type: “unsubscribe”, symbol})); }, []); useEffect(() => { if (!workerRef.current) return; let animationFrameId: number|null = null; workerRef.current.onmessage = (event: MessageEvent<any>) => { if (event.data.type === “update_trades”) { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } animationFrameId = requestAnimationFrame(() => draw(event.data.trades, event.data.camera)); } }; return () => { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } }; }, [workerRef.current, canvasRef.current, canvasSize, symbol, cupParams, theme, settings.minQuantity]); useEffect(() => { setDpiScale(Math.ceil(window.devicePixelRatio)); }, [window.devicePixelRatio]); useEffect(() => { if (!size) { return; } setCanvasSize({ width: Math.floor(size.width) * dpiScale, height: Math.floor(size.height) * dpiScale, }); }, [dpiScale, size]); useEffect(() => { tradeSubscribe(symbol); setSettings(state => ({ …state, minQuantity: window.localStorage.getItem(order-feed-min-qty-${symbol}) || “0”, })); return () => { tradeUnsubscribe(symbol); }; }, [symbol, workerRef.current]); useEffect(() => { containerRef.current?.scroll(800, 0); containerRef.current?.addEventListener(“wheel”, wheelHandler, {passive: false}); workerRef.current = new Worker(new URL(”/workers/order-feed-builder.ts", import.meta.url)); return () => { containerRef.current?.removeEventListener(“wheel”, wheelHandler); workerRef.current?.terminate(); }; }, []); useEffect(() => { workerRef.current?.postMessage(JSON.stringify({ type: “change_publisher_timeout”, value: parseInt(settings.timeout || “0”) < 40 ? 40 : parseInt(settings.timeout), })); workerRef.current?.postMessage(JSON.stringify({ type: “change_aggregation”, value: settings.aggregation, })); window.localStorage.setItem(order-feed-min-qty-${symbol}, settings.minQuantity); }, [settings]); return <Box ref={containerRef} sx={{ scrollbarWidth: “thin”, “&::-webkit-scrollbar-track”: { background: theme => theme.palette.background.paper, }, “&::-webkit-scrollbar-thumb”: { backgroundColor: theme => theme.palette.grey[300], border: theme => 3px solid ${theme.palette.white.main}, }, }} className={${styles.canvasWrapper} scroll-block}> <div className={styles.controls}> <IconButton onClick={() => setShowSettings(true)} size=“small”> <SettingsRounded // @ts-ignore fontSize=“xx-small” /> </IconButton> </div> <canvas ref={canvasRef} className={styles.canvas} width={canvasSize?.width} height={canvasSize?.height} /> <Dialog open={showSettings} onClose={() => setShowSettings(false)} fullWidth maxWidth=“xs”> <DialogTitle>Настройки списка ордеров</DialogTitle> <DialogContent dividers> <Box component=“form” autoComplete=“off” onSubmit={() => {}} > <TextField fullWidth label=“Минимальный отображаемый объем” variant=“standard” margin=“normal” value={settings.minQuantity} onChange={e => { setSettings({…settings, minQuantity: e.target.value}); }} /> <TextField fullWidth label=“Таймаут обновления стакана, мс.” variant=“standard” margin=“normal” value={settings.timeout} onChange={e => { setSettings({…settings, timeout: e.target.value}); }} /> <Typography fontSize=“xx-small”>Минимальный таймаут - 40 мс.</Typography> <FormControlLabel control={<Checkbox value=“isFixedVolume” checked={settings.aggregation} color=“primary” />} label=“Агрегация сделок.” onChange={() => setSettings({…settings, aggregation: !settings.aggregation})} /> </Box> </DialogContent> </Dialog> </Box>; }; export default OrderFeed; const TradingCup = () => { const cupWorkerRef = useRef<Worker>(); const orderFeedWorkerRef = useRef<Worker>(); useEffect(() => { const channel = new MessageChannel(); cupWorkerRef.current?.postMessage({type: “set_port”, port: channel.port1}, [channel.port1]); orderFeedWorkerRef.current?.postMessage({type: “set_port”, port: channel.port2}, [channel.port2]); }, []); return <Stack direction=“row” height=“100%”> <div className={styles.OfferFeed}> <OrderFeed workerRef={orderFeedWorkerRef} /> </div> <div className={styles.Cup}> <Cup workerRef={cupWorkerRef} /> </div> </Stack>; }; export default TradingCup; нужно настройки OrderFeed и Cup объединить в одно окно и кнопку. Нужно вынести этот попап в TradingCup компонент. Оттуда есть доступ к обоим воркерам.
509e83c5c993a24fafba26b993714354
{ "intermediate": 0.3493994474411011, "beginner": 0.4700883626937866, "expert": 0.1805122196674347 }
17,700
When another ChatGPT instance said I should use Hibernate, did it likely, more specifically, mean that I should use Hibernate Core? (Also, is my grammar correct in the question I just asked.)
d4a85eb921e04f5646faa25516566e62
{ "intermediate": 0.5786375403404236, "beginner": 0.1679345667362213, "expert": 0.2534279227256775 }
17,701
How to create temporary table inside calculated measure dax?
5f65ec40d95307d35013f6f2378edeb1
{ "intermediate": 0.3384625315666199, "beginner": 0.13198281824588776, "expert": 0.5295546650886536 }
17,702
using typescript, call 'await query()' until the code of response is 0 or -1
6963690024834dbdea51fae35f745f95
{ "intermediate": 0.5435411930084229, "beginner": 0.2802974581718445, "expert": 0.17616142332553864 }
17,703
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if buy_qty > sell_qty: signal.append('buy') elif sell_qty > buy_qty: signal.append('sell') else: signal.append('none') return signal end_time = int(time.time() * 1000) start_time = end_time - lookback * 60 * 1000 secret_key = API_KEY_BINANCE access_key = API_SECRET_BINANCE import binance while True: lookback = 10080 df = get_klines(symbol, interval, lookback) if df is not None: signals = signal_generator(df) print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Signals: {signals}") mark_price = client.ticker_price(symbol=symbol) time.sleep(1) But it giving me signals every second , it doesn't return none in terminal , please solve this problem
100ec4d58637241bb631cab9a511554c
{ "intermediate": 0.4845432937145233, "beginner": 0.299078106880188, "expert": 0.2163785994052887 }
17,704
why doesn't my outputFile function work with ascii? In the greeting section it looks like the same thing but on there it works for some reason, any clue why? please dont install any libraries, they are most likely not needed. package main import ( "fmt" //"io" "io/ioutil" "github.com/gliderlabs/ssh" "golang.org/x/crypto/ssh/terminal" ) type UserCredentials struct { Username string Password string } func isValidCredentials(username, password string) bool { // Define valid username-password combinations validCredentials := []UserCredentials{ {"user1", "pass1"}, {"user2", "pass2"}, } // Check if the provided credentials match for _, credentials := range validCredentials { if credentials.Username == username && credentials.Password == password { return true } } return false } func handleSession(s ssh.Session) { // Disable terminal modes term := terminal.NewTerminal(s, "> ") term.Write([]byte("Welcome to the cartel.\n\n")) // Read username and password term.Write([]byte("Username: ")) username, _ := term.ReadLine() term.Write([]byte("Password: ")) password, _ := term.ReadLine() term.Write([]byte("\n")) // Validate credentials if isValidCredentials(username, string(password)) { // Send greeting message with colored username outputFile(term, "./branding/banner.ans") greeting := fmt.Sprintf("Welcome \033[1;35m%s\033[0m to the cartel.\n", username) term.Write([]byte(greeting)) // Start command execution loop for { term.Write([]byte("$ ")) // Read the command entered by the user cmd, err := term.ReadLine() if err != nil { break } switch cmd { case "command1": term.Write([]byte("Executing command 1…\n")) // Implement the logic for command 1 case "command2": term.Write([]byte("Executing command 2…\n")) // Implement the logic for command 2 case "command3": term.Write([]byte("Executing command 3…\n")) // Implement the logic for command 3 case "exit": term.Write([]byte("Exiting…\n")) return default: term.Write([]byte("Invalid command.\n")) } } } else { term.Write([]byte("Invalid username or password.\n")) } s.Close() } func outputFile(term *terminal.Terminal, filePath string) { data, err := ioutil.ReadFile(filePath) if err != nil { term.Write([]byte(fmt.Sprintf("Failed to read file: %s\n", err))) } else { term.Write([]byte(data)) } } func main() { ssh.Handle(func(s ssh.Session) { handleSession(s) }) fmt.Println("Starting SSH server on port 22…") err := ssh.ListenAndServe(":22", nil) if err != nil { fmt.Println("Failed to start SSH server:", err) } }
3e5f0f0ec458fe43278e10b9870141ac
{ "intermediate": 0.2469540387392044, "beginner": 0.47103551030158997, "expert": 0.28201040625572205 }
17,705
safari cannot set focus to element. Please help
4df5d2ae8736068077ace662e39bd9fb
{ "intermediate": 0.36882227659225464, "beginner": 0.36305397748947144, "expert": 0.2681237459182739 }
17,706
overlay screen to all angular components when click on button
c2bdeac95490c8747c3bf34db9d1d121
{ "intermediate": 0.406888484954834, "beginner": 0.3066394627094269, "expert": 0.2864721119403839 }
17,707
while using procmon64 i can determine how and by whom process was started but not how it was terminate. Is there a way to find process termination info
d15e45f6d712d9575fb9dda3b231ef1c
{ "intermediate": 0.5007548332214355, "beginner": 0.1362103372812271, "expert": 0.36303484439849854 }
17,708
I want to verify warning for flight according to annex 3.An example of a warning is as follows: "ZCZC 711 WOIR31 OIII 010533 OIIX WARNING 1 VALID 010525/010830 OIII- OIIX TEHRAN FIR SFC WSPD MAX 35G45KT OBS/FCST OVER OIZB= NNNN". to compare metar data
43b1e0e7fbecb95412870a5100fdcf49
{ "intermediate": 0.3792237341403961, "beginner": 0.2137564867734909, "expert": 0.40701979398727417 }
17,709
Write a query that returns names of days. Please do it with C# code.
3d84c6154b4a9ac4470bc4381f299fd1
{ "intermediate": 0.5690024495124817, "beginner": 0.18716098368167877, "expert": 0.24383662641048431 }
17,710
мне нужно вынести логику Update в другой класс так как он теперь не MonoBehaviour public class UINavigator { public event Action<NamePopupItem> OnNextScreen; public event Action OnPreviousScreen; private PopupItem currentPanel = null; private int selectedPopupIndex = 0; private bool isEmptyScreen = false; private int selectedCurrentPopupIndex = 0; private IInputService inputService; public UINavigator() { inputService = new InputService(); } public void SetCurrentPopup(PopupItem panelItem) { currentPanel = panelItem; if (currentPanel.Popup.Length != 0) { ResetPopupSelection(); EventSystem.current.SetSelectedGameObject(currentPanel.Popup[currentPanel.SelectedPopupIndex].gameObject); currentPanel.Popup[currentPanel.SelectedPopupIndex].Highlight(); selectedCurrentPopupIndex = currentPanel.SelectedPopupIndex; } else { isEmptyScreen = true; } } private void Update() { if (isEmptyScreen) { HandleEmptyScreenInput(); } else { HandlePopupInput(); } } private void HandleEmptyScreenInput() { if (currentPanel.NextItemName == NamePopupItem.None) { if (inputService.GetLeftArrowKeyDown()) { OnPreviousScreen?.Invoke(); } } else { if (inputService.GetRightArrowKeyDown()) { OnNextScreen?.Invoke(currentPanel.NextItemName); } if (inputService.GetLeftArrowKeyDown()) { OnPreviousScreen?.Invoke(); } } } private void HandlePopupInput() { if (EventSystem.current.currentSelectedGameObject == null) { EventSystem.current.SetSelectedGameObject(currentPanel.Popup[selectedPopupIndex].gameObject); } if (inputService.GetUpArrowKeyDown()) { selectedPopupIndex = selectedCurrentPopupIndex; SelectFocus(-1); } if (inputService.GetDownArrowKeyDown()) { selectedPopupIndex = selectedCurrentPopupIndex; SelectFocus(1); } if (inputService.GetLeftArrowKeyDown()) { OnPreviousScreen?.Invoke(); } if (inputService.GetRightArrowKeyDown()) { selectedPopupIndex = selectedCurrentPopupIndex; currentPanel.Popup[selectedPopupIndex].Select(); currentPanel.SelectedPopupIndex = selectedPopupIndex; OnNextScreen?.Invoke(currentPanel.Popup[selectedPopupIndex].ScreenItem); } } private void SelectFocus(int direction) { EventSystem.current.SetSelectedGameObject(null); ResetPopupSelection(); selectedPopupIndex = (selectedPopupIndex + direction + currentPanel.Popup.Length) % currentPanel.Popup.Length; EventSystem.current.SetSelectedGameObject(currentPanel.Popup[selectedPopupIndex].gameObject); currentPanel.Popup[selectedPopupIndex].Highlight(); selectedCurrentPopupIndex = selectedPopupIndex; } private void ResetPopupSelection() { isEmptyScreen = false; EventSystem.current.SetSelectedGameObject(null); foreach (var item in currentPanel.Popup) { item.Deselect(); } } }
c577f4a064548f08c98c0c838fc0c2a1
{ "intermediate": 0.2861972451210022, "beginner": 0.6021185517311096, "expert": 0.11168424040079117 }
17,711
import {Grid, Box, Stack, Button, FormControl, MenuItem, Select, Slider, Typography, styled} from “@mui/material”; import React, {useState} from “react”; import {AddCircleIcon, ArrowDropDownIcon} from “…/…/icons”; import FormatPrice from “…/…/CicapDiary/FormatPrice/FormatPrice”; import {useSelector} from “react-redux”; import {AppState} from “…/…/…/store/store”; const AssetsBuySell = () => { const [orderSide, setOrderSide] = useState(“buy” as “buy” | “sell”); const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const StyledSlider = styled(Slider)({ color: orderSide === “buy” ? “#006943” : “#B41C18”, height: 2, “& .MuiSlider-thumb”: { backgroundColor: “#fff”, border: orderSide === “buy” ? “2px solid #006943” : “2px solid #B41C18”, transform: “translateY(-7.5px) translateX(-4px)”, height: 15, width: 15, “&.MuiSlider-thumbColorPrimary”: { boxShadow: “none”, }, }, “& .MuiSlider-rail”: { backgroundColor: “#D9D9D9”, opacity: 1, }, “& .MuiSlider-mark”: { height: 9, width: 9, borderRadius: “50%”, backgroundColor: “#fff”, border: “2px solid #D9D9D9”, “&.MuiSlider-markActive”: { height: 11, width: 11, backgroundColor: “#fff”, opacity: 1, transform: “translateY(-7.5px) translateX(-4px)”, border: orderSide === “buy” ? “2px solid #006943” : “2px solid #B41C18”, }, }, }); const [showLimit, setShowLimit] = useState(false); const [showTPSL, setShowTPSL] = useState(false); const [price, setPrice] = useState<number>(0); const [priceSymbol, setPriceSymbol] = useState(“USDT”); const min = 8440; const max = 24999; const range = max - min; const marks = [ {value: min}, {value: min + (range * .25)}, {value: min + (range * .5)}, {value: min + (range * .75)}, {value: max}, ]; return ( <Box className=“scroll-block” sx={{height: “100%”, overflowY: “auto”, overflowX: “hidden”, position: “relative”, bgcolor: theme => theme.palette.background.paper, borderRadius: “8px”}}> <Stack sx={{bgcolor: theme => theme.palette.background.paper, m: 1.5, mb: 1}}> <Grid mb={1.1} > <Button onClick={() => setOrderSide(“buy”)} variant={orderSide === “buy” ? “contained” : “text”} color=“black” sx={{backgroundColor: orderSide === “buy” ? “#EEEEEE” : “”, px: 1.6, fontWeight: orderSide === “buy” ? 600 : 400, fontSize: 13, py: .2, color: orderSide === “buy” ? “#191919” : “#999999”, “&:hover”: {boxShadow: “none”}}}>Купить</Button> <Button onClick={() => setOrderSide(“sell”)} variant={orderSide === “sell” ? “contained” : “text”} color=“black” sx={{backgroundColor: orderSide === “sell” ? “#EEEEEE” : “”, ml: 1, fontWeight: orderSide === “sell” ? 600 : 400, fontSize: 13, px: 1.6, py: .2, color: orderSide === “sell” ? “#191919” : “#999999”, “&:hover”: {boxShadow: “none”}}}>Продать</Button> </Grid> <Box display=“flex” alignItems=“center” justifyContent=“space-between” onClick={() => setShowLimit(prev => !prev)} sx={{cursor: “pointer”, backgroundColor: theme => theme.palette.grey[200], color: theme => theme.palette.text.secondary, px: 1.5, py: .8, borderRadius: showLimit ? “8px 8px 0 0” : “8px”}} > <Typography fontSize={13} className=“unselectable” fontWeight={400} >Лимит</Typography> <ArrowDropDownIcon sx={{fontSize: “9px”, mr: .5, transform: !showLimit ? “” : “rotate(180deg)”}} /> </Box> { showLimit && <> <Box display=“flex” alignItems=“center” justifyContent=“space-between” mt={.16} sx={{backgroundColor: theme => theme.palette.grey[200], color: theme => theme.palette.text.secondary, px: 1.5, py: 1.3}} > <Typography fontSize={13} className=“unselectable” color=“#999999”>Цена</Typography> <Typography fontSize={13}>30183.4 {priceSymbol}</Typography> </Box> <Box display=“flex” alignItems=“center” justifyContent=“space-between” mt={.12} sx={{backgroundColor: theme => theme.palette.grey[200], color: theme => theme.palette.text.secondary, pr: 0, pl: 1.5, py: 1.3, borderRadius: “0 0 8px 8px”}} > <Typography color=“#999999” fontSize={13} className=“unselectable”>Сумма</Typography> <FormControl sx={{fontSize: 13, “& svg”:{color: “#999999”}, " & .MuiSelect-select": {p: 0}, “& fieldset”: {border: “none”}, bgColor: theme => theme.palette.text.secondary}}> <Select sx={{fontSize: 13}} onChange={(e) => setPriceSymbol(e.target.value)} value={priceSymbol}> <MenuItem sx={{fontSize: 13}} value=“USDT”>USDT</MenuItem> <MenuItem sx={{fontSize: 13}} value=“BUSDT”>BUSDT</MenuItem> </Select> </FormControl> </Box> </> } <Grid mt={.3} ml={.6} mr={1.5} height={30} > <StyledSlider value={price} min={min} max={max} marks={marks} onChange={(e, value) => setPrice(value as number)} /> </Grid> <Box> <Stack display=“flex” mb={.6}> <Box display=“flex” onClick={() => setShowTPSL(prev => !prev)} mt={.3} className=“add_removed” > <AddCircleIcon sx={{fontSize: 17, “& path”: {fill: “#999999”}, fill:“#eeeeee”}} width={88} /> <Typography ml={.5} fontSize={11} color=“#999999” className=“unselectable”>TP/SL</Typography> </Box> { showTPSL && <> <Box display=“flex” alignItems=“center” justifyContent=“space-between” mt={.12} sx={{backgroundColor: “#eeeeee”, color: “#191919”, pr: 0, pl: 1.5, py: 1.3, borderRadius: “8px 8px 0 0”}} > <Typography color=“#999999” fontSize={13} className=“unselectable” fontWeight={400}>TP</Typography> <FormControl sx={{fontSize: 13, “& svg”:{color: “#999999”}, " & .MuiSelect-select": {py: 0, px: 0}, “& fieldset”: {border: “none”}}} style={{backgroundColor: “#eeeeee”, color: “#191919”}}> <Select sx={{fontSize: 13}} value=“Марк”> <MenuItem sx={{fontSize: 13}} value=“Марк”>Марк</MenuItem> <MenuItem sx={{fontSize: 13}} value=“USDT”>USDT</MenuItem> <MenuItem sx={{fontSize: 13}} value=“BUSDT”>BUSDT</MenuItem> </Select> </FormControl> </Box> <Box display=“flex” alignItems=“center” justifyContent=“space-between” mt={.12} sx={{backgroundColor: theme => theme.palette.grey[200], color: theme => theme.palette.text.secondary,pr: 0, pl: 1.5, py: 1.3, borderRadius: “0 0 8px 8px”}} > <Typography color=“#999999” fontSize={13} className=“unselectable”>SL</Typography> <FormControl sx={{fontSize: 13, “& svg”:{color: “#999999”}, " & .MuiSelect-select": {py: 0, px: 0}, “& fieldset”: {border: “none”}, color: theme => theme.palette.text.secondary}}> <Select sx={{fontSize: 13}} value=“Марк”> <MenuItem sx={{fontSize: 13}} value=“Марк”>Марк</MenuItem> <MenuItem sx={{fontSize: 13}} value=“BUSDT”>BUSDT</MenuItem> </Select> </FormControl> </Box> </> } </Stack> <Button variant=“contained” color=“discordInvite” sx={{ height: 52, px: 1, fontSize: 11, backgroundColor: orderSide === “buy” ? “#006943” : “#B41C18”, color: “#fff”, verticalAlign: “middle”, width: “100%”, }}> {orderSide === “buy” ? “Купить” : “Продать”} <Typography mt={-.8} lineHeight={“52px”}>.</Typography> {price} {symbol} </Button> <Grid mt={.5} display=“flex” justifyContent=“space-between” > <Typography fontSize={11} color=“#999999”>Доступно</Typography> <Typography fontSize={11} >{FormatPrice({amount: min, currency_iso_code: “USD”, dec: “decimal”})} USDT</Typography> </Grid> <Grid mt={-.5} display=“flex” justifyContent=“space-between” > <Typography fontSize={11} color=“#999999”>Макс</Typography> <Typography fontSize={11}>{FormatPrice({amount: max, currency_iso_code: “USD”, dec: “decimal”})} USDT</Typography> </Grid> </Box> </Stack> </Box>); }; export default AssetsBuySell; ползунок не перетаскивается если мышкрй двигать. посмотри и пойми почему не работает кога я тяну ползунок, работает только по клику
796b517c32132ee143dee7d879fbfe55
{ "intermediate": 0.32876354455947876, "beginner": 0.43788814544677734, "expert": 0.23334825038909912 }
17,712
i have a df. loop through each row
be49f29c66eb61ebd4df0fcdb31fcc7b
{ "intermediate": 0.2175213247537613, "beginner": 0.5505492687225342, "expert": 0.23192943632602692 }
17,713
can you do comprehensive comparison between these dataset for predicting the length of hospital stay: i. MIMIC-III, ii. eICU Collaborative Research Database, iii. SEER-Medicare, iv. HIMSS An, alytics Database, v. The Statewide Planning and Research Cooperative System (SPARCS) and vi. National Inpatient Sample (NIS)
6de7b26fb6a3c4069fd2310a361688a7
{ "intermediate": 0.3010878264904022, "beginner": 0.19715382158756256, "expert": 0.5017583966255188 }
17,714
Hi, i am using a winforms application. I show html text in a editor window, the text is in this prosess converted to rtf-format. At other moments the same text is shown as html. The problem is that there is added extra line space in the rtf-format compared to the html document. Do you have any suggestions how I can use the same html text in both rtf-format and html and identical display?
bf460552034fbec02cecdef8e50f76bb
{ "intermediate": 0.5671312808990479, "beginner": 0.22332541644573212, "expert": 0.20954331755638123 }
17,715
hi
ccb0f066139bc179ef8e491bb770f533
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
17,716
eterate over each row
50f994a9f5db0721ee301cf7a3fdf008
{ "intermediate": 0.4017918109893799, "beginner": 0.28814852237701416, "expert": 0.31005963683128357 }
17,717
Rewrite this block about me with a higher level of English that is suitable for a resume. 'I have two higher educations - tourism and international relations. I have made progress in my scientific work. I have experience in commercial work and experience in public service. Commercial experience in a small travel company that was engaged in excursions. Civil service is work at the department of the university and internships in departments and ministries. I recently received my diploma and am interested in hosting business events and congresses. My strengths are responsibility, perfectionism and attention to detail. In the future, I see myself and my career in this direction. I have extensive experience in participating in various forums, conferences and business events.'
0d45d7bbb84b45033287696234c4defe
{ "intermediate": 0.31787145137786865, "beginner": 0.3603196442127228, "expert": 0.32180896401405334 }
17,718
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if buy_qty > sell_qty: signal.append('buy') elif sell_qty > buy_qty: signal.append('sell') else: signal.append('') return signal But it giving me only sell signal
37c353926c593f3829ca4c03469696de
{ "intermediate": 0.375395268201828, "beginner": 0.37467920780181885, "expert": 0.24992553889751434 }
17,719
how do i save the results from: model.fit(train_objectives=[(train_dataloader, train_loss)], epochs=num_epochs, warmup_steps=warmup_steps)
9a3880715e332d30f4d7555400a06f18
{ "intermediate": 0.23469629883766174, "beginner": 0.15014901757240295, "expert": 0.6151547431945801 }
17,720
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if buy_qty > sell_qty: signal.append('buy') elif sell_qty > buy_qty: signal.append('sell') else: signal.append('') return signal But it doesn't return me else: signal.append('') in terminal
8aee01fcb1703c68de74bca7c37b3af6
{ "intermediate": 0.36870041489601135, "beginner": 0.4111070930957794, "expert": 0.22019241750240326 }
17,721
import random class Card: def __init__(self, name, base_score): self.name = name self.base_score = base_score self.cooperation_scores = {} def add_cooperation_score(self, other_card_name, score): self.cooperation_scores[other_card_name] = score class Game: def __init__(self, card_library): self.card_library = card_library def calculate_score(self, selection): total_score = sum(card.base_score for card in selection) cooperation_scores = {} # 创建一个新的字典来存储合作得分 for i in range(len(selection)): for j in range(i + 1, len(selection)): if selection[i].name in selection[j].cooperation_scores: cooperation_scores[(selection[i].name, selection[j].name)] = selection[i].cooperation_scores[ selection[j].name] # 修改此处,使用卡片i的合作得分字典来获取得分 for pair, score in cooperation_scores.items(): # 遍历新的字典来计算合作得分 total_score += score return total_score, [card.name for card in selection] def get_selected_cards(self): return self.selection cards = [Card("A", 50), Card("B", 50), Card("C", 50), Card("D", 50), Card("E", 50), Card("F", 50)] cooperation_scores = { ("A", "B"): 2, ("A", "B", "C"): 5, ("A", "B", "C", "D"): 10, } # 添加卡牌之间的加分关系 for card in cards: for other_card_name in cooperation_scores.keys(): if other_card_name == card.name: card.add_cooperation_score(other_card_name, cooperation_scores[other_card_name]) game = Game(cards) # 创建游戏实例 selection = random.sample(cards, 4) # 这里假设你使用的是随机选择的方式,你也可以根据需要选择不同的方式 score, names = game.calculate_score(selection) # 计算总分和选择的牌的名字 print("Total score:", score) # 打印总分 print("Selected cards:", names) # 打印选择的牌的名字 运行结果: Total score: 200 Selected cards: ['F', 'D', 'B', 'A'] 加分关系没有生效,请修改代码。
ce6bc90945e2d5c941f6883bc8da6e22
{ "intermediate": 0.252640962600708, "beginner": 0.5771940350532532, "expert": 0.17016498744487762 }
17,722
import random class Card: def __init__(self, name, base_score): self.name = name self.base_score = base_score self.cooperation_scores = {} def add_cooperation_score(self, other_card_name, score): self.cooperation_scores[other_card_name] = score class Game: def __init__(self, card_library): self.card_library = card_library def calculate_score(self, selection): total_score = sum(card.base_score for card in selection) selected_card_names = [card.name for card in selection] # 获取选中卡牌的名称 cooperation_scores = {} # 创建一个新的字典来存储合作得分 for cards, score in cooperation_scores.items(): if all(card_name in selected_card_names for card_name in cards): # 如果所有卡牌名称都在选中卡牌列表中 total_score += score return total_score, selected_card_names def get_selected_cards(self): return self.selection cards = [Card("A", 50), Card("B", 50), Card("C", 50), Card("D", 50), Card("E", 50), Card("F", 50)] cooperation_scores = { ("A", "B"): 2, ("A", "B", "C"): 5, ("A", "B", "C", "D"): 10, } # 添加卡牌之间的加分关系 for card in cards: for other_card_name in cooperation_scores.keys(): if other_card_name == card.name: card.add_cooperation_score(other_card_name, cooperation_scores[other_card_name]) game = Game(cards) # 创建游戏实例 selection = random.sample(cards, 4) # 这里假设你使用的是随机选择的方式,你也可以根据需要选择不同的方式 score, names = game.calculate_score(selection) # 计算总分和选择的牌的名字 print("Total score:", score) # 打印总分 print("Selected cards:", names) # 打印选择的牌的名字 运行结果如下: Total score: 200 Selected cards: ['A', 'D', 'B', 'C'] 加分关系不生效,请修改代码。
8b2391ab8e8dba5daed6d293e06c48f7
{ "intermediate": 0.2743103504180908, "beginner": 0.5160571932792664, "expert": 0.20963245630264282 }
17,723
File writing and file rotation perl
3dd608e05c67a10cae41ce4b8ea9d61e
{ "intermediate": 0.34366869926452637, "beginner": 0.3336998224258423, "expert": 0.3226314187049866 }
17,724
zoptymalizuj ten kod aby był bardziej wydajniejszy: package main import ( "fmt" "math/rand" "time" ) var alphabetB256U [256]rune = [256]rune{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // digits 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', // uppercase letters 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', // lowercase letters 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, // umlaut letters... 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, } func encodeB256U(dataPtr []byte) string { result := "" for _, v := range dataPtr { character := rune(alphabetB256U[v]) if character >= 128 { result += string(192 + (character >> 6)) result += string(128 + (character & 63)) } else { result += string(character) } } return result } func decodeB256U(str string) []byte { result := make([]byte, len(str)) dataPtr := 0 for i := 0; i < len(str); i++ { unicode := rune(str[i]) if unicode >= 128 { unicode = (unicode - 192) << 6 | (rune(str[i+1]) - 128) & 63 i++ } taPtr++ break } } } return result[:dataPtr] } func randomize(dataPtr []byte) { seed := time.Now().Unix() + rand.Int63() + int64(uintptr(unsafe.Pointer(&dataPtr))) + int64(len(dataPtr)) + int64(dataPtr[0]) rand.Seed(seed) for i := 0; i < len(dataPtr); i++ { dataPtr[i] = byte(rand.Int()) } } func main() { fmt.Println() fmt.Println("Examples of 128-bit of data in B256U Encoding") fmt.Println("---------------------------------------------") for i := 0; i < 100; i++ { binaryData := make([]byte, 128/8) randomize(binaryData) // encode: text := encodeB256U(binaryData) fmt.Printf("[%s]\t", text) // decode and check: decodedData := decodeB256U(text) if !bytes.Equal(binaryData, decodedData) { panic("check failed") } } }
9e161cc489321f8ecb2b28ac43abeec9
{ "intermediate": 0.4422287344932556, "beginner": 0.376207560300827, "expert": 0.18156367540359497 }
17,725
I'm writing C++ program with gRPC library. How do I use "grpc ChannelInterface" ?
b4f25367245f50112c8c3c6f55e64627
{ "intermediate": 0.853915274143219, "beginner": 0.0693168044090271, "expert": 0.0767679363489151 }
17,726
What does the below code do? await Metrics.aggregate([ { $match: { $and: [ { 'metrics.advertiserId': advertiserId, }, { 'dimensions.statTimeDay': { $gte: new Date(dateFrom), $lte: new Date(dateTo), }, }, ], }, }, { $group: { _id: { adId: '$dimensions.adId', campaignId: '$metrics.campaignId', adGroupId: '$metrics.adgroupId', }, adDetail: { $push: { adName: '$metrics.adName', adGroupName: '$metrics.adgroupName', campaignName: '$metrics.campaignName', date: '$dimensions.statTimeDay', impressions: '$metrics.impression', }, }, totalClicks: { $sum: { $toDouble: '$metrics.click', }, }, totalSpent: { $sum: { $toDouble: '$metrics.spend', }, }, totalImpressions: { $sum: { $toDouble: '$metrics.impressions', }, }, }, }, { $group: { _id: { campaignId: '$_id.campaignId', adGroupId: '$_id.adGroupId' }, ads: { $push: { adId: '$_id.adId', adName: { $first: '$adDetail.adName' }, adGroupName: { $first: '$adDetail.adGroupName' }, campaignName: { $first: '$adDetail.campaignName' }, date: { $first: '$adDetail.date' }, totalSpent: '$totalSpent', totalClicks: '$totalClicks', totalImpressions: '$totalImpressions', totalCpc: '$totalCpc', totalCpm: '$totalCpm', totalCtr: '$totalCtr', }, }, }, }, { $group: { _id: { campaignId: '$_id.campaignId' }, adGroups: { $push: { adGroupId: '$_id.adGroupId', ads: '$ads' } }, }, }, { $project: { _id: 0, campaignId: '$_id.campaignId', adGroups: 1 } }, ]);
25d241887f0da90b9859fbed864b40e5
{ "intermediate": 0.356114000082016, "beginner": 0.4363270699977875, "expert": 0.20755894482135773 }
17,727
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if buy_qty > sell_qty: signal.append('buy') elif sell_qty > buy_qty: signal.append('sell') else: signal.append('') return signal But time to time it giving me too much diference signals , its wrong solve it please
8dde48cbe5e57e170bead93dcbb234ff
{ "intermediate": 0.43320682644844055, "beginner": 0.29218345880508423, "expert": 0.2746097147464752 }
17,728
create table employee (id int, name varchar(20), salary int, department varchar(20)) insert into employee values (1, 'John', 100, 'IT'), (2, 'Sarah', 110, 'IT'), (3, 'Rich', 90, 'IT'), (4, 'Steve', 80, 'IT'), (5, 'Anna', 200, 'HR'), (6, 'Brandy', 180, 'HR'), (7, 'Nancy', 210, 'HR'),(8, 'Bob', 190, 'HR'),(9, 'Cody', 220, 'HR') , do the same result with window row_number function. self join with row_number = row_number + 1 based on those tables
d21c31ee8bc4ea46c8edb3768ecaf7b1
{ "intermediate": 0.39402255415916443, "beginner": 0.3588193655014038, "expert": 0.24715806543827057 }
17,729
create table employee (id int, name varchar(20), salary int, department varchar(20))insert into employee values (1, ‘John’, 100, ‘IT’), (2, ‘Sarah’, 110, ‘IT’), (3, ‘Rich’, 90, ‘IT’),(4, ‘Steve’, 80, ‘IT’), (5, ‘Anna’, 200, ‘HR’), (6, ‘Brandy’, 180, ‘HR’),(7, ‘Nancy’, 210, ‘HR’),(8, ‘Bob’, 190, ‘HR’),(9, ‘Cody’, 220, ‘HR’) , do the same result with window row_number function. self join with row_number = row_number + 1 based on those tables
725f5b314a45089cd63dadf0b6f2ddd1
{ "intermediate": 0.34863659739494324, "beginner": 0.3666818141937256, "expert": 0.2846815884113312 }
17,730
import {Input} from "@mui/material"; <Input type="number" value={summ} onChange={(e) => setSumm(+e.currentTarget.value)} /> нужно сделать инпут, чтобы то, что мы писали, цифры начинались справа, были прижаты к праавой стороне
ab4a391b897be09d0d2559f7a7f9c18b
{ "intermediate": 0.38616472482681274, "beginner": 0.34354978799819946, "expert": 0.2702855169773102 }
17,731
under debina, how to know a vxlan connection is established ?
b02c01614658b9155fbdf9b70eecac5f
{ "intermediate": 0.3719981014728546, "beginner": 0.15551479160785675, "expert": 0.4724871814250946 }
17,732
build spring boot authentication using ldap
4de39faca200730f5750309c9dbcfcec
{ "intermediate": 0.43624168634414673, "beginner": 0.13239328563213348, "expert": 0.43136507272720337 }
17,733
Development of a database for the subject area "Horse racing" Conduct an analysis of the subject area according to the following description: The information system of the club requires automation for racing enthusiasts. The information system should contain information about horses, their owners, jockeys (riders). Also, competitions are held in the club from time to time, it is necessary to form a database for storing information on each competition held.
13f496d5b8b26b6e7f97932bd1c47aa0
{ "intermediate": 0.3864409327507019, "beginner": 0.2397436499595642, "expert": 0.3738154172897339 }
17,734
I have a start date in A1 and an end date in B1 I want a formula in C1 that will calculate the number of weekend days between the start and end date
b2422052c5e7ac2caa7cff2b7eb2c7dd
{ "intermediate": 0.42125168442726135, "beginner": 0.2050458937883377, "expert": 0.3737024664878845 }
17,735
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if buy_qty > sell_qty: signal.append('buy') elif sell_qty > buy_qty: signal.append('sell') else: signal.append('') return signal Can you add in my algorithm some parameters : if buy_qty > sell_qty more than 10% signal.append('buy') elif sell_qty > buy_qty more than 10 % signal.append('sell') else signal.append('')
b8883774c6aa79a7cf3a1ed7aa8c5012
{ "intermediate": 0.27022069692611694, "beginner": 0.19654501974582672, "expert": 0.5332343578338623 }
17,736
Given two integers a and b, answer the sign of the product of a, a+1, ..., b. Input Two integers a and b separated by space. Output If the product is positive, output 1. If it is zero, output 0. If it is negative, output -1. Constraints -10^10 ≤ a ≤ b ≤ 10^10 Example Input 3 5 Output 1 ... Please solve with C# code
b2e9e4286a72f920b3c4c4f716864e36
{ "intermediate": 0.39352947473526, "beginner": 0.3105192482471466, "expert": 0.29595130681991577 }
17,737
Android разница между RecycleView и LisTView пиши на языке Kotlin
2de2270373031dbaf0199bc3dd78a3da
{ "intermediate": 0.5453824400901794, "beginner": 0.18294747173786163, "expert": 0.27167007327079773 }
17,738
how to limit quaternion rotation to 360 degree in c# ?
b9fa5182b4d8ca1fb6bf722df71c7f21
{ "intermediate": 0.49107059836387634, "beginner": 0.18346384167671204, "expert": 0.3254655599594116 }
17,739
if I want to work as a front end developer what are the requierments ?
4ba6e10d8d3ce09e38f0446058b878b0
{ "intermediate": 0.5021805167198181, "beginner": 0.3001679480075836, "expert": 0.19765156507492065 }
17,740
Hi, please write python code ro calculate prime numbers
9adca6d08f519e49982ffa805f4c42b1
{ "intermediate": 0.26891788840293884, "beginner": 0.13684092462062836, "expert": 0.594241201877594 }
17,741
How can I add an Active Directory group to the sudoers on Redhat Linux 8?
5a0a3691cc6ef9058374e99e7b40a1a9
{ "intermediate": 0.4396890103816986, "beginner": 0.2621929347515106, "expert": 0.29811805486679077 }
17,742
func lineIndexAtPosition(_ position: Int) -> Int { // Check for cached line let lines = lines if editedLine != nil { if NSLocationInRange(position, editedLine!.range) { let i = lines.firstIndex(of: editedLine!) if i != nil { return i! } } var i = lines.firstIndex(of: editedLine!) ?? 0 while true { // Inspect next line (currentLine + 1), currentLine + 2... if increasesPosition ? i < lines.count : i > 0 { let line = lines[i] if NSLocationInRange(position, line.range) { editedLine = line return i } increasesPosition ? (i += 1) : (i -= 1) } else { increasesPosition = false break // Don't go out of range } } } for i in 0..<lines.count { let line = lines[i] if NSLocationInRange(position, line.range) { editedLine = line return i } } NSLog("ERROR! Line not found") return 0 }
56378c7b815867fc63461e98ecf18af7
{ "intermediate": 0.37603914737701416, "beginner": 0.37763047218322754, "expert": 0.2463303655385971 }
17,743
this is my code. there is an error about not being able to find a gpu. fix it: from IPython.display import clear_output from pathlib import Path from ray import tune, air from ray.air import session, Checkpoint from ray.tune.schedulers import PopulationBasedTraining from torch.optim.lr_scheduler import StepLR from torch.utils.data import Dataset, DataLoader from torchvision.models import resnet50 from tqdm import tqdm import cv2 import json import math import numpy as np import optuna import os import random import ray import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms # Set Up device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Set a random seed for torch seed = 13 torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # If using multiple GPUs np.random.seed(seed) random.seed(seed) # Additional configurations for deterministic behavior on CUDA devices torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False data_path = '/workspaces/local_dev/Images/Training' validation_path = '/workspaces/local_dev/Images/Validation' model_name = 'rotnet_resnet50v2' # Training Parameters num_samples = 100 # None # Number of samples used for training. If None then all images # None # Number of samples used for validation. If None then all images num_val_samples = 25 # Tuple defining the input image shape (height, width) input_shape = (224, 224) num_classes = 4 # The possible rotation angles: 0, 90, 180, 270 # Optuna Optimization Parameters n_trials = 5 # Number of Optuna Trials learning_rate_options = (1e-5, 1e-1) # Learning rate for the optimizer batch_size_options = [8, 16] # Batch size for training num_epochs_options = (5, 5) # Number of epochs to train the model for weight_decay_options = (1e-6, 0.1) dropout_rate_options = (0.001, 0.5) # Create output folder if it doesn't exist output_folder = 'models' Path(output_folder).mkdir(parents=True, exist_ok=True) # Define Defs # Model definition class RotNetModel(nn.Module): def __init__(self, num_classes): super(RotNetModel, self).__init__() self.resnet = resnet50(weights=True) self.resnet.fc = nn.Linear(2048, num_classes) def forward(self, x): return self.resnet(x) # Error Function def angle_difference(x, y): """ Calculate minimum difference between two angles. """ return 180 - abs(abs(x - y) - 180) def angle_error(y_true, y_pred): """ Calculate the mean difference between the true angles and the predicted angles. """ diff = angle_difference(y_true, y_pred) return torch.mean(torch.abs(diff.float())) # Rotation Related def rotate(image, angle): """ Rotates an OpenCV 2 / NumPy image about its center by the given angle (in degrees). """ center = (image.shape[1] / 2, image.shape[0] / 2) rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0) return cv2.warpAffine(image, rot_mat, (image.shape[1], image.shape[0]), flags=cv2.INTER_LINEAR) def largest_rotated_rect(w, h, angle): """ Given a rectangle of size wxh that has been rotated by 'angle' (in radians), computes the width and height of the largest possible axis-aligned rectangle within the rotated rectangle. Original JS code by 'Andri' and Magnus Hoff from Stack Overflow Converted to Python by Aaron Snoswell Source: http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ quadrant = int(math.floor(angle / (math.pi / 2))) & 3 sign_alpha = angle if ((quadrant & 1) == 0) else math.pi - angle alpha = (sign_alpha % math.pi + math.pi) % math.pi bb_w = w * math.cos(alpha) + h * math.sin(alpha) bb_h = w * math.sin(alpha) + h * math.cos(alpha) gamma = math.atan2(bb_w, bb_w) if (w < h) else math.atan2(bb_w, bb_w) delta = math.pi - alpha - gamma length = h if (w < h) else w d = length * math.cos(alpha) a = d * math.sin(alpha) / math.sin(delta) y = a * math.cos(gamma) x = y * math.tan(gamma) return ( bb_w - 2 * x, bb_h - 2 * y ) def crop_around_center(image, width, height): """ Given a NumPy / OpenCV 2 image, crops it to the given width and height, around it's centre point Source: http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ image_size = (image.shape[1], image.shape[0]) image_center = (int(image_size[0] * 0.5), int(image_size[1] * 0.5)) if (width > image_size[0]): width = image_size[0] if (height > image_size[1]): height = image_size[1] x1 = int(image_center[0] - width * 0.5) x2 = int(image_center[0] + width * 0.5) y1 = int(image_center[1] - height * 0.5) y2 = int(image_center[1] + height * 0.5) return image[y1:y2, x1:x2] def crop_largest_rectangle(image, angle, height, width): """ Crop around the center the largest possible rectangle found with largest_rotated_rect. """ return crop_around_center( image, *largest_rotated_rect( width, height, math.radians(angle) ) ) def generate_rotated_image(image, angle, size=None, crop_center=False, crop_largest_rect=False): """ Generate a valid rotated image for the RotNetDataGenerator. If the image is rectangular, the crop_center option should be used to make it square. To crop out the black borders after rotation, use the crop_largest_rect option. To resize the final image, use the size option. """ height, width = image.shape[:2] if crop_center: if width < height: height = width else: width = height image = rotate(image, angle) if crop_largest_rect: image = crop_largest_rectangle(image, angle, height, width) if size: image = cv2.resize(image, size) return image def get_filenames(path, num_samples=None): image_paths = [] # Recursively traverse the directory structure for root, _, filenames in os.walk(path): for filename in filenames: image_paths.append(os.path.join(root, filename)) # Use all available images if num_samples is not provided if num_samples is None: train_filenames = image_paths else: # Randomly select num_samples images train_filenames = random.sample( image_paths, min(num_samples, len(image_paths))) # Shuffle the train_filenames list random.shuffle(train_filenames) return train_filenames # Dataset class for RotNet data class RotNetDataset(Dataset): def __init__(self, filenames, num_samples, input_shape, transform=None): self.filenames = filenames self.num_samples = num_samples self.input_shape = input_shape self.transform = transform def __len__(self): if self.num_samples is None: return len(self.filenames) else: return min(self.num_samples, len(self.filenames)) def __getitem__(self, idx): image = cv2.imread(self.filenames[idx]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) rotation_angle = random.choice([0, 90, 180, 270]) # Map rotation angles to class indices (0, 1, 2, 3) class_index = rotation_angle // 90 # 0, 1, 2, 3 rotated_image = generate_rotated_image( image, rotation_angle, size=self.input_shape, crop_center=True, crop_largest_rect=True ) sample = {'image': rotated_image, 'angle': class_index} if self.transform: sample['image'] = self.transform(sample['image']) return sample # Define transforms transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(input_shape), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # Run def setup_training(data_path, validation_path, num_samples, num_val_samples): train_filenames = get_filenames(data_path, num_samples) validation_filenames = get_filenames(validation_path, num_val_samples) print(len(train_filenames), 'train samples') print(len(validation_filenames), 'validation samples') batch_size = 8 train_dataset = RotNetDataset( train_filenames, num_samples, input_shape, transform=transform) train_dataloader = DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=2) validation_Data = RotNetDataset( validation_filenames, num_samples, input_shape, transform=transform) validation_dataloader = DataLoader( validation_Data, batch_size=batch_size, shuffle=False, num_workers=2) model = RotNetModel(num_classes=num_classes).to(device) optimizer = optim.SGD( model.parameters(), lr=0.01, # Default learning rate momentum=0.9, # Default momentum ) return train_dataloader, validation_dataloader, model, optimizer def train_model(config, checkpoint_dir=None): train_dataloader, validation_dataloader, model, optimizer = setup_training( data_path, validation_path, num_samples, num_val_samples) criterion = torch.nn.CrossEntropyLoss() if checkpoint_dir: checkpoint_dict = session.get_checkpoint(checkpoint_dir) if checkpoint_dict: model.load_state_dict(checkpoint_dict["model_state_dict"]) optimizer.load_state_dict(checkpoint_dict["optimizer_state_dict"]) step = 1 while True: model.train() running_loss = 0.0 for i, data in enumerate(train_dataloader, 0): inputs, labels = data['image'].to(device), data['angle'].to(device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() epoch_loss = running_loss / len(train_dataloader) # Placeholder accuracy calculation acc = 0.0 checkpoint = None if step % config["checkpoint_interval"] == 0: checkpoint = Checkpoint.from_dict({ "step": step, "model_state_dict": model.state_dict(), "optimizer_state_dict": optimizer.state_dict(), }) session.report( {"mean_accuracy": acc, "lr": config["lr"]}, checkpoint=checkpoint ) step += 1 perturbation_interval = 5 scheduler = PopulationBasedTraining( time_attr="training_iteration", perturbation_interval=perturbation_interval, metric="mean_accuracy", mode="max", hyperparam_mutations={ # distribution for resampling "lr": tune.uniform(0.0001, 1), # allow perturbations within this set of categorical values "momentum": [0.8, 0.9, 0.99], }, ) if ray.is_initialized(): ray.shutdown() ray.init() tuner = tune.Tuner( train_model, run_config=air.RunConfig( name="pbt_test", # Stop when we've reached a threshold accuracy, or a maximum # training_iteration, whichever comes first stop={"mean_accuracy": 0.96, "training_iteration": 50}, verbose=1, checkpoint_config=air.CheckpointConfig( checkpoint_score_attribute="mean_accuracy", num_to_keep=4, ), storage_path="/tmp/ray_results", ), tune_config=tune.TuneConfig( scheduler=scheduler, num_samples=4, ), param_space={ "lr": tune.uniform(0.001, 1), "momentum": tune.uniform(0.001, 1), "checkpoint_interval": perturbation_interval, }, ) results_grid = tuner.fit()
5375a2412eee8bf72f800d934c3db38a
{ "intermediate": 0.34354957938194275, "beginner": 0.36093154549598694, "expert": 0.2955188453197479 }
17,744
This error message indicates that there is an issue with the get_checkpoint() function in your code. The function is defined to not take any positional arguments, but it is being called with one argument. To fix this issue, you need to ensure that the get_checkpoint() function is correctly defined and called without any arguments. Double-check the implementation of the get_checkpoint() function and make sure it does not expect any arguments. If you are using a library or framework that defines the get_checkpoint() function, you may need to consult the documentation or example code to ensure you are using it correctly. Once you have fixed the get_checkpoint() function, you can retry running your code and see if the error is resolved. from IPython.display import clear_output from pathlib import Path from ray import tune, air from ray.air import session, Checkpoint from ray.tune.schedulers import PopulationBasedTraining from torch.optim.lr_scheduler import StepLR from torch.utils.data import Dataset, DataLoader from torchvision.models import resnet50 from tqdm import tqdm import cv2 import json import math import numpy as np import optuna import os import random import ray import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms # Set Up #!device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') device = torch.device('cpu') RAY_USE_XRAY=1 # Set a random seed for torch seed = 13 torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # If using multiple GPUs np.random.seed(seed) random.seed(seed) # Additional configurations for deterministic behavior on CUDA devices torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False data_path = '/workspaces/local_dev/Images/Training' validation_path = '/workspaces/local_dev/Images/Validation' model_name = 'rotnet_resnet50v2' # Training Parameters num_samples = 100 # None # Number of samples used for training. If None then all images # None # Number of samples used for validation. If None then all images num_val_samples = 25 # Tuple defining the input image shape (height, width) input_shape = (224, 224) num_classes = 4 # The possible rotation angles: 0, 90, 180, 270 # Optuna Optimization Parameters n_trials = 5 # Number of Optuna Trials learning_rate_options = (1e-5, 1e-1) # Learning rate for the optimizer batch_size_options = [8, 16] # Batch size for training num_epochs_options = (5, 5) # Number of epochs to train the model for weight_decay_options = (1e-6, 0.1) dropout_rate_options = (0.001, 0.5) # Create output folder if it doesn't exist output_folder = 'models' Path(output_folder).mkdir(parents=True, exist_ok=True) # Define Defs # Model definition class RotNetModel(nn.Module): def __init__(self, num_classes): super(RotNetModel, self).__init__() self.resnet = resnet50(weights=True) self.resnet.fc = nn.Linear(2048, num_classes) def forward(self, x): return self.resnet(x) # Error Function def angle_difference(x, y): """ Calculate minimum difference between two angles. """ return 180 - abs(abs(x - y) - 180) def angle_error(y_true, y_pred): """ Calculate the mean difference between the true angles and the predicted angles. """ diff = angle_difference(y_true, y_pred) return torch.mean(torch.abs(diff.float())) # Rotation Related def rotate(image, angle): """ Rotates an OpenCV 2 / NumPy image about its center by the given angle (in degrees). """ center = (image.shape[1] / 2, image.shape[0] / 2) rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0) return cv2.warpAffine(image, rot_mat, (image.shape[1], image.shape[0]), flags=cv2.INTER_LINEAR) def largest_rotated_rect(w, h, angle): """ Given a rectangle of size wxh that has been rotated by 'angle' (in radians), computes the width and height of the largest possible axis-aligned rectangle within the rotated rectangle. Original JS code by 'Andri' and Magnus Hoff from Stack Overflow Converted to Python by Aaron Snoswell Source: http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ quadrant = int(math.floor(angle / (math.pi / 2))) & 3 sign_alpha = angle if ((quadrant & 1) == 0) else math.pi - angle alpha = (sign_alpha % math.pi + math.pi) % math.pi bb_w = w * math.cos(alpha) + h * math.sin(alpha) bb_h = w * math.sin(alpha) + h * math.cos(alpha) gamma = math.atan2(bb_w, bb_w) if (w < h) else math.atan2(bb_w, bb_w) delta = math.pi - alpha - gamma length = h if (w < h) else w d = length * math.cos(alpha) a = d * math.sin(alpha) / math.sin(delta) y = a * math.cos(gamma) x = y * math.tan(gamma) return ( bb_w - 2 * x, bb_h - 2 * y ) def crop_around_center(image, width, height): """ Given a NumPy / OpenCV 2 image, crops it to the given width and height, around it's centre point Source: http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ image_size = (image.shape[1], image.shape[0]) image_center = (int(image_size[0] * 0.5), int(image_size[1] * 0.5)) if (width > image_size[0]): width = image_size[0] if (height > image_size[1]): height = image_size[1] x1 = int(image_center[0] - width * 0.5) x2 = int(image_center[0] + width * 0.5) y1 = int(image_center[1] - height * 0.5) y2 = int(image_center[1] + height * 0.5) return image[y1:y2, x1:x2] def crop_largest_rectangle(image, angle, height, width): """ Crop around the center the largest possible rectangle found with largest_rotated_rect. """ return crop_around_center( image, *largest_rotated_rect( width, height, math.radians(angle) ) ) def generate_rotated_image(image, angle, size=None, crop_center=False, crop_largest_rect=False): """ Generate a valid rotated image for the RotNetDataGenerator. If the image is rectangular, the crop_center option should be used to make it square. To crop out the black borders after rotation, use the crop_largest_rect option. To resize the final image, use the size option. """ height, width = image.shape[:2] if crop_center: if width < height: height = width else: width = height image = rotate(image, angle) if crop_largest_rect: image = crop_largest_rectangle(image, angle, height, width) if size: image = cv2.resize(image, size) return image def get_filenames(path, num_samples=None): image_paths = [] # Recursively traverse the directory structure for root, _, filenames in os.walk(path): for filename in filenames: image_paths.append(os.path.join(root, filename)) # Use all available images if num_samples is not provided if num_samples is None: train_filenames = image_paths else: # Randomly select num_samples images train_filenames = random.sample( image_paths, min(num_samples, len(image_paths))) # Shuffle the train_filenames list random.shuffle(train_filenames) return train_filenames # Dataset class for RotNet data class RotNetDataset(Dataset): def __init__(self, filenames, num_samples, input_shape, transform=None): self.filenames = filenames self.num_samples = num_samples self.input_shape = input_shape self.transform = transform def __len__(self): if self.num_samples is None: return len(self.filenames) else: return min(self.num_samples, len(self.filenames)) def __getitem__(self, idx): image = cv2.imread(self.filenames[idx]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) rotation_angle = random.choice([0, 90, 180, 270]) # Map rotation angles to class indices (0, 1, 2, 3) class_index = rotation_angle // 90 # 0, 1, 2, 3 rotated_image = generate_rotated_image( image, rotation_angle, size=self.input_shape, crop_center=True, crop_largest_rect=True ) sample = {'image': rotated_image, 'angle': class_index} if self.transform: sample['image'] = self.transform(sample['image']) return sample # Define transforms transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(input_shape), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # Run def setup_training(data_path, validation_path, num_samples, num_val_samples): train_filenames = get_filenames(data_path, num_samples) validation_filenames = get_filenames(validation_path, num_val_samples) print(len(train_filenames), 'train samples') print(len(validation_filenames), 'validation samples') batch_size = 8 train_dataset = RotNetDataset( train_filenames, num_samples, input_shape, transform=transform) train_dataloader = DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=1) validation_Data = RotNetDataset( validation_filenames, num_samples, input_shape, transform=transform) validation_dataloader = DataLoader( validation_Data, batch_size=batch_size, shuffle=False, num_workers=1) model = RotNetModel(num_classes=num_classes).to(device) optimizer = optim.SGD( model.parameters(), lr=0.01, # Default learning rate momentum=0.9, # Default momentum ) return train_dataloader, validation_dataloader, model, optimizer def train_model(config, checkpoint_dir=None): train_dataloader, validation_dataloader, model, optimizer = setup_training( data_path, validation_path, num_samples, num_val_samples) criterion = torch.nn.CrossEntropyLoss() if checkpoint_dir: checkpoint_dict = session.get_checkpoint(checkpoint_dir) if checkpoint_dict: model.load_state_dict(checkpoint_dict["model_state_dict"]) optimizer.load_state_dict(checkpoint_dict["optimizer_state_dict"]) step = 1 while True: model.train() running_loss = 0.0 for i, data in enumerate(train_dataloader, 0): inputs, labels = data['image'].to(device), data['angle'].to(device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() epoch_loss = running_loss / len(train_dataloader) # Placeholder accuracy calculation acc = 0.0 checkpoint = None if step % config["checkpoint_interval"] == 0: checkpoint = Checkpoint.from_dict({ "step": step, "model_state_dict": model.state_dict(), "optimizer_state_dict": optimizer.state_dict(), }) session.report( {"mean_accuracy": acc, "lr": config["lr"]}, checkpoint=checkpoint ) step += 1 perturbation_interval = 5 scheduler = PopulationBasedTraining( time_attr="training_iteration", perturbation_interval=perturbation_interval, metric="mean_accuracy", mode="max", hyperparam_mutations={ # distribution for resampling "lr": tune.uniform(0.0001, 1), # allow perturbations within this set of categorical values "momentum": [0.8, 0.9, 0.99], }, ) if ray.is_initialized(): ray.shutdown() ray.init() tuner = tune.Tuner( train_model, run_config=air.RunConfig( name="pbt_test", # Stop when we've reached a threshold accuracy, or a maximum # training_iteration, whichever comes first stop={"mean_accuracy": 0.96, "training_iteration": 50}, verbose=1, checkpoint_config=air.CheckpointConfig( checkpoint_score_attribute="mean_accuracy", num_to_keep=4, ), storage_path="/tmp/ray_results", ), tune_config=tune.TuneConfig( scheduler=scheduler, num_samples=4, ), param_space={ "lr": tune.uniform(0.001, 1), "momentum": tune.uniform(0.001, 1), "checkpoint_interval": perturbation_interval, }, ) results_grid = tuner.fit()
2fc460187cb162995fdd3501d70fdb53
{ "intermediate": 0.29239028692245483, "beginner": 0.4913192689418793, "expert": 0.2162904441356659 }
17,745
fix the checkpoint from IPython.display import clear_output from pathlib import Path from ray import tune, air from ray.air import session, Checkpoint from ray.tune.schedulers import PopulationBasedTraining from torch.optim.lr_scheduler import StepLR from torch.utils.data import Dataset, DataLoader from torchvision.models import resnet50 from tqdm import tqdm import cv2 import json import math import numpy as np import optuna import os import random import ray import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms # Set Up #!device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') device = torch.device('cpu') RAY_USE_XRAY=1 # Set a random seed for torch seed = 13 torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # If using multiple GPUs np.random.seed(seed) random.seed(seed) # Additional configurations for deterministic behavior on CUDA devices torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False data_path = '/workspaces/local_dev/Images/Training' validation_path = '/workspaces/local_dev/Images/Validation' model_name = 'rotnet_resnet50v2' # Training Parameters num_samples = 100 # None # Number of samples used for training. If None then all images # None # Number of samples used for validation. If None then all images num_val_samples = 25 # Tuple defining the input image shape (height, width) input_shape = (224, 224) num_classes = 4 # The possible rotation angles: 0, 90, 180, 270 # Optuna Optimization Parameters n_trials = 5 # Number of Optuna Trials learning_rate_options = (1e-5, 1e-1) # Learning rate for the optimizer batch_size_options = [8, 16] # Batch size for training num_epochs_options = (5, 5) # Number of epochs to train the model for weight_decay_options = (1e-6, 0.1) dropout_rate_options = (0.001, 0.5) # Create output folder if it doesn't exist output_folder = 'models' Path(output_folder).mkdir(parents=True, exist_ok=True) # Define Defs # Model definition class RotNetModel(nn.Module): def __init__(self, num_classes): super(RotNetModel, self).__init__() self.resnet = resnet50(weights=True) self.resnet.fc = nn.Linear(2048, num_classes) def forward(self, x): return self.resnet(x) # Error Function def angle_difference(x, y): """ Calculate minimum difference between two angles. """ return 180 - abs(abs(x - y) - 180) def angle_error(y_true, y_pred): """ Calculate the mean difference between the true angles and the predicted angles. """ diff = angle_difference(y_true, y_pred) return torch.mean(torch.abs(diff.float())) # Rotation Related def rotate(image, angle): """ Rotates an OpenCV 2 / NumPy image about its center by the given angle (in degrees). """ center = (image.shape[1] / 2, image.shape[0] / 2) rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0) return cv2.warpAffine(image, rot_mat, (image.shape[1], image.shape[0]), flags=cv2.INTER_LINEAR) def largest_rotated_rect(w, h, angle): """ Given a rectangle of size wxh that has been rotated by 'angle' (in radians), computes the width and height of the largest possible axis-aligned rectangle within the rotated rectangle. Original JS code by 'Andri' and Magnus Hoff from Stack Overflow Converted to Python by Aaron Snoswell Source: http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ quadrant = int(math.floor(angle / (math.pi / 2))) & 3 sign_alpha = angle if ((quadrant & 1) == 0) else math.pi - angle alpha = (sign_alpha % math.pi + math.pi) % math.pi bb_w = w * math.cos(alpha) + h * math.sin(alpha) bb_h = w * math.sin(alpha) + h * math.cos(alpha) gamma = math.atan2(bb_w, bb_w) if (w < h) else math.atan2(bb_w, bb_w) delta = math.pi - alpha - gamma length = h if (w < h) else w d = length * math.cos(alpha) a = d * math.sin(alpha) / math.sin(delta) y = a * math.cos(gamma) x = y * math.tan(gamma) return ( bb_w - 2 * x, bb_h - 2 * y ) def crop_around_center(image, width, height): """ Given a NumPy / OpenCV 2 image, crops it to the given width and height, around it's centre point Source: http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ image_size = (image.shape[1], image.shape[0]) image_center = (int(image_size[0] * 0.5), int(image_size[1] * 0.5)) if (width > image_size[0]): width = image_size[0] if (height > image_size[1]): height = image_size[1] x1 = int(image_center[0] - width * 0.5) x2 = int(image_center[0] + width * 0.5) y1 = int(image_center[1] - height * 0.5) y2 = int(image_center[1] + height * 0.5) return image[y1:y2, x1:x2] def crop_largest_rectangle(image, angle, height, width): """ Crop around the center the largest possible rectangle found with largest_rotated_rect. """ return crop_around_center( image, *largest_rotated_rect( width, height, math.radians(angle) ) ) def generate_rotated_image(image, angle, size=None, crop_center=False, crop_largest_rect=False): """ Generate a valid rotated image for the RotNetDataGenerator. If the image is rectangular, the crop_center option should be used to make it square. To crop out the black borders after rotation, use the crop_largest_rect option. To resize the final image, use the size option. """ height, width = image.shape[:2] if crop_center: if width < height: height = width else: width = height image = rotate(image, angle) if crop_largest_rect: image = crop_largest_rectangle(image, angle, height, width) if size: image = cv2.resize(image, size) return image def get_filenames(path, num_samples=None): image_paths = [] # Recursively traverse the directory structure for root, _, filenames in os.walk(path): for filename in filenames: image_paths.append(os.path.join(root, filename)) # Use all available images if num_samples is not provided if num_samples is None: train_filenames = image_paths else: # Randomly select num_samples images train_filenames = random.sample( image_paths, min(num_samples, len(image_paths))) # Shuffle the train_filenames list random.shuffle(train_filenames) return train_filenames # Dataset class for RotNet data class RotNetDataset(Dataset): def __init__(self, filenames, num_samples, input_shape, transform=None): self.filenames = filenames self.num_samples = num_samples self.input_shape = input_shape self.transform = transform def __len__(self): if self.num_samples is None: return len(self.filenames) else: return min(self.num_samples, len(self.filenames)) def __getitem__(self, idx): image = cv2.imread(self.filenames[idx]) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) rotation_angle = random.choice([0, 90, 180, 270]) # Map rotation angles to class indices (0, 1, 2, 3) class_index = rotation_angle // 90 # 0, 1, 2, 3 rotated_image = generate_rotated_image( image, rotation_angle, size=self.input_shape, crop_center=True, crop_largest_rect=True ) sample = {'image': rotated_image, 'angle': class_index} if self.transform: sample['image'] = self.transform(sample['image']) return sample # Define transforms transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(input_shape), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # Run def setup_training(data_path, validation_path, num_samples, num_val_samples): train_filenames = get_filenames(data_path, num_samples) validation_filenames = get_filenames(validation_path, num_val_samples) print(len(train_filenames), 'train samples') print(len(validation_filenames), 'validation samples') batch_size = 8 train_dataset = RotNetDataset( train_filenames, num_samples, input_shape, transform=transform) train_dataloader = DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=1) validation_Data = RotNetDataset( validation_filenames, num_samples, input_shape, transform=transform) validation_dataloader = DataLoader( validation_Data, batch_size=batch_size, shuffle=False, num_workers=1) model = RotNetModel(num_classes=num_classes).to(device) optimizer = optim.SGD( model.parameters(), lr=0.01, # Default learning rate momentum=0.9, # Default momentum ) return train_dataloader, validation_dataloader, model, optimizer def train_model(config, checkpoint_dir=None): train_dataloader, validation_dataloader, model, optimizer = setup_training( data_path, validation_path, num_samples, num_val_samples) criterion = torch.nn.CrossEntropyLoss() if checkpoint_dir: checkpoint_dict = session.get_checkpoint() if checkpoint_dict: model.load_state_dict(checkpoint_dict["model_state_dict"]) optimizer.load_state_dict(checkpoint_dict["optimizer_state_dict"]) step = 1 while True: model.train() running_loss = 0.0 for i, data in enumerate(train_dataloader, 0): inputs, labels = data['image'].to(device), data['angle'].to(device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() epoch_loss = running_loss / len(train_dataloader) # Placeholder accuracy calculation acc = 0.0 checkpoint = Checkpoint.from_config(checkpoint_dir) if step % config["checkpoint_interval"] == 0: checkpoint = Checkpoint.from_dict({ "step": step, "model_state_dict": model.state_dict(), "optimizer_state_dict": optimizer.state_dict(), }) session.report( {"mean_accuracy": acc, "lr": config["lr"]}, checkpoint=checkpoint ) step += 1 perturbation_interval = 5 scheduler = PopulationBasedTraining( time_attr="training_iteration", perturbation_interval=perturbation_interval, metric="mean_accuracy", mode="max", hyperparam_mutations={ # distribution for resampling "lr": tune.uniform(0.0001, 1), # allow perturbations within this set of categorical values "momentum": [0.8, 0.9, 0.99], }, ) if ray.is_initialized(): ray.shutdown() ray.init() tuner = tune.Tuner( train_model, run_config=air.RunConfig( name="pbt_test", # Stop when we've reached a threshold accuracy, or a maximum # training_iteration, whichever comes first stop={"mean_accuracy": 0.96, "training_iteration": 50}, verbose=1, checkpoint_config=air.CheckpointConfig( checkpoint_score_attribute="mean_accuracy", num_to_keep=4, ), storage_path="/tmp/ray_results", ), tune_config=tune.TuneConfig( scheduler=scheduler, num_samples=4, ), param_space={ "lr": tune.uniform(0.001, 1), "momentum": tune.uniform(0.001, 1), "checkpoint_interval": perturbation_interval, }, ) results_grid = tuner.fit()
4cbb8debe4d034325f6e281713565101
{ "intermediate": 0.2749863266944885, "beginner": 0.33180201053619385, "expert": 0.3932117223739624 }
17,746
(train_model pid=167735) /opt/conda/lib/python3.10/site-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=ResNet50_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet50_Weights.DEFAULT` to get the most up-to-date weights. (train_model pid=167735) warnings.warn(msg) 2023-08-16 00:18:24,525 ERROR tune_controller.py:911 -- Trial task failed for trial train_model_573ab_00002 Traceback (most recent call last): File "/opt/conda/lib/python3.10/site-packages/ray/air/execution/_internal/event_manager.py", line 110, in resolve_future result = ray.get(future) File "/opt/conda/lib/python3.10/site-packages/ray/_private/auto_init_hook.py", line 24, in auto_init_wrapper return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/ray/_private/client_mode_hook.py", line 103, in wrapper return func(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/ray/_private/worker.py", line 2524, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError(AttributeError): ray::ImplicitFunc.train() (pid=167735, ip=172.17.0.2, actor_id=c5b7b4bf7972626db823fc7601000000, repr=train_model) File "/opt/conda/lib/python3.10/site-packages/ray/tune/trainable/trainable.py", line 375, in train raise skipped from exception_cause(skipped) File "/opt/conda/lib/python3.10/site-packages/ray/tune/trainable/function_trainable.py", line 349, in entrypoint return self._trainable_func( File "/opt/conda/lib/python3.10/site-packages/ray/tune/trainable/function_trainable.py", line 666, in _trainable_func output = fn() File "/tmp/ipykernel_113847/2395570216.py", line 345, in train_model AttributeError: type object 'Checkpoint' has no attribute 'from_config'
b07900e0fb57da0c16710cd0dc54c213
{ "intermediate": 0.42790690064430237, "beginner": 0.349139004945755, "expert": 0.2229541391134262 }
17,747
can you make this page load the audio and video before the user actually clicks the button? make the video it be paused at 0:00 in the background and audio aswell. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width" ="device-width," initial-scale="1.0" /> <title>brrt.cash</title> <style> #blur { position: fixed; top: 0; left: 0; width: 100%; height: 100%; backdrop-filter: blur(10px); z-index: 9999; display: flex; justify-content: center; align-items: center; flex-direction: column; cursor: pointer; } #blur h1 { font-size: 30px; } #video-background { position: fixed; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; opacity: 0; transition: opacity 1s; } </style> </head> <body> HEYYYYY <h1>hello!!!!!!</h1> <div id="blur"> <h1>Click to Enter</h1> </div> <div id="videoContainer"> <video id="video-background" autoplay loop muted> <source src="media/Ambition For Cash.mp4" type=video/mp4> </video> </div> <script src="js/musicVideo.js"></script> </body> </html> musicVideo.js window.onload = function () { var blur = document.getElementById("blur"); var video = document.getElementById("video-background"); blur.onclick = function () { blur.style.display = "none"; video.style.opacity = 1; var audio = new Audio("media/Ambition For Cash.mp3"); audio.loop = true; audio.play(); }; };
eb746e3c020f7e6aad3583271b4bc755
{ "intermediate": 0.3771228492259979, "beginner": 0.4090392589569092, "expert": 0.21383792161941528 }
17,748
npm star # Mark your favorite packages
1c79a3ddd5ba250e1fcb5c0c22450541
{ "intermediate": 0.35884758830070496, "beginner": 0.2419380098581314, "expert": 0.39921438694000244 }
17,749
c# DrawRoundRect
172c602c4da78ffa4907f4fe338270a2
{ "intermediate": 0.38408124446868896, "beginner": 0.3176937997341156, "expert": 0.2982249855995178 }
17,750
export default { methods: { // MeasureTools.destory(window.cesiumViewer) destory(){ let sy = new MeasureTools(window.cesiumViewer) sy.destroy() }, measurePolyLine(){ let sy =new MeasureTools(window.cesiumViewer) sy.measurePolyLine() }, measurePolygon(){ let sy =new MeasureTools(window.cesiumViewer) sy.measurePolygon() }, measureHeight(){ let sy =new MeasureTools(window.cesiumViewer) sy.measureHeight() }, } }将此段代码改为vue3的代码
575377f7f8f5b3a2d4544e6ecacd1ce7
{ "intermediate": 0.4152590334415436, "beginner": 0.31353580951690674, "expert": 0.27120518684387207 }
17,751
export const MeasureTools = (function (viewer){ this.getCollection = function () { return entityCollection; };}前端vue3引用这个getCollection函数
367d522589d5e46ff17514d712298e7c
{ "intermediate": 0.39128199219703674, "beginner": 0.3671124577522278, "expert": 0.24160559475421906 }
17,752
export const MeasureTools = (function (viewer){ this.getCollection = function () { return entityCollection; };}前端通过vue3的写法来使用getCollection函数
faf44094b4e0911b83977c49e8b39021
{ "intermediate": 0.3867682218551636, "beginner": 0.40657782554626465, "expert": 0.20665404200553894 }
17,753
import pyproj import numpy as np # 定义地理右手坐标系 projection = pyproj.Proj(proj='cart', ellps='WGS84', datum='WGS84') # 定义数学笛卡尔坐标系 cartesian_coords = np.array([[5.051966,1.606852,0.951975]]) # [x2, y2, z2], # … # [xn, yn, zn]]) cartesian_coords = [5.051966,1.606852,0.951975] # 转换坐标系 lon, lat, _ = projection(cartesian_coords[:,0], cartesian_coords[:,1], cartesian_coords[:,2]) # 输出地理右手坐标系坐标 for i in range(len(lon)): print("经度:{}".format(lon[i])) print("纬度:{}".format(lat[i])) print("---------") Traceback (most recent call last): File "e:\桌面\新建文件夹\1.py", line 15, in <module> lon, lat, _ = projection(cartesian_coords[:,0], cartesian_coords[:,1], cartesian_coords[:,2]) TypeError: list indices must be integers or slices, not tuple
ea169fe0983f472c5a143ab3256ea374
{ "intermediate": 0.46462494134902954, "beginner": 0.3560090959072113, "expert": 0.17936591804027557 }
17,754
Consider the following diagram representing a combinational digital circuit – each gate implements a Boolean function of its inputs and there are no cycles in the circuit. The numbers annotated on the gates represent the delay d through the gate, in nanoseconds. If the inputs of a gate are ready at time t, then the output is ready at time t+d. (a) How much time does such a circuit take to compute its primary outputs? For the example above, the maximum delay for E is 2+4+3=9, and for F is 2+4+2=8. Write a program to compute the delay of every primary output in a combinational circuit (defined as the earliest time when the output is ready), given the circuit representation and delay information of the individual gates. Input: Circuit file (see example file circuit.txt for diagram above) Input: Gate Delay file (see example file gate_delays.txt for diagram above) Output: Output Delay file (see example file output_delays.txt for diagram above) write this code in python.
04ecd8622e93fb8989cddda905205c6d
{ "intermediate": 0.41057977080345154, "beginner": 0.2688773572444916, "expert": 0.3205428421497345 }
17,755
Consider the following diagram representing a combinational digital circuit – each gate implements a Boolean function of its inputs and there are no cycles in the circuit. The numbers annotated on the gates represent the delay d through the gate, in nanoseconds. If the inputs of a gate are ready at time t, then the output is ready at time t+d. (a) How much time does such a circuit take to compute its primary outputs? For the example above, the maximum delay for E is 2+4+3=9, and for F is 2+4+2=8. Write a program to compute the delay of every primary output in a combinational circuit (defined as the earliest time when the output is ready), given the circuit representation and delay information of the individual gates. Input: Circuit file (see example file circuit.txt for diagram above) Input: Gate Delay file (see example file gate_delays.txt for diagram above) Output: Output Delay file (see example file output_delays.txt for diagram above) write this code in python
b39f46ec7dbe5332b1a3f076b6b3c584
{ "intermediate": 0.45707738399505615, "beginner": 0.27769047021865845, "expert": 0.26523205637931824 }
17,756
const addactiveChip = async () =>{ if(activeText.value){ activeChips.value.push(activeText.value); activeText.value = ''; const activechipValues = activeChips.value.map(item =>{ const [text, percentage] = item.split(',') return [text, parseInt(percentage)] }) console.log("这是活性方案",activechipValues) } }让activechipValues转换为dict的形式
78548056c4ab24783837601b9ee410da
{ "intermediate": 0.3378949463367462, "beginner": 0.37126126885414124, "expert": 0.29084375500679016 }
17,757
fn main() { tauri::Builder::default() .run(tauri::generate_context!()) .expect("error while running tauri application"); } please explain this code in detail
fd4b1e5b8f22554d237fe62ccc795052
{ "intermediate": 0.4870728850364685, "beginner": 0.40083059668540955, "expert": 0.11209649592638016 }
17,758
write animated modal window on react-native
bc105996f48eaf510da2abb8bbf2d22d
{ "intermediate": 0.39567938446998596, "beginner": 0.20816589891910553, "expert": 0.3961547315120697 }
17,759
Help me with Delphi code for working with INI AND DLL files ? Basic read write functionalities in Delphi code
48d424abfb7b13cb065d4c391c9eca80
{ "intermediate": 0.2394781857728958, "beginner": 0.7023162841796875, "expert": 0.05820556357502937 }
17,760
A suitable constructor for type 'HangFireApi.Apis.V1.Controllers.UrlWatchController' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments
aeedc3342ec762f31d37cc9ce28a5fd1
{ "intermediate": 0.5240904688835144, "beginner": 0.2117726355791092, "expert": 0.2641369104385376 }
17,761
i used router-link in angulat but give me page not found, despite when hit the url on browser worked
481bb6cacdc6c8c8269e4d47d9a6b239
{ "intermediate": 0.4799647033214569, "beginner": 0.2436973601579666, "expert": 0.27633795142173767 }
17,762
make a python script to l ook at every line in lol.txt and write a new file w here you put the times the string appeared i n t he original file next to the actual line in the order of most common to least.
a9adc28a4920013af4c225731d213e22
{ "intermediate": 0.41580191254615784, "beginner": 0.18505385518074036, "expert": 0.3991442322731018 }
17,763
напиши полную настройку мониторинга производительности Sentry performance для spring boot приложения, чтобы отображались основные метрики и информация о запросе
f75068d352dc202fa9833bbaf8c7ee31
{ "intermediate": 0.3241954743862152, "beginner": 0.20496973395347595, "expert": 0.4708348214626312 }
17,764
i want to add in the [router-link] values come from list one of this value is /products-list?category=%2Fflash-deal, so he redirect me to not found page how solve
0dd65a15207a44e931eee9f9cc4e41d8
{ "intermediate": 0.3560793101787567, "beginner": 0.2577643394470215, "expert": 0.3861563205718994 }
17,765
i have <a *ngFor="let item of featuredData" [routerLink]="dataItem?.data?.fields?.url?.value"> one of the url value is /products-list?category=%2Fflash-deal, so redirect to not-found page
94c6484086840b6ec7a87ebbf04d353c
{ "intermediate": 0.36650726199150085, "beginner": 0.30317550897598267, "expert": 0.3303171992301941 }
17,766
cx_freeze seems to generate a folder with all the dlls and the python packages that the generated executable depends on. Is there a way I can bundle all the binaries and depencies into one simple .exe that I can run from any machine without exporting all this dlls
9a1dc354f58eede1ca56ce2ff11e0ec6
{ "intermediate": 0.4442700147628784, "beginner": 0.2590130865573883, "expert": 0.29671692848205566 }
17,767
write animated bottom sheet with swipe to close by native utilities on react-native
577bd407c98e2cc868e12884aaba8461
{ "intermediate": 0.5112122893333435, "beginner": 0.24197246134281158, "expert": 0.24681513011455536 }
17,768
write code in java that perfroms method copy with javassist, and copy the method's annotations
b66284013c7883e1a6675105b66ad4ea
{ "intermediate": 0.5189971327781677, "beginner": 0.13623742759227753, "expert": 0.34476545453071594 }
17,769
in networking, do multicast need a router in order to operate ?
ebdad2d570b7ed61ab61be72d3de9d4c
{ "intermediate": 0.2867313027381897, "beginner": 0.36247682571411133, "expert": 0.350791871547699 }
17,770
check if the returned value in dataItem?.data?.fields?.url?.value need encoded in [routerlink]
d264b6241c86880b4c8a1f1581c2cded
{ "intermediate": 0.5668282508850098, "beginner": 0.18143494427204132, "expert": 0.25173676013946533 }
17,771
copy java method with its annotations in java
406dcce80d80b0bc53e0bd541f08ab4b
{ "intermediate": 0.43078795075416565, "beginner": 0.31939300894737244, "expert": 0.24981902539730072 }
17,772
fix code //Recreate {{range $name, $dls := .Dls}} {{- $name | printf "$freqs[%s]"}} = {{stringifyInts $dls}} euRan.Create(Frequencies) {{- $name | printf " $freqs[%s]"}} {{end}} for input data: { "SubNetwork": "Shymkent", "cellsGroupsLabels": [ "Kcell", "Tele2" ], "isLte": true, "Controller": "", "ManagementHost": "Alenm2", "Dls": { "Kcell": [ 6200, 150, 1302 ], "Tele2": [ 500, 1652, 1850 ] } }
cbabd705f4fa5bc946a849ddff1f9cd8
{ "intermediate": 0.3712092936038971, "beginner": 0.38712745904922485, "expert": 0.24166323244571686 }
17,773
fix template Go code: '''//Recreate {{range $name, $dls := .Dls}} {{- $name | printf "$freqs[%s]"}} = {{stringifyInts $dls}} euRan.Create(Frequencies) {{- $name | printf " $freqs[%s]"}} {{end}}''' And the input data is like this: '''{ "SubNetwork": "Shymkent", "cellsGroupsLabels": [ "Kcell", "Tele2" ], "isLte": true, "Controller": "", "ManagementHost": "Alenm2", "Dls": { "Kcell": [ 6200, 150, 1302 ], "Tele2": [ 500, 1652, 1850 ] } }'''
a12d8bc6931bb03e94809b9b5f3bc95c
{ "intermediate": 0.38580620288848877, "beginner": 0.30739593505859375, "expert": 0.3067978620529175 }
17,774
fix template Go code:
d24bcd42ad5c43e71b347a62f16ef359
{ "intermediate": 0.3172267973423004, "beginner": 0.30139094591140747, "expert": 0.3813822567462921 }
17,775
как прописать desired_capabilities appium-python-client-2.11.1 для windows приложения
57b04906733fb1da943cb746ca771750
{ "intermediate": 0.4018159806728363, "beginner": 0.25316694378852844, "expert": 0.34501707553863525 }
17,776
Scaffold-DbContext "Data Source=192.168.0.91;Initial Catalog=YiDoc;User ID=sa;Password=Password01!" Microsoft.EntityFrameworkCore.SqlServer -O Models -F 请把这个命令转成链接mysql的
867a0da421818f0330ec51af68707c1a
{ "intermediate": 0.6981960535049438, "beginner": 0.1556878238916397, "expert": 0.14611610770225525 }
17,777
Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".
3c43f8490678f7c93fea7001dee664ed
{ "intermediate": 0.3725873529911041, "beginner": 0.40739455819129944, "expert": 0.22001807391643524 }
17,778
Write the matlab code for making a step up counter counting from 1 to 9
ded300f41c513af767b095962639287d
{ "intermediate": 0.21254587173461914, "beginner": 0.10130824893712997, "expert": 0.6861459016799927 }
17,779
Write the matlab code for making a step up counter counting from 1 to 9
f35f42febebac6dea0d39949eab87fab
{ "intermediate": 0.21254587173461914, "beginner": 0.10130824893712997, "expert": 0.6861459016799927 }
17,780
как прописать direct_conntction для appium-python-client-2.11.1 для windows приложения python
c43a1210514e4ff9580857c8c4a5d8f5
{ "intermediate": 0.38555291295051575, "beginner": 0.2346048504114151, "expert": 0.37984225153923035 }
17,781
fetch everything in model using mongoose aggreagate
77c3053ef5bed49dbf3b953475e12ffb
{ "intermediate": 0.33926424384117126, "beginner": 0.24166780710220337, "expert": 0.419067919254303 }