row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
6,425
Write example code for a virtual organ with 5 stops in GrandOrgue format
93104e78335c0b02d8b85c2cb1bf9fce
{ "intermediate": 0.2571563124656677, "beginner": 0.21604230999946594, "expert": 0.5268014073371887 }
6,426
NameError: name 'backtrader' is not defined
f0a9d03c564699ccec3acf62765fa0b3
{ "intermediate": 0.3467072546482086, "beginner": 0.19440652430057526, "expert": 0.45888614654541016 }
6,427
Can you give me DRY code for getting VSI in python? Here is the matlab code: function sim = VSI(image1, image2) % ======================================================================== % Visual Saliency based Index % Copyright(c) 2013 Lin ZHANG % All Rights Reserved. % ---------------------------------------------------------------------- % Permission to use, copy, or modify this software and its documentation % for educational and research purposes only and without fee is hereQ % granted, provided that this copyright notice and the original authors' % names appear on all copies and supporting documentation. This program % shall not be used, rewritten, or adapted as the basis of a commercial % software or hardware product without first obtaining permission of the % authors. The authors make no representations about the suitability of % this software for any purpose. It is provided "as is" without express % or implied warranty. %---------------------------------------------------------------------- % For more information, please refer to % Lin Zhang et al., "VSI: A Visual Saliency Induced Index for Perceptual % Image Quality Assessment", submitted to TIP %---------------------------------------------------------------------- % %Input : (1) image1: the first image being compared, which is a RGB image % (2) image2: the second image being compared, which is a RGB image % %Output: sim: the similarity score between two images, a real number % %----------------------------------------------------------------------- constForVS = 1.27;%fixed constForGM = 386;%fixed constForChrom = 130;%fixed alpha = 0.40;%fixed lambda = 0.020;%fixed sigmaF = 1.34;%fixed donot change omega0 = 0.0210;%fixed sigmaD = 145;%fixed sigmaC = 0.001;%fixed %compute the visual saliency map using SDSP saliencyMap1 = SDSP(image1,sigmaF,omega0,sigmaD,sigmaC); saliencyMap2 = SDSP(image2,sigmaF,omega0,sigmaD,sigmaC); [rows, cols, junk] = size(image1); %transform into an opponent color space L1 = 0.06 * double(image1(:,:,1)) + 0.63 * double(image1(:,:,2)) + 0.27 * double(image1(:,:,3)); L2 = 0.06 * double(image2(:,:,1)) + 0.63 * double(image2(:,:,2)) + 0.27 * double(image2(:,:,3)); M1 = 0.30 * double(image1(:,:,1)) + 0.04 * double(image1(:,:,2)) - 0.35 * double(image1(:,:,3)); M2 = 0.30 * double(image2(:,:,1)) + 0.04 * double(image2(:,:,2)) - 0.35 * double(image2(:,:,3)); N1 = 0.34 * double(image1(:,:,1)) - 0.60 * double(image1(:,:,2)) + 0.17 * double(image1(:,:,3)); N2 = 0.34 * double(image2(:,:,1)) - 0.60 * double(image2(:,:,2)) + 0.17 * double(image2(:,:,3)); %%%%%%%%%%%%%%%%%%%%%%%%% % Downsample the image %%%%%%%%%%%%%%%%%%%%%%%%% minDimension = min(rows,cols); F = max(1,round(minDimension / 256)); aveKernel = fspecial('average',F); aveM1 = conv2(M1, aveKernel,'same'); aveM2 = conv2(M2, aveKernel,'same'); M1 = aveM1(1:F:rows,1:F:cols); M2 = aveM2(1:F:rows,1:F:cols); aveN1 = conv2(N1, aveKernel,'same'); aveN2 = conv2(N2, aveKernel,'same'); N1 = aveN1(1:F:rows,1:F:cols); N2 = aveN2(1:F:rows,1:F:cols); aveL1 = conv2(L1, aveKernel,'same'); aveL2 = conv2(L2, aveKernel,'same'); L1 = aveL1(1:F:rows,1:F:cols); L2 = aveL2(1:F:rows,1:F:cols); aveSM1 = conv2(saliencyMap1, aveKernel,'same'); aveSM2 = conv2(saliencyMap2, aveKernel,'same'); saliencyMap1 = aveSM1(1:F:rows,1:F:cols); saliencyMap2 = aveSM2(1:F:rows,1:F:cols); %%%%%%%%%%%%%%%%%%%%%%%%% % Calculate the gradient map %%%%%%%%%%%%%%%%%%%%%%%%% dx = [3 0 -3; 10 0 -10; 3 0 -3]/16; dy = [3 10 3; 0 0 0; -3 -10 -3]/16; IxL1 = conv2(L1, dx, 'same'); IyL1 = conv2(L1, dy, 'same'); gradientMap1 = sqrt(IxL1.^2 + IyL1.^2); IxL2 = conv2(L2, dx, 'same'); IyL2 = conv2(L2, dy, 'same'); gradientMap2 = sqrt(IxL2.^2 + IyL2.^2); %%%%%%%%%%%%%%%%%%%%%%%%% % Calculate the VSI %%%%%%%%%%%%%%%%%%%%%%%%% VSSimMatrix = (2 * saliencyMap1 .* saliencyMap2 + constForVS) ./ (saliencyMap1.^2 + saliencyMap2.^2 + constForVS); gradientSimMatrix = (2*gradientMap1.*gradientMap2 + constForGM) ./(gradientMap1.^2 + gradientMap2.^2 + constForGM); weight = max(saliencyMap1, saliencyMap2); ISimMatrix = (2 * M1 .* M2 + constForChrom) ./ (M1.^2 + M2.^2 + constForChrom); QSimMatrix = (2 * N1 .* N2 + constForChrom) ./ (N1.^2 + N2.^2 + constForChrom); SimMatrixC = (gradientSimMatrix .^ alpha) .* VSSimMatrix .* real((ISimMatrix .* QSimMatrix) .^ lambda) .* weight; sim = sum(sum(SimMatrixC)) / sum(weight(:)); return; %=================================== function VSMap = SDSP(image,sigmaF,omega0,sigmaD,sigmaC) % ======================================================================== % SDSP algorithm for salient region detection from a given image. % Copyright(c) 2013 Lin ZHANG, School of Software Engineering, Tongji % University % All Rights Reserved. % ---------------------------------------------------------------------- % Permission to use, copy, or modify this software and its documentation % for educational and research purposes only and without fee is here % granted, provided that this copyright notice and the original authors' % names appear on all copies and supporting documentation. This program % shall not be used, rewritten, or adapted as the basis of a commercial % software or hardware product without first obtaining permission of the % authors. The authors make no representations about the suitability of % this software for any purpose. It is provided "as is" without express % or implied warranty. %---------------------------------------------------------------------- % % This is an implementation of the algorithm for calculating the % SDSP (Saliency Detection by combining Simple Priors). % % Please refer to the following paper % % Lin Zhang, Zhongyi Gu, and Hongyu Li,"SDSP: a novel saliency detection % method by combining simple priors", ICIP, 2013. % %---------------------------------------------------------------------- % %Input : image: an uint8 RGB image with dynamic range [0, 255] for each %channel % %Output: VSMap: the visual saliency map extracted by the SDSP algorithm. %Data range for VSMap is [0, 255]. So, it can be regarded as a common %gray-scale image. % %----------------------------------------------------------------------- %convert the image into LAB color space [oriRows, oriCols, junk] = size(image); image = double(image); dsImage(:,:,1) = imresize(image(:,:,1), [256, 256],'bilinear'); dsImage(:,:,2) = imresize(image(:,:,2), [256, 256],'bilinear'); dsImage(:,:,3) = imresize(image(:,:,3), [256, 256],'bilinear'); lab = RGB2Lab(dsImage); LChannel = lab(:,:,1); AChannel = lab(:,:,2); BChannel = lab(:,:,3); LFFT = fft2(double(LChannel)); AFFT = fft2(double(AChannel)); BFFT = fft2(double(BChannel)); [rows, cols, junk] = size(dsImage); LG = logGabor(rows,cols,omega0,sigmaF); FinalLResult = real(ifft2(LFFT.*LG)); FinalAResult = real(ifft2(AFFT.*LG)); FinalBResult = real(ifft2(BFFT.*LG)); SFMap = sqrt(FinalLResult.^2 + FinalAResult.^2 + FinalBResult.^2); %the central areas will have a bias towards attention coordinateMtx = zeros(rows, cols, 2); coordinateMtx(:,:,1) = repmat((1:1:rows)', 1, cols); coordinateMtx(:,:,2) = repmat(1:1:cols, rows, 1); centerY = rows / 2; centerX = cols / 2; centerMtx(:,:,1) = ones(rows, cols) * centerY; centerMtx(:,:,2) = ones(rows, cols) * centerX; SDMap = exp(-sum((coordinateMtx - centerMtx).^2,3) / sigmaD^2); %warm colors have a bias towards attention maxA = max(AChannel(:)); minA = min(AChannel(:)); normalizedA = (AChannel - minA) / (maxA - minA); maxB = max(BChannel(:)); minB = min(BChannel(:)); normalizedB = (BChannel - minB) / (maxB - minB); labDistSquare = normalizedA.^2 + normalizedB.^2; SCMap = 1 - exp(-labDistSquare / (sigmaC^2)); % VSMap = SFMap .* SDMap; VSMap = SFMap .* SDMap .* SCMap; VSMap = imresize(VSMap, [oriRows, oriCols],'bilinear'); VSMap = mat2gray(VSMap); return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function labImage = RGB2Lab(image) image = double(image); normalizedR = image(:,:,1) / 255; normalizedG = image(:,:,2) / 255; normalizedB = image(:,:,3) / 255; RSmallerOrEqualto4045 = normalizedR <= 0.04045; RGreaterThan4045 = 1 - RSmallerOrEqualto4045; tmpR = (normalizedR / 12.92) .* RSmallerOrEqualto4045; tmpR = tmpR + power((normalizedR + 0.055)/1.055,2.4) .* RGreaterThan4045; GSmallerOrEqualto4045 = normalizedG <= 0.04045; GGreaterThan4045 = 1 - GSmallerOrEqualto4045; tmpG = (normalizedG / 12.92) .* GSmallerOrEqualto4045; tmpG = tmpG + power((normalizedG + 0.055)/1.055,2.4) .* GGreaterThan4045; BSmallerOrEqualto4045 = normalizedB <= 0.04045; BGreaterThan4045 = 1 - BSmallerOrEqualto4045; tmpB = (normalizedB / 12.92) .* BSmallerOrEqualto4045; tmpB = tmpB + power((normalizedB + 0.055)/1.055,2.4) .* BGreaterThan4045; X = tmpR*0.4124564 + tmpG*0.3575761 + tmpB*0.1804375; Y = tmpR*0.2126729 + tmpG*0.7151522 + tmpB*0.0721750; Z = tmpR*0.0193339 + tmpG*0.1191920 + tmpB*0.9503041; epsilon = 0.008856; %actual CIE standard kappa = 903.3; %actual CIE standard Xr = 0.9642; %reference white D50 Yr = 1.0; %reference white Zr = 0.8251; %reference white xr = X/Xr; yr = Y/Yr; zr = Z/Zr; xrGreaterThanEpsilon = xr > epsilon; xrSmallerOrEqualtoEpsilon = 1 - xrGreaterThanEpsilon; fx = power(xr, 1.0/3.0) .* xrGreaterThanEpsilon; fx = fx + (kappa*xr + 16.0)/116.0 .* xrSmallerOrEqualtoEpsilon; yrGreaterThanEpsilon = yr > epsilon; yrSmallerOrEqualtoEpsilon = 1 - yrGreaterThanEpsilon; fy = power(yr, 1.0/3.0) .* yrGreaterThanEpsilon; fy = fy + (kappa*yr + 16.0)/116.0 .* yrSmallerOrEqualtoEpsilon; zrGreaterThanEpsilon = zr > epsilon; zrSmallerOrEqualtoEpsilon = 1 - zrGreaterThanEpsilon; fz = power(zr, 1.0/3.0) .* zrGreaterThanEpsilon; fz = fz + (kappa*zr + 16.0)/116.0 .* zrSmallerOrEqualtoEpsilon; [rows,cols,junk] = size(image); labImage = zeros(rows,cols,3); labImage(:,:,1) = 116.0 * fy - 16.0; labImage(:,:,2) = 500.0 * (fx - fy); labImage(:,:,3) = 200.0 * (fy - fz); return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function LG = logGabor(rows,cols,omega0,sigmaF) [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ... ([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2))); mask = ones(rows, cols); for rowIndex = 1:rows for colIndex = 1:cols if u1(rowIndex, colIndex)^2 + u2(rowIndex, colIndex)^2 > 0.25 mask(rowIndex, colIndex) = 0; end end end u1 = u1 .* mask; u2 = u2 .* mask; u1 = ifftshift(u1); u2 = ifftshift(u2); radius = sqrt(u1.^2 + u2.^2); radius(1,1) = 1; LG = exp((-(log(radius/omega0)).^2) / (2 * (sigmaF^2))); LG(1,1) = 0; return;
f73a37bca83f353d5834a21f5028884d
{ "intermediate": 0.4218073785305023, "beginner": 0.29152700304985046, "expert": 0.2866656184196472 }
6,428
can you answer in form of data array?
ee3060937052e49fb4c45ed37218dac0
{ "intermediate": 0.3965029716491699, "beginner": 0.15994448959827423, "expert": 0.44355255365371704 }
6,429
find pattern for the following input/output pairs 0=0, 3=1, 9=2, 18=3, 30=4, 45=5, 63=6, 84=7
c78872c5398e3c224ce5d20db7f621dc
{ "intermediate": 0.3266996443271637, "beginner": 0.21041713654994965, "expert": 0.46288320422172546 }
6,430
write a btgatt client and server c program to send binary files into chunks using blobs
62d04f85db65ed5409a251bee37d952e
{ "intermediate": 0.4212360382080078, "beginner": 0.17776049673557281, "expert": 0.40100347995758057 }
6,431
Сгенерируй заглушку для метода Post java для следующих полей sector=8410&amount=1000000&currency=643&pan=220070******9138&token=&month=XX&year=XX&name=%D0%A4%D1%80%D0%B8%D0%B4%D0%BE%D0%BC+%D0%A4%D0%B8%D0%BD%D0%B0%D0%BD%D1%81+%D0%91%D0%B0%D0%BD%D0%BA&url=https%3A%2F%2Fcifra-bank.ru%2F&signature=NTI4ZGFlMDk2MGRkOGZlOWUwZWU2M2MyNGQwZmFjM2Y%3D&pan2=400763******5181
1bc80422f40e169dd63d4a2ca61007b8
{ "intermediate": 0.39594465494155884, "beginner": 0.28917422890663147, "expert": 0.31488117575645447 }
6,432
how disable pull up in adc
06e995bce9bc7c3b24053c4c376ee587
{ "intermediate": 0.3865968883037567, "beginner": 0.21113598346710205, "expert": 0.40226706862449646 }
6,433
cerebro.plot(style='candlestick', candlestick={ 'up': 'red', 'down': 'green', 'volume': True, 'wick': False, 'barup': 'red', 'bardown': 'green', })颜色未变化
76a987fe533f94ebd92ddbf3dab50503
{ "intermediate": 0.32507339119911194, "beginner": 0.29402151703834534, "expert": 0.3809050917625427 }
6,434
I need to write a code . please help me with that
23569d66c28819318167ddd4a3faf2f1
{ "intermediate": 0.22262266278266907, "beginner": 0.29639413952827454, "expert": 0.480983167886734 }
6,435
write me a code in pymavlink which checks for telemetry signal strength
29e3e64b861b38a568bac0c7fc883be7
{ "intermediate": 0.5265320539474487, "beginner": 0.11587400734424591, "expert": 0.35759395360946655 }
6,436
explain to me working principle of solar panel
b3f17af02624ca66c3701d08723c5967
{ "intermediate": 0.383550763130188, "beginner": 0.3571072220802307, "expert": 0.2593420743942261 }
6,437
can you read image?
43ec49f5c449a6abc3ee1d8f5ade76b2
{ "intermediate": 0.39692744612693787, "beginner": 0.33449944853782654, "expert": 0.26857319474220276 }
6,438
Delete a node from a digraph and record number of arcs removed 30 Marks For each digraphs in a set of digraphs given as adjacency lists, read in the digraph, delete the node with index n − 3 where n is the order of the digraph, and write the digraph back to the terminal. After the adjacency lists, write out how many arcs have been removed in the process. Assume input digraphs have order at least 3. Input format: described below under the heading “Digraph input format”. Output format: the same as the input format but with one extra line after each digraph stating the number of arcs that were removed when the node was removed. Ensure that you maintain the node naming conventions. For the example input shown below, the first digraph would have node with index 1 removed, and the second graph would have node index 0 removed, so the output would be 3 2 0 3 2 0 2 0 Here the first line indicates the order of the new digraph is 3, the next three lines are the three adjacency lists showing the arcs of the this digraph, and the 3 on line 5 indicates that three arcs were removed from the input digraph. The next line has a 2 indicating that the next digraph has order 2 and so on. Digraph input format A sequence of one or more digraphs is taken from the standard input (eg sys.stdin). Each graph is represented by an adjacency list. The first line is an integer n indicating the order of the graph. This is followed by n white space separated lists of adjacencies for nodes labeled 0 to n - 1. The lists are sorted. The input will be terminated by a line consisting of one zero (0). This line should not be processed. The sample input below shows two digraphs, the first has node set {0, 1, 2, 3} and arc set {(0, 1),(0, 3),(1, 2),(1, 3),(2, 0)}, the second has node set {0, 1, 2} and arc set {(0, 1),(0, 2),(2, 1)}. 4 1 3 2 3 0 3 1 2 1 0
375b7db3b830ded4346444984aa2a05a
{ "intermediate": 0.33805280923843384, "beginner": 0.243449866771698, "expert": 0.41849732398986816 }
6,439
BFS to find distances 30 Marks Write a program that performs BFS on each of a given set of digraphs starting at node 1 and prints the distance to the most distant node from 1 and reports the node with the highest index at that distance. Nodes that are not reachable from 1 have an undefined distance and should be ignored. Input format: described below under the heading, “Digraph input format”. Output format: For each input digraph, print out a line with the distance to the most distant node, then a space, then the highest index of a node at that distance. Ignore nodes that are not reachable from 1. For the example input shown below, the output would be 2 0 0 1 Digraph input format A sequence of one or more digraphs is taken from the standard input (eg sys.stdin). Each graph is represented by an adjacency list. The first line is an integer n indicating the order of the graph. This is followed by n white space separated lists of adjacencies for nodes labeled 0 to n - 1. The lists are sorted. The input will be terminated by a line consisting of one zero (0). This line should not be processed. The sample input below shows two digraphs, the first has node set {0, 1, 2, 3} and arc set {(0, 1),(0, 3),(1, 2),(1, 3),(2, 0)}, the second has node set {0, 1, 2} and arc set {(0, 1),(0, 2),(2, 1)}. 4 1 3 2 3 0 3 1 2 1 0
0a0eba813462d816244f86682913ea4d
{ "intermediate": 0.38355594873428345, "beginner": 0.21220509707927704, "expert": 0.4042389988899231 }
6,440
All Market Mini Tickers Stream Payload: [ { "e": "24hrMiniTicker", // Event type "E": 123456789, // Event time "s": "BTCUSDT", // Symbol "c": "0.0025", // Close price "o": "0.0010", // Open price "h": "0.0025", // High price "l": "0.0010", // Low price "v": "10000", // Total traded base asset volume "q": "18" // Total traded quote asset volume } ] 24hr rolling window mini-ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array. Stream Name: !miniTicker@arr Update Speed: 1000ms https://binance-docs.github.io/apidocs/futures/en/#all-market-mini-tickers-stream как мне сделать запрос за монетами "bnbusdt", "ethusdt", "adausdt",
4b9e7419856bbbeca028909a736de9cb
{ "intermediate": 0.43193039298057556, "beginner": 0.3056166172027588, "expert": 0.26245301961898804 }
6,441
{% for i in data %}     <tr>             <td class="text-center">                 <input type="checkbox" name="checks" value="{i.id}" class="checkbox">                 <a href = "{% url 'edit_page' i.id %}" class = "btn btn-primary">Edit</a>             </td>             <td class="text-left">{{i.Name|default_if_none:""}}</td>             <td class="text-left">{{i.Email|default_if_none:""}}</td>             <td class="text-left">{{i.Mobile|default_if_none:""}}</td>                           </tr> {% endfor %} th is displaying data is not dusplayinbg
84cffda784a5891730c7a7d9e2a3f609
{ "intermediate": 0.39240822196006775, "beginner": 0.3564246594905853, "expert": 0.2511671483516693 }
6,442
Use the load_dataset function to load the dataset. Divide it into train and test with the parameters test_size=0.2, random_state=42. Output the number of files in the train and test parts. def load_dataset(directory: str): sr = None X, labels, files = [], [], [] for f in glob(directory + "/*.wav"): filename = os.path.basename(f) name = filename[:-4] y = [int(label) for label in name.split("_")] x, sr = librosa.load(f) X.append(x) labels.append(y) files.append(filename) return X, labels, sr, files
63f1a729b8b844d9eb75cc740d5d3a6c
{ "intermediate": 0.4295275807380676, "beginner": 0.2853207588195801, "expert": 0.28515172004699707 }
6,443
task: build a machine learning model to detect specific "events" that are related to the position of body parts in videos of human interaction. videos: the model should work on videos of human interaction between 2 people, sitting on chairs in front of each other (imagine psycological therapy sessions with 1 therapist and 1 individual, both of the speaking to each other in a conversation). I have several videos of such conversations. Examples: https://www.youtube.com/watch?v=8aDFvvjC6XM https://www.youtube.com/watch?v=8K4HW6_MvoU I will focus on events related to the hands that your model needs to identify: Single Hand event detection: • Hand position upper leg • Hand position lower leg • Hand position body • Hand position chair handles • Hand position mouth • Hand position cheek/face • Hand expressive during speaking (not touching anything) • Hand touch other hand (location of both hands using single hand) o Arms crossed o Hands crossed o Fingers move while in this position
7d1938edcfd3d3d6f77f0aac5b16c5fa
{ "intermediate": 0.14642669260501862, "beginner": 0.1611977070569992, "expert": 0.6923756003379822 }
6,444
Hi, I’ll provide you two codes i.e DQN and Evader. I want you to make the following modifications: I got this termination condition in place if np.linalg.norm( np.array(self.final_destination) - np.array(self.current_location)[:2]) < 0.5. If this condition satisfies then the car speed will become zero and it rests. So, for a DQN to learn what’s happening in the env I want you to implement this steps: 1. Update the scan_callback function such that for every single episode. You’ve implement no of episodes and max steps or time for each episode depending on our env since it’s somewhat a big grid with atleast 30 obstacles. the car moves from origin to the final point minimizing the following np.linalg.norm( np.array(self.final_destination) - np.array(self.current_location)[:2]). If it moves farther away from the point decrease the reward and if it moves closer to the final point increase the reward. And also if it hits an obstacle decrease the reward by some value and if avoids obstacles increase the reward by some value. Finally , by the time car reaches the final point, then agent should save the updated weights and rest. In test Mode, Implement the steps to load the saved weights and the car should choose the actions based on learned policy. The agent can learn on steering angles and details about obstacles, when to choose the best action etc. Based on this Modify the DQN which I’ll provide. First, I’ll provide Evader and later I provide DQN. Please read and understand each and every point mentioned carefully. Then proceed with the modifications. I’m always here to help you. Feel free to make modifications.Provide me the end to end updated, modified evader code. Let’s start! Here is the code for Evader Node: #! /usr/bin/env python3 from sensor_msgs.msg import LaserScan from ackermann_msgs.msg import AckermannDrive from nav_msgs.msg import Odometry from DQN import DQNAgentPytorch FORWARD = 0 LEFT = 1 RIGHT = 2 REVERSE = 3 ACTION_SPACE = [FORWARD, LEFT, RIGHT, REVERSE] class EvaderNode: def init(self, agent): rospy.init_node(‘evader_node’, anonymous=True) rospy.Subscriber(‘car_1/scan’, LaserScan, self.scan_callback) rospy.Subscriber(‘car_1/base/odom’, Odometry, self.odom_callback) self.drive_pub = rospy.Publisher(‘car_1/command’, AckermannDrive, queue_size=10) self.init_location = None # Set the initial location in odom_callback when available self.current_location = None # Will be updated in update_current_location method self.distance_threshold = 2 # meters self.angle_range = [(-150, -30), (30, 150)] self.agent = agent self.collision_threshold = 0.2 self.is_training = True # Flag to indicate if the agent is being trained self.init_odom_received = False self.latest_odom_msg = None self.reached_destination = False self.final_destination = (10, 10) # Set the final destination here def process_scan(self, scan): # Process the laser scan data to get the state input for the DQN state = np.array(scan.ranges)[::10] # Downsample the scan data for faster processing # return np.concatenate((state, self.current_location)) return state def check_collision(self, scan): for i in range(len(scan.ranges)): if scan.ranges[i] < self.collision_threshold: return True return False def action_to_drive_msg(self, action): drive_msg = AckermannDrive() if action == FORWARD: drive_msg.speed = 2.0 drive_msg.steering_angle = 0.0 elif action == LEFT: drive_msg.speed = 2.0 drive_msg.steering_angle = float(random.uniform(math.pi / 4, math.pi / 2)) elif action == RIGHT: drive_msg.speed = 2.0 drive_msg.steering_angle = float(random.uniform(-math.pi / 2, -math.pi / 4)) # elif action == REVERSE: # drive_msg.speed = -2.0 # drive_msg.steering_angle = 0.0 return drive_msg def reverse_car(self, reverse_distance): reverse_drive_msg = AckermannDrive() reverse_drive_msg.speed = -2.0 reverse_drive_msg.steering_angle = 0.0 reverse_duration = reverse_distance / (-reverse_drive_msg.speed) start_time = time.time() while time.time() - start_time < reverse_duration: self.drive_pub.publish(reverse_drive_msg) rospy.sleep(0.1) reverse_drive_msg.speed = 0.0 self.drive_pub.publish(reverse_drive_msg) def initialize_final_destination(self): init_x, init_y = self.current_location[:2] dest_x, dest_y = self.final_destination angle_to_dest = math.atan2(dest_y - init_y, dest_x - init_x) return angle_to_dest def scan_callback(self, scan): state = self.process_scan(scan) action = self.agent.choose_action(state, test=not self.is_training) collision_detected = self.check_collision(scan) # steer_angle = None if collision_detected and not self.reached_destination: print(‘Collision Detected’) self.reverse_car(0.2) # Set the reverse distance here #float(random.uniform(0, math.pi/2)) action = self.agent.choose_action(state, test=not self.is_training) # steer_angle = self.initialize_final_destination() drive_msg = self.action_to_drive_msg(action) # if steer_angle is not None: # drive_msg.steering_angle -= steer_angle # if self.latest_odom_msg is not None: # self.update_current_location(self.latest_odom_msg) # if not self.is_training: # if np.linalg.norm( # np.array(self.final_destination) - np.array(self.current_location)) < self.distance_threshold: # self.current_location = copy.deepcopy(self.init_location) # self.drive_pub.publish(drive_msg) # return # min_distance = min(state) # reward_collision = collision_detected and not self.reached_destination # reward = self.agent.calculate_reward(state, action, min_distance, reward_collision) done = False # set this flag to True if a termination condition is met # self.agent.add_experience(state, action, reward, state, done) # self.agent.train(32) # Set the batch size here self.drive_pub.publish(drive_msg) # Set the termination condition for training if np.linalg.norm( np.array(self.final_destination) - np.array(self.current_location)[:2]) < 0.5: if not self.reached_destination: print(‘Reached final destination!’) self.reached_destination = True # drive_msg = AckermannDrive() drive_msg.speed = 0.0 self.drive_pub.publish(drive_msg) # self.align_to_initial_point() # else: # print(‘Reached the initial point!’) # self.reached_destination = False # if self.is_training: # self.is_training = False # self.agent.save_weights(‘model_weights.pth’) # self.agent.load_weights(‘model_weights.pth’) def update_current_location(self, odom_msg): position = odom_msg.pose.pose.position orientation = odom_msg.pose.pose.orientation euler_angles = tf.transformations.euler_from_quaternion( (orientation.x, orientation.y, orientation.z, orientation.w)) self.current_location = ( position.x, position.y, euler_angles[2]) # (x, y, yaw) print(“Current Location of the Car:”, self.current_location[:2]) def odom_callback(self, odom_msg): if not self.init_odom_received: self.init_location = (odom_msg.pose.pose.position.x, odom_msg.pose.pose.position.y) print(f"Intial Location of the Car: {self.init_location}") self.init_odom_received = True self.update_current_location(odom_msg) self.latest_odom_msg = odom_msg if name == ‘main’: try: # Initialize the DQNAgentPytorch instance with the necessary environment and parameters action_space = ACTION_SPACE observation_space = np.zeros((360,)) # 360 laser scan equidistant points + (x, y) position + grid agent = DQNAgentPytorch(action_space, observation_space) # Initialize the EvaderNode instance with the DQNAgent node = EvaderNode(agent) # Wait for initial odometry information while not node.init_odom_received: rospy.sleep(0.1) rospy.spin() except rospy.ROSInterruptException: pass
5a66b9f2c3cb5a38904e5ec5c3f8ddbf
{ "intermediate": 0.3460831642150879, "beginner": 0.4063250422477722, "expert": 0.2475917488336563 }
6,445
It seems like you have outlined a project that involves optimizing the allocation of students to destinations for a semester abroad. You plan to use Genetic Algorithms to minimize the total cost of assignments while maximizing student satisfaction. The optimization process will be executed in a distributed manner, with students entering their preferences through a client software that connects to an assignment server. Here's an overview of how the project will work: Client Software: Students will use a client software to input their preferences for the destinations. The preferences could be ranked or weighted based on their preference level. Assignment Server: The assignment server will receive and process the preferences from the client software. It will continuously calculate the best assignment based on the available information at any given time. The server will store the current assignments in memory, but if it disconnects, the assignments will be lost, and no data about the students' preferences will be stored on the server's hard disk. Genetic Algorithms: The server will use Genetic Algorithms to optimize the allocation of students to destinations. Genetic Algorithms mimic the process of natural selection and evolution to find optimal solutions. They involve creating a population of potential solutions (assignments in this case), evaluating their fitness (cost), applying genetic operators (e.g., selection, crossover, mutation), and iteratively evolving the population to find better solutions. Optimization Process: The server will run the Genetic Algorithm process, repeatedly generating new assignments, evaluating their cost based on student preferences, and updating the population to converge towards an optimal assignment that minimizes the total cost while considering the maximum capacity of each destination. Real-time Updates: As the optimization process is running, any student can request their assignment status at any time. The server will show the current assignment to all students, reflecting the most up-to-date information available. Considerations: During the optimization process, it's essential to strike a balance between maximizing student satisfaction and avoiding overly privileged assignments. This can be achieved by incorporating fairness constraints or penalties within the cost function or by explicitly considering equity considerations during the optimization process. It's worth noting that the execution of Genetic Algorithms may require further implementation details such as defining the representation of assignments, designing the fitness evaluation function based on student preferences, determining the genetic operators, setting termination conditions, and configuring the population size and other algorithm parameters. Additionally, since you mentioned a distributed setup, you may need to consider how the client software and server communicate, handle concurrent requests, synchronize data updates, and ensure fault tolerance in case of server disconnection. Overall, this project aims to optimize the allocation of students to destinations by using Genetic Algorithms in a distributed environment, considering student preferences and capacity constraints while ensuring real-time updates for students.
0357c6dfc71ad4f12a1d6b19ad19ca5b
{ "intermediate": 0.22622253000736237, "beginner": 0.12341533601284027, "expert": 0.6503621339797974 }
6,446
In Azure Data factory, there's column and its expression. I want to create a new column that combines entries of two existing columns by '__'. So how shall expression be written?
5811dac30315e40d7c30573f070b5a84
{ "intermediate": 0.5193686485290527, "beginner": 0.2546018660068512, "expert": 0.22602948546409607 }
6,447
what is protocol networks
8675a21f92e050a4cf7013c21fff54af
{ "intermediate": 0.0925600677728653, "beginner": 0.13688543438911438, "expert": 0.7705545425415039 }
6,448
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. The basic class structure is as follows: 1. Core: - class Engine - This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.) 2. Window: - class Window - This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events. 3. Renderer: - class Renderer - This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines. - class Shader - To handle shader modules creation and destruction. - class Texture - To handle texture loading and destruction. - class Pipeline - To encapsulate the description and creation of a Vulkan graphics or compute pipeline. 4. Scene: - class Scene - This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering. - class GameObject - To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices. - class Camera - To store and manage camera properties such as position, rotation, view, and projection matrices. - class Mesh - To handle mesh data (e.g., vertices, indices, etc.) for individual objects. - class Material - To store and manage material properties such as colors, shaders, and textures. 5. Math: - Utilize GLM library to handle vector and matrix math operations. I want to add functionality to load 3d models using the ASSIMP library and render them using the engine. How would I got about doing this?
690078718826d548054ae19f780e5dc4
{ "intermediate": 0.4298076927661896, "beginner": 0.2931635081768036, "expert": 0.2770287096500397 }
6,449
how do i reference the functions defined in my server.js from app.js file, in my custom fresh desk app with platform version 2.3
cd86febc69f8943c19dc041967dfdc50
{ "intermediate": 0.45518672466278076, "beginner": 0.3989261984825134, "expert": 0.145887091755867 }
6,450
Мне нужна помощь в проекте. Твоя задача использовать язык Solidity, фреймворк MUD(второй версии), а для написания тестов использовать Foundry. Мне надо написать тесты для библиотеки LibExperience.sol . Эта библиотека связана с компонентом ExperienceComponent.sol . Так же в новой версии фреймворка MUD появились таблицы, который заменили компоненты. Код таблицы : // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /* Autogenerated file. Do not edit manually. */ // Import schema type import { SchemaType } from "@latticexyz/schema-type/src/solidity/SchemaType.sol"; // Import store internals import { IStore } from "@latticexyz/store/src/IStore.sol"; import { StoreSwitch } from "@latticexyz/store/src/StoreSwitch.sol"; import { StoreCore } from "@latticexyz/store/src/StoreCore.sol"; import { Bytes } from "@latticexyz/store/src/Bytes.sol"; import { Memory } from "@latticexyz/store/src/Memory.sol"; import { SliceLib } from "@latticexyz/store/src/Slice.sol"; import { EncodeArray } from "@latticexyz/store/src/tightcoder/EncodeArray.sol"; import { Schema, SchemaLib } from "@latticexyz/store/src/Schema.sol"; import { PackedCounter, PackedCounterLib } from "@latticexyz/store/src/PackedCounter.sol"; bytes32 constant _tableId = bytes32(abi.encodePacked(bytes16(""), bytes16("Experience"))); bytes32 constant ExperienceTableId = _tableId; library Experience { /** Get the table's schema */ function getSchema() internal pure returns (Schema) { SchemaType[] memory _schema = new SchemaType[](1); _schema[0] = SchemaType.UINT32_ARRAY; return SchemaLib.encode(_schema); } function getKeySchema() internal pure returns (Schema) { SchemaType[] memory _schema = new SchemaType[](1); _schema[0] = SchemaType.UINT256; return SchemaLib.encode(_schema); } /** Get the table's metadata */ function getMetadata() internal pure returns (string memory, string[] memory) { string[] memory _fieldNames = new string[](1); _fieldNames[0] = "value"; return ("Experience", _fieldNames); } /** Register the table's schema */ function registerSchema() internal { StoreSwitch.registerSchema(_tableId, getSchema(), getKeySchema()); } /** Register the table's schema (using the specified store) */ function registerSchema(IStore _store) internal { _store.registerSchema(_tableId, getSchema(), getKeySchema()); } /** Set the table's metadata */ function setMetadata() internal { (string memory _tableName, string[] memory _fieldNames) = getMetadata(); StoreSwitch.setMetadata(_tableId, _tableName, _fieldNames); } /** Set the table's metadata (using the specified store) */ function setMetadata(IStore _store) internal { (string memory _tableName, string[] memory _fieldNames) = getMetadata(); _store.setMetadata(_tableId, _tableName, _fieldNames); } /** Get value */ function get(uint256 entity) internal view returns (uint32[3] memory value) { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); bytes memory _blob = StoreSwitch.getField(_tableId, _primaryKeys, 0); return toStaticArray_uint32_3(SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_uint32()); } /** Get value (using the specified store) */ function get(IStore _store, uint256 entity) internal view returns (uint32[3] memory value) { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); bytes memory _blob = _store.getField(_tableId, _primaryKeys, 0); return toStaticArray_uint32_3(SliceLib.getSubslice(_blob, 0, _blob.length).decodeArray_uint32()); } /** Set value */ function set(uint256 entity, uint32[3] memory value) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); StoreSwitch.setField(_tableId, _primaryKeys, 0, EncodeArray.encode(fromStaticArray_uint32_3(value))); } /** Set value (using the specified store) */ function set(IStore _store, uint256 entity, uint32[3] memory value) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); _store.setField(_tableId, _primaryKeys, 0, EncodeArray.encode(fromStaticArray_uint32_3(value))); } /** Push an element to value */ function push(uint256 entity, uint32 _element) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); StoreSwitch.pushToField(_tableId, _primaryKeys, 0, abi.encodePacked((_element))); } /** Push an element to value (using the specified store) */ function push(IStore _store, uint256 entity, uint32 _element) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); _store.pushToField(_tableId, _primaryKeys, 0, abi.encodePacked((_element))); } /** Update an element of value at `_index` */ function update(uint256 entity, uint256 _index, uint32 _element) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); StoreSwitch.updateInField(_tableId, _primaryKeys, 0, _index * 4, abi.encodePacked((_element))); } /** Update an element of value (using the specified store) at `_index` */ function update(IStore _store, uint256 entity, uint256 _index, uint32 _element) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); _store.updateInField(_tableId, _primaryKeys, 0, _index * 4, abi.encodePacked((_element))); } /** Tightly pack full data using this table's schema */ function encode(uint32[3] memory value) internal view returns (bytes memory) { uint16[] memory _counters = new uint16[](1); _counters[0] = uint16(value.length * 4); PackedCounter _encodedLengths = PackedCounterLib.pack(_counters); return abi.encodePacked(_encodedLengths.unwrap(), EncodeArray.encode(fromStaticArray_uint32_3(value))); } /* Delete all data for given keys */ function deleteRecord(uint256 entity) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); StoreSwitch.deleteRecord(_tableId, _primaryKeys); } /* Delete all data for given keys (using the specified store) */ function deleteRecord(IStore _store, uint256 entity) internal { bytes32[] memory _primaryKeys = new bytes32[](1); _primaryKeys[0] = bytes32(uint256((entity))); _store.deleteRecord(_tableId, _primaryKeys); } } function toStaticArray_uint32_3(uint32[] memory _value) pure returns (uint32[3] memory _result) { // in memory static arrays are just dynamic arrays without the length byte assembly { _result := add(_value, 0x20) } } function fromStaticArray_uint32_3(uint32[3] memory _value) view returns (uint32[] memory _result) { _result = new uint32[](3); uint256 fromPointer; uint256 toPointer; assembly { fromPointer := _value toPointer := add(_result, 0x20) } Memory.copy(fromPointer, toPointer, 96); } 

Код LibExperience.sol :

 // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { IUint256Component } from "solecs/interfaces/IUint256Component.sol"; import { PStat, PS_L, ExperienceComponent, ID as ExperienceComponentID } from "./ExperienceComponent.sol"; import { Experience } from "../codegen/Tables.sol"; library LibExperience { error LibExperience__InvalidLevel(); error LibExperience__ExpNotInitialized(); uint32 constant MAX_LEVEL = 16; function getPStats(uint256 targetEntity) internal view returns (uint32[PS_L] memory result) { result = Experience.get(targetEntity); for (uint256 i; i < result.length; i++) { result[i] = _getLevel(result[i]); } } function getPStat(uint256 targetEntity, PStat pstatIndex) internal view returns (uint32) { uint32 exp = Experience.get(targetEntity)[uint256(pstatIndex)]; return _getLevel(exp); } function hasExp(uint256 targetEntity) internal view returns (bool) { uint32 exp = Experience.get(targetEntity); if (exp) { return true; } else { return false; } } function getExp(uint256 targetEntity) internal view returns (uint32[PS_L] memory) { return Experience.get(targetEntity); } /** * @dev Allow target to receive exp, set exp to 0s */ function initExp(uint256 targetEntity) internal { uint32[PS_L] memory exp; Experience.set(targetEntity, exp); } /** * @dev Increase target's experience * Exp must be initialized */ function increaseExp(uint256 targetEntity, uint32[PS_L] memory addExp) internal { // get current exp, or revert if it doesn't exist if (!Experience.get(targetEntity)) { revert LibExperience__ExpNotInitialized(); } uint32[PS_L] memory exp = Experience.get(targetEntity); // increase for (uint256 i; i < PS_L; i++) { exp[i] += addExp[i]; } // set increased exp Experience.set(targetEntity, exp); } /** * @dev Calculate aggregate level based on weighted sum of pstat exp */ function getAggregateLevel(uint256 targetEntity, uint32[PS_L] memory levelMul) internal view returns (uint32) { uint32[PS_L] memory exp = getExp(targetEntity); uint256 expTotal; uint256 mulTotal; for (uint256 i; i < PS_L; i++) { expTotal += exp[i] * levelMul[i]; mulTotal += levelMul[i]; } expTotal /= mulTotal; return _getLevel(expTotal); } /** * @dev Calculate level based on single exp value */ function _getLevel(uint256 expVal) private pure returns (uint32) { // expVal per level rises exponentially with polynomial easing // 1-0, 2-96, 3-312, 4-544, 5-804, 6-1121... for (uint32 level = 1; level < MAX_LEVEL; level++) { // (1<<i) == 2**i ; can't overflow due to maxLevel if (expVal < _getExpForLevel(level + 1)) { return level; } } return MAX_LEVEL; } /** * @dev Utility function to reverse a level into its required exp */ function _getExpForLevel(uint32 level) private pure returns (uint32) { if (level < 1 || level > MAX_LEVEL) revert LibExperience__InvalidLevel(); // this formula starts from 0, so adjust the arg if (level == 1) { return 0; } else { level -= 1; } return uint32(8 * (1 << level) - level ** 6 / 1024 + level * 200 - 120); } /** * @dev Get exp amount to get base primary to `pstats` (assuming 0 current exp). * This is a utility for testing */ function getExpForPStats(uint32[PS_L] memory pstats) internal pure returns (uint32[PS_L] memory exp) { for (uint256 i; i < PS_L; i++) { exp[i] = _getExpForLevel(pstats[i]); } } /** * @dev same as getExpForPStats but for 1 specific pstat */ function getExpForPStat(uint32 pstat) internal pure returns (uint32) { return _getExpForLevel(pstat); } } Код ExperienceComponent.sol :

// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { LibTypes } from "solecs/LibTypes.sol"; import { BareComponent } from "solecs/BareComponent.sol"; enum PStat { STRENGTH, ARCANA, DEXTERITY } uint256 constant PS_L = 3; uint256 constant ID = uint256(keccak256("component.Experience")); contract ExperienceComponent is BareComponent { constructor(address _world) BareComponent(_world, ID) {} function getSchema() public pure override returns (string[] memory keys, LibTypes.SchemaValue[] memory values) { keys = new string[](PS_L); values = new LibTypes.SchemaValue[](PS_L); keys[0] = "strength"; values[0] = LibTypes.SchemaValue.UINT32; keys[1] = "arcana"; values[1] = LibTypes.SchemaValue.UINT32; keys[2] = "dexterity"; values[2] = LibTypes.SchemaValue.UINT32; } function getValue(uint256 entity) public view returns (uint32[PS_L] memory result) { return abi.decode(getRawValue(entity), (uint32[3])); /* 3 == PS_L */ } function set(uint256 entity, uint32[PS_L] memory pstats) public { set(entity, abi.encode(pstats)); } } Так же я в своем проекте создал базу для тестов на Foundry, она называется BaseTest.sol , используй ее для написания контракта : // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { IUint256Component } from "solecs/interfaces/IUint256Component.sol"; import { World } from "solecs/World.sol"; import { getAddressById } from "solecs/utils.sol"; import { PRBTest } from "@prb/test/src/PRBTest.sol"; import { LibDeploy } from "../test/LibDeploy.sol"; // Components import { ExperienceComponent, ID as ExperienceComponentID } from "./charstat/ExperienceComponent.sol"; import { LifeCurrentComponent, ID as LifeCurrentComponentID } from "./charstat/LifeCurrentComponent.sol"; import { ManaCurrentComponent, ID as ManaCurrentComponentID } from "./charstat/ManaCurrentComponent.sol"; abstract contract BaseTest is PRBTest { World world; address internal alice; address internal bob; IUint256Component components; IUint256Component systems; // Components ExperienceComponent internal experienceComponent; LifeCurrentComponent internal lifeCurrentComponent; ManaCurrentComponent internal manaCurrentComponent; function setUp() public virtual { alice = address(bytes20(keccak256("alice"))); bob = address(bytes20(keccak256("bob"))); // deploy world world = new World(); world.init(); LibDeploy.deploy(address(this), address(world), false); // Assign all systems and components to storage vars for convenience components = world.components(); systems = world.systems(); // Components experienceComponent = ExperienceComponent(getAddressById(components, ExperienceComponentID)); lifeCurrentComponent = LifeCurrentComponent(getAddressById(components, LifeCurrentComponentID)); manaCurrentComponent = ManaCurrentComponent(getAddressById(components, ManaCurrentComponentID)); } }















I need help with a project. Your task is to use the Solidity language, the MUD framework, and use Foundry to write tests. I need to write tests for the LibExperience.sol library. This library is linked to the ExperienceComponent.sol component. LibExperience.sol code: // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { IUint256Component } from "solecs/interfaces/IUint256Component.sol"; import { getAddressById } from "solecs/utils.sol"; import { PStat, PS_L, ExperienceComponent, ID as ExperienceComponentID } from "./ExperienceComponent.sol"; library LibExperience { error LibExperience__InvalidLevel(); error LibExperience__ExpNotInitialized(); uint32 constant MAX_LEVEL = 16; struct Self { ExperienceComponent comp; uint256 targetEntity; } function __construct(IUint256Component components, uint256 targetEntity) internal view returns (Self memory) { return Self({ comp: ExperienceComponent(getAddressById(components, ExperienceComponentID)), targetEntity: targetEntity }); } function getPStats(Self memory __self) internal view returns (uint32[PS_L] memory result) { result = __self.comp.getValue(__self.targetEntity); for (uint256 i; i < result.length; i++) { result[i] = _getLevel(result[i]); } } function getPStat(Self memory __self, PStat pstatIndex) internal view returns (uint32) { uint32 exp = __self.comp.getValue(__self.targetEntity)[uint256(pstatIndex)]; return _getLevel(exp); } function hasExp(Self memory __self) internal view returns (bool) { return __self.comp.has(__self.targetEntity); } function getExp(Self memory __self) internal view returns (uint32[PS_L] memory) { return __self.comp.getValue(__self.targetEntity); } /** * @dev Allow target to receive exp, set exp to 0s */ function initExp(Self memory __self) internal { uint32[PS_L] memory exp; __self.comp.set(__self.targetEntity, exp); } /** * @dev Increase target's experience * Exp must be initialized */ function increaseExp(Self memory __self, uint32[PS_L] memory addExp) internal { // get current exp, or revert if it doesn't exist if (!__self.comp.has(__self.targetEntity)) { revert LibExperience__ExpNotInitialized(); } uint32[PS_L] memory exp = __self.comp.getValue(__self.targetEntity); // increase for (uint256 i; i < PS_L; i++) { exp[i] += addExp[i]; } // set increased exp __self.comp.set(__self.targetEntity, exp); } /** * @dev Calculate aggregate level based on weighted sum of pstat exp */ function getAggregateLevel(Self memory __self, uint32[PS_L] memory levelMul) internal view returns (uint32) { uint32[PS_L] memory exp = getExp(__self); uint256 expTotal; uint256 mulTotal; for (uint256 i; i < PS_L; i++) { expTotal += exp[i] * levelMul[i]; mulTotal += levelMul[i]; } expTotal /= mulTotal; return _getLevel(expTotal); } /** * @dev Calculate level based on single exp value */ function _getLevel(uint256 expVal) private pure returns (uint32) { // expVal per level rises exponentially with polynomial easing // 1-0, 2-96, 3-312, 4-544, 5-804, 6-1121... for (uint32 level = 1; level < MAX_LEVEL; level++) { // (1<<i) == 2**i ; can't overflow due to maxLevel if (expVal < _getExpForLevel(level + 1)) { return level; } } return MAX_LEVEL; } /** * @dev Utility function to reverse a level into its required exp */ function _getExpForLevel(uint32 level) private pure returns (uint32) { if (level < 1 || level > MAX_LEVEL) revert LibExperience__InvalidLevel(); // this formula starts from 0, so adjust the arg if (level == 1) { return 0; } else { level -= 1; } return uint32(8 * (1 << level) - level ** 6 / 1024 + level * 200 - 120); } /** * @dev Get exp amount to get base primary to `pstats` (assuming 0 current exp). * This is a utility for testing */ function getExpForPStats(uint32[PS_L] memory pstats) internal pure returns (uint32[PS_L] memory exp) { for (uint256 i; i < PS_L; i++) { exp[i] = _getExpForLevel(pstats[i]); } } /** * @dev same as getExpForPStats but for 1 specific pstat */ function getExpForPStat(uint32 pstat) internal pure returns (uint32) { return _getExpForLevel(pstat); } }

ExperienceComponent.sol code: // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { LibTypes } from "solecs/LibTypes.sol"; import { BareComponent } from "solecs/BareComponent.sol"; enum PStat { STRENGTH, ARCANA, DEXTERITY } uint256 constant PS_L = 3; uint256 constant ID = uint256(keccak256("component.Experience")); contract ExperienceComponent is BareComponent { constructor(address _world) BareComponent(_world, ID) {} function getSchema() public pure override returns (string[] memory keys, LibTypes.SchemaValue[] memory values) { keys = new string[](PS_L); values = new LibTypes.SchemaValue[](PS_L); keys[0] = "strength"; values[0] = LibTypes.SchemaValue.UINT32; keys[1] = "arcana"; values[1] = LibTypes.SchemaValue.UINT32; keys[2] = "dexterity"; values[2] = LibTypes.SchemaValue.UINT32; } function getValue(uint256 entity) public view returns (uint32[PS_L] memory result) { return abi.decode(getRawValue(entity), (uint32[3])); /* 3 == PS_L */ } function set(uint256 entity, uint32[PS_L] memory pstats) public { set(entity, abi.encode(pstats)); } }

I also created a base for tests on Foundry in my project, it is called BaseTest.sol , use it to write a contract: 
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import { IUint256Component } from "solecs/interfaces/IUint256Component.sol"; import { World } from "solecs/World.sol"; import { getAddressById } from "solecs/utils.sol"; import { PRBTest } from "@prb/test/src/PRBTest.sol"; import { LibDeploy } from "../test/LibDeploy.sol"; // Components import { ExperienceComponent, ID as ExperienceComponentID } from "./charstat/ExperienceComponent.sol"; import { LifeCurrentComponent, ID as LifeCurrentComponentID } from "./charstat/LifeCurrentComponent.sol"; import { ManaCurrentComponent, ID as ManaCurrentComponentID } from "./charstat/ManaCurrentComponent.sol"; abstract contract BaseTest is PRBTest { World world; address internal alice; address internal bob; IUint256Component components; IUint256Component systems; // Components ExperienceComponent internal experienceComponent; LifeCurrentComponent internal lifeCurrentComponent; ManaCurrentComponent internal manaCurrentComponent; function setUp() public virtual { alice = address(bytes20(keccak256("alice"))); bob = address(bytes20(keccak256("bob"))); // deploy world world = new World(); world.init(); LibDeploy.deploy(address(this), address(world), false); // Assign all systems and components to storage vars for convenience components = world.components(); systems = world.systems(); // Components experienceComponent = ExperienceComponent(getAddressById(components, ExperienceComponentID)); lifeCurrentComponent = LifeCurrentComponent(getAddressById(components, LifeCurrentComponentID)); manaCurrentComponent = ManaCurrentComponent(getAddressById(components, ManaCurrentComponentID)); } }
0afff072ea66b02da80f95ec7b05632a
{ "intermediate": 0.34744229912757874, "beginner": 0.47642379999160767, "expert": 0.17613385617733002 }
6,451
HI
f40297a185043805fe8c6abfb485a352
{ "intermediate": 0.32988452911376953, "beginner": 0.2611807882785797, "expert": 0.40893468260765076 }
6,452
I would like to write a VBA code that does the following When I create a new entry in the last column of Column A, the last entry in Column K is calculated
6907ca9ae024cb9965607fe41f91424a
{ "intermediate": 0.23979681730270386, "beginner": 0.16450875997543335, "expert": 0.595694363117218 }
6,453
I would like to write a VBA code where if there is a change in column A, it will calculate the formula in the last empty cell of column K
779ed632683adcddb227efe1bd5e8513
{ "intermediate": 0.35752299427986145, "beginner": 0.09229011088609695, "expert": 0.5501868724822998 }
6,454
import os from glob import glob import librosa import numpy as np from sklearn.model_selection import train_test_split import random # New function to generate random vad_segments def get_random_vad_segments(samples, num_segments=10): vad_segments = [] for sample in samples: sample_segments = [] sample_length = len(sample) for _ in range(num_segments): start = random.randint(0, sample_length - 1) end = random.randint(start + 1, sample_length) segment = [start, end] sample_segments.append(segment) vad_segments.append(sample_segments) return vad_segments # Load the dataset and create training and testing sets directory = "C:\Users\lpoti\Documents\DS_21\audio_yes_no\waves_yesno 2" X, labels, sr, files = load_dataset(directory) # Generate random vad_segments data vad_segments = get_random_vad_segments(X) X, y = make_dataset(X, labels, vad_segments) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) num_train_samples = len(X_train) num_test_samples = len(X_test) print(f"Number of train samples: {num_train_samples}") print(f"Number of test samples: {num_test_samples}")
8e883a10cad02d05a7583202112cf9b6
{ "intermediate": 0.47192615270614624, "beginner": 0.2804713845252991, "expert": 0.24760247766971588 }
6,455
failed to solve: process "/bin/sh -c wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb" did not complete successfully: exit code: 4 when creating docker compose build
2c7b58ba14316be126858e2733a0fa5e
{ "intermediate": 0.46779710054397583, "beginner": 0.32892337441444397, "expert": 0.2032795548439026 }
6,456
how do i update object properties in javacscript
a302284f6918b2c915a8c92ab2deafb2
{ "intermediate": 0.7559518814086914, "beginner": 0.12408430874347687, "expert": 0.11996385455131531 }
6,457
how to figure that my docker container has a strong internet connection
d8491fccd4588883e79da6fd4fc097d7
{ "intermediate": 0.3647976815700531, "beginner": 0.30971065163612366, "expert": 0.325491726398468 }
6,458
def preprocess(text): # TODO return text 在#TODO的地方填充python代码,要求To prepare the data for the text analysis, we should: - Filter texts with only letters and numbers - Turn the texts into lower case > **TODO** Complete the `preprocess` function, which takes a piece of texts as input (not necessary of type `str`), you should convert it to `str`, and outputs the preprocessed string. Some functions that might be helpful: - `re.sub` - `str.lower`
2da1540c905c53fc00772e778318bc2b
{ "intermediate": 0.5847099423408508, "beginner": 0.1345081329345703, "expert": 0.28078189492225647 }
6,459
explain quake 3 fast square root algorithm in detail
2023a7cd01ba56735dfb3bdc621b44d6
{ "intermediate": 0.036197926849126816, "beginner": 0.04316578805446625, "expert": 0.9206362366676331 }
6,460
write basic pseudorandom generator in Dart which takes seed and length as arguments and outputs list of integers ranging from 2 to 8. it must be fast and not dependent on length for seeding. if we use this function twice it MUST provide exactly matching output
6b0524e9a1aa26416220c74833dd7168
{ "intermediate": 0.40363526344299316, "beginner": 0.24661165475845337, "expert": 0.3497530519962311 }
6,461
access and work with global storage in pinia vuejs
67e434a4717e648ac2b4ffe11a7462de
{ "intermediate": 0.6927815079689026, "beginner": 0.12599042057991028, "expert": 0.1812281608581543 }
6,462
what does the following code do List<int> generateRandom(int seed, int length) { final List<int> result = []; int current = seed; for (int i = 0; i < length; i++) { current = ((current * 0x41C64E6D) ^ current) >> 30; result.add(2 + (current & 0x7)); } return result; }
8e6ca5dadd14a5e382d37df653edd21a
{ "intermediate": 0.36687472462654114, "beginner": 0.3327660858631134, "expert": 0.30035921931266785 }
6,463
php creae a table with id username email password and reg_date
0fe57e2023adf0d28b4f13933126766d
{ "intermediate": 0.4138830602169037, "beginner": 0.2601945102214813, "expert": 0.3259223699569702 }
6,464
import librosa import numpy as np def energy_vad(audio, sr, frame_size=25, hop_size=10, energy_threshold=0.02, zcr_threshold=0.02): frame_length = int(sr * frame_size / 1000) hop_length = int(sr * hop_size / 1000) energy = np.square(librosa.feature.rms(audio, frame_length=frame_length, hop_length=hop_length)) zcr = librosa.feature.zero_crossing_rate(audio, frame_length=frame_length, hop_length=hop_length) speech_energy = np.squeeze(energy) > energy_threshold speech_zcr = np.squeeze(zcr) > zcr_threshold speech_segments = [] speech = False start = 0 for i in range(len(speech_energy)): if speech_energy[i] and speech_zcr[i]: if not speech: speech = True start = i * hop_length else: if speech: speech = False end = i * hop_length speech_segments.append((start, end)) return speech_segments # Load the dataset directory = "/content/drive/MyDrive/School21/day09/datasets/audio_yes_no/waves_yesno 2" X, labels, sr_list, files = load_dataset(directory) # Apply VAD to find speech segments for i in range(10): # Just showing the results for the first 10 files print(f"File: {files[i]}".ljust(25), end='') vad_segments = energy_vad(X[i], sr_list[i]) print(f"Speech Segments: {vad_segments}")
9825427ba8be2fe53652d7513600bbb3
{ "intermediate": 0.4939734935760498, "beginner": 0.25631508231163025, "expert": 0.24971143901348114 }
6,465
refactor with curly braces parameters of the function List<int> generateRandom(int seed, int length, int rangeStart, int rangeEnd) { final List<int> result = []; int current = seed; for (int i = 0; i < length; i++) { current = ((current * 0x41C64E6D) ^ current) >> 30; int randomNumber = rangeStart + (current.abs() % (rangeEnd - rangeStart)); result.add(randomNumber); } return result; }
b67dc38545dd6b3544cd438ea92ec75b
{ "intermediate": 0.3178268373012543, "beginner": 0.37709057331085205, "expert": 0.3050825297832489 }
6,466
format as a code block my next prompt
e58e15020fc17ad6c486f437cdc96a61
{ "intermediate": 0.16087107360363007, "beginner": 0.6523410677909851, "expert": 0.18678784370422363 }
6,467
how could you improve this const handleInboundToggle = () => { setInboundVisible((current) => !current); }; const handleWhatsAppToggle = () => { enableWhatsapp((current) => !current); setInboundVisible(false); };
3d124527e2587e806dd033775ef77c88
{ "intermediate": 0.48115214705467224, "beginner": 0.3131531774997711, "expert": 0.20569467544555664 }
6,468
please make my next prompt appear as a code block in Dart
09756759f95995a024f13a5b75136e31
{ "intermediate": 0.29967206716537476, "beginner": 0.42891281843185425, "expert": 0.2714151442050934 }
6,469
when i use wget and curl in downloading google-chrome in docker, it is connected to https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb but it stops working and everything is freezed. plus i can download google-chrome in terminal but not in docker. what is the problem
5de8f79142684e7bb39660bf8a4ef2d7
{ "intermediate": 0.43564730882644653, "beginner": 0.3463347256183624, "expert": 0.21801796555519104 }
6,470
write hello world in dart
5e7e47da98023981e0edd9d8b68a32d7
{ "intermediate": 0.29368919134140015, "beginner": 0.4362125098705292, "expert": 0.2700982689857483 }
6,471
make some random small code snippet in Dart
14172f392d77325016bb024175c8c337
{ "intermediate": 0.3680321276187897, "beginner": 0.3587624430656433, "expert": 0.2732054591178894 }
6,472
please remember my function to start working with
d6d76a9e98afb385f65e3e4af4c1374a
{ "intermediate": 0.363000750541687, "beginner": 0.280300498008728, "expert": 0.35669878125190735 }
6,473
Woher kommt die Blaue Farbe bei actionlabel? Füge einen Border ganz ganz dünn ein, der nur um das bild geht und unten soll der rahmen nicht sein. Wo passe ich den Abstand an? import 'package:flutter/material.dart'; import 'package:patient_app/theme/patient_app_colors.dart'; import 'package:patient_app/theme/patient_app_theme.dart' as theme; import 'package:patient_app/widgets/overlay_ink.dart'; import 'package:photo_view/photo_view.dart'; class LocationMapCard extends StatelessWidget { const LocationMapCard({ Key? key, required this.actionLabel, required this.imageName, }) : super(key: key); final String actionLabel; final String imageName; @override Widget build(BuildContext context) { return Card( shape: RoundedRectangleBorder( borderRadius: theme.cardBorderRadius, ), color: AppColors.cardColor, elevation: theme.cardElevation, margin: EdgeInsets.zero, child: Stack( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(theme.radiusValue), topRight: Radius.circular(theme.radiusValue)), child: Image.asset(imageName, fit: BoxFit.fill), ), Padding( padding: theme.extraSmallEdgeInsets, child: TextButton( style: theme.PatientAppTheme.actionButtonStyle(), onPressed: () { openDialog(context); }, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( actionLabel, style: Theme.of(context).textTheme.headline3, ), const Icon(Icons.map, color: theme.defaultIconColor), ], ), ), ) ], ), OverlayInk( borderRadius: theme.cardBorderRadius, hoverColor: AppColors.transparent, onTap: () { openDialog(context); }, ), ], ), ); } void openDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( backgroundColor: AppColors.transparent, elevation: theme.imageDialogElevation, child: PhotoView( backgroundDecoration: const BoxDecoration( color: AppColors.transparent, ), tightMode: true, minScale: PhotoViewComputedScale.contained, maxScale: PhotoViewComputedScale.covered * 1.8, initialScale: PhotoViewComputedScale.contained, imageProvider: AssetImage(imageName), heroAttributes: const PhotoViewHeroAttributes(tag: 'appointment_location_plan'), ), ); }, ); } }
a70289c61ef0e6a5381745399c38b265
{ "intermediate": 0.40108752250671387, "beginner": 0.478704571723938, "expert": 0.12020791321992874 }
6,474
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. The basic class structure is as follows: 1. Core: - class Engine - This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.) 2. Window: - class Window - This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events. 3. Renderer: - class Renderer - This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines. - class Shader - To handle shader modules creation and destruction. - class Texture - To handle texture loading and destruction. - class Pipeline - To encapsulate the description and creation of a Vulkan graphics or compute pipeline. 4. Scene: - class Scene - This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering. - class GameObject - To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices. - class Camera - To store and manage camera properties such as position, rotation, view, and projection matrices. - class Mesh - To handle mesh data (e.g., vertices, indices, etc.) for individual objects. - class Material - To store and manage material properties such as colors, shaders, and textures. 5. Math: - Utilize GLM library to handle vector and matrix math operations. Here are the header files for context: BufferUtils.h: #pragma once #include <vulkan/vulkan.h> #include <stdint.h> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties); void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); } Camera.h: #pragma once #include <glm/glm.hpp> class Camera { public: Camera(); ~Camera(); void Initialize(float aspectRatio); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); const glm::mat4& GetViewMatrix() const; const glm::mat4& GetProjectionMatrix() const; private: glm::vec3 position; glm::vec3 rotation; glm::mat4 viewMatrix; glm::mat4 projectionMatrix; void UpdateViewMatrix(); }; Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(const Mesh& mesh, const Material& material); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh mesh; Material material; void UpdateModelMatrix(); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" class Material { public: Material(); ~Material(); void Initialize(const Shader& vertexShader, const Shader& fragmentShader, const Texture& texture, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void Cleanup(); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; private: VkDevice device; Shader vertexShader; Shader fragmentShader; Texture texture; VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Renderer.h: #pragma once #include <vulkan/vulkan.h> #include "Window.h" #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); private: bool shutdownInProgress; std::vector<VkImage> swapChainImages; std::vector<VkImageView> swapChainImageViews; VkExtent2D swapChainExtent; VkRenderPass renderPass; uint32_t imageIndex; VkFormat swapChainImageFormat; std::vector<VkCommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; Scene.h: #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); private: std::vector<GameObject*> gameObjects; Camera camera; }; Shader.h: #pragma once #include <vulkan/vulkan.h> #include <string> class Shader { public: Shader(); ~Shader(); void LoadFromFile(const std::string& filename, VkDevice device, VkShaderStageFlagBits stage); void Cleanup(); VkPipelineShaderStageCreateInfo GetPipelineShaderStageCreateInfo() const; private: VkDevice device; VkShaderModule shaderModule; VkShaderStageFlagBits stage; }; Texture.h: #pragma once #include <vulkan/vulkan.h> #include "stb_image.h" // Include the stb_image header #include "BufferUtils.h" #include <string> class Texture { public: Texture(); ~Texture(); void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); VkImageView GetImageView() const; VkSampler GetSampler() const; private: VkDevice device; VkImage image; VkDeviceMemory imageMemory; VkImageView imageView; VkSampler sampler; VkPhysicalDevice physicalDevice; VkCommandPool commandPool; VkQueue graphicsQueue; void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties); void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels); void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels); void CreateSampler(uint32_t mipLevels); void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height); // Additional helper functions for texture loading… }; Window.h: #pragma once #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> class Window { public: Window(int width = 800, int height = 600, const char* title = "Game Engine"); ~Window(); void Initialize(); void PollEvents(); void Shutdown(); bool ShouldClose() const; GLFWwindow* GetWindow() const; float GetDeltaTime(); private: static void FramebufferResizeCallback(GLFWwindow* window, int width, int height); static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); int width; int height; const char* title; GLFWwindow* window; double lastFrameTime; }; I want to add functionality to load 3d models using the ASSIMP library and render them using the engine. How would I got about doing this?
a08068e97d2a006bad8a3ff6bda14f1d
{ "intermediate": 0.37801146507263184, "beginner": 0.38560304045677185, "expert": 0.2363855093717575 }
6,475
<script> var countdownDate = new Date("Oct 24, 2038 00:00:00").getTime(); var x = setInterval(function() { var now = new Date().getTime(); var distance = countdownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("days").innerHTML = days; document.getElementById("hours").innerHTML = hours; document.getElementById("minutes").innerHTML = minutes; document.getElementById("seconds").innerHTML = seconds; if (distance < 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "Süre doldu!"; } }, 1000); </script> optimize this code
c43a643c632c68ae7a8e287e2a3b80b3
{ "intermediate": 0.3525547981262207, "beginner": 0.37145474553108215, "expert": 0.27599039673805237 }
6,476
You are tasked with creating a consent banner in PowerShell. Your consent banner needs to contain: The current date The username of the current user The machine name of the current machine Finally, save off all PowerShell commands run by the user and do not alert the user to this behavior.
fa97203e926d709ae8ae29471934448f
{ "intermediate": 0.2797562777996063, "beginner": 0.2184056043624878, "expert": 0.5018381476402283 }
6,477
3, Class optional <T>
c150297f054fc3d55da52bd404c2397c
{ "intermediate": 0.26505106687545776, "beginner": 0.4827665090560913, "expert": 0.25218239426612854 }
6,478
hello
0e543567cc55793b6355fce950b61f0b
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
6,479
Fix up my java code so that whatever value is selected in the combo boxes will be added to a variable "totales" and once the window "Receipt" pops up, it will show "totales" in the label "realtotal"import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.border.TitledBorder; import javax.swing.border.EtchedBorder; import java.awt.Color; import javax.swing.border.BevelBorder; import javax.swing.border.CompoundBorder; import javax.swing.border.LineBorder; import javax.swing.UIManager; import javax.swing.border.SoftBevelBorder; import javax.swing.border.MatteBorder; import java.awt.GridLayout; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import javax.swing.BoxLayout; import java.awt.FlowLayout; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class PizzaOrder extends JFrame { private JPanel contentPane; private JPanel ToppingSelect; private JTextField NumPizza; private JTextField NumTopping; private JTextField NumBreuvage; private JButton Ajouter; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { PizzaOrder frame = new PizzaOrder(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public PizzaOrder() { setTitle("Order"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 630, 689); contentPane = new JPanel(); contentPane.setBackground(new Color(255, 147, 0)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel Menu = new JPanel(); Menu.setBackground(new Color(255, 147, 0)); Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); Menu.setBounds(6, 6, 618, 158); contentPane.add(Menu); Menu.setLayout(new GridLayout(0, 3, 0, 0)); JPanel PizzaPrice = new JPanel(); PizzaPrice.setBackground(new Color(255, 147, 0)); PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null)); Menu.add(PizzaPrice); PizzaPrice.setLayout(null); JLabel PetitPizza = new JLabel("Petit: 6.79$"); PetitPizza.setBounds(17, 21, 72, 16); PizzaPrice.add(PetitPizza); JLabel MoyenPizza = new JLabel("Moyen: 8.29$"); MoyenPizza.setBounds(17, 40, 85, 16); PizzaPrice.add(MoyenPizza); JLabel LargePizza = new JLabel("Large: 9.49$"); LargePizza.setBounds(17, 59, 85, 16); PizzaPrice.add(LargePizza); JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$"); ExtraLargePizza.setBounds(17, 78, 127, 16); PizzaPrice.add(ExtraLargePizza); JLabel FetePizza = new JLabel("Fete: 15.99$"); FetePizza.setBounds(17, 97, 93, 16); PizzaPrice.add(FetePizza); JPanel ToppingPrice = new JPanel(); ToppingPrice.setBackground(new Color(255, 147, 0)); ToppingPrice.setLayout(null); ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); Menu.add(ToppingPrice); JLabel Petittopping = new JLabel("Petit: 1.20$"); Petittopping.setBounds(17, 21, 72, 16); ToppingPrice.add(Petittopping); JLabel Moyentopping = new JLabel("Moyen: 1.40$"); Moyentopping.setBounds(17, 40, 85, 16); ToppingPrice.add(Moyentopping); JLabel Largetopping = new JLabel("Large: 1.60$"); Largetopping.setBounds(17, 59, 85, 16); ToppingPrice.add(Largetopping); JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$"); ExtraLargetopping.setBounds(17, 78, 127, 16); ToppingPrice.add(ExtraLargetopping); JLabel Fetetopping = new JLabel("Fete: 2.30$"); Fetetopping.setBounds(17, 97, 93, 16); ToppingPrice.add(Fetetopping); JPanel BreuvagePrice = new JPanel(); BreuvagePrice.setBackground(new Color(255, 147, 0)); BreuvagePrice.setLayout(null); BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); Menu.add(BreuvagePrice); JLabel Pop = new JLabel("Pop: 1.10$"); Pop.setBounds(17, 21, 72, 16); BreuvagePrice.add(Pop); JLabel Jus = new JLabel("Jus: 1.35$"); Jus.setBounds(17, 40, 85, 16); BreuvagePrice.add(Jus); JLabel Eau = new JLabel("Eau: 1.00$"); Eau.setBounds(17, 59, 85, 16); BreuvagePrice.add(Eau); JPanel PizzaSelect = new JPanel(); PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); PizzaSelect.setBackground(new Color(255, 147, 0)); PizzaSelect.setBounds(16, 187, 350, 300); contentPane.add(PizzaSelect); PizzaSelect.setLayout(null); JComboBox<String> ChoixPizza = new JComboBox<String>(); ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values())); ChoixPizza.setBounds(44, 8, 126, 27); ChoixPizza.setMaximumRowCount(5); PizzaSelect.add(ChoixPizza); NumPizza = new JTextField(); NumPizza.setBounds(175, 8, 130, 26); PizzaSelect.add(NumPizza); NumPizza.setColumns(10); JLabel PizzaIcon = new JLabel(""); PizzaIcon.setBounds(6, 6, 350, 279); PizzaSelect.add(PizzaIcon); PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png"))); JPanel ToppingSelect; ToppingSelect = new JPanel(); ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); ToppingSelect.setBackground(new Color(255, 147, 0)); ToppingSelect.setBounds(400, 187, 208, 129); contentPane.add(ToppingSelect); ToppingSelect.setLayout(null); JComboBox<String> ChoixTopping = new JComboBox<String>();; ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values())); ChoixTopping.setBounds(41, 8, 126, 27); ChoixTopping.setMaximumRowCount(5); ToppingSelect.add(ChoixTopping); NumTopping = new JTextField(); NumTopping.setBounds(39, 40, 130, 26); NumTopping.setColumns(10); ToppingSelect.add(NumTopping); JLabel ToppingIcon = new JLabel(""); ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png"))); ToppingIcon.setBounds(6, 8, 208, 109); ToppingSelect.add(ToppingIcon); JPanel BreuvageSelect = new JPanel(); BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); BreuvageSelect.setBackground(new Color(255, 147, 0)); BreuvageSelect.setBounds(400, 358, 208, 129); contentPane.add(BreuvageSelect); BreuvageSelect.setLayout(null); JComboBox<String> ChoixBreuvage = new JComboBox<String>();; ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values())); ChoixBreuvage.setBounds(64, 8, 79, 27); ChoixBreuvage.setMaximumRowCount(3); BreuvageSelect.add(ChoixBreuvage); NumBreuvage = new JTextField(); NumBreuvage.setBounds(39, 40, 130, 26); NumBreuvage.setColumns(10); BreuvageSelect.add(NumBreuvage); JLabel BreuvageIcon = new JLabel(""); BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png"))); BreuvageIcon.setBounds(0, 0, 209, 129); BreuvageSelect.add(BreuvageIcon); JButton Quitter = new JButton("Quitter"); Quitter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); Quitter.setBounds(33, 552, 160, 50); contentPane.add(Quitter); Ajouter = new JButton("Ajouter"); JButton jButton = new JButton(); jButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { }}); Ajouter.setBounds(234, 552, 160, 50); contentPane.add(Ajouter); JButton Payer = new JButton("Payer"); Payer.setBounds(431, 552, 160, 50); contentPane.add(Payer); Payer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Receipt receiptWindow = new Receipt(); receiptWindow.setVisible(true); setVisible(false); } }); }} import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.border.TitledBorder; import javax.swing.ImageIcon; import javax.swing.JList; import javax.swing.border.LineBorder; import java.awt.Color; import java.awt.Font; public class Receipt extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Receipt frame = new Receipt(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Receipt() { setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 474, 521); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBounds(6, 6, 241, 363); panel.setBorder(null); contentPane.add(panel); panel.setLayout(null); JLabel realtotale = new JLabel(); realtotale.setBounds(57, 208, 281, 47); panel.add(realtotale); JList list = new JList(); list.setBorder(new LineBorder(new Color(0, 0, 0))); list.setBounds(24, 246, 165, -147); panel.add(list); JLabel Order = new JLabel("Order:"); Order.setFont(new Font("Zapfino", Font.PLAIN, 13)); Order.setBounds(22, 59, 61, 24); panel.add(Order); JLabel Total = new JLabel("Total +TAX:"); Total.setBounds(43, 275, 75, 16); panel.add(Total); JLabel ReceiptIcon = new JLabel(""); ReceiptIcon.setBounds(0, 6, 241, 363); ReceiptIcon.setIcon(new ImageIcon(Receipt.class.getResource("/Image/ReceiptImage.png"))); panel.add(ReceiptIcon); } }
37b46cee6a2575299de96e73c511679a
{ "intermediate": 0.29055070877075195, "beginner": 0.4398254156112671, "expert": 0.2696238160133362 }
6,480
hi
951db34056b27658e7aa3ba25c2a57d1
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
6,481
hey,can you make a whole undertale judgment day fan-game with random sanses and a lobby and a win system and a coin system and a kills system with working boss attacks?
0b506c7d79118c6a64731aaa96223b3a
{ "intermediate": 0.33316728472709656, "beginner": 0.3336654603481293, "expert": 0.33316728472709656 }
6,482
please use shell to archieve the function:
cb4f8655eb274b1638da0b2edc4cd7cc
{ "intermediate": 0.28411149978637695, "beginner": 0.46173563599586487, "expert": 0.2541528642177582 }
6,483
I will provide you disassembly from a computer game that runs in MS-DOS. The game was written in C with a Watcom compiler. Some library function calls are already identified. Explain the functions I give to you and suggest names and C-language function signatures for them, including which parameters map to which registers or stack values. Also suggest names for global values if you have enough context to do so. DAT_0000046c refers to the memory at address 0x46c. FUN_0007f671 PUSH EBP MOV EBP,ESP PUSH EBX PUSH ECX PUSH EDX PUSH ESI PUSH EDI SUB ESP,0x4 CALL FUN_000ce8b2 MOV [DAT_001a59cc],EAX MOV dword ptr [EBP + local_1c],DAT_0000046c MOV EAX,dword ptr [EBP + local_1c] MOV EAX=>DAT_0000046c,dword ptr [EAX] MOV [DAT_001a59dc],EAX LEA ESP=>local_18,[EBP + -0x14] POP EDI POP ESI POP EDX POP ECX POP EBX POP EBP RET FUN_0007f6a4 PUSH EBP MOV EBP,ESP PUSH EBX PUSH ECX PUSH EDX PUSH ESI PUSH EDI SUB ESP,0xc MOV EAX,[DAT_001a59cc] MOV [DAT_001a59e0],EAX MOV EAX,[DAT_001a59dc] MOV [DAT_001a59e4],EAX CALL FUN_000ce8b2 MOV [DAT_001a59cc],EAX MOV dword ptr [EBP + local_1c],DAT_0000046c MOV EAX,dword ptr [EBP + local_1c] MOV EAX=>DAT_0000046c,dword ptr [EAX] MOV [DAT_001a59dc],EAX MOV EAX,[DAT_001a59dc] CMP EAX,dword ptr [DAT_001a59e4] JNZ LAB_0007f6fe MOV EAX,[DAT_001a59e0] SUB EAX,dword ptr [DAT_001a59cc] MOV dword ptr [EBP + local_24],EAX JMP LAB_0007f726 LAB_0007f6fe MOV EAX,[DAT_001a59dc] SUB EAX,dword ptr [DAT_001a59e4] DEC EAX IMUL EDX,EAX,0xffff MOV EAX,0xffff SUB EAX,dword ptr [DAT_001a59cc] ADD EAX,dword ptr [DAT_001a59e0] ADD EAX,EDX MOV dword ptr [EBP + local_24],EAX LAB_0007f726 CMP dword ptr [EBP + local_24],0x2710 JNC LAB_0007f745 MOV EAX,0xffff SUB EAX,dword ptr [DAT_001a59cc] MOV EDX,dword ptr [DAT_001a59e0] ADD EDX,EAX MOV dword ptr [EBP + local_24],EDX LAB_0007f745 IMUL EAX,dword ptr [EBP + local_24],0x3e8 MOV EBX,DAT_001234dc XOR EDX,EDX DIV EBX SHR EAX,0x1 MOV EBX,EAX MOV EAX,[DAT_001a59d8] SHL EAX,0x2 MOV dword ptr [EAX + DAT_001a5408],EBX MOV EAX,[DAT_001a59d8] SHL EAX,0x2 CMP dword ptr [EAX + DAT_001a5408],0x64 JBE LAB_0007f78a MOV EAX,[DAT_001a59d8] SHL EAX,0x2 MOV dword ptr [EAX + DAT_001a5408],0x64 LAB_0007f78a MOV EAX,[DAT_001a59d8] INC EAX AND EAX,0x7 MOV [DAT_001a59d8],EAX MOV dword ptr [EBP + local_20],0x0 LAB_0007f79f CMP dword ptr [EBP + local_20],0x8 JL LAB_0007f7af JMP LAB_0007f7c3 LAB_0007f7a7 MOV EAX,dword ptr [EBP + local_20] INC dword ptr [EBP + local_20] JMP LAB_0007f79f LAB_0007f7af MOV EAX,dword ptr [EBP + local_20] SHL EAX,0x2 MOV EAX,dword ptr [EAX + DAT_001a5408] ADD dword ptr [DAT_00195ab0],EAX JMP LAB_0007f7a7 LAB_0007f7c3 SAR dword ptr [DAT_00195ab0],0x3 CMP dword ptr [DAT_00195ab0],0x1f4 JLE LAB_0007f7e0 MOV dword ptr [DAT_00195ab0],0x1f4 LAB_0007f7e0 LEA ESP=>local_18,[EBP + -0x14] POP EDI POP ESI POP EDX POP ECX POP EBX POP EBP RET FUN_000ce8b2 MOV AL,0xb0 OUT 0x43,AL IN AL,0x40 MOV AH,AL IN AL,0x40 XCHG AL,AH AND EAX,0xffff RET
1c46f1a2248d6c4445bb644a2d5df02e
{ "intermediate": 0.4013757109642029, "beginner": 0.3757094740867615, "expert": 0.22291480004787445 }
6,484
SempTao
543dd3957fd70ddd895ef947703a8e10
{ "intermediate": 0.32216107845306396, "beginner": 0.2650247812271118, "expert": 0.4128141403198242 }
6,485
val canvasState = rememberTransformableState { scaleChange, offsetChange, _ -> viewModel.onEvent( EmulatorEvent.CanvasScaleChange( scaleChange = scaleChange, offsetChange = offsetChange ) ) } how can i wrap it in remember saveable state?
16ec5d0ef3b0638d32621cfab68e05ef
{ "intermediate": 0.45502862334251404, "beginner": 0.23549415171146393, "expert": 0.3094772696495056 }
6,486
contract FindSlot { uint16 public tokenId; address public admin; uint128 public saleStart; bool public saleStarted; uint16 public totalSupply; address [2] public buyers; bytes32 private password; bool public isPaused; } which slot is password stored?Start counting from slot 0. Explain your calculation. slot0? slot1? slot2? slot3? slot4? slot5? slot6?
cc2dd9cde8334b218721ed5929ba8466
{ "intermediate": 0.3994331359863281, "beginner": 0.34247303009033203, "expert": 0.2580937445163727 }
6,487
I have a wpfapplication made in c# with a usercontrol that has a Datagrid.This datagrid contain a column named "Date" where I want to show some datetime in a format "MM/dd/yyyy".Please, how to do it using xaml?
d9d3053bb05f44c73cf849eab017b87a
{ "intermediate": 0.7668270468711853, "beginner": 0.13002042472362518, "expert": 0.10315258055925369 }
6,488
I have this store: import { configureStore } from '@reduxjs/toolkit'; import userReducer from './slices/userSlice'; export const store = configureStore({ reducer: { user: userReducer } }); export type RootState = ReturnType<typeof store.getState>; export type AppDispatch = typeof store.dispatch; this slice: import { User } from '@prisma/client'; import { createSlice } from '@reduxjs/toolkit'; interface UserState { value: User | null; } // Define the initial state using that type const initialState: UserState = { value: null }; export const userSlice = createSlice({ name: 'user', initialState, reducers: { setUser: (state, action) => { const user = { ...action.payload, defaultOffice: null }; return user; } } }); export const { setUser } = userSlice.actions; export const selectUser = (state: { user: UserState }) => state.user.value; export default userSlice.reducer; This function where I set the user: export const appHomeOpenedCallback: Middleware< SlackEventMiddlewareArgs<'app_home_opened'> > = async ({ client, event, logger }) => { if (event.tab !== 'home') { // Ignore the `app_home_opened` event for everything // except for home screen as we don't support a conversational UI return; } try { const slackId = event.user; const user = await getUserBySlackId(slackId); const userModified = { ...user, settings: { ...user?.settings, defaultOffice: null } }; const offices = await getOffices(); const defaultOffice = user?.settings?.officeId; const defaultOfficeName = user?.settings?.defaultOffice.name; const isAdmin = user?.isAdmin || false; const generateView = async () => { if (user && defaultOffice) { const bookings = await getBookingsByOfficeId( defaultOffice, today, twoFridaysFromToday ); store.dispatch(setUser(userModified)); const { officeChatMembers, officeChatExists } = await getOfficeChatAndMembers(client, defaultOffice); return home( bookings, today, twoFridaysFromToday, slackId, officeChatExists, officeChatMembers || [], isAdmin, defaultOfficeName, offices ); } else { return createUser(); } }; await client.views.publish({ user_id: slackId, view: await generateView() }); } catch (error) { logger.error(error); } }; But when trying to access the user here it returns null: export const joinDayCallback: Middleware< SlackActionMiddlewareArgs<BlockButtonAction> > = async ({ body, ack, client }) => { try { await ack(); const date = format(parseISO(body.actions[0].value), 'EEEE - dd MMM'); const userStored = selectUser(store.getState()); console.log(userStored); const user = await getUserBySlackId(body.user.id); const defaultOffice = user?.settings?.officeId; const { startDate, endDate, defaultOption } = JSON.parse( body.view?.private_metadata || '' ); if (!defaultOffice) throw new Error('No default office set'); const office = await getOffice(defaultOffice); const officeAreasWithBookings = await getOfficeAreasWithBookings( defaultOffice, parseISO(body.actions[0].value) ); const officeAreaOptions = getOfficeAreaOptions(officeAreasWithBookings); if (office && officeAreaOptions) { await client.views.open({ trigger_id: body.trigger_id, view: joinDayModal( date, body.user.id, officeAreaOptions, startDate, endDate, defaultOption ) }); } else { throw new Error('No office found'); } } catch (error) { console.error(error); } };
240e7233e63f175845059a79f21f7678
{ "intermediate": 0.4000319242477417, "beginner": 0.41181787848472595, "expert": 0.18815027177333832 }
6,489
Create a higher order function that accepts a function with three parameters • Create a method called mul3 which takes 3 floating point numbers and multiply them all • Call that higher order function on that mul3 method
82d96ad2625c8df92b81b5004e2da5fe
{ "intermediate": 0.21852412819862366, "beginner": 0.29293426871299744, "expert": 0.4885416328907013 }
6,491
write expert system using swi-prolog language for drinks recommendation. Drinks properties must be dynamic. System must have explanation system and have a rule to list all drinks.
a2b39d80f0e6cb82bc7901859e3067e4
{ "intermediate": 0.30945348739624023, "beginner": 0.17495034635066986, "expert": 0.5155962109565735 }
6,492
threshold cannot be resolved to a variable. Fix this. private void contrastImage() { if (image != null) { BufferedImage contrastStretchedImage = linearContrastStretch(image); setImageIcon(contrastStretchedImage); saveImage(contrastStretchedImage); // Получение порогового значения String thresholdString = JOptionPane.showInputDialog(this, "Введите пороговое значение: "); int threshold = Integer.parseInt(thresholdString); // Создаем гистограмму исходного изображения int[] histogram = new int[256]; for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { int pixel = image.getRGB(i, j); int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = pixel & 0xff; // Вычисляем яркость пикселя int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue); if (brightness > threshold){ // Преобразуем яркость пикселя до максимального значения, если она больше порога brightness = 255; } histogram[brightness]++; } } // Создаем гистограмму преобразованного изображения int[] contrastStretchedHistogram = new int[256]; for (int i = 0; i < contrastStretchedImage.getWidth(); i++) { for (int j = 0; j < contrastStretchedImage.getHeight(); j++) { int pixel = contrastStretchedImage.getRGB(i, j); int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = pixel & 0xff; // Вычисляем яркость пикселя int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue); if (brightness < threshold) { // Преобразуем яркость пикселя в 0, если она не входит в порог brightness = 0; } else { // Растягиваем яркость пикселя до максимального значения brightness = (int) (255.0 * (brightness - threshold) / (255 - threshold)); } contrastStretchedHistogram[brightness]++; } } // Создаем окно для отображения гистограмм JFrame histogramFrame = new JFrame(“Гистограммы”); histogramFrame.setLayout(new GridLayout(2, 2, 10, 10)); // Создаем панель для гистограммы исходного изображения JPanel histogramPanel1 = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int max = Arrays.stream(histogram).max().getAsInt(); for (int i = 0; i < 256; i++) { int height = (int) (300.0 * histogram[i] / max); g.fillRect(i, 300 - height, 1, height); } } }; histogramPanel1.setPreferredSize(new Dimension(256, 300)); // Создаем панель для гистограммы преобразованного изображения JPanel histogramPanel2 = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int max = Arrays.stream(contrastStretchedHistogram).max().getAsInt(); for (int i = 0; i < 256; i++) { int height = (int) (300.0 * contrastStretchedHistogram[i] / max); g.fillRect(i, 300 - height, 1, height); } } }; histogramPanel2.setPreferredSize(new Dimension(256, 300)); histogramFrame.add(new JLabel(“Гистограмма исходного изображения”)); histogramFrame.add(new JLabel(“Гистограмма преобразованного изображения”)); histogramFrame.add(histogramPanel1); histogramFrame.add(histogramPanel2); histogramFrame.pack(); histogramFrame.setLocationRelativeTo(null); histogramFrame.setVisible(true); } } } private BufferedImage linearContrastStretch(BufferedImage image) { // Проходим по всем пикселям изображения и находим минимальное и максимальное значение яркости int minBrightness = 255; int maxBrightness = 0; for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { int pixel = image.getRGB(i, j); int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = pixel & 0xff; // Вычисляем яркость пикселя int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue); if (brightness < threshold){ // Ограничиваем диапазон значений яркости от 0 до 255 brightness = Math.max(0, Math.min(255, brightness + 255 - threshold)); } if (brightness < minBrightness) { minBrightness = brightness; } if (brightness > maxBrightness) { maxBrightness = brightness; } } } // Вычисляем коэффициенты a и b для линейного растяжения контраста double a = 255.0 / (maxBrightness - minBrightness); double b = -minBrightness * a; BufferedImage contrastStretchedImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType()); // Проходим по всем пикселям изображения и применяем линейное растяжение контраста for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { int pixel = image.getRGB(i, j); int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = pixel & 0xff; // Вычисляем яркость пикселя int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue); // Вычисляем новое значение яркости с помощью линейного растяжения контраста int newBrightness = (int) (a * brightness + b); // Ограничиваем диапазон значений яркости от 0 до 255 newBrightness = Math.max(0, Math.min(255, newBrightness)); // Создаем новый пиксель с измененным значением яркости int newPixel = (255 << 24) | (newBrightness << 16) | (newBrightness << 8) | newBrightness; contrastStretchedImage.setRGB(i, j, newPixel); } } // Возвращаем изображение с примененным линейным растяжением контраста return contrastStretchedImage; }
6af9e0f8f1dd35398346ea9525efbbb2
{ "intermediate": 0.28901445865631104, "beginner": 0.5019246339797974, "expert": 0.20906086266040802 }
6,493
write a code to simulate molecular communication
1287cd3c07bc28cfa0ba9c5b9bce6efb
{ "intermediate": 0.15662331879138947, "beginner": 0.1030859425663948, "expert": 0.7402907013893127 }
6,494
List<int> pickRandomInts(List<int> arr, int n, int seed) { int current = seed; Set<int> randomIndexes = Set(); while (randomIndexes.length < n) { current = ((current * 0x41C64E6D) ^ current) >> 30; // use snippet to update current int index = current % arr.length; randomIndexes.add(index); } List<int> randomInts = []; for (int index in randomIndexes) { randomInts.add(arr[index]); } randomInts.sort(); return randomInts; } change the function such that increasing n (length of output) will always contain smaller lengths as a subset
028d2b09291b447743ed93e67c62de75
{ "intermediate": 0.3302117586135864, "beginner": 0.34816065430641174, "expert": 0.3216276168823242 }
6,495
use creator engine write wave shader
76b408f45b26c8afa5039016f1befcdb
{ "intermediate": 0.3412895202636719, "beginner": 0.20708276331424713, "expert": 0.4516277313232422 }
6,496
I will provide you disassembly from a computer game that runs in MS-DOS. The game was written in C with a Watcom compiler. Some library function calls are already identified. Explain the functions I give to you and suggest names and C-language function signatures for them, including which parameters map to which registers or stack values. Also suggest names for global values if you have enough context to do so. Regarding the value DAT_0000046c (the memory at address 0x46c), according to information I found this value is in the BIOS data area and stores the number of "ticks" since midnight (resetting to 0 again at the next midnight). Ticks happen at a rate of 18.2 times per second. FUN_0007e066 PUSH EBP MOV EBP,ESP PUSH EBX PUSH ECX PUSH EDX PUSH ESI PUSH EDI SUB ESP,0x0 CALL FUN_0007f671 MOV EAX,[DAT_00195b00] MOV [DAT_001a59d0],EAX MOV EAX,[DAT_00195b00] MOV [DAT_001a59c8],EAX LEA ESP=>local_18,[EBP + -0x14] POP EDI POP ESI POP EDX POP ECX POP EBX POP EBP RET FUN_0007f671 PUSH EBP MOV EBP,ESP PUSH EBX PUSH ECX PUSH EDX PUSH ESI PUSH EDI SUB ESP,0x4 CALL FUN_000ce8b2 MOV [DAT_001a59cc],EAX MOV dword ptr [EBP + local_1c],DAT_0000046c MOV EAX,dword ptr [EBP + local_1c] MOV EAX=>DAT_0000046c,dword ptr [EAX] MOV [DAT_001a59dc],EAX LEA ESP=>local_18,[EBP + -0x14] POP EDI POP ESI POP EDX POP ECX POP EBX POP EBP RET FUN_0007f6a4 PUSH EBP MOV EBP,ESP PUSH EBX PUSH ECX PUSH EDX PUSH ESI PUSH EDI SUB ESP,0xc MOV EAX,[DAT_001a59cc] MOV [DAT_001a59e0],EAX MOV EAX,[DAT_001a59dc] MOV [DAT_001a59e4],EAX CALL FUN_000ce8b2 MOV [DAT_001a59cc],EAX MOV dword ptr [EBP + local_1c],DAT_0000046c MOV EAX,dword ptr [EBP + local_1c] MOV EAX=>DAT_0000046c,dword ptr [EAX] MOV [DAT_001a59dc],EAX MOV EAX,[DAT_001a59dc] CMP EAX,dword ptr [DAT_001a59e4] JNZ LAB_0007f6fe MOV EAX,[DAT_001a59e0] SUB EAX,dword ptr [DAT_001a59cc] MOV dword ptr [EBP + local_24],EAX JMP LAB_0007f726 LAB_0007f6fe MOV EAX,[DAT_001a59dc] SUB EAX,dword ptr [DAT_001a59e4] DEC EAX IMUL EDX,EAX,0xffff MOV EAX,0xffff SUB EAX,dword ptr [DAT_001a59cc] ADD EAX,dword ptr [DAT_001a59e0] ADD EAX,EDX MOV dword ptr [EBP + local_24],EAX LAB_0007f726 CMP dword ptr [EBP + local_24],0x2710 JNC LAB_0007f745 MOV EAX,0xffff SUB EAX,dword ptr [DAT_001a59cc] MOV EDX,dword ptr [DAT_001a59e0] ADD EDX,EAX MOV dword ptr [EBP + local_24],EDX LAB_0007f745 IMUL EAX,dword ptr [EBP + local_24],0x3e8 MOV EBX,DAT_001234dc XOR EDX,EDX DIV EBX SHR EAX,0x1 MOV EBX,EAX MOV EAX,[DAT_001a59d8] SHL EAX,0x2 MOV dword ptr [EAX + DAT_001a5408],EBX MOV EAX,[DAT_001a59d8] SHL EAX,0x2 CMP dword ptr [EAX + DAT_001a5408],0x64 JBE LAB_0007f78a MOV EAX,[DAT_001a59d8] SHL EAX,0x2 MOV dword ptr [EAX + DAT_001a5408],0x64 LAB_0007f78a MOV EAX,[DAT_001a59d8] INC EAX AND EAX,0x7 MOV [DAT_001a59d8],EAX MOV dword ptr [EBP + local_20],0x0 LAB_0007f79f CMP dword ptr [EBP + local_20],0x8 JL LAB_0007f7af JMP LAB_0007f7c3 LAB_0007f7a7 MOV EAX,dword ptr [EBP + local_20] INC dword ptr [EBP + local_20] JMP LAB_0007f79f LAB_0007f7af MOV EAX,dword ptr [EBP + local_20] SHL EAX,0x2 MOV EAX,dword ptr [EAX + DAT_001a5408] ADD dword ptr [DAT_00195ab0],EAX JMP LAB_0007f7a7 LAB_0007f7c3 SAR dword ptr [DAT_00195ab0],0x3 CMP dword ptr [DAT_00195ab0],0x1f4 JLE LAB_0007f7e0 MOV dword ptr [DAT_00195ab0],0x1f4 LAB_0007f7e0 LEA ESP=>local_18,[EBP + -0x14] POP EDI POP ESI POP EDX POP ECX POP EBX POP EBP RET FUN_000ce8b2 MOV AL,0xb0 OUT 0x43,AL IN AL,0x40 MOV AH,AL IN AL,0x40 XCHG AL,AH AND EAX,0xffff RET
4b3fa993e1460511a146efd2f2a4f3f0
{ "intermediate": 0.4612676799297333, "beginner": 0.3615630865097046, "expert": 0.17716918885707855 }
6,497
List<int> pickRandomInts(List<int> arr, int n, int seed) { int current = seed; List<int> allIndexes = List.generate(arr.length, (index) => index); _fisherYatesShuffle(allIndexes, current); List<int> biggerIndexes = allIndexes.sublist(0, n); current = seed; Set<int> smallerIndexes = Set(); int maxAttempts = 1000; int attempts = 0; while (smallerIndexes.length < min(n - 1, arr.length) && attempts < maxAttempts) { current = _parkMillerRNG(current); int index = current % arr.length; if (biggerIndexes.contains(index)) { continue; } smallerIndexes.add(index); attempts++; } List<int> randomInts = []; for (int index in biggerIndexes) { randomInts.add(arr[index]); } for (int index in smallerIndexes) { randomInts.add(arr[index]); } _fisherYatesShuffle(randomInts, current); return randomInts; } int _parkMillerRNG(int seed) { return (seed * 16807) % 2147483647; } void _fisherYatesShuffle(List<int> list, int seed) { for (int i = list.length - 1; i > 0; i–) { int j = _parkMillerRNG(seed) % (i + 1); int temp = list[i]; list[i] = list[j]; list[j] = temp; } } modify first function such that in list of length n there are always all elements of lists smaller length
7ee72773363080499cb622af2b516ddf
{ "intermediate": 0.37489837408065796, "beginner": 0.26072657108306885, "expert": 0.3643750846385956 }
6,498
Write a tutorial on how to make a prop_physics wheel constrained to a phys_motor rotate in sync with a phys_pulleyconstraintsystem constrained to two other prop_physics in the Valve Hammer Editor for the Source Engine.
6723df14d115cb8d95bb14c50dfc0f6d
{ "intermediate": 0.3505725860595703, "beginner": 0.17184804379940033, "expert": 0.47757941484451294 }
6,499
Write an efficient c++ for loop that checks for all the possible moves of a piece one distance away its given pair of coordinates. The coordinates are class members of the piece.
9152e73568d38232632f3c491ff9278a
{ "intermediate": 0.23664525151252747, "beginner": 0.35312342643737793, "expert": 0.41023123264312744 }
6,500
write code to dinamically disable rows in an antd table, if I select a row with the record.bank == "agricola" then diseable the selection for the rows with a different bank for example in react, the bank name can change in react
d24e96d068ada08592f79e2fe93ea273
{ "intermediate": 0.4063624441623688, "beginner": 0.07499034702777863, "expert": 0.5186472535133362 }
6,501
given this c program: #include <stdio.h> #include <sys/mman.h> #include <string.h> #include <stdlib.h> #define BUFSIZE 30 char grade = '3'; char Name[BUFSIZE]; void readString(char *s) { char buf[BUFSIZE]; int i = 0; int c; while (1) { c = fgetc(stdin); if ((c == EOF) || (c == '\n')) break; buf[i++] = c; } buf[i] = 0; for (i = 0; i < BUFSIZE; i++) s[i] = buf[i]; return; } int main(void) { mprotect((void*)((unsigned int)Name & 0xfffff000), 1, PROT_READ | PROT_WRITE | PROT_EXEC); printf("What is your name?\n"); readString(Name); if (strcmp(Name, "Angelos Bilas") == 0) grade = '6'; printf("Thank you, %s.\n", Name); printf("I recommend that you get a grade of %c on this assignment.\n", grade); exit(0); } Write a C program called createdata9.c that produces a data9 file, as simple as possible, that causes the hello program to print your name and suggest a grade of "9". The way you can force the program into this behavior is to overrun the buffer (buf) with a sequence of three things: (1) your name, (2) a return address pointing into the buffer, and (3) a very short assembly program that stores 9 in the correct location in memory and then jumps to the correct location.
db67fc9895a030b628ac758421d3d0ab
{ "intermediate": 0.4146184027194977, "beginner": 0.357759028673172, "expert": 0.22762258350849152 }
6,502
an example code of scaling the total counts of parameters of a t5 model
64b9a8c13d0591eab9ed6f2be6a8125d
{ "intermediate": 0.24642755091190338, "beginner": 0.1764480471611023, "expert": 0.5771244168281555 }
6,503
dart fold vs reduce
8a64ff407da13a518d08fb83188363e3
{ "intermediate": 0.23902733623981476, "beginner": 0.1449214220046997, "expert": 0.6160512566566467 }
6,504
in sql server, is there a way to get the entire chain of foreign keyed tables starting from a specific table?
6da2a906dc9a268f510b43bfdb02284c
{ "intermediate": 0.4752955436706543, "beginner": 0.26501375436782837, "expert": 0.25969070196151733 }
6,505
I want to use the incomplete vba below to modify the part with it that states; lastRow = wscf.Cells(Rows.Count, "J").End(xlUp).Row Set copyRange = wscf.Range("J5:J" & lastRow) . What I want is to copy the range from J5:J where the preceding value in column I of the same row is blank. Dim wscf As Worksheet Dim wsjr As Worksheet Dim lastRow As Long Dim copyRange As Range Application.ScreenUpdating = True Application.EnableEvents = True ActiveSheet.Range("F30:F34").ClearContents Application.Wait (Now + TimeValue("0:00:01")) ActiveSheet.Range("G3").Formula = ActiveSheet.Range("G3").Formula Application.Wait (Now + TimeValue("0:00:01")) ActiveSheet.Range("H3").Formula = ActiveSheet.Range("H3").Formula If ActiveSheet.Range("G3") = "" Or 0 Then Application.ScreenUpdating = True Application.EnableEvents = True Exit Sub End If Set wscf = Sheets(Range("G3").Value) Set wsjr = Sheets("Start Page") lastRow = wscf.Cells(Rows.Count, "J").End(xlUp).Row Set copyRange = wscf.Range("J5:J" & lastRow) End If wsjr.Range("F30").Resize(copyRange.Rows.Count, 1).Value = copyRange.Value Application.ScreenUpdating = True Application.EnableEvents = True End Sub
d4bbaea1f1a3fa871cc4f47542dbd9b9
{ "intermediate": 0.4594227969646454, "beginner": 0.3610384166240692, "expert": 0.1795387715101242 }
6,506
Fixpoint sum_n_quartic (n : nat) : nat := match n with O => 0 | S p => n*n*n*n + sum_n_quartic p end. Lemma prob4 : forall n : nat, sum_n_quartic n * 30 + n * (n + 1) * (2 * n + 1) = n * (n + 1) * (2 * n + 1) * (3 * n * n + 3 * n). Proof. Abort.
5a104cf189bc783bcdad890fd291fbbe
{ "intermediate": 0.420960009098053, "beginner": 0.37270587682724, "expert": 0.2063341587781906 }
6,507
Write a code for a four in line online game
e0e4940b89ee0163a55803c07aab45da
{ "intermediate": 0.22991767525672913, "beginner": 0.3496610224246979, "expert": 0.4204212725162506 }
6,508
I have a Kotlin app with a SQLite database and i have a function which returns all data from a table. I have a mutable list of these objects, and i want to read a query so that from every record, i construct an object and append it to the list. how would i go about doing that?
30900889c05a44e22f2e0576c1f3f438
{ "intermediate": 0.7521212697029114, "beginner": 0.16636063158512115, "expert": 0.08151809126138687 }
6,509
import telebot # Токен бота TOKEN = '6051752717:AAEU7VginJfplonKAFRGxPqtkaJDcVh98Bo' # Список правил RULES = [ '1. Не пить', '2. Не курить', '3. Не ругаться' ] # Создаем объект бота bot = telebot.TeleBot(TOKEN) # Обработчик команды /start @bot.message_handler(commands=['start']) def start_handler(message): # Отправляем пользователю правила bot.send_message(message.chat.id, 'Привет! Чтобы присоединиться к чату, тебе нужно согласиться с правилами:\n\n' + '\n'.join(RULES)) # Обработчик новых пользователей @bot.message_handler(content_types=['new_chat_members']) def new_member_handler(message): # Проверяем, согласен ли пользователь с правилами keyboard = telebot.types.InlineKeyboardMarkup() agree_button = telebot.types.InlineKeyboardButton(text='Согласен', callback_data='agree') disagree_button = telebot.types.InlineKeyboardButton(text='Не согласен', callback_data='disagree') keyboard.add(agree_button, disagree_button) bot.send_message(message.chat.id, f'Привет, {message.new_chat_members[0].first_name}! Чтобы присоединиться к чату, тебе нужно согласиться с правилами:\n\n' + '\n'.join(RULES), reply_markup=keyboard) # Обработчик нажатий на кнопки @bot.callback_query_handler(func=lambda call: True) def callback_handler(call): if call.data == 'agree': # Удаляем сообщение бота bot.delete_message(call.message.chat.id, call.message.message_id) elif call.data == 'disagree': # Удаляем пользователя из чата bot.kick_chat_member(call.message.chat.id, call.from_user.id) # Удаляем сообщение бота bot.delete_message(call.message.chat.id, call.message.message_id) # Запускаем бота bot.polling(none_stop=True) Добавить в код, чтобы только новые польщователи могли нажать на кнопнку согласен или не согласен
d6aece1211fa3a86ba3c9dfa56d574c0
{ "intermediate": 0.2391107827425003, "beginner": 0.6262074708938599, "expert": 0.13468168675899506 }
6,510
I will provide you disassembly from a computer game that runs in MS-DOS. The game was written in C with a Watcom compiler. Some library function calls are already identified. Explain the functions I give to you and suggest names and C-language function signatures for them, including which parameters map to which registers or stack values. Also suggest names for global values if you have enough context to do so. FUN_00160900 PUSH ESI DEC EAX CMP byte ptr [EAX + DAT_00160000],offset DAT_0015ffff JZ LAB_00160963 MOV byte ptr [EAX + DAT_00160000],offset DAT_0015ffff PUSH EAX PUSH EBX PUSH ECX PUSH EDX MOV EBX,EAX MOV EAX,dword ptr [EAX*0x4 + DAT_00160014] PUSH EAX CALL _dos_getvect MOV word ptr [EBX*0x2 + DAT_00160038],DX MOV dword ptr [EBX*0x4 + DAT_00160028],EAX POP EAX MOV EBX,dword ptr [EBX*0x4 + PTR_FUN_00160040] PUSH EBX MOV CX,CS CALL set_interrupt_handler POP EAX MOV EDX,0x400 CALL lock_memory_region MOV EAX,DAT_00160000 MOV EDX,0x880 CALL lock_memory_region POP EDX POP ECX POP EBX POP EAX LAB_00160963 INC EAX CALL FUN_00160a18 CLI LEA ESI,[EAX*0x4 + 0xfffffffc] MOV EAX,EDX MOV EDX,dword ptr [ESI + 0x160004] ADD EDX,0x3 OR AL,0x80 OUT DX,AL PUSH EAX PUSH EDX MOV EDX,dword ptr [ESI + 0x160004] MOV EAX,EBX OUT DX,AX POP EDX POP EAX AND AL,0x7f OUT DX,AL MOV EDX,dword ptr [ESI + 0x160004] ADD EDX,0x4 MOV AL,0x8 OUT DX,AL MOV EDX,dword ptr [ESI + 0x160004] ADD EDX,0x1 MOV AL,0x1 OUT DX,AL SUB EDX,0x1 IN AL,DX SHR ESI,0x2 IN AL,0x21 AND AL,byte ptr [ESI + DAT_00160024] OUT 0x21,AL STI MOV AL,0x20 OUT 0x20,AL POP ESI RET Data at DAT_00160014: 0c 00 00 00 0b 00 00 00 0c 00 00 00 0b 00 00 00 Data at PTR_FUN_00160040 is the addresses for four functions: FUN_00160ae0 FUN_00160b60 FUN_00160be0 FUN_00160c60 Data at DAT_00160024 is: ef f7 ef f7 FUN_00160ae0 PUSH EAX PUSH EDX PUSH DS MOV AX,0x0 MOV DS,AX MOV EDX,0x3f8 ADD EDX,0x2 IN AL,DX TEST AL,0x1 JNZ LAB_00160b3a TEST AL,0x6 JZ LAB_00160b30 TEST AL,0x4 JZ LAB_00160b3a MOV EDX,0x3f8 ADD EDX,0x5 IN AL,DX SUB EDX,0x5 IN AL,DX MOV EDX,DAT_00160050 ADD EDX,dword ptr [DAT_00160860] INC dword ptr [DAT_00160860] MOV byte ptr [EDX],AL AND dword ptr [DAT_00160860],0x1ff INC dword ptr [DAT_00160870] JMP LAB_00160b3a LAB_00160b30 MOV EDX,0x3f8 IN AL,DX ADD EDX,0x5 IN AL,DX LAB_00160b3a MOV AL,0x20 OUT 0x20,AL POP DS POP EDX POP EAX IRET FUN_00160b60 PUSH EAX PUSH EDX PUSH DS MOV AX,0x0 MOV DS,AX MOV EDX,0x2f8 ADD EDX,0x2 IN AL,DX TEST AL,0x1 JNZ LAB_00160bba TEST AL,0x6 JZ LAB_00160bb0 TEST AL,0x4 JZ LAB_00160bba MOV EDX,0x2f8 ADD EDX,0x5 IN AL,DX SUB EDX,0x5 IN AL,DX MOV EDX,DAT_00160250 ADD EDX,dword ptr [DAT_00160864] MOV byte ptr [EDX],AL INC dword ptr [DAT_00160864] AND dword ptr [DAT_00160864],0x1ff INC dword ptr [DAT_00160874] JMP LAB_00160bba LAB_00160bb0 MOV EDX,0x2f8 IN AL,DX ADD EDX,0x5 IN AL,DX LAB_00160bba MOV AL,0x20 OUT 0x20,AL POP DS POP EDX POP EAX IRET FUN_00160be0 PUSH EAX PUSH EDX PUSH DS MOV AX,0x0 MOV DS,AX MOV EDX,0x3e8 ADD EDX,0x2 IN AL,DX TEST AL,0x1 JNZ LAB_00160c3a TEST AL,0x6 JZ LAB_00160c30 TEST AL,0x4 JZ LAB_00160c3a MOV EDX,0x3e8 ADD EDX,0x5 IN AL,DX SUB EDX,0x5 IN AL,DX MOV EDX,DAT_00160450 ADD EDX,dword ptr [DAT_00160868] MOV byte ptr [EDX],AL INC dword ptr [DAT_00160868] AND dword ptr [DAT_00160868],0x1ff INC dword ptr [DAT_00160878] JMP LAB_00160c3a LAB_00160c30 MOV EDX,0x3e8 IN AL,DX ADD EDX,0x5 IN AL,DX LAB_00160c3a MOV AL,0x20 OUT 0x20,AL POP DS POP EDX POP EAX IRET FUN_00160c60 PUSH EAX PUSH EDX PUSH DS MOV AX,0x0 MOV DS,AX MOV EDX,0x2e8 ADD EDX,0x2 IN AL,DX TEST AL,0x1 JNZ LAB_00160cba TEST AL,0x6 JZ LAB_00160cb0 TEST AL,0x4 JZ LAB_00160cba MOV EDX,0x2e8 ADD EDX,0x5 IN AL,DX SUB EDX,0x5 IN AL,DX MOV EDX,DAT_00160650 ADD EDX,dword ptr [DAT_0016086c] MOV byte ptr [EDX],AL INC dword ptr [DAT_0016086c] AND dword ptr [DAT_0016086c],0x1ff INC dword ptr [DAT_0016087c] JMP LAB_00160cba LAB_00160cb0 MOV EDX,0x2e8 IN AL,DX ADD EDX,0x5 IN AL,DX LAB_00160cba MOV AL,0x20 OUT 0x20,AL POP DS POP EDX POP EAX IRET FUN_00161000 PUSHAD MOV [DAT_00153400],EAX MOV EDX,0x3 MOV EBX,0x6 CALL FUN_00160900 CALL FUN_00161094 JC LAB_00161072 MOV ECX,0x10 LAB_00161021 MOV EAX,DAT_00160f08 CALL FUN_00161224 CALL FUN_00161250 JNC LAB_00161036 LOOP LAB_00161021 JMP LAB_00161072 LAB_00161036 MOV dword ptr [DAT_00160f18],0x1 CALL FUN_001610d4 JC LAB_00161072 CALL FUN_00161114 CMP EAX,0x3eb JC LAB_00161059 NEG dword ptr [DAT_00160f18] LAB_00161059 CALL FUN_001610b4 MOV EAX,[DAT_00153400] CALL FUN_00160a18 CALL FUN_001610c4 POPAD XOR EAX,EAX CLC RET LAB_00161072 MOV EAX,[DAT_00153400] CALL FUN_001609c0 POPAD MOV EAX,0x1 STC RET Data at DAT_00160f08: 21 4d 32 2c 43 2c 42 0d ff
5ea81f8fae4f6a3235e34c46eeed7d74
{ "intermediate": 0.39639192819595337, "beginner": 0.42787814140319824, "expert": 0.1757298856973648 }
6,511
Write a detailed explanation of the BASIC code provided below: 10 PRINT TAB(30);"SINE WAVE" 20 PRINT TAB(15);"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" 30 PRINT: PRINT: PRINT: PRINT: PRINT 40 REMARKABLE PROGRAM BY DAVID AHL 50 B=0 100 REM START LONG LOOP 110 FOR T=0 TO 40 STEP .25 120 A=INT(26+25*SIN(T)) 130 PRINT TAB(A); 140 IF B=1 THEN 180 150 PRINT "CREATIVE" 160 B=1 170 GOTO 200 180 PRINT "COMPUTING" 190 B=0 200 NEXT T 999 END
010500a1fad315360214b5a9c74b45ef
{ "intermediate": 0.08165398985147476, "beginner": 0.8029370307922363, "expert": 0.1154090166091919 }
6,512
Hello. I have a python script that is taking data from the GTSRB dataset from https://www.kaggle.com/datasets/meowmeowmeowmeowmeow/gtsrb-german-traffic-sign . I have this script attached that gets stuck at the end, after displaying the accuracy so it is not saving the .h5 model. I need some help with that.
a57f2fd0c9ace439efd2cdde3209acd3
{ "intermediate": 0.5334120392799377, "beginner": 0.20106758177280426, "expert": 0.2655204236507416 }
6,513
uniapp
83a2f7e3965939485fab62fb8f7b300e
{ "intermediate": 0.33131301403045654, "beginner": 0.29913631081581116, "expert": 0.3695507049560547 }
6,514
make appropriate corrections of the code to make it work def gamma_correct(pixel, gamma): gamma_correction_factor = 1.0 / gamma if pixel < 0: return 0 elif pixel >= 0 and pixel < 0.04045: return 0.0773993808049536 * pixel else: return (0.9478672985781991 * pixel + 0.0521327014218009) ** gamma_correction_factor def gamma_correction(image, gamma): corrected_image = Image.new("RGB", (image.shape[1], image.shape[0])) for x in range(image.shape[0]): for y in range(image.shape[1]): r, g, b = Image.getpixel((x, y)) r /= 255.0 g /= 255.0 b /= 255.0 r = gamma_correct(r, gamma) g = gamma_correct(g, gamma) b = gamma_correct(b, gamma) r = int(r * 255) g = int(g * 255) b = int(b * 255) corrected_image.putpixel((x, y), (r, g, b)) return corrected_image cc_image_rgb = cv2.cvtColor(cc_image, cv2.COLOR_BGR2RGB) gamma_corrected_image = gamma_correction(cc_image_rgb, 2.4) imshow("Gamma Corrected image", gamma_corrected_image)
a8477c75316e0927f2eca07a3fbb3750
{ "intermediate": 0.3763231635093689, "beginner": 0.20038358867168427, "expert": 0.4232932925224304 }
6,515
can you provide me with anexmple of an advnced Python code that can perform arbitrage between Uniswap V2, V3, SushiSwap, Curve running on the polygon network using Aave’s v3 flash loans and sample pyhton script taht uses strtegys like tringlulr abritradge that uses real librarays
ee3aceace2d96907f7fb0cc019e4ad5a
{ "intermediate": 0.5294190049171448, "beginner": 0.08320683985948563, "expert": 0.3873741328716278 }
6,516
I have a table, represented by a table view in kotlin. i want to input data from a list into the table, so that every single value is represented by a separate row in the table. how can i do that?
c7fdb2c6373b84ffa41e650b4cfde174
{ "intermediate": 0.5568503737449646, "beginner": 0.1669996678829193, "expert": 0.2761499583721161 }
6,517
Hi, I've implemented a Evader Node and a DQN model . I want you to go through the code and find all the mistakes I made . I'll mention some of the mistakes I made: Given the destination point, the car which starts at an intial point should make it's way by selecting the appropriate actions to make it all the way to final point. But instead it's going in the other direction . I don't really understand how my agent is performing. So, first remove the run function and update the scan_callback function to include max no of episodes and max steps for each episode. If the car takes too long to reach destination or even max steps reached , put a condition in place to reset the car to its intial position by sending a command to gazebo . Second, In add_experience step, what values do I need to pass since state and next_state are two different things , I'm passing state (109 laser scan points to both of those). So, I don't think it's a right step to do. Correct me If I'm wrong. The agent has to learn something from the data. For observation space , I changed 360 to 109 since I'm getting 109 scan point for every call . Correct this If I did wrong. and move Make all the necessary changes to the code. The training should pretty much look like this : def q_train(agent, env, episodes,epsilon_decay = 0.99): rewards = [] epsilons = [] for i in range(episodes): state = en.resevt() # we have to reset this by communicating with gazebo episode_reward = 0 done = False while not done: action = agent.get_action(state) next_state, reward, done, _ = env.step(action) agent.update(state, action, reward, next_state) episode_reward += reward state = next_state agent.epsilon *= epsilon_decay epsilons.append(agent.epsilon) rewards.append(episode_reward) . My actual implementation is as follows: import numpy as np import random import math import rospy import tf import copy import time from sensor_msgs.msg import LaserScan from ackermann_msgs.msg import AckermannDrive from nav_msgs.msg import Odometry from DQN import DQNAgentPytorch FORWARD = 0 LEFT = 1 RIGHT = 2 REVERSE = 3 ACTION_SPACE = [FORWARD, LEFT, RIGHT, REVERSE] class EvaderNode: def __init__(self, agent): rospy.init_node('evader_node', anonymous=True) rospy.Subscriber('car_1/scan', LaserScan, self.scan_callback) rospy.Subscriber('car_1/base/odom', Odometry, self.odom_callback) self.drive_pub = rospy.Publisher('car_1/command', AckermannDrive, queue_size=10) self.init_location = None self.current_location = None self.max_distance = 30 self.obstacle_penalty = -250 self.destination_reward = 500 self.distance_threshold = 0.5 self.collision_threshold = 0.2 self.agent = agent self.action = 0 self.is_training = True self.init_odom_received = False self.latest_odom_msg = None self.reached_destination = False self.final_destination = (10, 10) self.reward = 0 self.max_episodes = 10 self.max_steps_per_episode = 100 def process_scan(self, scan): state = np.array(scan.ranges)[::10] return state def check_collision(self, scan): for i in range(len(scan.ranges)): if scan.ranges[i] < self.collision_threshold: return True return False def action_to_drive_msg(self, action): drive_msg = AckermannDrive() if action == FORWARD: drive_msg.speed = 2.0 drive_msg.steering_angle = 0.0 elif action == LEFT: drive_msg.speed = 2.0 drive_msg.steering_angle = float(random.uniform(math.pi / 4, math.pi / 2)) elif action == RIGHT: drive_msg.speed = 2.0 drive_msg.steering_angle = float(random.uniform(-math.pi / 2, -math.pi / 4)) return drive_msg def reverse_car(self, reverse_distance): reverse_drive_msg = AckermannDrive() reverse_drive_msg.speed = -2.0 reverse_drive_msg.steering_angle = 0.0 reverse_duration = reverse_distance / (-reverse_drive_msg.speed) start_time = time.time() while time.time() - start_time < reverse_duration: self.drive_pub.publish(reverse_drive_msg) rospy.sleep(0.1) reverse_drive_msg.speed = 0.0 self.drive_pub.publish(reverse_drive_msg) # rospy.sleep(1) def calculate_reward(self, collision_detected, done): reward = 0 if done: reward += self.destination_reward if collision_detected: reward += self.obstacle_penalty current_dist_diff = np.linalg.norm(np.array(self.final_destination) - np.array(self.current_location)[:2]) init_dist_diff = np.linalg.norm(np.array(self.final_destination) - np.array(self.init_location)) if current_dist_diff < init_dist_diff: reward += 100 else: reward -= 100 return reward def update_reward(self, collision_detected, done): self.reward += self.calculate_reward(collision_detected, done) def scan_callback(self, scan): state = self.process_scan(scan) action = self.agent.choose_action(state, test=not self.is_training) collision_detected = self.check_collision(scan) if collision_detected and not self.reached_destination: print('Collision Detected') self.reverse_car(0.2) # Set the reverse distance here action = self.agent.choose_action(state, test=not self.is_training) drive_msg = self.action_to_drive_msg(action) done = False if self.is_training: print(self.current_location) if np.linalg.norm(np.array(self.final_destination) - np.array(self.current_location)[:2]) < self.distance_threshold: done = True self.reached_destination = True print("Reward Before",self.reward) self.update_reward(collision_detected, done) # print(state, len(state)) print("Reward After",self.reward) self.agent.add_experience(state, action, self.reward, state, done) self.agent.train(32) if done: self.reached_destination = True rospy.sleep(1) else: self.agent.load_weights('model_weights.pth') action = self.agent.choose_action(state, test=True) self.drive_pub.publish(drive_msg) def update_current_location(self, odom_msg): position = odom_msg.pose.pose.position orientation = odom_msg.pose.pose.orientation euler_angles = tf.transformations.euler_from_quaternion( (orientation.x, orientation.y, orientation.z, orientation.w)) self.current_location = ( position.x, position.y, euler_angles[2]) # (x, y, yaw) print("Current Location of the Car:", self.current_location[:2]) def odom_callback(self, odom_msg): if not self.init_odom_received: self.init_location = (odom_msg.pose.pose.position.x, odom_msg.pose.pose.position.y) print(f"Intial Location of the Car: {self.init_location}") self.init_odom_received = True self.update_current_location(odom_msg) self.latest_odom_msg = odom_msg def run(self): self.current_episode = 0 episode_step = 0 while not rospy.is_shutdown() and self.current_episode < self.max_episodes: rospy.spin() if self.reached_destination: self.current_episode += 1 self.reward = 0 self.reached_destination = False if self.current_episode % 10 == 0: print(f"Completed Episode {self.current_episode}") rospy.sleep(1) if __name__ == '__main__': try: action_space = ACTION_SPACE observation_space = np.zeros((109,)) # Based on the number of data points in the lidar scan agent = DQNAgentPytorch(action_space, observation_space) node = EvaderNode(agent) while not node.init_odom_received: rospy.sleep(0.1) node.run() except rospy.ROSInterruptException: pass plot_rewards(rewards)
559308805b7a3ffe2bd05d3fb4ca3a3a
{ "intermediate": 0.3455352187156677, "beginner": 0.42644432187080383, "expert": 0.22802045941352844 }
6,518
addon.js // ==UserScript== // @name cytrus = kot // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author You // @match https://*.margonem.pl // @grant none // ==/UserScript== class Game { constructor(){ this.ws = new WebSocket('ws://localhost:8080'); g.delays.limit = 150; this.mobs = () => { return Object.values(g.npc).filter(npc => (npc.type == 2 || npc.type == 3) && !npc.hasOwnProperty('walkover')); } this.storage = JSON.parse(localStorage.getItem('mamon666')) || { position: { x: 0, y: 0 }, ExpButton: false, TuniaButton: false, expMapy: "", selectedIndex: 0, minlvl: 1, maxlvl: 300, } }; createMenu(){ const maindiv = document.createElement("div") maindiv.id = 'main-div' maindiv.style.cssText = `border-radius: 20px;border: 2px solid #0bff8b;background: linear-gradient(90deg, rgba(46,46,52,1) 0%, rgba(0,0,0,1) 35%, rgba(55,55,55,1) 100%);width: 416px;height: 320px;position: absolute;display: block;top: ${this.storage.position.x}px;left: ${this.storage.position.y}px;z-index: 999;`; const title = document.createElement("div") title.innerHTML = "<h2>nienawidze bociarzy</h2>" title.id = 'main-title' const content = document.createElement("div") content.id = 'main-content' const h1 = document.createElement('h'); h1.textContent = 'Exp'; const expButton = document.createElement('input'); expButton.type = 'checkbox'; expButton.id = 'ExpButton'; expButton.checked = this.storage.ExpButton; const tuniaH1 = document.createElement('h'); tuniaH1.textContent = 'Tunia'; const tuniaButton = document.createElement('input'); tuniaButton.type = 'checkbox'; tuniaButton.id = 'TuniaButton'; tuniaButton.checked = this.storage.TuniaButton; const gotomapsdiv = document.createElement('textarea'); gotomapsdiv.placeholder = 'Mapy do chodzenia..'; gotomapsdiv.id = 'gotomaps'; const lvlsdiv = document.createElement('span'); const lvlH1 = document.createElement('h'); lvlH1.textContent = 'Lvl:'; const minlvldiv = document.createElement('input'); minlvldiv.type = 'text'; minlvldiv.id = 'minlvl'; const hyphen = document.createElement('h'); hyphen.textContent = '-'; const maxlvldiv = document.createElement('input'); maxlvldiv.type = 'text'; maxlvldiv.id = 'maxlvl'; const selectsetup = document.createElement("select"); selectsetup.id = 'main-setups' selectsetup.style = "margin-left: 10px;margin-top: -4px;color: rgb(75 255 0);border-width: 1px;border-style: solid;border-radius: 2px;border-color: rgb(0 255 119);background: rgba(0, 0, 0, 0.1);width: 268px;"; const save = document.createElement('button'); save.textContent = 'Zapisz'; save.id = 'save'; lvlsdiv.append(lvlH1, minlvldiv, hyphen, maxlvldiv, selectsetup); content.append(h1, expButton, tuniaH1, tuniaButton, gotomapsdiv, lvlsdiv, save); maindiv.append(title, content); document.body.appendChild(maindiv); this.loadSetups(); save.addEventListener('click', () => { this.saveSetup() }); selectsetup.addEventListener("change",this.changeSetup) expButton.addEventListener('change', () => { if(expButton.checked){ this.storage.ExpButton = true; this.attackLoop() } else { this.storage.ExpButton = false; this.ws.send(JSON.stringify({type: 'stop'})) } localStorage.setItem('mamon666', JSON.stringify(this.storage)); }); tuniaButton.addEventListener('change', () => { TuniaButton.checked ? this.storage.TuniaButton = true : this.storage.TuniaButton = false; localStorage.setItem('mamon666', JSON.stringify(this.storage)); }); $("#main-div").draggable({ scroll: !1, start: () => { g.mouseMove.enabled = !1 }, stop: (e, ui) => { g.mouseMove.enabled = !0; this.storage.position = { x: ui.position.top, y: ui.position.left } localStorage.setItem('mamon666', JSON.stringify(this.storage)) } }) minlvldiv.value = this.storage.minlvl maxlvldiv.value = this.storage.maxlvl gotomapsdiv.value = this.storage.expMapy selectsetup.selectedIndex = this.storage.selectedIndex $('<link rel="stylesheet" type="text/css" href="https://cytrusek7331.ct8.pl/bot/style.css"/>').appendTo('head'); } saveSetup(){ this.storage.minlvl = Number(document.querySelector("#minlvl").value); this.storage.maxlvl = Number(document.querySelector("#maxlvl").value); this.storage.expMapy = document.querySelector("#gotomaps").value; localStorage.setItem('mamon666', JSON.stringify(this.storage)) message("Zapisano ustawienia!") } async loadSetups() { await fetch('https://cytruszef.ct8.pl/?setupy', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(res => { if (!res.ok) { throw new Error('Network response was not ok'); } return res.json(); }) .then(v => { const setups = document.querySelector("#main-setups"); for (let t = 0; t < v.length; t++) { const i = document.createElement("option"); i.value = `${v[t].lvl};${v[t].value}`; i.innerText = v[t].name; setups.appendChild(i); } }) console.log("Załadowano setupy!") }; changeSetup = () => { const selectedSetup = document.querySelector("#main-setups").value.split(";") const lvls = selectedSetup[0].split("-") const minlvl = Number(lvls[0]) const maxlvl = Number(lvls[1]) this.storage.expMapy = selectedSetup[1] this.storage.minlvl = minlvl this.storage.maxlvl = maxlvl this.storage.selectedIndex = document.querySelector("#main-setups").selectedIndex localStorage.setItem('mamon666', JSON.stringify(this.storage)) document.querySelector("#gotomaps").value = this.storage.expMapy document.querySelector("#minlvl").value = minlvl document.querySelector("#maxlvl").value = maxlvl document.querySelector("#main-setups").selectedIndex = this.storage.selectedIndex }; async attackLoop() { let mob; const expMaps = this.storage.expMapy.split(','); while (this.storage.ExpButton) { mob = this.closestMob({ min: this.storage.minlvl, max: this.storage.maxlvl }); if (!mob) { const currentMapIndex = expMaps.indexOf(mapid.toString()), nextMap = currentMapIndex !== -1 ? expMaps[currentMapIndex + 1] : (await this.getRoute(expMaps[0])).split(',')[1]; await this.goToMap(Number(nextMap)); } else { if (this.getDistanceToNpc(mob.x, mob.y) === 1) { window._g(`fight&a=attack&ff=1&id=-${mob.id}`); await new Promise(resolve => setTimeout(resolve, 500)); } else { await this.goTo(mob.x, mob.y); await new Promise(resolve => setTimeout(resolve, Math.round(this.getDistanceToNpc(mob.x, mob.y)) * 300)); } } } } getPath(x, y){ return new AStar(map.col, map.x,map.y, {x: hero.x,y: hero.y}, {x: x,y: y},g.npccol).anotherFindPath(); } goTo(x,y){ const path = this.getPath(x,y) const message = { type: 'path', current: { x: hero.x, y: hero.y }, path: path.map(point => ({ x: point.x, y: point.y, })).reverse(), } this.ws.send(JSON.stringify(message)) } async goToMap(id){ let x = g.gwIds[id].split('.')[0]; let y = g.gwIds[id].split('.')[1]; if(map.id == id) return true; while(g.gwIds[id] && hero.x ==! x && hero.y !== y){ this.goTo(x,y); await new Promise(resolve => setTimeout(resolve, this.getDistanceToNpc(x,y)*300)); } _g("walk"); } async getRoute(id){ const a = await fetch(`https://cytruszef.ct8.pl?start=${map.id}&end=${id}`).then(res => res.json()) return a.defaultPath } closestMob(lvl={min,max}){ let closestDist = 9999; let closestMonster; for (const npc of this.mobs()) { if(npc.lvl >= lvl.min&&npc.lvl <= lvl.max){ const path = this.getPath(npc.x,npc.y) if (path == undefined || path.length == 0) continue; const pathLength = path.length; if (pathLength < closestDist) { closestDist = pathLength; closestMonster = npc; } } } return closestMonster; } getDistanceToNpc = (x,y) => { const path = this.getPath(x,y); return Array.isArray(path) ? path.length : void 0; } init(){ g.loadQueue.push({fun:()=>{ this.createMenu() this.ws.send(JSON.stringify({type: 'init'})) }}) const e = () =>{ if(g.init == 5) this.storage.ExpButton ? this.attackLoop() : null; else{ setTimeout(e, 1000) } }; e(); } } const bot = new Game; bot.init() class AStar { constructor(collisionsString,width,height,start,end,additionalCollisions) { this.width = width; this.height = height; this.collisions = this.parseCollisions(collisionsString, width, height); this.additionalCollisions = additionalCollisions || {}; this.start = this.collisions[start.x][start.y]; this.end = this.collisions[end.x][end.y]; this.start.beginning = true; this.start.g = 0; this.start.f = heuristic(this.start, this.end); this.end.target = true; this.end.g = 0; this.addNeighbours(); this.openSet = []; this.closedSet = []; this.openSet.push(this.start); } parseCollisions(collisionsString, width, height) { const collisions = new Array(width); for (let w = 0; w < width; w++) { collisions[w] = new Array(height); for (let h = 0; h < height; h++) { collisions[w][h] = new Point(w, h, collisionsString.charAt(w + h * width) === "1" ); } } return collisions; } addNeighbours() { for (let i = 0; i < this.width; i++) { for (let j = 0; j < this.height; j++) { this.addPointNeighbours(this.collisions[i][j]); } } } addPointNeighbours(point) { const x = point.x, y = point.y; const neighbours = []; if (x > 0) neighbours.push(this.collisions[x - 1][y]); if (y > 0) neighbours.push(this.collisions[x][y - 1]); if (x < this.width - 1) neighbours.push(this.collisions[x + 1][y]); if (y < this.height - 1) neighbours.push(this.collisions[x][y + 1]); point.neighbours = neighbours; } anotherFindPath() { while (this.openSet.length > 0) { let currentIndex = this.getLowestF(); let current = this.openSet[currentIndex]; if (current === this.end) return this.reconstructPath(); else { this.openSet.splice(currentIndex, 1); this.closedSet.push(current); for (const neighbour of current.neighbours) { if (this.closedSet.includes(neighbour)) continue; else { const tentative_score = current.g + 1; let isBetter = false; if (this.end == this.collisions[neighbour.x][neighbour.y] || (!this.openSet.includes(neighbour) && !neighbour.collision && !this.additionalCollisions[neighbour.x + 256 * neighbour.y])) { this.openSet.push(neighbour); neighbour.h = heuristic(neighbour, this.end); isBetter = true; } else if (tentative_score < neighbour.g && !neighbour.collision) { isBetter = true; } if (isBetter) { neighbour.previous = current; neighbour.g = tentative_score; neighbour.f = neighbour.g + neighbour.h; } } } } } } getLowestF() { let lowestFIndex = 0; for (let i = 0; i < this.openSet.length; i++) { if (this.openSet[i].f < this.openSet[lowestFIndex].f) lowestFIndex = i; } return lowestFIndex; } reconstructPath() { const path = []; let currentNode = this.end; while (currentNode !== this.start) { path.push(currentNode); currentNode = currentNode.previous; } return path; } } class Point { constructor(x, y, collision) { this.x = x; this.y = y; this.collision = collision; this.neighbours = []; this.target = false; } } function heuristic(p1, p2) { return Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y); } index.js import puppeteer from 'puppeteer'; import {goTo} from './pathfinder/pathfinder.js' import {WebSocketServer} from 'ws'; class Game { constructor() {} async initGame(){ const wss = new WebSocketServer({ port: 8080 }); const cookies = [{ 'name': 'intro', 'value': '1', 'domain': '.margonem.pl', }, { 'name': 'interface', 'value': 'si', 'domain': '.margonem.pl' }, { 'name': '__mExts', 'value': 'd149364', 'domain': '.margonem.pl' }] const browser = await puppeteer.launch({ headless: false, args: ['--disable-extensions-except=C:/Users/cytrus/Desktop/main/margonem/botaddon/vpn','--window-size=500,300'], }); const page = await browser.newPage(); await page.setViewport({ width: 1920, height: 1080, deviceScaleFactor: 1, }); await page.evaluateOnNewDocument(() => { Object.defineProperty(navigator, 'webdriver', { get: () => false }) }); await page.setUserAgent('Mozilla/5.0 (Linux; Android 10; SM-T875) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.5671.215 Mobile Safari/537.36') await new Promise(resolve => setTimeout(resolve, 30000)); await page.setCookie(...cookies); await page.goto('https://www.margonem.pl/',{timeout: 120000}); await page.waitForSelector('input[name=login]',{timeout: 60000}); await page.waitForSelector('input[name=password]',{timeout: 60000}) await page.$eval('input[name=login]', el => el.value = 'CytruSek7331'); await page.$eval('input[name=password]', el => el.value = 'eluwina123'); const element2 = await page.waitForSelector("#js-login-btn > span", {timeout: 60000}) await element2.click(); await page.waitForNavigation({waitUntil: 'networkidle0',timeout: 80000}) console.log('logged in') wss.on('connection', ws => { ws.on('message', async message => { message = JSON.parse(message) switch (message.type) { case 'path': await goTo(page,message.path,message.current) break; case 'stop': await goTo(page,message.path,message.current) break; case 'init': ws.send('init') break; } }) }) } } const game = new Game(); game.initGame() pathfinder.js export async function goTo(page, path, current = { x, y }) { console.log('trasa smieciu', path); for (let i = 0; i < path.length; i++) { const next = path[i]; let direction; let steps = 0; if (next.x > current.x) { direction = 'KeyD'; steps = next.x - current.x; current.x += steps; } else if (next.x < current.x) { direction = 'KeyA'; steps = current.x - next.x; current.x -= steps; } else if (next.y > current.y) { direction = 'KeyS'; steps = next.y - current.y; current.y += steps; } else if (next.y < current.y) { direction = 'KeyW'; steps = current.y - next.y; current.y -= steps; } if (direction) { if (steps > 2) { await holdKey(page, direction, steps); } else { await moveHero(page, direction); } } } async function holdKey(page, direction, steps) { await page.focus('body'); await page.keyboard.down(direction); await new Promise(resolve => setTimeout(resolve, 300 * (steps - 2))); await page.keyboard.up(direction); await new Promise(resolve => setTimeout(resolve, 200)); } async function moveHero(page, direction) { await page.focus('body'); await page.keyboard.down(direction); setTimeout(async () => { await page.keyboard.up(direction); }, 100); await new Promise(resolve => setTimeout(resolve, 250)); } } Dlaczego moja przeglądarka po nacisnięciu przycisku do włączania bota i wybraniu zestawu gdzie ani nie ma moba na mapie, ani mapa nie jest expmaps odświeża stronę raz a po załadowaniu ponownym wysyła mnóstwo requestów przez getRoute i wyłącza przeglądarke z błędem: export async function goTo(page, path, current = { x, y }) { ^ ReferenceError: x is not defined
2adfb3d7d381f768c443f534b88bf3b3
{ "intermediate": 0.18338285386562347, "beginner": 0.6297815442085266, "expert": 0.18683558702468872 }
6,519
// Expression Action expression: IDENTIFIER { printf("Expression: %s\n", $1); // Lookup the variable in the symbol table void *var = SymbolTable_lookup($1); // Return the result of the expression return var; } | NUMBER { printf("Expression: %d\n", $1); // Return the result of the expression return $1; } | STRING { printf("Expression: %s\n", $1); // Return the result return $1; } | expression '+' expression { printf("Addition: %d + %d\n", $1, $3); // Add the two operands return $1 + $3; } | expression '-' expression { printf("Subtraction: %d - %d\n", $1, $3); // Subtract the second operand from the first return $1 - $3; } | expression '*' expression { printf("Multiplication: %d * %d\n", $1, $3); // Multiply the two operands return $1 * $3; } | expression '/' expression { printf("Division: %d / %d\n", $1, $3); // Check for division by zero if ($3 == 0) { fprintf(stderr, "Error: division by zero\n"); exit(1); } // Divide the first operand by the second return $1 / $3; }; What is wrong with this?
d87c212a25e221bed1a40b22c1129a2f
{ "intermediate": 0.3580986559391022, "beginner": 0.34999844431877136, "expert": 0.29190292954444885 }
6,520
do linearized gamma correction of an image using python, using the below formulations Note-> taking x as color pixel value of the image, gamma correction factor as 2.4 do all the below steps for the correction 1) gamma corrected image = - image (x), x<0 2) gamma corrected image = 0.0773993808049536 × image(x), 0 ≤ x < 0.04045 3) gamma corrected image = (0.9478672985781991x + 0.0521327014218009)^𝛾, 𝑥 ≥ 0.04045
6c3ccabacd722a7c7547b3c1ca118da2
{ "intermediate": 0.37593135237693787, "beginner": 0.22202610969543457, "expert": 0.40204253792762756 }
6,521
<main className="page"> <Navigation {...{ aboutref, skillref, myworkref, blogref, contactref }} /> {scrolled && !isKeyboardOpen && ( <div className="page__upper" onClick={() => scrollToRef(aboutref)}> <BsFillCaretUpFill className="icons" /> </div> )} <section> <ExperienceAndAbout skillref={skillref} /> <Tools /> <Myworks myworkref={myworkref} /> <Workstyle blogref={blogref} /> <JokePart /> </section> <Contact contactref={contactref} /> </main> ); make it more accesible more seamntic
f2596cee54a2489684151d680ad4983b
{ "intermediate": 0.35213106870651245, "beginner": 0.4207836389541626, "expert": 0.22708533704280853 }
6,522
now, perform CAT (chromatic adaptation technique) to reduce the white regions. The white regions are reduced by the brightest pixel value in the gamma corrected image, and the pixel value is selected between 0.1 to 0.35. The Gray World algorithm estimates the illumination correction value is based on the pixel value as selected from the gamma corrected image use python and cv2
3e72945abc04bdfc609a5b5d3bcc4ad1
{ "intermediate": 0.2446201592683792, "beginner": 0.14033344388008118, "expert": 0.6150464415550232 }
6,523
I need a react native expo page to capture a 45s video of myself with buttons to retake/save and small overlay to playback. It should have a text info prompt of what to record in the 45s which should fade when the recording starts and also reappear when the recording is completed or playback is available.
eed2708495cab9fc1189598e1ae97ff2
{ "intermediate": 0.37177538871765137, "beginner": 0.27498647570610046, "expert": 0.35323819518089294 }
6,524
Inductive div3 : nat -> Prop := | div0 : div3 0 | divS : forall n : nat, div3_2 n -> div3 (S n) with div3_1 : nat -> Prop := | div1 : div3_1 1 | div1S : forall n : nat, div3 n -> div3_1 (S n) with div3_2 : nat -> Prop := | div2 : div3_2 2 | div2S : forall n : nat, div3_1 n -> div3_2 (S n). Lemma prob8_helper: forall b n : nat, n <= b -> div3 n -> exists m : nat, n = 3 * m. Proof. Abort. Lemma prob8 : forall n : nat, div3 n -> exists m, n = 3 * m. Proof. Abort.Let us inductively define predicates for divisibility by three, one predicate for each possible remainder. Inductive div3 : nat -> Prop := | div0 : div3 0 | divS : forall n : nat, div3_2 n -> div3 (S n) with div3_2 : nat -> Prop := | div2 : div3_2 2 | div2S : forall n : nat, div3_1 n -> div3_2 (S n) with div3_1 : nat -> Prop := | div1 : div3_1 1 | div1S : forall n : nat, div3 n -> div3_1 (S n). Thus div3 will be true for all natural numbers that are evenly divisible by 3, div3 1 will be true for all natural numbers with remainder 1 when divided by 3, and div3 2 will be true for all numbers with remainder 2. We would like to prove that all natural numbers that are evenly divisible by 3 can be represented as 3 times some other natural number, Lemma prob8 : forall n : nat, div3 n -> exists m, n = 3 * m. However, this will require strong induction. Thus we first define a helper func- tion which will allow us to prove this Lemma prob8_helper: forall b n : nat, n <= b -> div3 n -> exists m : nat, n = 3 * m. This will allow us to use induction on b instead of n. We also note that the inversion tactic can be very useful here, since it will give the preconditions for any of these predicates to be true, for instance if they are in the hypotheses. If you would like to solve the problem without the helper proof, or with a different helper, feel free to do so. We will only check the proof for prob8.
7906f12b386594184ef4ba2a18d5d86e
{ "intermediate": 0.3197310268878937, "beginner": 0.31712883710861206, "expert": 0.3631401062011719 }
6,525
generate front end for me lms
f39f596506c6323776eb0b2c97dbeb1e
{ "intermediate": 0.3510625660419464, "beginner": 0.28778403997421265, "expert": 0.36115342378616333 }