row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
47,791
How do I create dosbox witchaven bot?
1271fd88b89fc39f29f460c079dee340
{ "intermediate": 0.3325476348400116, "beginner": 0.11483265459537506, "expert": 0.5526196956634521 }
47,792
<div> <p style="margin: 0; font-size: 14px"> <b style="position: absolute; top: 0; right: 0; margin-top: 1rem; margin-right: 1rem;"> <a href="https://admin.resources.osu.edu/otdi-web-hosting/dashboard-definitions/#webroot-01" target="_blank">Webroot</a>: {{ data.webroot }} </b> <br> <div style="position: absolute; top: 0; right: 0; margin-top: 2rem; margin-right: 1rem;" aria-label="Read more about storage (opens in new tab)" href="https://admin.resources.osu.edu/otdi-web-hosting/dashboard-definitions/#storage"> <a target="_blank" href="https://admin.resources.osu.edu/otdi-web-hosting/dashboard-definitions/#space-used">{{ (data.storageused / 1024 / 1024 / 1024).toFixed(2) + "GB" }} used</a> </div> </p> </div> vue no parsing error
60b7f43ae66ec3cb91fc7a143bdcc737
{ "intermediate": 0.34450021386146545, "beginner": 0.40584444999694824, "expert": 0.24965538084506989 }
47,793
 When the volume of a gas is changed from 250 mL to 425 mL, the temperature will change from 137°C to °C. Assume that the number of moles and the pressure remain constant. Be sure to notice that temperatures are in °C!
72da5c5943afe25faafeac326a4a761f
{ "intermediate": 0.4205152690410614, "beginner": 0.2877469062805176, "expert": 0.29173779487609863 }
47,794
On a Linux desktop system running the SysV init without a GUI login manager, how can I make the TTY remember my user and ask for my password, just like a GUI login manager would do? This means, no autologin but neither asking for the user and password, just for the password
8620851abbbd5b4949d3c489c2442845
{ "intermediate": 0.3588717579841614, "beginner": 0.31273430585861206, "expert": 0.3283939063549042 }
47,795
I am making a c++ sdl based game engine, currently in an stage of moving all my raw pointers into smart pointers. I already finished several classes, and I already know how to do it. The thing is, when I was revisiting old code to convert, I found out my VertexCollection class (it wraps SDL_Vertex and adds more functionalities to it) has a SetTexture method which use a raw Texture pointer, Texture is my own class which wraps SDL_Texture and adds more functionalities to it and I don’t know if I should just use an object and use a make_unique or receive the smart pointer and use std::move. 1) void VertexCollection::SetTexture(std::unique_ptr<Texture> texture) { if (texture) { this->texture = std::move(texture); } } 2) void VertexCollection::SetTexture(const Texture& texture) { this->texture = std::make_unique<Texture>(texture); } 3) Using a shared_ptr? How possible or valid would be for a user to share the same texture between Vertex collections? I don't know if this is possible since Texture on itself, store a unique_ptr SDL_texture . Which of these options is better? Is there a better alternative to these?
2c46eb1ac59fb1d4e287512d42a1874f
{ "intermediate": 0.5285937786102295, "beginner": 0.30070775747299194, "expert": 0.17069844901561737 }
47,796
On a Linux desktop system running the SysV init without a GUI login manager, how can I make the TTY remember my user and ask for my password, just like a GUI login manager would do? This means, no autologin but neither asking for the user and password, just for the password.
683565e10e54056197563b19faeb7074
{ "intermediate": 0.3539607524871826, "beginner": 0.3203570544719696, "expert": 0.3256821632385254 }
47,797
I have a local country directory which the following information: ("Afghanistan" "AF" "AFG" "004" "512" "1"), ("Andorra", "AD", "AND", "020", "NOC", "1"), ("Angola", "AO", "AGO", "024", "614", "1"),. I need the values AF, AFG, 004,512, 1 to appear under column alpha_2, alpha_3, UN_num, IFS_num, UN every time Afghanistan is mentioned under the variable o_country. Can you write STATA code for that using loop, please?
ebf81255231c952bda1322e4b67c8d9b
{ "intermediate": 0.2065826654434204, "beginner": 0.6559598445892334, "expert": 0.13745743036270142 }
47,798
how many core i5s were released as of 2023
975443d7f4ed02290bbfee8b35772fe3
{ "intermediate": 0.2927289605140686, "beginner": 0.2986508905887604, "expert": 0.4086202085018158 }
47,799
I am making a c++ SDL based game engine, help me write the doxygen documentation of my Window Class: First part, the class: class Window { public: enum class WindowMode { Windowed, Fullscreen, FullscreenBorderless };
9da11b70166cc697efbb953cf3f23d4d
{ "intermediate": 0.24438175559043884, "beginner": 0.6141743063926697, "expert": 0.1414438933134079 }
47,800
import requests API_URL = "https://api-inference.huggingface.co/models/impira/layoutlm-document-qa" headers = {"Authorization": "Bearer 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"} def query(payload): with open(payload["image"], "rb") as f: img = f.read() payload["image"] = base64.b64encode(img).decode("utf-8") response = requests.post(API_URL, headers=headers, json=payload) return response.json() output = query({ "inputs": { "image": "cat.png", "question": "What is in this image?" }, }) با استفاده از کتابخانه TELEBOT و این کد رباتی بنویس که بتوانم به ان اسکرین شات و تصویر ارسال کنم و ربات نتیجه را به من برگرداند در تلگرام
26fd473ff39c4db0646c30d4b0afea49
{ "intermediate": 0.6594946980476379, "beginner": 0.173100084066391, "expert": 0.16740523278713226 }
47,801
How to setup a Webserver on Ubuntu 22.04 and add (not create) a SSL certificate?
95ced55187106b5fb5b26626b62ef157
{ "intermediate": 0.3535895347595215, "beginner": 0.37330877780914307, "expert": 0.27310171723365784 }
47,802
HellO!
0d947e32f7d9494adc717f1e0a34d98b
{ "intermediate": 0.3361802101135254, "beginner": 0.353905588388443, "expert": 0.309914231300354 }
47,803
look at the following 6 files: 3.cpp 3.h and telll me what u think
1e4b685db66d5ff70fb21c98a847e009
{ "intermediate": 0.33874109387397766, "beginner": 0.2823169529438019, "expert": 0.37894201278686523 }
47,804
How to transfer a picture from Windows to Linux?
9c8b2b7cef77b8111bf7927306bbf75e
{ "intermediate": 0.3560178577899933, "beginner": 0.2042456567287445, "expert": 0.4397364854812622 }
47,805
For this exercise, you are going to design 3 classes: Computer - Superclass Laptop - Subclass Desktop - Subclass You will design these classes to optimize the superclass/subclass relationship by creating instance variables and getter/setter methods. Include the following instance variables: int screenSize - Inches of monitor space int memory - GB of ram double batteryLife - Hours of battery life boolean monitor - Whether or not a monitor is included Each class should have at least one variable in it. Once completed, the Tester class should execute without error.
0802017f6b48e81dbdcdda39780103a4
{ "intermediate": 0.21280165016651154, "beginner": 0.4344559907913208, "expert": 0.3527423143386841 }
47,806
For this exercise, you are going to design 3 classes: Computer - Superclass Laptop - Subclass Desktop - Subclass You will design these classes to optimize the superclass/subclass relationship by creating instance variables and getter/setter methods. Include the following instance variables: int screenSize - Inches of monitor space int memory - GB of ram double batteryLife - Hours of battery life boolean monitor - Whether or not a monitor is included Each class should have at least one variable in it. Once completed, the Tester class should execute without error. public class Computer { private int screenSize; private int memory; public int getScreenSize() { return screenSize; } public void setScreenSize(int screenSize) { this.screenSize = screenSize; } public int getMemory() { return memory; } public void setMemory(int memory) { this.memory = memory; } } public class ComputerTester { public static void main(String[] args) { Laptop macBook = new Laptop(); macBook.setBatteryLife(8.5); macBook.setMemory(4); Desktop dell = new Desktop(); dell.setScreenSize(18); Computer surface = new Computer(); surface.setScreenSize(11); surface.setMemory(8); System.out.println(macBook.getBatteryLife()); System.out.println(macBook.getMemory()); System.out.println(dell.getScreenSize()); System.out.println(surface.getScreenSize()); System.out.println(surface.getMemory()); } }public class Desktop { }public class Laptop { }
f2ac4420e9fe89168f53f468fd8ad2cc
{ "intermediate": 0.21241876482963562, "beginner": 0.6086497902870178, "expert": 0.17893142998218536 }
47,807
For this exercise, you are going to create a part of an Animal hierarchy. Unlike some of our examples and the previous exercises, this exercise is going to have 3 levels in the hierarchy. At the top is the Animal class. Below that, we are going to have a subclass for Pets. Under pets, we are going to have 2 subclasses, Dogs and Fish. You will need to create your class hierarchy and add instance variables, getters, and setter methods to accommodate the following information: I need to save what type of animal I have (String variable) I want to be able to save a name for my fish and dog (String variable) I want to know which fish need salt water v. fresh water (String variable) I want to know if my dog has been trained (boolean variable) I want to know the size of my dog and fish (String variable) None of your classes should have constructors. Instead, create setter and getter methods to set the value of the instance variables that you create. Make sure you use common sense names for your variables!
70dc8dd97784f6f79a6e63e46f03a109
{ "intermediate": 0.15036197006702423, "beginner": 0.6310668587684631, "expert": 0.21857117116451263 }
47,808
For this exercise, you are going to create a part of an Animal hierarchy. Unlike some of our examples and the previous exercises, this exercise is going to have 3 levels in the hierarchy. At the top is the Animal class. Below that, we are going to have a subclass for Pets. Under pets, we are going to have 2 subclasses, Dogs and Fish. You will need to create your class hierarchy and add instance variables, getters, and setter methods to accommodate the following information: I need to save what type of animal I have (String variable) I want to be able to save a name for my fish and dog (String variable) I want to know which fish need salt water v. fresh water (String variable) I want to know if my dog has been trained (boolean variable) I want to know the size of my dog and fish (String variable) None of your classes should have constructors. Instead, create setter and getter methods to set the value of the instance variables that you create. Make sure you use common sense names for your variables!public class Animal { } public class AnimalTester { public static void main(String[] args) { // Add code to test your hierarchy } } public class Dog extends Pet { } public class Fish extends Pet { } public class Pet extends Animal { }
2ffbc83b76a476353a900c16d9dcdc84
{ "intermediate": 0.22741682827472687, "beginner": 0.5620979070663452, "expert": 0.21048524975776672 }
47,809
A table is defined by the following statement: CREATE TABLE Impression ( banner_id INTEGER, background_color VARCHAR(6), banner_width REAL, banner_height REAL, cost_per_click DECIMAL(3,3), is_click BOOLEAN ); Choose the correct query for getting data from this table. Select one option from the list HINT by look for I and i SELECT banner_id, cost_per_click FROM Impression; SELECT cost_per_click as "cost per click in US dollars"; SELECT * FROM table; SELECT banner_id, banner_width, banner_height FROM banner;
acf31cfd829e2cbd354e8b292d178346
{ "intermediate": 0.42717111110687256, "beginner": 0.2179032266139984, "expert": 0.35492563247680664 }
47,810
In servicenow, I have a requirement to remove the users from particular group and also to make the user profile Inactive if the user has not logged in for more than 30 days.
84b34fbba96a1e7a48cb3f845239f38c
{ "intermediate": 0.28801214694976807, "beginner": 0.26604849100112915, "expert": 0.4459393620491028 }
47,811
C# ef core 6 map one class to two tables
f03d4c5510158112929445db82e572f7
{ "intermediate": 0.261320561170578, "beginner": 0.5937725901603699, "expert": 0.1449069380760193 }
47,812
Помогите не работает функция fetch Суть: есть список карточек, по нажатию на одну из них надо перейти по ссылке к её описанию и подробной инфе. Я по сути не знаю как с помощью функции onClick передать uuid(id) в функцию handleClickGetNumber чтобы она отправила на сервак запрос с id-шником. Вот код: export default function ImgMediaCard() { const [uuid,setUUID] = React.useState('') const [number,setNumber] = React.useState('') const [numbers,setCards]=React.useState([]) const cardUUID = React.useState('') function handleClickGetNumber(uuid){ const url = new URL('http://localhost:8080/cards/get/'); url.search = new URLSearchParams(uuid); fetch(url,{ method:"GET", headers:{"Content-Type":"application/json"}, // body:JSON.stringify(card) }) } React.useEffect(()=>{ fetch("http://localhost:8080/cards/list") .then(res=>res.json()) .then((result)=>{ setCards(result);} )},[]) return ( <div > {numbers.map(card=>( <div className='Dives' key={card.number} style={{ display: 'inline-grid', maxWidth: "500px", maxHeight: "500px", paddingTop: "80px", // paddingRight: "100px", paddingLeft: "100px" }}> <CardMedia component="img" alt="DEFAULT" height="200" image={CarNumber} /> <Typography align='center' variant="body2" > </Typography> <CardActions> cardUUID = {card.uuid}; <Button size="small" onClick={handleClickGetNumber(cardUUID)}>Перейти к оформлению</Button> </CardActions> </div>))} </div> ); }
4801571f170d42b103092038d5d03dbf
{ "intermediate": 0.26869189739227295, "beginner": 0.5555973649024963, "expert": 0.17571070790290833 }
47,813
fix below:
794fa7d5f4ee66add3f760c37ad50413
{ "intermediate": 0.3272406756877899, "beginner": 0.3396996557712555, "expert": 0.333059698343277 }
47,814
$ pwd.getpwuid(os.getuid())[0] bash: syntax error near unexpected token `os.getuid'
daffd1b11b96aa1c4ba92971e6cd4710
{ "intermediate": 0.2792021334171295, "beginner": 0.5174337029457092, "expert": 0.20336413383483887 }
47,815
write django model with field of name which is unique
84359526f82939086e2948ee3dd51df9
{ "intermediate": 0.30343830585479736, "beginner": 0.12939998507499695, "expert": 0.5671616792678833 }
47,816
here: fn find_interval<T>(queue: &Vec<(T, T)>, query: &(T, T)) -> Option<(T, T)> where T: PartialOrd + Copy, { queue .iter() .any(|(s, e)| query.0 >= *s && query.0 < *e) } how can i return (s,e) as an option?
ef82b7149aaf75d17a59ac4dcae19624
{ "intermediate": 0.3713836669921875, "beginner": 0.3865441679954529, "expert": 0.24207216501235962 }
47,817
<br>“”“<br><s>1. N - Noise</s><br><s>2. A - Agitation</s><br><s>3. T - Turbulence</s><br><s>4. O - Outcry</s><br>”“”<br>~~~<br>“”“<br>C - Contentment<br>A - Amplitude<br>L - Lull<br>M - Mellowness<br>”“”
513bba4a48e0a7fbf56b97399a6f585d
{ "intermediate": 0.33323732018470764, "beginner": 0.4283803403377533, "expert": 0.2383822798728943 }
47,818
<br>“”“<br><s>1. N - Noise</s><br><s>2. A - Agitation</s><br><s>3. T - Turbulence</s><br><s>4. O - Outcry</s><br>”“”<br>~~~<br>“”“<br>C - Contentment<br>A - Amplitude<br>L - Lull<br>M - Mellowness<br>”“”
43697360dd59d8f26faef994e014f0ec
{ "intermediate": 0.33323732018470764, "beginner": 0.4283803403377533, "expert": 0.2383822798728943 }
47,819
the definition of recursion is Defining an object, mathematical function, or computer function in terms of itself. elaborate on this
75f0caa4005920c3db327bae47e4aba4
{ "intermediate": 0.23038585484027863, "beginner": 0.2655113935470581, "expert": 0.5041028261184692 }
47,820
who are you
780f7b0c100962d5d89c699f8e7a5021
{ "intermediate": 0.45451608300209045, "beginner": 0.2491701990365982, "expert": 0.29631373286247253 }
47,821
I have a pyspark.sql df with cols, IMSI, IMEI and usage. I want to find the max usage IMEI for every IMSI and make an another col and save it there. The max total usage is after grouping by IMSI and IMEI and doing agg on usage
e07cf2e43a402a66b40f6db7927360f0
{ "intermediate": 0.39606526494026184, "beginner": 0.28113463521003723, "expert": 0.3228000998497009 }
47,822
Error (10137): Verilog HDL Procedural Assignment error at 8bitadder.v(32): object "s" on left-hand side of assignment must have a variable data type
d129dd13b4c7095bc28f4b252979a356
{ "intermediate": 0.35220983624458313, "beginner": 0.2825644314289093, "expert": 0.36522573232650757 }
47,823
from langchain.document_loaders import DirectoryLoader from langchain_community.document_loaders import UnstructuredFileLoader dir_loader = DirectoryLoader('/home/ritik1s/Downloads/conv_ai/multi_doc', loader_cls=UnstructuredImageLoader) data = dir_loader.load()
c98f507d1cd6cfec2c86ddaa4b89e1e2
{ "intermediate": 0.5174005031585693, "beginner": 0.2876942455768585, "expert": 0.19490523636341095 }
47,824
How to show this message {DETAIL: Key (personal_code)=(12345) already exists.} in fastapi
38652f03be91df3d40a01ef75d753cf9
{ "intermediate": 0.5623258352279663, "beginner": 0.11977725476026535, "expert": 0.31789690256118774 }
47,825
Устанавливаю Asterisk 16 Выдает ошибку checking for LIBEDIT... no checking for history_init in -ledit... no configure: error: *** Please install the 'libedit' development package.
f1c406026e73334727813e94a37ec13d
{ "intermediate": 0.6287044882774353, "beginner": 0.1882530003786087, "expert": 0.183042511343956 }
47,826
how to write gtest for float area(const struct contour* contour) { int p, q; int n = contour->count - 1; float A = 0.f; for (p=n-1, q=0; q < n; p=q++) { A += contour->p[p].x * contour->p[q].y - contour->p[q].x * contour->p[p].y; } return A * .5f; }
2e2b66a08e4296b6cdbd65c51e494ad2
{ "intermediate": 0.3703542947769165, "beginner": 0.35348212718963623, "expert": 0.27616360783576965 }
47,827
In servicenow, in catalog item i have a requirement to Automatically populate the end date as 2 weeks after the user's selected start date and Restrict the user from selecting an end date that is 2 week past the start date.
ce65bb8ef6af7967eed1bdaa68f06bf6
{ "intermediate": 0.2721928656101227, "beginner": 0.2920559048652649, "expert": 0.43575119972229004 }
47,828
perbaiki script ini jika ada yang salah dan kurang tepat karena dari dataframe yang di berikan merupakan contoh dataframe bulliish engulf, tetapi output nya masih tidak mendeteksi hal tersebut : async def detect_engulfing(symbol, timeframe): if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) return None start_time = datetime.now() start_seconds = start_time.second wait_seconds = candle_close - start_seconds print("Waiting for candle to close. Sleeping for", wait_seconds, "seconds") await send_message_async(f"Waiting for candle to close: {wait_seconds} seconds") # await asyncio.sleep(wait_seconds) # candles = mt5.copy_rates_from_pos(symbol, timeframe, 0, 2) # df = pd.DataFrame(candles) data = { 'time': [1713938100, 1713938160, 1713938220], 'open': [2328.170, 2328.000, 2328.800], 'high': [2328.764, 2328.754, 2328.900], 'low': [2328.012, 2328.754, 2328.700], 'close': [2328.000, 2328.800, 2328.850], 'tick_volume': [120, 1, 150], 'spread': [200, 200, 150], 'real_volume': [0, 0, 0] } df = pd.DataFrame(data) print(df) # Ambil data yang diperlukan (open, high, low, close) opens = df['open'].values highs = df['high'].values lows = df['low'].values closes = df['close'].values # Deteksi pola Bullish Engulfing bullish_engulfing = talib.CDLENGULFING(opens, highs, lows, closes) # Deteksi pola Bearish Engulfing bearish_engulfing = talib.CDLENGULFING(opens, highs, lows, closes) engulfing_patterns = [] for i in range(1, len(df)): current = df.iloc[i] # Candle saat ini previous = df.iloc[i-1] # Candle sebelumnya tolerance = 1e-10 if current['close'] > current['open'] and \ previous['close'] < previous['open'] and \ (current['open'] - previous['close']) <= -tolerance and \ current['close'] > previous['open']: engulfing_patterns.append("Bullish Engulfing") print("Bullish Engulfing") await send_message_async("Bullish Engulfing") elif current['close'] < current['open'] and \ previous['close'] > previous['open'] and \ (current['open'] - previous['close']) >= tolerance and \ current['close'] < previous['open']: engulfing_patterns.append("Bearish Engulfing") print("Bearish Engulfing") await send_message_async("Bearish Engulfing") if engulfing_patterns: mt5.shutdown() return engulfing_patterns else: print("No engulfing pattern found. Retrying...") await send_message_async("No engulfing pattern found. Retrying...") await asyncio.sleep(3)
674a039933d37402a8aafce996b2dcd7
{ "intermediate": 0.3705699145793915, "beginner": 0.33144184947013855, "expert": 0.2979881763458252 }
47,829
write a hard problem related to Code search - given a bit of code, search within it to test my AI agent
2324dfebd651cd53b279d576524cdba9
{ "intermediate": 0.16144700348377228, "beginner": 0.25472569465637207, "expert": 0.5838272571563721 }
47,830
perbaiki fungsi ini karena terkadang candle sudah menunjukan engulfing di chart tapi secata dataframe current open nya kadang lebih besar dan kadang lebih kecil dari previous close nya, bagaimana mentolerir hal ini : async def detect_engulfing(symbol, timeframe): if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) return None start_time = datetime.now() start_seconds = start_time.second wait_seconds = candle_close - start_seconds print("Waiting for candle to close. Sleeping for", wait_seconds, "seconds") await send_message_async(f"Waiting for candle to close: {wait_seconds} seconds") await asyncio.sleep(wait_seconds) candles = mt5.copy_rates_from_pos(symbol, timeframe, 0, 2) df = pd.DataFrame(candles) # data = { # 'open': [2328.170, 2327.900], # 'high': [2328.764, 2328.754], # 'low': [2328.012, 2328.754], # 'close': [2328.000, 2328.800], # } # df = pd.DataFrame(data) print(df) engulfing_patterns = [] for i in range(1, len(df)): current = df.iloc[i] # Candle saat ini previous = df.iloc[i-1] # Candle sebelumnya tolerance = 1e-10 if current['close'] > current['open'] and \ previous['close'] < previous['open'] and \ (current['open'] - previous['close']) <= -tolerance and \ current['close'] > previous['open']: engulfing_patterns.append("Bullish Engulfing") print("Bullish Engulfing") await send_message_async("Bullish Engulfing") elif current['close'] < current['open'] and \ previous['close'] > previous['open'] and \ (current['open'] - previous['close']) >= tolerance and \ current['close'] < previous['open']: engulfing_patterns.append("Bearish Engulfing") print("Bearish Engulfing") await send_message_async("Bearish Engulfing") if engulfing_patterns: mt5.shutdown() return engulfing_patterns else: print("No engulfing pattern found. Retrying...") await send_message_async("No engulfing pattern found. Retrying...") await asyncio.sleep(3)
db781c35b461c6ae27d65f7ad772a47e
{ "intermediate": 0.3680347800254822, "beginner": 0.36228281259536743, "expert": 0.2696824073791504 }
47,831
quel serait la requete équivalent avec postgresql (psycopg2) : tables_cs = connection.execute(text("""SELECT table_name FROM information_schema.tables WHERE table_schema = :db_name AND table_name LIKE 'CS_%'"""), {'db_name': settings.db_name}).all()
19eabdba12fb13b86c7cae69fbe535d3
{ "intermediate": 0.2536865174770355, "beginner": 0.4254592955112457, "expert": 0.320854127407074 }
47,832
I have a teradata table "health care" with columns provider name, zipcode, latitude and longitude. Write a python script which tables zipcode as input and provide nearest 5 care provider using latitude and longitude.
d333f59324919b3b7cc7e166f7323e13
{ "intermediate": 0.4098063111305237, "beginner": 0.29117998480796814, "expert": 0.2990136742591858 }
47,833
new Date(createdDate * 1000).toLocaleDateString({ month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }) нужно сделать 24 формат времени
c833c7377eb8369b9121cc6fa8a6ea79
{ "intermediate": 0.39885056018829346, "beginner": 0.30156633257865906, "expert": 0.2995830774307251 }
47,834
write a hard question related to Log Analysis (Text -> Text) Parsing logs into structured templates in python
d0c63d3abb9d35f1aab2b6f9f8e05e4b
{ "intermediate": 0.3528951108455658, "beginner": 0.3708464801311493, "expert": 0.2762584686279297 }
47,835
write a code for a react native simple mobile app,
201c8b9ea6ccf58b466eb7bdc4e31894
{ "intermediate": 0.4016621708869934, "beginner": 0.3562347888946533, "expert": 0.24210308492183685 }
47,836
import { MessageType, RoomType, TodoOptionType } from "@openchat/types" import { RandomUtils } from "@openchat/core" import { useEffect, useState } from "react" import { Pressable, View, TouchableOpacity } from "react-native" import { StyledText } from "../../../ui-components/styled-text/styled-text" import {  NestableDraggableFlatList,  NestableScrollContainer,  RenderItemParams, } from "react-native-draggable-flatlist" import Modal from "react-native-modal" import { Button } from "../../../ui-components/button/button.component" import { Checkbox } from "../../../ui-components/checkbox/checkbox.component" import { Input } from "../../../ui-components/input/input" import { MenuOpener } from "../../../ui-components/menu/menu-opener.provider" import { EditDeleteTodos } from "./edit-delete-todos.component" import { styles } from "./message-board-card-info-modal-todos.styles.module" import { SvgXml } from "react-native-svg" import {  bgHeaderModal,  bgSVG,  bigVerticalLienForTodoEdit,  pencilIcon, } from "../../../ui-components/svgIcons/svgIcons" import { ConfirmationModalize } from "../../../ui-components/confirmation-modalize/confirmation-modalize.component" import { Icon } from "../../../ui-components/icon/icon.component" import { useRoomMetadata } from "@openchat/ui" import { AppColors } from "../../../app/app.colors" import { MessageBoardCardInfoPopup } from "./message-board-card-info-popup" import { useModal } from "../../../ui-components/modal/modal.hook" export const MessageBoardCardInfoModalTodos = ({  message,  todoOptions,  setTodoOptions,  room,  testID,  setIsDisableScrollInDrag, }: {  message: MessageType  todoOptions: TodoOptionType[]  setTodoOptions: (todoOptions: TodoOptionType[]) => void  room: RoomType  testID?: string  setIsDisableScrollInDrag: (arg: boolean) => void }) => {  // ---------------------------------------------------------------------------  // variables  // ---------------------------------------------------------------------------  const modal = useModal()  const [name, setName] = useState("")  const [isModalOpened, setModalOpened] = useState(false)  const [updateTodo, setUpdateTodo] = useState<TodoOptionType>()  const [contentType, setContentType] = useState<"create" | "delete">("create")  const [deleteTodoId, setDeleteTodoId] = useState("")  const { community, channel, group, user } = useRoomMetadata(room.id)  console.log("====================================")  console.log("todo options: ", todoOptions)  console.log("====================================")  // ---------------------------------------------------------------------------  // effects  // ---------------------------------------------------------------------------  useEffect(() => {   setTodoOptions(todoOptions.sort((a, b) => a.order - b.order))  }, [todoOptions])  useEffect(() => {   if (updateTodo && updateTodo.name) setName(updateTodo.name)  }, [updateTodo && updateTodo.name])  // ---------------------------------------------------------------------------  // functions  // ---------------------------------------------------------------------------  async function saveTodo() {   if (!name || !message.board || !community) return   setTodoOptions([    ...todoOptions,    {     id: RandomUtils.uuid(),     name: name,     isChecked: false,     order: todoOptions.length,    },   ])   // setModalOpened(false)   setName("")  }  async function remoteUpdateTodo(updatedTodo: any, isChecked: boolean) {   if (!message.board || !todoOptions || !community) return   setTodoOptions([    ...todoOptions.map((option) => {     if (updatedTodo.id !== option.id) return option     return {      ...option,      isChecked: isChecked,     }    }),   ])  }  async function remoteUpdateNameTodo(updatedId: string, name: string) {   if (!message.board || !todoOptions || !community) return   setTodoOptions([    ...todoOptions.map((option) => {     if (updatedId !== option.id) return option     return {      ...option,      name: name,     }    }),   ])   setName("")  }  async function removeTodo(optionId: string) {   if (!message.board || !todoOptions || !community) return   setTodoOptions([...todoOptions.filter((option) => option.id !== optionId)])  }  // ---------------------------------------------------------------------------  // render functions  // ---------------------------------------------------------------------------  function openTodoPopup(currentTodo: TodoOptionType) {   return (    <EditDeleteTodos     option={currentTodo}     removeTodo={removeTodo}     setUpdateTodo={setUpdateTodo}     setContentType={setContentType}    />   )  }  // function onDragEnd(reorderTodoOptions: TodoOptionType[]) {  //  const reordered = reorderTodoOptions.map((reorderOption, index) => {  //   const reorder = todoOptions.find((it) => it.id === reorderOption.id)!  //   reorder.order = index + 1  //   return reorder  //  })  //  setTodoOptions(reordered)  // }  function onDragEnd(reorderTodoOptions: TodoOptionType[]) {   const reordered = reorderTodoOptions.map((reorderOption, index) => {    const existingTodoOption = todoOptions.find(     (it) => it.id === reorderOption.id,    )!    const updatedTodoOption = {     ...existingTodoOption,     order: index + 1,    }    return updatedTodoOption   })   setTodoOptions(reordered)  }  // const renderItem = ({  //  item: todoOption,  //  isActive,  //  drag,  // }: RenderItemParams<TodoOptionType>) => {  //  return (  //   <View style={styles.checkboxWrapp} key={todoOption.id}>  //    <View style={{ flexDirection: "row", gap: 20 }}>  //     <TouchableOpacity  //      onLongPress={() => {  //       drag()  //      }}  //     >  //      {isActive ? (  //       <Icon name="fas fa-grid-round" size={18} />  //      ) : (  //       <Icon name="fal fa-grip-lines" size={18} />  //      )}  //     </TouchableOpacity>  //     <Checkbox  //      checked={todoOption.isChecked}  //      onClick={(isChecked) => remoteUpdateTodo(todoOption, isChecked)}  //     />  //    </View>  //    <View  //     style={{  //      flexDirection: "row",  //      justifyContent: "space-between",  //      flexGrow: 1,  //      paddingLeft: 20,  //      flex: 1,  //     }}  //    >  //     <StyledText  //      testID={`${testID}.todo.${todoOption.order}`}  //      onLongPress={drag}  //      style={{  //       fontSize: 16,  //       fontWeight: "400",  //       color: "#000",  //       fontFamily: "Source Sans Pro",  //       width: "95%",  //      }}  //     >  //      {todoOption.name}  //     </StyledText>  //     <View style={{ position: "relative", right: -5 }}>  //      <Pressable testID={`${testID}.${todoOption.order}.editIcon`}>  //       <MenuOpener  //        content={openTodoPopup(todoOption)}  //        style={{ marginLeft: -20 }}  //       >  //        <Icon name="far fa-ellipsis-vertical" height={16} width={4} />  //       </MenuOpener>  //      </Pressable>  //     </View>  //    </View>  //   </View>  //  )  // }  const renderItem = ({   item,   drag,   isActive,  }: RenderItemParams<TodoOptionType>) => {   return (    <View style={styles.folder}>     <View      style={{       flex: 1,       flexDirection: "row",       gap: 10,       alignItems: "center",      }}     >      <TouchableOpacity       onLongPress={() => {        console.log("====================================")        console.log("123333333", todoOptions)        console.log("====================================")        drag()       }}      >       {isActive ? (        <Icon         name="fa-solid fa-grid-round"         bald={true}         size={16}         fill={AppColors.textSecondaryGray}        />       ) : (        <Icon         bald={true}         name="fa-sharp fa-light fa-grip-lines"         size={16}         fill={AppColors.textSecondaryGray}        />       )}      </TouchableOpacity>      <View style={styles.folderContent}>       <StyledText        numberOfLines={1}        ellipsizeMode="tail"        style={styles.folderName}       >        {item.name}       </StyledText>      </View>     </View>     <MenuOpener      position="bottom-left"      // content={<MessageBoardCardInfoPopup todoOption={item} />}      content={openTodoPopup(item)}     >      <Icon       name="fa-regular fa-ellipsis-vertical"       size={18}       fill={AppColors.textSecondaryGray}      />     </MenuOpener>    </View>   )  }  function addTodoItem() {   modal.open({    component: (     <View style={{ backgroundColor: AppColors.light }}>      <View style={{ position: "relative" }}>       {/* <SvgXml xml={bgHeaderModal} /> */}       <StyledText        style={{         position: "absolute",         fontFamily: "Source Sans Pro",         fontSize: 24,         fontStyle: "normal",         fontWeight: "600",         left: 20,         top: 29,        }}       >        Todos       </StyledText>      </View>      <View       style={{        backgroundColor: AppColors.light,        paddingBottom: 20,        paddingHorizontal: 20,       }}      >       {todoOptions.length > 0 && (        <View style={styles.todoList}>         <NestableScrollContainer>          <NestableDraggableFlatList           contentContainerStyle={{ gap: 10 }}           data={todoOptions}           renderItem={renderItem}           onDragBegin={() => {            setIsDisableScrollInDrag(false)           }}           keyExtractor={(item) => item.id}           onDragEnd={({ data }) => {            onDragEnd(data)            setIsDisableScrollInDrag(true)           }}          />         </NestableScrollContainer>        </View>       )}       <View        style={{         backgroundColor: updateTodo?.name          ? AppColors.backgroundLight          : "transparent",         marginHorizontal: -20,         paddingHorizontal: 20,         paddingVertical: 10,        }}       >        <View         style={{          flexDirection: "row",          marginBottom: 10,          gap: 10,          display: updateTodo?.name ? "flex" : "none",          justifyContent: "space-between",          width: "100%",         }}        >         <View          style={{           flexDirection: "row",           gap: 10,          }}         >          <View           style={{            flexDirection: "row",            gap: 15,            alignItems: "center",           }}          >           <SvgXml xml={pencilIcon(AppColors.iconDefault)} />           <SvgXml xml={bigVerticalLienForTodoEdit()} />          </View>          <View           style={{            justifyContent: "space-between",           }}          >           <StyledText            style={{ color: AppColors.iconDefault, fontSize: 16 }}           >            Edit           </StyledText>           <StyledText            style={{             color: "#000",             fontSize: 14,             fontWeight: "400",             flexWrap: "wrap",            }}           >            {updateTodo?.name}           </StyledText>          </View>         </View>         <Pressable          onPress={() => {           setUpdateTodo({            id: "",            name: "",            isChecked: false,            order: 0,           })           setName("")          }}          style={{ justifyContent: "center" }}         >          <Icon name="far fa-xmark" height={16} width={10} />         </Pressable>        </View>        <Input         testID={`${testID}.addTodoItemInput`}         placeholder="Write a title"         value={name}         onChangeText={setName}         autoFocus={true}         wrapperStyle={{ backgroundColor: AppColors.light }}        />       </View>       <View style={styles.btnBox}>        <Button         containerStyle={{ width: 91 }}         onPress={() => {          if (!updateTodo?.name) {           saveTodo()          } else {           remoteUpdateNameTodo(updateTodo.id, name)           setUpdateTodo({            id: "",            name: "",            isChecked: false,            order: 0,           })          }         }}        >         {updateTodo?.name ? "Save" : "Add"}        </Button>       </View>       {/* <SvgXml        xml={bgSVG}        style={{         position: "absolute",         left: 0,         bottom: 0,         zIndex: -1,        }}       /> */}      </View>     </View>    ),    footer: "rgb",    keyboard: 220,   })  }  // ---------------------------------------------------------------------------  return (   <View style={styles.todoWrapper}>    <View     style={{      flexDirection: "row",      justifyContent: "space-between",      alignItems: "center",      marginBottom: 20,     }}    >     <StyledText style={styles.title}>Todos</StyledText>     <Pressable      style={{       display: todoOptions.length > 0 ? "flex" : "none",      }}      onPress={() => addTodoItem()}     >      <SvgXml xml={pencilIcon(AppColors.iconDefault)} />     </Pressable>    </View>    {todoOptions.length > 0 ? (     <View style={[styles.todoList, { gap: 5 }]}>      {todoOptions.map((todo) => (       <View style={styles.checkboxWrapp} key={todo.id}>        <View style={{ flexDirection: "row", gap: 20 }}>         <Checkbox          checked={todo.isChecked}          onClick={(isChecked) => remoteUpdateTodo(todo, isChecked)}         />        </View>        <View         style={{          flexDirection: "row",          justifyContent: "space-between",          flexGrow: 1,          paddingLeft: 20,          flex: 1,         }}        >         <StyledText          testID={`${testID}.todo.${todo.order}`}          style={{           fontSize: 16,           fontWeight: "400",           color: "#000",           fontFamily: "Source Sans Pro",           width: "95%",          }}         >          {todo.name}         </StyledText>        </View>       </View>      ))}     </View>    ) : (     <Button      onPress={() => addTodoItem()}      type="outline-small"      containerStyle={{ width: 150 }}      icon="plus"     >      Add todo item     </Button>    )}   </View>  ) } why this <Input         testID={`${testID}.addTodoItemInput`}         placeholder="Write a title"         value={name}         onChangeText={setName}         autoFocus={true}         wrapperStyle={{ backgroundColor: AppColors.light }}        /> is uncontrolled ? Please fix it ?
4d8463f4a6d03c910e6ae425868b1a87
{ "intermediate": 0.28627923130989075, "beginner": 0.5281451344490051, "expert": 0.1855756640434265 }
47,837
Напиши документацию к этому коду import os import sys from os.path import dirname sys.path.append(dirname(os.path.abspath(__file__)) + "/../pylib") sys.path.append(dirname(os.path.abspath(__file__)) + "/../srv-gpu-vutils") MY_DIR = os.path.dirname(os.path.abspath(__file__)) import re import requests import time import json from datetime import datetime, timedelta import pytz import multiprocessing import concurrent.futures from concurrent.futures import ThreadPoolExecutor import subprocess from subprocess import CalledProcessError import argparse import random from pathlib import Path import vol1 import s_heartbeat import vhelpers # import srv_gpu_task import dse_client ENTERPRISE_ID = os.environ['ENTERPRISE_ID'] if not ENTERPRISE_ID: print("set ENTERPRISE_ID before") os._exit(1) """ ЭТО СКРИПТ поиска начала и конца диалога по stt. пример !!! python3.6 и выше обязателен python3.6 <script.py> <id поставщика> -mode=select-source -max-try=10 -json-cfg={....} При запуске - он делает итераций -max-try на каждую итерацию пробует рандомно взять из конфига ОДИН микрофон и один день (рандомно от сегодня до х) и для этого дня и микрофона собрать файл в статистику и положить на стор результат. Этот скрипт можно смело запускать в множественном количестве - он будет работать только с данными обновленными и локировать объект результирубщий перед началом работы. """ # пример конфига для отладки """ [ { "tz":"Europe/Moscow", "start_time": "10:00", "end_time": "21:00", "sources": [ 10.8.6.82_badge.marya2 ] } ] """ _OUTPUT_EXT = ".stt.sedet.json" _PREV_FILE_CUT_SECS = 10 # сколько захватывает с конца предыдущего файла _MAX_PROCESSING_DURATION = 60 # максимальная длина обрабатываемого за раз сегмента parser = argparse.ArgumentParser(description='dialog_start_end supplier') parser.add_argument('supplier_id') # parser.add_argument("--stream-mode", "-sm", choices=['mpegts', 'png', 'jpg'], help="How send data to GPU worker. Mpegts is the most efficient and default", required=False, default="mpegts") parser.add_argument('-json-cfg', type=str, help='json config', required=True) parser.add_argument('-mode', type=str, default="select-source", choices=['select-source', 'build-source-results'], help='mode to run "select-source" / "build-source-results" ', required=True) parser.add_argument('-index', type=str, help='index of json config to process', required=False) parser.add_argument('-source', type=str, help='index of json config to process', required=False) parser.add_argument('-max-try', type=int, default=15, help='index of json config to process', required=False) parser.add_argument('-high-priority', dest='high_priority', action='store_true') parser.add_argument('-params', help='language and speakers', required=False) args = parser.parse_args() config = json.loads(args.json_cfg) if args.params: params = json.loads(args.params) else: params = None # !!!!! ОБЯЗАТЕЛЬНО ВСЕГДА делать сидирование - иначе некоторые части конфига НИКОГДА не будут браться random.seed(time.time()) # Получаем объекты и расширения файлов def get_object_ts_and_extention(object_name): ext_m = re.search(".+_([0-9]{10}).*(\\.[^\\.]+)$", object_name) if not ext_m: return None return int(ext_m[1]), ext_m[2] # Обработка файла def ProcessFile(selected_object, output_object_path, source_json_params, is_high_priority, reversed_object_list, params=None): download_folder = "/tmp/downloads/" import shutil try: shutil.rmtree(download_folder, ignore_errors=False) except FileNotFoundError as e: print("No folder to remove. It is normal: ", download_folder) # создаем новую директорию os.mkdir(download_folder) # получаем временную метку и расширение текущего объекта object_ts, object_ext = get_object_ts_and_extention(selected_object) # для микрофонов с потоковой записью (в отличие от телефонных звонков у нас может быть ситуация что надо # конец предыдущего файла добавить в начало чтобы слова не попадали в промежуток между # FIXME для телефонных записей это не нужно будет, также если prev_object_name = getPrevTsObjectSameExt(reversed_object_list, selected_object) # предыдущий файл может уже протухнуть или в список не попасть - но это очень редкое событие и поэтому мы # игнорируем его и просто тогда не обрабатываем текущий # также предыдущий файл может быть такой длины, что не подходит к текущему -> тогда его надо игнорировать prev_local_file = None prev_object_ts = None if prev_object_name: prev_local_file = download_folder + Path(prev_object_name).name if not vol1.download_object_to_file(prev_object_name, prev_local_file, timeout=30): print("ERROR: Could not download PREV object:", prev_object_name, prev_local_file) return False print("Donwloaded PREV object to local file", prev_object_name, prev_local_file) local_file = download_folder + Path(selected_object).name if not vol1.download_object_to_file(selected_object, local_file, timeout=30): print("ERROR: Could not download object:", selected_object, local_file) return False print("Downloaded object to local file", selected_object, local_file) # Для скаченного stt получаем результат, отдаем текущий объект и предыдущий с тем же расширением result = dse_client.DialogStartEnd(prev_file_path=prev_local_file, file_path=local_file, file_start_ts=object_ts, is_high_priority=is_high_priority, params=params) print('RESULT: ', result['result']) print(output_object_path) # сохраняем результат по переданному выходному пути how_much_to_store = 60 * 60 * 24 * 60 # храним 60 дней на всякий случай put_result = vol1.put_object(object_name=output_object_path, content=json.dumps(result, ensure_ascii=False), headers={ "X-Delete-After": str(how_much_to_store), "Content-Type": "application/json" }, timeout=300) print("FINISHED, result", put_result) if not put_result: print("ERROR: failed upload", output_object_path, result_file) return False return True def get_sources_codes(sources): codes = [] for item in sources: if isinstance(item, str): codes.append(item) elif isinstance(item, dict): # этот сорс в виде объекта передан codes.extend(item.keys()) else: print("ERROR: wrong source item", item) os._exit(1) return codes def get_source_params(sources, code): for item in sources: if isinstance(item, str): if item == code: # у строкового элемента нет параметров дополнительных return None elif isinstance(item, dict): for sub_item in item: if sub_item == code: return item[sub_item] print("ERROR: wrong source code", code) os._exit(1) # Получаем новый список файлов и сравниваем его со старым # Если в новом списке есть файлы, не входящие в старый список, то возвращаем их def filter_new_files(source_key, last_object): prefix = ENTERPRISE_ID + "/" + source_key # разбиваем /raw-uploads/enterprise-id/file-name path_parts = last_object.split('/') file_name = path_parts[len(path_parts) - 1] # имя последнего файла, только без /raw-uploads/, потому что уже прописан бакет raw-uploads marker = ENTERPRISE_ID + '/' + file_name # выставлено 9999999999, как заглушка, потому что если вернуть None, то end_marker не задействуется # и попадают лишние файлы, например 10.8.3.103_rtsp.camera.10_TEST_1644853800 вместо 10.8.3.103_rtsp.camera.10_1644853800 # end_marker = None end_marker = prefix + "_" + str(9999999999) print("PREFIX:", prefix) object_list = vol1.get_object_list(bucket="raw-uploads", prefix=prefix, marker=marker, end_marker=end_marker, extensions=[".stt.json", _OUTPUT_EXT]) return object_list # Ищем в списке предыдущий объект с тем же расширением def getPrevTsObjectSameExt(reversed_object_list, object_name): # таймпстемп и расширения для исследуемого объекта object_ts, object_ext = get_object_ts_and_extention(object_name) # обработка объекта без расширения if not object_ext: print("Extention not found... Code error") raise Exception("Extention not found. Error:", object_name) print(" Object extension: ", object_ext) for prev_object_name in reversed_object_list: print("PREV:", prev_object_name) if prev_object_name == object_name: continue prev_object_ts, prev_object_ext = get_object_ts_and_extention(prev_object_name) if prev_object_ext == object_ext: print("Prev object found:", prev_object_name) else: continue if int(object_ts) - int(prev_object_ts) > (60 * 60 * 4): # если предыдущий объект более чем на 4 часа старше (его начало) - # то считаем что он явно не может быть сопряжет с текущим print("Prev object timestamp is too old.") return None return prev_object_name return None def Process(processed_sources_keys): source = None index = None retValueOnAlreadyProcessed = False all_sources = [] if args.mode == "select-source": # чтобы равномерно распределять запуски на камеру - надо собрать все камеры в один массив и уже на нем сделать рандомизацию print("Get random index of the config entry from 0 to", len(config) - 1) if len(config) < 1: print("No config items") os._exit(1) # это ошибка конфига for cfg_index in range(len(config)): cfg_item = config[cfg_index] sources_keys = get_sources_codes(cfg_item["sources"]) if len(sources_keys) < 1: print("No sources") return False # Это потенциальная ошибка конфига for sources_key in sources_keys: # добавляем таппл с индексом и камерой all_sources.append((cfg_index, sources_key)) (cfg_index, sources_key) = random.choice(all_sources) print("========================================") print(cfg_index) print(sources_key) index = cfg_index source = sources_key retValueOnAlreadyProcessed = True else: index = args.index source = args.source all_sources.append( (index, source)) # добавляем в массив один - тк тут все источники у нас только один указанный # проверяем если у нас все источники уже обработаны по разу - то выходим сразу - иначе скрипт будет висеть долго # и занимать место if len(all_sources) == len(processed_sources_keys): print("ALL SOURCES ALREADY PROCESSED. EXIT") sys.exit(0) # проверяем что если уже обрабатывали выбранный источник - то просто пропускаем его if (index, source) not in processed_sources_keys: processed_sources_keys.append((index, source)) else: print("Already processed key: ", source, len(all_sources), len(processed_sources_keys)) # если уже процессили просто возвращает Try если рандомом выбирали камеру return retValueOnAlreadyProcessed MAX_PROCESS_TRY = args.max_try print("Input source:", source) print("Input index:", index) # по идее в этот скрипт придет только один конфига часть !!!! только по одной камере секция - # это для распарралеливания проще!!! """ 1. На этом этапе мы взяли одну камеру из одного конфига 2. Берем список ее файлов на сторе за последние 2 дня 3. Нам нужен файл без _OUTPUT_EXT (с конца который ближе к now) 4. Находим пробуем лочить - если не смогли залочить - берем следующий - тут можно хоть до последнего дойти 5. Скачиваем медию и подготавливаем (выравниваем) 6. Запускаем скрипт который детекции делает 7. По успеху заливаем на стор. """ cfg = config[int(index)] source_key = source source_json_params = get_source_params(cfg["sources"], source_key) print("JSON PARAMS:", source_json_params, source_key) tz = "UTC" if "tz" in cfg: tz = cfg["tz"] start_time_cfg = "00:00" if "start_time" in cfg: start_time_cfg = cfg["start_time"] end_time_cfg = "24:00" if "end_time" in cfg: end_time_cfg = cfg["end_time"] if end_time_cfg == "24:00": end_time_cfg = "00:00" # либа не поймет 24:00 - для нее это 00:00 what_day_ago_to_process = 35 print("DAY AGO TO PROCESS:", what_day_ago_to_process) # парсим конфиг по времени в таймстемпы (utc_start_timestamp, utc_end_timestamp, utc_day_start) = vhelpers.get_start_end_utc_ts(tz, what_day_ago_to_process, start_time_cfg, end_time_cfg) prefix = ENTERPRISE_ID + "/" + source_key marker = prefix + "_" + str(utc_start_timestamp) # выставлено 9999999999, как заглушка, потому что если вернуть None, то end_marker не задействуется # и попадают лишние файлы, например 10.8.3.103_rtsp.camera.10_TEST_1644853800 вместо # 10.8.3.103_rtsp.camera.10_1644853800 # end_marker = None end_marker = prefix + "_" + str(9999999999) print("PPREFIX:", prefix) object_list = vol1.get_object_list(bucket="raw-uploads", prefix=prefix, marker=marker, end_marker=end_marker, extensions=[".stt.json", _OUTPUT_EXT]) # теперь бежим с конца и пробуем найти медиа файл без детекций curr_try = 0 exit_code = False selected_object = None list_not_empty = len(object_list) > 0 # если список пуст - выходим if not list_not_empty: return # разворачиваем список свежими объектами вперед _object_list = list(reversed(object_list)) # запоминаем ts свежего файла, для запроса еще более свежих last_object = _object_list[0] while list_not_empty: # каждый раз достаем из списка самый первый объект и удаляем его из списка object_name = get_last_not_processed_from_list(_object_list) # это когда список стал пустым if not object_name: list_not_empty = False break if object_name.endswith(_OUTPUT_EXT): # ".det.json"): continue # нам надо понять, для объекта текущего - попадает ли он в нужный для нас отрезок времени # (при условии, что он может кончаться позже чем требуемое время (т.е. может пересекаться object_start_timestamp_utc = vol1.get_name_start_timestamp(object_name) # надо взять его день, получить диапазон дня, сравнить таймстемпы (пока без предсказаний длинны файла - # просто заложи 30-60 минут если нет следующего?) (obj_utc_start_day_timestamp, obj_utc_end_day_timestamp, obj_utc_day_start) = vhelpers.get_start_end_utc_ts_for_timestamp(tz, object_start_timestamp_utc, start_time_cfg, end_time_cfg) # сравниваем, что время файла попадает в расписание рабочее, тк файл может быть начат раньше начала # рабочего дня и содержать данные то берем для начала запас 60 минут if obj_utc_start_day_timestamp <= ( object_start_timestamp_utc + (60 * 60)) and object_start_timestamp_utc <= obj_utc_end_day_timestamp: print("GOOD timestamp to process", object_start_timestamp_utc, obj_utc_start_day_timestamp, obj_utc_end_day_timestamp) else: print("BAD timestamp to process. Skip file", object_start_timestamp_utc, obj_utc_start_day_timestamp, obj_utc_end_day_timestamp) continue if object_name + _OUTPUT_EXT in object_list: print("Already prepared for", object_name) continue selected_object = object_name print("Selected object:", selected_object) if not selected_object: print("No object without " + _OUTPUT_EXT + " found. Exit") os._exit(0) # пробуем захватить хеартбит для него output_object_path = selected_object + _OUTPUT_EXT print("Output PATH: ", output_object_path) heartbeat = s_heartbeat.CreateHeartbeat("detector_py_" + output_object_path) if not heartbeat: print("Could not lock target file. Skip. Try again.") continue # проверяем что объекта все еще нет (его могли создать пока мы предыдущий обрабатывали) (object_exists, object_name2, content, headers) = vol1.get_object_head(object_name=output_object_path) print(" Object existence check:", output_object_path, object_exists) if object_exists : print("Object exists already. It could be created by a parallel thread while we processed previous.") heartbeat.release() continue # Камеры с КЛ должны обрабатываться в приоритете high_priority = "" # srv-gpu принимает только отсутствие параметра high_priority # для низкоприоритетных запросов if 'high_priority' in config[index]: if source_key in config[index]['high_priority']: high_priority = "1" # На всякий случай меняем тип данных # if params is not None: # params["min_spkrs"] = int(params["min_spkrs"]) # params["max_spkrs"] = int(params["max_spkrs"]) det_result = ProcessFile(selected_object=selected_object, output_object_path=output_object_path, source_json_params=source_json_params, is_high_priority=high_priority, reversed_object_list=_object_list, params=params) exit_code = exit_code or det_result heartbeat.release() curr_try += 1 if curr_try >= MAX_PROCESS_TRY: return exit_code # sys.exit(0 if exit_code else 1) # обновляем список файлов - добавляем новые, если есть, в начало списка new_files = filter_new_files(source_key, last_object) if len(new_files) > 0: print("Update list with new files") # добавляем в начало списка for item in new_files: # если объект еще не попадал в обработку if item not in object_list: # ставим в начало очереди _object_list.insert(0, item) # кладем в изначальный массив, чтобы в нем находить _OUTPUT_EXT и не переделывать еще раз файл object_list.insert(0, item) # запоминаем самый свежий файл last_object = item print("============================= NEXT FILE =============================") continue # Возвращает первый элемент списка, если список не пуст, иначе False # obj_list - список с объектами def get_last_not_processed_from_list(obj_list): if len(obj_list) > 0: return obj_list.pop(0) else: return False MIN_TIME_TO_WORK_SEC_ = 60 # 10 minutes start_time = time.time() print("START TIMESTAMP: ", start_time) ret_ = False processed_sources = [] print("TIME_DIFF:", abs(time.time() - start_time)) while abs(time.time() - start_time) < MIN_TIME_TO_WORK_SEC_: print("CALL PROCESS with processed_sources:", len(processed_sources)) ret_ = Process(processed_sources) print("READY TO EXIT with ret_: ", ret_) sys.exit(1 if ret_ is False else 0)
4e51616e78fe2150fe3e00b5cd9a404e
{ "intermediate": 0.3774649202823639, "beginner": 0.3623507618904114, "expert": 0.26018425822257996 }
47,838
how to say in english: 把这个问题扔回给他们
db2ae1ce944e20e0b38d8996bc91ee68
{ "intermediate": 0.3115663230419159, "beginner": 0.43560269474983215, "expert": 0.25283095240592957 }
47,839
How to read txt file line by line and get 2 variables from each one. Variables are separated by space
d3e97f062746ee594ef6ef947882e89a
{ "intermediate": 0.30870839953422546, "beginner": 0.3157998025417328, "expert": 0.37549179792404175 }
47,840
How in powershell to read txt file line by line and get 2 variables from each one. Variables are separated by space.
52f28dc28afb12de924baa850dcaedc4
{ "intermediate": 0.33620893955230713, "beginner": 0.38634100556373596, "expert": 0.2774500548839569 }
47,841
How in powershell to read txt file line by line and get 2 variables from each one. Variables are separated by space. Dont use any special symbols in your answer
04658fac9ea1647a1c82751a8baf23a7
{ "intermediate": 0.386752724647522, "beginner": 0.3955700993537903, "expert": 0.21767713129520416 }
47,842
Hi there, please be a senior sapui5 developer and answer my following questions with working code examples.
3cbb5e94adbd2e0d2ebabc32723ca500
{ "intermediate": 0.42116406559944153, "beginner": 0.2712341248989105, "expert": 0.3076017498970032 }
47,843
ssh: handshake failed: ssh: unable to authenticate, attempted methods [none password], no supported methods remain
65d6c8e4cff9db5d0ad6aca2213495dc
{ "intermediate": 0.28506171703338623, "beginner": 0.22572356462478638, "expert": 0.4892147183418274 }
47,844
hi
778c7331692e8c1cb12578cda23baa48
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
47,845
fais moi une documentation en francais sans rien enlever comme info : the installation command is important because if it's changed you can replacaplite it if there are any change. this is the way we deploy on each server, any developpement tool but internally they use "bleedlogic" we have to use the all command again Installation de HarfangLab pour l'EDR de la Prépord Orange : Ubuntu
6c336ad93686fa2101eee25a9630d95a
{ "intermediate": 0.30362266302108765, "beginner": 0.15471071004867554, "expert": 0.541666567325592 }
47,846
Console Ctrl + Shift + J, code of auto-pressing spacebar in 1 sec
b20c22f402da263f14cc06ba59232cc7
{ "intermediate": 0.441218763589859, "beginner": 0.2710040211677551, "expert": 0.28777724504470825 }
47,847
excel formula to search a name based on a date
71e6001a5660140385d063436ae6680c
{ "intermediate": 0.2932831048965454, "beginner": 0.1954261064529419, "expert": 0.5112908482551575 }
47,848
hey can u help me with my notebook that i uploaded on kaggle?
a3c98a15dea06aa82d63875be5a8bf79
{ "intermediate": 0.3225329518318176, "beginner": 0.1972646266222, "expert": 0.48020240664482117 }
47,849
root@Andrew:/home/chernyshov# smbclient -L \\192.168.1.66 -U user1 WARNING: The "syslog" option is deprecated Enter WORKGROUP\user1's password: Sharename Type Comment --------- ---- ------- public Disk private Disk IPC$ IPC IPC Service (Samba 4.19.5-Debian) Reconnecting with SMB1 for workgroup listing. protocol negotiation failed: NT_STATUS_INVALID_NETWORK_RESPONSE Failed to connect with SMB1 -- no workgroup available root@Andrew:/home/chernyshov# smbclient -L \\192.168.1.66 -U user1 WARNING: The "syslog" option is deprecated Enter WORKGROUP\user1's password: Sharename Type Comment --------- ---- ------- public Disk private Disk IPC$ IPC IPC Service (Samba 4.19.5-Debian) Reconnecting with SMB1 for workgroup listing. protocol negotiation failed: NT_STATUS_INVALID_NETWORK_RESPONSE Failed to connect with SMB1 -- no workgroup available
d5ec0114bdcac54629b25c2a89d07186
{ "intermediate": 0.4297808110713959, "beginner": 0.23869073390960693, "expert": 0.33152851462364197 }
47,850
hi
7a93b6744850617dacd9e181baa8458b
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
47,851
How does typedef work in c++
8c8ed74b16faf2505a3498dedb582f47
{ "intermediate": 0.23729579150676727, "beginner": 0.4458862543106079, "expert": 0.3168180286884308 }
47,852
ng v Error: You need to specify a command before moving on. Use '--help' to view the available commands.
aba24213c250bcd4b72f2146a0f1be56
{ "intermediate": 0.32912373542785645, "beginner": 0.2721118628978729, "expert": 0.39876440167427063 }
47,853
private fun initStetho() { if (BuildConfig.DEBUG) { Stetho.initialize(Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector( RealmInspectorModulesProvider.builder(this) .withDeleteIfMigrationNeeded(true) //if there is any changes in database schema then rebuild db. .withMetaTables() //extract table meta data .withLimit(10000) //by default limit of data id 250, but you can increase with this .build() ) .build()) } }
377f868d662fceef5dcdac5fb7738427
{ "intermediate": 0.5758559107780457, "beginner": 0.26340028643608093, "expert": 0.1607438027858734 }
47,854
Установил FreePBX, зашел по ip а там Service Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.
69151740ae92099e5aa5f290a19fbdc8
{ "intermediate": 0.2729000449180603, "beginner": 0.36283260583877563, "expert": 0.3642672896385193 }
47,855
montre un exemple de cas d'utilisation avec du fulltext : conn.execute(""" CREATE INDEX IF NOT EXISTS idx_preprive_numen_fulltext ON preprive USING GIN(numen_tsvector); """) conn.execute(text(""" CREATE INDEX IF NOT EXISTS idx_aca_prive on preprive(codeaca); """)) anciennement : # conn.execute(text(""" # ALTER TABLE preprive ADD FULLTEXT numen (numen); # """)) avec un exemple mysql et un exemple postgresql
090018f13ad074ebf67f0b772f5aeae0
{ "intermediate": 0.3343614637851715, "beginner": 0.32998207211494446, "expert": 0.33565643429756165 }
47,856
il s'agit d'id donc pas besoin de frenhc ? CREATE INDEX IF NOT EXISTS idx_preprive_numen_fulltext ON preprive USING GIN (to_tsvector('french', numen));
dd6440347a7738f097dafd161be61334
{ "intermediate": 0.31854456663131714, "beginner": 0.1657453030347824, "expert": 0.515710175037384 }
47,857
Что за ошибка [root@localhost ~]# systemctl start asterisk Job for asterisk.service failed because the service did not take the steps required by its unit configuration. See "systemctl status asterisk.service" and "journalctl -xeu asterisk.service" for details.
503bd117326e6db3772de3c1ac56172a
{ "intermediate": 0.32418569922447205, "beginner": 0.36901187896728516, "expert": 0.3068023920059204 }
47,858
add an circle who change color in temperature3 way possible for differente temperature if the temperature : //Libraries #include "TFT_eSPI.h" //TFT LCD library #include "DHT.h" // DHT library //Definitions #define DHTPIN 0 //Define signal pin of DHT sensor // #define DHTPIN PIN_WIRE_SCL //Use I2C port as Digital Port */ #define DHTTYPE DHT11 //Define DHT sensor type //Initializations DHT dht(DHTPIN, DHTTYPE); //Initializing DHT sensor TFT_eSPI tft; //Initializing TFT LCD TFT_eSprite spr = TFT_eSprite(&tft); //Initializing buffer //Soil Moisture Sensor definitions int sensorPin = A1; //Define variable to store soil moisture sensor pin int sensorValue = 0; //Define variable to store soil moisture sensor value void setup() { Serial.begin(9600); //Start serial communication pinMode(WIO_LIGHT, INPUT); //Set light sensor pin as INPUT pinMode(WIO_BUZZER, OUTPUT); //Set buzzer pin as OUTPUT dht.begin(); //Start DHT sensor tft.begin(); //Start TFT LCD tft.setRotation(3); //Set TFT LCD rotation spr.createSprite(TFT_HEIGHT,TFT_WIDTH); //Create buffer } void loop() { int t = dht.readTemperature(); //Assign variable to store temperature int h = dht.readHumidity(); //Assign variable to store humidity int light = analogRead(WIO_LIGHT); //Assign variable to store light sensor values //titre spr.fillSprite(TFT_WHITE); spr.fillRect(0,0,320,50,TFT_BLUE); spr.setTextColor(TFT_WHITE); spr.setTextSize(3); spr.drawString("biotechnica",50,15); /*lignes spr.drawFastVLine(160,50,190,TFT_BLUE); spr.drawFastHLine(0,140,320,TFT_BLUE); */ // temperature spr.setTextColor(TFT_BLACK); //thermometre /**/ if(dht.readTemperature() < 15){ spr.fillRect(14,160,4,65,TFT_BLUE); } else if (dht.readTemperature() > 15 && dht.readTemperature()<18){ spr.fillRect(14,130,4,95,TFT_BLUE); } else if (dht.readTemperature() > 18 && dht.readTemperature()<21){ spr.fillRect(14,100,4,125,TFT_RED); } else if (dht.readTemperature() > 21 && dht.readTemperature()<24){ spr.fillRect(14,70,4,155,TFT_RED); } else if (dht.readTemperature() > 24){ spr.fillRect(14,40,4,185,TFT_RED); analogWrite(WIO_BUZZER, 10); //beep the buzzer delay(100); analogWrite(WIO_BUZZER, 0); //Silence the buzzer delay(100); } spr.fillCircle(16,220,6,TFT_RED); spr.setTextSize(2); spr.setTextSize(2); spr.drawNumber(t,30,210); //Display temperature values spr.drawString("C",55,210); /humiditee spr.setTextSize(2); spr.drawString("Humidity",35,40); spr.setTextSize(3); spr.drawNumber(h,45,190); //Display humidity values spr.drawString("%RH",70,190);/ //soil moisture sensorValue = analogRead(sensorPin); //Store sensor values sensorValue = map(sensorValue,1023,400,0,100); //Map sensor values spr.setTextSize(2); spr.drawString("Soil Moisture",162,65); spr.setTextSize(3); spr.drawNumber(sensorValue,200,95); //Display sensor values as percentage spr.drawString("%",260,95); //Setting light spr.setTextSize(2); spr.drawString("Light",200,160); spr.setTextSize(3); light = map(light,0,1023,0,100); //Map sensor values spr.drawNumber(light,205,190); //Display sensor values as percentage spr.drawString("%",245,190); //Condition for low soil moisture if(sensorValue < 10){ spr.fillSprite(TFT_RED); spr.drawString("Time to water!",35,100); analogWrite(WIO_BUZZER, 150); //beep the buzzer delay(1000); analogWrite(WIO_BUZZER, 0); //Silence the buzzer delay(1000); } spr.pushSprite(0,0); //Push to LCD delay(50); } To implement a feature where a circle changes color based on different temperature ranges on your TFT display, you can simplify and optimize your current setup. This involves creating a function to update the circle color based on the temperature. Here’s how you can modify your code to include a color-changing circle based on temperature: Optimize Temperature Reading: Instead of reading the temperature multiple times within the loop, read it once and store it in a variable. Create a Function for Color Determination: This makes your code cleaner and easier to maintain. Update Circle Color Based on Temperature: Use the function to determine the color and then update the circle. Here's the revised part of your code incorporating these changes: Step 1: Read Temperature Once Instead of calling dht.readTemperature() multiple times, read it once at the beginning of the loop and use the value throughout: void loop() { float temperature = dht.readTemperature(); // Only read once and reuse this value int h = dht.readHumidity(); int light = analogRead(WIO_LIGHT); Step 2: Define a Function to Get Color Based on Temperature Add this function before the setup() function: uint32_t getColorForTemperature(float temp) { if (temp < 15) { return TFT_BLUE; } else if (temp < 18) { return TFT_BLUE; } else if (temp < 21) { return TFT_RED; } else if (temp < 24) { return TFT_RED; } else { return TFT_RED; // Consider adding a different color for clarity if needed } } Step 3: Update the Circle Based on Temperature Modify the temperature display section in your loop() function: // Update circle color based on temperature uint32_t color = getColorForTemperature(temperature); spr.fillCircle(16, 220, 6, color); // Draw circle with dynamic color // Display temperature spr.setTextSize(2); spr.drawNumber((int)temperature, 30, 210); // Display temperature value as integer spr.drawString("C", 55, 210); // Additional code for thermometer visual (optional) // Update the thermometer visual if necessary, similar to the above logic This setup ensures that your code efficiently updates the circle color based on the temperature range, and it only reads the temperature from the sensor once per loop iteration, reducing redundancy and potential sensor reading errors. Make sure the rest of your loop() function accommodates these changes and that the circle's color change is visually clear on your display. Adjust the colors as needed to make sure they are distinct and meaningful based on your application's requirements.
2e7e08f3e4a394ce37138eb55313e432
{ "intermediate": 0.4542846381664276, "beginner": 0.3542070686817169, "expert": 0.1915082484483719 }
47,859
org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 347.0 failed 4 times, most recent failure: Lost task 2.3 in stage 347.0 (TID 189) (10.202.146.18 executor 0): java.sql.BatchUpdateException: String or binary data would be truncated in table 'db_dna_compliance.dna_fda.FDA_KRI_18_ATTACHMENT', column 'FLT_LOCATION'. Truncated value: '000'.
086c78e7913bdec188f7aa3c0956718e
{ "intermediate": 0.4897056818008423, "beginner": 0.23658215999603271, "expert": 0.2737121880054474 }
47,860
Thanks so much for your response, can I do this as part of the transform? I was hoping I can get a result like this: This is the sample excel data: number short description state created INC1089756 sample record new 4/24/2024 INC1089758 sample record2 in progress 4/23/2024 after transformation it will look like this on the target (incident) table number short description state created json string INC1089756 sample record new 4/24/2024 {number: "INC1089756", short_description: "sample record", state: "state", created: "4/24/2024"} INC1089758 sample record2 in progress 4/23/2024 {number: "INC1089758", short_description: "sample record2", state: "in progress", created: "4/23/2024"}
f6d9c1735b4e527aea1083e623cb8290
{ "intermediate": 0.3479989469051361, "beginner": 0.37599819898605347, "expert": 0.27600279450416565 }
47,861
Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: positions/ [name='positions_list'] positions/delete/<int:position_id>/ [name='delete_position'] positions/add/ [name='position_add'] positions/edit/<int:position_id>/ [name='position_edit'] admin/ django
5dce706f0ceddf9e2289c734b85941c9
{ "intermediate": 0.477749764919281, "beginner": 0.2509029805660248, "expert": 0.27134719491004944 }
47,862
i build an little greenhouse with arduino i build the data recupartionand i need an indicator for lighting with 3 cercle diffrent color for the ligthing your goal is to make a full program with the circle who change with the light and the code i provide to you : //Libraries #include "TFT_eSPI.h" //TFT LCD library #include "DHT.h" // DHT library //Definitions #define DHTPIN 0 //Define signal pin of DHT sensor // #define DHTPIN PIN_WIRE_SCL //Use I2C port as Digital Port */ #define DHTTYPE DHT11 //Define DHT sensor type //Initializations DHT dht(DHTPIN, DHTTYPE); //Initializing DHT sensor TFT_eSPI tft; //Initializing TFT LCD TFT_eSprite spr = TFT_eSprite(&tft); //Initializing buffer //Soil Moisture Sensor definitions int sensorPin = A1; //Define variable to store soil moisture sensor pin int sensorValue = 0; //Define variable to store soil moisture sensor value void setup() { Serial.begin(9600); //Start serial communication pinMode(WIO_LIGHT, INPUT); //Set light sensor pin as INPUT pinMode(WIO_BUZZER, OUTPUT); //Set buzzer pin as OUTPUT dht.begin(); //Start DHT sensor tft.begin(); //Start TFT LCD tft.setRotation(3); //Set TFT LCD rotation spr.createSprite(TFT_HEIGHT,TFT_WIDTH); //Create buffer } void loop() { int t = dht.readTemperature(); //Assign variable to store temperature int h = dht.readHumidity(); //Assign variable to store humidity int light = analogRead(WIO_LIGHT); //Assign variable to store light sensor values //titre spr.fillSprite(TFT_WHITE); spr.fillRect(0,0,320,50,TFT_BLUE); spr.setTextColor(TFT_WHITE); spr.setTextSize(3); spr.drawString("biotechnicaca",50,15); /*lignes spr.drawFastVLine(160,50,190,TFT_BLUE); spr.drawFastHLine(0,140,320,TFT_BLUE); */ // temperature spr.setTextColor(TFT_BLACK); //thermometre /**/ if(dht.readTemperature() < 15){ spr.fillRect(14,160,4,65,TFT_BLUE); } else if (dht.readTemperature() > 15 && dht.readTemperature()<18){ spr.fillRect(14,130,4,95,TFT_BLUE); } else if (dht.readTemperature() > 18 && dht.readTemperature()<21){ spr.fillRect(14,100,4,125,TFT_RED); } else if (dht.readTemperature() > 21 && dht.readTemperature()<24){ spr.fillRect(14,70,4,155,TFT_RED); } else if (dht.readTemperature() > 24){ spr.fillRect(14,40,4,185,TFT_RED); analogWrite(WIO_BUZZER, 10); //beep the buzzer delay(100); analogWrite(WIO_BUZZER, 0); //Silence the buzzer delay(100); } spr.fillCircle(16,220,6,TFT_RED); spr.setTextSize(2); spr.setTextSize(2); spr.drawNumber(t,30,210); //Display temperature values spr.drawString("C",55,210); /*humiditee spr.setTextSize(2); spr.drawString("Humidity",35,40); spr.setTextSize(3); spr.drawNumber(h,45,190); //Display humidity values spr.drawString("%RH",70,190);*/ //soil moisture sensorValue = analogRead(sensorPin); //Store sensor values sensorValue = map(sensorValue,1023,400,0,100); //Map sensor values spr.setTextSize(2); spr.drawString("Soil Moisture",162,65); spr.setTextSize(3); spr.drawNumber(sensorValue,200,95); //Display sensor values as percentage spr.drawString("%",260,95); //Setting light spr.setTextSize(2); spr.drawString("Light",200,160); spr.setTextSize(3); light = map(light,0,1023,0,100); //Map sensor values spr.drawNumber(light,205,190); //Display sensor values as percentage spr.drawString("%",245,190); //Condition for low soil moisture if(sensorValue < 10){ spr.fillSprite(TFT_RED); spr.drawString("Time to water!",35,100); analogWrite(WIO_BUZZER, 150); //beep the buzzer delay(1000); analogWrite(WIO_BUZZER, 0); //Silence the buzzer delay(1000); } spr.pushSprite(0,0); //Push to LCD delay(50); }
1f942c7a03847a2fdf6ca48cb32b3683
{ "intermediate": 0.5019645094871521, "beginner": 0.30357152223587036, "expert": 0.19446396827697754 }
47,863
Hey bot do you help me
533a1d771311733237dc33ef9b172e96
{ "intermediate": 0.33916404843330383, "beginner": 0.22185124456882477, "expert": 0.4389846622943878 }
47,864
Environment: Request Method: GET Request URL: http://localhost:8000/positions/ Django Version: 4.1.4 Python Version: 3.11.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Program Files\python\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Program Files\python\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\student\source\repos\djangoProject\myproject\myapp\views.py", line 9, in positions_list positions = Position.objects.all().order_by("-created") File "C:\Program Files\python\Lib\site-packages\django\db\models\query.py", line 1645, in order_by obj.query.add_ordering(*field_names) File "C:\Program Files\python\Lib\site-packages\django\db\models\sql\query.py", line 2202, in add_ordering self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) File "C:\Program Files\python\Lib\site-packages\django\db\models\sql\query.py", line 1709, in names_to_path raise FieldError( Exception Type: FieldError at /positions/ Exception Value: Cannot resolve keyword 'created' into field. Choices are: description, id, name
da896c2a32db53e0c62106891e21b28b
{ "intermediate": 0.456153929233551, "beginner": 0.23014293611049652, "expert": 0.31370311975479126 }
47,865
create plantuml for this composie design apttern public interface FileComponent { void add(FileComponent component); void remove(FileComponent component); void printFileDetails(); } public class File implements FileComponent { private String data; private String format; // Constructor, getters, setters, and other methods @Override public void add(FileComponent component) { throw new UnsupportedOperationException("Cannot add to a file."); } @Override public void remove(FileComponent component) { throw new UnsupportedOperationException("Cannot remove from a file."); } @Override public void printFileDetails() { System.out.println("File: " + data + "." + format); } } public class Folder implements FileComponent { private List<FileComponent> files; // Constructor, add, remove, printFileDetails methods @Override public void add(FileComponent component) { files.add(component); } @Override public void remove(FileComponent component) { files.remove(component); } @Override public void printFileDetails() { for (FileComponent file : files) { file.printFileDetails(); } } } // Example usage public class Main { public static void main(String[] args) { FileComponent image1 = new File("image1", "jpg"); FileComponent image2 = new File("image2", "png"); FileComponent video1 = new File("video1", "mp4"); FileComponent video2 = new File("video2", "avi"); FileComponent document1 = new File("document1", "docx"); FileComponent folder1 = new Folder(); folder1.add(image1); folder1.add(image2); folder1.add(video1); FileComponent folder2 = new Folder(); folder2.add(video2); folder2.add(document1); FileComponent rootFolder = new Folder(); rootFolder.add(folder1); rootFolder.add(folder2); rootFolder.printFileDetails(); } }
93c384898e1499b4a9328a1084fd6ae3
{ "intermediate": 0.40250930190086365, "beginner": 0.4035100042819977, "expert": 0.19398075342178345 }
47,866
make sure messaging app haas further two interfaces sms and emal which are impemented by sms ervice and emailserive to which the adpater of sms and emal use and connect Develop a messaging application that integrates with various messaging services, such as SMS, and email. However, each messaging service has its own unique interface for sending and receiving messages, making it challenging to create a unified interface for the messaging application. Using the Adapter design pattern (object adapter) in Java, design a solution to seamlessly integrate the messaging services with the messaging application, ensuring compatibility with each service's specific interface. Consider the following details: 1. The messaging application expects a unified interface for sending and receiving messages, with methods for sending messages, receiving messages i.e sendMessage, receiveMessage. 2. Each messaging service (SMS, email) has its own interface for sending and receiving messages, with methods specific to each service i.e. sendSMS, receiveSMS, sendEmail, receiveEmail. 3. The adapter should translate calls from the standard interface of the messaging application to the specific interface of each messaging service, enabling seamless integration between the application and the services.
699a897a6ffb26d41076c26484f7d232
{ "intermediate": 0.3089537024497986, "beginner": 0.3751469552516937, "expert": 0.3158993721008301 }
47,867
fix: C:\xampp\htdocs\LEMILL> npx create-evershop-app my-app Creating a new EverShop app in C:\xampp\htdocs\LEMILL\my-app. Installing @evershop/evershop added 869 packages in 3m 156 packages are looking for funding run `npm fund` for details > my-app@0.1.0 setup > evershop install ✅ ┌────────────────────────── EverShop ───────────────────────────┐ │ │ │ Welcome to EverShop - The open-source e-commerce platform │ │ │ └───────────────────────────────────────────────────────────────┘ √ Postgres Database Host (localhost) · localhost √ Postgres Database Port (5432) · 5432 √ Postgres Database Name (evershop) · lemill-shop √ Postgres Database User (postgres) · vice √ PostgreSQL Database Password (<empty>) · vice ❌ AggregateError at C:\xampp\htdocs\LEMILL\my-app\node_modules\pg-pool\index.js:45:11 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async install (C:\xampp\htdocs\LEMILL\my-app\node_modules\@evershop\evershop\bin\install\index.js:108:5) at async C:\xampp\htdocs\LEMILL\my-app\node_modules\@evershop\evershop\bin\install\index.js:287:5
a8b89b944be0c6025d73b4d5d7556f97
{ "intermediate": 0.35278964042663574, "beginner": 0.2864368259906769, "expert": 0.36077359318733215 }
47,868
package com.medicdigital.jjpodcasts.presentation.leaderboard import android.nfc.tech.MifareUltralight.PAGE_SIZE import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.CircleCrop import com.bumptech.glide.request.RequestOptions import com.medicdigital.jjpodcasts.NetworkUtils import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.leaderboard.BoardModel import com.medicdigital.jjpodcasts.presentation.base.BaseFragment import com.medicdigital.jjpodcasts.presentation.utils.DeviceUtil import com.medicdigital.jjpodcasts.presentation.utils.setProgressBarColor import com.medicdigital.jjpodcasts.presentation.utils.setToolbarColor import dagger.android.support.AndroidSupportInjection import com.medicdigital.jjpodcasts.databinding.FragmentLeaderboardBinding class LeaderBoardFragment : BaseFragment() { override lateinit var viewModel: LeaderBoardViewModel private lateinit var leaderBoardListAdapter: LeaderBoardListAdapter private lateinit var layoutManager: LinearLayoutManager override fun getMenuButton() = btn_toolbar_fragment_leaderboard_menuButton override fun getToolbar() = toolbar_fragment_leaderboard private var boardModel: BoardModel? = null private val rvScrollListener = object : RecyclerView.OnScrollListener() { val elevationActive = DeviceUtil.dp2px(8f) override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val visibleItemCount = layoutManager.childCount val totalItemCount = layoutManager.itemCount val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() if (viewModel.loadingLiveData.value == false && viewModel.hasMoreItems) { if (visibleItemCount + firstVisibleItemPosition >= totalItemCount && firstVisibleItemPosition >= 0 && totalItemCount >= PAGE_SIZE) { viewModel.loadParticipants(boardModel?.id ?: 0, viewModel.offset) } } if (!recyclerView.canScrollVertically(-1)) { wrp_fragment_leaderboard_participant.elevation = 0f } else { wrp_fragment_leaderboard_participant.elevation = elevationActive } } } override fun onCreate(savedInstanceState: Bundle?) { AndroidSupportInjection.inject(this) super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this, viewModelFactory) .get(LeaderBoardViewModel::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = FragmentLeaderboardBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity?.let { activity -> boardModel = arguments?.getParcelable(BOARD) val boardId = boardModel?.id ?: 0 setProgressBarColor(pw_fragment_leaderboard) setToolbarColor(toolbar_fragment_leaderboard, activity, activity.window) toolbar_fragment_leaderboard.setTitle(boardModel?.name) toolbar_fragment_leaderboard.setNavigationOnClickListener { activity.onBackPressed() } layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) leaderBoardListAdapter = LeaderBoardListAdapter() rv_fragment_leaderboard.layoutManager = layoutManager rv_fragment_leaderboard.adapter = leaderBoardListAdapter rv_fragment_leaderboard.addOnScrollListener(rvScrollListener) srl_fragment_leaderboard.setOnRefreshListener { viewModel.loadParticipants(boardId) } viewModel.participantsLiveData.observe(activity, Observer { if (viewModel.isInitialData) { wrp_fragment_leaderboard_participant.visibility = if (!it.isNullOrEmpty()) View.VISIBLE else View.INVISIBLE viewModel.isInitialData = false leaderBoardListAdapter.setNewData(it) } else { leaderBoardListAdapter.addNewData(it) } }) viewModel.currentParticipantLiveData.observe(activity, Observer { txt_fragment_leaderboard_username.text = it.name txt_fragment_leaderboard_rank.text = it.rank.toString() txt_fragment_leaderboard_points.text = it.score.toString() Glide.with(activity).load(it.url) .apply(RequestOptions().placeholder(R.drawable.ic_microfon_gray).fitCenter()) .transform(CircleCrop()) .into(iv_fragment_leaderboard_avatar) }) viewModel.refreshLiveData.observe(this, Observer { srl_fragment_leaderboard.isRefreshing = it }) viewModel.loadingLiveData.observe(this, Observer { pw_fragment_leaderboard.animate().alpha(if (it) 1F else 0F).setDuration(250L).start() }) if (NetworkUtils.isNetworkConnected(activity, false)) { viewModel.loadMyParticipantData(boardId) viewModel.loadParticipants(boardId) } else { viewModel.getMyParticipantData(boardId) viewModel.getParticipants(boardId) } } } companion object { const val BOARD = "board" } }
2f54c971f44734aff04da8e37909d3b3
{ "intermediate": 0.3498224914073944, "beginner": 0.47337913513183594, "expert": 0.17679840326309204 }
47,869
[4:30 PM] Sourav Panigrahi package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.podcasts.EpisodesClick import com.medicdigital.jjpodcasts.presentation.utils.Constants import com.medicdigital.jjpodcasts.presentation.utils.getNodeFeatureImage import com.medicdigital.jjpodcasts.presentation.utils.getNodeImage import com.medicdigital.jjpodcasts.presentation.utils.getTypeWithPriorityEx import com.medicdigital.jjpodcasts.presentation.podcasts.adapter.databinding.ItemPodcastFeaturedBinding class PodcastFeaturedListAdapter(private val itemClickListener: EpisodesClick?, private val itemWidth: Int, private val itemHeight: Int) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_featured), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView val ivPodcastFeatured = itemView.iv_podcast_featured_logo ivPodcastFeatured.layoutParams.height = itemHeight Glide.with(context) .load(getNodeFeatureImage(item?.assets ?: arrayListOf()) ?: getNodeImage(item?.assets ?: arrayListOf())) .placeholder(R.drawable.ic_microfon_gray) .apply(RequestOptions.fitCenterTransform()) .into(ivPodcastFeatured) itemView.txt_podcast_featured.text = item?.name itemView.vg_podcast_featured_logo.apply { tag = item setOnClickListener(this@PodcastFeaturedListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_podcast_featured_logo -> { if (nodeItem?.type == Constants.TYPE_PODCAST_EPISODE.toString()) { when (getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) { Constants.TYPE_VIDEO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_AUDIO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_PDF -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_GALLERY -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.EXTERNAL_LINK -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.QUIZ -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } } } else { itemClickListener?.onNodeWithDetailInfoClick(nodeItem) } } } } } [4:30 PM] Sourav Panigrahi package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.podcasts.EpisodesClick import com.medicdigital.jjpodcasts.presentation.utils.Constants import com.medicdigital.jjpodcasts.presentation.utils.getNodeFeatureImage import com.medicdigital.jjpodcasts.presentation.utils.getNodeImage import com.medicdigital.jjpodcasts.presentation.utils.getTypeWithPriorityEx import com.medicdigital.jjpodcasts.presentation.podcasts.adapter.databinding.ItemPodcastFeaturedBinding class PodcastFeaturedListAdapter(private val itemClickListener: EpisodesClick?, private val itemWidth: Int, private val itemHeight: Int) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_featured), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView val ivPodcastFeatured = itemView.iv_podcast_featured_logo ivPodcastFeatured.layoutParams.height = itemHeight Glide.with(context) .load(getNodeFeatureImage(item?.assets ?: arrayListOf()) ?: getNodeImage(item?.assets ?: arrayListOf())) .placeholder(R.drawable.ic_microfon_gray) .apply(RequestOptions.fitCenterTransform()) .into(ivPodcastFeatured) itemView.txt_podcast_featured.text = item?.name itemView.vg_podcast_featured_logo.apply { tag = item setOnClickListener(this@PodcastFeaturedListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_podcast_featured_logo -> { if (nodeItem?.type == Constants.TYPE_PODCAST_EPISODE.toString()) { when (getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) { Constants.TYPE_VIDEO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_AUDIO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_PDF -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_GALLERY -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.EXTERNAL_LINK -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.QUIZ -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } } } else { itemClickListener?.onNodeWithDetailInfoClick(nodeItem) } } } } } [4:30 PM] Sourav Panigrahi e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:16:66 Unresolved reference: databinding e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:26:36 Unresolved reference: iv_podcast_featured_logo e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:27:34 Variable expected e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:34:12 Unresolved reference: txt_podcast_featured e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:34:33 Variable expected e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:36:12 Unresolved reference: vg_podcast_featured_logo e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:37:4 Unresolved reference: tag e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:38:4 Unresolved reference: setOnClickListener e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:39:4 Unresolved reference: outlineProvider
33014b662423c6b7aacf4183b09700f9
{ "intermediate": 0.36945486068725586, "beginner": 0.4199637770652771, "expert": 0.21058131754398346 }
47,870
import os import csv # Define the directory where your text files are located directory = 'C:/Users/z.ahmizane/Downloads/tmp/retourFIXE' # Define the CSV file paths csv_file_path_internet = 'C:/Users/z.ahmizane/Downloads/tmp/retourFIXE/output_internet.csv' csv_file_path_fix = 'C:/Users/z.ahmizane/Downloads/tmp/retourFIXE/output_fix.csv' # Mapping of codes to enterprise names code_to_enterprise = { '002': 'ARAB', '007': 'BCM', '230': 'CIH', '040': 'BCP', '050': 'CFG', '013': 'BMCI', '022': 'SGMB', '021': 'CDM', '350': 'CCP', '310': 'TG', '011': 'BMCE', '005': 'UMB', '225': 'CNCA', } # Initialize a template for totals totals_template = {'nombre total': 0, 'montant total': 0.0, 'nombre prelever': 0, 'nombre rejetes': 0, 'montant prelever': 0.0, 'montant rejetes': 0.0} # Function to process and write data to a CSV file def process_and_write_files(file_type, file_path): data_to_write = [] totals = totals_template.copy() for filename in os.listdir(directory): if filename.startswith(file_type) and filename.endswith('R') and len(filename) > 7: enterprise_code = filename[1:4] enterprise_name = code_to_enterprise.get(enterprise_code, 'Unknown') with open(os.path.join(directory, filename), 'r') as file: lines = file.readlines() if lines: last_line = lines[-1].strip().replace(" ", "")[2:] fields = { 'nombre total': int(last_line[0:5]), 'montant total': float(int(last_line[5:25]) / 100), 'nombre prelever': int(last_line[25:30]), 'nombre rejetes': int(last_line[30:35]), 'montant prelever': float(int(last_line[35:55]) / 100), 'montant rejetes': float(int(last_line[55:75]) / 100) } # Update totals for key in totals.keys(): if key in fields: if 'montant' in key: totals[key] += fields[key] else: totals[key] += fields[key] fields['montant total'] = "{:.2f}".format(fields['montant total']) fields['montant prelever'] = "{:.2f}".format(fields['montant prelever']) fields['montant rejetes'] = "{:.2f}".format(fields['montant rejetes']) fields['Enterprise Name'] = enterprise_name data_to_write.append(fields) # Format monetary totals for output totals['montant total'] = "{:.2f}".format(totals['montant total']) totals['montant prelever'] = "{:.2f}".format(totals['montant prelever']) totals['montant rejetes'] = "{:.2f}".format(totals['montant rejetes']) totals['Enterprise Name'] = 'Total' data_to_write.append(totals) # Write the data to a CSV file with open(file_path, 'w', newline='') as csvfile: fieldnames = ['Enterprise Name', 'nombre total', 'montant total', 'nombre prelever', 'nombre rejetes', 'montant prelever', 'montant rejetes'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for row in data_to_write: writer.writerow(row) # Process and write files for INTERNET and FIX process_and_write_files('I', csv_file_path_internet) process_and_write_files('F', csv_file_path_fix) print(f"INTERNET CSV file has been created at {csv_file_path_internet}") print(f"FIX CSV file has been created at {csv_file_path_fix}")
13bb20db367d1f26279a101dae4bb56d
{ "intermediate": 0.32292410731315613, "beginner": 0.47240376472473145, "expert": 0.20467214286327362 }
47,871
uestion 2: Need For Speed 4.1 Introduction Lukarp has started his own tech company. He received a lot of funding from Igen with which he opened many offices around the world. Each office needs to communicate with one other, for which they’re using high speed connections between the offices. Office number 1 is Lukarp’s HQ. Some offices are important and hence need faster connections to the HQ for which Lukarp has use special fiber connections. Lukarp has already planned the connections but feels some fiber connections are redundant. You have been hired by Lukarp to remove those fiber connections which don’t cause faster connections. 4.2 Problem Statement 4.2.1 The Problem The offices and (bi-directional) connections (both normal and fiber) are given to you. HQ is numbered as 1. The ith normal connection connects any two offices ai and bi. Normal connections have latency li. The ith fiber connection connects the HQ with the office ci. Fiber connections also come with a latency pi. The total latency of a path is the sum of latencies on the connections. You are to output the maximum number of fiber connections that can be removed, such that the latency of the smallest latency path between the HQ and any other node remains the same as before. • There are n offices with m normal connections and k high-speed fiber connections. • The ith normal connection connects offices ai and bi (bi-directionally) with latency li. • The ith fiber connection connects offices 1 and ci (bi-directionally) with latency pi. 4.2.2 Input Format The first line of the input file will contain three space-separated integers n, m and k, the number of offices, the number of normal connections and the number of fiber connections. There will be m lines after this, the ith line signifying the ith normal connection, each containing three space-separated integers ai, bi and li the two offices that are connected and the latency of the connection respectively. There will be k lines after this, the ith line signifying the ith fiber connection, each containing three space-separated integers ci and pi, the office connected to the HQ and the latency of the fiber connection respectively. 6 4.2.3 Output Format Output only one integer m - the maximum number of fiber connections that can be removed without changing the latency of smallest latency path from office 1 to any other office. 4.2.4 Constraints • 2≤n≤105 • 1≤m≤2·105 • 1≤k≤105 • 1≤ai,bi,ci ≤n • 1≤li,pi ≤109 4.2.5 Example Input: 452 122 149 133 244 345 34 45 Output: 1 Explanation: In this example, there are five normal connections as shown in the figure below. The fiber connection going from 1 to 3 can be removed because the normal con- nection (3) is faster than the fiber connection (4). However, the fiber connection with 4 cannot be removed. Hence the maximum number of fiber connections that can be removed is 1. need c++ implementations also there can be multiple fibres and multiple normal connection between two nodes also after updating a fible connection maybe another fibre connection become redundant , this case also needs to be handled
239dfba40b9ababb82ab93aafdfe2a99
{ "intermediate": 0.47343510389328003, "beginner": 0.2204471379518509, "expert": 0.3061177730560303 }
47,872
package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.podcasts.EpisodesClick import com.medicdigital.jjpodcasts.presentation.utils.Constants import com.medicdigital.jjpodcasts.presentation.utils.getNodeFeatureImage import com.medicdigital.jjpodcasts.presentation.utils.getNodeImage import com.medicdigital.jjpodcasts.presentation.utils.getTypeWithPriorityEx import com.medicdigital.jjpodcasts.presentation.podcasts.adapter.databinding.ItemPodcastFeaturedBinding class PodcastFeaturedListAdapter(private val itemClickListener: EpisodesClick?, private val itemWidth: Int, private val itemHeight: Int) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_featured), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView val ivPodcastFeatured = itemView.iv_podcast_featured_logo ivPodcastFeatured.layoutParams.height = itemHeight Glide.with(context) .load(getNodeFeatureImage(item?.assets ?: arrayListOf()) ?: getNodeImage(item?.assets ?: arrayListOf())) .placeholder(R.drawable.ic_microfon_gray) .apply(RequestOptions.fitCenterTransform()) .into(ivPodcastFeatured) itemView.txt_podcast_featured.text = item?.name itemView.vg_podcast_featured_logo.apply { tag = item setOnClickListener(this@PodcastFeaturedListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_podcast_featured_logo -> { if (nodeItem?.type == Constants.TYPE_PODCAST_EPISODE.toString()) { when (getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) { Constants.TYPE_VIDEO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_AUDIO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_PDF -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_GALLERY -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.EXTERNAL_LINK -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.QUIZ -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } } } else { itemClickListener?.onNodeWithDetailInfoClick(nodeItem) } } } } }
169567b6f8fce147ef1f015907ef7a9f
{ "intermediate": 0.32954683899879456, "beginner": 0.5147563815116882, "expert": 0.1556968092918396 }
47,873
unit test application UM description
f5b8f552a69ec401f3dbb2c97f08b8a0
{ "intermediate": 0.28291818499565125, "beginner": 0.36926642060279846, "expert": 0.3478154242038727 }
47,874
Improve this snippet : import cv2 import numpy as np import mediapipe as mp import os from src import GLOBAL # CAPTURE TOUCHED n UNTOUCHED # track finger # save images def Capture(save_folder , finger_state , finger): mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands cap = cv2.VideoCapture(GLOBAL.WEB_CAM) iter = 0 with mp_hands.Hands( min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands: while cap.isOpened(): success, image = cap.read() if not success: print("Ignoring empty camera frame.") continue image = cv2.cvtColor(image , cv2.COLOR_BGR2RGB) copy_image = image.copy() image.flags.writeable = False results = hands.process(image) image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) finger_tracking_frame = None # initializing region of interest if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: mp_drawing.draw_landmarks( image, hand_landmarks, mp_hands.HAND_CONNECTIONS) for finger_tip_id in finger: # Landmark IDs for all five fingers' tips finger_tip = hand_landmarks.landmark[finger_tip_id] height, width, _ = image.shape tip_x, tip_y, tip_z = int(finger_tip.x * width), int(finger_tip.y * height), finger_tip.z box_size = int(GLOBAL.BOX_SIZE // 2) # Adjust the size of the box as needed box_color = (0, 255, 0) # Green color # Coordinates of the rectangle x1, y1 = tip_x - box_size, tip_y - box_size x2, y2 = tip_x + box_size, tip_y + box_size # Draw a square box around the finger tip cv2.rectangle(image, (x1, y1), (x2, y2), box_color, 2) # Crop the region of interest (ROI) finger_tracking_frame = copy_image[y1:y2, x1:x2] if finger_tracking_frame is not None and finger_tracking_frame.shape[0] > 0 and finger_tracking_frame.shape[1] > 0: finger_tracking_frame = cv2.cvtColor(finger_tracking_frame , cv2.COLOR_BGR2RGB) filename = os.path.join(save_folder, f'finger-{finger_state}{iter}.png') cv2.imwrite(filename, finger_tracking_frame) print(f'Saved touched image: {filename}') iter += 1 if iter >= GLOBAL.SAMPLES: cv2.destroyAllWindows() return cv2.imshow(f'{finger_state} SAVING', image) key = cv2.waitKey(5) if key == ord('q'): cap.release() cv2.destroyAllWindows() break def clear_training_data(): for file in os.listdir(GLOBAL.TOUCH_FOLDER): os.remove(f'{GLOBAL.TOUCH_FOLDER}/{file}') for file in os.listdir(GLOBAL.UNTOUCH_FOLDER): os.remove(f'{GLOBAL.UNTOUCH_FOLDER}/{file}') print("TRAINING DATA CLEARED") def delete_model(): model = os.listdir("models") if "touch_detection_model.h5" in model: model.remove("touch_detection_model.h5") print("model removed") else: print("model not present") def Try(finger): mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands cap = cv2.VideoCapture(GLOBAL.WEB_CAM) with mp_hands.Hands( min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands: while cap.isOpened(): success, image = cap.read() if not success: print("Ignoring empty camera frame.") continue image = cv2.cvtColor(image , cv2.COLOR_BGR2RGB) image.flags.writeable = False results = hands.process(image) image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: mp_drawing.draw_landmarks( image, hand_landmarks, mp_hands.HAND_CONNECTIONS) for finger_tip_id in finger: # Landmark IDs for all five fingers' tips finger_tip = hand_landmarks.landmark[finger_tip_id] height, width, _ = image.shape tip_x, tip_y, tip_z = int(finger_tip.x * width), int(finger_tip.y * height), finger_tip.z box_size = int(GLOBAL.BOX_SIZE // 2) # Adjust the size of the box as needed box_color = (0, 255, 0) # Green color # Coordinates of the rectangle x1, y1 = tip_x - box_size, tip_y - box_size x2, y2 = tip_x + box_size, tip_y + box_size # Draw a square box around the finger tip cv2.rectangle(image, (x1, y1), (x2, y2), box_color, 2) cv2.imshow('Tocuh tracking', image) key = cv2.waitKey(5) if key == ord('q'): break cap.release() cv2.destroyAllWindows()
47dc338b116f1c10625932c95a0b672e
{ "intermediate": 0.5319157838821411, "beginner": 0.3480135202407837, "expert": 0.12007066607475281 }
47,875
install @ng-bootstrap/ng-bootstrap specific version
c2c06c054c33365095d78174633de12b
{ "intermediate": 0.4054664373397827, "beginner": 0.26899346709251404, "expert": 0.32554012537002563 }
47,876
redux in react native typescript
59d11391e7e9630db8a77c52b262c0a0
{ "intermediate": 0.43909192085266113, "beginner": 0.41835343837738037, "expert": 0.14255453646183014 }
47,877
Hi
d809f8d2dfbb524a26a0329a56ede62f
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
47,878
перепиши этот код на питон #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #pragma GCC optimize("O3") #pragma GCC target("avx,avx2,popcnt,tune=native") #pragma GCC comment(linker, "/stack:200000000") using namespace __gnu_pbds; using namespace std; mt19937 rng(chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count()); constexpr int INF = 1e9 + 7, MD = 998244353, MAX = 200007, R = 1 << 19, MOD = 1040015701, MOD2 = 1e9 + 9, LG = 18, B = 40; int rt, s; int sub[MAX], heavy[MAX], used[MAX], side_s[2]; vector <int> g[MAX], query, side_v[2]; bool ask(vector <int>& a, int v) { cout << "? " << (int)(a.size()) << ' ' << v; for (auto& u : a) cout << ' ' << u; cout << endl; bool f; cin >> f; return f; } void dfs(int v, int p = 0) { sub[v] = 1, heavy[v] = 0; for (auto& u : g[v]) if (!used[u] && u != p) { dfs(u, v); sub[v] += sub[u], heavy[v] = max(heavy[v], sub[u]); } heavy[v] = max(heavy[v], s - sub[v]); if (!rt || heavy[v] < heavy[rt]) rt = v; } signed main() { int n; cin >> n, s = n; for (int i = 1; i < n; ++i) { int u, v; cin >> u >> v; g[u].push_back(v), g[v].push_back(u); } int where = 1; while (true) { side_s[0] = side_s[1] = rt = 0; side_v[0].clear(), side_v[1].clear(), query.clear(); dfs(where); where = rt; dfs(where); for (auto& v : g[where]) if (!used[v]) query.push_back(v); if ((int)(query.size()) == 1) { bool f = ask(query, where); return !(cout << "! " << (f ? where : query[0]) << endl); } sort(query.begin(), query.end(), [&sub](int u, int v) { return sub[u] > sub[v]; }); for (auto& v : query) side_v[side_s[0] >= side_s[1]].push_back(v), side_s[side_s[0] >= side_s[1]] += sub[v]; bool f = !ask(side_v[0], where); s -= side_s[f]; for (auto& v : side_v[f]) used[v] = 1; } }
54d52f444746216b00b60c6870185d4c
{ "intermediate": 0.28500545024871826, "beginner": 0.4029068946838379, "expert": 0.3120877146720886 }
47,879
rewrite this code in Python: #include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 7, MD = 998244353, MAX = 200007, R = 1 << 19, MOD = 1040015701, MOD2 = 1e9 + 9, LG = 18, B = 40; int rt, s; int sub[MAX], heavy[MAX], used[MAX], side_s[2]; vector <int> g[MAX], query, side_v[2]; bool ask(vector <int>& a, int v) { cout << "? " << (int)(a.size()) << ' ' << v; for (auto& u : a) cout << ' ' << u; cout << endl; bool f; cin >> f; return f; } void dfs(int v, int p = 0) { sub[v] = 1, heavy[v] = 0; for (auto& u : g[v]) if (!used[u] && u != p) { dfs(u, v); sub[v] += sub[u], heavy[v] = max(heavy[v], sub[u]); } heavy[v] = max(heavy[v], s - sub[v]); if (!rt || heavy[v] < heavy[rt]) rt = v; } signed main() { int n; cin >> n, s = n; for (int i = 1; i < n; ++i) { int u, v; cin >> u >> v; g[u].push_back(v), g[v].push_back(u); } int where = 1; while (true) { side_s[0] = side_s[1] = rt = 0; side_v[0].clear(), side_v[1].clear(), query.clear(); dfs(where); where = rt; dfs(where); for (auto& v : g[where]) if (!used[v]) query.push_back(v); if ((int)(query.size()) == 1) { bool f = ask(query, where); return !(cout << "! " << (f ? where : query[0]) << endl); } sort(query.begin(), query.end(), [&sub](int u, int v) { return sub[u] > sub[v]; }); for (auto& v : query) side_v[side_s[0] >= side_s[1]].push_back(v), side_s[side_s[0] >= side_s[1]] += sub[v]; bool f = !ask(side_v[0], where); s -= side_s[f]; for (auto& v : side_v[f]) used[v] = 1; } }
b5341ed1f425ee87920a6187bccc9282
{ "intermediate": 0.3647692799568176, "beginner": 0.41775012016296387, "expert": 0.21748067438602448 }
47,880
'scaled_actions' getting from the actor network is properly scaled with in the bounds, scaled_actions: tensor([1.9371e-07, 1.8211e-07, 1.8159e-07, 1.8159e-07, 1.8159e-07, 5.0000e-05, 5.3811e-06, 4.4282e-06, 4.4282e-06, 4.4282e-06, 1.5000e-05, 3.1397e-13, 8.5159e-01], grad_fn=<AddBackward0>) but after the process 'action = dist.sample()' i am getting the following results, which is not giving the result of my desired range and the result is also betwen negative to positive values. i need only positive values. action: tensor([ 0.0936, -0.3220, -0.1482, 0.1306, 0.1592, 0.2043, -0.3227, 0.0893, -0.2059, -0.0091, 0.3215, 0.1095, 0.7124]) because of the result getting goes out of bounds, i am getting the 'clamped_action' clamped_action [2.0e-07 1.8e-07 1.8e-07 2.0e-07 2.0e-07 5.0e-05 5.0e-07 5.0e-05 5.0e-07 5.0e-07 3.0e-05 1.0e-11 8.0e-01] the result of the required action data is completely changes and outof bounds, i made 'Clamp action to be within bounds' after the 'action = dist.sample()' it makes even worse that all the action data will be either the values of bounds low or bounds high, not getting any intermediate values between the bounds. all these problem arise in the process of action = dist.sample(). class Actor(torch.nn.Module): def __init__(self, gnn_model): super(Actor, self).__init__() self.gnn = gnn_model # Bounds are converted to tensors for ease of calculation self.bounds_low = torch.tensor([0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8], dtype=torch.float32) self.bounds_high = torch.tensor([0.2e-6, 0.2e-6, 0.2e-6, 0.2e-6, 0.2e-6, 50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4], dtype=torch.float32) def forward(self, state): node_features_tensor, _, edge_index = state processed_features = self.gnn(node_features_tensor, edge_index) #print("processed_features", processed_features) # Specific (row, column) indices for action values, converted to 0-based indexing action_indices = [ (10, 19), (16, 19), (5, 19), (3, 19), (0, 19), (10, 18), (16, 18), (5, 18), (3, 18), (0, 18), (17, 20), (18, 21), (19, 22) ] # For gathering specific indices, we first convert action_indices to a tensor format that can be used with gather or indexing action_indices_tensor = torch.tensor(action_indices, dtype=torch.long).t() selected_features = processed_features[action_indices_tensor[0], action_indices_tensor[1]] scaled_action = (selected_features + 0.1) / 2 # Scale the selected features directly. Assumes selected features and bounds are already positioned on the same device scaled_actions = self.bounds_low + (self.bounds_high - self.bounds_low) * scaled_action return scaled_actions class PPOAgent: def select_action(self, state, performance_metrics): action_probs = self.actor(state) print("action_probs:", action_probs) # Ensure the variance is at least 1D epsilon = 1e-5 variances = action_probs.var(dim=0, keepdim=True).expand(action_probs.shape[0]) + epsilon cov_mat = torch.diag(variances) # Form an [13, 13] covariance matrix with variances on the diagonal # Define the Multivariate Normal distribution dist = MultivariateNormal(action_probs, cov_mat) # Sample an action action = dist.sample() log_prob = dist.log_prob(action) # Clamp action to be within bounds clamped_action = torch.clamp(action, min=self.actor.bounds_low, max=self.actor.bounds_high) return clamped_action.detach().numpy().squeeze(), log_prob.item(), performance_metrics
c624785f9a18377793614fb25824972a
{ "intermediate": 0.3926655054092407, "beginner": 0.43024101853370667, "expert": 0.1770935356616974 }
47,881
ہے
e58b979e62d31d3dab4d867190ececd0
{ "intermediate": 0.33283862471580505, "beginner": 0.3134649395942688, "expert": 0.35369640588760376 }
47,882
Root-level (project-level) Gradle file (<project>/build.gradle): plugins { // ... // Add the dependency for the Google services Gradle plugin id 'com.google.gms.google-services' version '4.4.1' apply false }
06a2906821e66158fd88b72735ffccc4
{ "intermediate": 0.40063250064849854, "beginner": 0.2559390068054199, "expert": 0.3434285521507263 }
47,883
package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.utils.showImage import kotlinx.android.synthetic.main.item_podcast_block.view.* class PodcastBlockListAdapter(private val onPodcastItemClickListener: OnPodcastItemClickListener?) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_block), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView showImage(context, item?.assets, itemView.iv_item_podcast_block_logo) itemView.txt_item_podcast_block_name.text = item?.name itemView.vg_item_podcast_block_logo.apply { tag = item setOnClickListener(this@PodcastBlockListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_item_podcast_block_logo -> { nodeItem?.let { onPodcastItemClickListener?.onPodcastItemClick(it) } } } } interface OnPodcastItemClickListener { fun onPodcastItemClick(nodeItem: NodeItem) } }
92cdc79491151ff8bc61e3d6337e5f01
{ "intermediate": 0.3922460973262787, "beginner": 0.28468042612075806, "expert": 0.32307347655296326 }
47,884
remove synthetic and use view binding package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.utils.showImage import kotlinx.android.synthetic.main.item_podcast_block.view.* class PodcastBlockListAdapter(private val onPodcastItemClickListener: OnPodcastItemClickListener?) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_block), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView showImage(context, item?.assets, itemView.iv_item_podcast_block_logo) itemView.txt_item_podcast_block_name.text = item?.name itemView.vg_item_podcast_block_logo.apply { tag = item setOnClickListener(this@PodcastBlockListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_item_podcast_block_logo -> { nodeItem?.let { onPodcastItemClickListener?.onPodcastItemClick(it) } } } } interface OnPodcastItemClickListener { fun onPodcastItemClick(nodeItem: NodeItem) } }
bd677706ddaf64bc6db0af38fbb52060
{ "intermediate": 0.408188134431839, "beginner": 0.32742130756378174, "expert": 0.2643905282020569 }
47,885
package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.utils.showImage import kotlinx.android.synthetic.main.item_podcast_block.view.* class PodcastBlockListAdapter(private val onPodcastItemClickListener: OnPodcastItemClickListener?) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_block), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView showImage(context, item?.assets, itemView.iv_item_podcast_block_logo) itemView.txt_item_podcast_block_name.text = item?.name itemView.vg_item_podcast_block_logo.apply { tag = item setOnClickListener(this@PodcastBlockListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_item_podcast_block_logo -> { nodeItem?.let { onPodcastItemClickListener?.onPodcastItemClick(it) } } } } interface OnPodcastItemClickListener { fun onPodcastItemClick(nodeItem: NodeItem) } } Unresolved reference: synthetic
ba39969ab50728b078c0cd0b04e9bc31
{ "intermediate": 0.3579998314380646, "beginner": 0.3201511800289154, "expert": 0.32184892892837524 }
47,886
package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.utils.showImage import kotlinx.android.synthetic.main.item_podcast_block.view.* class PodcastBlockListAdapter(private val onPodcastItemClickListener: OnPodcastItemClickListener?) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_block), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView showImage(context, item?.assets, itemView.iv_item_podcast_block_logo) itemView.txt_item_podcast_block_name.text = item?.name itemView.vg_item_podcast_block_logo.apply { tag = item setOnClickListener(this@PodcastBlockListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_item_podcast_block_logo -> { nodeItem?.let { onPodcastItemClickListener?.onPodcastItemClick(it) } } } } interface OnPodcastItemClickListener { fun onPodcastItemClick(nodeItem: NodeItem) } } synthetic is deprecated
fb794923bc1aca876dc7d7f208a6ac71
{ "intermediate": 0.369627982378006, "beginner": 0.34970036149024963, "expert": 0.28067174553871155 }
47,887
package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.utils.showImage import kotlinx.android.synthetic.main.item_podcast_block.view.* class PodcastBlockListAdapter(private val onPodcastItemClickListener: OnPodcastItemClickListener?) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_block), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView showImage(context, item?.assets, itemView.iv_item_podcast_block_logo) itemView.txt_item_podcast_block_name.text = item?.name itemView.vg_item_podcast_block_logo.apply { tag = item setOnClickListener(this@PodcastBlockListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_item_podcast_block_logo -> { nodeItem?.let { onPodcastItemClickListener?.onPodcastItemClick(it) } } } } interface OnPodcastItemClickListener { fun onPodcastItemClick(nodeItem: NodeItem) } } dont use synthetic
17fa21c04c78c59847c407deb1991d48
{ "intermediate": 0.32975319027900696, "beginner": 0.3657344579696655, "expert": 0.3045123219490051 }
47,888
Hi, I would lk
9263e000dd00b7c211e102b7ae117ecb
{ "intermediate": 0.34319189190864563, "beginner": 0.2681073546409607, "expert": 0.38870078325271606 }
47,889
porque me da error el siguiente codigo: stop_words = nlp.Defaults.stop_words def normalizar_tweet(tweet): tokens = nlp(tweet) tweets_filtrados = [t.lower() for t in tokens if not t.is_punct and len(t.text)>3 and not t.is_space and not t.lower() in stop_words ] return tweets_filtrados df['tweet_normalizado'] = df['tweet'].apply(normalizar_tweet) df['labels_list'] = df['labels'].apply(lambda x: x.split(' ')) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[24], line 1 ----> 1 df['tweet_normalizado'] = df['tweet'].apply(normalizar_tweet) 2 df['labels_list'] = df['labels'].apply(lambda x: x.split(' ')) File ~/.pyenv/versions/3.9.7/lib/python3.9/site-packages/pandas/core/series.py:4771, in Series.apply(self, func, convert_dtype, args, **kwargs) 4661 def apply( 4662 self, 4663 func: AggFuncType, (...) 4666 **kwargs, 4667 ) -> DataFrame | Series: 4668 """ 4669 Invoke function on values of Series. 4670 (...) 4769 dtype: float64 4770 """ -> 4771 return SeriesApply(self, func, convert_dtype, args, kwargs).apply() File ~/.pyenv/versions/3.9.7/lib/python3.9/site-packages/pandas/core/apply.py:1123, in SeriesApply.apply(self) 1120 return self.apply_str() 1122 # self.f is Callable -> 1123 return self.apply_standard() ... ----> 9 not t.lower() in stop_words 10 ] 11 return tweets_filtrados TypeError: 'int' object is not callable
4ea9f7d76d9c943916e0ed0437cbda5d
{ "intermediate": 0.2871207296848297, "beginner": 0.4625832140445709, "expert": 0.250296026468277 }
47,890
package com.medicdigital.jjpodcasts.presentation.podcasts.adapter import android.view.View import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.medicdigital.jjpodcasts.R import com.medicdigital.jjpodcasts.data.remote.responce.NodeItem import com.medicdigital.jjpodcasts.presentation.extentions.getRoundedOutlineProvider import com.medicdigital.jjpodcasts.presentation.podcasts.EpisodesClick import com.medicdigital.jjpodcasts.presentation.utils.Constants import com.medicdigital.jjpodcasts.presentation.utils.getNodeFeatureImage import com.medicdigital.jjpodcasts.presentation.utils.getNodeImage import com.medicdigital.jjpodcasts.presentation.utils.getTypeWithPriorityEx import com.medicdigital.jjpodcasts.presentation.podcasts.adapter.databinding.ItemPodcastFeaturedBinding class PodcastFeaturedListAdapter(private val itemClickListener: EpisodesClick?, private val itemWidth: Int, private val itemHeight: Int) : BaseQuickAdapter<NodeItem, BaseViewHolder>(R.layout.item_podcast_featured), View.OnClickListener { override fun convert(holder: BaseViewHolder, item: NodeItem) { val itemView = holder.itemView val ivPodcastFeatured = itemView.iv_podcast_featured_logo ivPodcastFeatured.layoutParams.height = itemHeight Glide.with(context) .load(getNodeFeatureImage(item?.assets ?: arrayListOf()) ?: getNodeImage(item?.assets ?: arrayListOf())) .placeholder(R.drawable.ic_microfon_gray) .apply(RequestOptions.fitCenterTransform()) .into(ivPodcastFeatured) itemView.txt_podcast_featured.text = item?.name itemView.vg_podcast_featured_logo.apply { tag = item setOnClickListener(this@PodcastFeaturedListAdapter) outlineProvider = context.getRoundedOutlineProvider(alpha = .3f, cornerRadius = R.dimen.corner_4) } } override fun onClick(v: View?) { v ?: return val nodeItem = v.tag as? NodeItem? when (v.id) { R.id.vg_podcast_featured_logo -> { if (nodeItem?.type == Constants.TYPE_PODCAST_EPISODE.toString()) { when (getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) { Constants.TYPE_VIDEO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_AUDIO -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_PDF -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.TYPE_GALLERY -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.EXTERNAL_LINK -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } Constants.QUIZ -> { itemClickListener?.onEpisodeClick(nodeItem, getTypeWithPriorityEx(nodeItem, nodeItem.url, nodeItem.quiz)) } } } else { itemClickListener?.onNodeWithDetailInfoClick(nodeItem) } } } } } for this file we are expecting these errors e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:16:66 Unresolved reference: databinding e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:26:36 Unresolved reference: iv_podcast_featured_logo e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:27:34 Variable expected e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:34:12 Unresolved reference: txt_podcast_featured e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:34:33 Variable expected e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:36:12 Unresolved reference: vg_podcast_featured_logo e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:37:4 Unresolved reference: tag e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:38:4 Unresolved reference: setOnClickListener e: file:///home/sourav/Downloads/AIMeCAST-andriodapp-a8bbcfd55c39/app/src/main/java/com/medicdigital/jjpodcasts/presentation/podcasts/adapter/PodcastFeaturedListAdapter.kt:39:4 Unresolved reference: outlineProvider can you rewrite the entire code so that viewbinding is used and no unnecsary changes are broiught about
a51eac21e12ab1a58cd3c8b95f8bc767
{ "intermediate": 0.32954683899879456, "beginner": 0.5147563815116882, "expert": 0.1556968092918396 }