row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
3,414
|
write A vba to calculate rsi with close data in column d.write sub not function
|
66bfeb8f3af504f1cda9bf1fc4d0ad90
|
{
"intermediate": 0.3178268074989319,
"beginner": 0.3589775264263153,
"expert": 0.3231956362724304
}
|
3,415
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set_theme(style="darkgrid")
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_charts = st.checkbox("サマリーグラフを表示")
show_charts = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
chart_data = []
chart_data_likes = {}
chart_data_comments = {}
for key, value in count.items():
for c in value:
if c != 'followers_count':
post = count[list(count.keys())[-1]][c]
like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count'])
comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count'])
total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count')
total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count')
if 'followers_count' in value:
chart_data_likes[key] = total_likes_count_diff
chart_data_comments[key] = total_comments_count_diff
chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff])
if show_summary_charts:
df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"])
df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d")
fig, ax1 = plt.subplots(figsize=(15, 6))
sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1)
ax1.set(ylabel="followers_count")
ax2 = ax1.twinx()
sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2)
sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2)
ax2.set(ylabel="total_likes_count & total_comments_count")
plt.title("Summary Chart")
sns.despine()
st.pyplot(fig)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_charts:
days = list(chart_data_likes.keys())
likes = [chart_data_likes[d] for d in days]
comments = [chart_data_comments[d] for d in days]
df_like_data = pd.DataFrame({"Date": days, "likes_count": likes})
df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments})
fig, ax1 = plt.subplots(figsize=(5, 3))
sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1)
sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1)
plt.xticks(rotation=90)
plt.title("Like and Comment Counts")
sns.despine()
st.pyplot(fig)
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コード冒頭の修正内容についての説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "サマリーグラフ"の'like_count'と'comments_count'の数は、"各日の実数の合算"ではなく、"前日と比較して増加した数"を算出し表示する
- "いいね/コメント数グラフ"については、各投稿IDごとに'like_count'と'comments_count'の"前日と比較して増加した数"を算出し、その各投稿IDごとに別々のグラフを表示するようにする
|
fe02ff360e0b45b30b833b0f78547372
|
{
"intermediate": 0.3094857633113861,
"beginner": 0.43339425325393677,
"expert": 0.25711995363235474
}
|
3,416
|
Write me code that recursively scrapes the links inside all the folders of the site https://arcjav2.avax2.workers.dev/ which are generated with javascript using a script called Cloud BHADOO. Scraping JavaScript-rendered web pages can be challenging due to the dynamic loading of data. Regular libraries and methods may not be sufficient for scraping JavaScript-generated content. In this case, Selenium, a browser automation tool, can be used to scrape JavaScript-rendered web pages with Python. Scrape the relevant data using CSS selectors or other methods supported by Selenium. When scraping for the links, one of the results should be https://arcjav2.avax2.workers.dev/0:/EBOD-301%20(ebod00301)%20[E-BODY]%20%E3%82%A2%E3%83%80%E3%83%AB%E3%83%88Kiss%E3%81%AB%E6%BF%80%E3%83%8F%E3%83%9E%E3%83%AA%20%E5%B0%BE%E4%B8%8A%E8%8B%A5%E8%91%89.mp4 keep testing until you are able to successfully scrape links that end with .mkv .mp4 .mov .avi .flv .wmv and test to see if you can download a movie file from the scraped links. Remember to focus on recursively scraping links inside folders generated by Cloud BHADOO and filtering for video file extensions. Once you have confirmed everything is working in the code through testing, provide me with the code.
|
506ebd72cf5b86c3812d7dd7ad532d98
|
{
"intermediate": 0.6544519662857056,
"beginner": 0.12263317406177521,
"expert": 0.22291487455368042
}
|
3,417
|
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("$F$2")) Is Nothing Then
If Range("A2:E2").Find("") Is Nothing Then
Call Request
Else
MsgBox "Please fill in cells A2 to E2.", vbInformation
End If
End If
End Sub This code does not work as expected, Is there an error in it or is there an alternative code that does the same thing
|
c81a672044d2ab1346faabdaae6205dd
|
{
"intermediate": 0.47056686878204346,
"beginner": 0.3577696681022644,
"expert": 0.17166346311569214
}
|
3,418
|
code me a discord.py cog listener that listens for when a 0001 username and discriminator is available and sends it to a channel in discord
|
dd372e37100caced039d9c912c40ca8d
|
{
"intermediate": 0.40727049112319946,
"beginner": 0.2073068618774414,
"expert": 0.38542261719703674
}
|
3,419
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- jsonファイルに保存されている各日の日時データ増減で"followers_count"の実数と"'like_count'の投稿全体における当日に増加した数"を1軸目の縦軸とし、"'comments_count'の全投稿における当日に増加した数"を2軸目の縦軸とし、グラフ背景は"黒"でグラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの下部に横幅いっぱいに表示する機能を作成する
- "サマリーグラフ"の'like_count'と'comments_count'の数は、"各日の実数の合算"ではなく、"前日と比較して増加した数"を算出し表示する
- jsonファイルに保存されている各日の"各投稿ごとの'like_count'"と"各投稿ごとの'comments_count'"の日時データの当日に増加した総数を縦軸とし、グラフ背景は"黒"で各グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"1日"を横軸にした"いいね/コメント数グラフ"を、各投稿のボックス内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"については、各投稿IDごとに'like_count'と'comments_count'の"前日と比較して増加した数"を算出し、その各投稿IDごとに別々のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
6b91607f8ae50171cbbc6e79717fbc21
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,420
|
What is the vba code to enable events and allso to disable events
|
1b3de78b37a787cb96793a78cb29b43b
|
{
"intermediate": 0.5078231692314148,
"beginner": 0.16168807446956635,
"expert": 0.33048877120018005
}
|
3,421
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- jsonファイルに保存されている各日のデータ増減で"followers_count"の実数と、"すべての投稿においての当日の'like_count'の純増数"を1軸目の縦軸とし、"すべての投稿においての当日の'comments_count'の純増数"を2軸目の縦軸とし、グラフ背景は"黒"でグラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- jsonファイルに保存されている各日の"各投稿IDごとの'like_count'"と"各投稿ごとの'comments_count'"の日次データにおいて、"当日の純増数"を縦軸とし、グラフ背景は"黒"で各グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"いいね/コメント数グラフ"を、各投稿IDのボックス内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"については、各投稿IDごとに'like_count'と'comments_count'の"前日と比較して増加した数"を算出し、その各投稿IDごとに別々のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
a87cd383f0d859bb87ea13efa3b43549
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,422
|
write a vba to calculate stochastic rsi with open high low close data the data there is in column a to d .write sub .and data have header
|
7c549eb3ddd751f33e55a4d32d6e5952
|
{
"intermediate": 0.4255891740322113,
"beginner": 0.14698335528373718,
"expert": 0.4274274706840515
}
|
3,423
|
Write full code for TCPPacketServer MTServer Clients TCPPacketClient Pocket classes,names have to be exactly the same-->client/servimplementtransmitpacket.packetconsisttwopart;headerpartcontain“serialnumber”“datapart”containmessag(stringcharact).Clientsendpacketserverreceivacknowledg,entertextserverconvertuppercasletterreturnback.clientsend“CLOSE”messag,clientservertermin.Compilthreefile.Runserverclientfiletwodifferwindow.1.tcppacketserver.java●Use/**getoutputstream()methodsenddatasocketstream**/●Use/**getinputstream()methodobtainhandlsocketstream**/2.tcppacketclient.java●Use/**instancSocketclassuseaddresscomputportnumber1024**/●learnhostnameusecommand:.>ipconfig/all(Window+R)●Use/**getinputstream()methodobtainhandlsocketstream**/●Use/**getoutputstream()methodsenddatasocketstream**/●Usebufferedreadmethod/**readkeyboarddata(Packet)needsendserver**/●/**CreatnewinstancPacketclassdataheader,data(packet)packetnumber**/3.packet.java●privatintserialno;●privatStringdata;publicStringgetdata(){returndata;}publicintgetserialno(){returnserialno;}Step-1:Compiltcppacketserv–Openport…--Step-2:Compiltcppacketcli--Enterdatapacket:--Step-3:Entercommanddatapacket:tcppacketserv--Openport…ReceivClientPacketserialno#1packetDataCLIENT1–tcppacketcli--Enterdatapacket:Client1SERVER:Packetserialno#1recieved—Part-2partcreatClientServerconnect.clientapplicgeneratsocketendconnectattemptconnectsocketserver.connectestablish,serverconstructsocketobjectendcommunic.clientservercommunicwritereadsocketusejava.netpackag.Use(Mandatori):●printstreamps=newprintstream(socket.getoutputstream());”sendmessagClientServer.Use(Mandatori):●bufferedreadbr=newbufferedread(newinputstreamread(socket.getinputstream()));receivmessagClient.Step-1:Compilserve.javaclassStep-2:Compilclient.javaclass--Requestsentsuccess--Step-3:ClientServerconnectmtserver--WaitclientrequestNewclientipop!Server:HelloClient:HiServer:?Client:fine—Client--RequestsentsuccessServer:HelloClient:HiServer:?Client:fine--cantseeUMLdiagramwrite-->classPocket:-data:String-serialno:int+Packet(serialno:int,data:String)+getdata():String+getserialno():intPocketclassusejava.io.serializ<<util>>tcppacketservmain(argv:String[]):void<<util>>mtservermain(argLString[]):void<<util>>Clientmain(arg:String[]):void<<util>>tcppacketcli-output:String[]-host:inetaddress+main(argv:String[]):voidtcppacketservmtserverClienttcppacketcliPocketclass
|
f81c291e5708d17a4ec5f2a33ed00274
|
{
"intermediate": 0.38362181186676025,
"beginner": 0.4985615015029907,
"expert": 0.11781672388315201
}
|
3,424
|
if we had rsi in column e from row 15.write a vba to calculate stochastic rsi .write sub
|
0f2c61e136c244c1a92c3ab7735fb932
|
{
"intermediate": 0.32559457421302795,
"beginner": 0.32699260115623474,
"expert": 0.34741276502609253
}
|
3,425
|
in the below code, will the follower drone go 5 meters in front of master drone? or behind the master drone?
from pymavlink import mavutil
import math
import time
the_connection = mavutil.mavlink_connection('/dev/ttyUSB0', baud=57600)
the_connection.wait_heartbeat()
msg = the_connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
master_waypoint = (msg.lat / 10 ** 7, msg.lon / 10 ** 7, 10)
waypoints = [
master_waypoint,
(28.5861327, 77.3420592, 10),
(28.5860912, 77.3420042, 10), # Repeat the first waypoint to make the drone return to its starting point
]
distance = 5 # Distance in meters
angle = 60 # Angle in degrees
kp = 0.1
ki = 0.01
kd = 0.05
pid_limit = 0.0001
class Drone:
def __init__(self, system_id, connection):
self.system_id = system_id
self.connection = connection
def set_mode(self, mode):
self.connection.mav.set_mode_send(
self.system_id,
mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED,
mode
)
def arm(self, arm=True):
self.connection.mav.command_long_send(self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, int(arm), 0, 0, 0, 0, 0,
0)
def takeoff(self, altitude):
self.connection.mav.command_long_send(self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, altitude)
def send_waypoint(self, wp, next_wp, speed):
# Print wp and next_wp
print("Current waypoint: {} | Next waypoint: {}".format(wp, next_wp))
vx, vy, vz = calculate_velocity_components(wp, next_wp, speed)
# Print velocity components
print("Velocity components: vx={}, vy={}, vz={}".format(vx, vy, vz))
self.connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_global_int_message(
10,
self.system_id,
self.connection.target_component,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
int(0b110111111000),
int(wp[0] * 10 ** 7),
int(wp[1] * 10 ** 7),
wp[2],
vx * speed, # Multiply by speed
vy * speed, # Multiply by speed
vz * speed, # Multiply by speed
0,
0,
0,
0,
0)
)
def get_position(self):
self.connection.mav.request_data_stream_send(
self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_DATA_STREAM_POSITION, 1, 1)
while True:
msg = self.connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if msg.get_srcSystem() == self.system_id:
return (msg.lat / 10 ** 7, msg.lon / 10 ** 7, 10)
class PIDController:
def __init__(self, kp, ki, kd, limit):
self.kp = kp
self.ki = ki
self.kd = kd
self.limit = limit
self.prev_error = 0
self.integral = 0
def update(self, error, dt):
derivative = (error - self.prev_error) / dt
self.integral += error * dt
self.integral = max(min(self.integral, self.limit), -self.limit) # Clamp the integral term
output = self.kp * error + self.ki * self.integral + self.kd * derivative
self.prev_error = error
return output
pid_lat = PIDController(kp, ki, kd, pid_limit)
pid_lon = PIDController(kp, ki, kd, pid_limit)
master_drone = Drone(2, the_connection)
follower_drone = Drone(3, the_connection)
print("connection is done")
def calculate_follower_coordinates(wp, distance, angle):
earth_radius = 6371000.0 # in meters
latitude_change = -(180 * distance * math.cos(math.radians(angle))) / (math.pi * earth_radius)
longitude_change = -(180 * distance * math.sin(math.radians(angle))) / (
math.pi * earth_radius * math.cos(math.radians(wp[0])))
new_latitude = wp[0] + latitude_change
new_longitude = wp[1] + longitude_change
print("Calculated follower coordinates: lat={}, lon={}, alt={}".format(new_latitude, new_longitude, wp[2]))
return (new_latitude, new_longitude, wp[2])
def calculate_velocity_components(current_wp, next_wp, speed):
dx = next_wp[0] - current_wp[0]
dy = next_wp[1] - current_wp[1]
dz = next_wp[2] - current_wp[2]
dx2 = dx ** 2
dy2 = dy ** 2
dz2 = dz ** 2
distance = math.sqrt(dx2 + dy2 + dz2)
vx = (dx / distance) * speed
vy = (dy / distance) * speed
vz = (dz / distance) * speed
return vx, vy, vz
def abort():
print("Type 'abort' to return to Launch and disarm motors.")
start_time = time.monotonic()
while time.monotonic() - start_time < 7:
user_input = input("Time left: {} seconds \n".format(int(7 - (time.monotonic() - start_time))))
if user_input.lower() == "abort":
print("Returning to Launch and disarming motors…")
for drone in [master_drone, follower_drone]:
drone.set_mode(6) # RTL mode
drone.arm(False) # Disarm motors
return True
print("7 seconds have passed. Proceeding with waypoint task...")
return False
for drone in [master_drone, follower_drone]:
drone.set_mode(4)
drone.arm()
drone.takeoff(10)
print("arming and takeoff is done")
# Initialize the previous_mode variable to None
previous_mode = {2: None, 3: None} # initialize the previous_mode dictionary
while True:
msg = the_connection.recv_match(type='HEARTBEAT', blocking=False)
if msg:
sysid = msg.get_srcSystem()
if sysid in [2, 3]:
mode = mavutil.mode_string_v10(msg)
if mode != previous_mode[sysid]: # check if the mode has changed
previous_mode[sysid] = mode # update the previous_mode variable
print(f"System ID: {sysid}, Mode: {mode}")
# save the mode for sysid 2 and 3 in separate variables
if sysid == 2:
mode_sysid_2 = mode
elif sysid == 3:
mode_sysid_3 = mode
# Run the following code only when mode_sysid_3 is set to "GUIDED"
time_start = time.time()
if mode_sysid_3 == "GUIDED":
while mode_sysid_2 == "GUIDED":
if abort():
exit()
# main loop
if time.time() - time_start >= 1:
for index, master_wp in enumerate(waypoints[:-1]):
if mode_sysid_2 != "GUIDED":
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
next_wp = waypoints[index + 1]
master_drone.send_waypoint(master_wp, next_wp, speed=3)
follower_position = master_drone.get_position()
# Print follower position
print("follower position: {}".format(follower_position))
if follower_position is None:
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
break
follower_wp = calculate_follower_coordinates(follower_position, distance, angle)
dt = time.time() - time_start
pid_lat_output = pid_lat.update(follower_wp[0] - follower_position[0], dt)
pid_lon_output = pid_lon.update(follower_wp[1] - follower_position[1], dt)
# Print PID output adjustments
print("PID adjustments: lat={}, lon={}".format(pid_lat_output, pid_lon_output))
adjusted_follower_wp = (
follower_wp[0] + pid_lat_output, follower_wp[1] + pid_lon_output, follower_wp[2])
# Print adjusted follower waypoint
print("Adjusted follower waypoint: {}".format(adjusted_follower_wp))
follower_drone.send_waypoint(adjusted_follower_wp, next_wp, speed=3)
if abort():
exit()
if mode_sysid_2 != "GUIDED":
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
time.sleep(30)
# set the mode to rtl and disarms the drone
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
# set mode to rtl
master_drone.set_mode(6)
follower_drone.set_mode(6)
break
the_connection.close()
|
8328c64f3a7f4c5fc1766418809dba9b
|
{
"intermediate": 0.3446710705757141,
"beginner": 0.5339087247848511,
"expert": 0.12142018973827362
}
|
3,426
|
explian the code below#set up the first page table page
xor %esi, %esi
1:
movl %esi, %eax
shll $12, %eax
orl $(PTE_P|PTE_W), %eax
movl $(V2P_WO(first4mptp)), %edi
movl %esi, %ebx
shll $2, %ebx
addl %ebx, %edi
movl %eax, (%edi)
incl %esi
cmpl $1024, %esi
jb 1b
# Set page directory
movl $0, %esi
movl %esi, %ebx
shll $2, %ebx
movl $(V2P_WO(entrypgdir)), %edi
addl %ebx, %edi
movl $(V2P_WO(first4mptp)), (%edi)
orl $(PTE_P | PTE_W), (%edi)
movl $512, %esi
movl %esi, %ebx
shll $2, %ebx
movl $(V2P_WO(entrypgdir)), %edi
addl %ebx, %edi
movl $(V2P_WO(first4mptp)), (%edi)
orl $(PTE_P | PTE_W), (%edi)
|
e4abc1e5469335fb6bbfe42422d6d36c
|
{
"intermediate": 0.3131919503211975,
"beginner": 0.37441813945770264,
"expert": 0.31238988041877747
}
|
3,427
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- jsonファイルに保存されている各日のデータ増減で"followers_count"の実数と、"すべての投稿においての当日の'like_count'の純増数"を1軸目の縦軸とし、"すべての投稿においての当日の'comments_count'の純増数"を2軸目の縦軸とし、グラフ背景は"黒"でグラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- jsonファイルに保存されている各日の"各投稿IDごとの'like_count'"と"各投稿ごとの'comments_count'"の日次データにおいて、"当日の純増数"を縦軸とし、グラフ背景は"黒"で各グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"いいね/コメント数グラフ"を、各投稿IDのボックス内の"キャプション"の下に表示する機能を作成する
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
65e561ec531e20dd70cbf1ac1e5c1935
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,428
|
import random
from PIL import Image
# Define the artists and their monthly Spotify listeners
artists = {
"YoungBoy Never Broke Again": {"image": "C:/Users/elias/Pictures/Album covers/lil_durk.jpg", "listeners": 18212921},
"Young M.A": {"image": "C:/Users/elias/Pictures/Album covers/lil_baby.jpg", "listeners": 2274306},
"Young Nudy": {"image": "C:/Users/elias/Pictures/Album covers/lil_keed.jpg", "listeners": 7553116},
}
# Get the keys of the artists dictionary
keys = list(artists.keys())
# Initialize the score
score = 0
while True:
# Choose two random artists
firstartist, secondartist = random.sample(keys, 2)
# Load and show the images for the two artists
firstartistimg = Image.open(artists[firstartist]["image"])
secondartistimg = Image.open(artists[secondartist]["image"])
firstartistimg.show()
secondartistimg.show()
# Get the user's guess
guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {firstartist} or 2. {secondartist}? ")
guess_lower = guess.strip().lower()
# Check if the user wants to quit
if guess_lower == 'quit':
print("Thanks for playing!")
break
# Check if the user's input is valid
elif guess_lower not in ['1', '2', firstartist.lower(), secondartist.lower()]:
print("Invalid input. Please enter the name of one of the two artists, type 'quit' to end the game or enter 1 or 2 to make a guess.")
# Check if the user's guess is correct
elif guess_lower == firstartist.lower() or guess_lower == '1' and artists[firstartist]["listeners"] > artists[secondartist]["listeners"]:
print(f"You guessed correctly! {firstartist} had \033[1m{artists[firstartist]['listeners'] / 1e6:.1f}M\033[0m monthly Spotify listeners and {secondartist} has {artists[secondartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.")
score += 1
elif guess_lower == secondartist.lower() or guess_lower == '2' and artists[secondartist]["listeners"] > artists[firstartist]["listeners"]:
print(f"You guessed correctly! {secondartist} had \033[1m{artists[secondartist]['listeners'] / 1e6:.1f}M\033[0m monthly Spotify listeners and {firstartist} has {artists[firstartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.")
score += 1
else:
print(f"\nSorry, you guessed incorrectly. {firstartist} had {artists[firstartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {secondartist} has {artists[secondartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.\n")
score = 0
# Ask the user if they want to play again
play_again = input("\nWould you like to play again? (y/n/Ent) ")
if playagain.lower() == 'n':
print("Thanks for playing!")
break
print(f"\nYour score is {score}.")
why does the game show the score (0) after making a mistake and the players plays again, it shouldt show the score again but it should reset to 0
|
096980efcf6c6d17d5516cafc6177a6c
|
{
"intermediate": 0.3726464807987213,
"beginner": 0.4070691764354706,
"expert": 0.2202843278646469
}
|
3,429
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- jsonファイル内の"followers_count"の実数と、"すべての投稿の前日と比較した当日の'like_count'の純増数"を1軸目の縦軸とし、"すべての投稿の前日と比較した当日の'comments_count'の純増数"を2軸目の縦軸とし、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けし背景色はダークにした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- jsonファイル内の"各投稿IDごとの'like_count'"と"各投稿ごとの'comments_count'"の日次データにおいて、"前日と比較した当日の純増数"を縦軸とし、各グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"日付"を横軸にした"いいね/コメント数グラフ"を、各投稿IDのコンテナ内の"キャプション"の下に表示する機能を作成する
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
b43857acf77d7141e6e1d9f7efc5280a
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,430
|
I want the following code to also check Column 2 of the same row and it the value of the cell does not contain within the text value the word Request then it can run. If Target.Column = 10 And Target.Value <> "" Then
|
f9019c9c7f77aad50cca6a2475199755
|
{
"intermediate": 0.5165109038352966,
"beginner": 0.18296682834625244,
"expert": 0.3005223572254181
}
|
3,431
|
write a c program in xv6 that achive the same functionality(set up the first page table and page directory for the operating system) that the assembly code below does xor %esi, %esi
1:
movl %esi, %eax
shll 12, %eax
orl(PTE_P|PTE_W), %eax
movl $(V2P_WO(first4mptp)), %edi
movl %esi, %ebx
shll $2, %ebx
addl %ebx, %edi
movl %eax, (%edi)
incl %esi
cmpl $1024, %esi
jb 1b
# Set page directory
movl $0, %esi
movl %esi, %ebx
shll 2, %ebx
movl(V2P_WO(entrypgdir)), %edi
addl %ebx, %edi
movl (V2P_WO(first4mptp)), (%edi)
orl(PTE_P | PTE_W), (%edi)
movl $512, %esi
movl %esi, %ebx
shll 2, %ebx
movl(V2P_WO(entrypgdir)), %edi
addl %ebx, %edi
movl (V2P_WO(first4mptp)), (%edi)
orl(PTE_P | PTE_W), (%edi)
|
fcb02cb5718cfd6031b16a6a2aa5e610
|
{
"intermediate": 0.2979145348072052,
"beginner": 0.45009157061576843,
"expert": 0.25199389457702637
}
|
3,432
|
import random
from PIL import Image
# Define the artists and their monthly Spotify listeners
artists = {
"YoungBoy Never Broke Again": {"image": "C:/Users/elias/Pictures/Album covers/lil_durk.jpg", "listeners": 18212921},
"Young M.A": {"image": "C:/Users/elias/Pictures/Album covers/lil_baby.jpg", "listeners": 2274306},
"Young Nudy": {"image": "C:/Users/elias/Pictures/Album covers/lil_keed.jpg", "listeners": 7553116},
}
# Get the keys of the artists dictionary
keys = list(artists.keys())
# Initialize the score
score = 0
while True:
# Choose two random artists
firstartist, secondartist = random.sample(keys, 2)
# Load and show the images for the two artists
firstartistimg = Image.open(artists[firstartist]["image"])
secondartistimg = Image.open(artists[secondartist]["image"])
firstartistimg.show()
secondartistimg.show()
# Get the user's guess
guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {firstartist} or 2. {secondartist}? ")
guess_lower = guess.strip().lower()
# Check if the user wants to quit
if guess_lower == 'quit':
print("Thanks for playing!")
break
# Check if the user's input is valid
elif guess_lower not in ['1', '2', firstartist.lower(), secondartist.lower()]:
print("Invalid input. Please enter the name of one of the two artists, type 'quit' to end the game or enter 1 or 2 to make a guess.")
# Check if the user's guess is correct
elif guess_lower == firstartist.lower() or guess_lower == '1' and artists[firstartist]["listeners"] > artists[secondartist]["listeners"]:
print(f"You guessed correctly! {firstartist} had \033[1m{artists[firstartist]['listeners'] / 1e6:.1f}M\033[0m monthly Spotify listeners and {secondartist} has {artists[secondartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.")
score += 1
print(f"\nYour score is {score}.")
continue
elif guess_lower == secondartist.lower() or guess_lower == '2' and artists[secondartist]["listeners"] > artists[firstartist]["listeners"]:
print(f"You guessed correctly! {secondartist} had \033[1m{artists[secondartist]['listeners'] / 1e6:.1f}M\033[0m monthly Spotify listeners and {firstartist} has {artists[firstartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.")
score += 1
print(f"\nYour score is {score}.")
continue
else:
print(f"\nSorry, you guessed incorrectly. {firstartist} had {artists[firstartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {secondartist} has {artists[secondartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.\n")
# Ask the user if they want to play again
play_again = input("\nWould you like to play again? (y/n/Ent) ")
if play_again.lower() == 'n':
print("Thanks for playing!")
break
else:
print(f"\nYour score is {score}.")
how can i shorter the file path
|
088c745299a6d3b15d9a8b50562a94d9
|
{
"intermediate": 0.34939640760421753,
"beginner": 0.38199084997177124,
"expert": 0.268612802028656
}
|
3,433
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- jsonファイル内の"followers_count"の実数と、"すべての投稿の前日と比較した当日の'like_count'の純増数"を1軸目の縦軸とし、"すべての投稿の前日と比較した当日の'comments_count'の純増数"を2軸目の縦軸とし、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けし背景色はダークにした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- jsonファイル内の"各投稿IDごとの'like_count'"と"各投稿ごとの'comments_count'"の日次データにおいて、"前日と比較した当日の純増数"を縦軸とし、各グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"日付"を横軸にした"いいね/コメント数グラフ"を、各投稿IDのコンテナ内の"キャプション"の下に表示する機能を作成する
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
0e7a7ea9a3df92131c932bf7efe739e4
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,434
|
I want to check the value in column J and make sure it is not blank. I also want to check the value in column B and make sure it doe not contain the word Request in the text string. If any of the checks are true then it should run the next code
|
b1c384f2537b207acd9fbb2bf563aabb
|
{
"intermediate": 0.4101986885070801,
"beginner": 0.13070282340049744,
"expert": 0.4590985178947449
}
|
3,435
|
what is the crypto algo in PGP ? is it RSA ?
|
690f5d08f66ca140947ca2ad3055eb91
|
{
"intermediate": 0.18856731057167053,
"beginner": 0.14160576462745667,
"expert": 0.669826865196228
}
|
3,436
|
if volume be in column e write a vba to calculate last volume to average of volume of week in column j and volume to average of volume of month in column k and volume to average of volume of past 3 month in column L
|
b23b260481dd6adceaf670a58d5be856
|
{
"intermediate": 0.40463367104530334,
"beginner": 0.20727647840976715,
"expert": 0.3880898058414459
}
|
3,437
|
Интегрируй следующую функциональность генерации аудио по команде /audio *тут текст prompt* (возможность определять перенос строки и это будут отдельные генерации, как в примере ниже) (также возможность настраивать samples до 3 штук, прим.: /audio 3 *тут текст prompt*. Если цифры после команды /audio нет, то по умолчанию samples = 1) в код бота Telegram на Python:
"Download the TANGO model and generate audio from a text prompt:
import IPython
import soundfile as sf
from tango import Tango
tango = Tango("declare-lab/tango")
prompt = "An audience cheering and clapping"
audio = tango.generate(prompt, steps=200)
sf.write(f"{prompt}.wav", audio, samplerate=16000)
IPython.display.Audio(data=audio, rate=16000)
Use the generate_for_batch function to generate multiple audio samples for a batch of text prompts:
prompts = [
"A car engine revving",
"A dog barks and rustles with some clicking",
"Water flowing and trickling"
]
audios = tango.generate_for_batch(prompts, samples=2)
This will generate two samples for each of the three text prompts.Use the generate_for_batch function to generate multiple audio samples for a batch of text prompts:
prompts = [
"A car engine revving",
"A dog barks and rustles with some clicking",
"Water flowing and trickling"
]
audios = tango.generate_for_batch(prompts, samples=2)
This will generate two samples for each of the three text prompts."
Сам код бота:
"import logging
import openai
from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils.exceptions import BadRequest
from aiogram.types import Message, ChatType
import sqlite3
from sqlite3 import Error
from datetime import datetime
from config import *
from ratelimit import limits, sleep_and_retry
import time
import asyncio
openai.api_key = OPENAI_API_KEY
logging.basicConfig(level=logging.INFO)
bot = Bot(token=TELEGRAM_BOT_TOKEN)
dp = Dispatcher(bot)
def sql_connection():
try:
return sqlite3.connect('bot.db')
except Error:
print(Error)
def create_messages_table(con):
try:
cursorObj = con.cursor()
cursorObj.execute(
"CREATE TABLE IF NOT EXISTS messages(id integer PRIMARY KEY, telegram_user_id text, role text, content text, created_at date)")
con.commit()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
# роль по умолчанию (+ изменить в строке 67)
defaultrole = {"role": "system", "content": "Ты - полезный помощник."}
def add_message(con, telegram_user_id, role, message):
try:
cursorObj = con.cursor()
cursorObj.execute(f"SELECT COUNT(*) FROM messages WHERE telegram_user_id = '{telegram_user_id}'")
message_count = cursorObj.fetchone()[0]
if message_count >= 50:
cursorObj.execute(f"DELETE FROM messages WHERE telegram_user_id = '{telegram_user_id}' ORDER BY created_at LIMIT 1")
sqlite_insert_query = f"""INSERT INTO messages
(telegram_user_id, role, content, created_at)
VALUES
('{telegram_user_id}', '{role}', '{message}', '{datetime.now()}');"""
cursorObj.execute(sqlite_insert_query)
con.commit()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
def delete_user_messages(con, user_id):
global defaultrole
try:
cursorObj = con.cursor()
cursorObj.execute(
f"DELETE FROM messages WHERE telegram_user_id = '{user_id}'")
con.commit()
# роль по умолчанию
defaultrole = {"role": "system", "content": "Ты - полезный помощник."}
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
def get_messages(con, telegram_user_id):
try:
cursorObj = con.cursor()
cursorObj.execute(
f'SELECT * FROM messages WHERE telegram_user_id = "{telegram_user_id}"')
return cursorObj.fetchall()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
@limits(calls=5, period=60)
@sleep_and_retry
async def ai(prompt, user_id):
global defaultrole
try:
await asyncio.sleep(1)
messages = [
defaultrole,
]
user_messages = get_messages(db, user_id)
for message in user_messages:
messages.append({"role": message[2], "content": message[3]})
messages.append({"role": "user", "content": prompt})
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
)
add_message(db, user_id, 'user', prompt)
add_message(db, user_id, 'assistant', completion.choices[0].message.content)
return completion.choices[0].message.content
except:
return None
@dp.message_handler(commands=['role'])
async def set_role(message: types.Message):
global defaultrole
received_text = message.text.replace('/role ','')
if received_text.strip() == '':
await bot.send_message(message.chat.id, "Введите текст после команды /role")
return
delete_user_messages(db, message.from_user.id)
defaultrole = {"role": "system", "content": received_text.strip()}
await bot.send_message(message.chat.id, f"Роль изменена:\n{received_text}")
@dp.message_handler(commands=['clear'])
async def send_welcome(message: types.Message):
delete_user_messages(db, message.from_user.id)
await message.reply("История очищена")
@dp.message_handler(commands=['gpt'])
async def echo(message: types.Message):
answer = await ai(message.text[4:], message.from_user.id)
if answer != None:
await message.reply(answer)
print(get_messages(db, message.from_user.id))
else:
await message.reply('Произошла ошибка, очистите историю: /clear')
@limits(calls=10, period=60)
@sleep_and_retry
@dp.message_handler(commands=['img'])
async def generate_image(message: types.Message):
prompt_text = message.text.replace("/img", "")
if not prompt_text:
await bot.send_message(chat_id=message.chat.id, text="Введите текст")
return
try:
# Создаем изображение на основе текста пользователя
result = openai.Image.create(
prompt=prompt_text,
n=1,
size='256x256'
)
except Exception as e:
await bot.send_message(chat_id=message.chat.id, text="Ошибка при генерации изображения :(")
return
# Отправляем пользователю сгенерированное изображение
try:
await bot.send_photo(chat_id=message.chat.id, photo=result['data'][0]['url'])
except BadRequest:
await bot.send_message(chat_id=message.chat.id, text="Не удалось отправить изображение :(")
@dp.message_handler()
async def message_handler(message: types.Message):
if message.chat.type == ChatType.PRIVATE:
answer = await ai(message.text, message.from_user.id)
if answer != None:
await message.reply(answer)
print(get_messages(db, message.from_user.id))
else:
await message.reply('Произошла ошибка, очистите историю: /clear')
if __name__ == '__main__':
db = sql_connection()
create_messages_table(db)
executor.start_polling(dp, skip_updates=True)"
|
66c6ca7ddd3368e7da962f61eeddb5ac
|
{
"intermediate": 0.23944929242134094,
"beginner": 0.6622364521026611,
"expert": 0.09831424802541733
}
|
3,438
|
if volume be in column e write a vba to calculate the ratio of last volume to average of volume of week in column j and the ratio of last volume to average of volume of month in column k and the ratio of last volume to average of volume of past 3 month in column L
|
17c568bb92e2da42d0f9cb34c6f27b79
|
{
"intermediate": 0.4161245822906494,
"beginner": 0.23298227787017822,
"expert": 0.35089316964149475
}
|
3,439
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "followers_count"と'like_count'を左縦軸とし、'comments_count'を右縦軸とし、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けしグラフ背景色はダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- "サマリーグラフ"の'like_count'と'comments_count'の数は、jsonファイル内の"対象日とその前日データと比較して増加した数"を算出し表示する
- 'like_count'を左縦軸とし、'comments_count'を右縦軸とし、グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"は、jsonファイル内の各投稿IDの'like_count'と'comments_count'を、それぞれ"対象日とその前日データとの差分"を算出し、各ID別の投稿コンテナに個別のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
c629eb3b9273e6085c6c11af3913a3ae
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,440
|
how to make Apex chart clickable characters change another charts in react js
|
6f61134643929e1ef72e8e7d311f9f7b
|
{
"intermediate": 0.48007234930992126,
"beginner": 0.23041526973247528,
"expert": 0.28951239585876465
}
|
3,441
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- コード部分は'''で区切って表示する
- 指示のないコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "followers_count"と'like_count'を左縦軸とし、'comments_count'を右縦軸とし、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けしグラフ背景色はダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- "サマリーグラフ"の'like_count'と'comments_count'の数は、jsonファイル内の"対象日とその前日データと比較して増加した数"を算出し表示する
- 'like_count'を左縦軸とし、'comments_count'を右縦軸とし、グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"は、jsonファイル内の各投稿IDの'like_count'と'comments_count'を、それぞれ"対象日とその前日データとの差分"を算出し、各ID別の投稿コンテナに個別のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
939b1f7f7b4ab71926a8ea2ed31ef1bd
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,442
|
What's the name of the music in the beginning of this video https://youtu.be/WbxbWxbu-aI
|
527fd6d2dcd0b05e20a341a0f701d5f9
|
{
"intermediate": 0.32794880867004395,
"beginner": 0.39098605513572693,
"expert": 0.2810651361942291
}
|
3,443
|
Can you provide me with the code for an online Tic-Tac-Toe game using pygame and Photon?
|
74733c53b1aa28ccfdcee1657433f197
|
{
"intermediate": 0.7135726809501648,
"beginner": 0.12795919179916382,
"expert": 0.1584681123495102
}
|
3,444
|
hi
|
fa676c0de84cf643708781d949c938a0
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
3,445
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- 指示のない部分のコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "followers_count"と'like_count'を左縦軸とし、'comments_count'を右縦軸とし、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けしグラフ背景色はダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- "サマリーグラフ"の'like_count'と'comments_count'の数は、jsonファイル内の"対象日とその前日データと比較して増加した数"を算出し表示する
- 'like_count'を左縦軸とし、'comments_count'を右縦軸とし、グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"は、jsonファイル内の各投稿IDの'like_count'と'comments_count'を、それぞれ"対象日とその前日データとの差分"を算出し、各ID別の投稿コンテナに個別のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
98551c251b5c88f247a2a355a2cc6912
|
{
"intermediate": 0.36978060007095337,
"beginner": 0.47684019804000854,
"expert": 0.15337920188903809
}
|
3,446
|
Интегрируй следующую функциональность генерации аудио по команде /audio *тут текст prompt* (возможность определять перенос строки и это будут отдельные генерации, как в примере ниже) (также возможность настраивать samples до 3 штук, прим.: /audio 3 *тут текст prompt*. Если цифры после команды /audio нет, то по умолчанию samples = 1) в код бота Telegram на Python:
"github:
Download the TANGO model and generate audio from a text prompt:
import IPython
import soundfile as sf
from tango import Tango
tango = Tango("declare-lab/tango")
prompt = "An audience cheering and clapping"
audio = tango.generate(prompt)
sf.write(f"{prompt}.wav", audio, samplerate=16000)
IPython.display.Audio(data=audio, rate=16000)
CheerClap.webm
The model will be automatically downloaded and saved in cache. Subsequent runs will load the model directly from cache.
The generate function uses 100 steps by default to sample from the latent diffusion model. We recommend using 200 steps for generating better quality audios. This comes at the cost of increased run-time.
prompt = "Rolling thunder with lightning strikes"
audio = tango.generate(prompt, steps=200)
IPython.display.Audio(data=audio, rate=16000)
Thunder.webm
Use the generate_for_batch function to generate multiple audio samples for a batch of text prompts:
prompts = [
"A car engine revving",
"A dog barks and rustles with some clicking",
"Water flowing and trickling"
]
audios = tango.generate_for_batch(prompts, samples=2)
This will generate two samples for each of the three text prompts.
More generated samples are shown here.
Prerequisites
Our code is built on pytorch version 1.13.1+cu117. We mention torch==1.13.1 in the requirements file but you might need to install a specific cuda version of torch depending on your GPU device type.
Install requirements.txt. You will also need to install the diffusers package from the directory provided in this repo:
git clone https://github.com/declare-lab/tango/
cd tango
pip install -r requirements.txt
cd diffusers
pip install -e ."
Сам код бота:
"import logging
import openai
from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils.exceptions import BadRequest
from aiogram.types import Message, ChatType
import sqlite3
from sqlite3 import Error
from datetime import datetime
from config import *
from ratelimit import limits, sleep_and_retry
import time
import asyncio
openai.api_key = OPENAI_API_KEY
logging.basicConfig(level=logging.INFO)
bot = Bot(token=TELEGRAM_BOT_TOKEN)
dp = Dispatcher(bot)
def sql_connection():
try:
return sqlite3.connect('bot.db')
except Error:
print(Error)
def create_messages_table(con):
try:
cursorObj = con.cursor()
cursorObj.execute(
"CREATE TABLE IF NOT EXISTS messages(id integer PRIMARY KEY, telegram_user_id text, role text, content text, created_at date)")
con.commit()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
# роль по умолчанию (+ изменить в строке 67)
defaultrole = {"role": "system", "content": "Ты - полезный помощник."}
def add_message(con, telegram_user_id, role, message):
try:
cursorObj = con.cursor()
cursorObj.execute(f"SELECT COUNT(*) FROM messages WHERE telegram_user_id = '{telegram_user_id}'")
message_count = cursorObj.fetchone()[0]
if message_count >= 50:
cursorObj.execute(f"DELETE FROM messages WHERE telegram_user_id = '{telegram_user_id}' ORDER BY created_at LIMIT 1")
sqlite_insert_query = f"""INSERT INTO messages
(telegram_user_id, role, content, created_at)
VALUES
('{telegram_user_id}', '{role}', '{message}', '{datetime.now()}');"""
cursorObj.execute(sqlite_insert_query)
con.commit()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
def delete_user_messages(con, user_id):
global defaultrole
try:
cursorObj = con.cursor()
cursorObj.execute(
f"DELETE FROM messages WHERE telegram_user_id = '{user_id}'")
con.commit()
# роль по умолчанию
defaultrole = {"role": "system", "content": "Ты - полезный помощник."}
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
def get_messages(con, telegram_user_id):
try:
cursorObj = con.cursor()
cursorObj.execute(
f'SELECT * FROM messages WHERE telegram_user_id = "{telegram_user_id}"')
return cursorObj.fetchall()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
@limits(calls=5, period=60)
@sleep_and_retry
async def ai(prompt, user_id):
global defaultrole
try:
await asyncio.sleep(1)
messages = [
defaultrole,
]
user_messages = get_messages(db, user_id)
for message in user_messages:
messages.append({"role": message[2], "content": message[3]})
messages.append({"role": "user", "content": prompt})
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
)
add_message(db, user_id, 'user', prompt)
add_message(db, user_id, 'assistant', completion.choices[0].message.content)
return completion.choices[0].message.content
except:
return None
@dp.message_handler(commands=['role'])
async def set_role(message: types.Message):
global defaultrole
received_text = message.text.replace('/role ','')
if received_text.strip() == '':
await bot.send_message(message.chat.id, "Введите текст после команды /role")
return
delete_user_messages(db, message.from_user.id)
defaultrole = {"role": "system", "content": received_text.strip()}
await bot.send_message(message.chat.id, f"Роль изменена:\n{received_text}")
@dp.message_handler(commands=['clear'])
async def send_welcome(message: types.Message):
delete_user_messages(db, message.from_user.id)
await message.reply("История очищена")
@dp.message_handler(commands=['gpt'])
async def echo(message: types.Message):
answer = await ai(message.text[4:], message.from_user.id)
if answer != None:
await message.reply(answer)
print(get_messages(db, message.from_user.id))
else:
await message.reply('Произошла ошибка, очистите историю: /clear')
@limits(calls=10, period=60)
@sleep_and_retry
@dp.message_handler(commands=['img'])
async def generate_image(message: types.Message):
prompt_text = message.text.replace("/img", "")
if not prompt_text:
await bot.send_message(chat_id=message.chat.id, text="Введите текст")
return
try:
# Создаем изображение на основе текста пользователя
result = openai.Image.create(
prompt=prompt_text,
n=1,
size='256x256'
)
except Exception as e:
await bot.send_message(chat_id=message.chat.id, text="Ошибка при генерации изображения :(")
return
# Отправляем пользователю сгенерированное изображение
try:
await bot.send_photo(chat_id=message.chat.id, photo=result['data'][0]['url'])
except BadRequest:
await bot.send_message(chat_id=message.chat.id, text="Не удалось отправить изображение :(")
@dp.message_handler()
async def message_handler(message: types.Message):
if message.chat.type == ChatType.PRIVATE:
answer = await ai(message.text, message.from_user.id)
if answer != None:
await message.reply(answer)
print(get_messages(db, message.from_user.id))
else:
await message.reply('Произошла ошибка, очистите историю: /clear')
if __name__ == '__main__':
db = sql_connection()
create_messages_table(db)
executor.start_polling(dp, skip_updates=True)"
|
e9666368b42ecf0d5bf9cb32058d71af
|
{
"intermediate": 0.4135250747203827,
"beginner": 0.44432103633880615,
"expert": 0.14215387403964996
}
|
3,447
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set_theme(style="darkgrid")
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_charts = st.checkbox("サマリーグラフを表示")
show_charts = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
chart_data = []
chart_data_likes = {}
chart_data_comments = {}
for key, value in count.items():
for c in value:
if c != 'followers_count':
post = count[count.keys()[-1]][c]
like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count'])
comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count'])
total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count')
total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count')
if 'followers_count' in value:
chart_data_likes[key] = total_likes_count_diff
chart_data_comments[key] = total_comments_count_diff
chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff])
if show_summary_charts:
df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"])
df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d")
fig, ax1 = plt.subplots(figsize=(15, 6))
sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1)
ax1.set(ylabel="followers_count")
ax2 = ax1.twinx()
sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2)
sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2)
ax2.set(ylabel="total_likes_count & total_comments_count")
plt.title("Summary Chart")
sns.despine()
st.pyplot(fig)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_charts:
days = list(chart_data_likes.keys())
likes = [chart_data_likes[d] for d in days]
comments = [chart_data_comments[d] for d in days]
df_like_data = pd.DataFrame({"Date": days, "likes_count": likes})
df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments})
fig, ax1 = plt.subplots(figsize=(5, 3))
sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1)
sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1)
plt.xticks(rotation=90)
plt.title("Like and Comment Counts")
sns.despine()
st.pyplot(fig)
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。
- Python用のインデントを行頭に付与して出力する
- コード部分は'''で区切って表示する
- コードの説明文は表示しない
- 修正済みのコード全体を省略せずに表示する
- 指示のないコードの改変はしない
- "caption = post['caption']"以降のブロックについては改変しない
'''
TypeError Traceback (most recent call last)
Cell In [16], line 134
132 for c in value:
133 if c != 'followers_count':
--> 134 post = count[count.keys()[-1]][c]
135 like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count'])
136 comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count'])
TypeError: 'dict_keys' object is not subscriptable
|
8c29faee15015e4cd249c7078dc94383
|
{
"intermediate": 0.3094857633113861,
"beginner": 0.43339425325393677,
"expert": 0.25711995363235474
}
|
3,448
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set_theme(style="darkgrid")
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_charts = st.checkbox("サマリーグラフを表示")
show_charts = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
chart_data = []
chart_data_likes = {}
chart_data_comments = {}
for key, value in count.items():
for c in value:
if c != 'followers_count':
post = count[list(count.keys())[-1]][c]
like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count'])
comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count'])
total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count')
total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count')
if 'followers_count' in value:
chart_data_likes[key] = total_likes_count_diff
chart_data_comments[key] = total_comments_count_diff
chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff])
if show_summary_charts:
df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"])
df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d")
fig, ax1 = plt.subplots(figsize=(15, 6))
sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1)
ax1.set(ylabel="followers_count")
ax2 = ax1.twinx()
sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2)
sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2)
ax2.set(ylabel="total_likes_count & total_comments_count")
plt.title("Summary Chart")
sns.despine()
st.pyplot(fig)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_charts:
days = list(chart_data_likes.keys())
likes = [chart_data_likes[d] for d in days]
comments = [chart_data_comments[d] for d in days]
df_like_data = pd.DataFrame({"Date": days, "likes_count": likes})
df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments})
fig, ax1 = plt.subplots(figsize=(5, 3))
sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1)
sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1)
plt.xticks(rotation=90)
plt.title("Like and Comment Counts")
sns.despine()
st.pyplot(fig)
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- 指示のない部分のコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "followers_count"と'like_count'を左縦軸に表示し、'comments_count'を右縦軸に表示し、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けしグラフ背景色はダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- "サマリーグラフ"の'like_count'と'comments_count'の数は、jsonファイル内の過去すべてのデータを参照し、"対象日とその前日データと比較して増加した数"を算出し日を追って列挙して表示する
- 'like_count'を左縦軸に表示し、'comments_count'を右縦軸に表示し、グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"は、jsonファイル内の過去すべてのデータを参照し、各投稿IDの'like_count'と'comments_count'を、それぞれ"対象日とその前日データとの差分"を算出し日付を追って列挙し、各ID別の投稿コンテナに個別のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
d9ce7aa664795dd156a32e486b4baea2
|
{
"intermediate": 0.3094857633113861,
"beginner": 0.43339425325393677,
"expert": 0.25711995363235474
}
|
3,449
|
Интегрируй следующую функциональность генерации аудио по команде /audio *тут текст prompt* в код бота Telegram на Python. Я использую Visual Studio Code, и мне нужно, чтобы всё необходимое было в папке с проектом моего кода. Пусть пользователь имеет возможность выбирать язык, пример: /audio ru *prompt тут*.
github https://github.com/suno-ai/bark:
"
from bark import SAMPLE_RATE, generate_audio, preload_models
from IPython.display import Audio
# download and load all models
preload_models()
# generate audio from text
text_prompt = """
Hello, my name is Suno. And, uh — and I like pizza. [laughs]
But I also have other interests such as playing tic tac toe.
"""
audio_array = generate_audio(text_prompt)
# play text in notebook
Audio(audio_array, rate=SAMPLE_RATE)
pizza.webm
To save audio_array as a WAV file:
from scipy.io.wavfile import write as write_wav
write_wav("/path/to/audio.wav", SAMPLE_RATE, audio_array)
🌎 Foreign Language
Bark supports various languages out-of-the-box and automatically determines language from input text. When prompted with code-switched text, Bark will attempt to employ the native accent for the respective languages. English quality is best for the time being, and we expect other languages to further improve with scaling.
text_prompt = """
Buenos días Miguel. Tu colega piensa que tu alemán es extremadamente malo.
But I suppose your english isn't terrible.
"""
audio_array = generate_audio(text_prompt)
miguel.webm
🎶 Music
Bark can generate all types of audio, and, in principle, doesn't see a difference between speech and music. Sometimes Bark chooses to generate text as music, but you can help it out by adding music notes around your lyrics.
text_prompt = """
♪ In the jungle, the mighty jungle, the lion barks tonight ♪
"""
audio_array = generate_audio(text_prompt)
lion.webm
🎤 Voice Presets and Voice/Audio Cloning
Bark has the capability to fully clone voices - including tone, pitch, emotion and prosody. The model also attempts to preserve music, ambient noise, etc. from input audio. However, to mitigate misuse of this technology, we limit the audio history prompts to a limited set of Suno-provided, fully synthetic options to choose from for each language. Specify following the pattern: {lang_code}_speaker_{0-9}.
text_prompt = """
I have a silky smooth voice, and today I will tell you about
the exercise regimen of the common sloth.
"""
audio_array = generate_audio(text_prompt, history_prompt="en_speaker_1")
sloth.webm
Note: since Bark recognizes languages automatically from input text, it is possible to use for example a german history prompt with english text. This usually leads to english audio with a german accent.
👥 Speaker Prompts
You can provide certain speaker prompts such as NARRATOR, MAN, WOMAN, etc. Please note that these are not always respected, especially if a conflicting audio history prompt is given.
text_prompt = """
WOMAN: I would like an oatmilk latte please.
MAN: Wow, that's expensive!
"""
audio_array = generate_audio(text_prompt)
latte.webm
💻 Installation
pip install git+https://github.com/suno-ai/bark.git
or
git clone https://github.com/suno-ai/bark
cd bark && pip install .
🛠️ Hardware and Inference Speed
Bark has been tested and works on both CPU and GPU (pytorch 2.0+, CUDA 11.7 and CUDA 12.0). Running Bark requires running >100M parameter transformer models. On modern GPUs and PyTorch nightly, Bark can generate audio in roughly realtime. On older GPUs, default colab, or CPU, inference time might be 10-100x slower.
If you don't have new hardware available or if you want to play with bigger versions of our models, you can also sign up for early access to our model playground here.
⚙️ Details
Similar to Vall-E and some other amazing work in the field, Bark uses GPT-style models to generate audio from scratch. Different from Vall-E, the initial text prompt is embedded into high-level semantic tokens without the use of phonemes. It can therefore generalize to arbitrary instructions beyond speech that occur in the training data, such as music lyrics, sound effects or other non-speech sounds. A subsequent second model is used to convert the generated semantic tokens into audio codec tokens to generate the full waveform. To enable the community to use Bark via public code we used the fantastic EnCodec codec from Facebook to act as an audio representation.
Below is a list of some known non-speech sounds, but we are finding more every day. Please let us know if you find patterns that work particularly well on Discord!
[laughter]
[laughs]
[sighs]
[music]
[gasps]
[clears throat]
— or ... for hesitations
♪ for song lyrics
capitalization for emphasis of a word
MAN/WOMAN: for bias towards speaker
Supported Languages
Language Status
English (en) ✅
German (de) ✅
Spanish (es) ✅
French (fr) ✅
Hindi (hi) ✅
Italian (it) ✅
Japanese (ja) ✅
Korean (ko) ✅
Polish (pl) ✅
Portuguese (pt) ✅
Russian (ru) ✅
Turkish (tr) ✅
Chinese, simplified (zh) ✅
Мой код, куда нужно интегрировать функциональность:
"import logging
import openai
from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils.exceptions import BadRequest
from aiogram.types import Message, ChatType
import sqlite3
from sqlite3 import Error
from datetime import datetime
from config import *
from ratelimit import limits, sleep_and_retry
import time
import asyncio
openai.api_key = OPENAI_API_KEY
logging.basicConfig(level=logging.INFO)
bot = Bot(token=TELEGRAM_BOT_TOKEN)
dp = Dispatcher(bot)
def sql_connection():
try:
return sqlite3.connect('bot.db')
except Error:
print(Error)
def create_messages_table(con):
try:
cursorObj = con.cursor()
cursorObj.execute(
"CREATE TABLE IF NOT EXISTS messages(id integer PRIMARY KEY, telegram_user_id text, role text, content text, created_at date)")
con.commit()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
# роль по умолчанию (+ изменить в строке 67)
defaultrole = {"role": "system", "content": "Ты - полезный помощник."}
def add_message(con, telegram_user_id, role, message):
try:
cursorObj = con.cursor()
cursorObj.execute(f"SELECT COUNT(*) FROM messages WHERE telegram_user_id = '{telegram_user_id}'")
message_count = cursorObj.fetchone()[0]
if message_count >= 50:
cursorObj.execute(f"DELETE FROM messages WHERE telegram_user_id = '{telegram_user_id}' ORDER BY created_at LIMIT 1")
sqlite_insert_query = f"""INSERT INTO messages
(telegram_user_id, role, content, created_at)
VALUES
('{telegram_user_id}', '{role}', '{message}', '{datetime.now()}');"""
cursorObj.execute(sqlite_insert_query)
con.commit()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
def delete_user_messages(con, user_id):
global defaultrole
try:
cursorObj = con.cursor()
cursorObj.execute(
f"DELETE FROM messages WHERE telegram_user_id = '{user_id}'")
con.commit()
# роль по умолчанию
defaultrole = {"role": "system", "content": "Ты - полезный помощник."}
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
def get_messages(con, telegram_user_id):
try:
cursorObj = con.cursor()
cursorObj.execute(
f'SELECT * FROM messages WHERE telegram_user_id = "{telegram_user_id}"')
return cursorObj.fetchall()
except Error:
print("Ошибка при работе с SQLite", sqlite3.Error)
@limits(calls=5, period=60)
@sleep_and_retry
async def ai(prompt, user_id):
global defaultrole
try:
await asyncio.sleep(1)
messages = [
defaultrole,
]
user_messages = get_messages(db, user_id)
for message in user_messages:
messages.append({"role": message[2], "content": message[3]})
messages.append({"role": "user", "content": prompt})
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
)
add_message(db, user_id, 'user', prompt)
add_message(db, user_id, 'assistant', completion.choices[0].message.content)
return completion.choices[0].message.content
except:
return None
@dp.message_handler(commands=['role'])
async def set_role(message: types.Message):
global defaultrole
received_text = message.text.replace('/role ','')
if received_text.strip() == '':
await bot.send_message(message.chat.id, "Введите текст после команды /role")
return
delete_user_messages(db, message.from_user.id)
defaultrole = {"role": "system", "content": received_text.strip()}
await bot.send_message(message.chat.id, f"Роль изменена:\n{received_text}")
@dp.message_handler(commands=['clear'])
async def send_welcome(message: types.Message):
delete_user_messages(db, message.from_user.id)
await message.reply("История очищена")
@dp.message_handler(commands=['gpt'])
async def echo(message: types.Message):
answer = await ai(message.text[4:], message.from_user.id)
if answer != None:
await message.reply(answer)
print(get_messages(db, message.from_user.id))
else:
await message.reply('Произошла ошибка, очистите историю: /clear')
if __name__ == '__main__':
db = sql_connection()
create_messages_table(db)
executor.start_polling(dp, skip_updates=True)"
|
9a2c277fd2155762a7366e80406d82bd
|
{
"intermediate": 0.3541978597640991,
"beginner": 0.39780157804489136,
"expert": 0.24800057709217072
}
|
3,450
|
I got project description and code that is not doing things that said in programm description.I need you to rewrite my code making it match with description-->import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class TCPPacketServer {
private static int port = 1024;
private static ExecutorService pool = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
pool.execute(new ClientHandler(clientSocket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
String line;
while ((line = br.readLine()) != null && !line.equals("CLOSE")) {
byte[] buffer = new byte[1024];
int bytesRead = clientSocket.getInputStream().read(buffer);
if (bytesRead > 0) {
ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, bytesRead);
ObjectInputStream ois = new ObjectInputStream(bais);
Packet packet = (Packet) ois.readObject();
System.out.println("FROM CLIENT " + clientSocket.getRemoteSocketAddress() + ": Packet SerialNo#" + packet.getSerialNo() + " is received");
Packet responsePacket = new Packet(packet.getSerialNo(), "ACK");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(responsePacket);
byte[] responseBuffer = baos.toByteArray();
ps.write(responseBuffer);
}
}
ps.close();
br.close();
clientSocket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
import java.io.*;
import java.net.*;
public class TCPPacketClient {
private static String[] output = {"--Enter the data packet: "};
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1024);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (!line.equals("CLOSE")) {
System.out.print(output[0]);
line = input.readLine();
int serialNo = 1; // hardcoded for simplicity
Packet packet = new Packet(serialNo, line);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(packet);
byte[] buffer = baos.toByteArray();
ps.write(buffer);
InputStream is = socket.getInputStream();
byte[] responseBuffer = new byte[1024];
int bytesRead = is.read(responseBuffer);
if (bytesRead > 0) {
ByteArrayInputStream bais = new ByteArrayInputStream(responseBuffer, 0, bytesRead);
ObjectInputStream ois = new ObjectInputStream(bais);
Packet responsePacket = (Packet) ois.readObject();
System.out.println("FROM SERVER: Packet SerialNo#" + responsePacket.getSerialNo() + " is received");
}
}
ps.close();
br.close();
socket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.Serializable;
public class Packet implements Serializable {
private int serialNo;
private String data;
public Packet(int serialNo, String data) {
this.serialNo = serialNo;
this.data = data;
}
public String getData() {
return data;
}
public int getSerialNo() {
return serialNo;
}
}
import java.io.*;
import java.net.*;
public class MTServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("--Waiting for client request. New clients pop up!--");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Server: Hello");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Hello");
String response = br.readLine();
System.out.println("Clients: " + response);
ps.println("How are you?");
response = br.readLine();
System.out.println("Clients: " + response);
ps.close();
br.close();
socket.close();
System.out.println("Server: Connection closed");
}
} catch (IOException e) {
System.err.println(e);
}
}
}
import java.io.*;
import java.net.*;
public class Clients {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1024);
System.out.println("--Request sent successfully--");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (!line.equals("CLOSE")) {
System.out.print("Server: ");
line = input.readLine();
ps.println(line);
String response = br.readLine();
System.out.println("Clients: " + response);
}
ps.close();
br.close();
socket.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
---Here is description-->Thisisaclient/servimplementfortransmitpacket.Eachpacketconsistoftwopart;theheaderpartcontainonlithe“serialnumber”andthe“datapart”containamessag(anistringofcharact).``Client''sendapackettotheserverandreceivitacknowledg,thenenteratextandmtserverconvertitintouppercasletterandreturnitback.Whenaclientsenda“CLOSE”messagin``Client''class,both``Client''and``mtserver''termin.Compilallthreefile.Runserverandclientfileintwodifferwindow.1.tcppacketserver.java●Use/**Thegetoutputstream()methodtosendoutthedatathroughthesocketstream**/●Use/**Thegetinputstream()methodtoobtainahandltothesocketstream**/2.tcppacketclient.java●Use/**theinstancofSocketclassusetheaddressofthiscomputandtheportnumber1024**/●Tolearnyourhostnameusecommandbelow:a.>ipconfig/all(Window+R)●Use/**Thegetinputstream()methodtoobtainahandltothesocketstream**/●Use/**Thegetoutputstream()methodtosendoutthedatathroughthesocketstream**/●Usebufferedreadmethod/**toreadfromthekeyboardthedata(Packet)thatneedtobesendtotheserver**/●/**CreatanewinstancofPacketclasswithdataheader,thedata(packet)andpacketnumber**/3.packet.java●privatintserialno;●privatStringdata;publicStringgetdata(){returndata;}publicintgetserialno(){returnserialno;}Step-1:Compiltcppacketserv–Openport…--Step-2:Compiltcppacketcli--Enterthedatapacket:--Step-3:Entercommandtothedatapacket:tcppacketserv--Openport…ReceivFromClientPacketserialno#1andpacketDataisTHISISCLIENT1–tcppacketcli--Enterthedatapacket:thisisClient1FROMSERVER:Packetserialno#1isreceived—Part-2InthispartyouwillcreataClientandServerconnect.Aclientapplicgeneratasocketonitendoftheconnectandattempttoconnectthatsockettoaserver.Whentheconnectisestablish,theserverconstructasocketobjectonitendofthecommunic.Theclientandservercannowcommunicbywritetoandreadfromthesocketusethejava.netpackag.Use(Mandatori):●printstreamps=newprintstream(socket.getoutputstream());”tosendamessagtoClientfromServer.Use(Mandatori):●bufferedreadbr=newbufferedread(newinputstreamread(socket.getinputstream()));toreceivthemessagfrom``Client''Step-1:Compilserve.javaclass--WaitforclientrequestNewclientpopup!Server:--Step-2:Compilclient.javaclass--Requestsentsuccess--Step-3:Clientandmtserverconnectmtserver--WaitforclientrequestNewclientpopup!Server:HelloClient:HiServer:Howareyou?Client:Iamfine—Client--RequestsentsuccessServer:HelloClient:HiServer:Howareyou?Client:Iamfine--YoucantseeUMLdiagramsoIwriteithere-->classPocket:-data:String-serialno:int+Packet(serialno:int,data:String)+getdata():String+getserialno():intPacketclasshavetousejava.io.serializ<<util>>tcppacketservmain(argv:String[]):void<<util>>mtservermain(argLString[]):void<<util>>Clientmain(arg:String[]):void<<util>>tcppacketcli-output:String[]-host:inetaddress+main(argv:String[]):voidTherehavetobe5classnametcppacketservmtserverClienttcppacketcliPocketclass
|
b4795a02dec5a1d1a7f49d5c2bad907a
|
{
"intermediate": 0.38296905159950256,
"beginner": 0.48872992396354675,
"expert": 0.12830109894275665
}
|
3,451
|
hi
|
1cf0b843c5514d27f0c47f6a6a1ce6c1
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
3,452
|
write vba code to calculate ichimokou lines with high and low data in column b and c. write tenken in column m kijun in column n and span a in column o and span b in column p
|
eadba5c34eacd417a2514c621d4f5c91
|
{
"intermediate": 0.41322463750839233,
"beginner": 0.278512179851532,
"expert": 0.3082631230354309
}
|
3,453
|
Your code doing not right thing. When you run “TCPPacketServer” it have to write “Opening port…” and after when you run"TCPPacketClient" it have to write “Enter the data packet:” after you write anything like "Client1" it will return this info to “TCPPacketServer” and "TCPPacketServer" will write "Recieving From Clients Packet’s serialNo#1
and packet’s Data is CLIENT1"
it have to look like this-->
running of TCPPacketServer:
Opening port…
Recieving From Clients Packet’s serialNo#1
and packet’s Data is THIS IS CLIENT1
Recieving From Clients Packet’s serialNo#1
and packet’s Data is THIS IS CLIENT2
running of TCPPacketClient:
Enter the data packet: this is Client1
FROM SERVER:Packet SerialNo#1 is recieved
Enter the data packet: this is Client2
FROM SERVER:Packet SerialNo#2 is recieved
NOTE: that "THIS IS CLIENT1" and "THIS IS CLIENT2" is info from "Clients" class and anything could be written on their places
Here is the code of program that you have to fix-->import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class TCPPacketServer {
private static int port = 1024;
private static ExecutorService pool = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
pool.execute(new ClientHandler(clientSocket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try {
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
while (true) {
InputStream is = clientSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = is.read(buffer);
if (bytesRead > 0) {
ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, bytesRead);
ObjectInputStream ois = new ObjectInputStream(bais);
Packet packet = (Packet) ois.readObject();
System.out.println("FROM CLIENT " + clientSocket.getRemoteSocketAddress() + ": Packet SerialNo#" + packet.getSerialNo() + " is received");
if (packet.getData().equals("CLOSE")) {
break;
}
Packet responsePacket = new Packet(packet.getSerialNo(), packet.getData().toUpperCase());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(responsePacket);
byte[] responseBuffer = baos.toByteArray();
ps.write(responseBuffer);
}
}
ps.close();
clientSocket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
import java.io.*;
import java.net.*;
public class TCPPacketClient {
private static String[] output = {"–Enter the data packet: "};
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1024);
PrintStream ps = new PrintStream(socket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
int serialNo = 1;
while (!line.equals("CLOSE")) {
System.out.print(output[0]);
line = input.readLine();
Packet packet = new Packet(serialNo++, line);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(packet);
byte[] buffer = baos.toByteArray();
ps.write(buffer);
InputStream is = socket.getInputStream();
byte[] responseBuffer = new byte[1024];
int bytesRead = is.read(responseBuffer);
if (bytesRead > 0) {
ByteArrayInputStream bais = new ByteArrayInputStream(responseBuffer, 0, bytesRead);
ObjectInputStream ois = new ObjectInputStream(bais);
Packet responsePacket = (Packet) ois.readObject();
System.out.println("FROM SERVER: Packet SerialNo#" + responsePacket.getSerialNo() + ", Data: " + responsePacket.getData());
}
}
ps.close();
socket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.Serializable;
public class Packet implements Serializable {
private int serialNo;
private String data;
public Packet(int serialNo, String data) {
this.serialNo = serialNo;
this.data = data;
}
public String getData() {
return data;
}
public int getSerialNo() {
return serialNo;
}
}import java.io.*;
import java.net.*;
public class MTServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Waiting for client request…");
Socket socket = serverSocket.accept();
System.out.println("New client is pop up!");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
String response;
while (true) {
System.out.print("Server: ");
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
ps.println(line);
response = br.readLine();
if (response.equals("CLOSE")) {
break;
}
System.out.println("Clients: " + response);
}
ps.close();
br.close();
socket.close();
System.out.println("End of conversation");
} catch (IOException e) {
System.err.println(e);
}
}
}import java.io.*;
import java.net.*;
public class Clients {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8080);
System.out.println("Request sent successfully");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
String response;
while (true) {
response = br.readLine();
System.out.println("Server: " + response);
System.out.print("Clients: ");
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
ps.println(line);
if (line.equals("CLOSE")) {
break;
}
}
ps.close();
br.close();
socket.close();
System.out.println("End of conversation");
} catch (IOException e) {
System.err.println(e);
}
}
}
|
1e86dd4286af623fb28eeff533bdebdc
|
{
"intermediate": 0.3247829079627991,
"beginner": 0.521564781665802,
"expert": 0.15365229547023773
}
|
3,454
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- 指示のない部分のコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "followers_count"と'like_count'を左縦軸に表示し、'comments_count'を右縦軸に表示し、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けしグラフ背景色はダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーグラフ"を、ページの最上部に横幅いっぱいに表示する機能を作成する
- "サマリーグラフ"の'like_count'と'comments_count'の数は、jsonファイル内の過去すべてのデータを参照し、"対象日とその前日データと比較して増加した数"を算出し日を追って列挙して表示する
- 'like_count'を左縦軸に表示し、'comments_count'を右縦軸に表示し、グラフデータを"オレンジ"・"緑"で色分けしグラフ背景をダークにした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"は、jsonファイル内の過去すべてのデータを参照し、各投稿IDの'like_count'と'comments_count'を、それぞれ"対象日とその前日データとの差分"を算出し日付を追って列挙し、各ID別の投稿コンテナに個別のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
4712b6709aab96f97190ff9b220752ad
|
{
"intermediate": 0.3471693694591522,
"beginner": 0.4591856896877289,
"expert": 0.1936449408531189
}
|
3,455
|
In sheet Providers, Column C contails Text Names for companies. Colum D of the same row is the Name of the Sheet that holds the companies information.
When I click on a sheet name in Column D, it opens up the associated companies sheet.
I would like the associated companies sheet, to identify the cell in Column D of Sheet Providers that I last clicked on and copy the value of Column C of the same row into the next available empty cell in column A of the companies sheet and also copy from the same row in Sheet Providers the value in Column B into Column D of the same row where it pasted the value into Column A.
|
7cd6b6d008da4d4bdaf15fb575cf691a
|
{
"intermediate": 0.45145243406295776,
"beginner": 0.24101704359054565,
"expert": 0.3075305223464966
}
|
3,456
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
def basic_info():
config = dict()
config[“access_token”] = st.secrets[“access_token”]
config[‘instagram_account_id’] = st.secrets.get(“instagram_account_id”, “”)
config[“version”] = ‘v16.0’
config[“graph_domain”] = ‘https://graph.facebook.com/’
config[“endpoint_base”] = config[“graph_domain”] + config[“version”] + ‘/’
return config
def InstaApiCall(url, params, request_type):
if request_type == ‘POST’:
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res[“url”] = url
res[“endpoint_params”] = params
res[“endpoint_params_pretty”] = json.dumps(params, indent=4)
res[“json_data”] = json.loads(req.content)
res[“json_data_pretty”] = json.dumps(res[“json_data”], indent=4)
return res
def getUserMedia(params, pagingUrl=‘’):
Params = dict()
Params[‘fields’] = ‘id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count’
Params[‘access_token’] = params[‘access_token’]
if not params[‘endpoint_base’]:
return None
if pagingUrl == ‘’:
url = params[‘endpoint_base’] + params[‘instagram_account_id’] + ‘/media’
else:
url = pagingUrl
return InstaApiCall(url, Params, ‘GET’)
def getUser(params):
Params = dict()
Params[‘fields’] = ‘followers_count’
Params[‘access_token’] = params[‘access_token’]
if not params[‘endpoint_base’]:
return None
url = params[‘endpoint_base’] + params[‘instagram_account_id’]
return InstaApiCall(url, Params, ‘GET’)
def saveCount(count, filename):
with open(filename, ‘w’) as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, ‘r’) as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout=“wide”)
params = basic_info()
count_filename = “count.json”
if not params[‘instagram_account_id’]:
st.write(‘.envファイルでinstagram_account_idを確認’)
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write(‘.envファイルでaccess_tokenを確認’)
else:
posts = response[‘json_data’][‘data’][::-1]
user_data = user_response[‘json_data’]
followers_count = user_data.get(‘followers_count’, 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime(‘%Y-%m-%d’)
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get(‘followers_count’, followers_count)
st.markdown(f"<h4 style=‘font-size:1.2em;’>Follower: {followers_count} ({‘+’ if follower_diff >= 0 else ‘’}{follower_diff})</h4>“, unsafe_allow_html=True)
show_description = st.checkbox(“キャプションを表示”)
show_summary_graph = st.checkbox(“サマリーグラフを表示”)
show_like_comment_graph = st.checkbox(“いいね/コメント数グラフを表示”)
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%Y-%m-%d’)
if today not in count:
count[today] = {}
count[today][‘followers_count’] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%H:%M’) == ‘23:59’:
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post[‘like_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘like_count’, post[‘like_count’])
comment_count_diff = post[‘comments_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘comments_count’, post[‘comments_count’])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
like_diff_sum = 0
comment_diff_sum = 0
for date in sorted(count.keys()):
daily_like_diff = 0
daily_comment_diff = 0
for post_id in count[date]:
if post_id == “followers_count”:
continue
daily_like_diff += count[date][post_id][“like_count”] - count.get(datetime.datetime.strptime(date, “%Y-%m-%d”).strftime(”%Y-%m-%d"), {}).get(post_id, {}).get(“like_count”, count[date][post_id][“like_count”])
daily_comment_diff += count[date][post_id][“comments_count”] - count.get(datetime.datetime.strptime(date, “%Y-%m-%d”).strftime(“%Y-%m-%d”), {}).get(post_id, {}).get(“comments_count”, count[date][post_id][“comments_count”])
like_diff_sum += daily_like_diff
comment_diff_sum += daily_comment_diff
if show_summary_graph:
plt.xlabel(“Date”)
plt.ylabel(“Count”)
plt.title(‘Summary’)
sns.lineplot(x=date.strftime(“%m/%d”), y=like_diff_sum, label=‘like_count’, color=‘skyblue’)
sns.lineplot(x=date.strftime(“%m/%d”), y=comment_diff_sum, label=‘comments_count’, color=‘green’)
sns.lineplot(x=date.strftime(“%m/%d”), y=(follower_diff / (like_diff_sum + comment_diff_sum)), label=‘follower_diff’, color=‘orange’)
if show_summary_graph:
plt.legend(loc=‘best’)
plt.gca().set_facecolor(‘#121212’)
plt.show()
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post[‘media_url’], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post[‘timestamp’], ‘%Y-%m-%dT%H:%M:%S%z’).astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%Y-%m-%d %H:%M:%S’)}“)
like_count_diff = post[‘like_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘like_count’, post[‘like_count’])
comment_count_diff = post[‘comments_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘comments_count’, post[‘comments_count’])
st.markdown(
f"👍: {post[‘like_count’]} <span style=‘{’’ if like_count_diff != max_like_diff or max_like_diff == 0 else ‘color:green;’}‘>({’+’ if like_count_diff >= 0 else ‘’}{like_count_diff})</span>”
f"\n💬: {post[‘comments_count’]} <span style=‘{’’ if comment_count_diff != max_comment_diff or max_comment_diff == 0 else ‘color:green;’}‘>({’+’ if comment_count_diff >= 0 else ‘’}{comment_count_diff})</span>“,
unsafe_allow_html=True)
caption = post[‘caption’]
if caption is not None:
caption = caption.strip()
if “[Description]” in caption:
caption = caption.split(”[Description]“)[1].lstrip()
if “[Tags]” in caption:
caption = caption.split(”[Tags]“)[0].rstrip()
caption = caption.replace(”#“, “”)
caption = caption.replace(”[model]“, “👗”)
caption = caption.replace(”[Equip]“, “📷”)
caption = caption.replace(”[Develop]“, “🖨”)
if show_description:
st.write(caption or “No caption provided”)
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or “No caption provided”)
if show_like_comment_graph:
post_like_diffs = []
post_comment_diffs = []
post_dates = []
for date in sorted(count.keys()):
if post[‘id’] in count[date]:
date_like_diff = count[date][post[‘id’]][‘like_count’] - count.get(datetime.datetime.strptime(date, “%Y-%m-%d”).strftime(”%Y-%m-%d"), {}).get(post[‘id’], {}).get(“like_count”, count[date][post[‘id’]][‘like_count’])
date_comment_diff = count[date][post[‘id’]][‘comments_count’] - count.get(datetime.datetime.strptime(date, “%Y-%m-%d”).strftime(“%Y-%m-%d”), {}).get(post[‘id’], {}).get(“comments_count”, count[date][post[‘id’]][‘comments_count’])
post_like_diffs.append(date_like_diff)
post_comment_diffs.append(date_comment_diff)
post_dates.append(date.strftime(“%m/%d”))
post_data = pd.DataFrame({
“Date”: pd.to_datetime(post_dates),
“like_count”: post_like_diffs,
“comments_count”: post_comment_diffs
})
fig, ax1 = plt.subplots()
plt.title(‘Like/Comment Count’)
ax1.set_xlabel(‘Date’)
ax1.set_ylabel(‘Like’, color=‘C1’)
ax1.plot(post_data[“Date”], post_data[“like_count”], color=‘C1’)
ax1.tick_params(axis=‘y’, labelcolor=‘C1’)
ax2 = ax1.twinx()
ax2.set_ylabel(‘Comment’, color=‘C2’)
ax2.plot(post_data[“Date”], post_data[“comments_count”], color=‘C2’)
ax2.tick_params(axis=‘y’, labelcolor=‘C2’)
fig.tight_layout()
plt.gca().set_facecolor(‘#121212’)
plt.show()
count[today][post[‘id’]] = {‘like_count’: post[‘like_count’], ‘comments_count’: post[‘comments_count’]}
saveCount(count, count_filename)
'''
上記のコードを実行すると、下記のエラーが表示されます。改修したコード全文を表示してください
‘’'
AttributeError: ‘str’ object has no attribute ‘strftime’
Traceback:
File “/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py”, line 565, in _run_script
exec(code, module.dict)
File “/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py”, line 189, in <module>
post_dates.append(date.strftime(“%m/%d”))
AttributeError: ‘str’ object has no attribute ‘strftime’
Traceback:
File “/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py”, line 565, in _run_script
exec(code, module.dict)
File “/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py”, line 140, in <module>
sns.lineplot(x=date.strftime(“%m/%d”), y=like_diff_sum, label=‘like_count’, color=‘skyblue’)
|
9b8158378b4755d4167295e37088fe48
|
{
"intermediate": 0.31107547879219055,
"beginner": 0.39493420720100403,
"expert": 0.2939903736114502
}
|
3,457
|
поправте код и Создайте новый признак confirmed_per_hundred, который покажет процентное отношение заболевших вирусом к общему числу населения в странах ().
Постройте тепловую карту, которая покажет, как росло число заболевших в процентах от общего числа населения (confirmed_per_hundred) в странах из таблицы croped_covid_df.
import pandas as pd
covid_data = pd.read_csv('covid_data.csv')
vaccinations_data = pd.read_csv('country_vaccinations.csv')
vaccinations_data = vaccinations_data[
['country', 'date', 'total_vaccinations',
'people_vaccinated', 'people_vaccinated_per_hundred',
'people_fully_vaccinated', 'people_fully_vaccinated_per_hundred',
'daily_vaccinations', 'vaccines']
]
vaccinations_data['date'] = pd.to_datetime(vaccinations_data['date'])
#Группируем таблицу по дате и названию страны и рассчитываем суммарные показатели по всем регионам.
covid_data = covid_data.groupby(
['date', 'country'],
as_index=False
)[['confirmed', 'deaths', 'recovered']].sum()
#Преобразуем даты в формат datetime с помощью функции pd.to_datetime()
covid_data['date'] = pd.to_datetime(covid_data['date'])
#Создадим признак больных на данный момент (active). Для этого вычтем из общего числа зафиксированных случаев число смертей и число выздоровевших пациентов:
covid_data['active'] = covid_data['confirmed'] - covid_data['deaths'] - covid_data['recovered']
#Создадим признак ежедневного прироста числа заболевших, умерших и выздоровевших людей. Для этого отсортируем данные по датам, а затем по названиям стран. После этого произведём группировку по странам и рассчитаем разницу между «вчера и сегодня» с помощью метода diff()
covid_data = covid_data.sort_values(by=['country', 'date'])
covid_data['daily_confirmed'] = covid_data.groupby('country')['confirmed'].diff()
covid_data['daily_deaths'] = covid_data.groupby('country')['deaths'].diff()
covid_data['daily_recovered'] = covid_data.groupby('country')['recovered'].diff()
start_date = covid_data['date'].min()
end_date = covid_data['date'].max()
# Приведём столбец date к типу datetime и выберем только нужные строки из таблицы vaccinations_data
vaccinations_data['date'] = pd.to_datetime(vaccinations_data['date'])
vaccinations_data = vaccinations_data[(vaccinations_data['date'] >= start_date) & (vaccinations_data['date'] <= end_date)]
# Объединим таблицы covid_data и vaccinations_data по столбцам date и country
#covid_df = covid_data.merge(vaccinations_data, on=['date', 'country'])
covid_df = pd.merge(covid_data, vaccinations_data, on=['date', 'country'],how='left')
# Создаём столбцы death_rate и recover_rate
covid_df['death_rate'] = covid_df['deaths'] / covid_df['confirmed'] * 100
covid_df['recover_rate'] = covid_df['recovered'] / covid_df['confirmed'] * 100
|
41cf3c3010479f69df024d249ae94c9b
|
{
"intermediate": 0.3143182396888733,
"beginner": 0.5253256559371948,
"expert": 0.1603560745716095
}
|
3,458
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_graph = st.checkbox("サマリーグラフを表示")
show_like_comment_graph = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
like_diff_sum = 0
comment_diff_sum = 0
for date in sorted(count.keys()):
date = datetime.datetime.strptime(date, '%Y-%m-%d')
daily_like_diff = 0
daily_comment_diff = 0
for post_id in count[date]:
if post_id == "followers_count":
continue
daily_like_diff += count[date][post_id]["like_count"] - count.get(date.strftime('%Y-%m-%d'), {}).get(post_id, {}).get("like_count", count[date][post_id]["like_count"])
daily_comment_diff += count[date][post_id]["comments_count"] - count.get(date.strftime('%Y-%m-%d'), {}).get(post_id, {}).get("comments_count", count[date][post_id]["comments_count"])
like_diff_sum += daily_like_diff
comment_diff_sum += daily_comment_diff
if show_summary_graph:
plt.xlabel("Date")
plt.ylabel("Count")
plt.title('Summary')
sns.lineplot(x=date.strftime('%m/%d'), y=like_diff_sum, label='like_count', color='skyblue')
sns.lineplot(x=date.strftime('%m/%d'), y=comment_diff_sum, label='comments_count', color='green')
sns.lineplot(x=date.strftime('%m/%d'), y=(follower_diff / (like_diff_sum + comment_diff_sum)), label='follower_diff', color='orange')
if show_summary_graph:
plt.legend(loc='best')
plt.gca().set_facecolor('#121212')
plt.show()
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({ '+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({ '+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_like_comment_graph:
post_like_diffs = []
post_comment_diffs = []
post_dates = []
for date in sorted(count.keys()):
date = datetime.datetime.strptime(date, '%Y-%m-%d')
if post['id'] in count[date]:
date_like_diff = count[date][post['id']]['like_count'] - count.get(date.strftime('%Y-%m-%d'), {}).get(post['id'], {}).get("like_count", count[date][post['id']]['like_count'])
date_comment_diff = count[date][post['id']]['comments_count'] - count.get(date.strftime('%Y-%m-%d'), {}).get(post['id'], {}).get("comments_count", count[date][post['id']]['comments_count'])
post_like_diffs.append(date_like_diff)
post_comment_diffs.append(date_comment_diff)
post_dates.append(date.strftime('%m/%d'))
post_data = pd.DataFrame({
"Date": pd.to_datetime(post_dates),
"like_count": post_like_diffs,
"comments_count": post_comment_diffs
})
fig, ax1 = plt.subplots()
plt.title('Like/Comment Count')
ax1.set_xlabel('Date')
ax1.set_ylabel('Like', color='C1')
ax1.plot(post_data["Date"], post_data["like_count"], color='C1')
ax1.tick_params(axis='y', labelcolor='C1')
ax2 = ax1.twinx()
ax2.set_ylabel('Comment', color='C2')
ax2.plot(post_data["Date"], post_data["comments_count"], color='C2')
ax2.tick_params(axis='y', labelcolor='C2')
fig.tight_layout()
plt.gca().set_facecolor('#121212')
plt.show()
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを実行すると、下記のエラーが表示されます。改修したコード全文を表示してください
'''
2023-04-30 19:43:59.926 Uncaught app exception
Traceback (most recent call last):
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
exec(code, module.__dict__)
File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 130, in <module>
for post_id in count[date]:
KeyError: datetime.datetime(2023, 4, 24, 0, 0)
issing
|
faa2016f5291ccb132f6f16b76ea9e77
|
{
"intermediate": 0.36617717146873474,
"beginner": 0.3422478437423706,
"expert": 0.29157495498657227
}
|
3,459
|
snake game, pyhon
|
fd32748341ea5361b578fa5722f0d5cb
|
{
"intermediate": 0.3000521957874298,
"beginner": 0.43803101778030396,
"expert": 0.26191678643226624
}
|
3,460
|
I have the following Oracle SQL query: WITH lata(rok, liczba) AS (
SELECT EXTRACT(YEAR FROM zatrudniony), COUNT(id_prac) FROM pracownicy GROUP BY EXTRACT(YEAR FROM zatrudniony))
SELECT * FROM lata
ORDER BY 2 DESC;
|
0f19daacee9cff6150860fa6cff1e50b
|
{
"intermediate": 0.4308357834815979,
"beginner": 0.3024994134902954,
"expert": 0.2666647732257843
}
|
3,461
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_graph = st.checkbox("サマリーグラフを表示")
show_like_comment_graph = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
like_diff_sum = 0
comment_diff_sum = 0
for date_str in sorted(count.keys()):
date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
daily_like_diff = 0
daily_comment_diff = 0
for post_id in count[date_str]:
if post_id == "followers_count":
continue
daily_like_diff += count[date_str][post_id]["like_count"] - count.get(date.strftime('%Y-%m-%d'), {}).get(post_id, {}).get("like_count", count[date_str][post_id]["like_count"])
daily_comment_diff += count[date_str][post_id]["comments_count"] - count.get(date.strftime('%Y-%m-%d'), {}).get(post_id, {}).get("comments_count", count[date_str][post_id]["comments_count"])
like_diff_sum += daily_like_diff
comment_diff_sum += daily_comment_diff
if show_summary_graph:
plt.xlabel("Date")
plt.ylabel("Count")
plt.title('Summary')
sns.lineplot(x=date.strftime('%m/%d'), y=like_diff_sum, label='like_count', color='skyblue')
sns.lineplot(x=date.strftime('%m/%d'), y=comment_diff_sum, label='comments_count', color='green')
sns.lineplot(x=date.strftime('%m/%d'), y=(follower_diff / (like_diff_sum + comment_diff_sum)), label='follower_diff', color='orange')
if show_summary_graph:
plt.legend(loc='best')
plt.gca().set_facecolor('#121212')
plt.show()
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({ '+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({ '+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_like_comment_graph:
post_like_diffs = []
post_comment_diffs = []
post_dates = []
for date_str in sorted(count.keys()):
date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
if post['id'] in count[date_str]:
date_like_diff = count[date_str][post['id']]['like_count'] - count.get(date.strftime('%Y-%m-%d'), {}).get(post['id'], {}).get("like_count", count[date_str][post['id']]['like_count'])
date_comment_diff = count[date_str][post['id']]['comments_count'] - count.get(date.strftime('%Y-%m-%d'), {}).get(post['id'], {}).get("comments_count", count[date_str][post['id']]['comments_count'])
post_like_diffs.append(date_like_diff)
post_comment_diffs.append(date_comment_diff)
post_dates.append(date.strftime('%m/%d'))
post_data = pd.DataFrame({
"Date": pd.to_datetime(post_dates),
"like_count": post_like_diffs,
"comments_count": post_comment_diffs
})
fig, ax1 = plt.subplots()
plt.title('Like/Comment Count')
ax1.set_xlabel('Date')
ax1.set_ylabel('Like', color='C1')
ax1.plot(post_data["Date"], post_data["like_count"], color='C1')
ax1.tick_params(axis='y', labelcolor='C1')
ax2 = ax1.twinx()
ax2.set_ylabel('Comment', color='C2')
ax2.plot(post_data["Date"], post_data["comments_count"], color='C2')
ax2.tick_params(axis='y', labelcolor='C2')
fig.tight_layout()
plt.gca().set_facecolor('#121212')
plt.show()
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- 修正済みのコード全体を省略せずに表示する
- 指示のないコードの改変はしない
- "caption = post['caption']"以降のブロックについては改変しない
'''
OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-04-30 00:00:00
Traceback:
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
exec(code, module.__dict__)
File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 194, in <module>
"Date": pd.to_datetime(post_dates),
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/pandas/core/tools/datetimes.py", line 1076, in to_datetime
result = convert_listlike(arg, format)
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/pandas/core/tools/datetimes.py", line 402, in _convert_listlike_datetimes
result, tz_parsed = objects_to_datetime64ns(
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/pandas/core/arrays/datetimes.py", line 2242, in objects_to_datetime64ns
raise err
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/pandas/core/arrays/datetimes.py", line 2224, in objects_to_datetime64ns
result, tz_parsed = tslib.array_to_datetime(
File "pandas/_libs/tslib.pyx", line 381, in pandas._libs.tslib.array_to_datetime
File "pandas/_libs/tslib.pyx", line 608, in pandas._libs.tslib.array_to_datetime
File "pandas/_libs/tslib.pyx", line 604, in pandas._libs.tslib.array_to_datetime
File "pandas/_libs/tslib.pyx", line 559, in pandas._libs.tslib.array_to_datetime
File "pandas/_libs/tslibs/conversion.pyx", line 517, in pandas._libs.tslibs.conversion.convert_datetime_to_tsobject
File "pandas/_libs/tslibs/np_datetime.pyx", line 120, in pandas._libs.tslibs.np_datetime.check_dts_bounds
'''
ValueError: Could not interpret value `04/24` for parameter `x`
Traceback:
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
exec(code, module.__dict__)
File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 141, in <module>
sns.lineplot(x=date.strftime('%m/%d'), y=like_diff_sum, label='like_count', color='skyblue')
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/seaborn/relational.py", line 618, in lineplot
p = _LinePlotter(
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/seaborn/relational.py", line 365, in __init__
super().__init__(data=data, variables=variables)
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/seaborn/_oldcore.py", line 640, in __init__
self.assign_variables(data, variables)
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/seaborn/_oldcore.py", line 701, in assign_variables
plot_data, variables = self._assign_variables_longform(
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/seaborn/_oldcore.py", line 938, in _assign_variables_longform
raise ValueError(err)
|
94b1e3c51cc1bbcb769942eb9a504801
|
{
"intermediate": 0.3410457372665405,
"beginner": 0.3692958950996399,
"expert": 0.28965842723846436
}
|
3,462
|
fivem scripting Working on a Phone NUI
How would I make it so I've got a png of the phone border and then the phone contents inside the border
|
a52cb1109d48c2590773b1c390e290dc
|
{
"intermediate": 0.3703339397907257,
"beginner": 0.2177131623029709,
"expert": 0.4119529128074646
}
|
3,463
|
what is the null space of a matrix?
|
f130b63fde3e11846c4920a983d38d6c
|
{
"intermediate": 0.30644679069519043,
"beginner": 0.33562058210372925,
"expert": 0.3579326272010803
}
|
3,464
|
Добавь в скрипт отображении времени на записи в HH:MM:SS.mmm
И чтоб цвет надписи контрастировал на белом фоне
#!/bin/bash -e
while getopts "mnhv" o
do
case "$o" in
(\?) echo "Invalid option: -$OPTARG" >&2 ;;
(h) less $(readlink -f $(dirname $0))/README.md; exit;;
(v) verbose="";; # funnily ffmpeg is verbose by default
(*) break;;
esac
done
shift $((OPTIND - 1))
lockfile=/tmp/r2d2
if test -f $lockfile
then
pid=$(awk '{print $1}' $lockfile)
if kill -0 $pid
then
kill -INT $pid
echo Killed $(cat $lockfile)
logger x11captured: $(du -h $(awk '{print $2}' $lockfile))
rm $lockfile
exit
else
rm $lockfile
fi
fi
#output="$(dirname $(readlink -f $0))/$(date +%Y-%m-%d)/${1:-$(date +%s)}.mkv"
output="/home/samoylov/mh/videos/screencast/$(date +%Y-%m-%d)/${1:-$(date +%s)}.mov"
mkdir -p $(dirname $output)
# Only create RAW file if one does not exist
if test -f "$output"
then
echo $output already exists
logger $(basename $0): $output already exists
exit 1
fi
die() { echo "$@"; exit 1; }
require() { which $1 &> /dev/null; }
for prg in xdpyinfo ffmpeg; do
require $prg || die "needs ${prg} installed"
done
res="$(xdpyinfo | awk '/dimensions:/ { print $2; exit }')"
# https://trac.ffmpeg.org/wiki/Capture/Desktop
#FFREPORT=file=/tmp/$(basename $output).log ffmpeg -report -hide_banner -loglevel quiet \
# -f x11grab -video_size $res -i $DISPLAY -f pulse -i default -acodec pcm_s16le -c:v lib#x264 \
# $output &
# https://trac.ffmpeg.org/wiki/Capture/Desktop
X11GRAB=$(xrectsel "-f x11grab -s %wx%h -i :0.0+%x,%y") || exit -1
FFREPORT=file=/tmp/$(basename $output).log ffmpeg -report -hide_banner -loglevel quiet \
-framerate 24 $X11GRAB -f alsa -ac 2 -i hw:0 \
$output &
echo "$! $(readlink -f $output)" > $lockfile
echo -e "\033[1;34m$0\033[m Capturing $res to $output kill $(awk '{print $1}' $lockfile) to kill capture or run $0 again"
|
36260e55e69b0d9a869ec9ee05b4ec16
|
{
"intermediate": 0.32643330097198486,
"beginner": 0.47495147585868835,
"expert": 0.1986151784658432
}
|
3,465
|
Добавь в скрипт отображении времени на записи в HH:MM:SS.mmm
И чтоб цвет надписи контрастировал на белом фоне
#!/bin/bash -e
while getopts "mnhv" o
do
case "$o" in
(\?) echo "Invalid option: -$OPTARG" >&2 ;;
(h) less $(readlink -f $(dirname $0))/README.md; exit;;
(v) verbose="";; # funnily ffmpeg is verbose by default
(*) break;;
esac
done
shift $((OPTIND - 1))
lockfile=/tmp/r2d2
if test -f $lockfile
then
pid=$(awk '{print $1}' $lockfile)
if kill -0 $pid
then
kill -INT $pid
echo Killed $(cat $lockfile)
logger x11captured: $(du -h $(awk '{print $2}' $lockfile))
rm $lockfile
exit
else
rm $lockfile
fi
fi
#output="$(dirname $(readlink -f $0))/$(date +%Y-%m-%d)/${1:-$(date +%s)}.mkv"
output="/home/samoylov/mh/videos/screencast/$(date +%Y-%m-%d)/${1:-$(date +%s)}.mov"
mkdir -p $(dirname $output)
# Only create RAW file if one does not exist
if test -f "$output"
then
echo $output already exists
logger $(basename $0): $output already exists
exit 1
fi
die() { echo "$@"; exit 1; }
require() { which $1 &> /dev/null; }
for prg in xdpyinfo ffmpeg; do
require $prg || die "needs ${prg} installed"
done
res="$(xdpyinfo | awk '/dimensions:/ { print $2; exit }')"
# https://trac.ffmpeg.org/wiki/Capture/Desktop
#FFREPORT=file=/tmp/$(basename $output).log ffmpeg -report -hide_banner -loglevel quiet \
# -f x11grab -video_size $res -i $DISPLAY -f pulse -i default -acodec pcm_s16le -c:v lib#x264 \
# $output &
# https://trac.ffmpeg.org/wiki/Capture/Desktop
X11GRAB=$(xrectsel "-f x11grab -s %wx%h -i :0.0+%x,%y") || exit -1
FFREPORT=file=/tmp/$(basename $output).log ffmpeg -report -hide_banner -loglevel quiet \
-framerate 24 $X11GRAB -f alsa -ac 2 -i hw:0 \
$output &
echo "$! $(readlink -f $output)" > $lockfile
echo -e "\033[1;34m$0\033[m Capturing $res to $output kill $(awk '{print $1}' $lockfile) to kill capture or run $0 again"
|
36744df7e841ed7cf3fec5e6cf0904b3
|
{
"intermediate": 0.32643330097198486,
"beginner": 0.47495147585868835,
"expert": 0.1986151784658432
}
|
3,466
|
I want PPT about PMU
|
ebfa867c845ed635ee3c3d07a2bb8fb1
|
{
"intermediate": 0.2637803256511688,
"beginner": 0.30047884583473206,
"expert": 0.43574079871177673
}
|
3,467
|
def plot_accuracy_loss(history):
"""
Plot the accuracy and the loss during the training of the nn.
"""
fig = plt.figure(figsize=(10,5))
# Plot accuracy
plt.subplot(221)
plt.plot(history.history['acc'],'bo--', label = "acc")
plt.plot(history.history['val_acc'], 'ro--', label = "val_acc")
plt.title("train_acc vs val_acc")
plt.ylabel("accuracy")
plt.xlabel("epochs")
plt.legend()
# Plot loss function
plt.subplot(222)
plt.plot(history.history['loss'],'bo--', label = "loss")
plt.plot(history.history['val_loss'], 'ro--', label = "val_loss")
plt.title("train_loss vs val_loss")
plt.ylabel("loss")
plt.xlabel("epochs")
plt.legend()
plt.show()
|
6d59deb0632700229f47c08236715980
|
{
"intermediate": 0.417248398065567,
"beginner": 0.3318325877189636,
"expert": 0.25091904401779175
}
|
3,468
|
import random
from PIL import Image
# Define the artists and their monthly Spotify listeners
artists = {
"YoungBoy Never Broke Again": {"image": " C:\Users\elias\PycharmProjects\pythonProject2 pictures pillow\image\image lil_baby.jpg", "listeners": 18212921},
"Young M.A": {"image": " C:\Users\elias\PycharmProjects\pythonProject2 pictures pillow\image\image lil_durk.jpg", "listeners": 2274306},
"Young Nudy": {"image": " C:\Users\elias\PycharmProjects\pythonProject2 pictures pillow\image\image lil_keed.jpg", "listeners": 7553116},
}
# Get the keys of the artists dictionary
keys = list(artists.keys())
# Initialize the score
score = 0
while True:
# Choose two random artists
firstartist, secondartist = random.sample(keys, 2)
# Load and show the images for the two artists
firstartistimg = Image.open(artists[firstartist]["image"])
secondartistimg = Image.open(artists[secondartist]["image"])
firstartistimg.show()
secondartistimg.show()
# Get the user's guess
guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {firstartist} or 2. {secondartist}? ")
guess_lower = guess.strip().lower()
# Check if the user wants to quit
if guess_lower == 'quit':
print("Thanks for playing!")
break
# Check if the user's input is valid
elif guess_lower not in ['1', '2', firstartist.lower(), secondartist.lower()]:
print("Invalid input. Please enter the name of one of the two artists, type 'quit' to end the game or enter 1 or 2 to make a guess.")
# Check if the user's guess is correct
elif guess_lower == firstartist.lower() or guess_lower == '1' and artists[firstartist]["listeners"] > artists[secondartist]["listeners"]:
print(f"You guessed correctly! {firstartist} had \033[1m{artists[firstartist]['listeners'] / 1e6:.1f}M\033[0m monthly Spotify listeners and {secondartist} has {artists[secondartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.")
score += 1
print(f"\nYour score is {score}.")
continue
elif guess_lower == secondartist.lower() or guess_lower == '2' and artists[secondartist]["listeners"] > artists[firstartist]["listeners"]:
print(f"You guessed correctly! {secondartist} had \033[1m{artists[secondartist]['listeners'] / 1e6:.1f}M\033[0m monthly Spotify listeners and {firstartist} has {artists[firstartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.")
score += 1
print(f"\nYour score is {score}.")
continue
else:
print(f"\nSorry, you guessed incorrectly. {firstartist} had {artists[firstartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {secondartist} has {artists[secondartist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.\n")
# Ask the user if they want to play again
play_again = input("\nWould you like to play again? (y/n/Ent) ")
if play_again.lower() == 'n':
print("Thanks for playing!")
break
else:
print(f"\nYour score is {score}.")
why isnt the file path correct
|
386cd47cf31d4b2902a3be3ae0437be2
|
{
"intermediate": 0.4376924932003021,
"beginner": 0.28740647435188293,
"expert": 0.27490100264549255
}
|
3,469
|
please help translate this kotlin file to nodejs
|
75e3fc828f3031bd37a07a2d7e3f1417
|
{
"intermediate": 0.4443996548652649,
"beginner": 0.3169539272785187,
"expert": 0.23864640295505524
}
|
3,470
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- 指示のない部分のコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "followers_count"と'like_count'を左縦軸に表示し、'comments_count'を右縦軸に表示し、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーチャートを、ページの最上部に横幅いっぱいに表示する機能を作成する
- "サマリーチャート"の'like_count'と'comments_count'の数は、jsonファイル内の過去すべてのデータを参照し、"存在する対象日とその前日データの差分"を算出して日付を追って表示する
- 'like_count'を左縦軸に表示し、'comments_count'を右縦軸に表示し、グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"は、jsonファイル内の過去すべてのデータを参照し、各投稿IDの'like_count'と'comments_count'を、それぞれ"存在する対象日とその前日データとの差分"を算出して日付を追い、各ID別の投稿コンテナに個別のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
02da704143cb470a54aa754b1e220401
|
{
"intermediate": 0.3471693694591522,
"beginner": 0.4591856896877289,
"expert": 0.1936449408531189
}
|
3,471
|
from pygoogle_image import image as pi
pi.download('Dusty Locane jpeg',limit=5)
pi.download('Est Gee jpeg',limit=5)
pi.download('Famous Dex jpeg',limit=5)
pi.download('Fivio Foreign ',limit=5)
pi.download('Fredo Bang',limit=5)
pi.download('Future',limit=5)
pi.download('Gazo',limit=5)
pi.download('GloRilla',limit=5)
pi.download('Gunna',limit=5)
pi.download('Hotboii',limit=5)
pi.download('Iann Dior',limit=5)
pi.download('J. Cole',limit=5)
pi.download('JayDaYoungan',limit=5)
pi.download('Juice WRLD',limit=5)
pi.download('Key Glock',limit=5)
pi.download('King Von',limit=5)
pi.download('Kodak Black',limit=5)
pi.download('Latto',limit=5)
pi.download('Lil Baby',limit=5)
pi.download('Lil Durk',limit=5)
pi.download('Lil Keed',limit=5)
pi.download('Lil Loaded',limit=5)
pi.download('Lil Mabu',limit=5)
pi.download('Lil Mosey',limit=5)
pi.download('Lil Peep',limit=5)
pi.download('Lil Pump',limit=5)
pi.download('Lil Skies',limit=5)
pi.download('Lil Tecca',limit=5)
pi.download('Lil Tjay',limit=5)
pi.download('Lil Uzi Vert',limit=5)
pi.download('Lil Wayne',limit=5)
pi.download('Lil Xan',limit=5)
pi.download('Lil Yachty',limit=5)
pi.download('Machine Gun Kelly',limit=5)
pi.download('Megan Thee Stallion',limit=5)
pi.download('Moneybagg Yo',limit=5)
pi.download('NLE Choppa ',limit=5)
pi.download('NoCap',limit=5)
pi.download('Offset',limit=5)
pi.download('Playboi Carti',limit=5)
pi.download('PnB Rock',limit=5)
pi.download('Polo G',limit=5)
pi.download('Pooh Shiesty',limit=5)
pi.download('Pop Smoke',limit=5)
pi.download('Quando Rondo',limit=5)
pi.download('Quavo',limit=5)
pi.download('Rod Wave',limit=5)
pi.download('Roddy Ricch',limit=5)
pi.download('Russ Millions',limit=5)
pi.download('Ski Mask The Slump God',limit=5)
pi.download('Sleepy Hallow',limit=5)
pi.download('Smokepurpp',limit=5)
pi.download('Soulja Boy',limit=5)
pi.download('SpottemGottem',limit=5)
pi.download('Takeoff',limit=5)
pi.download('Tay-K',limit=5)
pi.download('Tee Grizzley',limit=5)
pi.download('Travis Scott',limit=5)
pi.download('Trippie Redd',limit=5)
pi.download('Waka Flocka Flame',limit=5)
pi.download('XXXTENTACION',limit=5)
pi.download('YBN Nahmir',limit=5)
pi.download('YK Osiris',limit=5)
pi.download('YNW Melly',limit=5)
pi.download('YounBoy Never Broke Again',limit=5)
pi.download('Young M.A',limit=5)
pi.download('Young Nudy',limit=5)
pi.download('Young Thug',limit=5)
pi.download('Yungeen Ace',limit=5)
how can i make it only download jpeg files
|
8b71432e242c854166bfd8c2a67616c8
|
{
"intermediate": 0.3826538026332855,
"beginner": 0.35030466318130493,
"expert": 0.26704153418540955
}
|
3,472
|
Когда я выполняю grub-mkconfig -o /boot/grub/grub.cfg мне пишет "added entry for uefi settings", однако мне нужен grub для bios
|
c61e68c263ef27b278df086ef3ca2003
|
{
"intermediate": 0.44235777854919434,
"beginner": 0.22637984156608582,
"expert": 0.33126235008239746
}
|
3,473
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
from matplotlib.backends.backend_agg import RendererAgg
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
_lock = RendererAgg.lock
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_chart = st.checkbox("サマリーグラフを表示")
show_count_chart = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
if show_summary_chart:
with _lock:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
followers_data = [c.get('followers_count', 0) for _, c in count.items()]
like_data = [c.get(p['id'], {}).get('like_count', 0) - count.get(yesterday, {}).get(p['id'], {}).get('like_count', c.get(p['id'], {}).get('like_count', 0)) for post in post_group for _, c in count.items()]
comment_data = [c.get(p['id'], {}).get('comments_count', 0) - count.get(yesterday, {}).get(p['id'], {}).get('comments_count', c.get(p['id'], {}).get('comments_count', 0)) for post in post_group for _, c in count.items()]
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], followers_data, color="cyan", label="followers_count")
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], like_data, color="orange", label='like_count')
ax2.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], comment_data, color="green", label='comments_count')
ax1.set_ylabel('follower_count, like_count')
ax2.set_ylabel('comment_count')
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
st.pyplot(fig)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_count_chart:
with _lock:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
like_data = [c.get(post['id'], {}).get('like_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('like_count', c.get(post['id'], {}).get('like_count', 0)) for _, c in count.items()]
comment_data = [c.get(post['id'], {}).get('comments_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', c.get(post['id'], {}).get('comments_count', 0)) for _, c in count.items()]
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], like_data, color="orange", label='like_count')
ax2.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], comment_data, color="green", label='comments_count')
ax1.set_ylabel('like_count')
ax2.set_ylabel('comment_count')
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
st.pyplot(fig)
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- 修正済みのコード全体を省略せずに表示する
- 指示のないコードの改変はしない
- "caption = post['caption']"以降のブロックについては改変しない
'''
NameError: name ‘p’ is not defined
Traceback:
File “/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py”, line 565, in _run_script
exec(code, module.dict)
File “/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py”, line 134, in <module>
like_data = [c.get(p[‘id’], {}).get(‘like_count’, 0) - count.get(yesterday, {}).get(p[‘id’], {}).get(‘like_count’, c.get(p[‘id’], {}).get(‘like_count’, 0)) for post in post_group for _, c in count.items()]
File “/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py”, line 134, in <listcomp>
like_data = [c.get(p[‘id’], {}).get(‘like_count’, 0) - count.get(yesterday, {}).get(p[‘id’], {}).get(‘like_count’, c.get(p[‘id’], {}).get(‘like_count’, 0)) for post in post_group for _, c in count.items()]
|
3ca1b298206195318394f4a0d7749b00
|
{
"intermediate": 0.3123318552970886,
"beginner": 0.37735357880592346,
"expert": 0.31031450629234314
}
|
3,474
|
I'm creating a database of Walking trails. My procedure is.
1. I track the route in Geo Tracker android app.
2. I record several waypoints
3. When the type of road changes, a waypoint is created denoting the type of road
'Road HT' - When the road type changes to Hiking Trail
'Road DT' - When the road type changes to Dirt Track
'Road BT' - When the road type changes to Black Top
This means that when I record the Road type, the subsequent trail data after the waypoint is of that Road Type. For eg. When I create a waypoint name 'Road HT'; this means that the trail data after the waypoint (wrt time and geolocation) represents a Hiking Trail.
4. I use services like https://gpx.studio, QGIS and GPS track editor to trim and edit the trail data.
I want to represent different Road types in different color in the final route data. To do so, I will need to divide the single trail file (in GPX format) into sections representing different Route type. How can I do so
|
ce6bfd16ecf2d217cfb24838bbe2b7dc
|
{
"intermediate": 0.49185270071029663,
"beginner": 0.26003143191337585,
"expert": 0.24811586737632751
}
|
3,475
|
Analyse the assingment below and then find the work I have done so far for the homepage of the assingment index.html and style.css
I want you to give me a good reviews page that contains sample reviews from made up people and it also has a form for customers to leave reviews in, give me the html and css for it.
Assingment:
Introduction
You have been asked to help develop a new website for a new camping equipment retailer
that is moving to online sales (RCC – Retail Camping Company). The company has been
trading from premises but now wants an online presence. The website currently doesn’t take
payments and orders online although the management hopes to do this in the future. The
website should be visual and should be viewable on different devices.
Scenario
The Retail Camping Company has the following basic requirements for the contents of the
website:
• Home Page:
o This page will introduce visitors to the special offers that are available and it
should include relevant images of camping equipment such as tents, cookers
and camping gear such as furniture and cookware.
o The text should be minimal, visuals should be used to break up the written
content.
o This page should include a navigation bar (with links inside the bar and hover
over tabs), slide show, header, sections, footer.
o Modal pop-up window that is displayed on top of the current page.
• Camping Equipment: This page will provide a catalogue of products that are on sale
such as tents, camping equipment and cookware.
• Furniture: This page should give customers a catalogue of camping furniture that is
on sale.
• Reviews: This page should include a forum where the registered members can
review the products they have purchased.
• Basket: This page should allow the customers to add camping equipment to their
basket which is saved and checked out later.
• Offers and Packages: This page provides a catalogue of the most popular
equipment that is sold
• Ensure you embed at least THREE (3) different plug ins such as java applets, display
maps and scan for viruses.
At the initial stage of the development process, you are required to make an HTML/CSS
prototype of the website that will clearly show the retail camping company how the final
website could work.
Content hasn’t been provided. Familiarise yourself with possible types of content by
choosing an appropriate organisation (by using web resources) to help you understand the
context in which the company operates. However, do not limit yourself to web-based sources
of information. You should also use academic, industry and other sources. Suitable content
for your prototype can be found on the web e.g. images. Use creative commons
(http://search.creativecommons.org/) or Wikimedia Commons
(http://commons.wikimedia.org/wiki/Main_Page) as a starting point to find content.
Remember the content you include in your site must be licensed for re-use. Do not spend
excessive amounts of time researching and gathering content. The purpose is to provide a
clear indication of how the final website could look and function. The client would provide
the actual content at a later point if they are happy with the website you have proposed.
Students must not use templates that they have not designed or created in the website
assessment. This includes website building applications, free HTML5 website templates,
or any software that is available to help with the assessment. You must create your own
HTML pages including CSS files and ideally you will do this through using notepad or
similar text editor.
Aim
The aim is to create a website for the Retail Camping Company (RCC).
Task 1– 25 Marks
HTML
The website must be developed using HTML 5 and feature a minimum of SIX (6) interlinked
pages which can also be viewed on a mobile device. The website must feature the content
described above and meet the following criteria:
• Researched relevant content to inform the design of the website.
• Be usable in at least TWO (2) different web browsers including being optimised for
mobile devices and responsive design. You should consult your tutor for guidance on
the specific browsers and versions you should use.
• Include relevant images of camping equipment you have selected from your research
including use of headers, sections and footers.
• Home Page:
o Minimal text with visuals to break up the written content.
o Navigation bar (with links inside the bar and hover over tabs)
o Responsive design and at least one plugin
o Header
o Sections
o Footer (including social media links)
• Reviews page: with responsive contact section including first name, last name, and
submit button (through email)
• Camping Equipment, Furniture Page and Offers and Package page with responsive
resize design and including TWO (2) different plug ins, catalogue style and animated
text search for products.
• Basket – Page created which allows the customers to add products to their basket.
Task 2 – 25 Marks
CSS
Create an external CSS file that specifies the design for the website. Each of the HTML
pages must link to this CSS file. There should be no use of the style attribute or the <style>
element in the website.
The boxes on the home page should include relevant elements such as border radius, boxshadow, hover etc.
Include on-page animated text search to allow customers to search for different products.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cabin:wght@400;700&display=swap">
<link rel="stylesheet" href="style/style.css" />
<title>Camping Equipment - Retail Camping Company</title>
</head>
<body>
<header>
<div class="sticky-nav">
<div class="nav-container">
<img src="assets/images/logo.svg" alt="Logo" class="logo">
<h1>Retail Camping Company</h1>
<div class="search-container">
<form action="/search" method="get">
<img src="assets/images/search.png" alt="search-icon" class="search-icon">
<input type="text" name="search" />
<button type="submit">Search</button>
</form>
</div>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="camping-equipment.html">Camping Equipment</a></li>
<li><a href="furniture.html">Furniture</a></li>
<li><a href="reviews.html">Reviews</a></li>
<li><a href="basket.html">Basket</a></li>
<li><a href="offers-and-packages.html">Offers and Packages</a></li>
</ul>
</nav>
</div>
</div>
</header>
<main>
<section class="video">
<video width="1000" height="1000" autoplay muted>
<source src="assets/videos/footage.mp4" type="video/mp4">
</video>
</section>
<section class="featured-section">
<h2 >Featured Products</h2>
<div class="featured-container">
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
</div>
</section>
<section>
<div class="special-offers-container">
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Tent Offer">
<p>20% off premium tents!</p>
</div>
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Cooker Offer">
<p>Buy a cooker, get a free utensil set!</p>
</div>
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Furniture Offer">
<p>Save on camping furniture bundles!</p>
</div>
</div>
</section>
<section class="buts">
<button id="modalBtn">Special Offer!</button>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Sign up now and receive 10% off your first purchase!</p>
</div>
</div>
</section>
<script>
var modal = document.getElementById('modal');
var modalBtn = document.getElementById('modalBtn');
var closeBtn = document.getElementsByClassName('close')[0];
modalBtn.addEventListener('click', openModal);
closeBtn.addEventListener('click', closeModal);
window.addEventListener('click', outsideClick);
function openModal() {
modal.style.display = 'block';
}
function closeModal() {
modal.style.display = 'none';
}
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = 'none';
}
}
</script>
</main>
<footer>
<div class="footer-container">
<div class="footer-item">
<p>Subscribe To Our Newsletter:</p>
<form action="subscribe.php" method="post">
<input type="email" name="email" placeholder="Enter your email" required>
<button type="submit">Subscribe</button>
</form>
</div>
<div class="footer-item address-container">
<p> Get In Contact:</p>
<p>Email: info@retailcampingcompany.com</p>
<p>Phone: +35699382994</p>
<p>Triq Malta,<br>Sliema 12345</p>
</div>
<div class="footer-item google-maps-container">
<p>Where To Find Us:</p>
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d12928.30174160605!2d14.5091557!3d35.8961681!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x130e452d3081f035%3A0x61f492f43cae68e4!2sCity%20Gate!5e0!3m2!1sen!2smt!4v1682559564194!5m2!1sen!2smt" width="650" height="200" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>
<div class="footer-item social-links-container">
<p>Follow Us On:</p>
<ul class="social-links">
<li><a href="https://www.facebook.com">Facebook</a></li>
<li><a href="https://www.instagram.com">Instagram</a></li>
<li><a href="https://www.twitter.com">Twitter</a></li>
</ul>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
<script>var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
</script>
</body>
</html>
styles.css:
html, body, h1, h2, h3, h4, p, a, ul, li, div, main, header, section, footer, img {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
box-sizing: border-box;
}
body {
font-family: "Cabin", sans-serif;
line-height: 1.5;
color: #333;
width: 100%;
margin: 0;
padding: 0;
min-height: 100vh;
flex-direction: column;
display: flex;
background-image: url("../assets/images/cover.jpg");
background-size: cover;
}
header {
background: #00000000;
padding: 0.5rem 2rem;
text-align: center;
color: #32612D;
font-size: 1.2rem;
}
main{
flex-grow: 1;
}
.sticky-nav {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 1000;
}
.nav-container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.search-container {
display: inline-block;
position: relative;
}
.search-container input[type="text"] {
padding: 0.8rem;
border: none;
border-bottom: 1.5px solid #32612D;
outline: none;
color: #32612D;
font-size: 1rem;
background-color: transparent;
margin-right: 30rem;
margin-bottom: 12px;
width: 65%;
}
.search-container input[type="text"]::placeholder {
color: #32612D;
opacity: 0.5;
}
.search-icon {
margin-right: 0.8rem;
width: 24px;
height: auto;
vertical-align: middle;
position: absolute;
top: 50%;
margin-top: -16px;
}
.search-container input[type="text"]:focus {
border-color: #ADC3AB;
}
.search-container button[type="submit"] {
display: none;
}
.logo {
width: 50px;
height: auto;
margin-right: 1rem;
}
h1 {
flex-grow: 1;
text-align: left;
text-shadow: 1px 1px #b3814b;
}
nav ul {
display: inline
list-style: none;
}
nav ul li {
display: inline;
margin-left: 1rem;
}
nav ul li a {
text-decoration: none;
color: #32612D;
position: relative;
transition: color 0.3s ease;
text-shadow: 0.2px 0.2px #b3814b;
}
@media screen and (max-width: 768px) {
.nav-container {
flex-direction: column;
}
h1 {
margin-bottom: 1rem;
}
}
nav ul li a {
text-decoration: none;
color: #32612D;
position: relative;
transition: color 0.3s ease;
}
nav ul li a::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 2px;
background-color: #000;
transform: scaleX(0);
transition: transform 0.3s;
}
nav ul li a:hover {
color: #000000;
}
nav ul li a:hover::after {
transform: scaleX(1);
}
.slideshow-container {
width: 100%;
position: relative;
margin: 1rem 0;
}
.mySlides {
display: none;
}
.mySlides img {
width: 100%;
height: auto;
}
/* Slideshow navigation */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: #32612D;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
background-color: rgba(255,255,255,0.8);
}
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.dot:hover {
background-color: #717171;
}
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
.catalog {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: 2rem 0;
}
.catalog-item {
width: 200px;
padding: 1rem;
margin: 1rem;
background-color: #ADC3AB;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
}
.catalog-item:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
.catalog-item img {
width: 100%;
height: auto;
margin-bottom: 0.5rem;
border-radius: 5px;
}
.catalog-item h3 {
margin-bottom: 0.5rem;
}
.catalog-item p {
margin-bottom: 0.5rem;
}
.catalog-item button {
background-color: #32612D;
color: #fff;
padding: 0.5rem;
border: none;
border-radius: 5px;
cursor: pointer;
}
.catalog-item button:hover {
background-color: #ADC3AB;
}
.category-title {
width: 100%;
text-align: center;
font-size: 24px;
font-weight: bold;
margin-bottom: 1rem;
color: #F5F3CE;
text-shadow: 2px 2px #0A381F;
}
.featured-section {
padding: 1rem;
text-align: center;
margin: 1rem 0;
}
.filter {
margin-bottom: 5rem;
}
.filter select {
padding: 0.5rem;
font-size: 0.9rem;
}
.video {
display: flex;
justify-content: center;
align-items: center;
margin-top: -265px;
margin-bottom: -250px;
}
footer form {
display: inline-flex;
align-items: center;
}
.about-section {
padding: 1rem;
text-align: center;
margin: 1rem 0;
}
.featured-section {
padding: 1rem;
text-align: center;
margin: 1rem 0;
}
.featured-section h2 {
font-size: 1.5rem;
margin-bottom: 1rem;
}
h2{
color: #0A381F;
text-shadow: 2px 2px #F5F3CE ;
}
v{
margin top:-1000px;
}
.featured-container {
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
margin: 1rem 0;
}
.featured-product {
width: 150px;
padding: 1rem;
background-color: #ADC3AB;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
margin: 0.5rem;
}
.featured-product:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
transform: translateY(-5px);
}
.featured-product img {
width: 100%;
height: auto;
margin-bottom: 1rem;
border-radius: 5px;
}
.furniture-item {
width: 200px;
padding: 1rem;
margin: 1rem;
background-color: #dcbba3;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
}
.furniture-item:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
.furniture-item img {
width: 100%;
height: auto;
margin-bottom: 0.5rem;
border-radius: 5px;
}
.furniture-item h3 {
margin-bottom: 0.5rem;
}
.furniture-item p {
margin-bottom: 0.5rem;
}
.furniture-item button {
background-color: #b38f71;
color: #fff;
padding: 0.5rem;
border: none;
border-radius: 5px;
cursor: pointer;
}
.furniture-item button:hover {
background-color: #dcbba3;
}
.special-offers-container {
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
margin: 1rem 0;
}
.special-offer {
width: 200px;
padding: 1rem;
text-align: center;
margin: 1rem;
background-color: #ADC3AB;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
}
.special-offer:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
transform: translateY(-5px);
}
.special-offer img {
width: 100%;
height: auto;
margin-bottom: 0.5rem;
border-radius: 5px;
}
.modal {
display: none;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
overflow: auto;
align-items: center;
}
.modal-content {
background-color: #fefefe;
padding: 2rem;
margin: 10% auto;
width: 30%;
min-width: 300px;
max-width: 80%;
text-align: center;
border-radius: 5px;
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);
}
.modalBtn{
background-color: #ADC3AB;
color: #32612D;
padding: 0.5rem;
border: none;
border-radius: 5px;
cursor: pointer;
}
.buts {
text-align: center;
}
.footer-item.address-container p {
margin: 0;
text-align: left;
}
.footer-item p {
text-align: center;
}
.add{
text-align: center;
}
.close {
display: block;
text-align: right;
font-size: 2rem;
color: #333;
cursor: pointer;
}
footer {
background: #32612D;
padding: 1rem;
text-align: center;
margin-top: auto;
}
.footer-container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.footer-item {
margin: 1rem 2rem;
}
footer p {
color: #fff;
margin-bottom: 1rem;
}
footer ul {
list-style: none;
}
footer ul li {
display: inline;
margin: 0.5rem;
}
footer ul li a {
text-decoration: none;
color: #fff;
}
@media screen and (max-width: 768px) {
.special-offers-container {
flex-direction: column;
}
}
@media screen and (max-width: 480px) {
h1 {
display: block;
margin-bottom: 1rem;
}
}
.footer-item iframe {
width: 100%;
height: 200px;
}
.footer-item form {
display: inline-flex;
align-items: center;
}
.footer-item input[type="email"] {
padding: 0.5rem;
border: none;
border-radius: 5px;
margin-right: 0.5rem;
}
.footer-item button {
background-color: #ADC3AB;
color: #32612D;
padding: 0.5rem;
border: none;
border-radius: 5px;
cursor: pointer;
}
.footer-item button:hover {
background-color: #32612D;
color: #fff;
}
.social-links-container {
order: 2;
}
.address-container {
order: 1;
}
.google-maps-container {
order: 0;
}
|
deb2c63169b93a3e536951aa170dd8f6
|
{
"intermediate": 0.20887434482574463,
"beginner": 0.33866235613822937,
"expert": 0.4524633288383484
}
|
3,476
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
from matplotlib.backends.backend_agg import RendererAgg
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
_lock = RendererAgg.lock
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_chart = st.checkbox("サマリーグラフを表示")
show_count_chart = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
if show_summary_chart:
with _lock:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
followers_data = [c.get('followers_count', 0) for _, c in count.items()]
like_data = [count[date].get(post['id'], {}).get('like_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('like_count', count[date].get(post['id'], {}).get('like_count', 0)) for post in post_group for date, c in count.items()]
comment_data = [count[date].get(post['id'], {}).get('comments_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', count[date].get(post['id'], {}).get('comments_count', 0)) for post in post_group for date, c in count.items()]
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], followers_data, color="cyan", label="followers_count")
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], like_data, color="orange", label='like_count')
ax2.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], comment_data, color="green", label='comments_count')
ax1.set_ylabel('follower_count, like_count')
ax2.set_ylabel('comment_count')
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
st.pyplot(fig)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_count_chart:
with _lock:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
like_data = [count[date].get(post['id'], {}).get('like_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('like_count', count[date].get(post['id'], {}).get('like_count', 0)) for date, c in count.items()]
comment_data = [count[date].get(post['id'], {}).get('comments_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', count[date].get(post['id'], {}).get('comments_count', 0)) for date, c in count.items()]
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], like_data, color="orange", label='like_count')
ax2.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], comment_data, color="green", label='comments_count')
ax1.set_ylabel('like_count')
ax2.set_ylabel('comment_count')
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
st.pyplot(fig)
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
023-04-30 21:30:39.207 Uncaught app exception
Traceback (most recent call last):
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
exec(code, module.__dict__)
File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 145, in <module>
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], like_data, color="orange", label='like_count')
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/matplotlib/axes/_axes.py", line 1635, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/matplotlib/axes/_base.py", line 312, in __call__
yield from self._plot_args(this, kwargs)
File "/home/walhalax/anaconda3/lib/python3.9/site-packages/matplotlib/axes/_base.py", line 498, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (3,) and (12,)
|
3cc62ab2165e59d72ef497efee1d0be5
|
{
"intermediate": 0.32332751154899597,
"beginner": 0.4301520586013794,
"expert": 0.24652044475078583
}
|
3,477
|
how can I call a python file inside running puyhon file
|
0be1bc4e52736ca65381e5adba545842
|
{
"intermediate": 0.49762895703315735,
"beginner": 0.26225847005844116,
"expert": 0.2401125729084015
}
|
3,478
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import seaborn as sns
from matplotlib.backends.backend_agg import RendererAgg
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
_lock = RendererAgg.lock
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
show_summary_chart = st.checkbox("サマリーグラフを表示")
show_count_chart = st.checkbox("いいね/コメント数グラフを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
if show_summary_chart:
with _lock:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
followers_data = [c.get('followers_count', 0) for _, c in count.items()]
like_data = [count[date].get(post['id'], {}).get('like_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('like_count', count[date].get(post['id'], {}).get('like_count', 0)) for post in post_group for date, c in count.items()]
comment_data = [count[date].get(post['id'], {}).get('comments_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', count[date].get(post['id'], {}).get('comments_count', 0)) for post in post_group for date, c in count.items()]
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], followers_data, color="cyan", label="followers_count")
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], like_data, color="orange", label='like_count')
ax2.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], comment_data, color="green", label='comments_count')
ax1.set_ylabel('follower_count, like_count')
ax2.set_ylabel('comment_count')
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
st.pyplot(fig)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
if show_count_chart:
with _lock:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
like_data = [count[date].get(post['id'], {}).get('like_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('like_count', count[date].get(post['id'], {}).get('like_count', 0)) for date, c in count.items()]
comment_data = [count[date].get(post['id'], {}).get('comments_count', 0) - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', count[date].get(post['id'], {}).get('comments_count', 0)) for date, c in count.items()]
ax1.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], like_data, color="orange", label='like_count')
ax2.plot([datetime.datetime.strptime(k, '%Y-%m-%d') for k in count], comment_data, color="green", label='comments_count')
ax1.set_ylabel('like_count')
ax2.set_ylabel('comment_count')
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
st.pyplot(fig)
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
|
67e780a04cf7582002a4d0b9d42b1c65
|
{
"intermediate": 0.32332751154899597,
"beginner": 0.4301520586013794,
"expert": 0.24652044475078583
}
|
3,479
|
ак исправить No error handlers are registered, logging exception. Traceback (most recent call last): File "C:\Users\home\PycharmProjects\телегабот\venv\lib\site-packages\telegram\ext\dispatcher.py", line 447, in process_update handler.handle_update(update, self, check, context) File "C:\Users\home\PycharmProjects\телегабот\venv\lib\site-packages\telegram\ext\handler.py", line 160, in handle_update return self.callback(update, context) File "C:\Users\home\PycharmProjects\телегабот\main.py", line 68, in referral add_invited_user(invitee_user_id, invited_user_name, referral_code, c) File "C:\Users\home\PycharmProjects\телегабот\main.py", line 105, in add_invited_user c.execute('UPDATE users SET invited_count = invited_count + 1, invited_users = COALESCE(invited_users, "") || "," WHERE id = ?', (user_name, inviter_user_id)) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied. в коде def add_invited_user(user_id: int, user_name: str, referral_code: str, c): inviter_user_id = get_user_id_by_referral_code(referral_code, c) c.execute('UPDATE users SET invited_count = invited_count + 1, invited_users = COALESCE(invited_users, "") || "," WHERE id = ?', (user_name, inviter_user_id))
|
bfc92a8a4be1178310849cc6b55bb9b9
|
{
"intermediate": 0.4127199351787567,
"beginner": 0.35650742053985596,
"expert": 0.23077267408370972
}
|
3,480
|
I'm thinking on how to make this "<label for="switch">Energy saving nightmode layer</label>" not to cover things when flag is triggered and content shown... because this "nightmode layer" should cover the whole area when activated but it don't allow to select text behind it.<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSS-only Multilingual eco-friendly site</title>
<style>
.switch-container input[type="checkbox"] {
width: 18px;
height: 18px;
}
.switch-container label:before {
content: "";
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
transition: opacity 0.3s ease-out;
}
.switch-container input[type="checkbox"]:checked ~ label:before {
opacity: 1;
}
body, html {
margin: 0;
padding: 0;
height: 100%;
line-height: 1.6;
background-color: #f7f7f7;
}
header {
background-color: #4CAF50;
color: #FFF;
padding: 16px 0px 0px 0px;
text-align: center;
position: relative;
}
h1, h2, h3, h4, h5, h6 {
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 18px;
width: 90%;
height: 1%;
}
.left, .right {
position: relative;
}
.left::before, .right::before {
content: '';
position: absolute;
top: 50%;
border-bottom: 1px dashed #FFF;
width: 40%;
}
.left::before {
right: 100%;
margin-right: 20px;
}
.right::before {
left: 100%;
margin-left: 20px;
}
.flags-container {
position: fixed;
top: 0;
left: 0;
right: 0;
--padding: 3px 0;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
--box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
z-index: 10;
}
.flag-radio {
display: none;
}
.flag-label {
cursor: pointer;
margin: 0 10px;
transition: 0.3s;
opacity: 0.6;
font-size: 24px;
}
.flag-label:hover {
opacity: 1;
}
.language-option {
position: run-in;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: none;
justify-content: center;
align-items: center;
padding-top: 0px; /* language-option container text from top height */
}
#english-flag:checked ~ #english,
#hindi-flag:checked ~ #hindi,
#hebrew-flag:checked ~ #hebrew,
#chinese-flag:checked ~ #chinese,
#french-flag:checked ~ #french,
#spanish-flag:checked ~ #spanish {
display: block;
}
</style>
</head>
<body>
<input id="english-flag" type="radio" name="flags" class="flag-radio">
<input id="hindi-flag" type="radio" name="flags" class="flag-radio">
<input id="hebrew-flag" type="radio" name="flags" class="flag-radio">
<input id="chinese-flag" type="radio" name="flags" class="flag-radio">
<input id="french-flag" type="radio" name="flags" class="flag-radio">
<input id="spanish-flag" type="radio" name="flags" class="flag-radio">
<div class="flags-container">
<label for="english-flag" class="flag-label">🇬🇧</label>
<label for="hindi-flag" class="flag-label">🇮🇳</label>
<label for="hebrew-flag" class="flag-label">🇮🇱</label>
<label for="chinese-flag" class="flag-label">🇨🇳</label>
<label for="french-flag" class="flag-label">🇫🇷</label>
<label for="spanish-flag" class="flag-label">🇪🇸</label>
</div><br>
<header>
<h1>
<span class="left">EcoWare</span>
<span class="right">Earthwise</span>
</h1>
</header>
<div class="switch-container">
<input type="checkbox" id="switch">
<label for="switch">Energy saving nightmode layer</label>
</div>
<div id="english" class="language-option">
<p>english details going here</p>
</div>
<div id="hindi" class="language-option">
<p>hindi details going here</p>
</div>
<div id="hebrew" class="language-option">
<p>hebrew details going here</p>
</div>
<div id="chinese" class="language-option">
<p>chinese details going here</p>
</div>
<div id="french" class="language-option">
<p>french details going here</p>
</div>
<div id="spanish" class="language-option">
<p>spanish details going here</p>
</div>
</body>
</html>
|
6fc257e8c104442cc97427959356966e
|
{
"intermediate": 0.3166506290435791,
"beginner": 0.41733619570732117,
"expert": 0.26601317524909973
}
|
3,481
|
почему код завершает работу, ничего не выведя
import requests
from bs4 import BeautifulSoup
url = "https://market.poizonshop.ru/?ysclid=lh3dvkwcpb735030874"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
items = soup.select(".js-store- grid-list>.t-store__grid-item")
for item in items:
# Получаем название предмета
title = item.select_one(".js-store-prod-name.js-product-name.t-store__card__title.t-name.t-name_md")
if title:
title = title.text.strip()
# Получаем ссылку на фото
img = item.select_one(".js-product-img.t-store__card__bgimg.t-store__card__bgimg_hover.t-bgimg.loaded")
if img:
img_url = img["style"].split("(", 1)[1].split(")")[0].strip()
# Получаем ссылку на подробную информацию
details_link = item.select_one(".store__card__wrap_txt-and-opts>a")
if details_link:
details_url = details_link["href"]
# Получаем цену на странице с подробной информацией товара
details_resp = requests.get(details_url)
details_soup = BeautifulSoup(details_resp.content, "html.parser")
price = details_soup.select_one(".js-product-price.js-store-prod-price-val.t-store__prod-popup__price-value.notranslate")
if price:
price = price.text.strip()
# Получаем подробную информацию о товаре
detailed_info = details_soup.select_one(".js-store-prod-text.t-store__prod-popup__text.t-descr.t-descr_xxs>div.js-store-prod-all-text>strong:nth-child(1)")
if detailed_info:
detailed_info = detailed_info.text.strip()
print(f"Название товара: {title}")
print(f"Ссылка на изображение: {img_url}")
print(f"Ссылка на подробную информацию: {details_url}")
print(f"Цена товара: {price}")
print(f"Подробная информация: {detailed_info}")
print("\n" + "="*30 + "\n")
|
299da2c3399295c179a27983f763bac5
|
{
"intermediate": 0.24426232278347015,
"beginner": 0.6451622843742371,
"expert": 0.11057545244693756
}
|
3,482
|
I need a code either as vba or validation which will pop up a message after values in a sheet are changed.
The pop up will ask if I want to allow the change I made to the cell value and if I select yes it will keep the change.
If I however select No the cell will revert to its former value. I do not want the code to continuously loop.
|
c501176cb82aef1665d3eeda58b8934c
|
{
"intermediate": 0.5643538236618042,
"beginner": 0.29327166080474854,
"expert": 0.14237448573112488
}
|
3,483
|
rmPy array vs. Python list
lst = [1,2,3]
arr = np.eye(3)
lst2 = lst + lst
arr2 = arr + arr
print('lst:',lst)
print('lst + lst =',lst2)
print('\narr:\n',arr)
print('arr + arr =\n',arr2)
|
73c7b19ae1afb77eb60c0c9ace53d937
|
{
"intermediate": 0.3695231080055237,
"beginner": 0.3927217423915863,
"expert": 0.23775510489940643
}
|
3,484
|
open(https://zhiji.yinghehr.com/static/template/ability.xlsx)
|
5f092ba7f17c5557bb5d76d500f4a039
|
{
"intermediate": 0.3376169204711914,
"beginner": 0.2897723317146301,
"expert": 0.37261077761650085
}
|
3,485
|
I do not want the following code to run on cell I2. Dim confirmation As Integer
On Error Resume Next
Application.EnableEvents = False
confirmation = MsgBox(“Do you want to save this change?”, vbYesNo)
If confirmation = vbNo Then
Application.Undo
End If
Application.EnableEvents = True
|
7553210802650b05d786ea51cada82c7
|
{
"intermediate": 0.4320312738418579,
"beginner": 0.40096941590309143,
"expert": 0.16699926555156708
}
|
3,486
|
in the below code, i want to move my master drone to waypoints in different directions, what would be the follower drones position?
from pymavlink import mavutil
import math
import time
the_connection = mavutil.mavlink_connection('/dev/ttyUSB0', baud=57600)
the_connection.wait_heartbeat()
msg = the_connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
master_waypoint = (msg.lat / 10 ** 7, msg.lon / 10 ** 7, 10)
waypoints = [
master_waypoint,
(28.5861327, 77.3420592, 10),
(28.5860912, 77.3420042, 10), # Repeat the first waypoint to make the drone return to its starting point
]
distance = 5 # Distance in meters
angle = 240 # Angle in degrees
kp = 0.1
ki = 0.01
kd = 0.05
pid_limit = 0.0001
class Drone:
def __init__(self, system_id, connection):
self.system_id = system_id
self.connection = connection
def set_mode(self, mode):
self.connection.mav.set_mode_send(
self.system_id,
mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED,
mode
)
def arm(self, arm=True):
self.connection.mav.command_long_send(self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, int(arm), 0, 0, 0, 0, 0,
0)
def takeoff(self, altitude):
self.connection.mav.command_long_send(self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, altitude)
def send_waypoint(self, wp, next_wp, speed):
# Print wp and next_wp
print("Current waypoint: {} | Next waypoint: {}".format(wp, next_wp))
vx, vy, vz = calculate_velocity_components(wp, next_wp, speed)
# Print velocity components
print("Velocity components: vx={}, vy={}, vz={}".format(vx, vy, vz))
self.connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_global_int_message(
10,
self.system_id,
self.connection.target_component,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
int(0b110111111000),
int(wp[0] * 10 ** 7),
int(wp[1] * 10 ** 7),
wp[2],
vx, # * speed, # Multiply by speed,
vy, # * speed, # Multiply by speed,
vz, # * speed, # Multiply by speed,
0,
0,
0,
0,
0)
)
def get_position(self):
self.connection.mav.request_data_stream_send(
self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_DATA_STREAM_POSITION, 1, 1)
while True:
msg = self.connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if msg.get_srcSystem() == self.system_id:
return (msg.lat / 10 ** 7, msg.lon / 10 ** 7, 10)
class PIDController:
def __init__(self, kp, ki, kd, limit):
self.kp = kp
self.ki = ki
self.kd = kd
self.limit = limit
self.prev_error = 0
self.integral = 0
def update(self, error, dt):
derivative = (error - self.prev_error) / dt
self.integral += error * dt
self.integral = max(min(self.integral, self.limit), -self.limit) # Clamp the integral term
output = self.kp * error + self.ki * self.integral + self.kd * derivative
self.prev_error = error
return output
pid_lat = PIDController(kp, ki, kd, pid_limit)
pid_lon = PIDController(kp, ki, kd, pid_limit)
master_drone = Drone(2, the_connection)
follower_drone = Drone(3, the_connection)
print("connection is done")
def calculate_follower_coordinates(wp, distance, angle):
earth_radius = 6371000.0 # in meters
latitude_change = -(180 * distance * math.cos(math.radians(angle))) / (math.pi * earth_radius)
longitude_change = -(180 * distance * math.sin(math.radians(angle))) / (
math.pi * earth_radius * math.cos(math.radians(wp[0])))
new_latitude = wp[0] + latitude_change
new_longitude = wp[1] + longitude_change
print("Calculated follower coordinates: lat={}, lon={}, alt={}".format(new_latitude, new_longitude, wp[2]))
return (new_latitude, new_longitude, wp[2])
def calculate_velocity_components(current_wp, next_wp, speed):
dx = next_wp[0] - current_wp[0]
dy = next_wp[1] - current_wp[1]
dz = next_wp[2] - current_wp[2]
dx2 = dx ** 2
dy2 = dy ** 2
dz2 = dz ** 2
distance = math.sqrt(dx2 + dy2 + dz2)
vx = (dx / distance) * speed
vy = (dy / distance) * speed
vz = (dz / distance) * speed
return vx, vy, vz
def abort():
print("Type 'abort' to return to Launch and disarm motors.")
start_time = time.monotonic()
while time.monotonic() - start_time < 7:
user_input = input("Time left: {} seconds \n".format(int(7 - (time.monotonic() - start_time))))
if user_input.lower() == "abort":
print("Returning to Launch and disarming motors…")
for drone in [master_drone, follower_drone]:
drone.set_mode(6) # RTL mode
drone.arm(False) # Disarm motors
return True
print("7 seconds have passed. Proceeding with waypoint task...")
return False
for drone in [master_drone, follower_drone]:
drone.set_mode(4)
drone.arm()
drone.takeoff(10)
print("arming and takeoff is done")
# Initialize the previous_mode variable to None
previous_mode = {2: None, 3: None} # initialize the previous_mode dictionary
while True:
msg = the_connection.recv_match(type='HEARTBEAT', blocking=False)
if msg:
sysid = msg.get_srcSystem()
if sysid in [2, 3]:
mode = mavutil.mode_string_v10(msg)
if mode != previous_mode[sysid]: # check if the mode has changed
previous_mode[sysid] = mode # update the previous_mode variable
print(f"System ID: {sysid}, Mode: {mode}")
# save the mode for sysid 2 and 3 in separate variables
if sysid == 2:
mode_sysid_2 = mode
elif sysid == 3:
mode_sysid_3 = mode
# Run the following code only when mode_sysid_3 and mode_sysid_2 is set to "GUIDED"
time_start = time.time()
if mode_sysid_3 == "GUIDED":
while mode_sysid_2 == "GUIDED":
if abort():
exit()
# main loop
if time.time() - time_start >= 1:
for index, master_wp in enumerate(waypoints[:-1]):
if mode_sysid_2 != "GUIDED":
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
next_wp = waypoints[index + 1]
master_drone.send_waypoint(master_wp, next_wp, speed=3)
follower_position = master_drone.get_position()
# Print follower position
print("follower position: {}".format(follower_position))
if follower_position is None:
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
break
follower_wp = calculate_follower_coordinates(follower_position, distance, angle)
dt = time.time() - time_start
pid_lat_output = pid_lat.update(follower_wp[0] - follower_position[0], dt)
pid_lon_output = pid_lon.update(follower_wp[1] - follower_position[1], dt)
# Print PID output adjustments
print("PID adjustments: lat={}, lon={}".format(pid_lat_output, pid_lon_output))
adjusted_follower_wp = (
follower_wp[0] + pid_lat_output, follower_wp[1] + pid_lon_output, follower_wp[2])
# Print adjusted follower waypoint
print("Adjusted follower waypoint: {}".format(adjusted_follower_wp))
follower_drone.send_waypoint(adjusted_follower_wp, next_wp, speed=3)
if abort():
exit()
if mode_sysid_2 != "GUIDED":
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
time.sleep(30)
# set the mode to rtl and disarms the drone
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
# set mode to rtl
# master_drone.set_mode(6)
# follower_drone.set_mode(6)
break
# break
# break
# break
the_connection.close()
|
dc603797c1d8cc5c4120391e5ac51fc0
|
{
"intermediate": 0.2997235655784607,
"beginner": 0.5655430555343628,
"expert": 0.13473331928253174
}
|
3,487
|
hi whats the meaning of cloud
|
68ef55351918d3373e4dc2bd218ef02f
|
{
"intermediate": 0.5026803016662598,
"beginner": 0.254120796918869,
"expert": 0.24319890141487122
}
|
3,488
|
'''
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
show_description = st.checkbox("キャプションを表示")
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを以下の要件をすべて満たして改修してください
- Python用のインデントを行頭に付与して出力する
- コードの説明文は表示しない
- 指示のない部分のコードの改変はしない
- 既存の'like_count'と"comments_count"表示部分は改変しない
- "caption = post['caption']"以降のブロックについては改変しない
- グラフ作成のためのPythonライブラリは"seaborn"のみを使用する
- "followers_count"と'like_count'と'comments_count'を縦軸に表示し、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーチャートを、ページの最上部に横幅いっぱいに表示する機能を作成する
- "サマリーチャート"の'like_count'と'comments_count'の数は、jsonファイル内の過去すべてのデータを参照し、"存在する対象日とその前日データの差分"を算出して日付を追って表示する
- 'like_count'と'comments_count'を右縦軸に表示し、グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する
- "いいね/コメント数グラフ"は、jsonファイル内の過去すべてのデータを参照し、各投稿IDの'like_count'と'comments_count'を、それぞれ"存在する対象日とその前日データとの差分"を算出して日付を追い、各ID別の投稿コンテナに個別のグラフを表示するようにする
- "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
|
290af5721b543507c256602e855f9f54
|
{
"intermediate": 0.3471693694591522,
"beginner": 0.4591856896877289,
"expert": 0.1936449408531189
}
|
3,489
|
hey whats uo?
|
58d79aa8ed32418be2868af2d5b538a2
|
{
"intermediate": 0.37507617473602295,
"beginner": 0.2957742512226105,
"expert": 0.32914963364601135
}
|
3,490
|
Foreign keys can only be of integer data type
|
d6851a0d24764c945293e7aa37bed7f1
|
{
"intermediate": 0.47995778918266296,
"beginner": 0.23437799513339996,
"expert": 0.2856641411781311
}
|
3,491
|
write js code of display queue basing on addChild architecture and use renderQuad to draw elements, all child transforms should be on place
|
cb3d670550e8928ee8bc800f64d5ce4c
|
{
"intermediate": 0.418600469827652,
"beginner": 0.278272420167923,
"expert": 0.30312711000442505
}
|
3,492
|
the problem here that I covered the entire content with nighmode switcher "<div class=“switch-container”>" but I want this thing to be able to activate on mouse click and at the same time be able to select text behind it and after when it disabled.: <html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS-only Multilingual eco-friendly site</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
line-height: 1.6;
background-color: #f7f7f7;
}
header {
background-color: #4CAF50;
color: #FFF;
padding: 16px 0;
text-align: center;
position: relative;
z-index: 0;
}
h1 {
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 18px;
width: 90%;
height: 1%;
}
.left, .right {
position: relative;
}
.left::before, .right::before {
content: ‘’;
position: absolute;
top: 50%;
border-bottom: 1px dashed #FFF;
width: 40%;
}
.left::before {
right: 100%;
margin-right: 20px;
}
.right::before {
left: 100%;
margin-left: 20px;
}
.flags-container {
position: fixed;
top: 0;
left: 0;
right: 0;
padding: 3px 0;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
z-index: 1;
}
.flag-radio {
display: none;
}
.flag-label {
cursor: pointer;
margin: 0 10px;
transition: 0.3s;
opacity: 0.6;
font-size: 24px;
}
.flag-label:hover {
opacity: 1;
}
.language-option {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: none;
justify-content: center;
align-items: center;
padding-top: 50px;
}
#english-flag:checked ~ #english,
#hindi-flag:checked ~ #hindi,
#hebrew-flag:checked ~ #hebrew,
#chinese-flag:checked ~ #chinese,
#french-flag:checked ~ #french,
#spanish-flag:checked ~ #spanish {
display: block;
}
.switch-container {
position: relative;
--padding: 20px;
user-select: text;
z-index: 21;
width: 100%;
height: 100%;
top:100px;
}
.switch-container input[type="checkbox"] {
width: 18px;
height: 18px;
pointer-events: all;
z-index: 21;
}
.switch-container label:before {
content: "";
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
transition: opacity 0.3s ease-out;
pointer-events: none; /* <--here! */
z-index: 21;
}
.switch-container input[type="checkbox"]:checked ~ label:before {
opacity: 1;
pointer-events: all;
z-index: 21;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body><div class="switch-container">
<input type="checkbox" id="switch">
<label for="switch">Energy saving night-mode layer</label>
<input id="english-flag" type="radio" name="flags" class="flag-radio" checked>
<input id="hindi-flag" type="radio" name="flags" class="flag-radio">
<input id="hebrew-flag" type="radio" name="flags" class="flag-radio">
<input id="chinese-flag" type="radio" name="flags" class="flag-radio">
<input id="french-flag" type="radio" name="flags" class="flag-radio">
<input id="spanish-flag" type="radio" name="flags" class="flag-radio">
<div class="flags-container">
<label for="english-flag" class="flag-label" title="English">🇬🇧</label>
<label for="hindi-flag" class="flag-label" title="Hindi">🇮🇳</label>
<label for="hebrew-flag" class="flag-label" title="Hebrew">🇮🇱</label>
<label for="chinese-flag" class="flag-label" title="Chinese">🇨🇳</label>
<label for="french-flag" class="flag-label" title="French">🇫🇷</label>
<label for="spanish-flag" class="flag-label" title="Spanish">🇪🇸</label>
</div>
<header>
<h1>
<span class="left">EcoWare</span>
<span class="right">Earthwise</span>
</h1>
</header>
<div id="english" class="language-option">
<p>English details go here</p>
</div>
<div id="hindi" class="language-option">
<p>Hindi details go here</p>
</div>
<div id="hebrew" class="language-option">
<p>Hebrew details go here</p>
</div>
<div id="chinese" class="language-option">
<p>Chinese details go here</p>
</div>
<div id="french" class="language-option">
<p>French details go here</p>
</div>
<div id="spanish" class="language-option">
<p>Spanish details go here</p>
</div></div>
</body>
</html>
|
a14626027363c25bcf779f12d5c12afc
|
{
"intermediate": 0.26377183198928833,
"beginner": 0.38854655623435974,
"expert": 0.3476816415786743
}
|
3,493
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
# グラフ表示用のデータを取得
count_data = getCount(count_filename)
post_ids = []
like_counts = []
comment_counts = []
dates = []
for date, posts in count_data.items():
if type(posts) is not dict:
continue
for post_id, post_values in posts.items():
if date not in dates:
dates.append(date)
if post_id == "followers_count":
continue
if post_id not in post_ids:
post_ids.append(post_id)
like_counts.append([])
comment_counts.append([])
idx = post_ids.index(post_id)
like_counts[idx].append(post_values['like_count'])
comment_counts[idx].append(post_values['comments_count'])
dates.sort()
df = pd.DataFrame({date: {"like_count": [], "comments_count": []} for date in dates},
index=post_ids)
for post_id, like_count, comment_count in zip(post_ids, like_counts, comment_counts):
for date, lc, cc in zip(dates, like_count, comment_count):
df.at[post_id, date] = {"like_count": lc, "comments_count": cc}
# 表示制御
show_summary_chart = st.checkbox("サマリーグラフを表示")
show_individual_chart = st.checkbox("いいね/コメント数グラフを表示")
show_description = st.checkbox("キャプションを表示")
# サマリーチャート
if show_summary_chart:
summary_data = {"followers_count": [], "like_count_sum": [], "comments_count_sum": []}
for date in dates:
summary_data["followers_count"].append(count_data[date]["followers_count"])
summary_data["like_count_sum"].append(sum([post['like_count'] for post in count_data[date].values() if type(post) is dict]))
summary_data["comments_count_sum"].append(sum([post['comments_count'] for post in count_data[date].values() if type(post) is dict]))
summary_df = pd.DataFrame(summary_data, index=dates)
fig_summary, ax = plt.subplots()
sns.lineplot(data=summary_df['followers_count'], ax=ax, color='lightblue', label='followers_count')
ax2 = ax.twinx()
sns.lineplot(data=summary_df['like_count_sum'], ax=ax2, color='orange', label='like_count')
sns.lineplot(data=summary_df['comments_count_sum'], ax=ax2, color='green', label='comments_count')
ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%m/%d'), dates), rotation=45)
st.pyplot(fig_summary)
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
# いいね/コメント数グラフ
if show_individual_chart:
post_id = post["id"]
lc = df.at[post_id, date]["like_count"]
cc = df.at[post_id, date]["comments_count"]
fig, ax = plt.subplots(figsize=(6, 2))
ax2 = ax.twinx()
sns.lineplot(x=dates, y=lc, ax=ax, color="orange", label="like_count")
sns.lineplot(x=dates, y=cc, ax=ax2, color="green", label="comments_count")
ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%m/%d'), dates), rotation=45)
st.pyplot(fig)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを実行すると、下記のエラーが表示されます。改修したコード全文を表示してください
‘’‘
AttributeError Traceback (most recent call last)
Cell In [42], line 157
154 ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, ‘%Y-%m-%d’).strftime(’%m/%d’), dates), rotation=45)
155 st.pyplot(fig_summary)
–> 157 posts.reverse()
158 post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
160 count = getCount(count_filename)
AttributeError: ‘dict’ object has no attribute ‘reverse’
|
3d753844eb4a187cc91fe5f2797efaa4
|
{
"intermediate": 0.3593063950538635,
"beginner": 0.34495285153388977,
"expert": 0.2957407832145691
}
|
3,494
|
Таблица SYS_LOGS: SYS_LOGS_PART230423 :ORA-02266: unique/primary keys in table referenced by enabled foreign keys
|
2b0e830492a4440df7ae0bac5102a664
|
{
"intermediate": 0.2868479788303375,
"beginner": 0.3370535671710968,
"expert": 0.3760984539985657
}
|
3,495
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
# グラフ表示用のデータを取得
count_data = getCount(count_filename)
post_ids = []
like_counts = []
comment_counts = []
dates = []
for date, posts in count_data.items():
if type(posts) is not dict:
continue
for post_id, post_values in posts.items():
if date not in dates:
dates.append(date)
if post_id == "followers_count":
continue
if post_id not in post_ids:
post_ids.append(post_id)
like_counts.append([])
comment_counts.append([])
idx = post_ids.index(post_id)
like_counts[idx].append(post_values['like_count'])
comment_counts[idx].append(post_values['comments_count'])
dates.sort()
df = pd.DataFrame({date: {"like_count": [], "comments_count": []} for date in dates},
index=post_ids)
for post_id, like_count, comment_count in zip(post_ids, like_counts, comment_counts):
for date, lc, cc in zip(dates, like_count, comment_count):
df.at[post_id, date] = {"like_count": lc, "comments_count": cc}
# 表示制御
show_summary_chart = st.checkbox("サマリーグラフを表示")
show_individual_chart = st.checkbox("いいね/コメント数グラフを表示")
show_description = st.checkbox("キャプションを表示")
# サマリーチャート
if show_summary_chart:
summary_data = {"followers_count": [], "like_count_sum": [], "comments_count_sum": []}
for date in dates:
summary_data["followers_count"].append(count_data[date]["followers_count"])
summary_data["like_count_sum"].append(sum([post['like_count'] for post in count_data[date].values() if type(post) is dict]))
summary_data["comments_count_sum"].append(sum([post['comments_count'] for post in count_data[date].values() if type(post) is dict]))
summary_df = pd.DataFrame(summary_data, index=dates)
fig_summary, ax = plt.subplots()
sns.lineplot(data=summary_df['followers_count'], ax=ax, color='lightblue', label='followers_count')
ax2 = ax.twinx()
sns.lineplot(data=summary_df['like_count_sum'], ax=ax2, color='orange', label='like_count')
sns.lineplot(data=summary_df['comments_count_sum'], ax=ax2, color='green', label='comments_count')
ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%m/%d'), dates), rotation=45)
st.pyplot(fig_summary)
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
# いいね/コメント数グラフ
if show_individual_chart:
post_id = post["id"]
lc = df.at[post_id, date]["like_count"]
cc = df.at[post_id, date]["comments_count"]
fig, ax = plt.subplots(figsize=(6, 2))
ax2 = ax.twinx()
sns.lineplot(x=dates, y=lc, ax=ax, color="orange", label="like_count")
sns.lineplot(x=dates, y=cc, ax=ax2, color="green", label="comments_count")
ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%m/%d'), dates), rotation=45)
st.pyplot(fig)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
|
50786ac648b9a0214357869fa7aab304
|
{
"intermediate": 0.3593063950538635,
"beginner": 0.34495285153388977,
"expert": 0.2957407832145691
}
|
3,496
|
Consider a store that sells 6 items from item1-item6. Assume that the available quantity of each item is 50 and price of each item1-item6 is $4 per item. A buyer gets discount of 1%, 2%, 3%,4%, 5% and 6% respectively on item1-item6 per item for buying more than 10 items. For example, if a buyer purchases 5 of item1 and 11 of item2 he/she will get 2% discount on item2. Write a code that runs for five customers and updates the stock every time you are done with a customer. When you run the code it should first display the following message. (a) Welcome to our Test Store! (b) Your name please...Here you enter the buyer name When you enter it should display the current stock in the following form, item Qty Price/item Discount item1 50 4 1% .... ... ... ... In the next step it should ask the order from the buyer, Your order please...User will enter the name and quantity of the item(s) in the form of a dictionary When you press enter it should display user invoice in the following format Dear username thank you for shopping with us. Please find below your invoice. item Qty Price/item Discount Price item1 5 4 0% 20 item2 11 4 2% 38.46 ................... Total = 58.46 Also, create a txt file by name of user name and print the above invoice in it. Once you are done with the first customer start the process from step (b) for the second customer. Repeat these steps for all five customers and display the sales report on the screen in the following format. item Available Qty Sold Qty Revenue item1 ... ... ... 1 item2 ... ... ... ..................... Total Sale = ... Finally, print the sales report in a txt file by the name of ’SalesReport.txt’. You should define some functions such as get price(),get discount(), get stock() get sale(), etc., in a separate file to perform various required tasks. Then, connect these functions in an another file to complete the code.
|
6662d10367e2051d1146dbd16b7141db
|
{
"intermediate": 0.47347354888916016,
"beginner": 0.2889450192451477,
"expert": 0.23758144676685333
}
|
3,497
|
Is it not possible to specify the values to be inserted into a table in an order that doesn't match the order of the columns
|
9232418de4422b61f13acbd5001b7642
|
{
"intermediate": 0.4372125566005707,
"beginner": 0.1758686751127243,
"expert": 0.3869188129901886
}
|
3,498
|
hi bro
|
cc6ed4123ed1544e5a906ad961df82f0
|
{
"intermediate": 0.34584465622901917,
"beginner": 0.2482806295156479,
"expert": 0.40587475895881653
}
|
3,499
|
напиши код на питоне, который заходит на сайт https://www.poizon.us/collections/sneakers-1 , копирует название из селектора #gf-products > li:nth-child(1) > div > div > div.card__content > div.card__information > h3 > a , берет от туда же ссылку и переходит по ней, после перехода копирует цену из #price-template--16663852253403__main > div.price.price--large.price--show-badge > div > div.price__regular а затем берет ссылку на фото из #Slide-template--16663852253403__main-31937321107675 > modal-opener > div . Вносит данные в базу данных, выводит в консоли.Повторяет это со всеми товарами на странице
|
63e8b02d73ce9b93d529cfca4b9010bc
|
{
"intermediate": 0.30566084384918213,
"beginner": 0.4064376950263977,
"expert": 0.2879014015197754
}
|
3,500
|
does class "wrapper" affects anything in html or it's just name?
|
95b12b3a2251681d83e66e48c3a1ce5c
|
{
"intermediate": 0.18342344462871552,
"beginner": 0.6828897595405579,
"expert": 0.13368681073188782
}
|
3,501
|
combine feature branch into main branch without merge in git
|
0fee43f9910b1f56b0352693835c853a
|
{
"intermediate": 0.37884029746055603,
"beginner": 0.24968065321445465,
"expert": 0.3714790344238281
}
|
3,502
|
import requests
import json
import datetime
import streamlit as st
from itertools import zip_longest
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def basic_info():
config = dict()
config["access_token"] = st.secrets["access_token"]
config['instagram_account_id'] = st.secrets.get("instagram_account_id", "")
config["version"] = 'v16.0'
config["graph_domain"] = 'https://graph.facebook.com/'
config["endpoint_base"] = config["graph_domain"] + config["version"] + '/'
return config
def InstaApiCall(url, params, request_type):
if request_type == 'POST':
req = requests.post(url, params)
else:
req = requests.get(url, params)
res = dict()
res["url"] = url
res["endpoint_params"] = params
res["endpoint_params_pretty"] = json.dumps(params, indent=4)
res["json_data"] = json.loads(req.content)
res["json_data_pretty"] = json.dumps(res["json_data"], indent=4)
return res
def getUserMedia(params, pagingUrl=''):
Params = dict()
Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
if pagingUrl == '':
url = params['endpoint_base'] + params['instagram_account_id'] + '/media'
else:
url = pagingUrl
return InstaApiCall(url, Params, 'GET')
def getUser(params):
Params = dict()
Params['fields'] = 'followers_count'
Params['access_token'] = params['access_token']
if not params['endpoint_base']:
return None
url = params['endpoint_base'] + params['instagram_account_id']
return InstaApiCall(url, Params, 'GET')
def saveCount(count, filename):
with open(filename, 'w') as f:
json.dump(count, f, indent=4)
def getCount(filename):
try:
with open(filename, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.decoder.JSONDecodeError):
return {}
st.set_page_config(layout="wide")
params = basic_info()
count_filename = "count.json"
if not params['instagram_account_id']:
st.write('.envファイルでinstagram_account_idを確認')
else:
response = getUserMedia(params)
user_response = getUser(params)
if not response or not user_response:
st.write('.envファイルでaccess_tokenを確認')
else:
posts = response['json_data']['data'][::-1]
user_data = user_response['json_data']
followers_count = user_data.get('followers_count', 0)
NUM_COLUMNS = 6
MAX_WIDTH = 1000
BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS)
BOX_HEIGHT = 400
yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count)
st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True)
# グラフ表示用のデータを取得
count_data = getCount(count_filename)
post_ids = []
like_counts = []
comment_counts = []
dates = []
for date, posts in count_data.items():
if type(posts) is not dict:
continue
for post_id, post_values in posts.items():
if date not in dates:
dates.append(date)
if post_id == "followers_count":
continue
if post_id not in post_ids:
post_ids.append(post_id)
like_counts.append([])
comment_counts.append([])
idx = post_ids.index(post_id)
like_counts[idx].append(post_values['like_count'])
comment_counts[idx].append(post_values['comments_count'])
dates.sort()
df = pd.DataFrame({date: {"like_count": [], "comments_count": []} for date in dates},
index=post_ids)
for post_id, like_count, comment_count in zip(post_ids, like_counts, comment_counts):
for date, lc, cc in zip(dates, like_count, comment_count):
df.at[post_id, date] = {"like_count": lc, "comments_count": cc}
# 表示制御
show_summary_chart = st.checkbox("サマリーグラフを表示")
show_individual_chart = st.checkbox("いいね/コメント数グラフを表示")
show_description = st.checkbox("キャプションを表示")
# サマリーチャート
if show_summary_chart:
summary_data = {"followers_count": [], "like_count_sum": [], "comments_count_sum": []}
for date in dates:
summary_data["followers_count"].append(count_data[date]["followers_count"])
summary_data["like_count_sum"].append(sum([post['like_count'] for post in count_data[date].values() if type(post) is dict]))
summary_data["comments_count_sum"].append(sum([post['comments_count'] for post in count_data[date].values() if type(post) is dict]))
summary_df = pd.DataFrame(summary_data, index=dates)
fig_summary, ax = plt.subplots()
sns.lineplot(data=summary_df['followers_count'], ax=ax, color='lightblue', label='followers_count')
ax2 = ax.twinx()
sns.lineplot(data=summary_df['like_count_sum'], ax=ax2, color='orange', label='like_count')
sns.lineplot(data=summary_df['comments_count_sum'], ax=ax2, color='green', label='comments_count')
ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%m/%d'), dates), rotation=45)
st.pyplot(fig_summary)
posts.reverse()
post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
count = getCount(count_filename)
today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d')
if today not in count:
count[today] = {}
count[today]['followers_count'] = followers_count
if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59':
count[yesterday] = count[today]
max_like_diff = 0
max_comment_diff = 0
for post_group in post_groups:
for post in post_group:
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
max_like_diff = max(like_count_diff, max_like_diff)
max_comment_diff = max(comment_count_diff, max_comment_diff)
for post_group in post_groups:
with st.container():
columns = st.columns(NUM_COLUMNS)
for i, post in enumerate(post_group):
with columns[i]:
st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True)
st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}")
like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count'])
comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count'])
st.markdown(
f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>"
f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>",
unsafe_allow_html=True)
# いいね/コメント数グラフ
if show_individual_chart:
post_id = post["id"]
lc = df.at[post_id, date]["like_count"]
cc = df.at[post_id, date]["comments_count"]
fig, ax = plt.subplots(figsize=(6, 2))
ax2 = ax.twinx()
sns.lineplot(x=dates, y=lc, ax=ax, color="orange", label="like_count")
sns.lineplot(x=dates, y=cc, ax=ax2, color="green", label="comments_count")
ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%m/%d'), dates), rotation=45)
st.pyplot(fig)
caption = post['caption']
if caption is not None:
caption = caption.strip()
if "[Description]" in caption:
caption = caption.split("[Description]")[1].lstrip()
if "[Tags]" in caption:
caption = caption.split("[Tags]")[0].rstrip()
caption = caption.replace("#", "")
caption = caption.replace("[model]", "👗")
caption = caption.replace("[Equip]", "📷")
caption = caption.replace("[Develop]", "🖨")
if show_description:
st.write(caption or "No caption provided")
else:
st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided")
count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']}
saveCount(count, count_filename)
'''
上記のコードを実行すると、下記のエラーが表示されます。改修したコード全文を表示してください
'''
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [42], line 157
154 ax.set_xticklabels(map(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%m/%d'), dates), rotation=45)
155 st.pyplot(fig_summary)
--> 157 posts.reverse()
158 post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)]
160 count = getCount(count_filename)
AttributeError: 'dict' object has no attribute 'reverse'
|
07c47fc2f3a0c848fed736ae3982b2e0
|
{
"intermediate": 0.3593063950538635,
"beginner": 0.34495285153388977,
"expert": 0.2957407832145691
}
|
3,503
|
I have this code that I want to modify: import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set the path to the chromedriver executable
chromedriver_path = "C:\\Users\\GadopsiPro\\chromedriver.exe"
# Create a new instance of the Chrome WebDriver
driver = webdriver.Chrome(executable_path=chromedriver_path)
# Open the URL and wait for 3 seconds
url = "https://kartor.eniro.se/?c=58.358872,15.664444&z=10"
driver.get(url)
time.sleep(3)
# Wait for the accept cookies button to be clickable and click it
accept_cookies_button_xpath = "/html/body/div[1]/div/div/div/div[2]/div/button[3]/span"
wait = WebDriverWait(driver, 2)
accept_cookies_button = wait.until(EC.element_to_be_clickable((By.XPATH, accept_cookies_button_xpath)))
accept_cookies_button.click()
# Open the coordinates.txt file for writing
with open("coordinates.txt", "w", encoding="utf8") as f:
# Read the search queries from results.txt and search them one by one
with open("results.txt", "r", encoding="utf8") as g:
for line in g:
# Find the search box and enter the query
search_box_xpath = '//*[@id="page"]/div[11]/form/span/span[1]/input'
search_box = wait.until(EC.presence_of_element_located((By.XPATH, search_box_xpath)))
search_box.clear()
search_box.send_keys(line.strip())
# Press the enter key to perform the search and wait for 1 seconds
search_box.submit()
time.sleep(1)
# Click the first search result if found, and continue the loop otherwise
try:
first_result_xpath = '/html/body/div[2]/div[5]/div[2]/ul/li[1]/div/div[3]/div[3]'
first_result = wait.until(EC.presence_of_element_located((By.XPATH, first_result_xpath)))
first_result.click()
time.sleep(1.5)
# Extract the coordinates from the URL and write the name and coordinates to the coordinates.txt file
coordinates = driver.current_url.split("?c=")[1].split("&")[0]
f.write(line.strip() + "\t" + coordinates + "\n")
except:
# Write "Not Found" to the coordinates.txt file if no results are found
f.write(line.strip() + "\tNot Found\n")
continue
# Wait for 0.1 second before searching for the next query
time.sleep(0.1)
# Wait for 1 seconds before closing the browser window
time.sleep(1)
driver.quit()
|
5e1f1e716000fb816a19092b92c7fa9f
|
{
"intermediate": 0.32792288064956665,
"beginner": 0.4821387529373169,
"expert": 0.18993833661079407
}
|
3,504
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Flight;
// Structure to store information about a passenger
class Passenger {
string name;
string email;
string phone;
public:
Passenger(string name, string email, string phone) {
this->name = name;
this->email = email;
this->phone = phone;
}
void bookFlight(Flight* flight) {
flight->passengers.push_back(*this);
}
string getName() const {
return name;
}
string getEmail() const {
return email;
}
string getPhone() const {
return phone;
}
};
// Base class for airlines
class Airline {
protected:
string name;
public:
Airline(string name) {
this->name = name;
}
virtual double getTicketPrice() = 0; // pure virtual function
string getName() {
return name;
}
};
// Derived class for economy airlines
class EconomyAirline : public Airline {
public:
EconomyAirline() : Airline("Economy") {}
double getTicketPrice() {
return 100.00; // arbitrary ticket price for example purposes
}
};
// Derived class for business airlines
class BusinessAirline : public Airline {
public:
BusinessAirline() : Airline("Business") {}
double getTicketPrice() {
return 200.00; // arbitrary ticket price for example purposes
}
};
// Derived class for first class airlines
class FirstClassAirline : public Airline {
public:
FirstClassAirline() : Airline("First Class") {}
double getTicketPrice() {
return 300.00; // arbitrary ticket price for example purposes
}
};
// Structure to store information about a flight
struct Flight {
string flightNumber;
string source;
string destination;
string date;
string time;
Airline* airline;
vector<Passenger> passengers;
Flight(string flightNumber, string source, string destination, string date, string time, Airline* airline) {
this->flightNumber = flightNumber;
this->source = source;
this->destination = destination;
this->date = date;
this->time = time;
this->airline = airline;
}
string getSource() {
return source;
}
};
// Class for the airport system
class AirportSystem {
public:
vector<Flight> flights;
public:
void bookFlight(string flightNumber, string destination, string date, string time, Airline* airline, vector<Passenger> passengers) {
Flight flight(flightNumber, "", destination, date, time, airline);
flight.passengers = passengers;
flights.push_back(flight); // add the new flight object to the flights vector
cout << "Flight " << flightNumber << " booked successfully!" << endl;
}
void displayFlights() {
for (int i = 0; i < flights.size(); i++) {
Flight flight = flights[i];
cout << "Flight Number: " << flight.flightNumber << endl;
cout << "Source: " << flight.getSource() << endl;
cout << "Destination: " << flight.destination << endl;
cout << "Date: " << flight.date << endl;
cout << "Time: " << flight.time << endl;
cout << "Airline: " << flight.airline->getName() << endl;
cout << "Ticket Price: $" << flight.airline->getTicketPrice() << endl;
cout << "Passengers: " << endl;
for (int j = 0; j < flight.passengers.size(); j++) {
Passenger passenger = flight.passengers[j];
cout << "Name: " << passenger.getName() << ", Email: " << passenger.getEmail() << ", Phone: " << passenger.getPhone() << endl;
}
cout << endl;
}
}
};
int main() {
AirportSystem airportSystem;
// Create passengers
Passenger passenger1("John Smith", "johnsmith@example.com", "1234567890");
Passenger passenger2("Sarah Johnson", "sarahjohnson@example.com", "0987654321");
// Create airlines
Airline* economyAirline = new EconomyAirline();
Airline* businessAirline = new BusinessAirline();
Airline* firstClassAirline = new FirstClassAirline();
// Create flights
Flight* flight1 = new Flight("ABC123", "New York", "London", "2023-05-01", "10:00", economyAirline);
Flight* flight2 = new Flight("DEF456", "London", "Paris", "2023-05-01", "11:30", businessAirline);
Flight* flight3 = new Flight("GHI789", "Paris", "Tokyo", "2023-05-02", "01:00", firstClassAirline);
vector<Passenger> passengers1 = { passenger1 };
vector<Passenger> passengers2 = { passenger2 };
vector<Passenger> passengers3 = { passenger1, passenger2 };
airportSystem.flights.push_back(*flight1);
airportSystem.flights.push_back(*flight2);
airportSystem.flights.push_back(*flight3);
// Display flight details
airportSystem.displayFlights();
// Clean up memory
// delete economyAirline;
// delete businessAirline;
// delete firstClassAirline;
// delete flight1;
// delete flight2;
// delete flight3;
return 0;
}
correct this code
|
864f1b13e792e4db43b9fca8a8e17389
|
{
"intermediate": 0.27457883954048157,
"beginner": 0.5245574712753296,
"expert": 0.20086371898651123
}
|
3,505
|
now integrate this CSS only nighmode switcher into the multilingual page, so this "language-option" texts could be nightmoded:
|
8498053a2e8debce7328dafade265b96
|
{
"intermediate": 0.4163472354412079,
"beginner": 0.22670358419418335,
"expert": 0.3569491505622864
}
|
3,506
|
now integrate this CSS only nighmode switcher into the multilingual page, so this "language-option" texts could be nightmoded:
|
1d79da6afccdac96c377983210a1bd9c
|
{
"intermediate": 0.4163472354412079,
"beginner": 0.22670358419418335,
"expert": 0.3569491505622864
}
|
3,507
|
java code to implement a blockchain from scratch
|
68370cc6ab3891899ce283de8d2ffc72
|
{
"intermediate": 0.36626508831977844,
"beginner": 0.17956236004829407,
"expert": 0.4541725516319275
}
|
3,508
|
you are a security consultant, list top 100 javascript exploits for chrome browser actual for 2023 with minimal js usage examples and one string description, most important first, so we can review and fix them
|
fadfde983f4f1777aae2749955a566af
|
{
"intermediate": 0.2565840482711792,
"beginner": 0.41942235827445984,
"expert": 0.32399362325668335
}
|
3,509
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Flight;
// Structure to store information about a passenger
class Passenger {
string name;
string email;
string phone;
public:
Passenger(string name, string email, string phone) {
this->name = name;
this->email = email;
this->phone = phone;
}
void bookFlight(Flight* flight) {
flight->passengers.push_back(*this);
}
string getName() const {
return name;
}
string getEmail() const {
return email;
}
string getPhone() const {
return phone;
}
};
// Base class for airlines
class Airline {
protected:
string name;
public:
Airline(string name) {
this->name = name;
}
virtual double getTicketPrice() = 0; // pure virtual function
string getName() {
return name;
}
};
// Derived class for economy airlines
class EconomyAirline : public Airline {
public:
EconomyAirline() : Airline("Economy") {}
double getTicketPrice() {
return 100.00; // arbitrary ticket price for example purposes
}
};
// Derived class for business airlines
class BusinessAirline : public Airline {
public:
BusinessAirline() : Airline("Business") {}
double getTicketPrice() {
return 200.00; // arbitrary ticket price for example purposes
}
};
// Derived class for first class airlines
class FirstClassAirline : public Airline {
public:
FirstClassAirline() : Airline("First Class") {}
double getTicketPrice() {
return 300.00; // arbitrary ticket price for example purposes
}
};
// Structure to store information about a flight
struct Flight {
string flightNumber;
string source;
string destination;
string date;
string time;
Airline* airline;
vector<Passenger> passengers;
Flight(string flightNumber, string source, string destination, string date, string time, Airline* airline) {
this->flightNumber = flightNumber;
this->source = source;
this->destination = destination;
this->date = date;
this->time = time;
this->airline = airline;
}
string getSource() {
return source;
}
};
// Class for the airport system
class AirportSystem {
public:
vector<Flight> flights;
public:
void bookFlight(string flightNumber, string destination, string date, string time, Airline* airline, vector<Passenger> passengers) {
Flight flight(flightNumber, "", destination, date, time, airline);
flight.passengers = passengers;
flights.push_back(flight); // add the new flight object to the flights vector
cout << "Flight " << flightNumber << " booked successfully!" << endl;
}
void displayFlights() {
for (int i = 0; i < flights.size(); i++) {
Flight flight = flights[i];
cout << "Flight Number: " << flight.flightNumber << endl;
cout << "Source: " << flight.getSource() << endl;
cout << "Destination: " << flight.destination << endl;
cout << "Date: " << flight.date << endl;
cout << "Time: " << flight.time << endl;
cout << "Airline: " << flight.airline->getName() << endl;
cout << "Ticket Price: $" << flight.airline->getTicketPrice() << endl;
cout << "Passengers: " << endl;
for (int j = 0; j < flight.passengers.size(); j++) {
Passenger passenger = flight.passengers[j];
cout << "Name: " << passenger.getName() << ", Email: " << passenger.getEmail() << ", Phone: " << passenger.getPhone() << endl;
}
cout << endl;
}
}
};
int main() {
AirportSystem airportSystem;
// Create passengers
Passenger passenger1("John Smith", "johnsmith@example.com", "1234567890");
Passenger passenger2("Sarah Johnson", "sarahjohnson@example.com", "0987654321");
// Create airlines
Airline* economyAirline = new EconomyAirline();
Airline* businessAirline = new BusinessAirline();
Airline* firstClassAirline = new FirstClassAirline();
// Create flights
Flight* flight1 = new Flight("ABC123", "New York", "London", "2023-05-01", "10:00", economyAirline);
Flight* flight2 = new Flight("DEF456", "London", "Paris", "2023-05-01", "11:30", businessAirline);
Flight* flight3 = new Flight("GHI789", "Paris", "Tokyo", "2023-05-02", "01:00", firstClassAirline);
vector<Passenger> passengers1 = { passenger1 };
vector<Passenger> passengers2 = { passenger2 };
vector<Passenger> passengers3 = { passenger1, passenger2 };
airportSystem.flights.push_back(*flight1);
airportSystem.flights.push_back(*flight2);
airportSystem.flights.push_back(*flight3);
// Display flight details
airportSystem.displayFlights();
// Clean up memory
// delete economyAirline;
// delete businessAirline;
// delete firstClassAirline;
// delete flight1;
// delete flight2;
// delete flight3;
return 0;
}
correct this code
|
4a5bd9241817149ba6f5571506bb53d2
|
{
"intermediate": 0.27457883954048157,
"beginner": 0.5245574712753296,
"expert": 0.20086371898651123
}
|
3,510
|
#include <iostream>
#include <string>
#include <vector>
#include <memory> // for smart pointers
using namespace std;
class Flight;
// Structure to store information about a passenger
class Passenger {
string name;
string email;
string phone;
public:
Passenger(string name, string email, string phone) {
this->name = name;
this->email = email;
this->phone = phone;
}
void bookFlight(Flight* flight) {
flight->passengers.push_back(*this);
}
string getName() const {
return name;
}
string getEmail() const {
return email;
}
string getPhone() const {
return phone;
}
};
// Base class for airlines
class Airline {
protected:
string name;
public:
Airline(string name) {
this->name = name;
}
virtual double getTicketPrice() const = 0; // pure virtual function
string getName() const {
return name;
}
};
// Derived class for economy airlines
class EconomyAirline : public Airline {
public:
EconomyAirline() : Airline(“Economy”) {}
double getTicketPrice() const {
return 100.00; // arbitrary ticket price for example purposes
}
};
// Derived class for business airlines
class BusinessAirline : public Airline {
public:
BusinessAirline() : Airline(“Business”) {}
double getTicketPrice() const {
return 200.00; // arbitrary ticket price for example purposes
}
};
// Derived class for first class airlines
class FirstClassAirline : public Airline {
public:
FirstClassAirline() : Airline(“First Class”) {}
double getTicketPrice() const {
return 300.00; // arbitrary ticket price for example purposes
}
};
// Structure to store information about a flight
struct Flight {
string flightNumber;
string source;
string destination;
string date;
string time;
shared_ptr<Airline> airline; // using smart pointers
vector<Passenger> passengers;
Flight(string flightNumber, string source, string destination, string date, string time, shared_ptr<Airline> airline) {
this->flightNumber = flightNumber;
this->source = source;
this->destination = destination;
this->date = date;
this->time = time;
this->airline = airline;
}
string getSource() const { // making this a const member function
return source;
}
};
// Class for the airport system
class AirportSystem {
public:
vector<Flight> flights;
public:
void bookFlight(string flightNumber, string destination, string date, string time, shared_ptr<Airline> airline, Passenger passenger) {
vector<Passenger> passengers = { passenger };
Flight flight(flightNumber, “”, destination, date, time, airline);
flight.passengers = passengers;
flights.push_back(flight); // add the new flight object to the flights vector
cout << “Flight " << flightNumber << " booked successfully!” << endl;
}
void displayFlights() const { // making this a const member function
for (int i = 0; i < flights.size(); i++) {
Flight flight = flights[i];
cout << "Flight Number: " << flight.flightNumber << endl;
cout << "Source: " << flight.getSource() << endl;
cout << "Destination: " << flight.destination << endl;
cout << "Date: " << flight.date << endl;
cout << "Time: " << flight.time << endl;
cout << "Airline: " << flight.airline->getName() << endl;
cout << “Ticket Price: $” << flight.airline->getTicketPrice() << endl;
cout << "Passengers: " << endl;
for (int j = 0; j < flight.passengers.size(); j++) {
Passenger passenger = flight.passengers[j];
cout << "Name: " << passenger.getName() << ", Email: " << passenger.getEmail() << ", Phone: " << passenger.getPhone() << endl;
}
cout << endl;
}
}
};
int main() {
AirportSystem airportSystem;
// Create passengers
Passenger passenger1(“John Smith”, “johnsmith@example.com”, “1234567890”);
Passenger passenger2(“Sarah Johnson”, “sarahjohnson@example.com”, “0987654321”);
// Create airlines using smart pointers
shared_ptr<Airline> economyAirline = make_shared<EconomyAirline>();
shared_ptr<Airline> businessAirline = make_shared<BusinessAirline>();
shared_ptr<Airline> firstClassAirline = make_shared<FirstClassAirline>();
// Create flights using smart pointers
shared_ptr<Flight> flight1 = make_shared<Flight>(“ABC123”, “New York”, “London”, “2023-05-01”, “10:00”, economyAirline);
shared_ptr<Flight> flight2 = make_shared<Flight>(“DEF456”, “London”, “Paris”, “2023-05-01”, “11:30”, businessAirline);
shared_ptr<Flight> flight3 = make_shared<Flight>(“GHI789”, “Paris”, “Tokyo”, “2023-05-02”, “01:00”, firstClassAirline);
// Book flights for passengers
airportSystem.bookFlight(flight1->flightNumber, flight1->destination, flight1->date, flight1->time, flight1->airline, passenger1);
airportSystem.bookFlight(flight2->flightNumber, flight2->destination, flight2->date, flight2->time, flight2->airline, passenger2);
airportSystem.bookFlight(flight3->flightNumber, flight3->destination, flight3->date, flight3->time, flight3->airline, passenger1);
// Display flight details
airportSystem.displayFlights();
// Clean up memory using smart pointers
// No need to manually delete objects
return 0;
}
main.cpp: In member function ‘void Passenger::bookFlight(Flight*)’:
main.cpp:25:7: error: invalid use of incomplete type ‘class Flight’
25 | flight->passengers.push_back(*this);
| ^~
main.cpp:9:7: note: forward declaration of ‘class Flight’
9 | class Flight;
| ^~~~~~
|
36da39b1eca7e73b596c451150a473d5
|
{
"intermediate": 0.2595306932926178,
"beginner": 0.6163252592086792,
"expert": 0.12414409965276718
}
|
3,511
|
is it possible to put this nightmode switcher near these horizontal line of flags from the right side and adjust the sizes properly, using only css and html, without any javascripts. can you do this without ruining functionality of displaying text on flag click, select text ability independent of nightmode state?: <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSS-only Multilingual eco-friendly site</title>
<style>
.switch-container input[type="checkbox"] {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
}
.switch-container input[type="checkbox"]:checked ~ label:before {
opacity: 1;
}
body, html {
margin: 0;
padding: 0;
height: 100%;
line-height: 1.6;
background-color: #f7f7f7;
transition: background-color .5s, color .5s;
}
header {
background-color: #4CAF50;
color: #FFF;
padding: 16px 0px 0px 0px;
text-align: center;
position: relative;
transition: background-color .5s;
}
h1, h2, h3, h4, h5, h6 {
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 18px;
width: 90%;
height: 1%;
}
.left, .right {
position: relative;
}
.left::before, .right::before {
content: '';
position: absolute;
top: 50%;
border-bottom: 1px dashed #FFF;
width: 40%;
}
.left::before {
right: 100%;
margin-right: 20px;
}
.right::before {
left: 100%;
margin-left: 20px;
}
.flags-container {
position: fixed;
top: 0;
left: 0;
right: 0;
--padding: 3px 0;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
--box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
z-index: 1;
}
.flag-radio {
display: none;
}
.flag-label {
cursor: pointer;
margin: 0 10px;
transition: 0.3s;
opacity: 0.6;
font-size: 24px;
}
.flag-label:hover {
opacity: 1;
}
.language-option {
position: run-in;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: none;
justify-content: center;
align-items: center;
padding-top: 0px;
}
#english-flag:checked ~ #english,
#hindi-flag:checked ~ #hindi,
#hebrew-flag:checked ~ #hebrew,
#chinese-flag:checked ~ #chinese,
#french-flag:checked ~ #french,
#spanish-flag:checked ~ #spanish {
display: block;
}
#night-mode-toggle:checked ~ body,
#night-mode-toggle:checked ~ header,
#night-mode-toggle:checked ~ .language-option {
background-color: #333;
color: #FFF;
}
#night-mode-toggle:checked ~ .flags-container {
background-color: #444;
}
#night-mode-toggle:checked ~ .switch-container label {
color: #FFF;
}
.switch {
position: absolute;
cursor: pointer;
width: 60px;
height: 30px;
background-color: #FFF;
border-radius: 15px;
transition: background-color .5s;
}
.switch:before {
content: '';
display: block;
position: absolute;
top: 2px;
left: 2px;
height: 26px;
width: 26px;
background-color: #333;
border-radius: 50%;
transition: left .3s;
}
#night-mode-toggle:checked ~ .switch-container .switch {
background-color: #444;
}
#night-mode-toggle:checked ~ .switch-container .switch:before {
left: calc(100% - 28px);
}
</style>
</head>
<body>
<!-- Night Mode Switch -->
<input type="checkbox" id="night-mode-toggle" />
<div class="switch-container">
<div class="switch"></div>
<label for="night-mode-toggle">Energy saving nightmode layer</label>
</div>
<input id="english-flag" type="radio" name="flags" class="flag-radio">
<input id="hindi-flag" type="radio" name="flags" class="flag-radio">
<input id="hebrew-flag" type="radio" name="flags" class="flag-radio">
<input id="chinese-flag" type="radio" name="flags" class="flag-radio">
<input id="french-flag" type="radio" name="flags" class="flag-radio">
<input id="spanish-flag" type="radio" name="flags" class="flag-radio">
<div class="flags-container">
<label for="english-flag" class="flag-label">🇬🇧</label>
<label for="hindi-flag" class="flag-label">🇮🇳</label>
<label for="hebrew-flag" class="flag-label">🇮🇱</label>
<label for="chinese-flag" class="flag-label">🇨🇳</label>
<label for="french-flag" class="flag-label">🇫🇷</label>
<label for="spanish-flag" class="flag-label">🇪🇸</label>
</div><br>
<header>
<h1>
<span class="left">EcoWare</span>
<span class="right">Earthwise</span>
</h1>
</header>
<div id="english" class="language-option">
<p>english details going here</p>
</div>
<div id="hindi" class="language-option">
<p>hindi details going here</p>
</div>
<div id="hebrew" class="language-option">
<p>hebrew details going here</p>
</div>
<div id="chinese" class="language-option">
<p>chinese details going here</p>
</div>
<div id="french" class="language-option">
<p>french details going here</p>
</div>
<div id="spanish" class="language-option">
<p>spanish details going here</p>
</div>
</body>
</html>
|
e3868b7ef78632f3eeb3642f7c40f428
|
{
"intermediate": 0.40735283493995667,
"beginner": 0.40783873200416565,
"expert": 0.1848084032535553
}
|
3,512
|
here is my python app. i am able to open the search result file. but after opening the file and going back to the app the app doesnt respond. but after closing the file it responds. heres my code.
please fix that issue
import os
import tkinter as tk
from tkinter import filedialog, messagebox
import chardet
import configparser
import threading
import re
import sys
import time
import subprocess
pause_task = None
paused_search_var = None
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def browse_files():
filetypes = [("ATM Journals", "*.jrn"), ("All files", "*.*")]
files = filedialog.askopenfilenames(title="Select files", filetypes=filetypes)
if not files:
return
directory_entry.delete(0, tk.END)
directory_entry.insert(0, "||".join(files))
search_started = False
search_terminated = False
def search_files():
global search_started
search_started = True
search_terminated.set(False)
files_str = directory_entry.get()
keywords = keywords_entry.get()
if not files_str or not keywords:
error_message = ""
if not files_str:
error_message = "You have not selected any journals."
if not keywords:
if error_message:
error_message += "\n"
error_message += "You have not added any keywords."
messagebox.showerror("Error", error_message)
return
config = configparser.ConfigParser()
config.read("keywords.ini")
if "Keywords" not in config.sections():
config.add_section("Keywords")
config.set("Keywords", "search_keywords", keywords)
with open("keywords.ini", "w") as configfile:
config.write(configfile)
files = files_str.split("||")
if not files or not keywords:
message = "Please select files and enter keywords to search.\n\n"
messagebox.showerror("Error", message)
return
results_listbox.delete(0, tk.END)
content_text.delete(1.0, tk.END)
paused_search_var.set(False)
search_started = True
file_path = None
def search():
nonlocal file_path
for file_path in files:
if search_terminated.get():
break
while paused_search_var.get():
time.sleep(0.1)
if os.path.isfile(file_path):
content = None
with open(file_path, "rb") as f:
raw_data = f.read()
detected_encoding = chardet.detect(raw_data)["encoding"]
try:
with open(file_path, "r", encoding=detected_encoding) as f:
content = f.read()
except UnicodeDecodeError:
with open(file_path, "r", encoding="ISO-8859-1") as f:
content = f.read()
content_lower = content.lower()
for keyword in keywords.split(","):
keyword = keyword.strip()
keyword_lower = keyword.lower()
start = content_lower.find(keyword_lower)
while start != -1:
end = start + len(keyword)
result = f"{file_path}: {keyword}: {start}-{end}"
results_listbox.insert(tk.END, result)
start = content_lower.find(keyword_lower, end)
if search_terminated.get():
break
search_thread = threading.Thread(target=search)
search_thread.start()
while search_thread.is_alive():
app.update()
time.sleep(0.1)
if search_terminated.get():
break
if not results_listbox.get(0, tk.END):
messagebox.showinfo("Message", "No results were found.")
else:
messagebox.showinfo("Message", "Search completed.")
pause_button.config(text="Pause")
paused_search_var.set(False)
if instance_data:
display_instance(-1, file_path)
search_started = False
def index_to_line_col(text_widget, index):
return tuple(map(int, text_widget.index(index).split(".")))
instance_data = []
def show_file_content(event):
selection = results_listbox.curselection()
if not selection:
return
result = results_listbox.get(selection[0])
filename, keyword, indices_str = result.split(": ")
indices = tuple(map(int, indices_str.split("-")))
instance_data.append((filename, keyword, indices))
file_path = filename
display_instance(-1, file_path)
def open_file(event):
selection = results_listbox.curselection()
if not selection:
return
result = results_listbox.get(selection[0])
filename, keyword, indices_str = result.split(": ")
file_path = os.path.join(directory_entry.get(), filename)
subprocess.run(["notepad.exe", file_path], check=True)
def display_instance(instance_index, file_path):
filename, keyword, indices = instance_data[instance_index]
def read_file():
with open(file_path, "r", encoding="ISO-8859-1") as file:
content = file.read()
return content
def highlight_keyword(content):
keyword_pattern = re.compile(re.escape(keyword), re.IGNORECASE)
match = keyword_pattern.search(content, indices[0])
if match:
start = match.start()
end = match.end()
start_line_col = content_text.index(f"1.0+{start}c")
end_line_col = content_text.index(f"1.0+{end}c")
content_text.tag_remove("highlight", "1.0", tk.END)
content_text.tag_add("highlight", start_line_col, end_line_col)
content_text.tag_configure("highlight", background="yellow")
content_text.see(start_line_col)
content_text.delete(1.0, tk.END)
content_text.insert(tk.END, "Loading...")
def update_content():
content = read_file()
content_text.delete(1.0, tk.END)
content_text.insert(tk.END, content)
highlight_keyword(content)
thread = threading.Thread(target=update_content)
thread.start()
def start_search():
search_thread = threading.Thread(target=search_files)
search_thread.start()
def pause_search():
global search_started, paused_search_var
if not search_started:
messagebox.showerror("Error", "Search process has not begun.")
return
if paused_search_var.get():
pause_button.config(text="Pause")
paused_search_var.set(False)
else:
if not results_listbox.get(0, tk.END):
return
pause_button.config(text="Resume")
paused_search_var.set(True)
def reset():
global search_started
if search_started:
if not paused_search_var.get():
messagebox.showerror(
"Error", "Please pause the current search before resetting."
)
else:
search_terminated.set(True)
search_started = False
directory_entry.delete(0, tk.END)
results_listbox.delete(0, tk.END)
content_text.delete(1.0, tk.END)
instance_data.clear()
search_started = False
search_terminated.set(False)
else:
directory_entry.delete(0, tk.END)
results_listbox.delete(0, tk.END)
content_text.delete(1.0, tk.END)
instance_data.clear()
search_started = False
def close_app():
global search_started
if search_started:
search_terminated.set(True)
if messagebox.askyesno("Exit", "Do you want to close the application?"):
app.destroy()
def show_about():
messagebox.showinfo("About", "Coded by U2816.")
app = tk.Tk()
app.protocol("WM_DELETE_WINDOW", lambda: close_app())
app.title("ATM Journal Searcher")
app.geometry("637x581")
app.resizable(False, False)
icon_path = resource_path("icon.ico")
app.iconbitmap(icon_path)
paused_search_var = tk.BooleanVar()
search_terminated = tk.BooleanVar()
directory_label = tk.Label(app, text="Directory:")
directory_label.place(x=10, y=10)
directory_entry = tk.Entry(app, width=70)
directory_entry.place(x=80, y=12)
browse_button = tk.Button(app, text="Browse", width=15, command=browse_files)
browse_button.place(x=510, y=10)
keywords_label = tk.Label(app, text="Keywords:")
keywords_label.place(x=10, y=40)
keywords_entry = tk.Entry(app, width=70)
keywords_entry.place(x=80, y=42)
search_button = tk.Button(app, text="Search", width=15, command=search_files)
search_button.place(x=510, y=40)
results_scrollbar = tk.Scrollbar(app)
results_scrollbar.place(x=610, y=70, height=146)
results_listbox = tk.Listbox(
app, width=100, height=9, yscrollcommand=results_scrollbar.set
)
results_listbox.place(x=10, y=70)
results_scrollbar.config(orient="vertical", command=results_listbox.yview)
results_listbox.bind("<<ListboxSelect>>", show_file_content)
results_listbox.bind("<Double-1>", open_file)
content_label = tk.Label(app, text="Content:")
content_label.place(x=10, y=220)
content_text = tk.Text(app, wrap=tk.WORD, width=75, height=18)
content_text.place(x=10, y=244)
scrollbar = tk.Scrollbar(app, command=content_text.yview)
scrollbar.place(x=610, y=244, height=293)
content_text.config(yscrollcommand=scrollbar.set)
reset_search_button = tk.Button(app, text="Reset", width=15, command=reset)
reset_search_button.place(x=10, y=545)
pause_button = tk.Button(app, text="Pause", width=15, command=pause_search)
pause_button.place(x=130, y=545)
about_button = tk.Button(app, text="About", width=15, command=show_about)
about_button.place(x=250, y=545)
instruction_label = tk.Label(
app, text="(Single-click to view content, Double-click to open file)"
)
instruction_label.place(x=163, y=220)
config = configparser.ConfigParser()
config.read("keywords.ini")
if "Keywords" in config.sections() and "search_keywords" in config.options("Keywords"):
keywords_entry.insert(0, config.get("Keywords", "search_keywords"))
app.mainloop()
|
f7ca552baf212479a5e367e4bf8d9f24
|
{
"intermediate": 0.43072015047073364,
"beginner": 0.35774368047714233,
"expert": 0.21153616905212402
}
|
3,513
|
Can I include object code the has both C and c++ linkages to the same library?
|
3e5d33f9f25f08ed4acdd315d6abc9f0
|
{
"intermediate": 0.7252136468887329,
"beginner": 0.15201854705810547,
"expert": 0.12276781350374222
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.