row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
17,983
все ли верно ? это метод из homefragment : fun placeHolder(adapterPosition: Int) { Toast.makeText(requireContext(), adapterPosition, Toast.LENGTH_SHORT).show() } код адаптера : package com.example.cinema_provider_app.main_Fragments.Home_Fragment.Adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import com.example.cinema_provider_app.R import com.example.cinema_provider_app.main_Fragments.Home_Fragment.Data_Classes.FirstDataType import com.example.cinema_provider_app.main_Fragments.Home_Fragment.HomeFragment class FirstTypeAdapter(private var list: List<FirstDataType>,private val homeFragment: HomeFragment) : RecyclerView.Adapter<FirstTypeAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val createItem = LayoutInflater.from(parent.context) .inflate(R.layout.first_type_recycleview, parent, false) return ViewHolder(createItem) } override fun getItemCount(): Int { return list.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentItem = list[position] holder.img.setImageResource(currentItem.image) holder.img.setOnClickListener{ homeFragment.placeHolder(holder.adapterPosition) } } class ViewHolder(item: View) : RecyclerView.ViewHolder(item) { var img: ImageView = item.findViewById(R.id.fistTypeImage) init { img.setOnClickListener {} } } }
291db081ab38a4b2fac4810f81624675
{ "intermediate": 0.4370880126953125, "beginner": 0.30660179257392883, "expert": 0.2563101351261139 }
17,984
properly endoded url with ut8 in in c#
a45702544d8f4baa172a2a2ca1a430cd
{ "intermediate": 0.3629428744316101, "beginner": 0.2629595100879669, "expert": 0.37409767508506775 }
17,985
How does working this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal
b726db5c3514c407a58e2515cafaa569
{ "intermediate": 0.6042636036872864, "beginner": 0.17898505926132202, "expert": 0.2167513221502304 }
17,986
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal So tell me shortly if the buy orders is 60 % of all orders and sell orders is 40% of all order , which signal my code will give me ?
bf813536bf0441a474e399fd9fb15cff
{ "intermediate": 0.43210774660110474, "beginner": 0.19994939863681793, "expert": 0.36794283986091614 }
17,987
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / (sell_qty + buy_qty)) > 0.5: signal.append('sell') elif buy_qty > sell_qty and (buy_qty / (sell_qty + buy_qty)) > 0.5: signal.append('buy') else: signal.append('') return signal but it giving me only buy signal
0a588549bfbb10da1cc2e6f2686887b9
{ "intermediate": 0.38447320461273193, "beginner": 0.3491296172142029, "expert": 0.2663972079753876 }
17,988
Is it possible to write VBA code to an excel sheet using VBA. What I am trying to do is as follows. When a sheet is activated, VBA is copied from a template into the activated excel sheets VBA page.
4d58f49f0846fe11a906e58c3397c2a6
{ "intermediate": 0.26998835802078247, "beginner": 0.4947652518749237, "expert": 0.23524634540081024 }
17,989
how to create a Zabbix data item for counting the number of added lines to a log file in the last 5 minutes
73a93a8163958679939454ce8de03a64
{ "intermediate": 0.5213379859924316, "beginner": 0.16549135744571686, "expert": 0.3131706416606903 }
17,990
как думаешь, стоит ли использовать такой код для бэкенда сайта? const projects = await Project.findAll({ include: { model: Contributor, include: { model: User } } }) const data = projects.map(project => ({ id: project.id, title: project.title, description: project.description, image: project.image, background: project.background, link: project.image, contributors: project.contributors.map(contributor => ({ avatar: contributor.user.avatar })) })) return res.json(data)
2ea627b9fadeb971874c6e9406064dc7
{ "intermediate": 0.4152921438217163, "beginner": 0.36179718375205994, "expert": 0.22291065752506256 }
17,991
explain different ways to get instance from a class in java
18175c8b6389239df317bc109fa8667a
{ "intermediate": 0.4351738691329956, "beginner": 0.44180360436439514, "expert": 0.12302253395318985 }
17,992
You've dropped your (12-Hour) digital alarm clock; somehow the minutes were added to the hours! Since you do not know the current time, you need to figure out all the possible times that could have been on the clock before you dropped it (In ascending order). Input Line 1: An integer t that represents the total value displayed on the clock. Output Lines 1+: String in the format HH:MM, where HH is the hours (without leading 0) and MM is the minutes (with leading 0) of a potential time on the clock. Constraints 0 < t < 72 Example Input 69 Output 10:59 11:58 12:57 ....Please solve it with C# Code
bfd741da76659246f463db2ae99fc5e8
{ "intermediate": 0.4364151060581207, "beginner": 0.3385533094406128, "expert": 0.2250315546989441 }
17,993
I moved the code below from the Sheet VBA into a Module. Now I am getting an error on the line 'Target.Offset(0, -5).Value = "Serviced"' : Public Sub ServiceCreation() MsgBox "A New Service row will now be created" Target.Offset(0, -5).Value = "Serviced" Target.Offset(0, 1).Value = "" Dim newRow As Long newRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row + 1 ActiveSheet.Range("B" & newRow).Value = "Service" ActiveSheet.Range("C" & newRow).Value = Target.Offset(0, 2).Value ActiveSheet.Range("F" & newRow).Value = Target.Offset(0, -1).Value ActiveSheet.Range("J" & newRow).Value = Target.Offset(0, 3).Value ActiveSheet.Range("L" & newRow).Value = Target.Offset(0, 5).Value ActiveSheet.Range("H" & newRow).Value = Target.Offset(0, 2).Value + Target.Value End Sub
eb26705f1f311da3ca50ce64b1c084e0
{ "intermediate": 0.3309125006198883, "beginner": 0.4265485107898712, "expert": 0.24253901839256287 }
17,994
generate a simple string in java for me
bfba64371261890fe7355b9c5d422d3c
{ "intermediate": 0.5592747330665588, "beginner": 0.18490341305732727, "expert": 0.2558218240737915 }
17,995
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (0.5 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (0.5 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only buy singal
d60316c457ba94c5a0063c905bb62046
{ "intermediate": 0.39727842807769775, "beginner": 0.3169536590576172, "expert": 0.28576788306236267 }
17,996
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (0.5 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (0.5 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only signal to buy , but I need signals to buy sell and empty
d74e760e74c9a521cd0cae82c140f146
{ "intermediate": 0.4098619222640991, "beginner": 0.26969289779663086, "expert": 0.3204452097415924 }
17,997
I used this code:def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only signal to buy, can you set my code for it will give me signals to buy sell and empty
5ebe04d59d47cbc22a78ef9e5a3e4172
{ "intermediate": 0.45324599742889404, "beginner": 0.17825151979923248, "expert": 0.3685024678707123 }
17,998
How do I fix a Snapraid error that says data error in parity position diff bits
549949607b4f7d84680944242aa97875
{ "intermediate": 0.5952531695365906, "beginner": 0.08097656071186066, "expert": 0.3237702548503876 }
17,999
Is it possible to double click on a cell in the range J5:J100 and cause a text document to open with the values of column L of the same row displayed in the text document. If the text document is edited, when closed the edited text is then saved to the cell in column L, overwriting the original value.
dcc886d0dadcbf86f782f04dbc9702e2
{ "intermediate": 0.44007930159568787, "beginner": 0.2071419209241867, "expert": 0.35277873277664185 }
18,000
why i get this error : /root/Env/imdb/lib/python3.8/site-packages/scipy/stats/_continuous_distns.py:411: RuntimeWarning: Mean of empty slice. loc = data.mean() /root/Env/imdb/lib/python3.8/site-packages/numpy/core/_methods.py:192: RuntimeWarning: invalid value encountered in scalar divide ret = ret.dtype.type(ret / rcount) /root/Env/imdb/lib/python3.8/site-packages/scipy/stats/_continuous_distns.py:416: RuntimeWarning: Mean of empty slice. scale = np.sqrt(((data - loc)**2).mean()) here is my code : def calculate_3month_priority(): try: Define the time periods in months ini Copy movies = get_movies_within_3month() ini Copy # Define the boxes for the priority scores boxes = np.linspace(-3, 3, 7)[1:-1] # Get the current date # Iterate over the time periods # Calculate the watch counts for the current time period watch_counts = [movie.engagementStatistics for movie in movies] # Check if there are no movies for the current time period # Fit a normal distribution to the watch counts mean, std_dev = norm.fit(watch_counts) # Normalize the watch counts using the normal distribution normalized_watch_counts = [(count - mean) / std_dev for count in watch_counts] # Divide the normalized watch counts into boxes box_indices = np.digitize(normalized_watch_counts, boxes, right=True) # Sort the movies by priority score in descending order (highest to lowest) sorted_movies = sorted(zip(movies, normalized_watch_counts, box_indices), key=lambda x: (x[2], x[1]), reverse=True) # Iterate over the sorted movies and write them to the worksheet for j, (movie, priority, box_index) in enumerate(sorted_movies, start=2): # Write the movie title, priority, and box index to the worksheet # my_json = json.loads(movie.periodPriority) # my_json[0]['3month'] = priority # movie.periodPriority = json.dumps(my_json) # movie.ThreeMonthPriority = priority # movie.save() logger.debug(f'title is {movie.title}--{priority}') logger.debug('movie saved') except Exception as e : logger.debug(f'error is : {e}') and here is my mode : class Film(models.Model): id = models.AutoField(primary_key=True, verbose_name='id') title = models.CharField(max_length=150, db_index=True, blank=True, verbose_name='title') type = models.IntegerField(choices=((1, 'movies'), (2, 'series')), verbose_name='type') ageClassification = models.CharField(max_length=150, db_index=True, verbose_name='ageClassification',null=True) runtime = models.CharField(max_length=150, db_index=True, verbose_name='runtime') featureYear = models.IntegerField(blank=True,null=True) description = HTMLField(blank=True, verbose_name='description',null=True) keyWordUrl = models.URLField(blank=True, verbose_name='keyWordLink',null=True) storyLineUrl = models.URLField(blank=True, verbose_name='storyLineLink',null=True) newsUrl = models.URLField(blank=True, verbose_name='newsLink',null=True) criticUrl = models.URLField(blank=True, verbose_name='criticLink',null=True) storyline= HTMLField(blank=True, verbose_name='storyline',null=True) sysnopse= HTMLField(blank=True, verbose_name='synopse',null=True) imdbScoreRate = models.FloatField(null=True, blank=True, verbose_name="imdbScore") MetaScoreRate = models.FloatField(null=True, blank=True, verbose_name="metaScore") imdbLink = models.URLField(verbose_name='ImdbLink',unique=True) productionStatus = models.CharField(max_length=200, blank=True,null=True, verbose_name='productionStatus') numVotes = models.FloatField(null=True, blank=True, verbose_name="numVotes") stars = models.CharField(max_length=250, blank=True,null=True) writers = models.CharField(max_length=250, blank=True,null=True) directors = models.CharField(max_length=250, blank=True,null=True) releaseDate = models.DateField(blank=True, null=True) artists = models.ManyToManyField(Artist, related_name='artists', through='Role', blank=True, verbose_name='artists',null=True) engagementStatistics = models.IntegerField(blank=True, verbose_name='engagementStatistics',null=True) genre = models.JSONField(blank=True,null=True) boxOffice = models.JSONField(blank=True,null=True) company = models.JSONField(blank=True,null=True) cast = models.JSONField(blank=True,null=True) relatedReviews = models.ManyToManyField(Reviews,through='FilmReviews', related_name='reviews',blank=True,verbose_name='reviews') relatedReviewsJson = models.JSONField(blank=True,null=True) relatedNewsJson = models.JSONField(blank=True,null=True) relatedNews = models.ManyToManyField(News,through='FilmNews',related_name='news',blank=True, verbose_name='news' ) pubDate = models.DateTimeField('date published', auto_now_add=True, db_index=True) periodPriority = models.JSONField(blank=True,null=True) ThreeMonthPriority = models.FloatField(null=True, blank=True) SixMonthPriority = models.FloatField(null=True, blank=True) FarMonthPriority = models.FloatField(null=True, blank=True) priorityMaxEngCompany = models.FloatField(null=True, blank=True) priorityMaxMovieActor = models.FloatField(null=True, blank=True) priorityMaxMovieDirecotr = models.FloatField(null=True, blank=True) priorityMeta = models.FloatField(null=True, blank=True) priority_meta_group = models.CharField(max_length=20, blank=True, null=True) modifyDate = models.DateTimeField(auto_now=True, db_index=True) InYearPriority = models.FloatField(null=True, blank=True)
896b1b05b31b4265b6e1b6675f388c4c
{ "intermediate": 0.37049761414527893, "beginner": 0.5006582140922546, "expert": 0.12884415686130524 }
18,001
Давай напишем пример программы на arduino для esp32. К пину 0 подключена матрица светодиодов ws2812. Подключен микрофон inmp441 к пинам I2S_WS 33, I2S_SD 32, I2S_SCK 27. Нужно использовать библиотек FFT library и нарисовать спектр, при этом использовать минимальное количество памяти для переменных
1344e75bdb26ba5b42a97be9b04bfc27
{ "intermediate": 0.554765522480011, "beginner": 0.2165064513683319, "expert": 0.2287280261516571 }
18,002
create table t1 (id int, name char(1)) insert into t1 values(1, 'a'), (2, 'b'), (3,'c'), (7,'d'), (9,'f') select id, name from t1 --Q: expected result: --id name result --1 a f --2 b d --3 c c --7 d b --9 f a
9f916634c7f821186f82b4da93e54ebd
{ "intermediate": 0.4288957715034485, "beginner": 0.26380571722984314, "expert": 0.3072985112667084 }
18,003
delete injured players from players table
f2363a51d4d5115a606375a7a1e5552e
{ "intermediate": 0.36206144094467163, "beginner": 0.27692529559135437, "expert": 0.3610133230686188 }
18,004
use numbers as pixels,make 80x80 symbols picture.sarah silverman face.do not use ASCII,just make it as if you wrote a text lines
918a5e40795457d547928c9d78f35d8d
{ "intermediate": 0.3793371915817261, "beginner": 0.2804296612739563, "expert": 0.34023311734199524 }
18,005
vnx,mnvc
89ad49acadd3f125c70a52b481b11eaa
{ "intermediate": 0.3147883713245392, "beginner": 0.32181671261787415, "expert": 0.3633948564529419 }
18,006
Write a SQL query to get the SCD - TYPE 2 Dimension achieve using SQL query. ENO & ENAME are business key, here any change happen to SAL or Dept has to maintain SCD-TYPE2 EMP_DIM (Target Table) ENO ENAME SAL DEPT Active_flag 100 ABC 1000 CSE 0 102 XYZ 2000 CSE 1 104 PQR 500 IT 1 100 ABC 3000 CSE 1 Source Record 100 ABC 5000 CSE -> day 2 (sal change) 104 PQR 500 MECH -> day 2 (dept change) 105 LMN 3000 CSE -> Day 2 (new row)
eb74b7181a3309ccaaa0d56a28545aa2
{ "intermediate": 0.3610984683036804, "beginner": 0.34196504950523376, "expert": 0.2969364821910858 }
18,007
写一段代码,若给出一组点可以根据点使用拉格朗日插值形成一条曲线,并且用pyqt开窗口绘制出来
813824a8134bcc116d8b00adb2251dfa
{ "intermediate": 0.3129587471485138, "beginner": 0.33783090114593506, "expert": 0.34921035170555115 }
18,008
style my material react component to be in middle of screen
1519f6bceb709cdbbbed2bf47baffbbd
{ "intermediate": 0.3290807902812958, "beginner": 0.3366887867450714, "expert": 0.3342303931713104 }
18,009
what is data entry
e01ba2d16811e740ee90974270b8125d
{ "intermediate": 0.30710741877555847, "beginner": 0.4481332004070282, "expert": 0.24475935101509094 }
18,011
give me simple code
f0bc4cb1db3cf34a91394df01cd8a8d0
{ "intermediate": 0.11996177583932877, "beginner": 0.6123875975608826, "expert": 0.26765063405036926 }
18,012
Within Mininet, create the following topology. Here h1 is a remote server (ie google.com) on the Internet that has a fast connection (1Gb/s) to your home router with a slow downlink connection (10Mb/s). The round-trip propagation delay, or the minimum RTT between h1 and h2 is 6ms. The router buffer size can hold 100 full sized ethernet frames (about 150kB with an MTU of 1500 bytes). Then do the following: Start a long lived TCP flow sending data from h1 to h2. Use iperf. . Send pings from h1 to h2 10 times a second and record the RTTs. .Plot the time series of the following: o The long lived TCP flow’s cwnd o The RTT reported by ping o Queue size at the bottleneck . Spawn a webserver on h1. Periodically download the index.html web page (three times every five seconds) from h1 and measure how long it takes to fetch it (on average). The starter code has some hints on how to do this. Make sure that the webpage download data is going in the same direction as the long-lived flow. The long lived flow, ping train, and web server downloads should all be happening simultaneously. Repeat the above experiment and replot all three graphs with a smaller router buffer size (Q=20 packets). write code in python
497f6b466effd1f7032f0e5a13b80c09
{ "intermediate": 0.45659321546554565, "beginner": 0.18975581228733063, "expert": 0.3536509573459625 }
18,013
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (0.5 + threshold): signal.append('sell') if buy_qty > sell_qty and (buy_qty / sell_qty) > (0.5 + threshold): signal.append('buy') if not signal: signal.append('') # Append an empty string for the empty scenario return signal But it giving me only signal to buy , plesae give me code which will give me signals to buy sell or empty
57a2920bb749a5337b1575e75b5fd54c
{ "intermediate": 0.3983486592769623, "beginner": 0.21376821398735046, "expert": 0.38788312673568726 }
18,014
how can i make my requests use TLS? package main import ( "encoding/json" "net/http" "math/rand" "strconv" "time" "fmt" ) type UAResponse struct { UserAgents []string `json:"user_agents"` } func getUserAgents() []string { url := "http://127.0.0.1:5000/api/get_ua"; req, _ := http.NewRequest("GET", url, nil); resp, _ := http.DefaultClient.Do(req); defer resp.Body.Close(); var response UAResponse; json.NewDecoder(resp.Body).Decode(&response); return response.UserAgents; }; func httpFlood(target string, UAs []string, duration int, startTime int){ for int(time.Now().Unix()) <= int(startTime+duration) { randNum := strconv.Itoa(rand.Int()); url := target + "?page=" + randNum; UA := UAs[rand.Intn(len(UAs))]; acceptEncodings := []string{ "*", "gzip, deflate, br", "gzip, compress, deflate", "gzip, deflate, br", "gzip, br", "gzip, deflate, br, compress, identity", } referers := []string{ "https://google.com/", "https://www.bing.com/", "https://yandex.com/", "https://search.brave.com/", "https://duckduckgo.com/", "https://search.yahoo.com/", "https://www.instagram.com/", "https://www.facebook.com/", } acceptEncoding := acceptEncodings[rand.Intn(len(acceptEncodings))]; refferer := referers[rand.Intn(len(referers))]; req, _ := http.NewRequest("GET", url, nil); req.Header.Set("User-Agent", UA); req.Header.Set("Referer", refferer); req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") req.Header.Set("Accept-Encoding", acceptEncoding) req.Header.Set("Accept-Language", "en-US,en;q=0.5") req.Header.Set("Connection", "keep-alive") http.DefaultClient.Do(req); fmt.Println("hi") } return; }; func attack(target string, threads int, duration int) { userAgents := getUserAgents() startTime := int(time.Now().Unix()); for i := 0; i < threads - 1; i++ { go httpFlood(target, userAgents, duration, startTime); }; httpFlood(target, userAgents, duration, startTime) return; } func main() { target := "https://tls.mrrage.xyz/nginx_status"; threads := 24; // Localhost - 4 duration := 10; attack(target, threads, duration) return; };
033ebe37403c47eecb8a240d6739f1a9
{ "intermediate": 0.292242169380188, "beginner": 0.34879228472709656, "expert": 0.35896557569503784 }
18,015
explain trading bots
74e854768f8bc8a9d0349a52c96dcfc5
{ "intermediate": 0.28117504715919495, "beginner": 0.33469951152801514, "expert": 0.3841255009174347 }
18,016
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') # Append an empty string for the empty scenario return signal But it giving me only buy signal and empty , please give me code which will give me signal to sell too
7f9fc5f4d1db58c0d314fdb367b226ca
{ "intermediate": 0.39434459805488586, "beginner": 0.2455860674381256, "expert": 0.36006927490234375 }
18,017
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') # Append an empty string for the empty scenario return signal But it giving me only signal to buy and empty, give me code which will give me signal to buy sell and empty
75afb5dae6a12af71b3e338716b9235e
{ "intermediate": 0.4209422469139099, "beginner": 0.23945021629333496, "expert": 0.3396076261997223 }
18,018
java testing using stub how to deal with comparison of objects ?
b439ff9600fa168f3c6cfdc911c2e372
{ "intermediate": 0.7055811882019043, "beginner": 0.08588086813688278, "expert": 0.2085379809141159 }
18,019
When I double click on a cell and it calls the event - Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) depending on the vba action It sometime calls the event Private Sub Worksheet_Change(ByVal Target As Range) How can I prevent this
52be082df76fe185d645987a43b2efe1
{ "intermediate": 0.6663116216659546, "beginner": 0.15794304013252258, "expert": 0.17574529349803925 }
18,020
Physical design. The physical design phase in various methodologies is called "Design at the storage level" or "Design implementation". This is the implementation stage in a specific software environment (in a specific DBMS). The fulfillment of such requirements as productivity, efficiency and reliability of functioning depends on the design results at this stage. The stage of physical design consists in linking the logical structure of the database and the physical storage medium in order to most efficiently place data, i.e. mapping the logical structure of the database to the storage structure. The issue of placing the stored data in the memory space, the choice of effective methods of access to various components of the "physical" database is being solved. The results of this step are documented in the form of a storage schema in a storage definition language. The decisions made at this stage have a decisive influence on the performance of the system. Design at this stage generally consists of the following steps: 1) Database analysis in terms of SQL command execution performance 2) Deciding on the need to denormalize the database. 3) Designing schemes for data storage and data placement. 4) Selecting the required indexes. Choose a DBMS (having justified the choice) and perform physical design for the subject area “Horse Racing”.
bc49e67715f1e9419cb042e54c82126d
{ "intermediate": 0.23051588237285614, "beginner": 0.45262616872787476, "expert": 0.3168579638004303 }
18,021
from openpyxl import load_workbook import pandas as pd # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) calculate_percentile(df,'2013-08-19','螺纹钢') def calculate_percentile(df,date, column): date = pd.to_datetime(date) year = date.year month = date.month day = date.day history_dates = df[(df.index.month == month) & (df.index.day == day) & (df.index.year <= year)].index history_values = df[df.index.isin(history_dates)][column] target_value = df.loc[date, column] min_value = history_values.min() max_value = history_values.max() percentile= (target_value - min_value) / (max_value - min_value) * 100 --------------------------------------------------------------------------- KeyError Traceback (most recent call last) ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.DatetimeEngine.get_loc() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 1376870400000000000 During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key) 3652 try: -> 3653 return self._engine.get_loc(casted_key) 3654 except KeyError as err: ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.DatetimeEngine.get_loc() ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.DatetimeEngine.get_loc() KeyError: Timestamp('2013-08-19 00:00:00') The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) ~\anaconda3\lib\site-packages\pandas\core\indexes\datetimes.py in get_loc(self, key) 583 try: --> 584 return Index.get_loc(self, key) 585 except KeyError as err: ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key) 3654 except KeyError as err: -> 3655 raise KeyError(key) from err 3656 except TypeError: KeyError: Timestamp('2013-08-19 00:00:00') The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_8864/2648162365.py in <module> 27 df.index = pd.to_datetime(df.index) 28 ---> 29 calculate_percentile(df,'2013-08-19','螺纹钢') 30 31 def calculate_percentile(df,date, column): ~\AppData\Local\Temp/ipykernel_8864/2397934083.py in calculate_percentile(df, date, column) 6 history_dates = df[(df.index.month == month) & (df.index.day == day) & (df.index.year <= year)].index 7 history_values = df[df.index.isin(history_dates)][column] ----> 8 target_value = df.loc[date, column] 9 min_value = history_values.min() 10 max_value = history_values.max() ~\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key) 1094 key = tuple(com.apply_if_callable(x, self.obj) for x in key) 1095 if self._is_scalar_access(key): -> 1096 return self.obj._get_value(*key, takeable=self._takeable) 1097 return self._getitem_tuple(key) 1098 else: ~\anaconda3\lib\site-packages\pandas\core\frame.py in _get_value(self, index, col, takeable) 3875 # results if our categories are integers that dont match our codes 3876 # IntervalIndex: IntervalTree has no get_loc -> 3877 row = self.index.get_loc(index) 3878 return series._values[row] 3879 ~\anaconda3\lib\site-packages\pandas\core\indexes\datetimes.py in get_loc(self, key) 584 return Index.get_loc(self, key) 585 except KeyError as err: --> 586 raise KeyError(orig_key) from err 587 588 @doc(DatetimeTimedeltaMixin._maybe_cast_slice_bound) KeyError: Timestamp('2013-08-19 00:00:00') 错误信息如下 帮我看看怎么改?
a0a4574f68fd6e2a6395b151bc6cbbec
{ "intermediate": 0.38120245933532715, "beginner": 0.3119480013847351, "expert": 0.3068494498729706 }
18,022
Act as a Chrome Extension developer. Generate code for chrome extension to scrap google maps places data with proper files and folder structure.
cfe18b96238c6a9032579a361ad863f3
{ "intermediate": 0.4905896484851837, "beginner": 0.20573550462722778, "expert": 0.3036748170852661 }
18,023
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only signal to buy, please don't copy my code and give me code which will give me signal to buy sell or empty
0af71e1b17423b4d600ed54952ddee2e
{ "intermediate": 0.37353649735450745, "beginner": 0.28985893726348877, "expert": 0.3366045355796814 }
18,024
class News(models.Model): id = models.AutoField(primary_key=True, verbose_name='id') writer = models.CharField(max_length=200, verbose_name='writer') title = models.CharField(max_length=200, blank=True, verbose_name='title') text = models.TextField(blank=True) url = models.URLField(blank=True) python Copy def __str__(self): if self.writer : return u'%s -- %s' % (self.title , self.writer) else: return u'%s' % (self.title) class Reviews(models.Model): id = models.AutoField(primary_key=True, verbose_name='id') writer = models.CharField(max_length=200, verbose_name='writer') text = models.TextField(blank=True) url = models.URLField(blank=True) python Copy def __str__(self): if self.writer : return u'%s -- %s' % (self.url , self.writer) else: return u'%s' % (self.url) class Film(models.Model): id = models.AutoField(primary_key=True, verbose_name='id') title = models.CharField(max_length=150, db_index=True, blank=True, verbose_name='title') type = models.IntegerField(choices=((1, 'movies'), (2, 'series')), verbose_name='type') ageClassification = models.CharField(max_length=150, db_index=True, verbose_name='ageClassification',null=True) runtime = models.CharField(max_length=150, db_index=True, verbose_name='runtime') featureYear = models.IntegerField(blank=True,null=True) description = HTMLField(blank=True, verbose_name='description',null=True) keyWordUrl = models.URLField(blank=True, verbose_name='keyWordLink',null=True) storyLineUrl = models.URLField(blank=True, verbose_name='storyLineLink',null=True) newsUrl = models.URLField(blank=True, verbose_name='newsLink',null=True) criticUrl = models.URLField(blank=True, verbose_name='criticLink',null=True) storyline= HTMLField(blank=True, verbose_name='storyline',null=True) sysnopse= HTMLField(blank=True, verbose_name='synopse',null=True) imdbScoreRate = models.FloatField(null=True, blank=True, verbose_name="imdbScore") MetaScoreRate = models.FloatField(null=True, blank=True, verbose_name="metaScore") imdbLink = models.URLField(verbose_name='ImdbLink',unique=True) productionStatus = models.CharField(max_length=200, blank=True,null=True, verbose_name='productionStatus') numVotes = models.FloatField(null=True, blank=True, verbose_name="numVotes") stars = models.CharField(max_length=250, blank=True,null=True) writers = models.CharField(max_length=250, blank=True,null=True) directors = models.CharField(max_length=250, blank=True,null=True) releaseDate = models.DateField(blank=True, null=True) artists = models.ManyToManyField(Artist, related_name='artists', through='Role', blank=True, verbose_name='artists',null=True) engagementStatistics = models.IntegerField(blank=True, verbose_name='engagementStatistics',null=True) genre = models.JSONField(blank=True,null=True) boxOffice = models.JSONField(blank=True,null=True) company = models.JSONField(blank=True,null=True) cast = models.JSONField(blank=True,null=True) relatedReviews = models.ManyToManyField(Reviews,through='FilmReviews', related_name='reviews',blank=True,verbose_name='reviews') relatedReviewsJson = models.JSONField(blank=True,null=True) relatedNewsJson = models.JSONField(blank=True,null=True) relatedNews = models.ManyToManyField(News,through='FilmNews',related_name='news',blank=True, verbose_name='news' ) pubDate = models.DateTimeField('date published', auto_now_add=True, db_index=True) periodPriority = models.JSONField(blank=True,null=True) ThreeMonthPriority = models.FloatField(null=True, blank=True) SixMonthPriority = models.FloatField(null=True, blank=True) FarMonthPriority = models.FloatField(null=True, blank=True) priorityMaxEngCompany = models.FloatField(null=True, blank=True) priorityMaxMovieActor = models.FloatField(null=True, blank=True) priorityMaxMovieDirecotr = models.FloatField(null=True, blank=True) priorityMeta = models.FloatField(null=True, blank=True) priority_meta_group = models.CharField(max_length=20, blank=True, null=True) modifyDate = models.DateTimeField(auto_now=True, db_index=True) InYearPriority = models.FloatField(null=True, blank=True) class FilmNews(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE) news = models.ForeignKey(News, on_delete=models.CASCADE) class FilmReviews(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE) review = models.ForeignKey(Reviews, on_delete=models.CASCADE) conside my django models below i want to see the reviews that connected to a specific film
173986e51b8bb090aaf340ad352f23ea
{ "intermediate": 0.2606687843799591, "beginner": 0.5387904644012451, "expert": 0.2005407065153122 }
18,025
I used your code : def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only signal to buy , I was need to take loss , give me code which will give me signals to buy sell or empty
e16df5b7c25d3404de3660210dd295f0
{ "intermediate": 0.479497492313385, "beginner": 0.23644982278347015, "expert": 0.28405264019966125 }
18,026
from openpyxl import load_workbook import pandas as pd import datetime # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df,date, column): date = pd.to_datetime(date) year = date.year month = date.month day = date.day five_years_ago = datetime.datetime.now() - pd.DateOffset(years=5) history_dates = df[(df.index.month == month) & (df.index.day == day) & (df.index.year <= year) & (df.index > five_years_ago)].index history_values = df[df.index.isin(history_dates)][column] target_value = df.loc[date, column] mean_target_value = df.loc[date:date-4, column].mean() min_value = history_values.min() max_value = history_values.max() percentile= (target_value - min_value) / (max_value - min_value) * 100 return percentile return history_dates percentile =calculate_percentile(df,'2023-08-19','螺纹钢') print(percentile) print(history_dates) TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_8864/817727447.py in <module> 43 return percentile 44 return history_dates ---> 45 percentile =calculate_percentile(df,'2023-08-19','螺纹钢') 46 print(percentile) 47 print(history_dates) 我运行上述代码 返回了如下错误 请帮我看下原因? ~\AppData\Local\Temp/ipykernel_8864/817727447.py in calculate_percentile(df, date, column) 37 history_values = df[df.index.isin(history_dates)][column] 38 target_value = df.loc[date, column] ---> 39 mean_target_value = df.loc[date:date-4, column].mean() 40 min_value = history_values.min() 41 max_value = history_values.max() ~\anaconda3\lib\site-packages\pandas\_libs\tslibs\timestamps.pyx in pandas._libs.tslibs.timestamps._Timestamp.__sub__() ~\anaconda3\lib\site-packages\pandas\_libs\tslibs\timestamps.pyx in pandas._libs.tslibs.timestamps._Timestamp.__add__() TypeError: Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting `n`, use `n * obj.freq`
d412f2bb7a13d307eac5efda9e78616a
{ "intermediate": 0.36316946148872375, "beginner": 0.39141619205474854, "expert": 0.2454143762588501 }
18,027
Write a matlab function for making a step-down counter from 10 to 1
3a83f3d759e6070920a1ed0693abcb6b
{ "intermediate": 0.15968920290470123, "beginner": 0.2344236820936203, "expert": 0.6058870553970337 }
18,028
could you post the past scripts
acc9bcb46c65399c65b0542b7327f51f
{ "intermediate": 0.3199043273925781, "beginner": 0.3908480703830719, "expert": 0.28924763202667236 }
18,029
def zdres(nav, obs, rs, dts, svh, rr, rtype=1): """ non-differencial residual """ _c = gn.rCST.CLIGHT nf = nav.nf n = len(obs.P) y = np.zeros((n, nf*2)) el = np.zeros(n) e = np.zeros((n, 3)) rr_ = rr.copy() if nav.tidecorr: pos = gn.ecef2pos(rr_) disp = tidedisp(gn.gpst2utc(obs.t), pos) rr_ += disp pos = gn.ecef2pos(rr_) for i in range(n): sys, _ = gn.sat2prn(obs.sat[i]) if svh[i] > 0 or sys not in nav.gnss_t or obs.sat[i] in nav.excl_sat: continue r, e[i, :] = gn.geodist(rs[i, :], rr_) _, el[i] = gn.satazel(pos, e[i, :]) if el[i] < nav.elmin: continue r += -_c*dts[i] zhd, _, _ = gn.tropmodel(obs.t, pos, np.deg2rad(90.0), 0.0) mapfh, _ = gn.tropmapf(obs.t, pos, el[i]) r += mapfh*zhd dant = gn.antmodel(nav, el[i], nav.nf, rtype) for f in range(nf): j = nav.obs_idx[f][sys] if obs.L[i, j] == 0.0: y[i, f] = 0.0 else: y[i, f] = obs.L[i, j]*_c/nav.freq[j]-r-dant[f] if obs.P[i, j] == 0.0: y[i, f+nf] = 0.0 else: y[i, f+nf] = obs.P[i, j]-r-dant[f] return y, e, el convert this python code to matlab. write simple as possible
313c057eb677f092bbd0213886781694
{ "intermediate": 0.3385579586029053, "beginner": 0.37007948756217957, "expert": 0.29136255383491516 }
18,030
I have this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal How does working this ocde?
1e067dda8de79aceceef979036670220
{ "intermediate": 0.47286248207092285, "beginner": 0.24768295884132385, "expert": 0.2794545888900757 }
18,031
def ddres(nav, x, y, e, sat, el): """ DD phase/code residual """ _c = gn.rCST.CLIGHT nf = nav.nf ns = len(el) mode = 1 if len(y) == ns else 0 # 0:DD,1:SD nb = np.zeros(2*len(nav.gnss_t)*nf, dtype=int) Ri = np.zeros(ns*nf*2) Rj = np.zeros(ns*nf*2) nv = 0 b = 0 H = np.zeros((ns*nf*2, nav.nx)) v = np.zeros(ns*nf*2) idx_f = [0, 1] for sys in nav.gnss_t: for f in range(nf): idx_f[f] = nav.obs_idx[f][sys] for f in range(0, nf*2): if f < nf: freq = nav.freq[idx_f[f]] # reference satellite idx = sysidx(sat, sys) if len(idx) > 0: i = idx[np.argmax(el[idx])] for j in idx: if i == j: continue if y[i, f] == 0.0 or y[j, f] == 0.0: continue # DD residual if mode == 0: if y[i+ns, f] == 0.0 or y[j+ns, f] == 0.0: continue v[nv] = (y[i, f]-y[i+ns, f])-(y[j, f]-y[j+ns, f]) else: v[nv] = y[i, f]-y[j, f] H[nv, 0:3] = -e[i, :]+e[j, :] if f < nf: # carrier idx_i = IB(sat[i], f, nav.na) idx_j = IB(sat[j], f, nav.na) lami = _c/freq v[nv] -= lami*(x[idx_i]-x[idx_j]) H[nv, idx_i] = lami H[nv, idx_j] = -lami Ri[nv] = varerr(nav, el[i], f) Rj[nv] = varerr(nav, el[j], f) nav.vsat[sat[i]-1, f] = 1 nav.vsat[sat[j]-1, f] = 1 else: Ri[nv] = varerr(nav, el[i], f) Rj[nv] = varerr(nav, el[j], f) nb[b] += 1 nv += 1 b += 1 v = np.resize(v, nv) H = np.resize(H, (nv, nav.nx)) R = ddcov(nb, b, Ri, Rj, nv) return v, H, R convert this python code to matlab. write simple as possible
624695c5667bad8e9d3069ff3e71d8dc
{ "intermediate": 0.3953838348388672, "beginner": 0.4203895330429077, "expert": 0.18422666192054749 }
18,032
def restamb(nav, bias, nb): """ restore SD ambiguity """ nv = 0 xa = nav.x.copy() xa[0:nav.na] = nav.xa[0:nav.na] for m in range(gn.uGNSS.GNSSMAX): for f in range(nav.nf): n = 0 index = [] for i in range(gn.uGNSS.MAXSAT): sys, _ = gn.sat2prn(i+1) if sys != m or (sys not in nav.gnss_t) or nav.fix[i, f] != 2: continue index.append(IB(i+1, f, nav.na)) n += 1 if n < 2: continue xa[index[0]] = nav.x[index[0]] for i in range(1, n): xa[index[i]] = xa[index[0]]-bias[nv] nv += 1 return xa def resamb_lambda(nav, sat): """ resolve integer ambiguity using LAMBDA method """ nx = nav.nx na = nav.na xa = np.zeros(na) ix = ddidx(nav, sat) nb = len(ix) if nb <= 0: print("no valid DD") return -1, -1 # y=D*xc, Qb=D*Qc*D', Qab=Qac*D' y = nav.x[ix[:, 0]]-nav.x[ix[:, 1]] DP = nav.P[ix[:, 0], na:nx]-nav.P[ix[:, 1], na:nx] Qb = DP[:, ix[:, 0]-na]-DP[:, ix[:, 1]-na] Qab = nav.P[0:na, ix[:, 0]]-nav.P[0:na, ix[:, 1]] # MLAMBDA ILS b, s = mlambda(y, Qb) if s[0] <= 0.0 or s[1]/s[0] >= nav.thresar[0]: nav.xa = nav.x[0:na].copy() nav.Pa = nav.P[0:na, 0:na].copy() bias = b[:, 0] y -= b[:, 0] K = Qab@np.linalg.inv(Qb) nav.xa -= K@y nav.Pa -= K@Qab.T # restore SD ambiguity xa = restamb(nav, bias, nb) else: nb = 0 return nb, xa convert this python code to matlab. write simple as possible
df77a3dd3299ceed2c4c848176783263
{ "intermediate": 0.29090386629104614, "beginner": 0.44955071806907654, "expert": 0.2595454454421997 }
18,033
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only signal to buy, please give me code which will give me signals to buy sell and empty
2f53278b48d0315cbe8ba72725139483
{ "intermediate": 0.43996462225914, "beginner": 0.21528491377830505, "expert": 0.34475043416023254 }
18,034
def holdamb(nav, xa): """ hold integer ambiguity """ nb = nav.nx-nav.na v = np.zeros(nb) H = np.zeros((nb, nav.nx)) nv = 0 for m in range(gn.uGNSS.GNSSMAX): for f in range(nav.nf): n = 0 index = [] for i in range(gn.uGNSS.MAXSAT): sys, _ = gn.sat2prn(i+1) if sys != m or nav.fix[i, f] != 2: continue index.append(IB(i+1, f, nav.na)) n += 1 nav.fix[i, f] = 3 # hold # constraint to fixed ambiguity for i in range(1, n): v[nv] = (xa[index[0]]-xa[index[i]]) - \ (nav.x[index[0]]-nav.x[index[i]]) H[nv, index[0]] = 1.0 H[nv, index[i]] = -1.0 nv += 1 if nv > 0: R = np.eye(nv)*VAR_HOLDAMB # update states with constraints nav.x, nav.P, _ = kfupdate(nav.x, nav.P, H[0:nv, :], v[0:nv], R) return 0 def relpos(nav, obs, obsb): """ relative positioning for RTK-GNSS """ nf = nav.nf if gn.timediff(obs.t, obsb.t) != 0: return -1 rs, _, dts, svh = satposs(obs, nav) rsb, _, dtsb, svhb = satposs(obsb, nav) # non-differencial residual for base yr, er, elr = zdres(nav, obsb, rsb, dtsb, svhb, nav.rb, 0) ns, iu, ir = selsat(nav, obs, obsb, elr) y = np.zeros((ns*2, nf*2)) e = np.zeros((ns*2, 3)) if ns < 4: return -1 y[ns:, :] = yr[ir, :] e[ns:, :] = er[ir, :] # Kalman filter time propagation udstate(nav, obs, obsb, iu, ir) xa = np.zeros(nav.nx) xp = nav.x # non-differencial residual for rover yu, eu, el = zdres(nav, obs, rs, dts, svh, xp[0:3]) y[:ns, :] = yu[iu, :] e[:ns, :] = eu[iu, :] el = el[iu] sat = obs.sat[iu] nav.el[sat-1] = el # DD residual v, H, R = ddres(nav, xp, y, e, sat, el) Pp = nav.P # Kalman filter measurement update xp, Pp, _ = kfupdate(xp, Pp, H, v, R) # non-differencial residual for rover after measurement update yu, eu, _ = zdres(nav, obs, rs, dts, svh, xp[0:3]) y[:ns, :] = yu[iu, :] e[:ns, :] = eu[iu, :] # residual for float solution v, H, R = ddres(nav, xp, y, e, sat, el) if valpos(nav, v, R): nav.x = xp nav.P = Pp else: nav.smode = 0 nb, xa = resamb_lambda(nav, sat) nav.smode = 5 # float if nb > 0: yu, eu, _ = zdres(nav, obs, rs, dts, svh, xa[0:3]) y[:ns, :] = yu[iu, :] e[:ns, :] = eu[iu, :] v, H, R = ddres(nav, xa, y, e, sat, el) if valpos(nav, v, R): if nav.armode == 3: holdamb(nav, xa) nav.smode = 4 # fix nav.t = obs.t return 0 convert this python code to matlab. write simple as possible
6ae9a327b469ef721e35e4179f61d0ba
{ "intermediate": 0.27358514070510864, "beginner": 0.49894627928733826, "expert": 0.2274685949087143 }
18,035
def resamb_lambda(nav, sat): """ resolve integer ambiguity using LAMBDA method """ nx = nav.nx na = nav.na xa = np.zeros(na) ix = ddidx(nav, sat) nb = len(ix) if nb <= 0: print("no valid DD") return -1, -1 # y=D*xc, Qb=D*Qc*D', Qab=Qac*D' y = nav.x[ix[:, 0]]-nav.x[ix[:, 1]] DP = nav.P[ix[:, 0], na:nx]-nav.P[ix[:, 1], na:nx] Qb = DP[:, ix[:, 0]-na]-DP[:, ix[:, 1]-na] Qab = nav.P[0:na, ix[:, 0]]-nav.P[0:na, ix[:, 1]] # MLAMBDA ILS b, s = mlambda(y, Qb) if s[0] <= 0.0 or s[1]/s[0] >= nav.thresar[0]: nav.xa = nav.x[0:na].copy() nav.Pa = nav.P[0:na, 0:na].copy() bias = b[:, 0] y -= b[:, 0] K = Qab@np.linalg.inv(Qb) nav.xa -= K@y nav.Pa -= K@Qab.T # restore SD ambiguity xa = restamb(nav, bias, nb) else: nb = 0 return nb, xa def initx(nav, x0, v0, i): """ initialize x and P for index i """ nav.x[i] = x0 for j in range(nav.nx): nav.P[j, i] = nav.P[i, j] = v0 if i == j else 0 def kfupdate(x, P, H, v, R): """ kalmanf filter measurement update """ PHt = P@H.T S = H@PHt+R K = PHt@np.linalg.inv(S) x += K@v P = P - K@H@P return x, P, S convert this python code to matlab
df36cf8f7fd6d75e30fa31fcbb30d513
{ "intermediate": 0.4436250627040863, "beginner": 0.24616596102714539, "expert": 0.3102090060710907 }
18,036
Generate a good looking and modern html template for "google maps scraping" chrome extension
5baffb2d2cd07fb736079133d583e4ed
{ "intermediate": 0.3832271099090576, "beginner": 0.22757282853126526, "expert": 0.3892000913619995 }
18,037
I have this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it doesn't give me signals to sell
afc86bfe3a47a8f7ca3c327c1d9d68fd
{ "intermediate": 0.4599379003047943, "beginner": 0.34426170587539673, "expert": 0.19580042362213135 }
18,038
Generate a good looking and modern html landing page for “google maps scraping” chrome extension
de92ec815044cf819c6e19645750d701
{ "intermediate": 0.3259631097316742, "beginner": 0.24711903929710388, "expert": 0.4269178509712219 }
18,039
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and (sell_qty / buy_qty) > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and (buy_qty / sell_qty) > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only signal to buy, and because of this problem I was need to take a loss , give me right code which will give me signals to buy sell or empty , and don't copy my code !!!
03d455a48152219c7cb429a48c3143ad
{ "intermediate": 0.4249280095100403, "beginner": 0.23336215317249298, "expert": 0.34170979261398315 }
18,040
#include<iostream> #include<fstream> #include<vector> #include<sstream> #include<cstring> using namespace std; int loc(vector<string> v, string word) { for (int i = 0; i<v.size();i++) { if (v[i]==word) { return i; } } return -1; } int main(int count, char** args) { if (!strcmp("A",args[1])) { ifstream myfile; myfile.open(args[3]); string line; float gate_delay[5]; while(getline(myfile,line)){ stringstream ss(line); string word; ss>>word; if (word == "AND2") { ss>>word; gate_delay[0] = stof(word); } else if (word == "NAND2") { ss>>word; gate_delay[1] = stof(word); } else if (word == "OR2") { ss>>word; gate_delay[2] = stof(word); } else if (word == "NOR2") { ss>>word; gate_delay[3] = stof(word); } else if (word == "INV") { ss>>word; gate_delay[4] = stof(word); } }; myfile.close(); vector<string> signame; vector<float> sigtime; vector<int> sigtype; myfile.open(args[2]); while(getline(myfile,line)) { stringstream ss(line); string word; ss>>word; if (word=="PRIMARY_INPUTS") { while(ss>>word) { signame.push_back(word); sigtype.push_back(0); sigtime.push_back(0); } } else if (word=="PRIMARY_OUTPUTS") { while(ss>>word) { signame.push_back(word); sigtype.push_back(-2); sigtime.push_back(0); } } else if (word=="INTERNAL_SIGNALS") { while(ss>>word) { signame.push_back(word); sigtype.push_back(-1); sigtime.push_back(0); } } } myfile.close(); bool done = false; while(!done) { myfile.open(args[2]); while(getline(myfile,line)) { stringstream ss(line); string word; string s1,s2,s3; int n1,n2,n3; ss>>word; if (word=="AND2") { ss>>s1; ss>>s2; ss>>s3; n1 = loc(signame,s1); n2 = loc(signame,s2); n3 = loc(signame,s3); if (sigtype[n1] >= 0 && sigtype[n2] >= 0 && sigtype[n3] < 0) { sigtime[n3] = max(sigtime[n1],sigtime[n2]) + gate_delay[0]; sigtype[n3] = -sigtype[n3]; } } if (word=="NAND2") { ss>>s1; ss>>s2; ss>>s3; n1 = loc(signame,s1); n2 = loc(signame,s2); n3 = loc(signame,s3); if (sigtype[n1] >= 0 && sigtype[n2] >= 0 && sigtype[n3] < 0) { sigtime[n3] = max(sigtime[n1],sigtime[n2]) + gate_delay[1]; sigtype[n3] = -sigtype[n3]; } } if (word=="OR2") { ss>>s1; ss>>s2; ss>>s3; n1 = loc(signame,s1); n2 = loc(signame,s2); n3 = loc(signame,s3); if (sigtype[n1] >= 0 && sigtype[n2] >= 0 && sigtype[n3] < 0) { sigtime[n3] = max(sigtime[n1],sigtime[n2]) + gate_delay[2]; sigtype[n3] = -sigtype[n3]; } } if (word=="NOR2") { ss>>s1; ss>>s2; ss>>s3; n1 = loc(signame,s1); n2 = loc(signame,s2); n3 = loc(signame,s3); if (sigtype[n1] >= 0 && sigtype[n2] >= 0 && sigtype[n3] < 0) { sigtime[n3] = max(sigtime[n1],sigtime[n2]) + gate_delay[3]; sigtype[n3] = -sigtype[n3]; } } if (word=="INV") { ss>>s1; ss>>s2; n1 = loc(signame,s1); n2 = loc(signame,s2); if (sigtype[n1] >= 0 && sigtype[n2] < 0) { sigtime[n2] = (sigtime[n1]) + gate_delay[4]; sigtype[n2] = -sigtype[n2]; } } } myfile.close(); done = true; for (int i = 0; i < signame.size(); i++) { if (sigtype[i]<0) { done = false; break; } } } ofstream outputter; outputter.open("output_delays.txt",ios::trunc); for (int i = 0; i < signame.size(); i++) { if (sigtype[i]==2) { outputter<<signame[i]<<" "<<sigtime[i]<<endl; } } outputter.close(); } else if (!strcmp("B",args[1])) { vector<string> gates = {"AND2","NAND2","OR2","NOR2","INV"}; ifstream myfile; myfile.open(args[3]); string line; float gate_delay[5]; while(getline(myfile,line)){ stringstream ss(line); string word; ss>>word; if (word == "AND2") { ss>>word; gate_delay[0] = stof(word); } else if (word == "NAND2") { ss>>word; gate_delay[1] = stof(word); } else if (word == "OR2") { ss>>word; gate_delay[2] = stof(word); } else if (word == "NOR2") { ss>>word; gate_delay[3] = stof(word); } else if (word == "INV") { ss>>word; gate_delay[4] = stof(word); } }; myfile.close(); vector<string> signame; vector<string> inputs; vector<float> sigtime; vector<int> sigtype; myfile.open(args[2]); while(getline(myfile,line)) { stringstream ss(line); string word; ss>>word; if (word=="PRIMARY_INPUTS") { while(ss>>word) { signame.push_back(word); inputs.push_back(word); sigtype.push_back(1); sigtime.push_back(0); } } else if (word=="PRIMARY_OUTPUTS") { while(ss>>word) { signame.push_back(word); sigtype.push_back(0); sigtime.push_back(0); } } else if (word=="INTERNAL_SIGNALS") { while(ss>>word) { signame.push_back(word); sigtype.push_back(1); sigtime.push_back(0); } } } myfile.close(); myfile.open(args[4]); float m; while(getline(myfile,line)) { stringstream ss(line); string word; string s1; while(ss>>word) { int n1 = loc(signame,word); if (n1>=0) { ss>>s1; sigtime[n1] = stof(s1); m = max(m,stof(s1)); } } } for(int i = 0; i < sigtime.size(); i++) { if (sigtime[i] == 0) { sigtime[i] = m; } } myfile.close(); bool done = false; while(!done) { myfile.open(args[2]); while(getline(myfile,line)) { stringstream ss(line); string word; string s1,s2,s3; int n1,n2,n3; ss>>word; if (word=="AND2" || word=="NAND2" || word == "OR2" || word == "NOR2") { ss>>s1; ss>>s2; ss>>s3; n1 = loc(signame,s1); n2 = loc(signame,s2); n3 = loc(signame,s3); sigtime[n1] = min(sigtime[n1],sigtime[n3]-gate_delay[loc(gates,word)]); sigtime[n2] = min(sigtime[n2],sigtime[n3]-gate_delay[loc(gates,word)]); sigtype[n1]+=sigtype[n3]; sigtype[n2]+=sigtype[n3]; } else if (word == "INV") { ss>>s1; ss>>s2; n1 = loc(signame,s1); n2 = loc(signame,s2); sigtime[n1] = min(sigtime[n1],sigtime[n2]-gate_delay[loc(gates,word)]); sigtype[n1]+=sigtype[n2]; } } for(int i = 0; i < signame.size(); i++) { if (sigtype[i]==1) { sigtype[i] = 0; } if (sigtype[i] > 1) { sigtype[i] = 1; sigtime[i] = m; } } myfile.close(); done = true; for (int i = 0; i < signame.size(); i++) { if (sigtype[i]!=0) { done = false; break; } } } ofstream outputter; outputter.open("input_delays.txt", ios::trunc); for (string word : inputs) { outputter<<word<<" "<<sigtime[loc(signame,word)]<<endl; } outputter.close(); } } change this code in python.
47b693094b8aa7801a7b9518dc203aeb
{ "intermediate": 0.3010767698287964, "beginner": 0.47371307015419006, "expert": 0.22521013021469116 }
18,041
Im making a program for linux in go that needs to be auto updated, its just a binary that occasionally needs an update and i was wondering if i should make the auto updater a seperate file in shell or something as i dont want multiple binaries nor know how id do it in the same binary
3c5d67026a68413a2a51c061951d3fe1
{ "intermediate": 0.44035136699676514, "beginner": 0.28229135274887085, "expert": 0.2773573398590088 }
18,042
from openpyxl import load_workbook import pandas as pd import datetime # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df,date, column): date = pd.to_datetime(date) year = date.year month = date.month day = date.day five_years_ago = datetime.datetime.now() - pd.DateOffset(years=5) history_dates = df[(df.index.month == month) & (df.index.day == day) & (df.index.year <= year) & (df.index > five_years_ago)].index history_values = df[df.index.isin(history_dates)][column] target_value = df.loc[date, column] mean_target_value = df.loc[date:date - pd.DateOffset(years=4), column].mean() min_value = history_values.min() max_value = history_values.max() percentile= (target_value - min_value) / (max_value - min_value) * 100 return percentile,history_dates percentile =calculate_percentile(df,'2023-08-19','螺纹钢') print(percentile) print(history_dates) percentile =calculate_percentile(df,'2023-08-(0.0, DatetimeIndex(['2020-08-19', '2021-08-19', '2022-08-19', '2023-08-19'], dtype='datetime64[ns]', name=NaT, freq=None)) --------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_8864/724220345.py in <module> 44 percentile =calculate_percentile(df,'2023-08-19','螺纹钢') 45 print(percentile) ---> 46 print(history_dates) NameError: name 'history_dates' is not defined
627e45d09b5a13faa478511ea459aa34
{ "intermediate": 0.3986034095287323, "beginner": 0.4103924632072449, "expert": 0.19100405275821686 }
18,043
from openpyxl import load_workbook import pandas as pd import datetime # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df,date, column): date = pd.to_datetime(date) year = date.year month = date.month day = date.day five_years_ago = datetime.datetime.now() - pd.DateOffset(years=5) history_dates = df[(df.index.month == month) & (df.index.day == day) & (df.index.year <= year) & (df.index > five_years_ago)].index history_values = df[df.index.isin(history_dates)][column] target_value = df.loc[date, column] mean_target_value = df.loc[date:date - pd.DateOffset(years=4), column].mean() min_value = history_values.min() max_value = history_values.max() percentile= (target_value - min_value) / (max_value - min_value) * 100 return percentile,history_values percentile, history_values =calculate_percentile(df,'2023-08-19','螺纹钢') print(percentile) print(history_values) 我写了一段代码 但他好像跟我的要求不匹配 请帮我修改一下。我想让mean_target_value 代表date所在行,及df向上数1、2、3、4行的对应值的均值。
418e479317caea88c0a72ef6bf849c79
{ "intermediate": 0.32341375946998596, "beginner": 0.4307413399219513, "expert": 0.24584487080574036 }
18,044
make gui window bigger in python
a9f55e1d71f9a35fec02197e61521fba
{ "intermediate": 0.36242932081222534, "beginner": 0.2580845355987549, "expert": 0.3794861435890198 }
18,045
I have this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty: signal.append('sell') elif buy_qty > sell_qty: signal.append('buy') else: signal.append('') return signal Can you add in my strategy those params: If buy_qty is more than 10% than sell_qty signal.append('buy') elif sell_qty is more than 10% than buy_qty signal.append('sell') else: signal.append('')
04282a904467d6527de4e81ca91cd99e
{ "intermediate": 0.3902249336242676, "beginner": 0.19710585474967957, "expert": 0.41266918182373047 }
18,046
Create dropdown menu using reactt
1eaab4938c5e7beb0e659a3f2b6a0164
{ "intermediate": 0.4128503203392029, "beginner": 0.21975427865982056, "expert": 0.36739540100097656 }
18,047
how to setup two smart card reader at the same time in python
b59c8d04716d541bc9307c0ca9720437
{ "intermediate": 0.23389074206352234, "beginner": 0.18787935376167297, "expert": 0.5782299041748047 }
18,048
how c# check duplicate unity event Action listeners
ba0aa3dbbf70eb8dfaf273a78e5295c0
{ "intermediate": 0.5365151166915894, "beginner": 0.21523892879486084, "expert": 0.24824590981006622 }
18,049
where is cookies.pkl file
33320843a82d209aad203b352b2b8b0a
{ "intermediate": 0.3465932607650757, "beginner": 0.37897172570228577, "expert": 0.27443498373031616 }
18,050
from openpyxl import load_workbook import pandas as pd import datetime # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean() five_years_ago = date - pd.DateOffset(years=5) date_range = pd.date_range(start=five_years_ago, end=date, closed='left') history_means = df[df.index.isin(date_range)][column].rolling(window=5).mean() min_value = history_means.min() max_value = history_means.max() percentile = (target_value_mean - min_value) / (max_value - min_value) * 100 return percentile, history_means percentile, history_values =calculate_percentile(df,'2023-08-19','螺纹钢') print(percentile) print(history_values) 这个代码不是很符合我的需求 我想请你帮我改一改
f1757c6b45341b07028a7ac588393609
{ "intermediate": 0.3187708258628845, "beginner": 0.5555264949798584, "expert": 0.1257026642560959 }
18,051
from openpyxl import load_workbook import pandas as pd import datetime # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean() five_years_ago = date - pd.DateOffset(years=4) date_range = pd.date_range(start=five_years_ago, end=date, closed='left') history_values = df.loc[date_range, column] # Calculate smoothed values history_means = history_values.rolling(window=5).mean() # Filter out the same month and day values history_values = df[(df.index.month.isin(date_range.month)) & (df.index.day.isin(date_range.day))][column] target_smoothed_value = target_value_mean max_smoothed_value = history_means.max() min_smoothed_value = history_means.min() percentile = (target_smoothed_value - min_smoothed_value) / (max_smoothed_value - min_smoothed_value) * 100 return percentile, history_means percentile, history_values =calculate_percentile(df,'2023-08-19','螺纹钢') print(percentile) print(history_values) 这是我的代码,但返回错误,请帮我修改 TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_1100/614213639.py in <module> 51 return percentile, history_means 52 ---> 53 percentile, history_values =calculate_percentile(df,'2023-08-19','螺纹钢') 54 print(percentile) 55 print(history_values) ~\AppData\Local\Temp/ipykernel_1100/614213639.py in calculate_percentile(df, date, column) 35 36 five_years_ago = date - pd.DateOffset(years=4) ---> 37 date_range = pd.date_range(start=five_years_ago, end=date, closed='left') 38 history_values = df.loc[date_range, column] 39 ~\anaconda3\lib\site-packages\pandas\core\indexes\datetimes.py in date_range(start, end, periods, freq, tz, normalize, name, inclusive, unit, **kwargs) 943 freq = "D" 944 --> 945 dtarr = DatetimeArray._generate_range( 946 start=start, 947 end=end, TypeError: _generate_range() got an unexpected keyword argument 'closed'
8be4e1042373a07d6cc187d87688a29a
{ "intermediate": 0.46812787652015686, "beginner": 0.32560455799102783, "expert": 0.2062675505876541 }
18,052
ForEach-Object -Parallel如何使用?
98f3ba119c47afae3d5e12a136df3e74
{ "intermediate": 0.30281272530555725, "beginner": 0.284791499376297, "expert": 0.4123958349227905 }
18,053
from openpyxl import load_workbook import pandas as pd import datetime # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean() five_years_ago = date - pd.DateOffset(years=4) date_range = pd.date_range(start=five_years_ago, end=date) date_range = pd.to_datetime(pd.concat([pd.Series([five_years_ago]), date_range, pd.Series([date])])) history_values = df.loc[date_range, column] # Calculate smoothed values history_means = history_values.rolling(window=5).mean() # Filter out the same month and day values history_values = df[(df.index.month.isin(date_range.month)) & (df.index.day.isin(date_range.day))][column] target_smoothed_value = target_value_mean max_smoothed_value = history_means.max() min_smoothed_value = history_means.min() percentile = (target_smoothed_value - min_smoothed_value) / (max_smoothed_value - min_smoothed_value) * 100 return percentile, history_means percentile, history_values =calculate_percentile(df,'2023-08-19','螺纹钢') print(percentile) print(history_values) 我的代码返回了这个错误信息,请你看下问题在哪儿 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_1100/1808308807.py in <module> 52 return percentile, history_means 53 ---> 54 percentile, history_values =calculate_percentile(df,'2023-08-19','螺纹钢') 55 print(percentile) 56 print(history_values) ~\AppData\Local\Temp/ipykernel_1100/1808308807.py in calculate_percentile(df, date, column) 36 five_years_ago = date - pd.DateOffset(years=4) 37 date_range = pd.date_range(start=five_years_ago, end=date) ---> 38 date_range = pd.to_datetime(pd.concat([pd.Series([five_years_ago]), date_range, pd.Series([date])])) 39 history_values = df.loc[date_range, column] 40 ~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy) 370 copy = False 371 --> 372 op = _Concatenator( 373 objs, 374 axis=axis, ~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in __init__(self, objs, axis, join, keys, levels, names, ignore_index, verify_integrity, copy, sort) 460 "only Series and DataFrame objs are valid" 461 ) --> 462 raise TypeError(msg) 463 464 ndims.add(obj.ndim) TypeError: cannot concatenate object of type '<class 'pandas.core.indexes.datetimes.DatetimeIndex'>'; only Series and DataFrame objs are valid
2666b27d1defb90e2332c2201f2031ff
{ "intermediate": 0.4194113612174988, "beginner": 0.3160271942615509, "expert": 0.2645614743232727 }
18,054
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if buy_qty > sell_qty and (1 + threshold): signal.append('buy') elif sell_qty > buy_qty and (1 + threshold): signal.append('sell') else: signal.append('') return signal But it giving me only buy signal, how you cant understand that I need coed whcih will give me signals to buy and sell or empty
183018f0a639d542b2a14ec1e41e3b2d
{ "intermediate": 0.469550758600235, "beginner": 0.28180965781211853, "expert": 0.24863958358764648 }
18,055
I have a class A and class B. A has List<B> Items in it and I want use Items.AddRange() input of AddRange is a list of string that can use to new B. how to do it in dotnet
f33f26726140de3f867aed302e95f199
{ "intermediate": 0.45464006066322327, "beginner": 0.3179045021533966, "expert": 0.22745545208454132 }
18,056
const publish = () => { if (!isSubscribed) return; if (!cameras[pair]) { cameras[pair] = 0; } const zoomedTickSize = priceStep * aggregation; const startMicroPrice = cameras[pair] + rowsCount / 2 * zoomedTickSize - zoomedTickSize; const centerCupPosition = parseInt((Math.ceil(bestAskPrice / zoomedTickSize) * zoomedTickSize).toFixed(0)); const rows: {[key: number]: CupItem} = {}; const timeModifier = parseInt((publisherTimeoutInMs / 40).toFixed(0)); const diffModifier = Math.max( 2, parseInt(((centerCupPosition - cameras[pair] / zoomedTickSize) / rowsCount).toFixed(0)) ); if (centerCupPosition !== cameras[pair] && cameras[pair] !== 0 && !cameraIsBlocked) { cameras[pair] = cameras[pair] > centerCupPosition ? Math.max(centerCupPosition, cameras[pair] - zoomedTickSize * timeModifier * diffModifier) : Math.min(centerCupPosition, cameras[pair] + zoomedTickSize * timeModifier * diffModifier); } for (let index = 0; index <= rowsCount; index++) { const microPrice = startMicroPrice - index * zoomedTickSize; if (microPrice < 0) continue; rows[microPrice] = cup[microPrice] || {}; maxVolume = Math.max(maxVolume, rows[microPrice]?.bid || 0, rows[microPrice]?.ask || 0); } port?.postMessage({type: “set_camera”, value: cameras[pair]}); postMessage({ type: “update_cup”, cup: rows, camera: cameras[pair], aggregation, bestBidPrice, bestAskPrice, pricePrecision, priceStep, quantityPrecision, rowsCount, maxVolume: volumeIsFixed ? fixedMaxVolume : maxVolume / Math.pow(10, quantityPrecision), }); }; const publisherStart = () => { if (publisherIntervalId) { clearInterval(publisherIntervalId); } publisherIntervalId = setInterval(publish, publisherTimeoutInMs); }; const publisherStop = () => { if (publisherIntervalId) { clearInterval(publisherIntervalId); } }; есть функция publish. Она подготавливает и отправляет данные в сам стакан. Там есть расчет maxVolume. Цена и кол-во из CupItem. максимальный объем определять путем перемножения цены на кол-во. Напиши код, что нужно изменить или что добавить
9928bdb9d2dbe72ea4c1ea8e5cdc37a4
{ "intermediate": 0.33061662316322327, "beginner": 0.5115088820457458, "expert": 0.1578744798898697 }
18,057
Can you please check if the code I have written has any error and if it can still be optimised: Private Sub Worksheet_Change(ByVal Target As Range) Dim rngI As Range Dim rngG As Range Dim cell As Range Dim innercell As Range If Target.CountLarge > 1 Then Exit Sub If Not Intersect(Target, Range("I6:I505")) Is Nothing Then If IsDate(Target.Value) Then If Target.Offset(0, -7).Value = "Service" Then MsgBox "Thank you for entering Service Date Completed. Please proceed to enter Service Schedule as number of days.", vbInformation, "DATE" ActiveSheet.Range("G" & Target.Row).Select 'Exit Sub End If End If End If If Target.CountLarge > 1 Then Exit Sub If Not Intersect(Target, Range("G6:G505")) Is Nothing Then If Not doubleClickFlag Then ' DoublClickFlag previously set to True to prevent Change Reaction If Target.Value <> "" And Target.Offset(0, 2).Value = "" Then MsgBox "Date Completed not present", vbCritical, "DATE" Application.EnableEvents = False Target.Value = "" Application.EnableEvents = True End If End If Else MsgBox "Please change the Issue description ( column B ) as required.", vbInformation, "ISSUE" ActiveSheet.Range("B" & Target.Row).Select Else If Target.Value <> "" And Target.Offset(0, -5).Value <> "Service" Then MsgBox "Task is not a current Service", vbCritical, "TASK TYPE" Application.EnableEvents = False Target.Value = "" Application.EnableEvents = True End If End If Else If Target.Value <> "" And Target.Offset(0, -5).Value = "Service" And Target.Offset(0, 2).Value <> "" Then MsgBox "A New Service row will now be created", vbInformation, "NEW SERVICE" Target.Offset(0, -5).Value = "Serviced" Target.Offset(0, 1).Value = "" Dim newRow As Long newRow = Cells(Rows.Count, "B").End(xlUp).Row + 1 ActiveSheet.Range("B" & newRow).Value = "Service" ActiveSheet.Range("C" & newRow).Value = Target.Offset(0, 2).Value ActiveSheet.Range("F" & newRow).Value = Target.Offset(0, -1).Value ActiveSheet.Range("J" & newRow).Value = Target.Offset(0, 3).Value ActiveSheet.Range("L" & newRow).Value = Target.Offset(0, 5).Value ActiveSheet.Range("H" & newRow).Value = Target.Offset(0, 2).Value + Target.Value End If End If If Target.Column = 5 Then ColumnList Target End If doubleClickFlag = False End Sub
83d8ae3f2f55371448fe59eb4c64e5ac
{ "intermediate": 0.32538095116615295, "beginner": 0.4190847873687744, "expert": 0.25553426146507263 }
18,058
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) spread_percent = ((sell_price - buy_price) / buy_price) * 100 if buy_qty > sell_qty and spread_percent >= 10: signal.append('buy') elif sell_qty > buy_qty and spread_percent <= -10: signal.append('sell') else: signal.append('') return signal But it doesn't give me any signals
13c3498742af4a0e06efcbaeaaa70da5
{ "intermediate": 0.45693156123161316, "beginner": 0.3412295877933502, "expert": 0.20183880627155304 }
18,059
from openpyxl import load_workbook import pandas as pd import datetime # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 11, 12, 13, 14, 15] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # 构建DataFrame headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean() five_years_ago = date - pd.DateOffset(years=3) date_range = pd.date_range(start=five_years_ago, end=date) history_values = df.loc[date_range, column] # Calculate smoothed values history_means = history_values.rolling(window=5).mean() # Filter out the same month and day values history_values = df[(df.index.month.isin(date_range.month)) & (df.index.day.isin(date_range.day))][column] target_smoothed_value = target_value_mean max_smoothed_value = history_means.max() min_smoothed_value = history_means.min() percentile = (target_smoothed_value - min_smoothed_value) / (max_smoothed_value - min_smoothed_value) * 100 return percentile # 创建一个空的列表,用于存储每一天的percentile值 percentiles = [] # 设置起始日期 start_date = pd.to_datetime('2023-01-01') # 循环遍历DataFrame的每一行 for index, row in df.iterrows(): # 检查是否满足起始日期的条件,如果不满足,则跳过计算 if index < start_date: percentiles.append(None) continue # 获取当前行的日期和列名 date = index column = '螺纹钢' # 要计算percentile的列名,请根据实际情况修改 # 调用calculate_percentile函数计算percentile值 percentile = calculate_percentile(df, date, column) # 将percentile值添加到列表中 percentiles.append(percentile) # 将percentiles列表添加为新的一列到DataFrame中 df['Percentile'] = percentiles 现在我要在df增加一列df['Percentile YOY'],对每一个date,'Percentile YOY'就是这个date上的Percentile列结果减去上年同期的Percentile列结果。这个代码怎么写。
71d2c335776a5d430f6f7253be31f3b5
{ "intermediate": 0.37348058819770813, "beginner": 0.35557878017425537, "expert": 0.2709405720233917 }
18,060
import os import json import requests import openpyxl from concurrent.futures import ThreadPoolExecutor import traceback # Function to send push notifications def send_push_notification(group, payload): # Create an xlsx file to store the results wb = openpyxl.Workbook() sheet = wb.active sheet['A1'] = 'Token' sheet['B1'] = 'Success' try: # Update the payload with the current token group payload['registration_ids'] = group # Send the request and get the response response = requests.post( 'https://fcm.googleapis.com/fcm/send', headers={'Authorization': 'key=A', 'Content-Type': 'application/json'}, data=json.dumps(payload) ) result = response.json() # Write the result to the xlsx file for i, token in enumerate(group): success = result['results'][i].get('success', 0) sheet.cell(row=i+2, column=1).value = token sheet.cell(row=i+2, column=2).value = success except Exception as e: print(f"Error in thread: {traceback.format_exc()}") finally: # Save the xlsx file wb.save('result.xlsx') # Function to read tokens from a file def read_tokens_from_file(file_path): with open(file_path, 'r') as f: tokens = f.read().split(',') return tokens def send_notifications_concurrently(tokens, payload): # Split tokens into groups of 500 token_groups = [tokens[i:i+500] for i in range(0, len(tokens), 500)] # Create a pool of workers with ThreadPoolExecutor(max_workers=4) as executor: executor.map(send_push_notification, token_groups, [payload]*len(token_groups)) # Process Android tokens android_files = [f for f in os.listdir('.') if f.startswith('android') and f.endswith('.txt')] for file in android_files: tokens = read_tokens_from_file(file) payload = { "notification": { "title": "ثانیه‌های یک میلیونی در جشنواره پلانو", "body": "تماشای رایگان «توطئه آمیز» با جایزه", "image": "https://pelano.net/uploads/push/CinemaFestival/01.jpg", "icon": "https://pelano.net/uploads/Pelano_Push_Logo.png", "sound": "default", }, "data": { "url": "https://pelano.net/Campaign?PF=CB", "image": "https://pelano.net/uploads/push/CinemaFestival/01.jpg" }, "priority": "high", "content_available": True, "mutable_content": True, } send_notifications_concurrently(tokens, payload) # Process web tokens web_files = [f for f in os.listdir('.') if f.startswith('web') and f.endswith('.txt')] for file in web_files: tokens = read_tokens_from_file(file) payload = { "notification": { "title": "ثانیه‌های یک میلیونی در جشنواره پلانو", "body": "تماشای رایگان «توطئه آمیز» با جایزه", "image": "https://pelano.net/uploads/push/CinemaFestival/02.jpg", "icon": "https://pelano.net/uploads/Pelano_Push_Logo.png", "sound": "default", "click_action": "https://pelano.net/Campaign", }, "priority": "high", "content_available": True, "mutable_content": True, } send_notifications_concurrently(tokens, payload) in the top code i want to print response please give me the full edited code
3ba855b69a867915aca82410b34c1637
{ "intermediate": 0.45483699440956116, "beginner": 0.3547854721546173, "expert": 0.19037751853466034 }
18,061
How can I write a VBA to make sure that when in column I, when I press enter on my keyboard, the selection does not move down to the next cell but to the next cell right
1ee415225f000f97fe09c637692c53e5
{ "intermediate": 0.2846216559410095, "beginner": 0.08986559510231018, "expert": 0.6255127191543579 }
18,062
write a code in python for the below request: "take the data.xlsx in drive D. It is a matrix that contains data in 47 columns and 11 rows. the first row is the header that includes the name of columns. Estimate the values for 12th row using a machine learning model. Save the new file with estimated cells in drive D
79e99db4ddca9fc71710c737fa93519b
{ "intermediate": 0.29743072390556335, "beginner": 0.1085435152053833, "expert": 0.5940257906913757 }
18,063
i want the code code below only read the secoond line and only value of success in each file : import pandas as pd import glob # Define the path where the Excel files are located path = r'/root/SendPush/*.xlsx' # Create an empty list to store the sum of "Success" column in each file success_sum_list = [] # Loop through each Excel file in the directory for file in glob.glob(path): # Read the Excel file into a Pandas DataFrame df = pd.read_excel(file) # Sum the values in the "Success" column success_sum = df['Success'].sum() # Append the sum to the list success_sum_list.append(success_sum) # Print the sum of "Success" column in each file for i, sum in enumerate(success_sum_list): print(f'Sum of "Success" column in file {i+1}: {sum}') sum = 0 for item in success_sum_list: sum += item print(f'Sum of Success : {sum} ')
2247f3499b519f1b97ef49fa6dad4a75
{ "intermediate": 0.4358587861061096, "beginner": 0.2626824975013733, "expert": 0.3014586567878723 }
18,064
hello
fa48447364869362ff317c171f045143
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
18,065
How to remove duplicates in excel
4e2801ae63ce6e3c8ff64723c0894754
{ "intermediate": 0.3129950165748596, "beginner": 0.32547497749328613, "expert": 0.36152997612953186 }
18,066
You will see the string S, which is a mathematical expression with mixed alphabets. Find the formula and output the answer. Alphabetic characters may also be mixed in between numbers. Example: In the case of 12+56, It may look like abc1Def2ghIjK+L5mOPQ6rS. So the answer is 38. In the case of 2**5, It may look like dahoui2fne*fneofewnoi*5huz. So the answer is 32.(The decimal point in the final answer is truncated.) In the case of 3/2, It may look like uehuw3fjeoi/nohGIY2fehudIYGdwj. So the answe is 1.(not 1.5.) Input Line :1 A String S for the mathematical expression with mixed alphabets. Output Line 1: Formula answer Constraints 5 <= S.length <= 100 S consists of the upper and lower case letters of the alphabet, as well as the numbers 0 through 9, and one of the following operators: '+', '-', '*', '/', '%', and '**'. The result of division allows for a decimal point, but the decimal point in the final calculation result is truncated. Example Input A1B+C1 Output 2 ..... Please solve with C# code.
955c579500366fda1eb1e5c05ee9740b
{ "intermediate": 0.3886665999889374, "beginner": 0.2975831925868988, "expert": 0.31375014781951904 }
18,067
Today is Pi Day (March 14th), so let's celebrate it by approximating pi's value using the simplest maths operations ! Although it has a slow converging rate, one of the oldest way to do such approximation is the Madhava–Leibniz series: pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... Given an integer n, compute an approximation value of pi using the first n terms of the Madhava-Leibniz series. The computed pi value should be rounded to 5 decimal places. Example: n = 1 ==> pi/4 = 1 ==> The expected output is 4.00000 n = 3 ==> pi/4 = 1 - 1/3 + 1/5 ==> The expected output is 3.46667 Input Line 1: Integer n Output The approximated value of pi, rounded to 5 decimal places. Constraints 0 < n < 10^7 Example Input 1 Output 4.00000 ...Please solve with C# code
4d7551999632a9a4cdb7fcddf976089e
{ "intermediate": 0.3809644281864166, "beginner": 0.3171367645263672, "expert": 0.3018988072872162 }
18,068
I used your code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) spread_percent = ((sell_price - buy_price) / buy_price) * 100 if buy_qty > sell_qty and spread_percent > threshold: signal.append('buy') elif sell_qty > buy_qty and spread_percent < -threshold: signal.append('sell') else: signal.append('') return signal But it doesn't give me signals to buy and sell , I think problem in if buy_qty > sell_qty and spread_percent > threshold: signal.append('buy') elif sell_qty > buy_qty and spread_percent < -threshold: signal.append('sell') else: signal.append('')
c1167a310a9b770f067fc93e70ceb5af
{ "intermediate": 0.3997475802898407, "beginner": 0.2894064486026764, "expert": 0.31084591150283813 }
18,069
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = sum(float(bid[1]) for bid in bid_depth) sell_qty = sum(float(ask[1]) for ask in ask_depth) if sell_qty > buy_qty and sell_qty > (1 + threshold): signal.append('sell') elif buy_qty > sell_qty and buy_qty > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it giving me only signal to buy , I think the first problem is in else , the else is doesn't work, please give me code where else will work
240a9b7f269dc0486a414969f05cb9d9
{ "intermediate": 0.4782114624977112, "beginner": 0.2331416755914688, "expert": 0.2886469066143036 }
18,070
Human traffic stadium X stadium built a new stadium, each day many people visit it, write a query to display the records which have 3 or more consecutive rows and the amount of people more than 100(inclusive) using cte and joins
297b0ca5b5351605b5b0314786956f3b
{ "intermediate": 0.5044923424720764, "beginner": 0.2627319395542145, "expert": 0.23277565836906433 }
18,071
Human traffic stadium X stadium built a new stadium, each day many people visit it, write a query to display the records which have 3 or more consecutive rows and the amount of people more than 100(inclusive) using cte
b15dd036e72d3f2cd1b06e79ab09bf61
{ "intermediate": 0.502128005027771, "beginner": 0.2587488293647766, "expert": 0.23912313580513 }
18,072
<body> <button id="back" class="mdc-button" onclick="goBack()"> <span class="mdc-button__ripple"></span><i class="material-icons"> keyboard_return </i>&nbsp;Regrese<style>body{background:salmon}</style></button> <div id="header2" style="background-color:#4b7aa4; position:relative; height:67px; color:white;"> <div style="position:absolute;left:5px;top:5px;"> <object data="/images/category_index/earth.svg" type="image/svg+xml" width="60" height="60" class="img" style="z-index:20"> </object> </div> <div style="position:absolute;left:74px;top:18px;"> <a href="/esp/" style="font-size:140%;font-weight:bold;color:white;text-decoration:none">LanguageGuide.org</a></div> </div> <div class="subhead main es"> <div class="image"> <img src="images/birds-en.png" class="screen"> <img style="width: 110px;width: 110px;position: absolute; top: 150px; left: 20px;" src="images/pointing-man.svg"> </div> <div> <h1>Explore el mundo del vocabulario con 80 páginas con diversos temas. </h1> <div class="description">Simplemente apunte a una imagen con el cursor para escucharla pronunciada en voz alta y deletreada. </div> <ul> <li>Cambie la dificultad haciendo click en la configuración del icono de preferencias<i class="material-icons">settings</i>. Elija entre los niveles inicial, intermedio y avanzado. (Avanzado es el valor predeterminado) </li> <li>¿No está claro qué objeto es? Active las traducciones a través de las preferencias o presionando la tecla 't'. </li> <li>Asegúrese de probar los desafíos de escuchar y hablar, ahora con <a href="https://www.blogger.com/u/1/blogger.g?blogID=7092322379253305804#editor/target=post;postID=8758195529630410803;onPublishedMenu=allposts;onClosedMenu=allposts;postNum=0;src=postname">reconocimiento de voz</a>. </li> </ul> </div> </div> <div class="subhead" style="clear: both; height: 170px;"> <div id="fb-root" class=" fb_reset"><div style="position: absolute; top: -10000px; width: 0px; height: 0px;"><div></div></div></div> <script async="" defer="" crossorigin="anonymous" src="https://connect.facebook.net/es_LA/sdk.js#xfbml=1&amp;version=v5.0&amp;appId=203269926360183&amp;autoLogAppEvents=1"></script> <div class="fb-page fb_iframe_widget" data-href="https://www.facebook.com/languageguide.org/" data-tabs="timeline" data-width="300" data-height="70" data-small-header="false" data-adapt-container-width="true" data-hide-cover="true" data-show-facepile="true" fb-xfbml-state="rendered" fb-iframe-plugin-query="adapt_container_width=true&amp;app_id=203269926360183&amp;container_width=727&amp;height=70&amp;hide_cover=true&amp;href=https%3A%2F%2Fwww.facebook.com%2Flanguageguide.org%2F&amp;locale=es_LA&amp;sdk=joey&amp;show_facepile=true&amp;small_header=false&amp;tabs=timeline&amp;width=300"><span style="vertical-align: bottom; width: 300px; height: 130px;"><iframe name="f3effed28a98184" width="300px" height="70px" data-testid="fb:page Facebook Social Plugin" title="fb:page Facebook Social Plugin" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" allow="encrypted-media" src="https://www.facebook.com/v5.0/plugins/page.php?adapt_container_width=true&amp;app_id=203269926360183&amp;channel=https%3A%2F%2Fstaticxx.facebook.com%2Fx%2Fconnect%2Fxd_arbiter%2F%3Fversion%3D46%23cb%3Df2d063660d31dbc%26domain%3Dwww.languageguide.org%26is_canvas%3Dfalse%26origin%3Dhttps%253A%252F%252Fwww.languageguide.org%252Ff7ad0ed51d042c%26relation%3Dparent.parent&amp;container_width=727&amp;height=70&amp;hide_cover=true&amp;href=https%3A%2F%2Fwww.facebook.com%2Flanguageguide.org%2F&amp;locale=es_LA&amp;sdk=joey&amp;show_facepile=true&amp;small_header=false&amp;tabs=timeline&amp;width=300" style="border: none; visibility: visible; width: 300px; height: 130px;" class=""></iframe></span></div> </div> <div style="margin: 8px; text-align: center"><a href="/page/donations.jsp?lang=es">Donaciones</a> | <a href="/page/contact.jsp?lang=es">Contacto</a> | </div> &lt; <div id="chrome-extension-boilerplate-react-vite-content-view-root"></div></body> Generating JSON Object from HTML Content Below are the necessary steps to generate a JSON object with information extracted from HTML content, including paragraphs, divs, sections, and other readable information-holding tags, following the given specifications: Objective: Create a JSON object that contains specific information from paragraphs, divs, sections, and other tags that hold readable information in an HTML document. Instructions: Open a new HTML file or use an existing one that contains the provided HTML content. Extraction of Information: Thoroughly analyze the provided HTML content and check the following points: Identify paragraphs, divs, sections, and other readable information-holding tags that need to meet the given criteria. Maintain the original structure and links within the content. JSON Object Generation: Use JavaScript to perform the following actions: Create an empty array to hold the extracted data. For each valid paragraph, div, section, or other relevant tag: Create a new object with the fields selector, original, and summary. Generate a specific selector for the current node and add it to the object. Capture the original content of the node (including all tags and links) and add it to the object. Generate a summary of the content while preserving sub-nodes, limiting it to 100 characters, and add it to the object. Add the object to the array. Incorporation in the Document: Convert the generated array of objects to a JSON string. Display the JSON string within the HTML document or perform any other desired action. Expected Outcome: When opening the HTML file in a web browser, the JSON object should be displayed or processed according to your desired approach. The object should have the structure { "selector": "...", "original": "...", "summary": "..." } for each target paragraph, div, section, or other readable information-holding tag that meets the specified criteria.
fe856fe35d241c6469e48621763ca6e2
{ "intermediate": 0.45972028374671936, "beginner": 0.3808985948562622, "expert": 0.15938116610050201 }
18,073
rows[microPrice]?.bid !== undefined && rows[microPrice]?.bid * maxVolume || 0; Object is possibly 'undefined'.ts(2532) (property) bid?: number | undefined как исправить
665c9d1ff4db69319861b9700b8afc54
{ "intermediate": 0.32961881160736084, "beginner": 0.41545942425727844, "expert": 0.2549217641353607 }
18,074
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.1 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 if sell_qty > (1 + threshold): signal.append('sell') elif buy_qty > (1 + threshold): signal.append('buy') else: signal.append('') return signal But it doesn't give me ''
9be5ce0d662c5d87061ece3535c6e44b
{ "intermediate": 0.3496032953262329, "beginner": 0.422478049993515, "expert": 0.2279186099767685 }
18,075
How do i load voice cover ai by downloaded model
64a44e3974f7ac3e710e87ce6c09bc6b
{ "intermediate": 0.27906715869903564, "beginner": 0.11392736434936523, "expert": 0.6070054769515991 }
18,076
this my alert widget. import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:investment_com/abstract_provider.dart'; import 'package:investment_com/core/Config/Converter.dart'; import 'package:investment_com/core/enums/enums.dart'; import 'package:investment_com/features/service_invoices/presentation/providers/add_delete_update_services_invoices_provider.dart'; import 'package:lottie/lottie.dart'; import 'package:provider/provider.dart'; class AnimatedPopUpDialog<T> extends StatefulWidget { const AnimatedPopUpDialog({ @required this.executeFunction, this.autoDismiss, this.duration, this.onOkTap, this.showRetryButton, this.lottieErrorAssetsName, this.lottieLoadingAssetsName, this.lottieSuccessAssetsName, }); final Function() onOkTap; final Function() executeFunction; final String lottieSuccessAssetsName; final String lottieErrorAssetsName; final String lottieLoadingAssetsName; final bool showRetryButton; final bool autoDismiss; final Duration duration; @override State<AnimatedPopUpDialog<T>> createState() => _AnimatedPopUpDialogState<T>(); } class _AnimatedPopUpDialogState<T> extends State<AnimatedPopUpDialog<T>> with TickerProviderStateMixin { AnimationController _controller; Animation<double> _iconScaleAnimation; Animation<double> _containerScaleAnimation; Animation<Offset> _yAnimation; AnimationController _textAnimation; AnimationController _retryRotateController; Animation<double> _retryRotateAnimation; AudioPlayer _player; Color circleColor = Converter.hexToColor("#2094cd").withOpacity(0.1); String _lottieName; bool _isFirstRun = true; bool isStateChanging = false; AbstractProvider _provider; @override void initState() { super.initState(); Future.delayed( Duration.zero, () => widget.executeFunction(), ); //? initialize the first state _lottieName = widget.lottieLoadingAssetsName; print(widget.lottieErrorAssetsName); //? initialize the Audio player and aninimation controllers _player = AudioPlayer(); _controller = AnimationController( vsync: this, duration: const Duration(seconds: 1), ); _textAnimation = AnimationController( vsync: this, duration: const Duration(seconds: 1), ); _retryRotateController = AnimationController( vsync: this, duration: const Duration(milliseconds: 500), ); _retryRotateAnimation = Tween<double>( begin: 0.1, end: 1.0, ).animate( CurvedAnimation( parent: _retryRotateController, curve: Curves.easeInOut, ), ); _yAnimation = Tween<Offset>( begin: const Offset(0, 0), end: const Offset(0, -0.23), ).animate( CurvedAnimation( parent: _controller, curve: Curves.easeInOut, ), ); _iconScaleAnimation = Tween<double>( begin: 4, end: 3, ).animate( CurvedAnimation( parent: _controller, curve: Curves.easeInOut, ), ); _containerScaleAnimation = Tween<double>( begin: 3.0, end: 0.4, ).animate( CurvedAnimation( parent: _controller, curve: Curves.bounceOut, ), ); //Start the animation _controller ..reset() ..forward().whenComplete(() { setState(() { circleColor = Colors.transparent; }); }); _textAnimation ..reset() ..forward(); } @override void didChangeDependencies() { //Excute the function super.didChangeDependencies(); } @override void dispose() { _controller.dispose(); _textAnimation.dispose(); _retryRotateController.dispose(); super.dispose(); } @override void deactivate() { _provider.reset(); super.deactivate(); } @override Widget build(BuildContext context) { return Consumer<T>( builder: (context, value, child) { _provider = value as AbstractProvider; updateUiState(); return WillPopScope( onWillPop: () async => _provider.dataState != DataState.loading, child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Container( height: 350, decoration: BoxDecoration( color: Colors.white, ), child: ConstrainedBox( constraints: BoxConstraints(minWidth: 100, minHeight: 100, maxWidth: 100), child: Stack( children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const SizedBox( height: 200, ), if (!isStateChanging && _provider.canPlayTheAnimation) Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '${tanslatedDataState(_provider.dataState)}', textAlign: TextAlign.center, style: const TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black, ), ).animate(controller: _textAnimation).fadeIn().slideX(), ], ) else SizedBox(height: 15), const SizedBox( height: 50, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_provider.dataState == DataState.loading && !isStateChanging) ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStatePropertyAll(Colors.red[400]), shadowColor: MaterialStatePropertyAll(Colors.transparent), ), onPressed: () { if (widget.onOkTap != null) widget.onOkTap(); Navigator.pop(context); }, child: Text('Cancel'), ).animate(controller: _textAnimation).fadeIn().slideX(), ], ), if (_provider.dataState != DataState.loading && !isStateChanging) Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStatePropertyAll(Converter.hexToColor("#2094cd")), shadowColor: MaterialStatePropertyAll(Colors.transparent), ), onPressed: () { if (widget.onOkTap != null) widget.onOkTap(); Navigator.pop(context); }, child: Text('OK'), ).animate(controller: _textAnimation).fadeIn().slideX(), if (_provider.dataState == DataState.failure && widget.showRetryButton && !_provider.canPlayTheAnimation) ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStatePropertyAll(Colors.transparent), shadowColor: MaterialStatePropertyAll(Colors.transparent), side: MaterialStatePropertyAll( BorderSide(color: Converter.hexToColor("#2094cd")))), onPressed: () async { _retryRotateController.forward(); isStateChanging = true; await _provider.setLoadingState(); _changeToLoading(); widget.executeFunction(); ///Excute the onRetry function after tje animation is complete ///if it is not null _retryRotateController.reset(); }, child: Row( children: [ RotationTransition( turns: _retryRotateAnimation, child: Icon(Icons.restart_alt_sharp, color: Converter.hexToColor("#2094cd"))), Text('Retry', style: TextStyle(color: Converter.hexToColor("#2094cd"))), ], ), ).animate(controller: _textAnimation).shimmer().slideX(), ], ) // if (isStateChanging) SizedBox(height: 60) ], ), Positioned.fill( child: Padding( padding: const EdgeInsets.only(top: 25, left: 40, right: 40), child: SlideTransition( position: _yAnimation, child: ScaleTransition( scale: _containerScaleAnimation, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: circleColor, ), child: ScaleTransition( scale: _iconScaleAnimation, child: isStateChanging ? SizedBox.shrink() : InkWell( onTap: () { context .read<AddDeleteUpdateServicesInvoicesProvider>() .updateCreatingState(DataState.done); }, child: Lottie.asset('assets/lottie/$_lottieName.json', reverse: true)), ), ), ), ), ), ) ], )))), ); }, ); } String tanslatedDataState(DataState state) { switch (state) { case DataState.loading: return 'جاري التنفذي'; case DataState.done: return 'تمت العملية بنجاح'; case DataState.failure: return 'حدث خطأ'; case DataState.notSet: break; case DataState.empty: break; case DataState.hasData: break; case DataState.offline: return 'تأكد من جودة الانترنت'; } return ''; } void updateUiState() { Future.delayed(Duration.zero, () async { _provider.compaerStates(); print(_provider.dataState); // print(widget.lottieErrorAssetsName); switch (_provider.dataState) { case DataState.loading: if (_provider.playAnimation && _provider.canPlayTheAnimation) { _provider.playAnimation = false; await _changeToLoading(); } break; case DataState.done: if (_provider.playAnimation && _provider.canPlayTheAnimation) { _provider.playAnimation = false; await _changeToSucces(); } break; case DataState.failure: if (_provider.playAnimation && _provider.canPlayTheAnimation) { _provider.playAnimation = false; await _changeToError(); } break; case DataState.offline: if (_provider.playAnimation && _provider.canPlayTheAnimation) { _provider.playAnimation = false; await _changeToOffline(); } break; case DataState.notSet: break; case DataState.empty: break; case DataState.hasData: break; } }); } Future<void> _changeToError() async { setState(() { isStateChanging = true; _controller.reverse(); circleColor = Converter.hexToColor('#f33342'); _textAnimation..reverse(); _lottieName = widget.lottieErrorAssetsName; }); await _player.play(AssetSource('sounds/error.wav')); await Future.delayed(Duration(seconds: 1)); _controller ..forward().whenComplete(() { circleColor = Colors.transparent; setState(() {}); _textAnimation..forward(); }); await Future.delayed(Duration(seconds: 4)); setState(() { isStateChanging = false; }); _provider.completeAnimation(); } Future<void> _changeToOffline() async { setState(() { isStateChanging = true; _controller.reverse(); circleColor = Colors.blue[800]; _textAnimation..reverse(); _lottieName = 'offline'; }); await Future.delayed(Duration(seconds: 1)); _controller ..forward().whenComplete(() { circleColor = Colors.transparent; setState(() {}); _textAnimation..forward(); }); await Future.delayed(Duration(seconds: 4)); setState(() { isStateChanging = false; }); _provider.completeAnimation(); } Future<void> _changeToSucces() async { setState(() { isStateChanging = true; }); _controller.reverse(); circleColor = Colors.blue[300]; _textAnimation..reverse(); await _player.play(AssetSource('sounds/success.mp3')); await Future.delayed(Duration(seconds: 1)); _lottieName = widget.lottieSuccessAssetsName; print('$_lottieName +++++++='); setState(() {}); isStateChanging = false; _controller ..forward().whenComplete(() { circleColor = Colors.transparent; setState(() {}); _textAnimation.forward(); }); await Future.delayed(Duration(seconds: 4)); _provider.completeAnimation(); //Dismiss the dialog if (widget.autoDismiss) autoDismiss(); } Future<void> _changeToLoading() async { print('isStateChanging $isStateChanging'); _textAnimation ..reverse() ..stop(); _retryRotateController.forward(); isStateChanging = true; setState(() {}); _controller.reverse(); circleColor = Converter.hexToColor("#2094cd").withOpacity(0.1); await _player.play(AssetSource('sounds/loading.wav')); await Future.delayed(Duration(seconds: 1)); _lottieName = widget.lottieLoadingAssetsName; _controller ..forward().whenComplete( () { circleColor = Color.fromRGBO(0, 0, 0, 0); setState(() {}); _textAnimation..forward(); }, ); setState(() { isStateChanging = false; }); await Future.delayed(Duration(seconds: 3)); print('isStateChanging $isStateChanging'); _provider.completeAnimation(); } void autoDismiss() { Future.delayed(widget.duration, () => Navigator.of(context).pop()); } } this my provider handling the ui state. import 'package:flutter/material.dart'; import 'package:investment_com/core/enums/enums.dart'; abstract class AbstractProvider extends ChangeNotifier { DataState dataState = DataState.loading; DataState oldState = DataState.notSet; String message = ""; bool playAnimation = true; bool canPlayTheAnimation = true; void compaerStates() async { if (oldState != dataState && canPlayTheAnimation) { print('yes i can'); await Future.delayed(Duration(seconds: 2)); print('${dataState.name} VS ${oldState.name}'); playAnimation = true; oldState = dataState; canPlayTheAnimation = false; notifyListeners(); } } Future<void> setLoadingState() async { await Future.delayed(Duration(seconds: 2)); dataState = DataState.loading; notifyListeners(); } void completeAnimation() async { canPlayTheAnimation = true; notifyListeners(); } void reset() { dataState = DataState.notSet; oldState = DataState.notSet; playAnimation = true; canPlayTheAnimation = true; } } how to await the animate tho complete to play other animation while the data state is upditing
5edbac2767dc3f690fdb225a99b0a4c3
{ "intermediate": 0.2933122515678406, "beginner": 0.5300467014312744, "expert": 0.1766410917043686 }
18,077
5 2017-01-05 145 6 2017-01-06 1455 7 2017-01-07 199 8 2017-01-08 188 get these results using cte function on mysql
dd356910b95a0d5b136d8d58aedb8af8
{ "intermediate": 0.32573744654655457, "beginner": 0.29776597023010254, "expert": 0.3764966130256653 }
18,078
5 2017-01-05 145 6 2017-01-06 1455 7 2017-01-07 199 8 2017-01-08 188 get these results using inner join
7b614d4f3c569870f061ad7ae74a690a
{ "intermediate": 0.24838876724243164, "beginner": 0.2567768692970276, "expert": 0.494834303855896 }
18,079
create table Players(number int,name varchar(50),age int,starts int,totalGoals int,totalShots int) create table injuredPlayers(number int,name varchar(50)) insert into Players values (3,'Eric Bailly',23,8,1,NULL), (17,'Daley Blind',27,3,NULL,NULL), (36,'Matteo Darmian',28,2,NULL,NULL), (4,'Phil Jones',25,17,NULL,NULL), (2,'Victor Lindelof',23,7,NULL,NULL), (35,'Demetri Mitchell',20,NULL,NULL,NULL), (5,'Marcos Rojo',28,5,NULL,NULL), (23,'Luke Shaw',22,5,NULL,NULL), (12,'Chris Smaling',28,13,1,NULL), (38,'Axel Tuanzebe',20,NULL,NULL,NULL), (25,'Antonio Valencia',32,18,2,NULL), (16,'Michael Carrick',36,NULL,NULL,NULL), (27,'Marouane Fellaini',30,3,3,NULL), (21,'Ander Herrera',28,8,NULL,NULL), (14,'Jesse Lingard',25,9,8,NULL), (8,'Juan Mata',29,15,3,NULL), (31,'Nemanja Matic',29,22,NULL,NULL), (39,'Scott McTominay',21,1,NULL,NULL), (22,'Henrikh Mkhitaryan',28,11,1,NULL), (6,'Paul Pogba',24,12,3,NULL), (18,'Ashley Young',32,16,2,NULL), (10,'Zlatan Ibrahimovic',36,1,NULL,NULL), (9,'Romelu Lukaku',24,21,10,NULL), (11,'Anthony Martial',22,11,7,NULL), (19,'Marcus Rashford',20,13,4,NULL) insert into injuredPlayers values (16,'Michael Carrick'), (3,'Eric Bailly'), (27,'Marouane Fellaini'), (25,'Antonio Valencia'), (10,'Zlatan Ibrahimovich'), (9,'Romelu Lukaku') SELECT * FROM injuredPlayers SELECT * FROM Players
b365c88f2bd583e37abbf1ddf79c374e
{ "intermediate": 0.3286128342151642, "beginner": 0.4434671401977539, "expert": 0.22792008519172668 }
18,080
from openpyxl import load_workbook import pandas as pd import datetime from openpyxl import Workbook from openpyxl.utils.dataframe import dataframe_to_rows # 打开Excel文件 wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # 选择指定的sheet sheet = wb['吨钢毛利'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改 # 选择指定的列 columns = [0, 9, 10, 11, 12] # 读取数据 data = [] for row in sheet.iter_rows(values_only=True): if all(value is None for value in row): break data.append([row[column] for column in columns]) # 构建DataFrame df = pd.DataFrame(data) df.columns = df.iloc[0] df = df[1:] # 将第一列作为索引并转换为datetime格式 df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean() five_years_ago = date - pd.DateOffset(years=6) date_range = pd.date_range(start=five_years_ago, end=date) history_values = df.loc[date_range, column] # Calculate smoothed values history_means = history_values.rolling(window=5).mean() # Filter out the same month and day values history_values = df[(df.index.month.isin(date_range.month)) & (df.index.day.isin(date_range.day))][column] target_smoothed_value = target_value_mean max_smoothed_value = history_means.max() min_smoothed_value = history_means.min() percentile = (target_smoothed_value - min_smoothed_value) / (max_smoothed_value - min_smoothed_value) * 100 return percentile # 创建一个空的列表,用于存储每一天的percentile值 percentiles = [] # 设置起始日期 start_date = pd.to_datetime('2018-12-31') # 循环遍历DataFrame的每一行 for index, row in df.iterrows(): # 检查是否满足起始日期的条件,如果不满足,则跳过计算 if index < start_date: percentiles.append(None) continue # 获取当前行的日期和列名 date = index column = '螺纹钢' # 要计算percentile的列名,请根据实际情况修改 # 调用calculate_percentile函数计算percentile值 percentile = calculate_percentile(df, date, column) # 将percentile值添加到列表中 percentiles.append(percentile) df['Percentile'] = percentiles # 创建一个空的列表,用于存储每一天的Percentile YOY值 percentile_yoy = [] # 循环遍历DataFrame的每一行 for index, row in df.iterrows(): # 检查是否满足起始日期的条件,如果不满足,则跳过计算 if index < start_date: percentile_yoy.append(None) continue # 获取当前行的日期和列名 date = index column = '螺纹钢' # 要计算Percentile YOY的列名,请根据实际情况修改 # 获取上一年同期的日期 last_year_date = date - pd.DateOffset(years=1) # 检查上一年同期的日期是否在DataFrame中存在 if last_year_date in df.index: # 计算上一年同期的Percentile值 last_year_percentile = df.loc[last_year_date, 'Percentile'] # 计算Percentile YOY值 percentile_yoy_value = row['Percentile'] - last_year_percentile percentile_yoy.append(percentile_yoy_value) else: percentile_yoy.append(None) # 将percentile_yoy列表添加为新的一列到DataFrame中 df['Percentile YOY'] = percentile_yoy # 创建一个空的列表,用于存储每一天的Percentile WOW值 percentile_wow = [] # 循环遍历DataFrame的每一行 for index, row in df.iterrows(): # 检查是否满足起始日期的条件,如果不满足,则跳过计算 if index < start_date: percentile_wow.append(None) continue # 获取当前行的日期和列名 date = index column = '螺纹钢' # 要计算Percentile YOY的列名,请根据实际情况修改 # 获取两周前的日期 two_weeks_ago = date - pd.DateOffset(weeks=2) # 检查两周前的日期是否在DataFrame中存在 if two_weeks_ago in df.index: # 计算两周前的的Percentile值 two_weeks_ago_percentile = df.loc[two_weeks_ago, 'Percentile'] # 计算Percentile WOW值 percentile_wow_value = row['Percentile'] - two_weeks_ago_percentile percentile_wow.append(percentile_wow_value) else: percentile_wow.append(None) # 将percentile_wow列表添加为新的一列到DataFrame中 df['Percentile WOW'] = percentile_wow # 创建一个新的工作簿 new_wb = Workbook() # 获取新工作簿的默认sheet new_sheet = new_wb.active # 将DataFrame的数据逐行写入新sheet for r in dataframe_to_rows(df, index=True, header=True): new_sheet.append() # 设置新sheet的名称 new_sheet.title = "数据分析结果" 运行以后错误信息如下 怎么改? --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_1100/3893421799.py in <module> 150 # 将DataFrame的数据逐行写入新sheet 151 for r in dataframe_to_rows(df, index=True, header=True): --> 152 new_sheet.append() 153 154 # 设置新sheet的名称 TypeError: append() missing 1 required positional argument: 'iterable'
d44e1fceced33f70e0058e6b58b49661
{ "intermediate": 0.48766642808914185, "beginner": 0.3247459828853607, "expert": 0.18758758902549744 }
18,081
Create stored proc to return only forwards
ad29c9f9318192f8c3f0908c997cc434
{ "intermediate": 0.33505722880363464, "beginner": 0.22258330881595612, "expert": 0.44235947728157043 }
18,082
用Cython优化下列代码: from bs4 import BeautifulSoup import requests,concurrent.futures,time def get_proxies(url, session): try: response = session.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"请求失败: {e}") return None soup = BeautifulSoup(response.text, 'html.parser') rows = soup.find_all('tr') proxies = [] for row in rows[1:]: columns = row.find_all('td') second = columns[5].text.strip() if float(second.strip("秒")[0]) <= 10.0: ip = columns[0].text.strip() port = columns[1].text.strip() proxies.append(f'{ip}:{port}') return proxies def test_proxy(proxy, checked_proxies, session): if proxy in checked_proxies: return None try: response = session.get('https://www.baidu.com', proxies={"http": proxy, "https": proxy}, timeout=5) response.raise_for_status() if response.status_code == 200: ping=round(response.elapsed.total_seconds(),4) print(f'[第 {page} 页](延迟 {ping} 秒){proxy}') checked_proxies.add(proxy) except: pass return checked_proxies def test_proxies(proxies, checked_proxies, session): with concurrent.futures.ThreadPoolExecutor(max_workers=64) as executor: results = [executor.submit(test_proxy, proxy, checked_proxies, session) for proxy in proxies] for future in concurrent.futures.as_completed(results): checked_proxies = future.result() return checked_proxies def main(): base_url = 'https://www.kuaidaili.com/free/inha' num_pages = 80 # 爬取页数 checked_proxies = set() # 存储可用代理 session = requests.Session() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35' } session.headers.update(headers) for page in range(1, num_pages+1): url = f'{base_url}/{page}/' proxies = get_proxies(url, session) if proxies: checked_proxies = test_proxies(proxies, checked_proxies, session) print(f"已处理结果均在本行之上 「进度: {page}/{num_pages} 页」",end='\r') time.sleep(5) #必要 防封禁 if __name__ == "__main__": main()
e9dc032a0e294a1ec2ea94a9ea16d165
{ "intermediate": 0.4331766366958618, "beginner": 0.39338719844818115, "expert": 0.17343619465827942 }
18,083
show how to create an ordered list in jupyter notebook.
6aba19a81b1ce0572195d55d62610d66
{ "intermediate": 0.5061133503913879, "beginner": 0.20488609373569489, "expert": 0.2890004813671112 }