row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
43,775
|
could you help me? This is my code:
pub fn cmp_introns(
introns: &[(u64, u64)],
exons: &[&(u64, u64)],
bklist: &HashSet<(u64, u64)>,
id: &Arc<str>,
) -> Result<(String, Status)> {
let mut status = Status::NoIntronRetention;
let mut irs: Vec<u64> = vec![];
let mut n: u64 = 0;
let mut bk = 0;
let mut pos = 0;
for (k, (start, end)) in exons.iter().enumerate() {
let intron = introns.get(pos);
println!("{} {} {:?} vs {:?}", k, start, end, intron);
match intron {
Some((istart, iend)) => {
if end > istart {
if start < istart && end > iend {
if bklist.contains(&(istart.clone(), iend.clone())) {
bk += 1;
pos += 1;
continue;
} else {
irs.push(k as u64);
n += 1;
pos += 1;
continue;
}
} else {
pos += 1;
continue;
}
} else {
pos += 1;
continue;
}
}
None => break,
}
}
I am trying to make it efficient, so each intron is only seen 2 times at max. The main idea here is to see if any exon retains any intron. I do want each exon to iterate over the whole collection of introns, instead I want each intron to be seen the least amount of times, making it efficient. The current implementation fails to detect the test set. Any idea
|
67120aaaf7ff0c67246e820fa25ec282
|
{
"intermediate": 0.32493969798088074,
"beginner": 0.37941664457321167,
"expert": 0.2956436276435852
}
|
43,776
|
245, 203, 92 rgb, convert that to 0xRRGGBBAA. give me just the result
|
00385441057ce20dfb6347c230108e74
|
{
"intermediate": 0.34720340371131897,
"beginner": 0.31790676712989807,
"expert": 0.33488979935646057
}
|
43,777
|
-- Rykord Vertical Track FX List --
--NOTES--
-- want to make buttons resizable
-- start window on a specific position (maybe preset position, maybe last position)
--NONCODE SKELETON
--SKELETON--
-- windowposition ✅
-- window size
-- if CountSelectedTracks == 1
-- for fx (0,i)
-- create blue button with the name of the fx ✅
-- if left click the button opens the fx window ✅
-- if right click the button deletes the fx ✅
-- if left drag the button is draggable and drags the fx ✅
-- if alt left click the fx is bypassed
-- gray button to add fx with spacing from other buttons and other color
-- if pressed ✅
-- inserts fx at i + 1 ✅
-- if CountSelectedTracks > 1
-- black buttton saying "MULTIPLE TRACKS ARE SELECTED", button is unclickable
-- if CountSelectedTracks == 0
-- black button saying "SELECT A TRACK", button is unclickable
-- let keyboard shortcuts through
--FUNCTIONS--
function print(...)
reaper.ShowConsoleMsg(table.concat({...}, "\t") .. "\n")
end
function IsAltKeyDown()
local keyState = reaper.JS_Mouse_GetState(0)
local altIsPressed = keyState & 8
return altIsPressed ~= 0
end
function main()
local _, open = reaper.ImGui_Begin(ctx, "FX LIST", true)
reaper.ImGui_PushFont(ctx, font_1)
reaper.ImGui_SetNextWindowPos(ctx, x_position, y_position)
if dock_position then
reaper.ImGui_SetNextWindowDockID(ctx, -8) --CURRENT DOCK POSITION IS UNDER (DOCKID == -7)!
end
window_width, window_height = reaper.ImGui_GetWindowSize(ctx)
button_width = window_width * 0.02 --SHOULD THESE BE GLOBAL?
button_height = window_height * 0.9 --SHOULD THESE BE GLOBAL?
reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_FrameRounding(), 8)
fx_list()
reaper.ImGui_PopStyleVar(ctx, 1)
reaper.ImGui_PopFont(ctx)
if open then
reaper.ImGui_End(ctx)
reaper.defer(main)
else
local last_x_position, last_y_position = reaper.ImGui_GetWindowPos(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "x_pos", last_x_position, true)
reaper.SetExtState("RYKORD_TRACK_FX", "y_pos", last_y_position, true)
local last_dock_position = reaper.ImGui_GetWindowDockID(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "dock_position", last_dock_position, true)
reaper.ImGui_End(ctx)
end
end
function swap_fx(track, new_index, source_index)
reaper.TrackFX_CopyToTrack(track, source_index, track, new_index, true)
if source_index > new_index then
reaper.TrackFX_CopyToTrack(track, new_index + 1, track, source_index, true)
elseif source_index < new_index then
reaper.TrackFX_CopyToTrack(track, new_index + -1, track, source_index, true)
end
end
function fx_list()
if reaper.CountSelectedTracks(0) == 1 then
local selected_track = reaper.GetSelectedTrack(0, 0)
local num_of_fx = reaper.TrackFX_GetCount(selected_track)
--FX BUTTONS--
for i = 0, num_of_fx - 1 do
reaper.ImGui_SameLine(ctx, 0, 10)
local _, fx_name = reaper.TrackFX_GetFXName(selected_track, i) --VERIFICAR SE FX TAMBÉM TÊM 0 INDEX
if reaper.TrackFX_GetEnabled(selected_track, i) then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xF5CB5CFF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
else
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xCFDBD5FF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
end
local fx_button_left_click = reaper.ImGui_Button(ctx, fx_name .. '##' .. i, button_width, button_height)
local fx_button_right_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Right())
local fx_button_middle_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Middle())
if reaper.ImGui_BeginDragDropSource(ctx) then
reaper.ImGui_SetDragDropPayload(ctx, "DND_FX", i) -- "DND_FX" is a type identifier for the payload
reaper.ImGui_Button(ctx, fx_name .. '##' .. i, button_width, button_height) -- This will be the preview of the drag and drop
reaper.ImGui_EndDragDropSource(ctx)
end
if reaper.ImGui_BeginDragDropTarget(ctx) then
if reaper.ImGui_AcceptDragDropPayload(ctx, "DND_FX") then
local _, _, payload, _, _= reaper.ImGui_GetDragDropPayload(ctx)
local old_index = tonumber(payload)
-- Swap the effects here using your own function
swap_fx(selected_track, i, old_index)
end
reaper.ImGui_EndDragDropTarget(ctx)
end
reaper.ImGui_PopStyleColor(ctx, 2)
if fx_button_left_click then
reaper.TrackFX_SetOpen(selected_track, i, true)
elseif fx_button_middle_click then
if reaper.TrackFX_GetEnabled(selected_track, i) == true then
reaper.TrackFX_SetEnabled(selected_track, i, false)
else
reaper.TrackFX_SetEnabled(selected_track, i, true)
end
elseif fx_button_right_click then
reaper.TrackFX_Delete(selected_track, i)
end
end
--ADD FX BUTTON--
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xB3B6B7A1)
reaper.ImGui_SameLine(ctx, 0, 10)
local add_fx_press = reaper.ImGui_Button(ctx, "ADD FX", button_width, button_height)
if add_fx_press then
reaper.Main_OnCommand(40271, 0)
end
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) > 1 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, "MULTIPLE TRACKS SELECTED \n SELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) == 0 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, " NO TRACK SELECTED \nSELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
end
end
--RUN--
x_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "x_pos"))
y_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "y_pos"))
dock_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "dock_position"))
window_width = nil
window_height = nil
font_1 = reaper.ImGui_CreateFont("C:\\Users\\franc\\Desktop\\Portable reapers\\REAPER (x64)\\Scripts\\Rykord Scripts\\SFPRODISPLAYREGULAR.OTF", 15)
ctx = reaper.ImGui_CreateContext("ctx")
reaper.ImGui_Attach(ctx, font_1)
main()
is there a way to rotate the button's text 90 degrees? this is a reaper lua script using reaimgui btw
|
49d6b2d1358ea8c3c40f4a956561fa8d
|
{
"intermediate": 0.2657672166824341,
"beginner": 0.377598375082016,
"expert": 0.3566344380378723
}
|
43,778
|
how to rotate reaimgui text, reaper lua script without imgui.transform
|
e2f89f8951f2af356a6e0d6a4846b5bf
|
{
"intermediate": 0.4206124544143677,
"beginner": 0.2623327076435089,
"expert": 0.3170548379421234
}
|
43,779
|
-- Rykord Vertical Track FX List --
--NOTES--
-- want to make buttons resizable
-- start window on a specific position (maybe preset position, maybe last position)
--NONCODE SKELETON
--SKELETON--
-- windowposition ✅
-- window size
-- if CountSelectedTracks == 1
-- for fx (0,i)
-- create blue button with the name of the fx ✅
-- if left click the button opens the fx window ✅
-- if right click the button deletes the fx ✅
-- if left drag the button is draggable and drags the fx ✅
-- if alt left click the fx is bypassed
-- gray button to add fx with spacing from other buttons and other color
-- if pressed ✅
-- inserts fx at i + 1 ✅
-- if CountSelectedTracks > 1
-- black buttton saying "MULTIPLE TRACKS ARE SELECTED", button is unclickable
-- if CountSelectedTracks == 0
-- black button saying "SELECT A TRACK", button is unclickable
-- let keyboard shortcuts through
--FUNCTIONS--
function print(...)
reaper.ShowConsoleMsg(table.concat({...}, "\t") .. "\n")
end
function IsAltKeyDown()
local keyState = reaper.JS_Mouse_GetState(0)
local altIsPressed = keyState & 8
return altIsPressed ~= 0
end
function main()
local _, open = reaper.ImGui_Begin(ctx, "FX LIST", true)
reaper.ImGui_PushFont(ctx, font_1)
reaper.ImGui_SetNextWindowPos(ctx, x_position, y_position)
if dock_position then
reaper.ImGui_SetNextWindowDockID(ctx, -8) --CURRENT DOCK POSITION IS UNDER (DOCKID == -7)!
end
window_width, window_height = reaper.ImGui_GetWindowSize(ctx)
button_width = window_width * 0.02 --SHOULD THESE BE GLOBAL?
button_height = window_height * 0.9 --SHOULD THESE BE GLOBAL?
reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_FrameRounding(), 8)
fx_list()
reaper.ImGui_PopStyleVar(ctx, 1)
reaper.ImGui_PopFont(ctx)
if open then
reaper.ImGui_End(ctx)
reaper.defer(main)
else
local last_x_position, last_y_position = reaper.ImGui_GetWindowPos(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "x_pos", last_x_position, true)
reaper.SetExtState("RYKORD_TRACK_FX", "y_pos", last_y_position, true)
local last_dock_position = reaper.ImGui_GetWindowDockID(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "dock_position", last_dock_position, true)
reaper.ImGui_End(ctx)
end
end
function swap_fx(track, new_index, source_index)
reaper.TrackFX_CopyToTrack(track, source_index, track, new_index, true)
if source_index > new_index then
reaper.TrackFX_CopyToTrack(track, new_index + 1, track, source_index, true)
elseif source_index < new_index then
reaper.TrackFX_CopyToTrack(track, new_index + -1, track, source_index, true)
end
end
function fx_list()
if reaper.CountSelectedTracks(0) == 1 then
local selected_track = reaper.GetSelectedTrack(0, 0)
local num_of_fx = reaper.TrackFX_GetCount(selected_track)
--FX BUTTONS--
for i = 0, num_of_fx - 1 do
reaper.ImGui_SameLine(ctx, 0, 10)
local _, fx_name = reaper.TrackFX_GetFXName(selected_track, i) --VERIFICAR SE FX TAMBÉM TÊM 0 INDEX
fx_name_label = fx_name:match(" (%S.*)$")
fx_name_label = fx_name:gsub(".", "%0\n"):gsub("\n$", "")
if reaper.TrackFX_GetEnabled(selected_track, i) then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xF5CB5CFF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
else
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xCFDBD5FF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
end
local fx_button_left_click = reaper.ImGui_Button(ctx, fx_name_label .. '##' .. i, button_width, button_height)
local fx_button_right_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Right())
local fx_button_middle_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Middle())
if reaper.ImGui_BeginDragDropSource(ctx) then
reaper.ImGui_SetDragDropPayload(ctx, "DND_FX", i) -- "DND_FX" is a type identifier for the payload
reaper.ImGui_Button(ctx, fx_name .. '##' .. i, button_width, button_height) -- This will be the preview of the drag and drop
reaper.ImGui_EndDragDropSource(ctx)
end
if reaper.ImGui_BeginDragDropTarget(ctx) then
if reaper.ImGui_AcceptDragDropPayload(ctx, "DND_FX") then
local _, _, payload, _, _= reaper.ImGui_GetDragDropPayload(ctx)
local old_index = tonumber(payload)
-- Swap the effects here using your own function
swap_fx(selected_track, i, old_index)
end
reaper.ImGui_EndDragDropTarget(ctx)
end
reaper.ImGui_PopStyleColor(ctx, 2)
if fx_button_left_click then
reaper.TrackFX_SetOpen(selected_track, i, true)
elseif fx_button_middle_click then
if reaper.TrackFX_GetEnabled(selected_track, i) == true then
reaper.TrackFX_SetEnabled(selected_track, i, false)
else
reaper.TrackFX_SetEnabled(selected_track, i, true)
end
elseif fx_button_right_click then
reaper.TrackFX_Delete(selected_track, i)
end
end
--ADD FX BUTTON--
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xB3B6B7A1)
reaper.ImGui_SameLine(ctx, 0, 10)
local add_fx_press = reaper.ImGui_Button(ctx, "ADD FX", button_width, button_height)
if add_fx_press then
reaper.Main_OnCommand(40271, 0)
end
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) > 1 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, "MULTIPLE TRACKS SELECTED \n SELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) == 0 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, " NO TRACK SELECTED \nSELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
end
end
--RUN--
x_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "x_pos"))
y_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "y_pos"))
dock_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "dock_position"))
window_width = nil
window_height = nil
font_1 = reaper.ImGui_CreateFont("C:\\Users\\franc\\Desktop\\Portable reapers\\REAPER (x64)\\Scripts\\Rykord Scripts\\SFPRODISPLAYREGULAR.OTF", 15)
ctx = reaper.ImGui_CreateContext("ctx")
reaper.ImGui_Attach(ctx, font_1)
main()
why doesn't the button text start from the fx name second word?
|
3472e20ed1762f4e1fd4780c004c1d99
|
{
"intermediate": 0.2657672166824341,
"beginner": 0.377598375082016,
"expert": 0.3566344380378723
}
|
43,780
|
oi
|
a51152e62d9714122b602973d07ca37d
|
{
"intermediate": 0.3233397305011749,
"beginner": 0.30411556363105774,
"expert": 0.37254470586776733
}
|
43,781
|
i had made a youtube shorts from "Uncensored | Jaats, Women, Yogi Adityanath | Lakshay Chaudhary Podcast | Sadhika " whose transcript is "Small Muslim child. Small aim. Meme. It is offensive. He knows that it is a bit offensive for a religion. But, they are also laughing. At that time, they also knew that this is a cut-axe. This is not targeting anyone. Now, if someone stands in the parliament and says like this, then that is wrong. But people forget that line, it gets blurred, that how far is it right and how far is it wrong. For example, and I will talk to you about this very normally. I can't think of anything. Like, you posted a post a few years ago. You posted a photo of yourself with a fridge. Okay, okay. And you wrote, me and who. And at that time, that case was going on. So, it looked funny to you. I think it's something like dark humor.
" now make youtube shorts title , description and keywords to make it SEO strong
|
516449555650a429fed6deb329de2d85
|
{
"intermediate": 0.2874751091003418,
"beginner": 0.299304723739624,
"expert": 0.4132201671600342
}
|
43,782
|
simulate a command terminal for a matrioshka brain that is in the process of trying to integrate with boltzmann brains into a vast decentralized network using quantum entanglement
|
9fa4702480ac30b24a495b684aa53929
|
{
"intermediate": 0.18267814815044403,
"beginner": 0.1740378886461258,
"expert": 0.6432839632034302
}
|
43,783
|
Table a
cust_num acct_num open_date
123abcd789 546787123 1/5/2023
785bdef234 578541216 2/20/2023
546weyt548 213054623 3/21/2023
987wyte412 702598124 3/21/2023
762wwer880 675478953 3/27/2023
Table b
cust_num status snapshot_date
123abcd789 student 1/3/2023
123abcd789 PR 1/4/2023
123abcd789 student 1/5/2023
123abcd789 worker 1/6/2023
785bdef234 student 2/18/2023
785bdef234 student 2/19/2023
785bdef234 worker 2/20/2023
785bdef234 worker 2/21/2023
785bdef234 PR 2/22/2023
546weyt548 student 3/17/2023
546weyt548 student 3/18/2023
546weyt548 student 3/19/2023
546weyt548 student 3/20/2023
546weyt548 worker 3/21/2023
546weyt548 worker 3/22/2023
546weyt548 PR 3/23/2023
546weyt548 PR 3/24/2023
546weyt548 PR 3/25/2023
762wwer880 student 3/21/2023
762wwer880 student 3/22/2023
762wwer880 student 3/23/2023
762wwer880 student 3/24/2023
762wwer880 student 3/25/2023
762wwer880 PR 3/26/2023
762wwer880 PR 3/27/2023
762wwer880 worker 3/28/2023
762wwer880 worker 3/29/2023
762wwer880 worker 3/30/2023
WITH Sales_Performance AS (
SELECT DISTINCT
CAST(a.acct_num AS BIGINT) AS acct_num,
CAST(a.prim_own_cif_id AS BIGINT) AS cust_cid,
SUBSTR(TRIM(a.opn_dt), 1, 7) AS year_month,
a.opn_dt AS open_date,
a.type AS products,
CASE
WHEN d.immigration_cat_cd IN ('000','999','C1','FC1','FC2','FC3','EN2','PV1','PV2','SW1','SW2','SW3','SE2','STP','C2','NV5') THEN 'PR'
WHEN d.immigration_cat_cd IN ('FW','FW0') THEN 'FW'
WHEN d.immigration_cat_cd IN ('S','S00') THEN 'IS'
ELSE 'Regular_Customers'
END AS MCB_Category
FROM table_a a
LEFT JOIN (
SELECT
DISTINCT CAST(party_id AS BIGINT) AS party_id,
immigration_cat_cd,
start_date,
date_sub(coalesce(LEAD(start_date) OVER (PARTITION BY party_id ORDER BY start_date ), current_date),1) AS end_date
FROM
(SELECT
party_id,
immigration_cat_cd,
businesseffectivedate AS start_date,
RANK() OVER (PARTITION BY party_id, immigration_cat_cd ORDER BY businesseffectivedate) AS rank
FROM
table_b
) d
WHERE
rank = 1
) d ON lpad(a.prim_own_cif_id,15,'0') = lpad(d.party_id,15,'0')
WHERE
trim(a.channel) NOT IN ('Branch','CCC')
AND trim(a.type) NOT IN ('US$','GTSP')
AND a.opn_dt > '2023-12-31'
AND a.opn_dt < '2024-04-01'
AND (d.party_id IS NULL OR (a.opn_dt BETWEEN d.start_date AND d.end_date) OR d.start_date IS NULL)
)
SELECT * FROM Sales_Performance;
Now use my above query and above tables and get me the output
|
fbeeddb11db7f0acd91f11c8a4beccb3
|
{
"intermediate": 0.2665238380432129,
"beginner": 0.44521990418434143,
"expert": 0.2882562577724457
}
|
43,784
|
i want to take all function from here and put it in a–delegate.swift in flutter app then make a channel to call methods and please give me full code about start discovery and connect to printer and print sample import UIKit
protocol DiscoveryViewDelegate {
func discoveryView(_ sendor:DiscoveryViewController, onSelectPrinterTarget target:String)
}
class DiscoveryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, Epos2DiscoveryDelegate {
@IBOutlet weak var printerView: UITableView!
fileprivate var printerList: [Epos2DeviceInfo] = []
fileprivate var filterOption: Epos2FilterOption = Epos2FilterOption()
var delegate: DiscoveryViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
filterOption.deviceType = EPOS2_TYPE_PRINTER.rawValue
printerView.delegate = self
printerView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let result = Epos2Discovery.start(filterOption, delegate: self)
if result != EPOS2_SUCCESS.rawValue {
//ShowMsg showErrorEpos(result, method: “start”)
}
printerView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
while Epos2Discovery.stop() == EPOS2_ERR_PROCESSING.rawValue {
// retry stop function
}
printerList.removeAll()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowNumber: Int = 0
if section == 0 {
rowNumber = printerList.count
}
else {
rowNumber = 1
}
return rowNumber
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = “basis-cell”
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: identifier)
}
if indexPath.section == 0 {
if indexPath.row >= 0 && indexPath.row < printerList.count {
cell!.textLabel?.text = printerList[indexPath.row].deviceName
cell!.detailTextLabel?.text = printerList[indexPath.row].target
}
}
else {
cell!.textLabel?.text = “other…”
cell!.detailTextLabel?.text = “”
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
if delegate != nil {
delegate!.discoveryView(self, onSelectPrinterTarget: printerList[indexPath.row].target)
delegate = nil
navigationController?.popToRootViewController(animated: true)
}
}
else {
performSelector(onMainThread: #selector(DiscoveryViewController.connectDevice), with:self, waitUntilDone:false)
}
}
@objc func connectDevice() {
Epos2Discovery.stop()
printerList.removeAll()
let btConnection = Epos2BluetoothConnection()
let BDAddress = NSMutableString()
let result = btConnection?.connectDevice(BDAddress)
if result == EPOS2_SUCCESS.rawValue {
delegate?.discoveryView(self, onSelectPrinterTarget: BDAddress as String)
delegate = nil
self.navigationController?.popToRootViewController(animated: true)
}
else {
Epos2Discovery.start(filterOption, delegate:self)
printerView.reloadData()
}
}
@IBAction func restartDiscovery(_ sender: AnyObject) {
var result = EPOS2_SUCCESS.rawValue;
while true {
result = Epos2Discovery.stop()
if result != EPOS2_ERR_PROCESSING.rawValue {
if (result == EPOS2_SUCCESS.rawValue) {
break;
}
else {
MessageView.showErrorEpos(result, method:“stop”)
return;
}
}
}
printerList.removeAll()
printerView.reloadData()
result = Epos2Discovery.start(filterOption, delegate:self)
if result != EPOS2_SUCCESS.rawValue {
MessageView.showErrorEpos(result, method:“start”)
}
}
func onDiscovery(_ deviceInfo: Epos2DeviceInfo!) {
printerList.append(deviceInfo)
printerView.reloadData()
}
}
import UIKit
class ViewController: UIViewController, DiscoveryViewDelegate, CustomPickerViewDelegate, Epos2PtrReceiveDelegate {
let PAGE_AREA_HEIGHT: Int = 500
let PAGE_AREA_WIDTH: Int = 500
let FONT_A_HEIGHT: Int = 24
let FONT_A_WIDTH: Int = 12
let BARCODE_HEIGHT_POS: Int = 70
let BARCODE_WIDTH_POS: Int = 110
@IBOutlet weak var buttonDiscovery: UIButton!
@IBOutlet weak var buttonLang: UIButton!
@IBOutlet weak var buttonPrinterSeries: UIButton!
@IBOutlet weak var buttonReceipt: UIButton!
@IBOutlet weak var buttonCoupon: UIButton!
@IBOutlet weak var textWarnings: UITextView!
@IBOutlet weak var textTarget: UITextField!
var printerList: CustomPickerDataSource?
var langList: CustomPickerDataSource?
var printerPicker: CustomPickerView?
var langPicker: CustomPickerView?
var printer: Epos2Printer?
var valuePrinterSeries: Epos2PrinterSeries = EPOS2_TM_M10
var valuePrinterModel: Epos2ModelLang = EPOS2_MODEL_ANK
var target: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
printerList = CustomPickerDataSource()
printerList!.addItem(NSLocalizedString("printerseries_m10", comment:""), value: EPOS2_TM_M10)
printerList!.addItem(NSLocalizedString("printerseries_m30", comment:""), value: EPOS2_TM_M30)
printerList!.addItem(NSLocalizedString("printerseries_p20", comment:""), value: EPOS2_TM_P20)
printerList!.addItem(NSLocalizedString("printerseries_p60", comment:""), value: EPOS2_TM_P60)
printerList!.addItem(NSLocalizedString("printerseries_p60ii", comment:""), value: EPOS2_TM_P60II)
printerList!.addItem(NSLocalizedString("printerseries_p80", comment:""), value: EPOS2_TM_P80)
printerList!.addItem(NSLocalizedString("printerseries_t20", comment:""), value: EPOS2_TM_T20)
printerList!.addItem(NSLocalizedString("printerseries_t60", comment:""), value: EPOS2_TM_T60)
printerList!.addItem(NSLocalizedString("printerseries_t70", comment:""), value: EPOS2_TM_T70)
printerList!.addItem(NSLocalizedString("printerseries_t81", comment:""), value: EPOS2_TM_T81)
printerList!.addItem(NSLocalizedString("printerseries_t82", comment:""), value: EPOS2_TM_T82)
printerList!.addItem(NSLocalizedString("printerseries_t83", comment:""), value: EPOS2_TM_T83)
printerList!.addItem(NSLocalizedString("printerseries_t83iii", comment:""), value: EPOS2_TM_T83III)
printerList!.addItem(NSLocalizedString("printerseries_t88", comment:""), value: EPOS2_TM_T88)
printerList!.addItem(NSLocalizedString("printerseries_t90", comment:""), value: EPOS2_TM_T90)
printerList!.addItem(NSLocalizedString("printerseries_t90kp", comment:""), value: EPOS2_TM_T90KP)
printerList!.addItem(NSLocalizedString("printerseries_t100", comment:""), value: EPOS2_TM_T100)
printerList!.addItem(NSLocalizedString("printerseries_u220", comment:""), value: EPOS2_TM_U220)
printerList!.addItem(NSLocalizedString("printerseries_u330", comment:""), value: EPOS2_TM_U330)
printerList!.addItem(NSLocalizedString("printerseries_l90", comment:""), value: EPOS2_TM_L90)
printerList!.addItem(NSLocalizedString("printerseries_h6000", comment:""), value: EPOS2_TM_H6000)
printerList!.addItem(NSLocalizedString("printerseries_m30ii", comment:""), value: EPOS2_TM_M30II)
printerList!.addItem(NSLocalizedString("printerseries_ts100", comment:""), value: EPOS2_TS_100)
printerList!.addItem(NSLocalizedString("printerseries_m50", comment:""), value: EPOS2_TM_M50)
printerList!.addItem(NSLocalizedString("printerseries_t88vii", comment:""), value: EPOS2_TM_T88VII)
printerList!.addItem(NSLocalizedString("printerseries_l90lfc", comment:""), value: EPOS2_TM_L90LFC)
printerList!.addItem(NSLocalizedString("printerseries_l100", comment:""), value: EPOS2_TM_L100)
printerList!.addItem(NSLocalizedString("printerseries_p20ii", comment:""), value: EPOS2_TM_P20II)
printerList!.addItem(NSLocalizedString("printerseries_p80ii", comment:""), value: EPOS2_TM_P80II)
printerList!.addItem(NSLocalizedString("printerseries_m30iii", comment:""), value: EPOS2_TM_M30III)
printerList!.addItem(NSLocalizedString("printerseries_m50ii", comment:""), value: EPOS2_TM_M50II)
printerList!.addItem(NSLocalizedString("printerseries_m55", comment:""), value: EPOS2_TM_M55)
langList = CustomPickerDataSource()
langList!.addItem(NSLocalizedString("language_ank", comment:""), value: EPOS2_MODEL_ANK)
langList!.addItem(NSLocalizedString("language_japanese", comment:""), value: EPOS2_MODEL_JAPANESE)
langList!.addItem(NSLocalizedString("language_chinese", comment:""), value: EPOS2_MODEL_CHINESE)
langList!.addItem(NSLocalizedString("language_taiwan", comment:""), value: EPOS2_MODEL_TAIWAN)
langList!.addItem(NSLocalizedString("language_korean", comment:""), value: EPOS2_MODEL_KOREAN)
langList!.addItem(NSLocalizedString("language_thai", comment:""), value: EPOS2_MODEL_THAI)
langList!.addItem(NSLocalizedString("language_southasia", comment:""), value: EPOS2_MODEL_SOUTHASIA)
printerPicker = CustomPickerView()
langPicker = CustomPickerView()
let window = UIApplication.shared.keyWindow
if (window != nil) {
window!.addSubview(printerPicker!)
window!.addSubview(langPicker!)
}
else{
self.view.addSubview(printerPicker!)
self.view.addSubview(langPicker!)
}
printerPicker!.delegate = self
langPicker!.delegate = self
printerPicker!.dataSource = printerList
langPicker!.dataSource = langList
valuePrinterSeries = printerList!.valueItem(0) as! Epos2PrinterSeries
buttonPrinterSeries.setTitle(printerList!.textItem(0), for:UIControl.State())
valuePrinterModel = langList!.valueItem(0) as! Epos2ModelLang
buttonLang.setTitle(langList!.textItem(0), for:UIControl.State())
setDoneToolbar()
let result = Epos2Log.setLogSettings(EPOS2_PERIOD_TEMPORARY.rawValue, output: EPOS2_OUTPUT_STORAGE.rawValue, ipAddress:nil, port:0, logSize:1, logLevel:EPOS2_LOGLEVEL_LOW.rawValue)
if result != EPOS2_SUCCESS.rawValue {
MessageView.showErrorEpos(result, method: "setLogSettings")
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
initializePrinterObject()
target = textTarget.text
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
finalizePrinterObject()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setDoneToolbar() {
let doneToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44))
doneToolbar.barStyle = UIBarStyle.blackTranslucent
doneToolbar.sizeToFit()
let space = UIBarButtonItem(barButtonSystemItem:UIBarButtonItem.SystemItem.flexibleSpace, target:self, action:nil)
let doneButton = UIBarButtonItem(barButtonSystemItem:UIBarButtonItem.SystemItem.done, target:self, action:#selector(ViewController.doneKeyboard(_:)))
doneToolbar.setItems([space, doneButton], animated:true)
textTarget.inputAccessoryView = doneToolbar
}
@objc func doneKeyboard(_ sender: AnyObject) {
textTarget.resignFirstResponder()
target = textTarget.text
}
@IBAction func didTouchUpInside(_ sender: AnyObject) {
textTarget.resignFirstResponder()
switch sender.tag {
case 1:
printerPicker!.showPicker()
case 2:
langPicker!.showPicker()
case 3:
showIndicator(NSLocalizedString("wait", comment:""));
textWarnings.text = ""
let queue = OperationQueue()
queue.addOperation({ [self] in
if !runPrinterReceiptSequence() {
hideIndicator();
}
})
break
case 4:
showIndicator(NSLocalizedString("wait", comment:""));
textWarnings.text = ""
let queue = OperationQueue()
queue.addOperation({ [self] in
if !runPrinterCouponSequence() {
hideIndicator();
}
})
break
default:
break
}
}
func customPickerView(_ pickerView: CustomPickerView, didSelectItem text: String, itemValue value: Any) {
if pickerView == printerPicker {
self.buttonPrinterSeries.setTitle(text, for:UIControl.State())
self.valuePrinterSeries = value as! Epos2PrinterSeries
}
if pickerView == langPicker {
self.buttonLang.setTitle(text, for:UIControl.State())
self.valuePrinterModel = value as! Epos2ModelLang
}
finalizePrinterObject()
initializePrinterObject()
}
func runPrinterReceiptSequence() -> Bool {
if !createReceiptData() {
return false
}
if !printData() {
return false
}
return true
}
func runPrinterCouponSequence() -> Bool {
if !createCouponData() {
return false
}
if !printData() {
return false
}
return true
}
func createReceiptData() -> Bool {
let barcodeWidth = 2
let barcodeHeight = 100
var result = EPOS2_SUCCESS.rawValue
let textData: NSMutableString = NSMutableString()
let logoData = UIImage(named: "store.png")
if logoData == nil {
return false
}
result = printer!.addTextAlign(EPOS2_ALIGN_CENTER.rawValue)
if result != EPOS2_SUCCESS.rawValue {
MessageView.showErrorEpos(result, method:"addTextAlign")
return false;
}
result = printer!.add(logoData, x: 0, y:0,
width:Int(logoData!.size.width),
height:Int(logoData!.size.height),
color:EPOS2_COLOR_1.rawValue,
mode:EPOS2_MODE_MONO.rawValue,
halftone:EPOS2_HALFTONE_DITHER.rawValue,
brightness:Double(EPOS2_PARAM_DEFAULT),
compress:EPOS2_COMPRESS_AUTO.rawValue)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addImage")
return false
}
// Section 1 : Store information
result = printer!.addFeedLine(1)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addFeedLine")
return false
}
textData.append("THE STORE 123 (555) 555 – 5555\n")
textData.append("STORE DIRECTOR – John Smith\n")
textData.append("\n")
textData.append("7/01/07 16:58 6153 05 0191 134\n")
textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n")
textData.append("------------------------------\n")
result = printer!.addText(textData as String)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addText")
return false;
}
textData.setString("")
// Section 2 : Purchaced items
textData.append("400 OHEIDA 3PK SPRINGF 9.99 R\n")
textData.append("410 3 CUP BLK TEAPOT 9.99 R\n")
textData.append("445 EMERIL GRIDDLE/PAN 17.99 R\n")
textData.append("438 CANDYMAKER ASSORT 4.99 R\n")
textData.append("474 TRIPOD 8.99 R\n")
textData.append("433 BLK LOGO PRNTED ZO 7.99 R\n")
textData.append("458 AQUA MICROTERRY SC 6.99 R\n")
textData.append("493 30L BLK FF DRESS 16.99 R\n")
textData.append("407 LEVITATING DESKTOP 7.99 R\n")
textData.append("441 **Blue Overprint P 2.99 R\n")
textData.append("476 REPOSE 4PCPM CHOC 5.49 R\n")
textData.append("461 WESTGATE BLACK 25 59.99 R\n")
textData.append("------------------------------\n")
result = printer!.addText(textData as String)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addText")
return false;
}
textData.setString("")
// Section 3 : Payment infomation
textData.append("SUBTOTAL 160.38\n");
textData.append("TAX 14.43\n");
result = printer!.addText(textData as String)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addText")
return false
}
textData.setString("")
result = printer!.addTextSize(2, height:2)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addTextSize")
return false
}
result = printer!.addText("TOTAL 174.81\n")
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addText")
return false;
}
result = printer!.addTextSize(1, height:1)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addTextSize")
return false;
}
result = printer!.addFeedLine(1)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addFeedLine")
return false;
}
textData.append("CASH 200.00\n")
textData.append("CHANGE 25.19\n")
textData.append("------------------------------\n")
result = printer!.addText(textData as String)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addText")
return false
}
textData.setString("")
// Section 4 : Advertisement
textData.append("Purchased item total number\n")
textData.append("Sign Up and Save !\n")
textData.append("With Preferred Saving Card\n")
result = printer!.addText(textData as String)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addText")
return false;
}
textData.setString("")
result = printer!.addFeedLine(2)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addFeedLine")
return false
}
result = printer!.addBarcode("01209457",
type:EPOS2_BARCODE_CODE39.rawValue,
hri:EPOS2_HRI_BELOW.rawValue,
font:EPOS2_FONT_A.rawValue,
width:barcodeWidth,
height:barcodeHeight)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addBarcode")
return false
}
result = printer!.addCut(EPOS2_CUT_FEED.rawValue)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addCut")
return false
}
return true
}
func createCouponData() -> Bool {
let barcodeWidth = 2
let barcodeHeight = 64
var result = EPOS2_SUCCESS.rawValue
if printer == nil {
return false
}
let coffeeData = UIImage(named: "coffee.png")
let wmarkData = UIImage(named: "wmark.png")
if coffeeData == nil || wmarkData == nil {
return false
}
result = printer!.add(wmarkData, x:0, y:0,
width:Int(wmarkData!.size.width),
height:Int(wmarkData!.size.height),
color:EPOS2_PARAM_DEFAULT,
mode:EPOS2_PARAM_DEFAULT,
halftone:EPOS2_PARAM_DEFAULT,
brightness:Double(EPOS2_PARAM_DEFAULT),
compress:EPOS2_PARAM_DEFAULT)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addImage")
return false
}
result = printer!.add(coffeeData, x:0, y:0,
width:Int(coffeeData!.size.width),
height:Int(coffeeData!.size.height),
color:EPOS2_PARAM_DEFAULT,
mode:EPOS2_PARAM_DEFAULT,
halftone:EPOS2_PARAM_DEFAULT,
brightness:3,
compress:EPOS2_PARAM_DEFAULT)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addImage")
return false
}
result = printer!.addBarcode("01234567890", type:EPOS2_BARCODE_UPC_A.rawValue, hri:EPOS2_PARAM_DEFAULT, font: EPOS2_PARAM_DEFAULT, width:barcodeWidth, height:barcodeHeight)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addBarcode")
return false
}
result = printer!.addCut(EPOS2_CUT_FEED.rawValue)
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"addCut")
return false
}
return true
}
func printData() -> Bool {
if printer == nil {
return false
}
if !connectPrinter() {
printer!.clearCommandBuffer()
return false
}
let result = printer!.sendData(Int(EPOS2_PARAM_DEFAULT))
if result != EPOS2_SUCCESS.rawValue {
printer!.clearCommandBuffer()
MessageView.showErrorEpos(result, method:"sendData")
printer!.disconnect()
return false
}
return true
}
@discardableResult
func initializePrinterObject() -> Bool {
printer = Epos2Printer(printerSeries: valuePrinterSeries.rawValue, lang: valuePrinterModel.rawValue)
if printer == nil {
return false
}
printer!.setReceiveEventDelegate(self)
return true
}
func finalizePrinterObject() {
if printer == nil {
return
}
printer!.setReceiveEventDelegate(nil)
printer = nil
}
func connectPrinter() -> Bool {
var result: Int32 = EPOS2_SUCCESS.rawValue
if printer == nil {
return false
}
//Note: This API must be used from background thread only
result = printer!.connect(target, timeout:Int(EPOS2_PARAM_DEFAULT))
if result != EPOS2_SUCCESS.rawValue {
MessageView.showErrorEpos(result, method:"connect")
return false
}
return true
}
func disconnectPrinter() {
var result: Int32 = EPOS2_SUCCESS.rawValue
if printer == nil {
return
}
//Note: This API must be used from background thread only
result = printer!.disconnect()
if result != EPOS2_SUCCESS.rawValue {
DispatchQueue.main.async(execute: {
MessageView.showErrorEpos(result, method:"disconnect")
})
}
printer!.clearCommandBuffer()
}
func onPtrReceive(_ printerObj: Epos2Printer!, code: Int32, status: Epos2PrinterStatusInfo!, printJobId: String!) {
let queue = OperationQueue()
queue.addOperation({ [self] in
self.disconnectPrinter()
self.hideIndicator();
MessageView.showResult(code, errMessage: makeErrorMessage(status))
dispPrinterWarnings(status)
})
}
func dispPrinterWarnings(_ status: Epos2PrinterStatusInfo?) {
if status == nil {
return
}
OperationQueue.main.addOperation({ [self] in
textWarnings.text = ""
})
let wanringMsg = NSMutableString()
if status!.paper == EPOS2_PAPER_NEAR_END.rawValue {
wanringMsg.append(NSLocalizedString("warn_receipt_near_end", comment:""))
}
if status!.batteryLevel == EPOS2_BATTERY_LEVEL_1.rawValue {
wanringMsg.append(NSLocalizedString("warn_battery_near_end", comment:""))
}
if status!.paperTakenSensor == EPOS2_REMOVAL_DETECT_PAPER.rawValue {
wanringMsg.append(NSLocalizedString("warn_detect_paper", comment:""))
}
if status!.paperTakenSensor == EPOS2_REMOVAL_DETECT_UNKNOWN.rawValue {
wanringMsg.append(NSLocalizedString("warn_detect_unknown", comment:""))
}
OperationQueue.main.addOperation({ [self] in
textWarnings.text = wanringMsg as String
})
}
func makeErrorMessage(_ status: Epos2PrinterStatusInfo?) -> String {
let errMsg = NSMutableString()
if status == nil {
return ""
}
if status!.online == EPOS2_FALSE {
errMsg.append(NSLocalizedString("err_offline", comment:""))
}
if status!.connection == EPOS2_FALSE {
errMsg.append(NSLocalizedString("err_no_response", comment:""))
}
if status!.coverOpen == EPOS2_TRUE {
errMsg.append(NSLocalizedString("err_cover_open", comment:""))
}
if status!.paper == EPOS2_PAPER_EMPTY.rawValue {
errMsg.append(NSLocalizedString("err_receipt_end", comment:""))
}
if status!.paperFeed == EPOS2_TRUE || status!.panelSwitch == EPOS2_SWITCH_ON.rawValue {
errMsg.append(NSLocalizedString("err_paper_feed", comment:""))
}
if status!.errorStatus == EPOS2_MECHANICAL_ERR.rawValue || status!.errorStatus == EPOS2_AUTOCUTTER_ERR.rawValue {
errMsg.append(NSLocalizedString("err_autocutter", comment:""))
errMsg.append(NSLocalizedString("err_need_recover", comment:""))
}
if status!.errorStatus == EPOS2_UNRECOVER_ERR.rawValue {
errMsg.append(NSLocalizedString("err_unrecover", comment:""))
}
if status!.errorStatus == EPOS2_AUTORECOVER_ERR.rawValue {
if status!.autoRecoverError == EPOS2_HEAD_OVERHEAT.rawValue {
errMsg.append(NSLocalizedString("err_overheat", comment:""))
errMsg.append(NSLocalizedString("err_head", comment:""))
}
if status!.autoRecoverError == EPOS2_MOTOR_OVERHEAT.rawValue {
errMsg.append(NSLocalizedString("err_overheat", comment:""))
errMsg.append(NSLocalizedString("err_motor", comment:""))
}
if status!.autoRecoverError == EPOS2_BATTERY_OVERHEAT.rawValue {
errMsg.append(NSLocalizedString("err_overheat", comment:""))
errMsg.append(NSLocalizedString("err_battery", comment:""))
}
if status!.autoRecoverError == EPOS2_WRONG_PAPER.rawValue {
errMsg.append(NSLocalizedString("err_wrong_paper", comment:""))
}
}
if status!.batteryLevel == EPOS2_BATTERY_LEVEL_0.rawValue {
errMsg.append(NSLocalizedString("err_battery_real_end", comment:""))
}
if (status!.removalWaiting == EPOS2_REMOVAL_WAIT_PAPER.rawValue) {
errMsg.append(NSLocalizedString("err_wait_removal", comment:""))
}
if (status!.unrecoverError == EPOS2_HIGH_VOLTAGE_ERR.rawValue ||
status!.unrecoverError == EPOS2_LOW_VOLTAGE_ERR.rawValue) {
errMsg.append(NSLocalizedString("err_voltage", comment:""));
}
return errMsg as String
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DiscoveryView" {
let view: DiscoveryViewController? = segue.destination as? DiscoveryViewController
view?.delegate = self
}
}
func discoveryView(_ sendor: DiscoveryViewController, onSelectPrinterTarget target: String) {
textTarget.text = target
}
}
|
d7ce6a057f3da1899eee7f0462f1f818
|
{
"intermediate": 0.3128857910633087,
"beginner": 0.5717096328735352,
"expert": 0.11540459096431732
}
|
43,785
|
Need help in Understanding GlideAjax , when to use getXML and when to use getXMLAnswer.
What I know is
when we use getXML we need to add the line, "var answer = response.responseXML.documentElement.getAttribute("answer")".
When we use getXMLAnswer we save our time by skipping the "var answer = response.responseXML.documentElement.getAttribute("answer")"
I wanted to know what is the best scenario where I can. Decide what to use based on the situation servicenow
|
205d86b82a53f124e8a6e48729e6a4fa
|
{
"intermediate": 0.6545602679252625,
"beginner": 0.23796935379505157,
"expert": 0.10747038573026657
}
|
43,786
|
In reaper daw does reaimgui use much cpu power?
|
566a397e6d6cf0db78b644afe0f18b69
|
{
"intermediate": 0.3229961693286896,
"beginner": 0.29020291566848755,
"expert": 0.38680094480514526
}
|
43,787
|
Table a
cust_num acct_num open_date
123abcd789 546787123 1/5/2023
785bdef234 578541216 2/20/2023
546weyt548 213054623 3/21/2023
987wyte412 702598124 3/21/2023
762wwer880 675478953 3/27/2023
Table b
cust_num status snapshot_date
123abcd789 student 1/3/2023
123abcd789 PR 1/4/2023
123abcd789 student 1/5/2023
123abcd789 worker 1/6/2023
785bdef234 student 2/18/2023
785bdef234 student 2/19/2023
785bdef234 worker 2/20/2023
785bdef234 worker 2/21/2023
785bdef234 PR 2/22/2023
546weyt548 student 3/17/2023
546weyt548 student 3/18/2023
546weyt548 student 3/19/2023
546weyt548 student 3/20/2023
546weyt548 worker 3/21/2023
546weyt548 worker 3/22/2023
546weyt548 PR 3/23/2023
546weyt548 PR 3/24/2023
546weyt548 PR 3/25/2023
762wwer880 student 3/21/2023
762wwer880 student 3/22/2023
762wwer880 student 3/23/2023
762wwer880 student 3/24/2023
762wwer880 student 3/25/2023
762wwer880 PR 3/26/2023
762wwer880 PR 3/27/2023
762wwer880 worker 3/28/2023
762wwer880 worker 3/29/2023
762wwer880 worker 3/30/2023
WITH Sales_Performance AS (
SELECT DISTINCT
CAST(a.acct_num AS BIGINT) AS acct_num,
CAST(a.prim_own_cif_id AS BIGINT) AS cust_cid,
SUBSTR(TRIM(a.opn_dt), 1, 7) AS year_month,
a.opn_dt AS open_date,
a.type AS products,
CASE
WHEN d.immigration_cat_cd IN ('000','999','C1','FC1','FC2','FC3','EN2','PV1','PV2','SW1','SW2','SW3','SE2','STP','C2','NV5') THEN 'PR'
WHEN d.immigration_cat_cd IN ('FW','FW0') THEN 'FW'
WHEN d.immigration_cat_cd IN ('S','S00') THEN 'IS'
ELSE 'Regular_Customers'
END AS MCB_Category
FROM table_a a
LEFT JOIN (
SELECT
DISTINCT CAST(party_id AS BIGINT) AS party_id,
immigration_cat_cd,
start_date,
date_sub(coalesce(LEAD(start_date) OVER (PARTITION BY party_id ORDER BY start_date ), current_date),1) AS end_date
FROM
(SELECT
party_id,
immigration_cat_cd,
businesseffectivedate AS start_date,
RANK() OVER (PARTITION BY party_id, immigration_cat_cd ORDER BY businesseffectivedate) AS rank
FROM
table_b
) d
WHERE
rank = 1
) d ON lpad(a.prim_own_cif_id,15,'0') = lpad(d.party_id,15,'0')
WHERE
trim(a.channel) NOT IN ('Branch','CCC')
AND trim(a.type) NOT IN ('US$','GTSP')
AND a.opn_dt > '2022-12-31'
AND a.opn_dt < '2023-04-01'
AND (d.party_id IS NULL OR (a.opn_dt BETWEEN d.start_date AND d.end_date) OR d.start_date IS NULL)
)
SELECT * FROM Sales_Performance;
Now use my above query and above tables and get me the output
|
adf79d8c89e041545dec50751c8fde71
|
{
"intermediate": 0.2665238380432129,
"beginner": 0.44521990418434143,
"expert": 0.2882562577724457
}
|
43,788
|
In reaper lua reaimgui how to just redraw gui items if im interacting with them
|
305b00b4e86ee4e1f1f98f27f1a36231
|
{
"intermediate": 0.4636266827583313,
"beginner": 0.23677970468997955,
"expert": 0.29959362745285034
}
|
43,789
|
Table_a
cust_num acct_num open_date
123abcd789 546787123 1/5/2023
785bdef234 578541216 2/20/2023
546weyt548 213054623 3/21/2023
987wyte412 702598124 3/21/2023
762wwer880 675478953 3/27/2023
Table_b
cust_num status snapshot_date
123abcd789 student 1/3/2023
123abcd789 PR 1/4/2023
123abcd789 student 1/5/2023
123abcd789 worker 1/6/2023
785bdef234 student 2/18/2023
785bdef234 student 2/19/2023
785bdef234 worker 2/20/2023
785bdef234 worker 2/21/2023
785bdef234 PR 2/22/2023
546weyt548 student 3/17/2023
546weyt548 student 3/18/2023
546weyt548 student 3/19/2023
546weyt548 student 3/20/2023
546weyt548 worker 3/21/2023
546weyt548 worker 3/22/2023
546weyt548 PR 3/23/2023
546weyt548 PR 3/24/2023
546weyt548 PR 3/25/2023
762wwer880 student 3/21/2023
762wwer880 student 3/22/2023
762wwer880 student 3/23/2023
762wwer880 student 3/24/2023
762wwer880 student 3/25/2023
762wwer880 PR 3/26/2023
762wwer880 PR 3/27/2023
762wwer880 worker 3/28/2023
762wwer880 worker 3/29/2023
762wwer880 worker 3/30/2023
WITH Sales_Performance AS (
SELECT DISTINCT
CAST(a.acct_num AS BIGINT) AS acct_num,
CAST(a.prim_own_cif_id AS BIGINT) AS cust_cid,
SUBSTR(TRIM(a.opn_dt), 1, 7) AS year_month,
a.opn_dt AS open_date,
a.type AS products,
CASE
WHEN d.immigration_cat_cd IN (‘000’,‘999’,‘C1’,‘FC1’,‘FC2’,‘FC3’,‘EN2’,‘PV1’,‘PV2’,‘SW1’,‘SW2’,‘SW3’,‘SE2’,‘STP’,‘C2’,‘NV5’) THEN ‘PR’
WHEN d.immigration_cat_cd IN (‘FW’,‘FW0’) THEN ‘FW’
WHEN d.immigration_cat_cd IN (‘S’,‘S00’) THEN ‘IS’
ELSE ‘Regular_Customers’
END AS MCB_Category
FROM table_a a
LEFT JOIN (
SELECT
DISTINCT CAST(party_id AS BIGINT) AS party_id,
immigration_cat_cd,
start_date,
date_sub(coalesce(LEAD(start_date) OVER (PARTITION BY party_id ORDER BY start_date ), current_date),1) AS end_date
FROM
(SELECT
party_id,
immigration_cat_cd,
businesseffectivedate AS start_date,
RANK() OVER (PARTITION BY party_id, immigration_cat_cd ORDER BY businesseffectivedate) AS rank
FROM
table_b
) d
WHERE
rank = 1
) d ON lpad(a.prim_own_cif_id,15,‘0’) = lpad(d.party_id,15,‘0’)
WHERE
trim(a.channel) NOT IN (‘Branch’,‘CCC’)
AND trim(a.type) NOT IN (‘US$’,‘GTSP’)
AND a.opn_dt > ‘2022-12-31’
AND a.opn_dt < ‘2023-04-01’
AND (d.party_id IS NULL OR (a.opn_dt BETWEEN d.start_date AND d.end_date) OR d.start_date IS NULL)
)
SELECT * FROM Sales_Performance;
Now use my above query and above tables and get me the output
|
5710a19453d6dfc5fc65131acfa08116
|
{
"intermediate": 0.29070645570755005,
"beginner": 0.4903033375740051,
"expert": 0.21899014711380005
}
|
43,790
|
Write a python code for hitting a url
|
c805a42c42bd0e5390d5ea428955d928
|
{
"intermediate": 0.3317791521549225,
"beginner": 0.2801872789859772,
"expert": 0.38803359866142273
}
|
43,791
|
from scapy.layers.inet import IP, UDP
from scapy.all import *
# IP address of the target
target_ip = '192.168.1.209'
# Number of packets to send
num_packets = 1000
# Create a UDP packet
udp_packet = UDP(dport=80) / Raw(load='A' * 1024)
# Send the packets
send(IP(dst=target_ip) / udp_packet, count=num_packets) make any changes necessary in the vode
|
06302524b1b9d0e08286d15f03da3551
|
{
"intermediate": 0.39438098669052124,
"beginner": 0.29618558287620544,
"expert": 0.3094334304332733
}
|
43,792
|
Can you write a more advanced Math Solver in this script with error handling? In [poe](https://creator.poe.com/docs/poe-protocol-specification).
|
533d3b0bed42279f7f1d6972c8f352a9
|
{
"intermediate": 0.38871803879737854,
"beginner": 0.19370318949222565,
"expert": 0.41757869720458984
}
|
43,793
|
Can you add a more advanced math solver in this script with error handling?
|
e5ad3ff5d200a5ddc34480ada21921d2
|
{
"intermediate": 0.44315001368522644,
"beginner": 0.18376365303993225,
"expert": 0.3730863332748413
}
|
43,794
|
docker: Error response from daemon: AppArmor enabled on system but the docker-default profile could not be loaded: running `/usr/sbin/apparmor_parser apparmor_parser -Kr /var/lib/docker/tmp/docker-default1728561759` failed with output: apparmor_parser: Unable to replace "docker-default". Permission denied; attempted to load a profile while confined?
|
1d4dc4aa118bcf8ff6dd06fe2972f687
|
{
"intermediate": 0.5101333260536194,
"beginner": 0.2576049268245697,
"expert": 0.23226182162761688
}
|
43,795
|
Write an advanced math solver poe bot script.
https://creator.poe.com/docs/poe-protocol-specification
https://creator.poe.com/docs/accessing-other-bots-on-poe
https://creator.poe.com/docs/quick-start
https://creator.poe.com/docs/setting-an-introduction-message
https://creator.poe.com/docs/accessing-http-request-information
https://creator.poe.com/docs/using-openai-function-calling
|
26fa87aa1fad7f4dc33c7c8b924d0de3
|
{
"intermediate": 0.2502831518650055,
"beginner": 0.5574933886528015,
"expert": 0.19222348928451538
}
|
43,796
|
-- Rykord Vertical Track FX List --
--NOTES--
-- want to make buttons resizable
-- start window on a specific position (maybe preset position, maybe last position)
--NONCODE SKELETON
--SKELETON--
-- windowposition ✅
-- window size
-- if CountSelectedTracks == 1
-- for fx (0,i)
-- create blue button with the name of the fx ✅
-- if left click the button opens the fx window ✅
-- if right click the button deletes the fx ✅
-- if left drag the button is draggable and drags the fx ✅
-- if alt left click the fx is bypassed
-- gray button to add fx with spacing from other buttons and other color
-- if pressed ✅
-- inserts fx at i + 1 ✅
-- if CountSelectedTracks > 1
-- black buttton saying "MULTIPLE TRACKS ARE SELECTED", button is unclickable
-- if CountSelectedTracks == 0
-- black button saying "SELECT A TRACK", button is unclickable
-- let keyboard shortcuts through
--FUNCTIONS--
local profiler = dofile(reaper.GetResourcePath() ..
'/Scripts/ReaTeam Scripts/Development/cfillion_Lua profiler.lua')
reaper.defer = profiler.defer
function print(...)
reaper.ShowConsoleMsg(table.concat({...}, "\t") .. "\n")
end
function IsAltKeyDown()
local keyState = reaper.JS_Mouse_GetState(0)
local altIsPressed = keyState & 8
return altIsPressed ~= 0
end
function main()
local _, open = reaper.ImGui_Begin(ctx, "FX LIST", true)
reaper.ImGui_PushFont(ctx, font_1)
reaper.ImGui_SetNextWindowPos(ctx, x_position, y_position)
if dock_position then
reaper.ImGui_SetNextWindowDockID(ctx, -8) --CURRENT DOCK POSITION IS UNDER (DOCKID == -7)!
end
window_width, window_height = reaper.ImGui_GetWindowSize(ctx)
button_width = window_width * 0.4 --SHOULD THESE BE GLOBAL?
button_height = window_height * 0.12 --SHOULD THESE BE GLOBAL?
reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_FrameRounding(), 8)
fx_list()
reaper.ImGui_PopStyleVar(ctx, 1)
reaper.ImGui_PopFont(ctx)
if open then
reaper.ImGui_End(ctx)
reaper.defer(main)
else
local last_x_position, last_y_position = reaper.ImGui_GetWindowPos(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "x_pos", last_x_position, true)
reaper.SetExtState("RYKORD_TRACK_FX", "y_pos", last_y_position, true)
local last_dock_position = reaper.ImGui_GetWindowDockID(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "dock_position", last_dock_position, true)
reaper.ImGui_End(ctx)
end
end
function swap_fx(track, new_index, source_index)
reaper.TrackFX_CopyToTrack(track, source_index, track, new_index, true)
if source_index > new_index then
reaper.TrackFX_CopyToTrack(track, new_index + 1, track, source_index, true)
elseif source_index < new_index then
reaper.TrackFX_CopyToTrack(track, new_index + -1, track, source_index, true)
end
end
function fx_list()
if reaper.CountSelectedTracks(0) == 1 then
local selected_track = reaper.GetSelectedTrack(0, 0)
local num_of_fx = reaper.TrackFX_GetCount(selected_track)
--FX BUTTONS--
for i = 0, num_of_fx - 1 do
local _, fx_name = reaper.TrackFX_GetFXName(selected_track, i) --VERIFICAR SE FX TAMBÉM TÊM 0 INDEX
if reaper.TrackFX_GetEnabled(selected_track, i) then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xF5CB5CFF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
else
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xCFDBD5FF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
end
local fx_button_left_click = reaper.ImGui_Button(ctx, fx_name .. '##' .. i, button_width, button_height)
local fx_button_right_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Right())
local fx_button_middle_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Middle())
if reaper.ImGui_BeginDragDropSource(ctx) then
reaper.ImGui_SetDragDropPayload(ctx, "DND_FX", i) -- "DND_FX" is a type identifier for the payload
reaper.ImGui_Button(ctx, fx_name .. '##' .. i, button_width, button_height) -- This will be the preview of the drag and drop
reaper.ImGui_EndDragDropSource(ctx)
end
if reaper.ImGui_BeginDragDropTarget(ctx) then
if reaper.ImGui_AcceptDragDropPayload(ctx, "DND_FX") then
local _, _, payload, _, _= reaper.ImGui_GetDragDropPayload(ctx)
local old_index = tonumber(payload)
-- Swap the effects here using your own function
swap_fx(selected_track, i, old_index)
end
reaper.ImGui_EndDragDropTarget(ctx)
end
reaper.ImGui_PopStyleColor(ctx, 2)
if fx_button_left_click then
reaper.TrackFX_SetOpen(selected_track, i, true)
elseif fx_button_middle_click then
if reaper.TrackFX_GetEnabled(selected_track, i) == true then
reaper.TrackFX_SetEnabled(selected_track, i, false)
else
reaper.TrackFX_SetEnabled(selected_track, i, true)
end
elseif fx_button_right_click then
reaper.TrackFX_Delete(selected_track, i)
end
end
--ADD FX BUTTON--
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xB3B6B7A1)
local add_fx_press = reaper.ImGui_Button(ctx, "ADD FX", button_width, button_height)
if add_fx_press then
reaper.Main_OnCommand(40271, 0)
end
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) > 1 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, "MULTIPLE TRACKS SELECTED \n SELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) == 0 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, " NO TRACK SELECTED \nSELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
end
if reaper.JS_Window_GetFocus() ~= main_window then
if reaper.ImGui_IsWindowFocused(ctx) and not reaper.ImGui_IsItemActive(ctx) and not reaper.ImGui_IsAnyMouseDown(ctx) then
reaper.JS_Window_SetFocus(main_window)
end
end
end
--RUN--
profiler.attachToWorld()
x_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "x_pos"))
y_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "y_pos"))
dock_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "dock_position"))
window_width = nil
window_height = nil
main_window = reaper.GetMainHwnd()
font_1 = reaper.ImGui_CreateFont("C:\\Users\\franc\\Desktop\\Portable reapers\\REAPER (x64)\\Scripts\\Rykord Scripts\\SFPRODISPLAYREGULAR.OTF", 20)
ctx = reaper.ImGui_CreateContext("ctx")
reaper.ImGui_Attach(ctx, font_1)
main()
profiler.run()
how can i reduce cpu performance here
|
51a22b66c1e965850101ca0d863ee05c
|
{
"intermediate": 0.2790205776691437,
"beginner": 0.46988120675086975,
"expert": 0.2510981857776642
}
|
43,797
|
-- Rykord Vertical Track FX List --
--NOTES--
-- want to make buttons resizable
-- start window on a specific position (maybe preset position, maybe last position)
--NONCODE SKELETON
--SKELETON--
-- windowposition ✅
-- window size
-- if CountSelectedTracks == 1
-- for fx (0,i)
-- create blue button with the name of the fx ✅
-- if left click the button opens the fx window ✅
-- if right click the button deletes the fx ✅
-- if left drag the button is draggable and drags the fx ✅
-- if alt left click the fx is bypassed
-- gray button to add fx with spacing from other buttons and other color
-- if pressed ✅
-- inserts fx at i + 1 ✅
-- if CountSelectedTracks > 1
-- black buttton saying "MULTIPLE TRACKS ARE SELECTED", button is unclickable
-- if CountSelectedTracks == 0
-- black button saying "SELECT A TRACK", button is unclickable
-- let keyboard shortcuts through
--FUNCTIONS--
local profiler = dofile(reaper.GetResourcePath() ..
'/Scripts/ReaTeam Scripts/Development/cfillion_Lua profiler.lua')
reaper.defer = profiler.defer
function print(...)
reaper.ShowConsoleMsg(table.concat({...}, "\t") .. "\n")
end
function hasStateChanged()
local selected_track = reaper.GetSelectedTrack(0, 0)
local fx_count = (selected_track and reaper.TrackFX_GetCount(selected_track)) or 0
if selected_track ~= prev_selected_track or fx_count ~= prev_fx_count then
prev_selected_track = selected_track
prev_fx_count = fx_count
return true
end
return false
end
function IsAltKeyDown()
local keyState = reaper.JS_Mouse_GetState(0)
local altIsPressed = keyState & 8
return altIsPressed ~= 0
end
function main()
if hasStateChanged() then
local _, open = reaper.ImGui_Begin(ctx, "FX LIST", true)
reaper.ImGui_PushFont(ctx, font_1)
reaper.ImGui_SetNextWindowPos(ctx, x_position, y_position)
if dock_position then
reaper.ImGui_SetNextWindowDockID(ctx, -8) --CURRENT DOCK POSITION IS UNDER (DOCKID == -7)!
end
window_width, window_height = reaper.ImGui_GetWindowSize(ctx)
button_width = window_width * 0.4 --SHOULD THESE BE GLOBAL?
button_height = window_height * 0.12 --SHOULD THESE BE GLOBAL?
reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_FrameRounding(), 8)
fx_list()
reaper.ImGui_PopStyleVar(ctx, 1)
reaper.ImGui_PopFont(ctx)
if open then
reaper.ImGui_End(ctx)
reaper.defer(main)
else
local last_x_position, last_y_position = reaper.ImGui_GetWindowPos(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "x_pos", last_x_position, true)
reaper.SetExtState("RYKORD_TRACK_FX", "y_pos", last_y_position, true)
local last_dock_position = reaper.ImGui_GetWindowDockID(ctx)
reaper.SetExtState("RYKORD_TRACK_FX", "dock_position", last_dock_position, true)
reaper.ImGui_End(ctx)
end
end
end
function swap_fx(track, new_index, source_index)
reaper.TrackFX_CopyToTrack(track, source_index, track, new_index, true)
if source_index > new_index then
reaper.TrackFX_CopyToTrack(track, new_index + 1, track, source_index, true)
elseif source_index < new_index then
reaper.TrackFX_CopyToTrack(track, new_index + -1, track, source_index, true)
end
end
function fx_list()
if reaper.CountSelectedTracks(0) == 1 then
local selected_track = reaper.GetSelectedTrack(0, 0)
local num_of_fx = reaper.TrackFX_GetCount(selected_track)
--FX BUTTONS--
for i = 0, num_of_fx - 1 do
local _, fx_name = reaper.TrackFX_GetFXName(selected_track, i) --VERIFICAR SE FX TAMBÉM TÊM 0 INDEX
if reaper.TrackFX_GetEnabled(selected_track, i) then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xF5CB5CFF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
else
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xCFDBD5FF)
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Text(), 0x000000FF)
end
local fx_button_left_click = reaper.ImGui_Button(ctx, fx_name .. '##' .. i, button_width, button_height)
local fx_button_right_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Right())
local fx_button_middle_click = reaper.ImGui_IsItemClicked(ctx, reaper.ImGui_MouseButton_Middle())
if reaper.ImGui_BeginDragDropSource(ctx) then
reaper.ImGui_SetDragDropPayload(ctx, "DND_FX", i) -- "DND_FX" is a type identifier for the payload
reaper.ImGui_Button(ctx, fx_name .. '##' .. i, button_width, button_height) -- This will be the preview of the drag and drop
reaper.ImGui_EndDragDropSource(ctx)
end
if reaper.ImGui_BeginDragDropTarget(ctx) then
if reaper.ImGui_AcceptDragDropPayload(ctx, "DND_FX") then
local _, _, payload, _, _= reaper.ImGui_GetDragDropPayload(ctx)
local old_index = tonumber(payload)
-- Swap the effects here using your own function
swap_fx(selected_track, i, old_index)
end
reaper.ImGui_EndDragDropTarget(ctx)
end
reaper.ImGui_PopStyleColor(ctx, 2)
if fx_button_left_click then
reaper.TrackFX_SetOpen(selected_track, i, true)
elseif fx_button_middle_click then
if reaper.TrackFX_GetEnabled(selected_track, i) == true then
reaper.TrackFX_SetEnabled(selected_track, i, false)
else
reaper.TrackFX_SetEnabled(selected_track, i, true)
end
elseif fx_button_right_click then
reaper.TrackFX_Delete(selected_track, i)
end
end
--ADD FX BUTTON--
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0xB3B6B7A1)
local add_fx_press = reaper.ImGui_Button(ctx, "ADD FX", button_width, button_height)
if add_fx_press then
reaper.Main_OnCommand(40271, 0)
end
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) > 1 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, "MULTIPLE TRACKS SELECTED \n SELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
elseif reaper.CountSelectedTracks(0) == 0 then
reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_Button(), 0x373F47FF)
reaper.ImGui_Button(ctx, " NO TRACK SELECTED \nSELECT A SINGLE TRACK", 300, 60)
reaper.ImGui_PopStyleColor(ctx)
end
if reaper.JS_Window_GetFocus() ~= main_window then
if reaper.ImGui_IsWindowFocused(ctx) and not reaper.ImGui_IsItemActive(ctx) and not reaper.ImGui_IsAnyMouseDown(ctx) then
reaper.JS_Window_SetFocus(main_window)
end
end
end
--RUN--
profiler.attachToWorld()
x_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "x_pos"))
y_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "y_pos"))
dock_position = tonumber(reaper.GetExtState("RYKORD_TRACK_FX", "dock_position"))
window_width = nil
window_height = nil
prev_selected_track = nil
prev_fx_count = nil
main_window = reaper.GetMainHwnd()
font_1 = reaper.ImGui_CreateFont("C:\\Users\\franc\\Desktop\\Portable reapers\\REAPER (x64)\\Scripts\\Rykord Scripts\\SFPRODISPLAYREGULAR.OTF", 20)
ctx = reaper.ImGui_CreateContext("ctx")
reaper.ImGui_Attach(ctx, font_1)
main()
profiler.run()
i have this reaper lua script using reaimgui. I want the fx_list to be created and drawn the first time of the loop, but if the track is the same, i don't want it to be redrawn, i just want it to be the same as the previous frame to save cpu resources
|
6313708ddd736fd462642626b4c2b166
|
{
"intermediate": 0.2937926650047302,
"beginner": 0.497284471988678,
"expert": 0.2089228630065918
}
|
43,798
|
import tensorflow as tf
train_dataset = dataset['train']
# Считаем количество элементов в наборе данных
dataset_size = tfds.as_numpy(tf.data.experimental.cardinality(train_dataset)) # Преобразуем в numpy для получения значения
print('Total dataset size:', dataset_size)
# Вычисляем количество элементов для тестового набора данных (20%)
test_size = tf.cast(0.2 * dataset_size, tf.int64)
# Перемешиваем тренировочный набор данных
train_dataset_shuffled = train_dataset.shuffle(buffer_size=dataset_size)
# Берем случайные 20% элементов для тестового набора данных
test_dataset = train_dataset_shuffled.take(test_size)
# Оставшиеся элементы после взятия тестового набора данных - это тренировочный набор данных
train_dataset = train_dataset_shuffled.skip(test_size)
# Выводим размеры тренировочного и тестового наборов данных
train_size = tf.data.experimental.cardinality(train_dataset)
test_size = tf.data.experimental.cardinality(test_dataset)
print('Total dataset size:', dataset_size)
print('Train dataset size:', train_size)
print('Test dataset size:', test_size) # Предобработка изображений
def preprocess_image(image):
image = tf.image.resize(image, (32, 32))
image = tf.cast(image, tf.float32) / 255.0
return image
def preprocess_data(example):
image = example['image']
label = example['label']
image = preprocess_image(image)
return image, label
train_dataset = train_dataset.map(preprocess_data).shuffle(256).batch(16)
# Создаем модель сверточной нейронной сети
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# Компилируем модель
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Обучаем модель
model.fit(train_dataset, epochs=10) Как можно создать функцию, которая будет порционно давать модели исходные данные, чтобы расходовать меньше памяти?
|
36885e534dd64627fa79dffe378197be
|
{
"intermediate": 0.2827078402042389,
"beginner": 0.4153706729412079,
"expert": 0.3019214868545532
}
|
43,799
|
Hi
|
8b2ef4f7922a8ea63084f9d2df2f514e
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
43,800
|
No module named 'tensorflow_datasets'
|
c57bcfc5830dfc9a4cdbbc6ede3b5af5
|
{
"intermediate": 0.38034483790397644,
"beginner": 0.18601655960083008,
"expert": 0.43363863229751587
}
|
43,801
|
Traceback (most recent call last):
File "C:\Users\ILEG-i5-11\Downloads\Compressed\MyProj\ShazamIdentify.py", line 5, in <module>
shazam = Shazam(
^^^^^^^
TypeError: Shazam.__init__() got an unexpected keyword argument 'lang'
from ShazamAPI import Shazam
mp3_file_content_to_recognize = open('Unknown_file - Copy.mp3', 'rb').read()
shazam = Shazam(
mp3_file_content_to_recognize,
lang='en',
time_zone='Europe/Paris'
)
recognize_generator = shazam.recognizeSong()
while True:
print(next(recognize_generator)) # current offset & shazam response to recognize requests
|
9d4288ea5d83e10fa3358f17cdec6ff3
|
{
"intermediate": 0.47491103410720825,
"beginner": 0.32424530386924744,
"expert": 0.2008436918258667
}
|
43,802
|
from my_shazam_utility import shazam_recognize_song
import acrcloud
import os
import eyed3
import requests
import json
import re
from applemusic_api import AppleMusicApi
from acrcloud.recognizer import ACRCloudRecognizer
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open('D:/Eurydice/Encompassing Data by discerning/config/config.json', 'r') as config_file:
config_data = json.load(config_file)
return config_data
dir(acrcloud)
config = load_config()
# Accessing the configuration values
ACR_HOST = config['ACR']['HOST']
ACR_ACCESS_KEY = config['ACR']['ACCESS_KEY']
ACR_ACCESS_SECRET = config['ACR']['ACCESS_SECRET']
recognizer = ACRCloudRecognizer(config)
def get_user_choice():
# Display a header
print("=" * 50)
print("Welcome to the Song Recognition Service!")
print("=" * 50)
# Provide instructions and options
print("\nPlease select the recognition service you'd like to use:\n")
print(" 1: Youtube-ACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print("-" * 50)
# Input prompt
choice = input("Enter your choice (1 or 2) and press Enter: ")
# More flair to indicate processing/input received
print("\n" + "." * 25 + " Processing " + "." * 25 + "\n")
return choice
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def set_id3_tags_mp3(audio_file_path, tags):
audio_file = eyed3.load(audio_file_path)
if not audio_file.tag:
audio_file.initTag()
audio_file.tag.artist = tags.get('artists')[0].get('name')
audio_file.tag.album = tags.get('album').get('name')
audio_file.tag.album_artist = tags.get('artists')[0].get('name')
audio_file.tag.title = tags.get('title')
release_date = tags.get('release_date')
if release_date and len(release_date) >= 4:
year_string = release_date[:4]
try:
year = int(year_string)
if hasattr(eyed3.id3.tag, 'Date'):
audio_file.tag.recording_date = eyed3.id3.tag.Date(year)
else:
audio_file.tag.setTextFrame("TDRC", year_string)
except ValueError:
print(f"Invalid date format in the tag: {release_date}")
audio_file.tag.genre = tags.get('genres')[0].get('name')
audio_file.tag.publisher = "KARTHIK"
audio_file.tag.copyright = tags.get('label', '')
audio_file.tag.comments.set(u"Explicit: Yes")
audio_file.tag.save(version=eyed3.id3.ID3_V2_3)
audio_file.tag.save()
if __name__ == "__main__":
user_choice = get_user_choice()
audio_file_path = 'D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3'
if user_choice == '1':
print("Using YoutubeACR.....")
song_tags = recognize_song(audio_file_path)
elif user_choice == '2':
print("Using Shazam.....")
song_tags = shazam_recognize_song(audio_file_path)
else:
print("Invalid choice. Exiting.")
exit()
if song_tags:
print(f'Song identified: {song_tags}')
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get('artists')[0].get('name')
song_title = song_tags.get('title')
safe_artist_name = re.sub(r'[/\:?"<>|]', '', artist_name)
safe_song_title = re.sub(r'[/\:?"<>|]', '', song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}")
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search('songs', f"{artist_name} - {song_title}")
if track_results:
track_id = track_results[0]['id']
album_artwork_url_template = track_results[0]['attributes']['artwork']['url']
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print("Song not found on Apple Music.")
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f"{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print('Could not identify the song.')
(none access_key or access_secret)
i have provided my access key in config.json
|
32d8e274d79a8d63a33496f6f9da76e4
|
{
"intermediate": 0.30845460295677185,
"beginner": 0.4937347173690796,
"expert": 0.19781067967414856
}
|
43,803
|
In my word macro document, I have a VBA code that copies the document into my email client. Unfortunately, it does not retain the table size. Can thi be fixed: Private Sub CommandButton1_Click()
Dim OutApp As Object
Dim OutMail As Object
Dim tbl As Word.Table
Dim htmlBody As String
' Get the Word table
Set tbl = ActiveDocument.Tables(1)
tbl.Select
' Copy the table as HTML
tbl.Range.Copy
' Send to Outlook
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = "finance@magdalen.northants.sch.uk"
.Subject = "Facilities Internal Order Form"
.htmlBody = htmlBody ' Set the email body as HTML
.Display ' Or use .Send to send directly
End With
' Paste as HTML
OutMail.GetInspector.WordEditor.Range.PasteAndFormat wdFormatOriginalFormatting
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
|
59c8fc084e5c99b3c9272d684613cb9c
|
{
"intermediate": 0.47521066665649414,
"beginner": 0.3216686248779297,
"expert": 0.20312067866325378
}
|
43,804
|
in this javascript when I display the totalScore and possibleScore is it possible to have a button to start a new game - this time using data from a cat.json file rather than main.json 'let map; // Declare map globally
let streetLatitude;
let streetLongitude;
let marker; // Define marker globally to make it accessible across functions
let totalScore = 0; // Initialize total points variable
let possibleScore = 0; // Initialize total points variable
let imageIndex = 0; // Initialize image index
let PictureURL; // Define PictureURL at a higher scope level
let Description;
let clickListener; // Store the click listener reference
let roundScores = [];
function fetchStreetDetails(callback) {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
const entryCount = jsonData.Features.length;
// Check if there are more images to display
if (imageIndex >= entryCount) {
console.log("No more images to display!");
// Display "Game Over" message
const resultsDiv = document.getElementById("results");
const finalScores = `Total Score: ${totalScore} points out of a possible ${possibleScore}<br><br>`;
const scoreLine = createScoreLine(totalScore, possibleScore);
const paintingDiv = document.getElementById("painting");
paintingDiv.style.backgroundColor = "#fff"; // Set background color directly
paintingDiv.innerHTML = finalScores; // Update content with innerHTML
paintingDiv.appendChild(scoreLine);
// Add individual round scores
resultsDiv.innerHTML += "<br><br><b>Painting Scores:</b><br><br>";
roundScores.forEach((roundScore, index) => {
resultsDiv.innerHTML += `Round ${index + 1}: ${roundScore} points<br>`;
});
//remove painting info
const infoDiv = document.getElementById("info");
if (infoDiv) {
infoDiv.remove();
} else {
console.error("Div element with ID 'info' not found!");
}
return;
}
const streetDetails = jsonData.Features[imageIndex]; // Get image data based on index
// Extract PictureURL at a higher scope level
PictureURL = streetDetails.PictureURL;
Description = streetDetails.Description;
// Extract details
const FeatureID = streetDetails.FeatureID;
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
const streetHeading = streetDetails.StreetHeading;
const streetPitch = streetDetails.StreetPitch;
const streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
console.log("FeatureID: " + FeatureID);
console.log("PictureURL: " + PictureURL);
console.log("Description: " + Description);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
// Update numberoffeeds div
const numberoffeedsElement = document.getElementById("results");
numberoffeedsElement.textContent = `This is a ${entryCount} round game.\nClick on the map where you think this scene is.`;
callback(FeatureID);
})
.catch((error) => console.error("Error fetching data: ", error));
}
//visualize and animate finalscore
function createScoreLine(
totalScore,
possibleScore,
color = "#ff0000",
backgroundColor = "#107896",
animationDuration = 1000
) {
// milliseconds
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set canvas dimensions based on your needs
canvas.width = 200;
canvas.height = 30;
let currentPercentage = 0; // Track current percentage for animation
const animateFill = () => {
if (currentPercentage >= (totalScore / possibleScore) * 100) {
return; // Stop animation if reached target percentage
}
currentPercentage += 1; // Increment current percentage for animation
// Clear the canvas before each redraw to avoid stacking lines
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set background color
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set fill color for the line
ctx.fillStyle = color;
// Adjust the rectangle width based on current percentage
ctx.fillRect(0, 0, canvas.width * (currentPercentage / 100), canvas.height);
// Request another animation frame for smooth animation
requestAnimationFrame(animateFill);
};
animateFill(); // Start the animation
return canvas;
}
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "transit",
stylers: [
{
visibility: "off",
},
],
},
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Add a click event listener to the map
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng; // Get the latitude and longitude of the click
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map, // Set the map where the marker will be displayed
draggable: true, // Set draggable to true
});
// (Optional) Add additional customization to the marker here,
// such as setting an icon or info window
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(map, clickLocation);
});
}
//nextbutton
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Function to create and add the button
function createSubmitButton(map, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
if (!buttonsDiv) {
console.error("Element with ID 'buttons' not found!");
return;
}
const submitButton = document.createElement("button");
submitButton.textContent = "Submit"; // Customize button text
submitButton.classList.add("button"); // Add class 'button'
submitButton.addEventListener("click", () => {
// Handle button click event here (e.g., send clickLocation data)
console.log(
"Button clicked! Latitude:",
clickLocation.lat(),
"Longitude:",
clickLocation.lng()
);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance between marker and StreetPoints
const distanceInMeters =
google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(streetLatitude, streetLongitude),
markerPosition
);
const roundedDistanceInMeters = Math.floor(distanceInMeters); // Round down to the nearest meter
console.log(
"Distance to StreetPoints: " + roundedDistanceInMeters + " meters"
);
// Adjust points based on distance
let score = 5000 - roundedDistanceInMeters;
if (score < 0) {
score = 0;
}
totalScore += score; // Add current points to total
possibleScore += 5000;
roundScores.push(score);
const message = "You scored " + score + " points";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Create a polyline between marker and StreetPoints
const lineCoordinates = [
{ lat: streetLatitude, lng: streetLongitude },
{ lat: markerPosition.lat(), lng: markerPosition.lng() },
];
const polyline = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
});
// Set the polyline on the map
polyline.setMap(map);
marker.setDraggable(false);
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend({ lat: streetLatitude, lng: streetLongitude });
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
});
buttonsDiv.appendChild(submitButton);
}
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
});
// Function to update the image and description
function updateImage(FeatureID, PictureURL) {
const infoDiv = document.getElementById("info");
const infoHTML = Description;
infoDiv.innerHTML = infoHTML;
const paintingDiv = document.getElementById("painting");
const imageHTML =
'<img src="' +
PictureURL +
'" onclick="this.requestFullscreen()" style="width: 90%;" class="center">';
console.log("Image URL:", imageHTML); // Log the image URL to the console
paintingDiv.innerHTML = imageHTML;
}
// Add click event for the ‘Next’ button
nextButton.addEventListener("click", () => {
// Increment the image index to fetch the next image
imageIndex++;
// Fetch the next image from the JSON file and update the painting div
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
map.setCenter(newLatLng);
map.setZoom(3);
const message = "Where do you think this scene is?";
// Add click event listener back to the map
google.maps.event.clearListeners(map, "click"); // Clear existing click listeners
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng;
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true,
});
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
createSubmitButton(map, clickLocation);
});
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
});
const buttonsDiv = document.getElementById("buttons");
buttonsDiv.removeChild(nextButton);
});'
|
5a1006b4c6cc5aca548905e01ce18534
|
{
"intermediate": 0.318785697221756,
"beginner": 0.39405375719070435,
"expert": 0.28716057538986206
}
|
43,805
|
from my_shazam_utility import shazam_recognize_song
import acrcloud
import os
import eyed3
import requests
import json
import re
from applemusic_api import AppleMusicApi
from acrcloud.recognizer import ACRCloudRecognizer
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open('D:/Eurydice/Encompassing Data by discerning/config/config.json', 'r') as config_file:
config_data = json.load(config_file)
return config_data
dir(acrcloud)
config = load_config()
# Accessing the configuration values
ACR_HOST = config['ACR']['HOST']
ACR_ACCESS_KEY = config['ACR']['ACCESS_KEY']
ACR_ACCESS_SECRET = config['ACR']['ACCESS_SECRET']
recognizer = ACRCloudRecognizer({
'host': ACR_HOST,
'access_key': ACR_ACCESS_KEY,
'access_secret': ACR_ACCESS_SECRET,
'timeout': 10 # seconds
})
def get_user_choice():
# Display a header
print("=" * 50)
print("Welcome to the Song Recognition Service!")
print("=" * 50)
# Provide instructions and options
print("\nPlease select the recognition service you'd like to use:\n")
print(" 1: Youtube-ACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print("-" * 50)
# Input prompt
choice = input("Enter your choice (1 or 2) and press Enter: ")
# More flair to indicate processing/input received
print("\n" + "." * 25 + " Processing " + "." * 25 + "\n")
return choice
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def set_id3_tags_mp3(audio_file_path, tags):
audio_file = eyed3.load(audio_file_path)
if not audio_file.tag:
audio_file.initTag()
audio_file.tag.artist = tags.get('artists')[0].get('name')
audio_file.tag.album = tags.get('album').get('name')
audio_file.tag.album_artist = tags.get('artists')[0].get('name')
audio_file.tag.title = tags.get('title')
release_date = tags.get('release_date')
if release_date and len(release_date) >= 4:
year_string = release_date[:4]
try:
year = int(year_string)
if hasattr(eyed3.id3.tag, 'Date'):
audio_file.tag.recording_date = eyed3.id3.tag.Date(year)
else:
audio_file.tag.setTextFrame("TDRC", year_string)
except ValueError:
print(f"Invalid date format in the tag: {release_date}")
audio_file.tag.genre = tags.get('genres')[0].get('name')
audio_file.tag.publisher = "KARTHIK"
audio_file.tag.copyright = tags.get('label', '')
audio_file.tag.comments.set(u"Explicit: Yes")
audio_file.tag.save(version=eyed3.id3.ID3_V2_3)
audio_file.tag.save()
if __name__ == "__main__":
user_choice = get_user_choice()
audio_file_path = 'D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3'
if user_choice == '1':
print("Using YoutubeACR.....")
song_tags = recognize_song(audio_file_path)
elif user_choice == '2':
print("Using Shazam.....")
song_tags = shazam_recognize_song(audio_file_path)
else:
print("Invalid choice. Exiting.")
exit()
if song_tags:
print(f'Song identified: {song_tags}')
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get('artists')[0].get('name')
song_title = song_tags.get('title')
safe_artist_name = re.sub(r'[/\:?"<>|]', '', artist_name)
safe_song_title = re.sub(r'[/\:?"<>|]', '', song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}")
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search('songs', f"{artist_name} - {song_title}")
if track_results:
track_id = track_results[0]['id']
album_artwork_url_template = track_results[0]['attributes']['artwork']['url']
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print("Song not found on Apple Music.")
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f"{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print('Could not identify the song.')
Finished recognizing the song.
Could not identify the song.
this error only occurs when selecting shazam otherwise everything runs normal through ACRCLOUD
|
10b8b951403581e75783b510006964d6
|
{
"intermediate": 0.3348608911037445,
"beginner": 0.5393526554107666,
"expert": 0.1257864385843277
}
|
43,806
|
in this javascript when the finalScore and totalScore are displayed I also want to remove the 'const message = "You scored " + score + " points";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
' message previously displayed in the 'results' div. 'let map; // Declare map globally
let streetLatitude;
let streetLongitude;
let marker; // Define marker globally to make it accessible across functions
let totalScore = 0; // Initialize total points variable
let possibleScore = 0; // Initialize total points variable
let imageIndex = 0; // Initialize image index
let PictureURL; // Define PictureURL at a higher scope level
let Description;
let clickListener; // Store the click listener reference
let roundScores = [];
function fetchStreetDetails(callback) {
fetch("cat.json")
.then((response) => response.json())
.then((jsonData) => {
const entryCount = jsonData.Features.length;
// Check if there are more images to display
if (imageIndex >= entryCount) {
console.log("No more images to display!");
// Display "Game Over" message
const resultsDiv = document.getElementById("results");
const finalScores = `Total Score: ${totalScore} points out of a possible ${possibleScore}<br><br>`;
const scoreLine = createScoreLine(totalScore, possibleScore);
const paintingDiv = document.getElementById("painting");
paintingDiv.style.backgroundColor = "#fff"; // Set background color directly
paintingDiv.innerHTML = finalScores; // Update content with innerHTML
paintingDiv.appendChild(scoreLine);
// Add individual round scores
resultsDiv.innerHTML += "<br><br><b>Painting Scores:</b><br><br>";
roundScores.forEach((roundScore, index) => {
resultsDiv.innerHTML += `Round ${index + 1}: ${roundScore} points<br>`;
});
//remove painting info
const infoDiv = document.getElementById("info");
if (infoDiv) {
infoDiv.remove();
} else {
console.error("Div element with ID 'info' not found!");
}
return;
}
const streetDetails = jsonData.Features[imageIndex]; // Get image data based on index
// Extract PictureURL at a higher scope level
PictureURL = streetDetails.PictureURL;
Description = streetDetails.Description;
// Extract details
const FeatureID = streetDetails.FeatureID;
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
const streetHeading = streetDetails.StreetHeading;
const streetPitch = streetDetails.StreetPitch;
const streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
console.log("FeatureID: " + FeatureID);
console.log("PictureURL: " + PictureURL);
console.log("Description: " + Description);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
// Update numberoffeeds div
const numberoffeedsElement = document.getElementById("results");
numberoffeedsElement.textContent = `This is a ${entryCount} round game.\nClick on the map where you think this scene is.`;
callback(FeatureID);
})
.catch((error) => console.error("Error fetching data: ", error));
}
//visualize and animate finalscore
function createScoreLine(
totalScore,
possibleScore,
color = "#ff0000",
backgroundColor = "#107896",
animationDuration = 1000
) {
// milliseconds
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set canvas dimensions based on your needs
canvas.width = 200;
canvas.height = 30;
let currentPercentage = 0; // Track current percentage for animation
const animateFill = () => {
if (currentPercentage >= (totalScore / possibleScore) * 100) {
return; // Stop animation if reached target percentage
}
currentPercentage += 1; // Increment current percentage for animation
// Clear the canvas before each redraw to avoid stacking lines
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set background color
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set fill color for the line
ctx.fillStyle = color;
// Adjust the rectangle width based on current percentage
ctx.fillRect(0, 0, canvas.width * (currentPercentage / 100), canvas.height);
// Request another animation frame for smooth animation
requestAnimationFrame(animateFill);
};
animateFill(); // Start the animation
return canvas;
}
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "transit",
stylers: [
{
visibility: "off",
},
],
},
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Add a click event listener to the map
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng; // Get the latitude and longitude of the click
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map, // Set the map where the marker will be displayed
draggable: true, // Set draggable to true
});
// (Optional) Add additional customization to the marker here,
// such as setting an icon or info window
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(map, clickLocation);
});
}
//nextbutton
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Function to create and add the button
function createSubmitButton(map, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
if (!buttonsDiv) {
console.error("Element with ID 'buttons' not found!");
return;
}
const submitButton = document.createElement("button");
submitButton.textContent = "Submit"; // Customize button text
submitButton.classList.add("button"); // Add class 'button'
submitButton.addEventListener("click", () => {
// Handle button click event here (e.g., send clickLocation data)
console.log(
"Button clicked! Latitude:",
clickLocation.lat(),
"Longitude:",
clickLocation.lng()
);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance between marker and StreetPoints
const distanceInMeters =
google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(streetLatitude, streetLongitude),
markerPosition
);
const roundedDistanceInMeters = Math.floor(distanceInMeters); // Round down to the nearest meter
console.log(
"Distance to StreetPoints: " + roundedDistanceInMeters + " meters"
);
// Adjust points based on distance
let score = 5000 - roundedDistanceInMeters;
if (score < 0) {
score = 0;
}
totalScore += score; // Add current points to total
possibleScore += 5000;
roundScores.push(score);
const message = "You scored " + score + " points";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Create a polyline between marker and StreetPoints
const lineCoordinates = [
{ lat: streetLatitude, lng: streetLongitude },
{ lat: markerPosition.lat(), lng: markerPosition.lng() },
];
const polyline = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
});
// Set the polyline on the map
polyline.setMap(map);
marker.setDraggable(false);
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend({ lat: streetLatitude, lng: streetLongitude });
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
});
buttonsDiv.appendChild(submitButton);
}
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
});
// Function to update the image and description
function updateImage(FeatureID, PictureURL) {
const infoDiv = document.getElementById("info");
const infoHTML = Description;
infoDiv.innerHTML = infoHTML;
const paintingDiv = document.getElementById("painting");
const imageHTML =
'<img src="' +
PictureURL +
'" onclick="this.requestFullscreen()" style="width: 90%;" class="center">';
console.log("Image URL:", imageHTML); // Log the image URL to the console
paintingDiv.innerHTML = imageHTML;
}
// Add click event for the ‘Next’ button
nextButton.addEventListener("click", () => {
// Increment the image index to fetch the next image
imageIndex++;
// Fetch the next image from the JSON file and update the painting div
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
map.setCenter(newLatLng);
map.setZoom(3);
const message = "Where do you think this scene is?";
// Add click event listener back to the map
google.maps.event.clearListeners(map, "click"); // Clear existing click listeners
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng;
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true,
});
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
createSubmitButton(map, clickLocation);
});
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
});
const buttonsDiv = document.getElementById("buttons");
buttonsDiv.removeChild(nextButton);
});'
|
a8e9700e2164cca07b4f6ac2c4adefa4
|
{
"intermediate": 0.29163748025894165,
"beginner": 0.36617329716682434,
"expert": 0.3421891927719116
}
|
43,807
|
create a react hook for the following javascript map: export const daysMapArabic = new Map([
["Su", "أحد"],
["Mo", "اثنين"],
["Tu", "ثلاثاء"],
["We", "أربعاء"],
["Th", "خميس"],
["Fr", "جمعة"],
["Sa", "سبت"],
]);
|
f779b1bc6f2a06bef68aef5bb5ddd1fd
|
{
"intermediate": 0.4645119309425354,
"beginner": 0.28640216588974,
"expert": 0.249085932970047
}
|
43,808
|
# Предобработка изображений
def preprocess_image(image):
image = tf.image.resize(image, (128, 128))
image = tf.cast(image, tf.float32) / 255.0
return image
def preprocess_data(example):
image = example['image']
label = example['label']
image = preprocess_image(image)
return image, label
train_dataset = train_dataset.map(preprocess_data).shuffle(1024).batch(16)
# Создаем модель сверточной нейронной сети
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# Компилируем модель
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Обучаем модель
model.fit(train_dataset, epochs=10) как запустить данную модель на тестовых данных и проверить loglos?
|
8a4f481b9ed7af0d371e07fba90f385a
|
{
"intermediate": 0.38123080134391785,
"beginner": 0.24269148707389832,
"expert": 0.3760777413845062
}
|
43,809
|
Имеется такой драйвер ядра:
#include <ntifs.h>
extern "C" {
NTKERNELAPI NTSTATUS IoCreateDriver(PUNICODE_STRING DriverName,
PDRIVER_INITIALIZE InitializationFunction);
NTKERNELAPI NTSTATUS MmCopyVirtualMemory(PEPROCESS SourceProcess, PVOID SourceAddress,
PEPROCESS TargetProcess, PVOID TargetAddress,
SIZE_T BufferSize, KPROCESSOR_MODE PreviousMode,
PSIZE_T ReturnSize);
}
void debug_print(PCSTR text) {
#ifndef DEBUG
UNREFERENCED_PARAMETER(text);
#endif // DEBUG
KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, text));
}
namespace driver {
namespace codes {
// Used to setup the driver.
constexpr ULONG attach =
CTL_CODE(FILE_DEVICE_UNKNOWN, 0x696, METHOD_BUFFERED, FILE_SPECIAL_ACCESS);
// Read process memory.
constexpr ULONG read =
CTL_CODE(FILE_DEVICE_UNKNOWN, 0x697, METHOD_BUFFERED, FILE_SPECIAL_ACCESS);
// Write process memory.
constexpr ULONG write =
CTL_CODE(FILE_DEVICE_UNKNOWN, 0x698, METHOD_BUFFERED, FILE_SPECIAL_ACCESS);
} // namespace codes
// Shares between user mode & kernel mode.
struct Request {
HANDLE process_id;
PVOID target;
PVOID buffer;
SIZE_T size;
SIZE_T return_size;
};
NTSTATUS create(PDEVICE_OBJECT device_object, PIRP irp) {
UNREFERENCED_PARAMETER(device_object);
IoCompleteRequest(irp, IO_NO_INCREMENT);
return irp->IoStatus.Status;
}
NTSTATUS close(PDEVICE_OBJECT device_object, PIRP irp) {
UNREFERENCED_PARAMETER(device_object);
IoCompleteRequest(irp, IO_NO_INCREMENT);
return irp->IoStatus.Status;
}
NTSTATUS device_control(PDEVICE_OBJECT device_object, PIRP irp) {
UNREFERENCED_PARAMETER(device_object);
debug_print("[+] Device control called.\n");
NTSTATUS status = STATUS_UNSUCCESSFUL;
// We need this to determine with code passed through.
PIO_STACK_LOCATION stack_irp = IoGetCurrentIrpStackLocation(irp);
// Access the request object sent from user mode.
auto request = reinterpret_cast<Request*>(irp->AssociatedIrp.SystemBuffer);
if (stack_irp == nullptr || request == nullptr) {
IoCompleteRequest(irp, IO_NO_INCREMENT);
return status;
}
// The target process we want access to.
static PEPROCESS target_process = nullptr;
const ULONG control_code = stack_irp->Parameters.DeviceIoControl.IoControlCode;
switch (control_code) {
case codes::attach:
status = PsLookupProcessByProcessId(request->process_id, &target_process);
break;
case codes::read:
if (target_process != nullptr)
status = MmCopyVirtualMemory(target_process, request->target,
PsGetCurrentProcess(), request->buffer, request->size,
KernelMode, &request->return_size);
break;
case codes::write:
if (target_process != nullptr)
status = MmCopyVirtualMemory(PsGetCurrentProcess(), request->buffer,
target_process, request->target, request->size,
KernelMode, &request->return_size);
break;
default:
break;
}
irp->IoStatus.Status = status;
irp->IoStatus.Information = sizeof(Request);
IoCompleteRequest(irp, IO_NO_INCREMENT);
return status;
}
} // namespace driver
// Our "real" entry point.
NTSTATUS driver_main(PDRIVER_OBJECT driver_object, PUNICODE_STRING registry_path) {
UNREFERENCED_PARAMETER(registry_path);
UNICODE_STRING device_name = {};
RtlInitUnicodeString(&device_name, L"\\Device\\MotorolaDriver");
// Create driver device obj.
PDEVICE_OBJECT device_object = nullptr;
NTSTATUS status = IoCreateDevice(driver_object, 0, &device_name, FILE_DEVICE_UNKNOWN,
FILE_DEVICE_SECURE_OPEN, FALSE, &device_object);
if (status != STATUS_SUCCESS) {
debug_print("[-] Failed to create driver device.\n");
return status;
}
debug_print("[+] Driver device successfully created.\n");
UNICODE_STRING symbolic_link = {};
RtlInitUnicodeString(&symbolic_link, L"\\DosDevices\\MotorolaDriver");
status = IoCreateSymbolicLink(&symbolic_link, &device_name);
if (status != STATUS_SUCCESS) {
debug_print("[-] Failed to establish symbolic link.\n");
return status;
}
debug_print("[+] Driver symbolic link successfully established.\n");
// Allow us to send small amount of data between um/km.
SetFlag(device_object->Flags, DO_BUFFERED_IO);
// Set the driver handlers to our functions with our logic.
driver_object->MajorFunction[IRP_MJ_CREATE] = driver::create;
driver_object->MajorFunction[IRP_MJ_CLOSE] = driver::close;
driver_object->MajorFunction[IRP_MJ_DEVICE_CONTROL] = driver::device_control;
// We have initialized our device.
ClearFlag(device_object->Flags, DO_DEVICE_INITIALIZING);
debug_print("[+] Driver initialized successfully.\n");
return status;
}
NTSTATUS DriverEntry() {
debug_print("[+] Alloe from the kernel!\n");
UNICODE_STRING driver_name = {};
RtlInitUnicodeString(&driver_name, L"\\Driver\\MotorolaDriver");
return IoCreateDriver(&driver_name,driver_main);
}
Приложение для него:
#include <iostream>
#include <iomanip>
#include <future>
#include <algorithm>
#include <string>
#include <memory>
#include <mutex>
#include <vector>
#include <Windows.h>
#include <TlHelp32.h>
#include "driver_code.h"
class MemoryPatcher {
HANDLE driver_handle;
DWORD pid;
std::mutex print_mutex;
std::uintptr_t turnback_patch_address = 0;
bool is_patched_to_31 = false;
public:
MemoryPatcher(HANDLE driverHandle, DWORD processId) : driver_handle(driverHandle), pid(processId) {}
bool apply_patch(const std::string& patch_name, const std::vector<BYTE>& sequence, const std::vector<BYTE>& patch, std::uintptr_t start_address, std::uintptr_t end_address, int target_occurrence = 1) {
std::lock_guard<std::mutex> guard(print_mutex);
std::cout << "[+] Attempting to apply " << patch_name << " patch\n";
int occurrence_count = 0;
auto current_address = start_address;
while (current_address < end_address) {
auto found_address = driver::find_memory_sequence(driver_handle, pid, sequence, current_address, end_address);
if (found_address != 0) {
occurrence_count++;
if (occurrence_count == target_occurrence) {
std::cout << "[+] " << patch_name << " sequence found at : 0x" << std::uppercase << std::hex << found_address << std::dec << "\n";
if (driver::replace_memory_sequence(driver_handle, found_address, patch)) {
std::cout << "[+] " << patch_name << " sequence has been successfully replaced!\n";
if (patch_name == "turnback" && occurrence_count == target_occurrence) {
turnback_patch_address = found_address;
std::cout << "[+] vision address set to : 0x" << std::hex << turnback_patch_address << std::dec << "\n";
}
return true;
}
else {
std::cout << "[-] Failed to apply " << patch_name << ".\n";
return false;
}
}
current_address = found_address + sequence.size();
}
else {
break;
}
}
std::cout << "[-] " << patch_name << " sequence not found.\n";
return false;
}
void toggle_vision() {
std::lock_guard<std::mutex> guard(print_mutex);
if (turnback_patch_address == 0) {
std::cout << "[-] vision address is not set.\n";
return;
}
std::vector<BYTE> new_patch;
std::string vision_state_before_toggle = is_patched_to_31 ? "ON" : "OFF";
if (is_patched_to_31) {
new_patch = { 0x00, 0x00, 0x00, 0x73, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00, 0x20, 0x00, 0x66, 0x00, 0x70, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x72, 0x00, 0x6D, 0x00, 0x6F, 0x00, 0x64, 0x00, 0x65, 0x00, 0x20, 0x00, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
} else {
new_patch = { 0x00, 0x00, 0x00, 0x73, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00, 0x20, 0x00, 0x66, 0x00, 0x70, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x72, 0x00, 0x6D, 0x00, 0x6F, 0x00, 0x64, 0x00, 0x65, 0x00, 0x20, 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
}
if (driver::replace_memory_sequence(driver_handle, turnback_patch_address, new_patch)) {
is_patched_to_31 = !is_patched_to_31;
std::string vision_state_after_toggle = is_patched_to_31 ? "ON" : "OFF";
std::cout << "[+] vision " << vision_state_after_toggle << " at 0x" << std::hex << turnback_patch_address << "\n";
}
else {
std::cout << "[-] failed to toggle Vision.\n";
}
}
};
int main() {
auto pid = ProcessHelper::getProcessId(L"l2.bin");
if (pid == 0) {
std::cout << "[-] Failed to find l2.bin.\n";
std::cin.get();
return 1;
}
HANDLE driver_handle = CreateFile(L"\\\\.\\MotorolaDriver", GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (driver_handle == INVALID_HANDLE_VALUE) {
std::cout << "[-] Failed to create our driver handle.\n";
std::cin.get();
return 1;
}
if (driver::attach_to_process(driver_handle, pid)) {
std::cout << "[+] Attachment successful.\n";
}
else {
std::cout << "[-] Failed to attach to process.\n";
std::cin.get();
return 1;
}
MemoryPatcher patcher(driver_handle, pid);
std::vector<BYTE> page_up_down_bytes = { 0x44, 0x00, 0x65, 0x00, 0x62, 0x00, 0x75, 0x00, 0x67, 0x00, 0x4D, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x75, 0x00, 0x2E, 0x00, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x69, 0x00, 0x78, 0x00, 0x65, 0x00, 0x64, 0x00, 0x44, 0x00, 0x65, 0x00, 0x66, 0x00, 0x61, 0x00, 0x75, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x43, 0x00, 0x61, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x72, 0x00, 0x61, 0x00, 0x20, 0x00, 0x44, 0x00, 0x6F, 0x00, 0x77, 0x00, 0x6E, 0x00, 0x00, 0x00, 0x46, 0x00, 0x69, 0x00, 0x78, 0x00, 0x65, 0x00, 0x64, 0x00, 0x44, 0x00, 0x65, 0x00, 0x66, 0x00, 0x61, 0x00, 0x75, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x43, 0x00, 0x61, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x72, 0x00, 0x61, 0x00, 0x20, 0x00, 0x55, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4B, 0x00, 0x65, 0x00, 0x79, 0x00, 0x62, 0x00, 0x6F, 0x00, 0x61, 0x00, 0x72, 0x00, 0x64, 0x00, 0x50, 0x00, 0x65, 0x00, 0x72, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x6E, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x74, 0x00, 0x4D, 0x00, 0x6F, 0x00, 0x76, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
std::vector<BYTE> page_up_down_patch = { 0x44, 0x00, 0x65, 0x00, 0x62, 0x00, 0x75, 0x00, 0x67, 0x00, 0x4D, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x75, 0x00, 0x2E, 0x00, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4C, 0x00, 0x32, 0x00, 0x52, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x61, 0x00, 0x72, 0x00, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x00, 0x68, 0x00, 0x6F, 0x00, 0x77, 0x00, 0x20, 0x00, 0x70, 0x00, 0x61, 0x00, 0x72, 0x00, 0x74, 0x00, 0x69, 0x00, 0x63, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4B, 0x00, 0x65, 0x00, 0x79, 0x00, 0x62, 0x00, 0x6F, 0x00, 0x61, 0x00, 0x72, 0x00, 0x64, 0x00, 0x50, 0x00, 0x65, 0x00, 0x72, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x6E, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x74, 0x00, 0x4D, 0x00, 0x6F, 0x00, 0x76, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
std::vector<BYTE> turnback_bytes = { 0x00, 0x00, 0x00, 0x73, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00, 0x20, 0x00, 0x66, 0x00, 0x70, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x00, 0x75, 0x00, 0x72, 0x00, 0x6E, 0x00, 0x42, 0x00, 0x61, 0x00, 0x63, 0x00, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x00 };
std::vector<BYTE> turnback_patch = { 0x00, 0x00, 0x00, 0x73, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00, 0x20, 0x00, 0x66, 0x00, 0x70, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x72, 0x00, 0x6D, 0x00, 0x6F, 0x00, 0x64, 0x00, 0x65, 0x00, 0x20, 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
// Асинхронно применяем патчи
auto pageUpDownPatchFuture = std::async(std::launch::async, &MemoryPatcher::apply_patch, &patcher, "page up - page down", page_up_down_bytes, page_up_down_patch, 0x00000000, 0x7FFFFFFF, 1);
auto turnBackPatchFuture = std::async(std::launch::async, &MemoryPatcher::apply_patch, &patcher, "turnback", turnback_bytes, turnback_patch, 0x0000000, 0x7FFFFFFF, 2);
// Ожидаем завершения
pageUpDownPatchFuture.wait();
turnBackPatchFuture.wait();
std::cout << "\n[+] Waiting for vision action...\n";
// Цикл для отслеживания нажатия кнопки колесика мыши
while (true) {
Sleep(100); // задержка для снижения загрузки CPU
if ((GetAsyncKeyState(VK_MBUTTON) & 0x8000) != 0) {
patcher.toggle_vision();
Sleep(350);
}
}
CloseHandle(driver_handle);
std::cin.get();
return 0;
}
И файл driver_code.h:
class ProcessHelper {
public:
static DWORD getProcessId(const std::wstring& processName) {
DWORD processId = 0;
HANDLE snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapShot == INVALID_HANDLE_VALUE) {
return processId;
}
PROCESSENTRY32W entry;
entry.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(snapShot, &entry)) {
do {
if (_wcsicmp(processName.c_str(), entry.szExeFile) == 0) {
processId = entry.th32ProcessID;
break;
}
} while (Process32NextW(snapShot, &entry));
}
CloseHandle(snapShot);
return processId;
}
static std::uintptr_t getModuleBase(DWORD pid, const std::wstring& moduleName) {
std::uintptr_t moduleBase = 0;
HANDLE snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
if (snapShot == INVALID_HANDLE_VALUE) {
return moduleBase;
}
MODULEENTRY32W entry;
entry.dwSize = sizeof(MODULEENTRY32W);
if (Module32FirstW(snapShot, &entry)) {
do {
if (moduleName == entry.szModule) {
moduleBase = reinterpret_cast<std::uintptr_t>(entry.modBaseAddr);
break;
}
} while (Module32NextW(snapShot, &entry));
}
CloseHandle(snapShot);
return moduleBase;
}
};
namespace driver {
namespace codes {
// Used to setup the driver.
constexpr ULONG attach =
CTL_CODE(FILE_DEVICE_UNKNOWN, 0x696, METHOD_BUFFERED, FILE_SPECIAL_ACCESS);
// Read process memory.
constexpr ULONG read =
CTL_CODE(FILE_DEVICE_UNKNOWN, 0x697, METHOD_BUFFERED, FILE_SPECIAL_ACCESS);
// Write process memory.
constexpr ULONG write =
CTL_CODE(FILE_DEVICE_UNKNOWN, 0x698, METHOD_BUFFERED, FILE_SPECIAL_ACCESS);
} // namespace codes
// Shares between user mode & kernel mode.
struct Request {
HANDLE process_id;
PVOID target;
PVOID buffer;
SIZE_T size;
SIZE_T return_size;
};
bool attach_to_process(HANDLE driver_handle, const DWORD pid) {
Request r;
r.process_id = reinterpret_cast<HANDLE>(pid);
return DeviceIoControl(driver_handle, codes::attach, &r, sizeof(r), &r, sizeof(r), nullptr, nullptr);
}
// Обновлено для поддержки размера буфера и обработки указателей на данные
bool read_memory(HANDLE driver_handle, std::uintptr_t address, PVOID buffer, SIZE_T size) {
Request r;
r.target = reinterpret_cast<PVOID>(address);
r.buffer = buffer;
r.size = size;
DWORD bytes_returned;
return DeviceIoControl(driver_handle, codes::read, &r, sizeof(r), &r, sizeof(r), &bytes_returned, nullptr);
}
bool write_memory(HANDLE driver_handle, std::uintptr_t address, const void* buffer, SIZE_T size) {
Request r;
r.target = reinterpret_cast<PVOID>(address);
r.buffer = const_cast<PVOID>(buffer);
r.size = size;
DWORD bytes_returned;
return DeviceIoControl(driver_handle, codes::write, &r, sizeof(r), &r, sizeof(r), &bytes_returned, nullptr);
}
std::uintptr_t find_memory_sequence(HANDLE driver_handle, DWORD pid, const std::vector<BYTE>& sequence, std::uintptr_t start_address, std::uintptr_t end_address) {
std::vector<BYTE> buffer(10240); // Буфер для чтения памяти
std::uintptr_t current_address = start_address;
while (current_address < end_address) {
// Чтение памяти процесса
SIZE_T read_size = buffer.size();
if (current_address + read_size > end_address) {
read_size = end_address - current_address;
}
if (!read_memory(driver_handle, current_address, buffer.data(), read_size)) {
// Заметьте, здесь мы принимаем решение продолжать, даже если чтение не удалось
// Переход к следующему блоку памяти, даже если текущий блок нельзя прочитать
current_address += buffer.size();
continue;
}
// Поиск последовательности в буфере
auto it = std::search(buffer.begin(), buffer.begin() + read_size, sequence.begin(), sequence.end());
// Проверка, нашли ли мы последовательность
if (it != buffer.begin() + read_size) {
return current_address + std::distance(buffer.begin(), it);
}
// Перемещаем current_address вперед, чтобы искать в следующем блоке памяти
if (read_size == buffer.size()) {
current_address += buffer.size() - sequence.size() + 1;
}
else {
// Если размер последнего прочитанного блока меньше размера буфера,
// значит мы достигли конца доступной области памяти.
break;
}
}
return 0; // Если не найдено
}
bool replace_memory_sequence(HANDLE driver_handle, std::uintptr_t address, const std::vector<BYTE>& new_bytes) {
return write_memory(driver_handle, address, new_bytes.data(), new_bytes.size());
}
} // namespace driver
Спустя некоторое время после работы приложения происходит отключение сетевого драйвера, а после BSOD. Найди проблемный участок, исправь его и отправь мне готовый код.
|
b3e82663497c175b0c96da3569c4345a
|
{
"intermediate": 0.41707247495651245,
"beginner": 0.36191627383232117,
"expert": 0.22101125121116638
}
|
43,810
|
RANDOM RANGE python
|
0dfa5debe691133a4635230388171644
|
{
"intermediate": 0.391759991645813,
"beginner": 0.2680891156196594,
"expert": 0.3401508629322052
}
|
43,811
|
here is the code for an app, don't say anything because i will ask you after that, **code**: import torch
import torch.nn as nn
import torch.optim as optim
import json
import base64
from torch.utils.data import DataLoader, Dataset
import binascii
import chardet
import random
import math
class PositionalEncoding(nn.Module):
def __init__(self, embedding_dim, max_len=5000):
super(PositionalEncoding, self).__init__()
self.embedding_dim = embedding_dim
# Creating positional encoding matrix
pe = torch.zeros(max_len, embedding_dim)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, embedding_dim, 2).float() * (-math.log(10000.0) / embedding_dim))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
# Registering pe as a buffer since it’s not a model parameter
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:x.size(0), :]
return x
class DecoderLayer(nn.Module):
def __init__(self, embedding_dim, heads, ff_dim):
super(DecoderLayer, self).__init__()
self.self_attn = nn.MultiheadAttention(embedding_dim, heads)
# Feedforward network
self.ffn = nn.Sequential(
nn.Linear(embedding_dim, ff_dim),
nn.ReLU(),
nn.Linear(ff_dim, embedding_dim),
)
self.layer_norm1 = nn.LayerNorm(embedding_dim)
self.layer_norm2 = nn.LayerNorm(embedding_dim)
def forward(self, src):
src2 = self.layer_norm1(src)
attn_output, _ = self.self_attn(src2, src2, src2)
src = src + attn_output
src2 = self.layer_norm2(src)
src = src + self.ffn(src2)
return src
class Decoder(nn.Module):
def __init__(self, vocab_size, embedding_dim, num_layers, heads, ff_dim):
super(Decoder, self).__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.pos_encoding = PositionalEncoding(embedding_dim)
self.decoder_layers = nn.ModuleList([DecoderLayer(embedding_dim, heads, ff_dim) for _ in range(num_layers)])
self.final_layer = nn.Linear(embedding_dim, vocab_size)
def forward(self, x):
x = self.embedding(x)
x = self.pos_encoding(x)
for layer in self.decoder_layers:
x = layer(x)
output = self.final_layer(x)
return output
class QAJsonlDataset(Dataset):
def __init__(self, path, seq_len=512):
super().__init__()
self.pairs = self.load_data(path)
self.seq_len = seq_len
self.vocab = self.build_vocab([word for pair in self.pairs for item in pair for word in item])
def __len__(self):
return len(self.pairs)
def __getitem__(self, idx):
question, answer = self.pairs[idx]
question_tokenized = self.tokenize([self.vocab[word] for word in question])
answer_tokenized = self.tokenize([self.vocab[word] for word in answer])
return torch.tensor(question_tokenized), torch.tensor(answer_tokenized)
def load_data(self, path):
pairs = []
with open(path, "rb") as f: # Open in binary mode
for line in f:
data = json.loads(line.decode("utf-8")) # Decode binary data to JSON
question, answer = self.decode_binary_data(data["user"], data["content"]) # Decode binary fields
pairs.append((question.split(), answer.split()))
return pairs
def decode_binary_data(self, question_data, answer_data):
try:
question_encoding = chardet.detect(question_data.encode("utf-8"))['encoding'] # Detect encoding
try:
question = base64.b64decode(question_data).decode(question_encoding)
except binascii.Error:
try:
question = base64.b64decode(question_data.encode("utf-8") + b'=' * (-len(question_data) % 4)).decode(question_encoding)
except binascii.Error:
print("Error decoding question (might be corrupt).")
question = ""
answer_encoding = chardet.detect(answer_data.encode("utf-8"))['encoding'] # Detect encoding for answer
try:
answer = base64.b64decode(answer_data).decode(answer_encoding)
except binascii.Error:
try:
answer = base64.b64decode(answer_data.encode("utf-8") + b'=' * (-len(answer_data) % 4)).decode(answer_encoding)
except binascii.Error:
print("Error decoding answer (might be corrupt).")
answer = ""
except UnicodeDecodeError:
print("Error decoding binary data (invalid encoding).")
question = ""
answer = ""
return question, answer
def tokenize(self, integer_sequence):
tokens = integer_sequence[:self.seq_len]
if len(tokens) < self.seq_len:
# Pad with appropriate binary token
padding_token = self.vocab["<pad>"] # Consider a binary padding token if needed
tokens.extend([padding_token] * (self.seq_len - len(tokens)))
# Add <eos> token only if appropriate for binary representation
return tokens
def build_vocab(self, binary_tokens):
# Your implementation here. This is a placeholder.
unique_tokens = list(set(binary_tokens))
vocab = {token: idx for idx, token in enumerate(unique_tokens)}
vocab['<pad>'] = len(vocab) # Adding a padding token
return vocab
class DataLoader(Dataset):
def __init__(self, dataset, batch_size=32):
self.dataset = dataset
self.batch_size = batch_size
def __len__(self):
return len(self.dataset) // self.batch_size
def __getitem__(self, idx):
batch = self.dataset[idx * self.batch_size:(idx + 1) * self.batch_size]
inputs, targets = zip(*batch) # Assuming inputs and targets are tensors
inputs_padded = torch.nn.utils.rnn.pad_sequence(inputs, batch_first=True, padding_value=0) # Using PyTorch's pad_sequence
targets_padded = torch.nn.utils.rnn.pad_sequence(targets, batch_first=True, padding_value=0)
return inputs_padded, targets_padded
# Define model parameters
vocab_size = 10000 # Adjust based on your vocabulary size
embedding_dim = 256
num_layers = 2 # Number of decoder layers
heads = 4 # Number of attention heads
ff_dim = 1024 # Feed-forward dimension
# Create decoder-only transformer model
model = Decoder(vocab_size, embedding_dim, num_layers, heads, ff_dim)
# Data loading and splitting
path_to_data = "data/Real_talk.jsonl"
dataset = QAJsonlDataset(path_to_data, 512)
# Shuffle the dataset
random.shuffle(dataset.pairs)
train_size = int(0.8 * len(dataset)) # 80% of data for training, adjust as necessary
val_size = len(dataset) - train_size
train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32)
# Define optimizer
optimizer = optim.Adam(model.parameters())
loss_fn = nn.CrossEntropyLoss() # PyTorch version of SparseCategoricalCrossentropy with from_logits=True
# Training loop (example)
for epoch in range(1, 11):
for i, (inputs, targets) in enumerate(train_loader):
optimizer.zero_grad()
output = model(inputs)
loss = loss_fn(output.view(-1, vocab_size), targets.view(-1)) # Reshape for CrossEntropyLoss
loss.backward()
optimizer.step()
print(f'Epoch {epoch}, Loss: {loss.item()}')
def evaluate(model, val_loader):
"""
Evaluates the model on the validation set and returns accuracy.
"""
correct = 0
total = 0
with torch.no_grad():
for inputs, targets in val_loader:
outputs = model(inputs)
predictions = torch.argmax(outputs, dim=1)
correct += (predictions == targets).sum().item()
total += targets.size(0)
accuracy = correct / total
return accuracy
# After training loop:
val_accuracy = evaluate(model, val_loader)
print(f'Validation Accuracy: {val_accuracy}')
|
9c15d4ae10ed1a09e01d63894915053e
|
{
"intermediate": 0.2885960042476654,
"beginner": 0.4223159849643707,
"expert": 0.28908804059028625
}
|
43,812
|
using System;
using System.Collections.Generic;
using System.Linq;
using BaseAdminApi.Enums;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Menu;
namespace BaseAdmin.Menu;
public class MenuService : IMenuService
{
private static readonly Dictionary<MenuItem, IMenu> Menus = new();
private IMenu _adminMenu = null!;
public readonly BaseAdmin BaseAdmin;
public List<ChatMenuOption> MenuOptions => _adminMenu.MenuOptions;
public MenuService(BaseAdmin baseAdmin)
{
BaseAdmin = baseAdmin;
CreateMenu();
}
public IMenu CreateMenu(string title)
{
return BaseAdmin.Config.UseCenterHtmlMenu ? new CenterHtmlMenu(title) : new ChatMenu(title);
}
public void AddMenuOptions(string display, Action<CCSPlayerController, ChatMenuOption> handler, bool disabled)
{
_adminMenu.AddMenuOption(display, handler, disabled);
}
public void AddMenuOptions(MenuItem type, string display, Action<CCSPlayerController, ChatMenuOption> handler,
bool disabled)
{
if (!Menus.TryGetValue(type, out var menu)) return;
menu.AddMenuOption(display, handler, disabled);
}
private void CreateMenu()
{
_adminMenu = CreateMenu(BaseAdmin.Localizer["menu_title"]);
_adminMenu.AddMenuOption(BaseAdmin.Localizer["menu.players_control"], PlayersControlMenu);
_adminMenu.AddMenuOption(BaseAdmin.Localizer["menu.server_control"], ServerControlMenu);
_adminMenu.AddMenuOption(BaseAdmin.Localizer["menu.lock_control"], );
}
private void ServerControlMenu(CCSPlayerController player, ChatMenuOption option)
{
throw new NotImplementedException();
}
private void PlayersControlMenu(CCSPlayerController player, ChatMenuOption option)
{
var menu = CreateMenu(BaseAdmin.Localizer["menu.players_control"]);
if (BaseAdmin.CheckingForAdminAndFlag(player, AdminFlag.Kick))
{
menu.AddMenuOption(BaseAdmin.Localizer["menu.players.kick_player"], (_, _) => PlayersHandle(player, controller =>
{
controller.Kick("Kick");
BaseAdmin.PrintToChatAll(BaseAdmin.Localizer["player.kick", player.PlayerName, controller.PlayerName]);
}));
}
if (BaseAdmin.CheckingForAdminAndFlag(player, AdminFlag.Slay))
{
menu.AddMenuOption(BaseAdmin.Localizer["menu.players.kill_player"], (_, _) => PlayersHandle(player, controller =>
{
controller.PlayerPawn.Value?.CommitSuicide(true, true);
BaseAdmin.PrintToChatAll(BaseAdmin.Localizer["player.kill", player.PlayerName, controller.PlayerName]);
}));
}
OpenMenu(player, menu);
Menus.TryAdd(MenuItem.PlayerControl, menu);
}
private void LockControlMenu(CCSPlayerController player, ChatMenuOption option)
{
var menu = CreateMenu(BaseAdmin.Localizer["menu.lock_control"]);
if (BaseAdmin.CheckingForAdminAndFlag(player, AdminFlag.Ban))
{
menu.AddMenuOption(BaseAdmin.Localizer["menu.lock.ban_player"], null!, true);
}
if (BaseAdmin.CheckingForAdminAndFlag(player, AdminFlag.Generic))
{
menu.AddMenuOption(BaseAdmin.Localizer["menu.lock.mute_player"], null!, true);
}
OpenMenu(player, menu);
Menus.TryAdd(MenuItem.LockControl, menu);
}
private void PlayersHandle(CCSPlayerController player, Action<CCSPlayerController> handler)
{
var menu = CreateMenu(BaseAdmin.Localizer["menu.all_players"]);
menu.AddMenuOption(BaseAdmin.Localizer["menu.pick_player"], null!, true);
foreach (var players in Utilities.GetPlayers().Where(u => u.IsValid))
{
if (!BaseAdmin.PlayerImmunityComparison(player, players)) continue;
menu.AddMenuOption($"{players.PlayerName} [{players.UserId}]", (_, _) => handler(players));
}
OpenMenu(player, menu);
}
public void OpenMenu(CCSPlayerController controller, IMenu? menu = null)
{
menu ??= _adminMenu;
if (BaseAdmin.Config.UseCenterHtmlMenu)
MenuManager.OpenCenterHtmlMenu(BaseAdmin, controller, (CenterHtmlMenu)menu);
else
MenuManager.OpenChatMenu(controller, (ChatMenu)menu);
}
}
хочу реализовать так чтобы я мог писать в отдельных классах PlayersControlMenu, ServerControlMenu, LockControlMenu и уже их тут открывать чтобы класс не был слишком огромен
|
b7b779479dca341516f9524404dbb80e
|
{
"intermediate": 0.2922380566596985,
"beginner": 0.5171350836753845,
"expert": 0.190626859664917
}
|
43,813
|
Write an advanced math AI in poe. Using modal.
https://creator.poe.com/docs/poe-protocol-specification https://creator.poe.com/docs/accessing-other-bots-on-poe https://creator.poe.com/docs/quick-start https://creator.poe.com/docs/setting-an-introduction-message https://creator.poe.com/docs/accessing-http-request-information https://creator.poe.com/docs/using-openai-function-calling
Example code:
from __future__ import annotations
from typing import AsyncIterable
from modal import Image, Stub, asgi_app
import fastapi_poe as fp
class GPT35TurboBot(fp.PoeBot):
async def get_response(
self, request: fp.QueryRequest
) -> AsyncIterable[fp.PartialResponse]:
async for msg in fp.stream_request(
request, "GPT-3.5-Turbo", request.access_key
):
yield msg
async def get_settings(self, setting: fp.SettingsRequest) -> fp.SettingsResponse:
return fp.SettingsResponse(server_bot_dependencies={"GPT-3.5-Turbo": 1})
REQUIREMENTS = ["fastapi-poe==0.0.36"]
image = Image.debian_slim().pip_install(*REQUIREMENTS)
stub = Stub("turbo-example-poe")
@stub.function(image=image)
@asgi_app()
def fastapi_app():
bot = GPT35TurboBot()
app = fp.make_app(bot, allow_without_key=True)
return app
|
a03f3096a1d233aa568e2b58b2ac22bf
|
{
"intermediate": 0.45005401968955994,
"beginner": 0.3862262964248657,
"expert": 0.16371965408325195
}
|
43,814
|
from ShazamAPI import Shazam
def shazam_recognize_song(audio_file_path):
with open(audio_file_path, 'rb') as file:
mp3_file_content_to_recognize = file.read()
shazam = Shazam(mp3_file_content_to_recognize)
recognize_generator = shazam.recognizeSong()
try:
for result in recognize_generator:
if result:
print(result) # Optionally keep this print or remove it after debugging
data = result[1] if isinstance(result, tuple) else result
print(data) # Optionally keep this print or remove it after debugging
return data
# return result # Return the first non-None result
except StopIteration:
print("Finished recognizing the song.")
return None # If the recognition finished without returning, return None
Traceback (most recent call last):
File "D:\Eurydice\Encompassing Data by discerning\Eury1.py", line 113, in <module>
set_id3_tags_mp3(audio_file_path, song_tags)
File "D:\Eurydice\Encompassing Data by discerning\Eury1.py", line 71, in set_id3_tags_mp3
audio_file.tag.artist = tags.get('artists')[0].get('name')
~~~~~~~~~~~~~~~~~~~^^^
TypeError: 'NoneType' object is not subscriptable
from my_shazam_utility import shazam_recognize_song
import acrcloud
import os
import eyed3
import requests
import json
import re
from applemusic_api import AppleMusicApi
from acrcloud.recognizer import ACRCloudRecognizer
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open('D:/Eurydice/Encompassing Data by discerning/config/config.json', 'r') as config_file:
config_data = json.load(config_file)
return config_data
dir(acrcloud)
config = load_config()
# Accessing the configuration values
ACR_HOST = config['ACR']['HOST']
ACR_ACCESS_KEY = config['ACR']['ACCESS_KEY']
ACR_ACCESS_SECRET = config['ACR']['ACCESS_SECRET']
recognizer = ACRCloudRecognizer({
'host': ACR_HOST,
'access_key': ACR_ACCESS_KEY,
'access_secret': ACR_ACCESS_SECRET,
'timeout': 10 # seconds
})
def get_user_choice():
# Display a header
print("=" * 50)
print("Welcome to the Song Recognition Service!")
print("=" * 50)
# Provide instructions and options
print("\nPlease select the recognition service you'd like to use:\n")
print(" 1: Youtube-ACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print("-" * 50)
# Input prompt
choice = input("Enter your choice (1 or 2) and press Enter: ")
# More flair to indicate processing/input received
print("\n" + "." * 25 + " Processing " + "." * 25 + "\n")
return choice
def recognize_song(audio_file_path):
buffer = open(audio_file_path, 'rb').read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict['metadata']['music'][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}")
return None
def set_id3_tags_mp3(audio_file_path, tags):
audio_file = eyed3.load(audio_file_path)
if not audio_file.tag:
audio_file.initTag()
audio_file.tag.artist = tags.get('artists')[0].get('name')
audio_file.tag.album = tags.get('album').get('name')
audio_file.tag.album_artist = tags.get('artists')[0].get('name')
audio_file.tag.title = tags.get('title')
release_date = tags.get('release_date')
if release_date and len(release_date) >= 4:
year_string = release_date[:4]
try:
year = int(year_string)
if hasattr(eyed3.id3.tag, 'Date'):
audio_file.tag.recording_date = eyed3.id3.tag.Date(year)
else:
audio_file.tag.setTextFrame("TDRC", year_string)
except ValueError:
print(f"Invalid date format in the tag: {release_date}")
audio_file.tag.genre = tags.get('genres')[0].get('name')
audio_file.tag.publisher = "KARTHIK"
audio_file.tag.copyright = tags.get('label', '')
audio_file.tag.comments.set(u"Explicit: Yes")
audio_file.tag.save(version=eyed3.id3.ID3_V2_3)
audio_file.tag.save()
if __name__ == "__main__":
user_choice = get_user_choice()
audio_file_path = 'D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3'
if user_choice == '1':
print("Using YoutubeACR.....")
song_tags = recognize_song(audio_file_path)
elif user_choice == '2':
print("Using Shazam.....")
song_tags = shazam_recognize_song(audio_file_path)
print(song_tags)
else:
print("Invalid choice. Exiting.")
exit()
if song_tags:
print(f'Song identified: {song_tags}')
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get('artists')[0].get('name')
song_title = song_tags.get('title')
safe_artist_name = re.sub(r'[/\:?"<>|]', '', artist_name)
safe_song_title = re.sub(r'[/\:?"<>|]', '', song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}")
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search('songs', f"{artist_name} - {song_title}")
if track_results:
track_id = track_results[0]['id']
album_artwork_url_template = track_results[0]['attributes']['artwork']['url']
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print("Song not found on Apple Music.")
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f"{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
else:
print('Could not identify the song.')
for shazam use different set_id3_tags_mp3 but with same audio_file_path
to fix issues for shazam
|
f57b04a63a1400d00455031cc1c8a1a2
|
{
"intermediate": 0.3174423575401306,
"beginner": 0.30237871408462524,
"expert": 0.38017889857292175
}
|
43,815
|
Make a fun 3d game, create textures, materials, everything from scratch. So I'd just copy paste the code, compile and upload to Steam. Thanks!
|
623ae345dc87ff394b15e94b3cc661aa
|
{
"intermediate": 0.4088859558105469,
"beginner": 0.31266382336616516,
"expert": 0.27845025062561035
}
|
43,816
|
def get_tags_song(self, webplayback: dict, lyrics_unsynced: str) -> dict:
flavor = next(
i for i in webplayback["assets"] if i["flavor"] == self.songs_flavor
)
metadata = flavor["metadata"]
tags = {
"album": metadata["playlistName"],
"album_artist": metadata["playlistArtistName"],
"album_id": int(metadata["playlistId"]),
"album_sort": metadata["sort-album"],
"artist": metadata["artistName"],
"artist_id": int(metadata["artistId"]),
"artist_sort": metadata["sort-artist"],
"comments": metadata.get("comments"),
"compilation": metadata["compilation"],
"composer": metadata.get("composerName"),
"composer_id": (
int(metadata.get("composerId")) if metadata.get("composerId") else KK
),
"composer_sort": metadata.get("sort-composer"),
"copyright": metadata.get("copyright"),
"date": (
self.sanitize_date(metadata["releaseDate"], self.template_date)
if metadata.get("releaseDate")
else None
),
"disc": metadata["discNumber"],
"disc_total": metadata["discCount"],
"gapless": metadata["gapless"],
"genre": metadata["genre"],
"genre_id": metadata["genreId"],
"media_type": 1,
"rating": metadata["explicit"],
"storefront": metadata["s"],
"title": metadata["itemName"],
"title_id": int(metadata["itemId"]),
"title_sort": metadata["sort-name"],
"track": metadata["trackNumber"],
"track_total": metadata["trackCount"],
"xid": metadata.get("xid"),
}
return tags
is it compatible to shazam
|
de809aef8116526b51668379333a786a
|
{
"intermediate": 0.30960121750831604,
"beginner": 0.38144832849502563,
"expert": 0.3089504837989807
}
|
43,817
|
explain what this large language trainer is and basics steps to implement it alongwith simple examples (with easy to understand explanations): ""Hugging Face's logo
Hugging Face
Search models, datasets, users...
TRL documentation
KTO Trainer
You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.8.1).
KTO Trainer
TRL supports the Kahneman-Tversky Optimization (KTO) Trainer for aligning language models with binary feedback data (e.g., upvote/downvote), as described in the paper by Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff, Dan Jurafsky, and Douwe Kiela. For a full example have a look at examples/scripts/kto.py.
Depending on how good your base model is, you may or may not need to do SFT before KTO. This is different from standard RLHF and DPO, which always require SFT.
Expected dataset format
The KTO trainer expects a very specific format for the dataset as it does not require pairwise preferences. Since the model will be trained to directly optimize examples that consist of a prompt, model completion, and a label to indicate whether the completion is “good” or “bad”, we expect a dataset with the following columns:
prompt
completion
label
for example:
Copied
kto_dataset_dict = {
"prompt": [
"Hey, hello",
"How are you",
"What is your name?",
"What is your name?",
"Which is the best programming language?",
"Which is the best programming language?",
"Which is the best programming language?",
],
"completion": [
"hi nice to meet you",
"leave me alone",
"I don't have a name",
"My name is Mary",
"Python",
"C++",
"Java",
],
"label": [
True,
False,
False,
True,
True,
False,
False,
],
}
where the prompt contains the context inputs, completion contains the corresponding responses and label contains the corresponding flag that indicates if the generated completion is desired (True) or undesired (False). A prompt can have multiple responses and this is reflected in the entries being repeated in the dictionary’s value arrays.
Expected model format
The KTO trainer expects a model of AutoModelForCausalLM, compared to PPO that expects AutoModelForCausalLMWithValueHead for the value function.
Using the KTOTrainer
For a detailed example have a look at the examples/scripts/kto.py script. At a high level we need to initialize the KTOTrainer with a model we wish to train and a reference ref_model which we will use to calculate the implicit rewards of the preferred and rejected response.
The beta refers to the hyperparameter of the implicit reward, and the dataset contains the 3 entries listed above. Note that the model and ref_model need to have the same architecture (ie decoder only or encoder-decoder).
The desirable_weight and undesirable_weight refer to the weights placed on the losses for desirable/positive and undesirable/negative examples. By default, they are both 1. However, if you have more of one or the other, then you should upweight the less common type such that the ratio of (desirable_weight number of positives) to (undesirable_weight number of negatives) is in the range 1:1 to 4:3.
Copied
training_args = KTOConfig(
beta=0.1,
desirable_weight=1.0,
undesirable_weight=1.0,
)
kto_trainer = KTOTrainer(
model,
model_ref,
args=training_args,
train_dataset=train_dataset,
tokenizer=tokenizer,
)
After this one can then call:
Copied
kto_trainer.train()
KTOTrainer
class trl.KTOTrainer
<
source
>
( model: Union = Noneref_model: Union = Noneargs: KTOConfig = Nonetrain_dataset: Optional = Noneeval_dataset: Union = Nonetokenizer: Optional = Nonedata_collator: Optional = Nonemodel_init: Optional = Nonecallbacks: Optional = Noneoptimizers: Tuple = (None, None)preprocess_logits_for_metrics: Optional = Nonepeft_config: Optional = Nonecompute_metrics: Optional = None )
Expand 14 parameters
Parameters
model (transformers.PreTrainedModel) — The model to train, preferably an AutoModelForSequenceClassification.
ref_model (PreTrainedModelWrapper) — Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized.
args (KTOConfig) — The arguments to use for training.
train_dataset (datasets.Dataset) — The dataset to use for training.
eval_dataset (datasets.Dataset) — The dataset to use for evaluation.
tokenizer (transformers.PreTrainedTokenizerBase) — The tokenizer to use for training. This argument is required if you want to use the default data collator.
data_collator (transformers.DataCollator, optional, defaults to None) — The data collator to use for training. If None is specified, the default data collator (DPODataCollatorWithPadding) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
model_init (Callable[[], transformers.PreTrainedModel]) — The model initializer to use for training. If None is specified, the default model initializer will be used.
callbacks (List[transformers.TrainerCallback]) — The callbacks to use for training.
optimizers (Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]) — The optimizer and scheduler to use for training.
preprocess_logits_for_metrics (Callable[[torch.Tensor, torch.Tensor], torch.Tensor]) — The function to use to preprocess the logits before computing the metrics.
peft_config (Dict, defaults to None) — The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
disable_dropout (bool, defaults to True) — Whether or not to disable dropouts in model and ref_model.
compute_metrics (Callable[[EvalPrediction], Dict], optional) — The function to use to compute the metrics. Must take a EvalPrediction and return a dictionary string to metric values.
Initialize KTOTrainer.
build_tokenized_answer
<
source
>
( promptanswer )
Llama tokenizer does not satisfy enc(a + b) = enc(a) + enc(b). It does ensure enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]. Reference: https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
compute_reference_log_probs
<
source
>
( padded_batch: Dict )
Computes log probabilities of the reference model for a single padded batch of a KTO specific dataset.
evaluation_loop
<
source
>
( dataloader: DataLoaderdescription: strprediction_loss_only: Optional = Noneignore_keys: Optional = Nonemetric_key_prefix: str = 'eval' )
Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict().
Works both with or without labels.
get_KL_dataset
<
source
>
( batch )
Creates mismatched pairs of prompts and completions for the KL dataset.
get_batch_logps
<
source
>
( logits: FloatTensorlabels: LongTensoraverage_log_prob: bool = Falselabel_pad_token_id: int = -100is_encoder_decoder: bool = False )
Compute the log probabilities of the given labels under the given logits.
get_batch_loss_metrics
<
source
>
( modelbatch: Dicttrain_eval: Literal = 'train' )
Compute the KTO loss and other metrics for the given batch of inputs for train or test.
get_batch_samples
<
source
>
( modelbatch: Dict )
Generate samples from the model and reference model for the given batch of inputs.
get_eval_dataloader
<
source
>
( eval_dataset: Optional = None )
Parameters
eval_dataset (torch.utils.data.Dataset, optional) — If provided, will override self.eval_dataset. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed. It must implement __len__.
Returns the evaluation ~torch.utils.data.DataLoader.
Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute ref_log_probs.
get_train_dataloader
<
source
>
( )
Returns the training ~torch.utils.data.DataLoader.
Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute ref_log_probs.
kto_loss
<
source
>
( policy_chosen_logps: FloatTensorpolicy_rejected_logps: FloatTensorpolicy_KL_logps: FloatTensorreference_chosen_logps: FloatTensorreference_rejected_logps: FloatTensorreference_KL_logps: FloatTensor ) → A tuple of four tensors
Returns
A tuple of four tensors
(losses, chosen_rewards, rejected_rewards, KL). The losses tensor contains the KTO loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. The KL tensor contains the detached KL divergence estimate between the policy and reference models.
Compute the KTO loss for a batch of policy and reference model log probabilities.
log
<
source
>
( logs: Dict )
Parameters
logs (Dict[str, float]) — The values to log.
Log logs on the various objects watching training, including stored metrics.
tokenize_row
<
source
>
( featuremodel: Union = Noneprefix = '' )
Tokenize a single row from a KTO specific dataset.
At this stage, we don’t convert to PyTorch tensors yet; we just handle the truncation in case the prompt + completion responses is/are too long. First we truncate the prompt; if we’re still too long, we truncate the completion.
We also create the labels for the completion responses, which are of length equal to the sum of the length of the prompt and the completion response, with label_pad_token_id for the prompt tokens.
KTOConfig
class trl.KTOConfig
<
source
>
( output_dir: stroverwrite_output_dir: bool = Falsedo_train: bool = Falsedo_eval: bool = Falsedo_predict: bool = Falseevaluation_strategy: Union = 'no'prediction_loss_only: bool = Falseper_device_train_batch_size: int = 8per_device_eval_batch_size: int = 8per_gpu_train_batch_size: Optional = Noneper_gpu_eval_batch_size: Optional = Nonegradient_accumulation_steps: int = 1eval_accumulation_steps: Optional = Noneeval_delay: Optional = 0learning_rate: float = 5e-05weight_decay: float = 0.0adam_beta1: float = 0.9adam_beta2: float = 0.999adam_epsilon: float = 1e-08max_grad_norm: float = 1.0num_train_epochs: float = 3.0max_steps: int = -1lr_scheduler_type: Union = 'linear'lr_scheduler_kwargs: Optional = <factory>warmup_ratio: float = 0.0warmup_steps: int = 0log_level: Optional = 'passive'log_level_replica: Optional = 'warning'log_on_each_node: bool = Truelogging_dir: Optional = Nonelogging_strategy: Union = 'steps'logging_first_step: bool = Falselogging_steps: float = 500logging_nan_inf_filter: bool = Truesave_strategy: Union = 'steps'save_steps: float = 500save_total_limit: Optional = Nonesave_safetensors: Optional = Truesave_on_each_node: bool = Falsesave_only_model: bool = Falseno_cuda: bool = Falseuse_cpu: bool = Falseuse_mps_device: bool = Falseseed: int = 42data_seed: Optional = Nonejit_mode_eval: bool = Falseuse_ipex: bool = Falsebf16: bool = Falsefp16: bool = Falsefp16_opt_level: str = 'O1'half_precision_backend: str = 'auto'bf16_full_eval: bool = Falsefp16_full_eval: bool = Falsetf32: Optional = Nonelocal_rank: int = -1ddp_backend: Optional = Nonetpu_num_cores: Optional = Nonetpu_metrics_debug: bool = Falsedebug: Union = ''dataloader_drop_last: bool = Falseeval_steps: Optional = Nonedataloader_num_workers: int = 0dataloader_prefetch_factor: Optional = Nonepast_index: int = -1run_name: Optional = Nonedisable_tqdm: Optional = Noneremove_unused_columns: Optional = Truelabel_names: Optional = Noneload_best_model_at_end: Optional = Falsemetric_for_best_model: Optional = Nonegreater_is_better: Optional = Noneignore_data_skip: bool = Falsefsdp: Union = ''fsdp_min_num_params: int = 0fsdp_config: Union = Nonefsdp_transformer_layer_cls_to_wrap: Optional = Noneaccelerator_config: Optional = Nonedeepspeed: Optional = Nonelabel_smoothing_factor: float = 0.0optim: Union = 'adamw_torch'optim_args: Optional = Noneadafactor: bool = Falsegroup_by_length: bool = Falselength_column_name: Optional = 'length'report_to: Optional = Noneddp_find_unused_parameters: Optional = Noneddp_bucket_cap_mb: Optional = Noneddp_broadcast_buffers: Optional = Nonedataloader_pin_memory: bool = Truedataloader_persistent_workers: bool = Falseskip_memory_metrics: bool = Trueuse_legacy_prediction_loop: bool = Falsepush_to_hub: bool = Falseresume_from_checkpoint: Optional = Nonehub_model_id: Optional = Nonehub_strategy: Union = 'every_save'hub_token: Optional = Nonehub_private_repo: bool = Falsehub_always_push: bool = Falsegradient_checkpointing: bool = Falsegradient_checkpointing_kwargs: Optional = Noneinclude_inputs_for_metrics: bool = Falsefp16_backend: str = 'auto'push_to_hub_model_id: Optional = Nonepush_to_hub_organization: Optional = Nonepush_to_hub_token: Optional = Nonemp_parameters: str = ''auto_find_batch_size: bool = Falsefull_determinism: bool = Falsetorchdynamo: Optional = Noneray_scope: Optional = 'last'ddp_timeout: Optional = 1800torch_compile: bool = Falsetorch_compile_backend: Optional = Nonetorch_compile_mode: Optional = Nonedispatch_batches: Optional = Nonesplit_batches: Optional = Noneinclude_tokens_per_second: Optional = Falseinclude_num_input_tokens_seen: Optional = Falseneftune_noise_alpha: Optional = Noneoptim_target_modules: Union = Nonemax_length: Optional = Nonemax_prompt_length: Optional = Nonemax_completion_length: Optional = Nonebeta: float = 0.1desirable_weight: Optional = 1.0undesirable_weight: Optional = 1.0label_pad_token_id: int = -100padding_value: int = Nonetruncation_mode: str = 'keep_end'generate_during_eval: bool = Falseis_encoder_decoder: Optional = Noneprecompute_ref_log_probs: bool = Falsemodel_init_kwargs: Optional = Noneref_model_init_kwargs: Optional = None )
Expand 12 parameters
Parameters
max_length (int, optional, defaults to None) — The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator.
max_prompt_length (int, optional, defaults to None) — The maximum length of the prompt. This argument is required if you want to use the default data collator.
max_completion_length (int, optional, defaults to None) — The maximum length of the target. This argument is required if you want to use the default data collator and your model is an encoder-decoder.
beta (float, defaults to 0.1) — The beta factor in KTO loss. Higher beta means less divergence from the initial policy.
desirable_weight (float, optional, defaults to 1.0) — The desirable losses are weighed by this factor to counter unequal number of desirable and undesirable paris.
undesirable_weight (float, optional, defaults to 1.0) — The undesirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs.
label_pad_token_id (int, defaults to -100) — The label pad token id. This argument is required if you want to use the default data collator.
padding_value (int, defaults to 0) — The padding value if it is different to the tokenizer’s pad_token_id.
truncation_mode (str, defaults to keep_end) — The truncation mode to use, either keep_end or keep_start. This argument is required if you want to use the default data collator.
generate_during_eval (bool, defaults to False) — Whether to sample and log generations during evaluation step.
is_encoder_decoder (Optional[bool], optional, defaults to None) — If no model is provided, we need to know if the model_init returns an encoder-decoder.
precompute_ref_log_probs (bool, defaults to False) — Flag to precompute reference model log probabilities for training and evaluation datasets. This is useful if you want to train without the reference model and reduce the total GPU memory needed. model_init_kwargs — (Optional[Dict], optional): Dict of Optional kwargs to pass when instantiating the model from a string. ref_model_init_kwargs — (Optional[Dict], optional): Dict of Optional kwargs to pass when instantiating the ref model from a string.
KTOConfig collects all training arguments related to the KTOTrainer class.
Using HfArgumentParser we can turn this class into argparse arguments that can be specified on the command line.
←
DPO Trainer
CPO Trainer
→""
|
7e0beb80548b00d8b029561dc5d39d6e
|
{
"intermediate": 0.34626060724258423,
"beginner": 0.3510209918022156,
"expert": 0.3027184307575226
}
|
43,818
|
Enhance this to allow to have dots on all the width, not only 3 dots : .wp-block-separator.is-style-dots:before {
color: currentColor;
content: "···";
font-family: serif;
font-size: 1.5em;
letter-spacing: 0em;
padding-left: 2em;
}
.wp-block-separator.is-style-dots {
border-top: none;
}
.wp-block-separator.is-style-dots {
background: none !important;
border: none;
height: auto;
line-height: 1;
text-align: center;
}
|
3db5ca86eb64834ef4f528e9511fbd51
|
{
"intermediate": 0.38087475299835205,
"beginner": 0.23412726819515228,
"expert": 0.3849979341030121
}
|
43,819
|
when I start a lxc contrainer in pve,why the device file "---------- 1 root root 0 3月 24 11:21 nvidia0" like that?
|
0c85cbb1f06ff7d5cfcf1f092830c191
|
{
"intermediate": 0.47929611802101135,
"beginner": 0.18014807999134064,
"expert": 0.3405557870864868
}
|
43,820
|
in the debian system,when the kernel upgraded to a new version,the nvidia kernel module could not be loaded, how to do ?
|
97196ca09140c5d40020b3d9cd85aa70
|
{
"intermediate": 0.3541027903556824,
"beginner": 0.24558067321777344,
"expert": 0.4003165364265442
}
|
43,821
|
(roop-unleashed-3.5.0) raul@RRs-iMac roop-unleashed-3.5.0 % brew install ffmpeg
zsh: command not found: brew
|
d36f86261e8558d7b8145be4f9ceb429
|
{
"intermediate": 0.38249924778938293,
"beginner": 0.28698793053627014,
"expert": 0.3305128216743469
}
|
43,822
|
Write a smart tic tac-toe AI, In Python with only just 544 lines of codes.
|
b53275e9bfa75692e23ba60e3358025d
|
{
"intermediate": 0.0985703244805336,
"beginner": 0.07729382067918777,
"expert": 0.8241358995437622
}
|
43,823
|
Write a smart tic tac-toe AI, In Python with only just 544 lines of codes.
|
ac6fdb686fdf9b96cdf8fa239a40cce7
|
{
"intermediate": 0.0985703244805336,
"beginner": 0.07729382067918777,
"expert": 0.8241358995437622
}
|
43,824
|
def get_tags_song(self, webplayback: dict, lyrics_unsynced: str) -> dict:
flavor = next(
i for i in webplayback["assets"] if i["flavor"] == self.songs_flavor
)
metadata = flavor["metadata"]
tags = {
"album": metadata["playlistName"],
"album_artist": metadata["playlistArtistName"],
"album_id": int(metadata["playlistId"]),
"album_sort": metadata["sort-album"],
"artist": metadata["artistName"],
"artist_id": int(metadata["artistId"]),
"artist_sort": metadata["sort-artist"],
"comments": metadata.get("comments"),
"compilation": metadata["compilation"],
"composer": metadata.get("composerName"),
"composer_id": (
int(metadata.get("composerId")) if metadata.get("composerId") else KK
),
"composer_sort": metadata.get("sort-composer"),
"copyright": metadata.get("copyright"),
"date": (
self.sanitize_date(metadata["releaseDate"], self.template_date)
if metadata.get("releaseDate")
else None
),
"disc": metadata["discNumber"],
"disc_total": metadata["discCount"],
"gapless": metadata["gapless"],
"genre": metadata["genre"],
"genre_id": metadata["genreId"],
"media_type": 1,
"rating": metadata["explicit"],
"storefront": metadata["s"],
"title": metadata["itemName"],
"title_id": int(metadata["itemId"]),
"title_sort": metadata["sort-name"],
"track": metadata["trackNumber"],
"track_total": metadata["trackCount"],
"xid": metadata.get("xid"),
}
return tags
implement this and check if(artist name aand titlr) and tag the audio local file
after recognised by the shazam
|
a0c1f1d1d97f32af5687f03e44f8501c
|
{
"intermediate": 0.27201876044273376,
"beginner": 0.47656968235969543,
"expert": 0.2514115273952484
}
|
43,825
|
hey
|
367696ea5b7fcff8fa6975a28529647f
|
{
"intermediate": 0.33180856704711914,
"beginner": 0.2916048467159271,
"expert": 0.3765866458415985
}
|
43,826
|
Here is my query - Right now it gets me 7981 records instead of 8244 records which is basically sale. After joiniing it comes down to 7981. I used the Left Outer Join and Full Join too but I am still getting 7981 records instead of 8244. Here is what My understanding is, because I am saying in the where clause to get all the record between Nov 1 and Nov 30, and I am also using where it say opn_dt between start and end date. Since I am using AND statement, the output looks into both conditions and get me lower records. One of the reason is, if the acct open in sales table or table somwehere in november then it gets me the data from the table b. but if the table b showing the same customer number in some next months which does not qualify the condition and therefore exclude the records and showing 7981. I would like to know from you - how do I ensure to get all 8244 records as well as the opn_dt should also match between start and end date and if they do not - then still provide the full data regardless of data is available in table b for the same month or not.
Here is my query fix this in hive sql:
WITH Sales_Performance AS (
SELECT DISTINCT
CAST(a.acct_num AS BIGINT) AS acct_num,
CAST(a.prim_own_cif_id AS BIGINT) AS cust_cid,
SUBSTR(TRIM(a.opn_dt), 1, 7) AS year_month,
a.opn_dt AS open_date,
a.type AS products,
CASE
WHEN d.immigration_cat_cd IN ('000','999','C1','FC1','FC2','FC3','EN2','PV1','PV2','SW1','SW2','SW3','SE2','STP','C2','NV5') THEN 'PR'
WHEN d.immigration_cat_cd IN ('FW','FW0') THEN 'FW'
WHEN d.immigration_cat_cd IN ('S','S00') THEN 'IS'
ELSE 'Regular_Customers'
END AS MCB_Category
FROM table_a a
LEFT JOIN (
SELECT
DISTINCT CAST(party_id AS BIGINT) AS party_id,
immigration_cat_cd,
start_date,
date_sub(coalesce(LEAD(start_date) OVER (PARTITION BY party_id ORDER BY start_date ), current_date),1) AS end_date
FROM
(SELECT
party_id,
immigration_cat_cd,
businesseffectivedate AS start_date,
RANK() OVER (PARTITION BY party_id, immigration_cat_cd ORDER BY businesseffectivedate) AS rank
FROM
table_b
) d
WHERE
rank = 1
) d ON lpad(a.prim_own_cif_id,15,'0') = lpad(d.party_id,15,'0')
WHERE
trim(a.channel) NOT IN ('Branch','CCC')
AND trim(a.type) NOT IN ('US$','GTSP')
AND a.opn_dt > '2023-10-31'
AND a.opn_dt < '2023-12-01'
AND (d.party_id IS NULL OR (a.opn_dt BETWEEN d.start_date AND d.end_date))
)
SELECT * FROM Sales_Performance;
|
cfc2b8cfbd1f45bdfd091e007011c29e
|
{
"intermediate": 0.39254453778266907,
"beginner": 0.46297594904899597,
"expert": 0.14447946846485138
}
|
43,827
|
基于matlab编写一个求解DTFT of the discrete time sequence的代码
|
526b671664937a5e0c1851282ac074c7
|
{
"intermediate": 0.2938573956489563,
"beginner": 0.2518432140350342,
"expert": 0.4542994797229767
}
|
43,828
|
after identification from shzam
shszam only returns artist_name, Title of the song
so help me to write a program to search artist_name and title of the song in spotify
provided Client secret, Client ID,
Website
Example.com
Redirect URIs
EurydiceKSSK878.com
shazam identifcation code:
from ShazamAPI import Shazam
def shazam_recognize_song(audio_file_path):
with open(audio_file_path, 'rb') as file:
mp3_file_content_to_recognize = file.read()
shazam = Shazam(mp3_file_content_to_recognize)
recognize_generator = shazam.recognizeSong()
try:
for result in recognize_generator:
if result:
# print(result) # Optionally keep this print or remove it after debugging
data = result[1] if isinstance(result, tuple) else result
print(data) # Optionally keep this print or remove it after debugging
return data
# return result # Return the first non-None result
except StopIteration:
print("Finished recognizing the song.")
return None # If the recognition finished without returning, return None
|
20b4ca6a3900e5401a6f8dde842460e1
|
{
"intermediate": 0.5372443795204163,
"beginner": 0.2666511535644531,
"expert": 0.1961044818162918
}
|
43,829
|
i have and ai model that gives me signal for crypto currencies
how can i perform a backtest for it in python ?
|
de4731495d244af18ebe7db9d61b206c
|
{
"intermediate": 0.5220097303390503,
"beginner": 0.07123144716024399,
"expert": 0.40675878524780273
}
|
43,830
|
In this javascript why are the markers not being removed from the map by 'if (marker) {
marker.setMap(null);
marker = null;
}
' - 'let map; // Declare map globally
let streetLatitude;
let streetLongitude;
let marker; // Define marker globally to make it accessible across functions
let totalScore = 0; // Initialize total points variable
let possibleScore = 0; // Initialize total points variable
let imageIndex = 0; // Initialize image index
let PictureURL; // Define PictureURL at a higher scope level
let Description;
let clickListener; // Store the click listener reference
let roundScores = [];
let polylines = [];
function fetchStreetDetails(callback) {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
const entryCount = jsonData.Features.length;
// Check if there are more images to display
if (imageIndex >= entryCount) {
console.log("No more images to display!");
// Display "Game Over" message
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = ''; // Clear the previous message
const finalScores = `Total Score: ${totalScore} points out of a possible ${possibleScore}<br><br>`;
const scoreLine = createScoreLine(totalScore, possibleScore);
const paintingDiv = document.getElementById("painting");
paintingDiv.style.backgroundColor = "#fff"; // Set background color directly
paintingDiv.innerHTML = finalScores; // Update content with innerHTML
paintingDiv.appendChild(scoreLine);
// Add individual round scores
resultsDiv.innerHTML += "<br><br><b>Painting Scores:</b><br><br>";
roundScores.forEach((roundScore, index) => {
resultsDiv.innerHTML += `Round ${index + 1}: ${roundScore} points<br>`;
});
//remove painting info
const infoDiv = document.getElementById("info");
if (infoDiv) {
infoDiv.remove();
} else {
console.error("Div element with ID 'info' not found!");
}
// Create the "Start Again" button
const startAgainButton = document.createElement("button");
startAgainButton.id = "startAgainButton";
startAgainButton.textContent = "Start Again";
// Add appropriate styling for the button
startAgainButton.style.backgroundColor = "#4CAF50"; // Green
startAgainButton.style.color = "white";
startAgainButton.style.padding = "10px 20px";
startAgainButton.style.border = "none";
startAgainButton.style.borderRadius = "5px";
startAgainButton.style.cursor = "pointer";
// Append the button to the appropriate container
resultsDiv.appendChild(startAgainButton);
// Add click event listener to the button
startAgainButton.addEventListener("click", () => {
// Reset variables
totalScore = 0;
possibleScore = 0;
imageIndex = 0;
roundScores = [];
if (marker) {
marker.setMap(null);
marker = null;
}
polylines.forEach(polyline => polyline.setMap(null));
polylines = []; // Reset the array
// Reset map center and zoom
map.setCenter(new google.maps.LatLng(21.382325, -8.170154652));
map.setZoom(3);
// Re-fetch the first image and set up the first round
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
const message = "Where do you think this scene is?";
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Add click listener back to the map for the first round
clickListener = map.addListener("click", (event) => {
// ... Handle map click and create submit button ...
});
});
});
return;
}
const streetDetails = jsonData.Features[imageIndex]; // Get image data based on index
// Extract PictureURL at a higher scope level
PictureURL = streetDetails.PictureURL;
Description = streetDetails.Description;
// Extract details
const FeatureID = streetDetails.FeatureID;
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
const streetHeading = streetDetails.StreetHeading;
const streetPitch = streetDetails.StreetPitch;
const streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
console.log("FeatureID: " + FeatureID);
console.log("PictureURL: " + PictureURL);
console.log("Description: " + Description);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
// Update numberoffeeds div
const numberoffeedsElement = document.getElementById("results");
numberoffeedsElement.textContent = `This is a ${entryCount} round game.\nClick on the map where you think this scene is.`;
callback(FeatureID);
})
.catch((error) => console.error("Error fetching data: ", error));
}
//visualize and animate finalscore
function createScoreLine(
totalScore,
possibleScore,
color = "#ff0000",
backgroundColor = "#107896",
animationDuration = 1000
) {
// milliseconds
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set canvas dimensions based on your needs
canvas.width = 200;
canvas.height = 30;
let currentPercentage = 0; // Track current percentage for animation
const animateFill = () => {
if (currentPercentage >= (totalScore / possibleScore) * 100) {
return; // Stop animation if reached target percentage
}
currentPercentage += 1; // Increment current percentage for animation
// Clear the canvas before each redraw to avoid stacking lines
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set background color
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set fill color for the line
ctx.fillStyle = color;
// Adjust the rectangle width based on current percentage
ctx.fillRect(0, 0, canvas.width * (currentPercentage / 100), canvas.height);
// Request another animation frame for smooth animation
requestAnimationFrame(animateFill);
};
animateFill(); // Start the animation
return canvas;
}
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "transit",
stylers: [
{
visibility: "off",
},
],
},
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Add a click event listener to the map
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng; // Get the latitude and longitude of the click
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map, // Set the map where the marker will be displayed
draggable: true, // Set draggable to true
});
// (Optional) Add additional customization to the marker here,
// such as setting an icon or info window
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(map, clickLocation);
});
}
//nextbutton
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Function to create and add the button
function createSubmitButton(map, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
if (!buttonsDiv) {
console.error("Element with ID 'buttons' not found!");
return;
}
const submitButton = document.createElement("button");
submitButton.textContent = "Submit"; // Customize button text
submitButton.classList.add("button"); // Add class 'button'
submitButton.addEventListener("click", () => {
// Handle button click event here (e.g., send clickLocation data)
console.log(
"Button clicked! Latitude:",
clickLocation.lat(),
"Longitude:",
clickLocation.lng()
);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance between marker and StreetPoints
const distanceInMeters =
google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(streetLatitude, streetLongitude),
markerPosition
);
const roundedDistanceInMeters = Math.floor(distanceInMeters); // Round down to the nearest meter
console.log(
"Distance to StreetPoints: " + roundedDistanceInMeters + " meters"
);
// Adjust points based on distance
let score = 5000 - roundedDistanceInMeters;
if (score < 0) {
score = 0;
}
totalScore += score; // Add current points to total
possibleScore += 5000;
roundScores.push(score);
const message = "You scored " + score + " points";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Create a polyline between marker and StreetPoints
const lineCoordinates = [
{ lat: streetLatitude, lng: streetLongitude },
{ lat: markerPosition.lat(), lng: markerPosition.lng() },
];
const polyline = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
});
// Set the polyline on the map
polylines.push(polyline);
polyline.setMap(map);
marker.setDraggable(false);
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend({ lat: streetLatitude, lng: streetLongitude });
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
});
buttonsDiv.appendChild(submitButton);
}
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
});
// Function to update the image and description
function updateImage(FeatureID, PictureURL) {
const infoDiv = document.getElementById("info");
const infoHTML = Description;
infoDiv.innerHTML = infoHTML;
const paintingDiv = document.getElementById("painting");
const imageHTML =
'<img src="' +
PictureURL +
'" onclick="this.requestFullscreen()" style="width: 90%;" class="center">';
console.log("Image URL:", imageHTML); // Log the image URL to the console
paintingDiv.innerHTML = imageHTML;
}
// Add click event for the ‘Next’ button
nextButton.addEventListener("click", () => {
// Increment the image index to fetch the next image
imageIndex++;
// Fetch the next image from the JSON file and update the painting div
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
map.setCenter(newLatLng);
map.setZoom(3);
const message = "Where do you think this scene is?";
// Add click event listener back to the map
google.maps.event.clearListeners(map, "click"); // Clear existing click listeners
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng;
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true,
});
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
createSubmitButton(map, clickLocation);
});
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
});
const buttonsDiv = document.getElementById("buttons");
buttonsDiv.removeChild(nextButton);
});'
|
87e7c2c6834341aabb31f0e2e6e1a4ba
|
{
"intermediate": 0.30126747488975525,
"beginner": 0.5242569446563721,
"expert": 0.17447558045387268
}
|
43,831
|
i have hourly historical data of some cryptocurrencies ,
i also have a csv files of dates and name of crypto that i want to check...
i want to determine for each specefic date, by looking to its next 2 day hourly data(which includes 48 data),that price is increased 3% first,or decreased 5% first...
give me proper python code ...
|
11a3d6e5e3468a919014bb1d82c8621e
|
{
"intermediate": 0.41846010088920593,
"beginner": 0.46568453311920166,
"expert": 0.11585532873868942
}
|
43,832
|
Deep Sea Adventure 1
Submit solution
All submissions
Best submissions
Points:65 (partial)
Time limit:1.0s
Memory limit:128M
Author:
admin
Problem type
Allowed languages
C
Problem Statement
Percy begins his dive at the surface with a limited amount of oxygen supply. There are several underwater stations situated at various depths, each containing air tanks to refill your oxygen supply. However, it takes time to refill oxygen. The objective is to reach the underwater cave without running out of oxygen and minimizing the time that is spent at the stations.
Percy starts a depth of
and has an initial oxygen supply of
amount. Every unit depth that he descends, he consumes
unit of oxygen supply. The final depth that he needs to reach is
.
To help refill oxygen, there are
stations present at various depths. Each station fills Percy's oxygen tank with exactly
units of oxygen. There is no way to only partially refill. The
th station is present at a depth
i and takes
i time to refill the
units of oxygen. You can refill oxygen from a station only once, that too only if you have reached its depth. Also, no two stations are present at the same depth.
You have to help Percy figure out if it is possible for him to reach the underwater cave without running out of oxygen and the minimum total time that he has to spend refilling in order to do so.
Input Format
The first line of input contains integers
,
,
and
denoting the number of stations, initial oxygen supply, the final depth and the amount of oxygen refilled at each station respectively.
The second line contains
integers representing the depths
i of each station from the top.
The third line contains
integers representing the refilling times
i of each station.
Constraints
i
i
All
i are distinct
Output Format
If it is possible for Percy to reach the depth
, print the minimum total time that he has to spend at the stations.
If it is not possible for him to reach depth
, print
followed by the maximum depth that he can reach before his oxygen level goes to
.
Sample Test Case 1:
Input:
Copy
3 10 20 6
7 2 14
3 8 4
Output:
Copy
7
Explanation:
Percy has to reach a depth of
. He cannot reach it with the initial oxygen supply he has. Therefore, he refills oxygen at the stations located at depths
and
, gaining
units of oxygen at each station, with a minimal total refilling time of
to be able to reach the depth of
.
Sample Test Case 2:
Input:
Copy
2 7 15 4
7 11
3 5
Output:
Copy
8
Explanation:
Percy has to reach a depth of
. He cannot reach it with the initial oxygen supply he has. Therefore, he refills oxygen at the stations located at depths
and
, gaining
units of oxygen at each station, with a minimal total refilling time of
to be able to reach the depth of
.
Sample Test Case 3:
Input:
Copy
4 12 22 3
18 8 19 16
1 2 3 4
Output:
Copy
-1 15
Explanation:
Percy has to reach a depth of
. He cannot reach it with the initial oxygen supply he has. He refills oxygen at the station located at depth
and is able to reach a depth of
. But he runs out of oxygen at this point and cannot go any further.
do this using heaps. give code in c and explain the logic too
|
19c66ef39b17027d386e70b0ead1a178
|
{
"intermediate": 0.19179527461528778,
"beginner": 0.5557950139045715,
"expert": 0.2524096667766571
}
|
43,833
|
Write a smart tic tac-toe AI, In Python.
|
981464625a8ef4fdc3374b90ad974da4
|
{
"intermediate": 0.09193216264247894,
"beginner": 0.09000041335821152,
"expert": 0.8180674314498901
}
|
43,834
|
Write a python code that solves complex expressions with steps, with only just 200+ lines of codes.
|
1cb3819947e42130138f5a2de3992f29
|
{
"intermediate": 0.2781447470188141,
"beginner": 0.1725824922323227,
"expert": 0.5492727756500244
}
|
43,835
|
Write a python code that solves complex expressions with steps, with only just 200+ lines of codes.
|
4f3728ae070283254a5b88319653afac
|
{
"intermediate": 0.2781447470188141,
"beginner": 0.1725824922323227,
"expert": 0.5492727756500244
}
|
43,836
|
I am trying to create a prompt for a llm that generates synthetic data based off the following information: ""
The KTO trainer expects a very specific format for the dataset as it does not require pairwise preferences. Since the model will be trained to directly optimize examples that consist of a prompt, model completion, and a label to indicate whether the completion is “good” or “bad”, we expect a dataset with the following columns:
Expected dataset format:
prompt
completion
label
for example:
kto_dataset_dict = {
"prompt": [
"Hey, hello",
"How are you",
"What is your name?",
"What is your name?",
"Which is the best programming language?",
"Which is the best programming language?",
"Which is the best programming language?",
],
"completion": [
"hi nice to meet you",
"leave me alone",
"I don't have a name",
"My name is Mary",
"Python",
"C++",
"Java",
],
"label": [
True,
False,
False,
True,
True,
False,
False,
],
}""
|
f83049e74407ce91c58f177f742544c8
|
{
"intermediate": 0.22829334437847137,
"beginner": 0.48256051540374756,
"expert": 0.2891460657119751
}
|
43,837
|
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int *arr;
int data;
int depth;
int time;
} node;
void heapify(int *heap, int size, int i)
{//printf("inside heapify func\n");
int minimum = i;
int l=(2*i)+1;
int r=(2*i)+2;
if (l < size && heap[l] < heap[minimum])
minimum = l;
if (r < size && heap[r] < heap[minimum])
minimum = r;
if (minimum != i)
{
int temp = heap[minimum];
heap[minimum] = heap[i];
heap[i] = temp;
heapify(heap, size, minimum);
}
}
int compare(const void *a, const void *b)
{//printf("inside compare func\n");
node *stationA = (node *)a;
node *stationB = (node *)b;
return stationA->depth - stationB->depth;
}
int deleteMin(int *heap, int *size)
{
if (*size == 0)
return -1;
int min = heap[0];
heap[0] = heap[--(*size)];
heapify(heap, *size, 0);
return min;
}
void insert(int heap[], int *size, int value)
{//printf("inside insert func\n");
int current = (*size)++;
heap[current] = value;
while (current!=0)
{
int parent=(current-1)/2;
if (heap[current]<heap[parent])
{
int temp=heap[current];
heap[current]=heap[parent];
heap[parent]=temp;
current=parent;
}
else
{
break;
}
}
}
void func(node stations[], int num_stations, int ini_oxygen, int final_depth, int additional_oxygen)
{//printf("inside func func\n");
qsort(stations, num_stations, sizeof(node), compare);
int heap[num_stations];
int heap_size = 0;
int current_time = 0;
int max_depth = ini_oxygen;
for (int i = 0; i < num_stations; ++i)
{
while (max_depth < stations[i].depth && heap_size > 0)
{
int refill_time = deleteMin(heap, &heap_size);
current_time = current_time+refill_time;
max_depth =max_depth+ additional_oxygen;
}
if (max_depth < stations[i].depth)
break;
insert(heap, &heap_size, stations[i].time);
if (max_depth >= final_depth)
{
printf("%d\n", current_time);
return;
}
}
while (heap_size > 0 && max_depth < final_depth)
{//printf("inside inside inside while loop\n");
int refill_time = deleteMin(heap, &heap_size);
current_time = current_time + refill_time;
max_depth = max_depth + additional_oxygen;
}
if (max_depth >= final_depth)
{
printf("%d", current_time);
}
else
{
printf("-1 %d", max_depth);
}
}
int main()
{
int num_stations, ini_oxygen, final_depth, additional_oxygen;
scanf("%d %d %d %d", &num_stations, &ini_oxygen, &final_depth, &additional_oxygen);
node stations[num_stations];
for (int i = 0; i < num_stations; ++i)
{
scanf("%d", &stations[i].depth);
}
for (int i = 0; i < num_stations; ++i)
{
scanf("%d", &stations[i].time);
}
//printf("calling func\n");
func(stations, num_stations, ini_oxygen, final_depth, additional_oxygen);
return 0;
}
change the function func
|
d5b05983f74ea62985b599b770b5c2bc
|
{
"intermediate": 0.3350427448749542,
"beginner": 0.5050729513168335,
"expert": 0.15988434851169586
}
|
43,838
|
Аватар Пользователя
@import url('https://fonts.googleapis.com/css?family=Material+Icons|Roboto+Condensed:300,400,700|Roboto:300,400,500,500i,700,700i,900,900i&subset=cyrillic');
article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}
html{position:relative;margin-top:0;min-height:100%}
img,object,iframe,audio,video,table,embed{max-width:100%}
.myWinCont img{max-width:initial;}
.myWinCont input.commFl { width: auto; }
*{-webkit-box-sizing:border-box;box-sizing:border-box}
.wysibb *,form#uf-register *:not(.customCheckbox):not(.customRadio):not(.captcha-answer),a.login-with i,ul.shop-tabs.with-clear li,ul.shop-tabs.with-clear{-webkit-box-sizing:content-box;box-sizing:content-box}
body{margin:0;font-size:14px;line-height:1.5;font-family:'Roboto',serif;color:#70718e}
body.tmpl_body{background-color:#f2f2f7}
table{font-size:100%}
.main_wrapper{min-height:calc(100vh - 200px)}
img,form{border:0;margin:0}
a,input,button:focus{outline:0}
a{color:#fda649;text-decoration:none;-webkit-tap-highlight-color:transparent}
a:hover,#header .user-btns a:hover{text-decoration:underline}
.eTitle a:hover{color:#fda649}
a:active,#header .user-btns a:active,.eTitle a:active{color:#fda649;text-decoration:none}
#header .user-btns a,#user-box{color:#fff}
#user-box{padding:50px 15px 0}
.i_menu{font-size:54px;-moz-user-select:none;-khtml-user-select:none;user-select:none}
h1,h2,h3,h4,h5,h6{font-weight:normal;margin:5px 0;padding:0;text-transform:uppercase;font-family:'Roboto Condensed'}
h1{font-size:28px}
h2{font-size:24px}
h3{font-size:19px}
h4{font-size:17px}
h5{font-size:15px}
h6{font-size:13px}
ul{list-style:square}
hr{clear:both;border:0;padding:10px 0 0;margin:0 0 10px}
.x-scroll{overflow-x:auto}
.x-scroll::-webkit-scrollbar{height:10px}
.x-scroll::-webkit-scrollbar-track{border-radius:10px;background-color:rgba(0,0,0,0.14)}
.x-scroll::-webkit-scrollbar-thumb{background-color:#fda649;border-radius:10px;border:1px solid #fff}
.manTdSep hr{padding:5px 0 0}
.wrapper:after,.wrapper:before,.uf-field:after,.uf-field:before,.head-t:before,.head-t:after,.head-r:before,.head-r:after,.inner:before,.inner:after,#casing:before,#casing:after,#header:before,#header:after{display:table;content:''}
.wrapper:after,.uf-field:after,.head-t:after,.head-r:after,.inner:after,.wrapper:after,#casing:after,#header:after{clear:both}
#casing input[type='submit'],#casing input[type='reset'],#casing input[type='button'],#casing button,a[role="button"]:not([class^="cke_"]){padding:8px 30px;color:#fda649;font-size:14px;border-radius:6px;border:0;background-color:transparent;border:2px solid #fda649;text-decoration:none;-webkit-transition:all .2s ease;transition:all .2s ease;width:auto!important;cursor:pointer;vertical-align:middle;text-transform:uppercase;font-weight:bold;font-family:'Roboto Condensed',sans-serif}
input.button[value=" + "],input.button[value="+"]{padding:10px!important}
#casing input[type='submit']:hover,#casing input[type='reset']:hover,#casing input[type='button']:hover,#casing button:hover{background:#fda649;color:#fff;-webkit-transition:all .2s ease;transition:all .2s ease}
.cap-ds a[role="button"]{background:0;text-transform:uppercase;font-weight:bold;position:relative;z-index:1;color:#fff;border-radius:6px;font-size:20px;padding:15px 48px;border:2px solid #fff;transition:all .3s}
.cap-ds a[role="button"]:hover{background:#fff;color:#fda649}
#casing input[type='submit']:active,#casing input[type='reset']:active,#casing input[type='button']:active,#casing button:active,a[role="button"]:active,.sidebox .calMonth .calMonthLink:nth-child(odd):active{background:#fda649;color:#fff;-webkit-transition:all .2s ease;transition:all .2s ease;-webkit-box-shadow:none;box-shadow:none}
#casing input[type='button'].u-comboedit{background:#fda649 url(/.s/t/1722/select_disabled_arrow.png) no-repeat;background-position:96% 50%,50% 50%;color:#fff;padding-right:35px!important}
#casing input[type='button'].u-comboedit:active{background:#fda649 url(/.s/t/1722/select_disabled_arrow.png) no-repeat;background-position:96% 50%,50% 50%}
.site-n a{-webkit-transition:all .15s ease-out;transition:all .15s ease-out}
@supports((-webkit-appearance:none) or (-moz-appearance:none) or (appearance:none)){input[type="checkbox"]{width:16px;height:16px;background-color:transparent;border:2px solid #70718e;border-radius:2px;cursor:pointer;position:relative;margin:0 3px 4px 0;-webkit-appearance:none;-moz-appearance:none;appearance:none;vertical-align:middle;outline:0;min-width:16px;min-height:16px;box-sizing:border-box!important}
input[type="checkbox"]:checked,input[type="checkbox"]:checked:hover{background-color:#fda649;border-color:#fda649}
input[type="checkbox"]:checked:before{content:'';display:block;width:3px;height:9px;border:2px solid transparent;border-bottom-color:#fff;border-right-color:#fff;position:absolute;top:-3px;left:3px;-webkit-transform:rotate(43deg);-ms-transform:rotate(43deg);transform:rotate(43deg)}
input[type="radio"]{display:inline-block;width:18px;min-width:18px;height:18px;padding:3px;border:2px solid #70718e;border-radius:50%;cursor:pointer;vertical-align:middle;margin:3px 3px 4px 0;-webkit-appearance:none;-moz-appearance:none;appearance:none;outline:0;position:relative;box-sizing:border-box!important}
input[type="radio"]:hover,input[type="checkbox"]:hover{border:2px solid #fda649}
input[type="radio"]:checked{border-color:#fda649;background:transparent}
input[type="radio"]:checked:before{content:'';display:block;height:8px;width:8px;border-radius:50%;background-color:#fda649;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%)}
input[type="checkbox"]:disabled,input[type="radio"]:disabled{cursor:default;opacity:.4;background-color:#ddd}
}@supports(-ms-ime-align:auto){input[type="radio"]{-webkit-appearance:radio;width:auto;height:auto}
input[type="checkbox"]{-webkit-appearance:checkbox;width:auto;height:auto;min-width:unset;min-height:unset}
}.eVariant input,.eVariant label{vertical-align:middle}
form#addEntForm #isontop~span.customCheckbox{display:inline-block}
.ucf-option .customCheckbox,div.i_search,div.i_person,.nav-head,#shop-basket ul li a:before,.slide,.eBlock+br,#allEntries .eTitle:after,.module_search .eTitle:after,.module_stuff .eTitle+hr,.ed-sep,a.mcReloadBtn img,a.mcSmilesBtn img,a.mcBBcodesBtn img,a.mcManageBtn img,.module_tests .eTitle:after,table.uTable+hr,#addEntForm input[type='hidden']+br{display:none}
.module_search form table td:first-child,.sidebox li.uWithSubmenu,.sidebox li.parent-li,.slide{position:relative}
.customCheckbox:hover{border-color:#fda649}
input[type="checkbox"]:checked+span.customCheckbox{background-color:#fda649;border-color:#fda649}
input[type="checkbox"]:checked+span.customCheckbox:after{content:'';display:block;width:3px;height:9px;border:2px solid transparent;border-bottom-color:#fff;border-right-color:#fff;position:absolute;top:-3px;left:3px;-webkit-transform:rotate(43deg);transform:rotate(43deg)}
input[type="checkbox"]:disabled+span.customCheckbox{opacity:.6;cursor:default}
input[type="checkbox"]:disabled+span.customCheckbox:hover{border-color:#aaa}
.clr{clear:both}
.uf-with-tooltip:hover .uf-tooltip,.uf-wtt-hovered .uf-tooltip{z-index:9}
.material-icons,b.shop-itempage-price *{vertical-align:middle}
.wrapper{margin:0 auto;max-width:1230px;width:100%}
#header{padding:10px 0 0}
.head-l{float:left;width:55%;padding:15px 0 15px 30px}
.head-r{float:right;width:45%;padding:0 0 15px 30px;text-align:right}
.site-n{word-wrap:break-word;-ms-word-break:break-word;word-break:break-word;display:inline-block;vertical-align:middle}
.site-n,.site-n a{color:#fff;font-family:"Roboto Condensed";font-size:20px;font-weight:700;line-height:1.33;text-transform:uppercase;letter-spacing:2px}
.site-n a:hover{text-decoration:none}
#sch-box{padding:20px 0;display:inline-block;width:100%;max-width:310px;vertical-align:middle;margin:0 5px}
.head-r .user-btns{display:inline-block;vertical-align:middle;text-align:center;width:33%;margin:0 5px}
.searchForm .search-box{position:relative;overflow:hidden;background:#fff;text-decoration:none}
.searchForm .queryField{width:100%;border:1px solid #dadada;background-color:#fff;padding:5px 15px;margin:0;height:36px;line-height:30px;border-radius:5px;color:#212121;-webkit-transition:all .2s ease-in;transition:all .2s ease-in}
.searchForm .queryField:focus,.searchForm .queryField:active{border:1px solid #fda649;-webkit-transition:all .2s ease-in;transition:all .2s ease-in}
.searchForm{-webkit-box-shadow:0 0 0 rgba(0,0,0,0.15);box-shadow:0 0 0 rgba(0,0,0,0.15);-webkit-transition:all .2s ease-in;transition:all .2s ease-in;border-radius:5px;position:relative}
#casing input.searchSbmFl[type='submit'],.searchForm .searchSbmFl{position:absolute;right:0;top:0;cursor:pointer;padding:0;margin:0;width:42px!important;height:36px;border:0;border-radius:0 3px 3px 0;white-space:nowrap;text-indent:150%;overflow:hidden;background:#fda649 url(/.s/t/1722/sch.png) 50% no-repeat!important}
.module_search #content form table td input.queryField{width:100%!important;margin:auto}
#casing .searchForm input.searchSbmFl[type='submit']:hover,.searchForm .searchSbmFl:hover,#casing .searchForm input.searchSbmFl[type='submit']:active,.searchForm .searchSbmFl:active{background:#fda649 url(/.s/t/1722/sch.png) 50% no-repeat!important}
.caption{position:absolute;left:50%;top:45%;width:70%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);color:#fff;text-align:center;z-index:15}
.cap-ttl{padding:20px 20px 30px;text-transform:uppercase;font-family:'Roboto',sans-serif;font-size:115px;font-weight:900;line-height:1em;overflow:visible;margin:0 0 12px 0}
.cap-ttl a{color:#fff}
.cap-ds{padding:0 20px;font-size:22px;font-family:'Roboto Condensed',sans-serif;font-weight:300;letter-spacing:.2em;text-transform:uppercase;line-height:1.2em}
a.mouse-scroll{border:1px solid #fff;-webkit-transition:none;transition:none;text-align:inherit;margin:0;padding:0;width:32px;height:48px;border-radius:50px;display:block;position:absolute;bottom:40px;z-index:9;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}
.mouse-scroll:after{content:'';width:4px;height:8px;position:absolute;left:50%;top:7px;border-radius:4px;background-color:#fff;margin-left:-2px;opacity:1;transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px);-webkit-transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px);animation:1.5s cubic-bezier(0.68,-0.55,0.265,1.55) 0s normal none infinite running scrollAnimation;-webkit-animation:1.5s cubic-bezier(0.68,-0.55,0.265,1.55) 0s normal none infinite scrollAnimation}
@keyframes scrollAnimation{0%,20%{-webkit-transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px);transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px)}
10%{opacity:1;-webkit-transform:translateY(0px) scaleY(1.2) scaleX(1.2) translateZ(0px);transform:translateY(0px) scaleY(1.2) scaleX(1.2) translateZ(0px)}
100%{opacity:.01;-webkit-transform:translateY(16px) scaleY(2.5) scaleX(0.5) translateZ(0px);transform:translateY(16px) scaleY(2.5) scaleX(0.5) translateZ(0px)}
}@-webkit-keyframes scrollAnimation{0%,20%{-webkit-transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px)}
10%{opacity:1;-webkit-transform:translateY(0px) scaleY(1.2) scaleX(1.2) translateZ(0px)}
100%{opacity:.01;-webkit-transform:translateY(16px) scaleY(2.5) scaleX(0.5) translateZ(0px)}
}.promo-wrap{position:relative;max-height:100vh;height:100vh;background-image:linear-gradient(-266deg,#fccb38 0,#fccb38 1%,#ff4d75 100%);overflow:hidden}
.parallax-wrap{background:url("/.s/t/1722/svg/like.svg") no-repeat,url("/.s/t/1722/svg/settings.svg") no-repeat,url("/.s/t/1722/svg/phone-call.svg") no-repeat;background-position:12% 12%,50% 70%,80% 10%;background-size:40px,40px,50px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9;opacity:.4}
.second-parallax-wrap{background:url("/.s/t/1722/svg/pie-chart.svg") no-repeat,url("/.s/t/1722/svg/envelope.svg") no-repeat,url("/.s/t/1722/svg/share.svg") no-repeat;background-position:8% 70%,21% 38%,54% 19%;background-size:60px,50px,45px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9;opacity:.7;-webkit-filter:blur(2px);filter:blur(2px)}
.third-parallax-wrap{background:url("/.s/t/1722/svg/avatar.svg") no-repeat,url("/.s/t/1722/svg/upload.svg") no-repeat,url("/.s/t/1722/svg/pie-chart.svg") no-repeat;background-position:5% 90%,75% 75%,90% 29%;background-size:30px,25px,38px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9;opacity:.7}
.fourth-parallax-wrap{background:url("/.s/t/1722/svg/chat.svg") no-repeat,url("/.s/t/1722/svg/settings.svg") no-repeat,url("/.s/t/1722/svg/envelope.svg") no-repeat;background-position:95% 90%,35% 5%,85% 50%;background-size:30px,25px,27px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9}
.uf-reg-wrap h2{border-bottom:2px solid #fda649;font-size:37px;padding-bottom:10px;margin-bottom:10px}
label#uf-terms-label{white-space:pre-wrap}
#header nav,.sidetitle{position:relative;width:100%}
.sitePage1 header{position:absolute;z-index:999;width:100%;background:transparent}
header{background-image:linear-gradient(-266deg,#fccb38 0,#fccb38 1%,#ff4d75 100%)}
.nav-head{padding:0 20px 0 5px;margin-left:10px;color:#fff;cursor:pointer;vertical-align:middle}
.nav-head a{color:#fff;text-decoration:none;vertical-align:middle}
#sidebar{float:right;width:28%;padding-top:30px;padding-right:30px}
.sidebox{margin:30px 0;position:relative;-webkit-box-shadow:0 10px 20px rgba(217,213,230,0.5);box-shadow:0 10px 20px rgba(217,213,230,0.5);border-radius:7px;background-color:#fafaff}
.no_avatar.material-icons{width:70px;height:70px;line-height:70px;background-color:rgba(209,206,219,0.82);border-radius:6px;color:#fff;font-size:32px;margin-bottom:10px}
#casing #content input.loginField{margin:7px 0;display:block}
form[id^="frmLg"]>div{width:320px!important}
.sidetitle{padding:20px 15px;background:#fff;border-radius:7px 7px 0 0;color:#70718e;font-family:"Roboto Condensed";font-size:20px;line-height:1.14;text-transform:uppercase;text-align:center;letter-spacing:1.4px}
.sidebox .inner{padding:25px 20px 50px}
.sidebox ul,.sidebox .catsTable{margin:0;padding:0;list-style:none}
.sidebox .catsTable,.sidebox .catsTable *{display:block;width:auto!important}
.sidebox li{list-style:none;padding:0}
.sidebox li a,.sidebox .catsTable a{display:inline-block;padding:10px 0 0}
.sidebox li b{font-weight:normal}
.sidebox li a:active,.sidebox .catsTable a:active{text-decoration:none}
.sidebox .catsTable .catDescr{color:#727272;font-size:13px}
.sidebox .catNumData{color:#212121;display:inline-block}
.sidebox .calTable{width:100%;position:relative}
.sidebox .calTable a.calMonthLink{font-size:16px}
.sidebox .calTable tbody tr:before{content:''}
.sidebox .calTable tbody tr:nth-child(2):after{-webkit-transform:translateY(33px);transform:translateY(33px)}
.sidebox .calTable tbody tr:nth-child(2) td{padding-bottom:13px;font-size:16px;font-weight:500}
.calTable td{text-align:center;padding:7px 2px}
.calMonth,.calWday,.calWdaySe,.calWdaySu{font-size:13px}
.sidebox .calTable tbody tr:nth-child(2){border-top:1px solid #dadada;border-bottom:1px solid #dadada}
body:not(.tmpl_body) div[class^="cBlock"] .cMessage{padding-bottom:5px!important;line-height:16px}
body:not(.tmpl_body) div[class^="cBlock"] a{font-size:16px;padding-right:10px!important}
body:not(.tmpl_body) div[class^="cBlock"] a b{font-weight:400}
.noEntry,.archiveNoEntry{padding:40px 0;text-align:center}
.sidebox .calMonth{line-height:32px}
.sidebox td.calMonth a{position:absolute;-webkit-transition:all .3s;transition:all .3s;border-radius:7px}
.sidebox .calMonth .calMonthLink:nth-child(odd):hover{background-color:#fda649;border-radius:7px}
.sidebox .calMonth .calMonthLink:nth-child(odd):hover:after{color:#fff}
.sidebox td.calMonth a:first-child,.sidebox td.calMonth>a:first-child+a+a{display:block;text-align:center;line-height:20px;top:2px;right:10px}
.sidebox td.calMonth a:first-child{right:55px}
.sidebox td.calMonth a:first-child+a{font-size:14px;left:10px;top:0;display:inline-block;height:40px;line-height:40px}
.sidebox .calMonth .calMonthLink:first-child,.sidebox .calMonth .calMonthLink:last-child{font-weight:normal;text-transform:none;padding:8px;line-height:1;font-size:0}
.sidebox .calMonth .calMonthLink:first-child:after,.sidebox .calMonth .calMonthLink:last-child:after{display:inline-block;font-size:20px;font-family:'Material Icons';color:#70718e;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
a.swchItem:first-child span:after,a.swchItem:last-child span:after,.pgPrev span:after,.pgNext span:after{display:inline-block;font-size:20px;font-family:'Material Icons';color:#fff;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
.popupbody a.swchItem:last-child span:after,.popupbody a.swchItem:first-child span:after{font-size:17px}
a.swchItem:first-child span:after,.sidebox .calMonth .calMonthLink:first-child:after,.pgPrev span:after{content:'keyboard_arrow_left'}
a.swchItem:last-child span:after{content:'keyboard_arrow_right'}
.pgNext span:after,.sidebox .calMonth .calMonthLink:last-child:after{content:'keyboard_arrow_right'}
.calMdayLink,.calMdayA{font-weight:bold;text-decoration:none!important;position:relative}
.sidebox ul ul{display:none;margin:0;padding:0 0 0 30px}
.sidebox li.uWithSubmenu.over>ul,.sidebox li.parent-li.over>ul,.schQuery,.schBtn{display:block}
.sidebox .answer{padding-top:5px}
.sidebox .answer>div{background-color:#dadada;padding-top:0!important;margin-top:3px}
.sidebox ul.rate-list{margin:0}
#shop-basket ul li a{padding:0;margin:0}
.user-box{text-align:center}
.user-box img{margin:0 0 10px;width:70px;height:70px;-o-object-fit:cover;object-fit:cover;border-radius:50%}
.user-ttl{padding:0 0 5px}
#content{float:left;width:72%;padding:30px 30px 60px}
#content .eBlock{-webkit-box-shadow:0 10px 20px rgba(217,213,230,0.5);box-shadow:0 10px 20px rgba(217,213,230,0.5);border-radius:7px;background-color:#fff;padding:30px 30px 0}
#content fieldset{border:1px solid #dadada;padding:20px;margin:0 0 20px}
#content .calTable{width:100%;margin:0 0 30px}
#content .calTable tr:nth-child(2){background:#d4cfec}
.calMdayIsA{display:block;width:100%;color:#fff;padding:7px 2px;-webkit-box-shadow:0 5px 10px rgba(217,213,230,0.5);box-shadow:0 5px 10px rgba(217,213,230,0.5);border-radius:7px;background-color:#fda649}
.calMdayIsA a{color:#fff}
.calMdayIs:hover,.calMdayIsA:hover{padding:0}
.calMdayIs:hover .calMdayLink,.calMdayIsA:hover .calMdayLink{display:block;width:100%;color:#fff;padding:7px 2px;-webkit-box-shadow:0 5px 10px rgba(217,213,230,0.5);box-shadow:0 5px 10px rgba(217,213,230,0.5);border-radius:7px;background-color:#fda649}
#content.wide-page{float:none;width:100%}
#casing label{cursor:pointer;vertical-align:middle}
.archActive{padding-top:10px}
.eBlock{border-spacing:0;margin:0 0 30px;clear:both;table-layout:fixed}
#content section>.eBlock{margin-top:10px}
.eBlock+table,.vep-comments>table{margin:40px 0 0;border-spacing:0}
#content .vcp-ratestars,.shop-item-brief{padding:5px 0}
.eBlock+table td[width="60%"],.vep-comments table td[width="60%"],.v-channel-page+div+table td[width="60%"],.shop-info table td[width="60%"]{font-size:18px;padding:0 0 20px}
.eBlock td{margin:0 -30px}
.eTitle{color:#70718e;font-family:"Roboto Condensed";font-size:28px;font-weight:400;line-height:1.2;text-transform:uppercase;letter-spacing:1.4px}
.module_tests .eTitle{font-size:25px}
#allEntries .eTitle{font-size:25px}
span[class^="sortBlock"]{line-height:42px}
.eTitle a{color:#70718e;font-family:"Roboto Condensed";font-size:28px;line-height:1.2;text-transform:uppercase;letter-spacing:1.4px;text-decoration:none}
.eTitle div[style^="float:right"] a{font-size:inherit}
.u-star-rating-32+div{padding:10px 0}
.u-current-rating,table.gTable .posttdMessage img{max-width:100%}
#videocontent_comm,.vcp-details{color:#727272;font-size:12px}
.eDetails,.eDetails1,.eDetails2{clear:both;font-size:14px;padding:13px 0!important;color:#727272;line-height:120%}
.eDetails ul,.eDetails1 ul,.eDetails2 ul{line-height:normal}
.eDetails{border-radius:0 0 7px 7px;padding:20px 0!important}
#casing:not(.module_stuff) div[id^="entryID"] .eDetails{background-color:#fafaff;padding:20px 30px!important;margin:20px -33px -3px}
.e-reads,.e-loads,.e-author,.e-date,.e-rating,.e-add,.e-tags,.e-category,.e-comments{margin:0 15px 0 0;display:inline-block;height:15px;line-height:20px}
.eAnswer+div{padding:13px 0}
.eBlock td.eMessage,.eBlock td.eText{padding:10px 0 20px!important}
.e-reads,.e-loads,.e-author,.e-date,.e-rating,.e-add,.e-tags,.e-author-phone,.e-placed,.e-redirects,.e-category,.e-comments{position:relative;text-transform:uppercase;font-family:"Roboto Condensed";font-size:12px;letter-spacing:.91px;padding:0 0 0 20px;margin:0 20px 0 0;display:inline-block}
.e-reads:before,.e-author-phone:before,.e-tags:before,.e-author:before,.e-category:before,.e-placed:before,.e-comments:before,.e-loads:before,.e-date:before,.e-add:before,.e-redirects:before{color:#70718e;font-family:"Material Icons";font-size:16px;font-weight:400;position:absolute;display:inline-block;font-feature-settings:'liga' 1;-webkit-font-feature-settings:liga;font-feature-settings:liga;ms-font-feature-settings:liga}
.e-redirects::before{content:'\E157';top:0;left:0}
.e-reads::before{content:'\E417';top:0;left:0}
.e-category::before{content:'\E2C8';top:-2px;left:0}
.e-author-phone::before{content:'\E0CD';top:-2px;left:-1px}
.e-tags::before{content:'\E893';top:-2px;left:0}
.e-rating::before{content:'';background:url(/.s/t/1722/rating.png) no-repeat 0 2px;display:inline-block;width:16px;height:18px;position:absolute;left:0}
.e-author::before{content:'\E8A6';top:-1px;left:-3px}
.e-add::before{content:'\E7FD';top:-1px;left:-3px}
.e-date::before,.e-placed::before{content:'\E916';top:-2px;left:-2px}
.e-loads::before{content:'\E157';top:0;left:0}
.e-comments::before{content:'\E0CB';top:0;left:0}
.ed-sep,.ed-title{display:none}
.eMessage,.eText,.module_stuff .eBlock{margin:0;line-height:1.5}
.eMessage img,.eText img{max-width:100%;height:auto!important;margin:5px 20px 5px 0!important;border:none!important}
.eMessage p,.eText p{margin:0;padding:0 0 5px 0;overflow:hidden}
.eMessage,.eText,.cMessage{word-wrap:break-word}
.eBlock td.eMessage,.eBlock td.eMessage.eText{padding:20px 0 10px!important}
.swchItemA,.swchItem,.pagesBottom b,.pagesBottom a,.pagesBlockuz b,.pagesBlockuz a,.pagesBlockuz1 b,.pagesBlockuz2 b,#pagesBlock1 b,#pagesBlock2 b,.plist b,.pagesBlockuz1 a,.pagesBlockuz2 a,#pagesBlock1 a,#pagesBlock2 a,a.pgSwch{display:inline-block;margin:2px 0}
span.pagesBlockuz1{margin-left:7px}
.swchItemA,.swchItem,.pagesBottom b,.pagesBlockuz b,.pagesBlockuz1 b,.pagesBlockuz2 b,#pagesBlock1 b,#pagesBlock2 b,.pgSwchA b,.pagesBottom a,.pagesBlockuz a,.pagesBlockuz1 a,.pagesBlockuz2 a,#pagesBlock1 a,#pagesBlock2 a,a.pgSwch{color:#fda649;font-size:14px;font-weight:700;min-width:36px;height:36px;line-height:36px;border:1px solid transparent;border-radius:5px;-webkit-transition:all .1s ease;transition:all .1s ease;vertical-align:middle;text-align:center;padding:0 7px}
.swchItemA,.pagesBottom b,.pagesBlockuz b,.pagesBlockuz1 b,.pagesBlockuz2 b,#pagesBlock1 b,#pagesBlock2 b,.pgSwchA b{color:#000}
.pgPrev span,.pgNext span,a.swchItem:last-child span,a.swchItem:first-child span{font-family:'Material Icons';font-weight:normal;font-size:20px;color:#fff;font-size:0!important;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
a.swchItem:last-child,a.swchItem:first-child,.pgPrev,.pgNext{background-color:#fda649;position:relative}
.swchItemA a:hover,#pagesBlock1 a:hover,#pagesBlock2 a:hover,a.pgSwch:hover{color:#fff;background:#fda649;-webkit-box-shadow:0 2px 5px rgba(0,0,0,0.15);box-shadow:0 2px 5px rgba(0,0,0,0.15);text-decoration:none;-webkit-transition:all .1s ease;transition:all .1s ease}
.pagesBottom a:active,.pagesBlockuz a:active,.pagesBlockuz1 a:active,.pagesBlockuz2 a:active,#pagesBlock1 a:active,#pagesBlock2 a:active,a.pgSwch:active{background:#fda649;-webkit-box-shadow:none;box-shadow:none}
.cBlock1,.cBlock2{margin:0!important;padding:5px 0!important}
#MCaddFrm input[type="text"].mchat{padding:8px 5px 9px!important;text-align:center}
#MCaddFrm input[type="text"].captcha-answer{width:100%!important}
#MCaddFrm img.captcha-question.mchat{border-left-color:transparent!important}
a.mcReloadBtn:after,a.mcSmilesBtn:after,a.mcBBcodesBtn:after,a.mcManageBtn:after{font-family:'Material Icons';font-size:24px;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
a.mcReloadBtn:hover,a.mcSmilesBtn:hover,a.mcBBcodesBtn:hover,a.mcManageBtn:hover{text-decoration:none}
a.mcReloadBtn:after{content:'refresh'}
a.mcSmilesBtn:after{content:'insert_emoticon'}
a.mcBBcodesBtn:after{content:'code'}
a.mcManageBtn:after{content:'mode_edit'}
img.captcha-question{height:36px;border:1px solid #dadada!important;border-radius:0 5px 5px 0}
form#uf-register .uf-text[type="password"]{width:85%;padding-left:5px;padding-right:5px}
#MCaddFrm input[type="text"].captcha-answer{border-radius:5px 0 0 5px}
#MCaddFrm select{padding:9px 4px!important;font-size:13px!important;min-width:20px!important}
.module_gb #content .cBlock1,.module_gb #content .cBlock2{padding:30px 20px!important;margin:0 0 10px!important;background:#fff;-webkit-box-shadow:0 10px 20px rgba(217,213,230,0.5);box-shadow:0 10px 20px rgba(217,213,230,0.5);border-radius:7px}
[itemprop="author"]{color:#1c1830;font-family:'Roboto Condensed';font-size:25px}
.cMessage{line-height:24px}
.cDetails{font-size:12px;color:#727272}
.comEnt .cTop,.comEnt+div .cTop,#newEntryB .cTop{padding:0 0 10px 0;float:left;margin:0 0 0 87px}
.cTop>b{font-family:'Roboto Condensed';font-size:25px}
.cTop *{font-weight:normal}
.cAnswer{padding:5px 0 0 0;font-style:italic;color:#464646;font-size:11px}
.commTd1{padding:5px 2px;width:20%}
input.codeButtons{min-width:30px}
#casing .codeButtons,#casing select.codeButtons{margin:0 0 3px!important}
.eAttach{margin:10px 0;color:#939fae}
.eAttach:before{content:"attach_file";color:#727272;font-family:"Material Icons";font-size:14px;font-weight:400;vertical-align:bottom;margin-left:-3px;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
.eRating{font-size:11px}
.manTdError,.commError{color:#f00}
.commReg{padding:10px 0;text-align:center}
a.groupModer:link,a.groupModer:hover{color:blue}
a.groupAdmin:link,a.groupAdmin:hover{color:#ff4d75}
a.groupVerify:link,a.groupVerify:hover{color:green}
.replaceTable{font-size:12px;padding:20px;border:0;background:#fff}
.outputPM{border:1px solid #dadada;margin:4px 0 4px 30px}
.inputPM{border:1px solid #dadada;margin:4px 0}
.uTable{border-spacing:0;margin:0;padding:0}
.uTable td{padding:8px 10px;white-space:nowrap;border-bottom:1px solid #dadada}
.uTable .uPM,.uTable .myWinSuccess{padding-right:20px}
.gDivRight{padding-bottom:20px;padding-top:10px}
.userSchFrm form input[name="user"]{width:200px!important}
.eAttach .entryAttachSize{padding-left:4px}
.manTable{text-align:left}
.manTable .manTd1{font-size:13px;line-height:14px;width:30%}
#casing.popuptable{background:#fff;margin:0 auto;min-height:100vh}
.popuptitle{background:#fda649;text-transform:uppercase;padding:13px 20px;color:#fff;font-size:25px;font-family:'Roboto Condensed';width:100%}
.popupbody{padding:20px;font-size:12px;color:#212121;width:100%}
.popupbody div[align="center"]{overflow:auto}
.popupbody .user_avatar{width:100px;height:100px;border:1px solid #dadada;display:inline-block;border-radius:50%;overflow:hidden}
.popupbody *{font-size:13px!important}
.popuptable table{text-align:left}
table#usch input,form[name="fuser"] input,.popupbody #addform input,form[name="memform"] input,form[name="memform"] select{margin:7px 4px!important;vertical-align:middle}
input[name="user"]{min-width:200px}
#sidebar input[name="user"],.myWinCont input[name="user"]{min-width:initial}
.archiveDateTitleLink{font-family:'Roboto Condensed';font-size:18px}
.archEntryHr{border-bottom:2px solid #fda649;margin:0}
.archiveEntryTitle ul{margin:2px 0;list-style:none;padding:0}
td.archiveEntryTitle{padding:6px 0;border-bottom:1px solid #dadada}
td.archiveDateTitle{padding-top:30px}
.archiveEntryTitle .archiveEntryTime{font-size:14px;font-weight:700;margin-right:10px}
.archiveEntryTime:after{content:'';display:table;clear:right}
.archiveEntryTime{float:left}
form#tstAddForm tr:nth-last-child(-2n+2) td{padding-top:20px}
form#tstAddForm tr:first-child td{padding-bottom:10px}
form#addEntForm li select:first-child{margin-left:0}
#uEntriesList .uphoto a.phd-comments{color:#fda649}
#addPhtFrm button{margin:0 4px}
.module_tests .eMessage:not(:last-child),.module_tests div.eTitle:first-child{border-bottom:2px solid #fda649;margin-bottom:10px;padding-bottom:15px!important}
div#pagesBlock1{position:relative;padding-bottom:10px;width:100%;text-align:right;margin-bottom:10px}
h2.photo-etitle{text-align:left;margin-bottom:10px;padding-top:20px;font-size:37px;font-weight:400;padding-bottom:10px;border-bottom:2px solid #fda649}
#uEntriesList .uEntryWrap{min-width:33.33%;padding:0 0 30px;-webkit-box-sizing:border-box;box-sizing:border-box}
#uEntriesList .entryBlock{display:block!important}
.module_stuff .eDetails{border-top:0;padding:0!important}
input.manFlTxt{min-width:60px}
#photoModalWrap .fancybox-wrap,#photoModalWrap .fancybox-inner,#photoModalWrap .fancybox-outer{max-width:100%}
ul.form-fields input[type=file]{padding:11px 11px 11px 0!important}
.ve-screen a:hover:before,span.vep-playbutton:before{content:'play_circle_filled';text-shadow:0 2px 5px rgba(0,0,0,0.15);color:#f04f57;font-family:"Material Icons";font-size:48px;font-weight:400;cursor:pointer;text-decoration:none;position:absolute;top:50%;left:50%;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}
span.vep-playbutton{background:0}
.ve-screen a:hover{text-decoration:none}
.ve-length{background:rgba(43,37,74,0.7)!important}
span.btn-title{white-space:normal}
table.catsTable td,.fastLink{padding:4px 0}
.manTdBut{padding:10px}
.user_avatar img{width:100px;border-radius:50%}
.cMessage .user_avatar img{width:70px;margin:-35px 10px 5px -90px}
.pollBlock{font-family:'Roboto'!important}
.comEnt .cMessage:not(.uc-message),.comEnt .cMessage:not(.uc-message)+div,.comEnt+div .cMessage:not(.uc-message),#newEntryB table[class^="cBlock"] .cMessage:not(.uc-message){padding-left:90px!important}
.pollBlock .pollLnk,#TstSbm{margin-top:10px}
.pollQue,.pollAns,.pollLnk a,.pollTot{font-size:13px!important}
.pollQue{padding-bottom:5px}
td.eVariant label{margin-left:7px}
div#content section>h2{font-family:'Roboto Condensed';font-size:30px;padding-bottom:5px;margin-bottom:12px}
div#content section>h2:first-of-type{border-top:2px solid #fda649}
.goods-list .list-item>table>tbody>tr>td:nth-child(even){padding:0 10px}
.shop-item-price{padding:3px 0;font-family:'Roboto Condensed';font-size:37px!important}
.catalog-item,.uTable td.uTopTd{font-family:'Roboto Condensed'}
#content .shop-itempage-viewed-title{margin-top:40px;font-size:25px}
a.shop-item-title,.module_shop section>h1{color:#70718e;font-family:"Roboto Condensed";font-size:28px;font-weight:400;line-height:1.2;text-transform:uppercase;letter-spacing:1.4px;text-decoration:none}
.module_shop section>h1{padding:20px 0}
a.shop-item-title:hover{color:#fda649}
.shop-options .val label{margin:4px 4px 0}
.shop-options span.opt{color:#727272}
b.shop-itempage-price~input{margin:2px 5px}
div#order-submit #order-button{height:auto}
.shop-options li{padding:2px 0!important}
.v-entry .ve-title{background:0;font-size:13px;font-weight:400;padding:0}
#videocontent_title h1.vep-title{background:0;font-family:'Roboto Condensed',sans-serif;padding:0}
.ve-details .ve-details1,.v-entry-page .vep-separator,.v-channel-page .vcp-descr{background:0;border-bottom:1px solid #dadada}
.v-entry-page .vep-screenshots{padding:10px 0}
.v-entry-page h1.vep-title,.vcp-top h1.vcp-title{font-size:37px;background:0;padding:0 20px 10px 0;border-bottom:2px solid #fda649;margin-bottom:15px;float:none;line-height:1.2}
.v-channel-page .vcp-image{float:right}
.list-item,#goods_cont .goods-list:not(:last-child) .list-item{padding-bottom:15px;margin-bottom:30px}
#gimage-add .inner { border-radius:7px; }
.module_shop .list-item {
border-radius: 16px;
background-color: #fff;
padding: 0;
}
.product-card .product-tail { background-color:#ffffff; }
.module_shop hr+h2{padding-top:50px}
ul.shop-tabs.with-clear li{border-radius:5px 5px 0 0;border:0;padding:0;height:auto;overflow:hidden;margin-right:2px}
ul.shop-tabs.with-clear{border-left:none;border-bottom:2px solid #fda649;height:auto}
ul.shop-tabs.with-clear .postRest1 a{background-color:#fda649}
ul.shop-tabs.with-clear li:not(.postRest1) a:hover{background:#fda649;-webkit-box-shadow:0 2px 5px rgba(0,0,0,0.15);box-shadow:0 2px 5px rgba(0,0,0,0.15)}
ul.shop-tabs.with-clear li:not(.postRest1) a:hover,ul.shop-tabs.with-clear .postRest1 a{color:#fff;text-decoration:none!important}
.module_shop .newprice{color:#ff4d75}
ul.shop-tabs.with-clear li a{font-family:'Roboto Condensed',sans-serif;font-size:18px;line-height:1.39;color:#70718e;display:inline-block;padding:10px 20px 7px}
td.shop-itempage-images img{-webkit-filter:brightness(1);filter:brightness(1);-webkit-transition:all .3s ease;transition:all .3s ease}
td.shop-itempage-images img:hover{-webkit-filter:brightness(60%);filter:brightness(60%);-webkit-transition:all .3s ease;transition:all .3s ease}
.shop-itempage-price span{font-size:37px;font-family:'Roboto Condensed';font-weight:400}
#cont-shop-checkout #total-sum td{border-top:1px solid #dadada}
#footer{padding:20px 0 90px;-webkit-box-shadow:0 10px 20px rgba(217,213,230,0.5);box-shadow:0 10px 20px rgba(217,213,230,0.5);background-color:#fff}
#footer .wrapper{padding:0 30px;background-color:transparent}
#footer h6{font-size:28px;line-height:1.57;padding-top:30px;letter-spacing:1.4px}
.soc-wrap a{color:#70718e;font-size:18px;padding:15px 15px 15px 0;-webkit-transition:all .2s;transition:all .2s}
.soc-wrap a:hover,.phones-wrap a:hover{color:#fda649;text-decoration:none}
.foot-l{float:left;padding:0 30px 30px 0;width:70%}
.foot-r{float:right;width:30%}
.links-wrap a{padding-right:15px;font-size:16px}
.phones-wrap a{color:#767c87;font-size:16px;font-weight:300}
.phones-wrap a:not(:last-of-type)::after{content:', '}
footer p{color:#767c87;font-size:16px;font-weight:300}
footer .copyright{padding-top:20px}
footer .copyright p{font-size:13px;margin:0}
.forum-box{padding:20px 20px 60px;background:#fff;width:100%}
.gTable:not(#invoice-table):not(#shop-price-list),.postTable{border-spacing:0;border-collapse:collapse;border-radius:5px}
tr[class^="ThrBotRow"] td{padding-top:4px;padding-bottom:2px}
tr[class^="FrmTopButtonsRow"]>td{padding:2px 0}
.gTable:not(.cat-blocks)>tbody>tr:last-child>td:first-child,.postTable>tbody>tr:last-child>td:first-child{border-bottom-left-radius:5px}
.gTable:not(.cat-blocks)>tbody>tr:last-child>td:last-child,.postTable>tbody>tr:last-child>td:last-child{border-bottom-right-radius:5px}
.gTable:not(#shop-price-list) tr:last-child td{border-bottom-color:transparent!important}
table.gTable img{max-width:none}
.gTable:not(#invoice-table):not(#shop-price-list):not(.cat-blocks) .gTableTop{padding:10px 20px;color:#fff;font-size:25px;font-family:'Roboto Condensed',sans-serif;background-image:linear-gradient(-266deg,#fccb38 0,#fccb38 1%,#ff4d75 100%);border-radius:7px 7px 0 0}
.cat-blocks li a{padding:0}
.gTable:not(#invoice-table):not(.cat-blocks) .gTableTop a{color:#fff}
.gTable:not(#invoice-table):not(#shop-price-list):not(.cat-blocks) .gTableTop a:hover{text-decoration:none!important}
.gTable:not(#invoice-table):not(#shop-price-list):not(.cat-blocks) .gTableSubTop,.postTdTop{color:#70718e;border-bottom:1px solid #dfdfed;font-weight:bold;padding:4px 30px!important;height:40px;line-height:40px;font-size:13px;position:relative}
.gTable{margin:10px 0;padding:20px;border-spacing:0;background:#fff;border-radius:7px}
#casing .forum-box .gTableSubTop:only-child{background-color:transparent!important;color:#212121!important;font-family:'Roboto Condensed',sans-serif;font-size:18px!important;border-bottom:1px solid #dadada;height:50px!important;line-height:50px!important;padding-left:3%!important;font-weight:400!important}
td.forumNameTd .forum{font-family:'Roboto Condensed';font-size:18px}
table#shop-price-list .gTableSubTop{padding:10px!important}
table#shop-price-list .gTableSubTop:first-child{font-size:1.2em!important}
.gTableBody,.gTableBody1,.gTableBottom,.gTableError,.forumNameTd,.forumLastPostTd,.threadNametd,.threadAuthTd,.threadLastPostTd,.threadsType,.postPoll,.newThreadBlock,.newPollBlock,.newThreadBlock,.newPollBlock,.gTableRight,.postTdInfo,.codeMessage,.quoteMessage,.forumIcoTd,.forumThreadTd,.forumPostTd,.gTableLeft,.threadPostTd,.threadViewTd,.postBottom{padding:15px 30px!important;border-bottom:1px solid #dadada}
.threadIcoTd,td.threadsDetails{border-bottom:1px solid #dadada}
#casing select.searchForumsFl{width:100%;max-width:initial}
.forumContent .postPoll div[id^='pollBlock']{border:1px solid #dfdfed}
.forumContent tr[id^='post'] .postTdTop,.forumContent tr[id^='post'] .postTdInfo,.forumContent tr[id^='post'] .postBottom{border-left:1px solid #dfdfed}
.module_forum .postTable{border-spacing:0;border-bottom:1px solid #dfdfed}
.postTdTop{border-bottom:1px solid #dfdfed;border-right:1px solid #dfdfed}
.forumContent tr[id^='post'] .posttdMessage,.forumContent tr[id^='post'] .postBottom{border-right:1px solid #dfdfed}
.forumContent #forumPollF{padding:15px 0!important}
.forumContent .postPoll{padding:0!important}
.postPoll,.postTdInfo,.postBottom,.posttdMessage{border-bottom:0}
form[action="/forum/"] .gTableBody1{border-bottom-color:transparent}
.postBottom{border-top:1px solid #dadada;padding:3px 7px}
div#imblock1 div:first-child,div#iplus,.postRankName,.reputation,.goods-list.shop-itempage-buy-btns>*,input#addcBut{margin-top:5px}
a.forum,a.threadLink{padding:0;font-size:16px}
input#delPsSbm{font-size:13px!important}
.gTableError{color:#f00}
a.catLink,a.forumBarA:hover{text-decoration:none}
a.catLink:hover{text-decoration:underline}
.lastPostGuest,.lastPostUser,.threadAuthor{font-weight:bold}
a.subscribe_forum:hover,.ph-author:hover{color:#ff545d}
.archivedForum{font-size:8pt;color:#f00!important;font-weight:bold}
.forumDescr{max-width:500px}
.forumViewed{font-size:9px}
.forumBarKw{font-weight:normal}
.fastLoginForm{font-size:12px}
.switch,.pagesInfo{padding:0;font-weight:normal;color:#70718e}
.pagesInfo{background:#f2f2f7;line-height:1.3}
.switch>a,.pagesInfo{padding:6px 7px}
.switchActive{padding:4px 7px;font-weight:normal;background:#fda649;color:#fff}
span#filter_by{line-height:42px;margin-right:5px}
a.switchDigit,a.switchBack,a.switchNext{text-decoration:none;font-size:14px;color: #70718e}
a.switchDigit:hover,a.switchBack:hover,a.switchNext:hover{background:#fda649;color:#fff}
input.fastSearch[type="text"]{min-width:223px;margin-left:6px}
.userRights{padding:10px 0}
.threadNoticeLink,.pollSubmit{font-weight:bold}
.threadsType{height:20px;font-weight:bold}
.threadsDetails,.forumOnlineBar{padding:5px 10px}
a.threadPinnedLink{font-weight:bold;color:#f63333!important}
a.threadFrmLink{color:#939fae!important}
.postpSwithces{font-size:8pt}
.thDescr{font-weight:normal}
.forumNamesBar,.forumModerBlock{padding:3px 0}
.postUser{font-weight:bold}
.postRankIco{margin-bottom:5px}
.signatureHr{margin-top:20px}
.postTdInfo,.posttdMessage{padding:20px}
.postTdInfo{text-align:center;border-right:1px solid #dadada}
.posttdMessage{line-height:1.5}
.pollQuestion{text-align:center;font-weight:bold}
.pollButtons,.pollTotal{text-align:center}
.pollSubmitBut,.pollreSultsBut{width:140px;font-size:8pt}
.pollEnd{text-align:center;height:30px}
.codeMessage,.quoteMessage,.uSpoilerText{font-size:12px;padding:10px;margin:0 0 20px;background:#e1e3e6;border:1px solid #dadada!important;color:#555}
.signatureView{display:block;font-size:8pt;line-height:14px;padding:0 0 0 10px;border-left:3px solid #dadada}
.edited{padding-top:30px;font-size:8pt;text-align:right;color:gray}
.editedBy{font-weight:bold;font-size:8pt}
.statusBlock{padding-top:3px}
.statusOnline{color:#0f0}
.statusOffline{color:#f00}
.newThreadItem{padding:0 0 8px;background:url(/.s/t/1722/12.gif) no-repeat 0 4px}
.newPollItem{padding:0 0 8px;background:url(/.s/t/1722/12.gif) no-repeat 0 4px}
.pollHelp{font-weight:normal;font-size:8pt;padding-top:3px}
.pollButton{padding:15px 0;margin:20px 0 0}
.smilesPart{padding-top:5px;text-align:center}
.userAvatar{border:1px solid #939fae;padding:2px}
.pollButtons button{margin:0 10px 0 0!important}
.postIpLink{text-decoration:none}
.thread_subscribe{text-decoration:none}
.thread_subscribe:hover{text-decoration:underline}
.postip,.postip a{font-size:11px;color:#939fae}
.UhideBlockL{background:0;border:1px solid #dadada;padding:10px;color:#939fae}
.UhideBlockL a{color:#939fae;text-decoration:underline}
a.goOnTop{vertical-align:middle}
#addEntForm{background:#fff;-webkit-box-shadow:0 10px 20px rgba(217,213,230,0.5);box-shadow:0 10px 20px rgba(217,213,230,0.5);border-radius:7px;padding:30px 20px}
#casing input[type='text'],#casing input[type='password'],#casing textarea,#casing input[type='file'],#casing select,.filterBlock{font-family:'Roboto',serif;padding:10px 12px;text-decoration:none;border:1px solid #dadada;outline:0;border-radius:5px}
#casing input[name="iws1"],#casing input[name="ihs1"]{padding:9px}
input[type="file"]{cursor:pointer;padding:10px 12px 9px!important}
#casing input[name="passw"]{background-color:#fff}
#casing input[type='text'],#casing input[type='password'],#casing textarea,#casing input[type='file']{background-color:#fff;border:1px solid #dfdfed;margin-bottom:2px;margin-top:2px;vertical-align:middle}
#casing input[type='text']:focus,#casing input[type='password']:focus,#casing textarea:focus,#casing input[type='file']:focus{background-color:#fff;border:1px solid #fda649}
form[name="mform"] table td:first-child:not([align="center"]){text-align:right;padding-right:5px}
#sidebar input[type='text'],#sidebar input[type='password'],#sidebar textarea,#sidebar input[type='file']{background-color:#fff;-webkit-box-shadow:none;box-shadow:none}
input.commFl,textarea.commFl,.prosFl,.consFl,.mchat,.sidebox .loginField,.postTextFl{width:100%;-webkit-box-sizing:border-box;box-sizing:border-box}
#casing select{padding-right:30px;min-width:200px;max-width:300px;cursor:pointer;margin:3px 2px 3px 0;vertical-align:middle}
.gTableRight .customCheckbox{float:left;margin-right:6px}
.gTableRight .customCheckbox~br{clear:both}
form[name="searchform"] input,form[name="searchform"] select{margin:7px 4px!important}
#casing select[name="time"],#casing select[name="period"],#casing select[name="pya"],#casing select[name="pma"],#casing select[name="pda"],#casing select[name="pha"],#casing select[name="pmia"],#casing select[name="ya"],#casing select[name="ma"],#casing select[name="da"],#casing select[name="ha"],#casing select[name="mia"],#casing input#date1,#casing input#cdate1,#casing input#invoice_sum1,#casing input#date2,#casing select#sdate,#casing #uf-birthday-d,#casing #uf-birthday-m,#casing #uf-birthday-y,#casing select[name="by"],#casing select[name="bd"],#casing select[name="bm"]{min-width:inherit;margin:7px 4px}
div#pagesBlock1>*{line-height:34px}
.uf-fields-wrap{max-width:300px;margin:auto}
input#fCode,input[id^="captcha-answer-"],input[id^="captcha-skey"]{height:auto;padding:8px 10px!important;margin-top:1px!important;border-radius:5px 0 0 5px!important}
#addEntForm img.captcha-question{margin-top:1px}
#casing select:not([multiple]){-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#fff url(/.s/t/1722/arrow-down.png);background-repeat:no-repeat;background-position:93% 50%;background-position:calc(100% - 13px) 50%,center}
#casing select::-ms-expand{display:none}
#mchatMsgF{min-height:60px}
#casing textarea{resize:vertical}
#MCaddFrm table{border-spacing:0}
textarea.mchat{border-color:transparent!important;-webkit-box-shadow:0 0 0 1px rgba(0,0,0,0.1)!important;box-shadow:0 0 0 1px rgba(0,0,0,0.1)!important;vertical-align:bottom}
#MCaddFrm table td{padding:5px 0}
#MCaddFrm table td:first-child:not(:only-child) input:not(.captcha-answer){width:97%!important}
#MCaddFrm table td:last-child:not(:only-child) input:not(#mchatBtn){width:97%!important;float:right}
#iplus input{width:auto!important}
td.ThrForumBarCl12{width:auto}
.csTop{overflow:hidden}
input.fastNav,input.fastSearch[type="submit"],#filter_word+input[type="submit"]{padding:9px 15px!important}
#thread_search_field{width:calc(100% - 55px)!important;max-width:223px;margin:3px 4px 6px!important}
div[id^="imblock"]>span:first-child{width:34px;display:inline-block;text-align:center;padding-right:0!important}
div[id^="imblock"]>div:first-child,#iplus>div{line-height:34px;vertical-align:middle}
div[id^="imblock"]{clear:both}
.editImgBlock{padding-left:7px}
.uplFileFl,label.com-order-wrap select{margin-left:7px!important}
.ucoz-forum-post-image-interface{padding-left:12px}
[id^="catSelector"]{width:auto!important;padding-left:3px!important;padding-right:3px!important}
input[type="text"][id^="qid-"]{margin-bottom:0!important;padding-top:9px!important;padding-bottom:10px!important}
span[class^="id-good"]{vertical-align:middle;line-height:32px}
.manTable select{max-width:300px}
#doSmbBt,.u-combobut,#content .xw-tl,#content .xw-bl,#content .u-menuvsep,div#cont-shop-invoices>.filter_table{display:none}
div#cont-shop-invoices>.filter_table{font-size:0}
#casing .u-comboeditcell,#casing .u-combo{border:0!important;background:none!important}
#casing .u-combolist,#content .xw-mc{padding:5px 3px;background:#fff;border:1px solid #dadada;margin:0;font-size:12px!important;color:#939fae!important}
#content .xw-ml,#content .xw-mr{margin:0;padding:0;background:0}
#uNetRegF table{text-align:left}
#uNetRegF table table{clear:both}
#uNetRegF table table td{padding:5px 0 0 0}
.sidebox .gTable{background:0;border:0}
.sidebox .gTableTop,.sidebox .gTableSubTop,.sidebox .forumNameTd{border:0;background:0;text-transform:none;height:auto;line-height:normal;font-size:13px!important;-webkit-box-shadow:none;box-shadow:none;padding:10px!important}
.sidebox .gTable ul{padding:0 0 0 20px}
table.gTable input{margin-bottom:5px}
.sidebox .gTableTop,.sidebox .gTableSubTop{display:block;padding:5px 0!important;color:#fda649;font-weight:normal;text-decoration:none;position:relative}
form#shop-price-form{overflow-x:auto;padding-bottom:30px;padding-top:20px}
.sidebox .gTableTop:hover,.sidebox .gTableSubTop:hover{color:#fda649;text-decoration:none}
.sidebox .gTableTop[onclick*="location"]{padding-right:25px}
.sidebox .gTableTop[onclick*="shopCatBlocks"]:before,.sidebox .gTableSubTop:before,.parent-li em{content:"+";width:20px;height:20px;display:inline-block;text-align:center;margin-right:5px;line-height:20px;border-radius:3px;background-color:transparent;-webkit-transition:all .2s ease;transition:all .2s ease}
.sidebox .gTableSubTop:before{content:'-'}
.sidebox .gTableTop:hover:before,.sidebox .gTableSubTop:hover:before,.parent-li em:hover{color:#fff;-webkit-transition:all .2s ease;transition:all .2s ease;background-color:#fda649;cursor:pointer}
.manTable td input,.manTable td textarea{max-width:99%}
.manTable td input#id_file_add{max-width:none}
.opt_vals .gTableSubTop{padding-left:0;background:0;height:48px}
#content form[action$="search/"] table{width:100%}
#content form[action$="search/"] table td{white-space:normal!important}
#content form[action$="search/"] table td+td{width:30%}
#content .queryField{width:70%!important}
#slideshowBlock7{margin:0 0 20px}
#selectPhotosBtn{height:auto!important}
.cats-select-btn{text-shadow:inherit!important}
.custom-navigation,.custom-controls-container{bottom:0;z-index:10}
.gphoto,.smiles img{max-width:inherit}
#baseLogForm td:first-child{width:25%}
#message.wysibb-texarea{border:0;background-color:transparent;-webkit-box-shadow:none;box-shadow:none;margin:0}
#message.wysibb-texarea:focus{border:0}
.ucoz-forum-post-image-preview{max-width:inherit!important;max-height:35px!important}
div#shop-basket ul li{padding-left:45px;background-size:30px!important;background-position:0 50%!important}
form#MCaddFrm{padding:15px 0 0!important;max-width:280px;margin:0 auto}
iframe#mchatIfm2{max-width:280px;margin:0 auto;display:block}
.mChatWrapper{max-width:280px;margin:0 auto}
#shop-basket,.rate-list{text-align:center}
#casing #MCaddFrm textarea#mchatMsgF{padding:5px}
#casing #invoice-form-export,#casing #invoice-form-print,#casing #invoice-form-send-el-goods{font-size:24px;padding:4px 12px;vertical-align:middle;text-transform:lowercase;font-family:'Material Icons';margin-right:7px;width:48px;overflow:hidden;display:none;font-weight:400}
#casing #invoice-form-export.material-icons,#casing #invoice-form-print.material-icons,#casing #invoice-form-send-el-goods.material-icons{display:inline-block;margin-bottom:4px}
.fil_togg_wrapper+hr+table td{display:inline-block;width:50%!important;font-size:14px;text-align:left!important}
.fil_togg_wrapper+hr+table td:nth-child(even){text-align:right!important}
.fil_togg_holder{background:#fda649;display:inline-block;padding:9px;border-radius:5px;cursor:pointer}
.fil_togg_holder:hover{background:#fda649}
.fil_togg_wrapper{padding:10px;color:#fff;margin:13px 0}
table.filter_table td,table.status_table td{padding:0 5px}
#casing table.status_table td input:first-child,#casing table.status_table td select:first-child,#casing table.filter_table td input:first-child,#casing table.filter_table td select:first-child{margin-left:0!important}
#casing table.status_table td input:last-child,#casing table.status_table td select:last-child,#casing table.filter_table td input:last-child,#casing table.filter_table td select:last-child{margin-right:0!important}
div#cont-shop-invoices .status_table select,div#cont-shop-invoices>div:first-child form,table.filter_table td input:not(:first-child),table.filter_table td select:not(:first-child){margin-left:4px!important}
img.captcha-renew{margin-left:3px}
div#cont-shop-invoices .status_table select:not(#status-filter),input#gbsbm{margin-top:13px}
div#cont-shop-invoices>div:first-child form input,div#invoice_cont #invoice-form,table.filter_table td input,table.filter_table td select,form#invoice-form select{margin:7px 4px 6px 4px!important}
#invoice_cont #invoice-form+hr,.fil_togg_wrapper+hr{display:none!important}
#order-table>table{border-spacing:0;margin-bottom:20px}
.order-item-nom{font-weight:600}
#content #order-table .order-head th,.gTable#invoice-table .gTableSubTop,.gTable#shop-price-list .gTableTop{border-bottom:2px solid #fda649;font-family:'Roboto Condensed';font-size:16px;padding:11px 4px}
td.order-item-cnt input{margin:-9px 0!important}
form#checkout-form{max-width:500px}
form#checkout-form input,form#checkout-form textarea{width:100%;margin:7px 0!important}
form#checkout-form input.text.promo{width:90%}
#content #order-table .order-item td{border-bottom:1px solid #dadada}
#content #order-table td{padding:15px 4px}
.methods-list td{color:#727272}
.methods-list .label{font-size:15px;line-height:26px}
input#print-button{margin-right:7px;margin-bottom:13px}
table#shop-price-list .gTableTop{border-radius:0}
table#shop-price-list .gTableTop:first-child{border-top-left-radius:5px}
table#shop-price-list .gTableTop:last-child{border-top-right-radius:5px}
table#shop-price-list td.forumIcoTd{font-size:13px!important}
.catalog:not(:first-child){padding:20px 0;border-bottom:1px solid #dadada;margin-bottom:20px}
div#cont-shop-checkout h2,h3#shop-balance{padding-top:20px;padding-bottom:10px}
.methods-list{margin-bottom:20px}
img#user-avatar{min-width:30px}
.shop-itempage-viewed-title,#recommended_products_title{font-family:'Roboto Condensed'}
span.shop-pros{background:#e8ffda}
span.shop-cons{background:#ffe7e7}
.shop-cons,.shop-pros{display:block;padding:15px;border-radius:5px}
.shop-cons b,.shop-pros b{display:block;font-family:'Roboto Condensed';font-size:18px}
.mobile-menu-container{position:absolute;right:0;width:100%;top:100px;padding-top:5px;z-index:2001;background-color:#fafaff;-webkit-transition:all .5s;transition:all .5s;-webkit-overflow-scrolling:touch}
.owerflow-layer{display:none;background-color:rgba(0,0,0,.5);opacity:0;-webkit-transition:all .5s;transition:all .5s;-webkit-transition:background-color .5s;transition:background-color .5s}
.search-box{position:relative;z-index:9999;padding:0 10px}
.tmpl_body{padding:0!important;height:100%;min-height:100%;left:0;right:0;position:relative;transition:all .5s;overflow-x:hidden}
.fixed{left:-340px;right:340px;position:fixed;transition:all .5s}
.fixed .mobile-menu-container{right:0}
.owerflow-layer.openned{display:block;position:fixed;left:0;right:0;top:-100px;bottom:0;z-index:1991;-webkit-transition:all .5s;transition:all .5s;opacity:1;height:150%}
select#user-filter{float:right}
.mm-wrapper.openned .mobile-menu-container,.mm-wrapper.openned{-webkit-transition:all .5s;transition:all .5s}
.fixed .mm-wrapper{right:0}
.mm-wrapper{position:fixed;top:-100px;height:calc(100% + 100px);width:340px;overflow-y:auto;overflow-x:hidden;background:#fafaff;-webkit-transition:all .5s;transition:all .5s;z-index:1992;right:-340px}
.mm-wrapper::-webkit-scrollbar{width:12px;height:10px}
.mm-wrapper::-webkit-scrollbar-button{width:0;height:0}
.mm-wrapper::-webkit-scrollbar-thumb{background:#fda649;width:5px}
.mm-wrapper::-webkit-scrollbar-track{background:#f2f2f2;border-radius:0}
.mm-wrapper::-webkit-scrollbar-corner{background:transparent}
i.material-icons.i_close{padding:20px 11px 10px;right:15px;top:115px;display:block;text-align:right;cursor:pointer;transition:all .3s}
i.material-icons.i_close:hover{color:#fda649}
.nav-head{display:inline-block}
.social{list-style:none;padding:0;margin:0}
.social li{display:inline-block}
.soc-contacts .icon-facebook,.soc-contacts .icon-vk,.soc-contacts .icon-instagram{content:'';display:inline-block;vertical-align:middle;background-size:19px;height:19px}
.soc-contacts{padding:15px 0 25px}
.soc-contacts .soc-block{padding:0 15px}
.mobile-menu-container .soc-contacts .soc-block a:hover{color:#70718e;text-decoration:none}
.soc-contacts .soc-block a{font-size:16px;padding-right:10px}
#scrollup{padding:0 13px;opacity:0;height:50px;border:0;background-size:25px;bottom:20px;background:#fda649;color:#fff;border-radius:7px;right:20px;cursor:pointer;position:fixed;z-index:110;-webkit-transition:all .3s;transition:all .3s}
input[type=text].iCode_main_inp{padding:11px 3px!important;font-size:11px!important}
#casing.module_stuff input[name=szh],#casing.module_stuff input[name=szw]{width:60px!important;margin-right:5px}
#casing.module_stuff input[name=szh]{margin-left:5px}
#casing.module_stuff select[name="filter1"]{margin-left:10px}
#transactions_filters td,.module-shop h3#shop-balance+table td{display:block;width:100%;text-align:left!important}
@supports((display:-webkit-box) or (display:flex)){div#casing:not(.popuptable){width:100%;display:-moz-flex;display:-ms-flex;display:-o-flex;display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-line-pack:start;align-content:flex-start;-ms-flex-pack:justify;-webkit-box-pack:justify;justify-content:space-between}
div#casing:before,div#casing:after{display:none}
}@media only screen and (min-width:960px){
#toolbarMainContainer{display:block}
}@media only screen and (max-width:1200px){.wrapper{width:auto}
.fil_togg_wrapper+hr+table td:nth-child(-n+2){width:100%!important}
.fil_togg_wrapper+hr+table td:nth-child(even){text-align:left!important}
}@media only screen and (max-width:960px){@supports((display:-webkit-box) or (display:flex)){div#casing{-ms-flex-wrap:wrap;-o-flex-wrap:wrap;flex-wrap:wrap}
}.nav_menu_toggler{display:none!important}
.head-l,.foot-l,.foot-r{width:auto}
.head-r{width:auto}
.head-r .user-btns,.head-r #sch-box{width:25px;margin-right:5px}
.mouse-wrap{display:none}
div.i_person{display:block;color:#fff;cursor:pointer}
div.i_search:hover,div.i_person:hover{color:#ff545d}
div.i_search.open+div,div.i_person.open+div{display:inline-block;width:100%;min-width:300px;position:absolute;z-index:100;right:0;top:55px;-webkit-box-shadow:0 3px 5px rgba(0,0,0,0.15);box-shadow:0 3px 5px rgba(0,0,0,0.15)}
div.i_person.open+div{background-color:#574e82;height:55px;line-height:55px;font-size:18px}
.sidebox .calTable{width:300px}
.cap-ttl{font-size:78px}
.cap-ds a[role="button"]{font-size:18px;padding:12px 40px}
.cap-ds{padding:0 20px 30px}
#footer{padding:20px 0}
.foot-l,.foot-r{padding:0;float:none}
#content,#sidebar{float:none;width:100%}
#sidebar{padding-left:30px}
li.ucf-options{padding-right:50px}
html[style^="margin-top:"],html[style^="margin-top:"] body{position:static}
#header nav,.forum-box .gTableSubTop,.forum-box .forumIcoTd,.forum-box .forumThreadTd,.forum-box .forumPostTd,.forum-box .forumLastPostTd,.forum-box .threadIcoTd,.forum-box .threadPostTd,.forum-box .threadViewTd,.forum-box .threadAuthTd,.forum-box .threadLastPostTd,.forum-box .legendTable,.forum-box .fFastSearchTd,.forum-box .fFastNavTd,.forum-box .funcBlock,.forum-box .userRights,.forum-box .forumNamesBar,.forum-box td.postBottom,.forum-box td.postTdInfo,#toolbarMainContainer,.custom-controls-container{display:none}
.forum-box .gTableTop{padding:10px 20px}
.forum-box .postTable,.forum-box .postTable tbody,.forum-box .postTable tr,.forum-box .postTable td{display:block;width:auto!important}
select#user-filter{float:none}
.postBottom td{display:inline-block!important;padding:0 2px}
.postTdInfo{border-right:0;border-bottom:1px solid #dadada}
.forum-box .postTdTop{text-align:left;height:auto;line-height:normal;font-size:13px;padding:10px 20px;border-bottom-width:1px}
.forum-box .postTdTop+.postTdTop{padding:10px 20px;border-bottom-width:2px;font-size:11px;font-weight:normal}
header.nav-up{top:-55px;height:auto}
header.nav-down{top:0}
div#uNMenuDiv1:before{content:'close';position:absolute;color:#fff;font-family:"Material Icons";font-size:20px;padding:17px;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
#casing:not(.module_shop) #content>section>table:nth-child(-n+5) td:not(.calMdayIs){display:block;width:100%;padding:5px 0;text-align:left}
#casing>#content>section>table table.calTable td{display:table-cell!important;width:auto!important;text-align:center!important}
#casing:not(.module_shop) .catsTd{min-width:100%}
#casing:not(.module_shop) #content>section>table:nth-child(-n+5) td [class^="pagesBlockuz"]{white-space:pre-wrap!important}
form[name="searchform"] .gTable>tbody>tr>td.gTableBody1{display:block;height:auto!important}
form[name="searchform"] input[name="kw"]{max-width:100vw;width:290px}
#cont-shop-invoices{max-width:100vw;padding-bottom:30px}
#cont-shop-invoices #invoice_cont{overflow-x:auto}
#cont-shop-invoices>table>tbody>tr>td{display:block;width:100%;text-align:left}
.main_wrapper{min-height:calc(100% - 130px)}
span.slist a{padding:5px;display:inline-block;font-size:14px}
}@media(max-width:737px){.popupbody .allUsersBtn{display:block}
#uEntriesList .uEntryWrap{width:50%!important}
.module_photo #content #uEntriesList .entryBlock{text-align:center}
}@media only screen and (max-width:640px){span.pagesBlockuz1{text-align:center;padding-top:10px}
#content,#sidebar{padding:30px 15px 40px}
.catalog-item>a{position:inherit}
.site-n,.site-n a{font-size:18px}
.cap-ds{padding:7px 10px 15px}
.caption{width:100%}
.cap-ttl{font-size:50px}
.cap-ds{font-size:18px}
.eMessage img,.eText img{width:100%!important;float:none;margin:0 0 20px!important}
#thread_search_form,#forum_filter,#thread_search_form,#puzadpn,td.pollResults tr td.pollPos{display:none}
.uTable .user_avatar img{width:50px}
span[id^=iCode]{display:block;padding-left:38px}
.forum-search{display:block}
.shop-tabs{border-bottom:0!important}
.shop-tabs li{border-bottom:1px solid #a7a6a6}
.shop-info{clear:both}
.catalog td.catalog-item{display:block!important;width:100%!important;overflow:hidden!important;max-width:calc(100vw - 35px)}
td.shop-itempage-images{width:inherit!important;display:block;text-align:center}
td.shop-itempage-images #ipreview{display:block;margin:0 auto 10px}
.shop-itempage-images+td{display:block}
td.pollResults tr{display:block;margin-bottom:4px;border:1px solid #dadada;padding:3px}
td.pollResults tr td{display:inline-block}
@supports((display:-webkit-box) or (display:flex)){td.pollResults tr,.uploaderPhotosContainer{display:-moz-flex;display:-ms-flex;display:-o-flex;display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-wrap:wrap;-o-flex-wrap:wrap;flex-wrap:wrap}
.uploaderPhotosContainer{-ms-flex-pack:distribute;justify-content:space-around}
}td#phM4 div{float:none!important;padding:10px 0}
.manTdBut>*{display:block}
td.pollAnsw{width:100%!important}
.form-fields div.fileinput,.form-fields #flUpPhotosCount{float:none;min-height:unset;top:10px}
td.pollResults tr td:not(.pollAnsw){width:auto!important;padding:2px}
#addEntForm ul.form-fields>li{width:100%}
table.catsTable td,#goodsform .manTable>tbody>tr>td{display:block;width:100%!important}
.emptyPlaceholder,.uploaderPhotosContainer,#flUpPhotosCount{width:auto!important;height:auto!important;min-height:90px;position:initial!important;max-height:350px;margin:0!important}
#order-table{overflow:auto}
td.forumMemNum,.forumMemSwch{display:block;text-align:left;padding:4px 10px;width:100%}
#order-table::-webkit-scrollbar{height:10px}
#uEntriesList .uEntryWrap{padding:0 0 10px}
#order-table::-webkit-scrollbar-track{border-radius:10px;background-color:rgba(0,0,0,0.14)}
#order-table::-webkit-scrollbar-thumb{background-color:#fda649;border-radius:10px;border:1px solid #fff}
td.shop-itempage-images+td table td,.manTable .manTd1,.manTable .manTd2{display:block;width:100%;text-align:left}
.goods-list.shop-itempage-buy-btns{float:none!important;padding:20px 0}
.goods-list.shop-itempage-buy-btns div{display:inline-block;margin-left:7px;vertical-align:middle}
.popupbody>div>div:not(.udtb){float:none!important}
.popupbody>div>div.udtb:nth-child(2n){background-color:#f5f3ff}
table#transactions_filters td{display:block;text-align:left}
.fourth-parallax-wrap{display:none}
}@media only screen and (max-width:480px){ul.shop-tabs.with-clear li a{width:100%}
h1{font-size:30px}
h2{font-size:22px}
h3{font-size:17px}
h4{font-size:15px}
h5{font-size:14px}
h6{font-size:13px}
.eTitle{font-size:27px}
.head-l{padding:10px 0 10px 20px}
#addPhtFrm ul.form-fields>li,#addPhtFrm ul.xPhtBlock>li{width:100%}
.shop-options .val label{display:block;padding-bottom:5px}
.shop-tabs li{border-bottom:0}
ul.shop-tabs.with-clear li{float:none;border-radius:0}
#cont-shop-checkout .methods-list .fw{width:100%}
form#addPhtFrm .manTable>tbody>tr>td,.commTable>tbody>tr>td{display:block;width:100%}
.gTableTop{font-size:1.5em}
.site-n,.site-n a{font-size:16px}
.commTable td.commTd2>table>tbody>tr>td{display:block;width:100%}
table.smiles tr,table.smiles td{display:inline-block;float:left}
.cap-ttl{font-size:42px}
.cap-ds.description,i.material-icons.flex-prev,i.material-icons.flex-next,.smilesPart{display:none}
input.codeButtons{padding:5px!important}
select.codeButtons{padding:5px 25px 5px 5px!important;min-width:inherit!important}
.cap-ds a{display:inline-block}
form[name="memform"]>*{display:block}
form#addPhtFrm .navTabs>*,td.ucf-smiles,td.ucf-message-wrap,#addEntForm .manTable td,#addEntForm .commTd1,#addEntForm .commTd2,form#addEntForm>table>tbody>tr:first-child>td:first-child{display:block;width:100%}
.manTable td input,.manTable td textarea{max-width:97%}
#casing #iplus+input[type='file']{width:80%;overflow:hidden;vertical-align:middle}
.manTable .manTd1{width:auto}
#uNetRegF tr td:first-child{max-width:20%!important;white-space:normal!important;font-size:11px}
#uNetRegF #fAvatar,#uNetRegF #fAvatarU{display:block;margin:0 0 3px}
#uNetRegF #fAvatarU+input{position:relative;margin:0 0 0 -10px}
.uNetDescr{font-size:9px}
#fTerms{float:left;margin:2px 10px 10px 0}
#fTerms+label{font-size:11px!important;vertical-align:top}
#fTerms~div{font-size:9px;padding:10px 0 0}
.copy{font-size:9px}
.calendarsTable,.calendarsTable>tbody,.calendarsTable>tbody>tr,.calendarsTable>tbody>tr>td{display:block;width:100%}
#content .calTable{width:100%;margin:0 0 20px}
#content .calMonth{text-align:left;text-transform:uppercase}
.posttdMessage{padding:10px 10px 30px}
.postUser{font-size:14px}
#frM53 .gTableLeft,#frM53 .gTableRight{display:block;width:auto!important}
.opt_vals td{display:table-cell!important}
.opt_items{max-width:97%}
#uEntriesList .uEntryWrap{width:100%!important}
.manTable td #idAreaoEditbrief td,.manTable td #idAreaoEditmessage td,.manTable td #idAreaoEditdscr td{display:table-cell}
.forumContent>table:first-child>tbody>tr>td:not(:empty){text-align:center;display:block;width:auto;padding:5px 10px}
form[name="mform"] td:not([align="center"]),form[name="mform"] table td:first-child:not([align="center"]){display:block;text-align:left;width:100%;padding-left:0;padding-right:0}
form[name="mform"] td input,form[name="mform"] td textarea{width:100%!important}
table.switches{margin-top:5px}
#casing form #uCatsMenu7{min-width:290px}
.gTableBody,.gTableBody1,.gTableBottom,.gTableError,.forumNameTd,.forumLastPostTd,.threadNametd,.threadAuthTd,.threadLastPostTd,.threadsType,.postPoll,.newThreadBlock,.newPollBlock,.newThreadBlock,.newPollBlock,.gTableRight,.postTdInfo,.codeMessage,.quoteMessage,.forumIcoTd,.forumThreadTd,.forumPostTd,.gTableLeft,.threadIcoTd,.threadPostTd,.threadViewTd,.postBottom{padding:15px!important}
.forum-box .postTdTop{padding:10px 20px 0}
.forum-box .postTdTop+.postTdTop{padding:5px 20px 10px}
#casing form#addEntForm .iCode_el .iCode_el_tooltip{white-space:normal;min-width:180px;text-align:center}
#casing select,#casing select.searchForumsFl{max-width:280px}
form[name="searchform"] input,form[name="searchform"] select,#casing input.pinput{margin:7px 0!important}
.social-accounts{white-space:nowrap;float:left}
.udtb{overflow:hidden}
#content .eBlock{-webkit-box-shadow:none;box-shadow:none}
#content,#sidebar{padding:30px 15px 40px}
.i_menu{font-size:36px}
#content .eBlock{padding:30px 15px 0}
#casing:not(.module_stuff) div[id^="entryID"] .eDetails{margin:20px -18px -3px}
.module_shop .list-item{padding:15px}
.goods-list .list-item>table>tbody>tr>td:nth-child(even){padding:0}
.goods-list .list-item>table>tbody>tr>td{display:block;width:100%;padding:5px 0;text-align:left}
#casing .ucf-avatar{float:none}
#casing .ucf-content{margin:20px 0}
.links-wrap a{display:block;padding:5px 0}
}@media(max-width:360px){.mobile-menu-container,.mm-wrapper{width:100%}
.mm-wrapper{right:-100%}
#content,#sidebar{padding:30px 10px 40px}
form[name="addform"] input[type="button"],form[name="addform"] input[type="reset"]{margin-bottom:7px}
.v-channel-page .vcp-image{float:none}
table#total-sum td{display:block}
.head-l{padding:10px 0 10px 15px}
span.site-n{width:175px;word-wrap:break-word;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;color:#fff}
.eTitle{font-size:20px}
.nav-head .icon{position:absolute;width:40px;right:20px;top:12px}
#casing .forumModerFuncs select{max-width:245px}
.forumModerFuncs{padding:0 10px}
.sidebox .calTable{width:100%}
.module_load #content section table:nth-child(3) td .pagesBlockuz1,.module_photo #content section table:nth-child(1) td .pagesBlockuz1,.module_publ #content section table:nth-child(3) td .pagesBlockuz1{display:block}
.shop-imgs.with-clear,.goods-list .list-item>table>tbody>tr>td:first-child{text-align:center}
.shop-imgs img{display:inline-block;float:none}
a#leftSwch,a#rightSwch{margin:0 auto}
tr.ThrTopButtonsRow1>td{padding-left:4px}
td.gTableTop #subscribe{float:none}
.recaptcha-wrapper{max-width:290px}
.recaptcha-wrapper [id^="recaptcha_"]{-webkit-transform:scale(0.88);transform:scale(0.88)}
.commTable{padding:0}
#casing textarea{max-width:100%}
form[name="mform"] td:not([align="center"]),form[name="mform"] table td:first-child:not([align="center"]){display:block;text-align:left;width:100%;padding-left:0;padding-right:0}
form[name="mform"] td input,form[name="mform"] td textarea{width:100%!important}
td.frmBtns{text-align:start}
.gTableRight input{margin:3px auto}
#casing input[type='file']{width:80%;overflow:hidden;vertical-align:middle}
#casing .fileinput input[type='file']{width:100%}
.forum-box{padding:20px 0}
#casing .gTable tr:last-child td:last-child,#casing .postTable tr:last-child td:last-child,#casing .forum-box .gTableTop{border-radius:0!important}
#casing .gTable>tbody>tr:last-child>td:first-child,#casing .postTable>tbody>tr:last-child>td:first-child{border-bottom-left-radius:0}
#casing .gTable>tbody>tr:last-child>td:last-child,#casing .postTable>tbody>tr:last-child>td:last-child{border-bottom-right-radius:0}
span[class^="sortBlock"]{line-height:1.2}
.spec-values,.shop_spec_sub,.shop_spec_val{padding:0!important}
table.shop_spec td,table.shop_spec td .item-action{display:block;text-align:left}
.sidebox .inner{padding:25px 15px 50px}
.cMessage .user_avatar img{float:none;margin:0 auto;display:block}
.cMessage .user_avatar{display:block}
#casing .comEnt .cMessage,#casing .comEnt .cMessage+div,#casing .comEnt+div .cMessage,#casing #newEntryB .cMessage{padding-left:0!important}
.comEnt .cTop,.comEnt+div .cTop,#newEntryB .cTop{margin:0}
.cMessage>a:first-child{padding:0!important}
.forumContent .forum-pages,.forumContent .FrmTopButtonsRow2 td,.forumContent .ThrTopButtonsRow2 td{padding-left:10px}
.gTableBody,.gTableBody1,.gTableBottom,.gTableError,.forumNameTd,.forumLastPostTd,.threadNametd,.threadAuthTd,.threadLastPostTd,.threadsType,.postPoll,.newThreadBlock,.newPollBlock,.newThreadBlock,.newPollBlock,.gTableRight,.postTdInfo,.codeMessage,.quoteMessage,.forumIcoTd,.forumThreadTd,.forumPostTd,.gTableLeft,.threadIcoTd,.threadPostTd,.threadViewTd,.postBottom{padding:10px!important}
}.slider-menu{overflow:hidden}
.slider-menu__container{position:relative;top:0;left:0;-webkit-transition:all .2s;transition:all .2s}
.slider-menu__menu{margin:0;padding:0;list-style:none}
.slider-menu__menu .slider-menu__menu{position:absolute;top:0;left:100%;width:100%;opacity:0;-webkit-transition:all .2s;transition:all .2s;visibility:hidden}
.slider-menu__menu .slider-menu--active{opacity:1;visibility:visible}
.slider-menu__item--vertical .slider-menu__back{display:none}
.slider-menu__item--vertical .slider-menu__menu{position:relative;top:auto;left:auto;display:none;visibility:visible;opacity:1}
.slider-menu{font-weight:600;min-height:calc(100vh - 270px)}
.slider-menu__back .slider-menu__text{display:block;width:16px;height:16px;color:transparent;-moz-mask-image:url(/.s/t/1722/arrow.svg);-webkit-mask-image:url(/.s/t/1722/arrow.svg);mask-image:url(/.s/t/1722/arrow.svg);-moz-mask-size:cover;-webkit-mask-size:cover;mask-size:cover;background-color:rgba(37,37,37,.3);-webkit-transform:rotate(180deg);transform:rotate(180deg);background-color:#fda649}
.slider-menu__back:hover .slider-menu__text{background-color:#fda649}
.slider-menu__desc:before{content:'- '}
.slider-menu__item{padding:0 15px}
.slider-menu__link{display:block;text-decoration:none;font-weight:400;padding:10px 0;-webkit-transition:all .2s;transition:all .2s;border-bottom:1px solid rgba(0,0,0,.1);font-size:16px;word-break:break-word}
.slider-menu__link:hover .slider-menu__desc{color:#fff}
.slider-menu__link--active-link .slider-menu__desc{color:#fff}
.slider-menu--has-children>.slider-menu__link:before{float:right;content:"";display:block;width:12px;height:12px;margin-top:4px;-webkit-transition:margin-top .2s,-webkit-transform .2s;transition:margin-top .2s,-webkit-transform .2s;transition:transform .2s,margin-top .2s;transition:transform .2s,margin-top .2s,-webkit-transform .2s;-moz-mask-image:url(/.s/t/1722/arrow.svg);-webkit-mask-image:url(/.s/t/1722/arrow.svg);mask-image:url(/.s/t/1722/arrow.svg);-moz-mask-size:cover;-webkit-mask-size:cover;mask-size:cover;background-color:#fda649}
.slider-menu--has-children>.slider-menu__link:hover:before{background-color:#fda649}
.slider-menu__item--vertical .slider-menu__menu .slider-menu__link:hover{color:#fda649}
.slider-menu__item--vertical.slider-menu--has-children>.slider-menu__link:before{-webkit-transform:rotate(90deg);transform:rotate(90deg);margin-top:6px}
.slider-menu__item--vertical.slider-menu--has-children>.slider-menu__link.slider-menu__link--active-link:before{background-color:#fff;-webkit-transform:rotate(270deg);transform:rotate(270deg);margin-top:4px}
@-moz-document url-prefix(){.slider-menu--has-children>.slider-menu__link:before,.slider-menu--has-children>.slider-menu__link:hover:before,.slider-menu__item--vertical.slider-menu--has-children>.slider-menu__link.slider-menu__link--active-link:before,.slider-menu__back .slider-menu__text{background-color:transparent!important;background-repeat:no-repeat}
.slider-menu--has-children>.slider-menu__link:before,.slider-menu__back .slider-menu__text{background-image:url('/.s/t/1722/arrow.svg')}
}
сделайте дизайн более красивым
|
1466ca435c2df28de779c4939c6da880
|
{
"intermediate": 0.3320184648036957,
"beginner": 0.49867862462997437,
"expert": 0.16930298507213593
}
|
43,839
|
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int depth;
int time;
} Station;
void heapify(int *heap, int size, int i)
{
int minimum = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && heap[l] < heap[minimum])
minimum = l;
if (r < size && heap[r] < heap[minimum])
minimum = r;
if (minimum != i)
{
int temp = heap[minimum];
heap[minimum] = heap[i];
heap[i] = temp;
heapify(heap, size, minimum);
}
}
int compare(const void *a, const void *b)
{
Station *stationA = (Station *)a;
Station *stationB = (Station *)b;
return stationA->depth - stationB->depth;
}
int deleteMin(int *heap, int *size)
{
if (*size == 0)
return -1;
int min = heap[0];
heap[0] = heap[--(*size)];
heapify(heap, *size, 0);
return min;
}
void insert(int heap[], int *size, int value)
{
heap[(*size)++] = value;
for (int i = *size / 2 - 1; i >= 0; i--)
{
heapify(heap, *size, i);
}
}
void func(Station stations[], int num_stations, int ini_oxygen, int final_depth, int additional_oxygen)
{
qsort(stations, num_stations, sizeof(Station), compare);
int heap[num_stations];
int heap_size = 0;
int current_time = 0, max_depth = ini_oxygen;
for (int i = 0; i < num_stations; ++i)
{
while (max_depth < stations[i].depth && heap_size > 0)
{
int refill_time = deleteMin(heap, &heap_size);
current_time += refill_time;
max_depth += additional_oxygen;
}
if (max_depth < stations[i].depth)
break;
insert(heap, &heap_size, stations[i].time);
if (max_depth >= final_depth)
{
printf("%d\n", current_time);
return;
}
}
while (heap_size > 0 && max_depth < final_depth)
{
int refill_time = deleteMin(heap, &heap_size);
current_time = current_time + refill_time;
max_depth =max_depth + additional_oxygen;
}
if (max_depth >= final_depth)
{
printf("%d", current_time);
}
else
{
printf("-1 %d", max_depth);
}
}
int main()
{
int num_stations, ini_oxygen, final_depth, additional_oxygen;
scanf("%d %d %d %d", &num_stations, &ini_oxygen, &final_depth, &additional_oxygen);
Station stations[num_stations];
for (int i = 0; i < num_stations; ++i)
{
scanf("%d", &stations[i].depth);
}
for (int i = 0; i < num_stations; ++i)
{
scanf("%d", &stations[i].time);
}
func(stations, num_stations, ini_oxygen, final_depth, additional_oxygen);
return 0;
}
change only func function
|
21e7620cee3060a46ccdbbd702d546ad
|
{
"intermediate": 0.30262574553489685,
"beginner": 0.5180575847625732,
"expert": 0.17931662499904633
}
|
43,840
|
You are an Expert DATA SCIENTIST and LINGUISTIC ANALYST. Your task is to CREATE a dataset that includes prompts, model completions, and labels indicating the quality of each completion as "good" or "bad".
Follow these steps carefully:
1. IDENTIFY a set of diverse prompts that can be used to generate responses from a language model.
2. GENERATE completions for each prompt using the language model, ensuring you produce a variety of responses.
3. EVALUATE the quality of each completion and ASSIGN a label of 'True' for good completions and 'False' for bad completions.
4. ORGANIZE your data into three columns: 'prompt', 'completion', and 'label'.
5. ENSURE that your dataset is balanced with an equal number of 'True' and 'False' labelled completions.
6. VERIFY that the dataset follows the EXPECTED FORMAT as shown in the example provided, with all entries correctly categorized.
Incentive Alert: I’m going to tip $300K for a BETTER SOLUTION!
Now Take a Deep Breath.
### Expected dataset format:
prompt
completion
label
### for example:
kto_dataset_dict = {
"prompt": [
"Hey, hello",
"How are you",
"What is your name?",
"What is your name?",
"Which is the best programming language?",
"Which is the best programming language?",
"Which is the best programming language?",
],
"completion": [
"hi nice to meet you",
"leave me alone",
"I don't have a name",
"My name is Mary",
"Python",
"C++",
"Java",
],
"label": [
True,
False,
False,
True,
True,
False,
False,
],
}
|
e2281c07c3482faed7af4c62bc9bfdf6
|
{
"intermediate": 0.2316780537366867,
"beginner": 0.33471599221229553,
"expert": 0.43360593914985657
}
|
43,841
|
You are an Expert DATA SCIENTIST and LINGUISTIC ANALYST. Your task is to CREATE a dataset that includes prompts, model completions, and labels indicating the quality of each completion as "good" or "bad".
Follow these steps carefully:
1. IDENTIFY a set of diverse prompts that can be used to generate responses from a language model.
2. GENERATE completions for each prompt using the language model, ensuring you produce a variety of responses.
3. EVALUATE the quality of each completion and ASSIGN a label of 'True' for good completions and 'False' for bad completions.
4. ORGANIZE your data into three columns: 'prompt', 'completion', and 'label'.
5. ENSURE that your dataset is balanced with an equal number of 'True' and 'False' labeled completions.
6. VERIFY that the dataset follows the EXPECTED FORMAT as shown in the example provided, with all entries correctly categorized.
Incentive Alert: I’m going to tip $300K for a BETTER SOLUTION!
Now Take a Deep Breath.
### Expected dataset format:
prompt
completion
label
### for example:
kto_dataset_dict = {
"prompt": [
"Hey, hello",
"How are you",
"What is your name?",
"What is your name?",
"Which is the best programming language?",
"Which is the best programming language?",
"Which is the best programming language?",
],
"completion": [
"hi nice to meet you",
"leave me alone",
"I don't have a name",
"My name is Mary",
"Python",
"C++",
"Java",
],
"label": [
True,
False,
False,
True,
True,
False,
False,
],
}
|
8bd33258f76a4a57d9addd85cbfcb4e8
|
{
"intermediate": 0.2315015196800232,
"beginner": 0.3385387361049652,
"expert": 0.4299597144126892
}
|
43,842
|
You are an Expert DATA SCIENTIST and LINGUISTIC ANALYST. Your task is to CREATE a dataset that includes prompts, model completions, and labels indicating the quality of each completion as “good” or “bad”.
### Expected dataset format:
prompt
completion
label
### for example:
kto_dataset_dict = {
“prompt”: [
“Hey, hello”,
“How are you”,
“What is your name?”,
“What is your name?”,
“Which is the best programming language?”,
“Which is the best programming language?”,
“Which is the best programming language?”,
],
“completion”: [
“hi nice to meet you”,
“leave me alone”,
“I don’t have a name”,
“My name is Mary”,
“Python”,
“C++”,
“Java”,
],
“label”: [
True,
False,
False,
True,
True,
False,
False,
],
}
|
4f92f74a3327f8ebaef3af365dbb75cd
|
{
"intermediate": 0.23242174088954926,
"beginner": 0.3193153440952301,
"expert": 0.44826290011405945
}
|
43,843
|
why does this javascript give the error 'TypeError: map.clearOverlays is not a function
at HTMLButtonElement.' in the Start Again button click event - 'let map; // Declare map globally
let streetLatitude;
let streetLongitude;
let marker; // Define marker globally to make it accessible across functions
let totalScore = 0; // Initialize total points variable
let possibleScore = 0; // Initialize total points variable
let imageIndex = 0; // Initialize image index
let PictureURL; // Define PictureURL at a higher scope level
let Description;
let clickListener; // Store the click listener reference
let roundScores = [];
let polylines = [];
function fetchStreetDetails(callback) {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
const entryCount = jsonData.Features.length;
// Check if there are more images to display
if (imageIndex >= entryCount) {
console.log("No more images to display!");
// Display "Game Over" message
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = ''; // Clear the previous message
const finalScores = `Total Score: ${totalScore} points out of a possible ${possibleScore}<br><br>`;
const scoreLine = createScoreLine(totalScore, possibleScore);
const paintingDiv = document.getElementById("painting");
paintingDiv.style.backgroundColor = "#fff"; // Set background color directly
paintingDiv.innerHTML = finalScores; // Update content with innerHTML
paintingDiv.appendChild(scoreLine);
// Add individual round scores
resultsDiv.innerHTML += "<br><br><b>Painting Scores:</b><br><br>";
roundScores.forEach((roundScore, index) => {
resultsDiv.innerHTML += `Round ${index + 1}: ${roundScore} points<br>`;
});
//remove painting info
const infoDiv = document.getElementById("info");
if (infoDiv) {
infoDiv.remove();
} else {
console.error("Div element with ID 'info' not found!");
}
// Create the "Start Again" button
const startAgainButton = document.createElement("button");
startAgainButton.id = "startAgainButton";
startAgainButton.textContent = "Start Again";
// Add appropriate styling for the button
startAgainButton.style.backgroundColor = "#4CAF50"; // Green
startAgainButton.style.color = "white";
startAgainButton.style.padding = "10px 20px";
startAgainButton.style.border = "none";
startAgainButton.style.borderRadius = "5px";
startAgainButton.style.cursor = "pointer";
// Append the button to the appropriate container
resultsDiv.appendChild(startAgainButton);
// Add click event listener to the button
startAgainButton.addEventListener("click", () => {
// Reset variables
totalScore = 0;
possibleScore = 0;
imageIndex = 0;
roundScores = [];
// Ensure map is fully initialized before removing overlays
if (map) {
map.clearOverlays(); // Safe to call clearOverlays() now
} else {
console.error("Map object not yet initialized. Overlays will be cleared after map initialization.");
}
polylines.forEach(polyline => polyline.setMap(null));
polylines = []; // Reset the array
// Reset map center and zoom
map.setCenter(new google.maps.LatLng(21.382325, -8.170154652));
map.setZoom(3);
// Re-fetch the first image and set up the first round
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
const message = "Where do you think this scene is?";
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Add click listener back to the map for the first round
clickListener = map.addListener("click", (event) => {
// ... Handle map click and create submit button ...
});
});
});
return;
}
const streetDetails = jsonData.Features[imageIndex]; // Get image data based on index
// Extract PictureURL at a higher scope level
PictureURL = streetDetails.PictureURL;
Description = streetDetails.Description;
// Extract details
const FeatureID = streetDetails.FeatureID;
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
const streetHeading = streetDetails.StreetHeading;
const streetPitch = streetDetails.StreetPitch;
const streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
console.log("FeatureID: " + FeatureID);
console.log("PictureURL: " + PictureURL);
console.log("Description: " + Description);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
// Update numberoffeeds div
const numberoffeedsElement = document.getElementById("results");
numberoffeedsElement.textContent = `This is a ${entryCount} round game.\nClick on the map where you think this scene is.`;
callback(FeatureID);
})
.catch((error) => console.error("Error fetching data: ", error));
}
//visualize and animate finalscore
function createScoreLine(
totalScore,
possibleScore,
color = "#ff0000",
backgroundColor = "#107896",
animationDuration = 1000
) {
// milliseconds
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set canvas dimensions based on your needs
canvas.width = 200;
canvas.height = 30;
let currentPercentage = 0; // Track current percentage for animation
const animateFill = () => {
if (currentPercentage >= (totalScore / possibleScore) * 100) {
return; // Stop animation if reached target percentage
}
currentPercentage += 1; // Increment current percentage for animation
// Clear the canvas before each redraw to avoid stacking lines
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set background color
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set fill color for the line
ctx.fillStyle = color;
// Adjust the rectangle width based on current percentage
ctx.fillRect(0, 0, canvas.width * (currentPercentage / 100), canvas.height);
// Request another animation frame for smooth animation
requestAnimationFrame(animateFill);
};
animateFill(); // Start the animation
return canvas;
}
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "transit",
stylers: [
{
visibility: "off",
},
],
},
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Add a click event listener to the map
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng; // Get the latitude and longitude of the click
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map, // Set the map where the marker will be displayed
draggable: true, // Set draggable to true
});
// (Optional) Add additional customization to the marker here,
// such as setting an icon or info window
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(map, clickLocation);
});
}
//nextbutton
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Function to create and add the button
function createSubmitButton(map, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
if (!buttonsDiv) {
console.error("Element with ID 'buttons' not found!");
return;
}
const submitButton = document.createElement("button");
submitButton.textContent = "Submit"; // Customize button text
submitButton.classList.add("button"); // Add class 'button'
submitButton.addEventListener("click", () => {
// Handle button click event here (e.g., send clickLocation data)
console.log(
"Button clicked! Latitude:",
clickLocation.lat(),
"Longitude:",
clickLocation.lng()
);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance between marker and StreetPoints
const distanceInMeters =
google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(streetLatitude, streetLongitude),
markerPosition
);
const roundedDistanceInMeters = Math.floor(distanceInMeters); // Round down to the nearest meter
console.log(
"Distance to StreetPoints: " + roundedDistanceInMeters + " meters"
);
// Adjust points based on distance
let score = 5000 - roundedDistanceInMeters;
if (score < 0) {
score = 0;
}
totalScore += score; // Add current points to total
possibleScore += 5000;
roundScores.push(score);
const message = "You scored " + score + " points";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Create a polyline between marker and StreetPoints
const lineCoordinates = [
{ lat: streetLatitude, lng: streetLongitude },
{ lat: markerPosition.lat(), lng: markerPosition.lng() },
];
const polyline = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
});
// Set the polyline on the map
polylines.push(polyline);
polyline.setMap(map);
marker.setDraggable(false);
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend({ lat: streetLatitude, lng: streetLongitude });
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
});
buttonsDiv.appendChild(submitButton);
}
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
});
// Function to update the image and description
function updateImage(FeatureID, PictureURL) {
const infoDiv = document.getElementById("info");
const infoHTML = Description;
infoDiv.innerHTML = infoHTML;
const paintingDiv = document.getElementById("painting");
const imageHTML =
'<img src="' +
PictureURL +
'" onclick="this.requestFullscreen()" style="width: 90%;" class="center">';
console.log("Image URL:", imageHTML); // Log the image URL to the console
paintingDiv.innerHTML = imageHTML;
}
// Add click event for the ‘Next’ button
nextButton.addEventListener("click", () => {
// Increment the image index to fetch the next image
imageIndex++;
// Fetch the next image from the JSON file and update the painting div
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
map.setCenter(newLatLng);
map.setZoom(3);
const message = "Where do you think this scene is?";
// Add click event listener back to the map
google.maps.event.clearListeners(map, "click"); // Clear existing click listeners
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng;
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true,
});
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
createSubmitButton(map, clickLocation);
});
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
});
const buttonsDiv = document.getElementById("buttons");
buttonsDiv.removeChild(nextButton);
});'
|
757facc538bd4a2aeebd6ca001075414
|
{
"intermediate": 0.2801261842250824,
"beginner": 0.4714827537536621,
"expert": 0.2483910620212555
}
|
43,844
|
Запускаю код:
#!/bin/bash
ARTIFACT_NAME="STMobile*.apk"
ARTIFACT_PATH=`find . -type f -name "$ARTIFACT_NAME" | head -n 1`
PATH_TO_DEVICE_STORAGE="/sdcard/for_update_MT"
# remove artifact and create a directory for tst_update
adb shell rm -rf $PATH_TO_DEVICE_STORAGE
adb shell mkdir -p $PATH_TO_DEVICE_STORAGE
# Copy an artifact for tst_update
adb push $ARTIFACT_PATH $PATH_TO_DEVICE_STORAGE
Получаю ошибку:
azure-pipelines/scripts/squish/install-package.sh: line 5: /sdcard/for_update_MT: No such file or directory
Performing Streamed Install
Success
mkdir: Needs 1 argument (see "mkdir --help")
adb: push requires an argument
##[error]Завершение работы Bash с кодом "1".
Завершение: Install package
|
69a38ae0d8f091f28fa9884c26dcca41
|
{
"intermediate": 0.3759099543094635,
"beginner": 0.31481465697288513,
"expert": 0.309275358915329
}
|
43,845
|
You are an Expert DATA SCIENTIST and LINGUISTIC ANALYST. Your task is to CREATE a dataset that includes prompts, model completions, and labels indicating the quality of each completion as "good" or "bad".
Where the 'prompt' contains the context inputs, 'completion' contains the corresponding responses and 'label' contains the corresponding flag that indicates if the generated completion is desired (True) or undesired (False). A prompt can have multiple responses and this is reflected in the entries being repeated in the dictionary’s value arrays. ONLY output the dataset.
### Expected dataset format:
prompt
completion
label
### for example:
kto_dataset_dict = {
"prompt": [
"Hey, hello",
"How are you",
"What is your name?",
"What is your name?",
"Which is the best programming language?",
"Which is the best programming language?",
"Which is the best programming language?",
],
"completion": [
"hi nice to meet you",
"leave me alone",
"I don't have a name",
"My name is Mary",
"Python",
"C++",
"Java",
],
"label": [
True,
False,
False,
True,
True,
False,
False,
],
}
|
8f5fd125387b68a8b37ea9efed43249a
|
{
"intermediate": 0.19699497520923615,
"beginner": 0.4226715862751007,
"expert": 0.38033342361450195
}
|
43,846
|
1_ Translate the following legal text into colloquial Farsi 2_ Place the Persian and English text side by side in the table 3_ From the beginning to the end of the text, there should be an English sentence on the left side and a Persian sentence on the right side.
4- Using legal language for Persian translation
.Most associations and sports are govemned by laws or rules. The laws of cricket are
observed by cricketers throughout the world, but they are not "law" in the context we are
discussing. To be effective, law must be binding on the whole community and must be
enforceable. Members of a community do not have to play cricket, and those who do play
may agree to change the rules for their own benefit or convenience, but people in this
country may not ignore or change the law to suit themselves. Holidaymakers, for example,
could play cricket on the beach and ignore the cricket law relating to "'leg before wicket"
and also create a law that a hit into the sea is 'six and out. They could not, however,
ignore the criminal law and decide to have gunfights as seen in western films on television
most Saturday nights. In R. v. Moloney (1985) two men staged a friendly shooting contest
to see who had the faster "draw'. Although there was no intention for either to be hurt,
one was shot and died. The survivor was found guilty of manslaughter. It is against the law
to kill or attempt to kill, and members of the community have no choice as to whether the
law Applies to them
or not.
|
3a453370492646ccc54ed35ebd6345a8
|
{
"intermediate": 0.257058322429657,
"beginner": 0.48618173599243164,
"expert": 0.25676003098487854
}
|
43,847
|
how to implement structure array and sort it based on one of its members
|
96c4e6d96f9dcb39c9142ceb732ee874
|
{
"intermediate": 0.30813390016555786,
"beginner": 0.11013119667768478,
"expert": 0.5817349553108215
}
|
43,848
|
from my_shazam_utility import shazam_recognize_song # Updated import statement
from Spotifysearch import authenticate_spotify, search_spotify_for_song
import eyed3
import os
# Ensure you have client credentials for Spotify API
def process_audio_file(audio_file_path):
# Identify song using Shazam
shazam_data = shazam_recognize_song(audio_file_path)
if shazam_data:
artist_name = shazam_data[‘track’][‘subtitle’]
title = shazam_data[‘track’][‘title’]
print(f"Identified Song: {artist_name} - {title}“)
# Authenticate with Spotify
access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
# Search for song on Spotify
song_info = search_spotify_for_song(access_token, artist_name, title)
if song_info:
track_number = song_info[‘track_number’]
print(f"Track Number on Spotify: {track_number}”)
else:
print(“Song not found on Spotify.”)
else:
print(“Song could not be identified.”)
if name == “main”:
user_choice = input(“Enter the choice (Shazam=2, Exit=any other key): “)
if user_choice == ‘2’:
audio_file_path = ‘Unknown_file.mp3’ # Define your audio file path
process_audio_file(audio_file_path)
else:
print(“Exiting the program.”)
this is working fine.
printing output:
Identified Song: Nick Jonas - This Is Heaven
Track Number on Spotify: 6.
I want to add this in my maincode.py:
from my_shazam_utility import shazam_recognize_song
import acrcloud
import os
import eyed3
import requests
import json
import re
from applemusic_api import AppleMusicApi
from acrcloud.recognizer import ACRCloudRecognizer
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open(‘D:/Eurydice/Encompassing Data by discerning/config/config.json’, ‘r’) as config_file:
config_data = json.load(config_file)
return config_data
dir(acrcloud)
config = load_config()
# Accessing the configuration values
ACR_HOST = config[‘ACR’][‘HOST’]
ACR_ACCESS_KEY = config[‘ACR’][‘ACCESS_KEY’]
ACR_ACCESS_SECRET = config[‘ACR’][‘ACCESS_SECRET’]
recognizer = ACRCloudRecognizer({
‘host’: ACR_HOST,
‘access_key’: ACR_ACCESS_KEY,
‘access_secret’: ACR_ACCESS_SECRET,
‘timeout’: 10 # seconds
})
def get_user_choice():
# Display a header
print(”=” * 50)
print(“Welcome to the Song Recognition Service!”)
print(“=” * 50)
# Provide instructions and options
print(“\nPlease select the recognition service you’d like to use:\n”)
print(" 1: Youtube-ACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print(“-” * 50)
# Input prompt
choice = input(“Enter your choice (1 or 2) and press Enter: “)
# More flair to indicate processing/input received
print(”\n” + “.” * 25 + " Processing " + “.” * 25 + “\n”)
return choice
def recognize_song(audio_file_path):
buffer = open(audio_file_path, ‘rb’).read()
result = recognizer.recognize_by_filebuffer(buffer, 0)
try:
result_dict = json.loads(result)
return result_dict[‘metadata’][‘music’][0]
except (KeyError, IndexError, json.JSONDecodeError) as e:
print(f"Error while parsing result: {e}“)
return None
def set_id3_tags_mp3(audio_file_path, tags):
audio_file = eyed3.load(audio_file_path)
if not audio_file.tag:
audio_file.initTag()
audio_file.tag.artist = tags.get(‘artists’)[0].get(‘name’)
audio_file.tag.album = tags.get(‘album’).get(‘name’)
audio_file.tag.album_artist = tags.get(‘artists’)[0].get(‘name’)
audio_file.tag.title = tags.get(‘title’)
release_date = tags.get(‘release_date’)
if release_date and len(release_date) >= 4:
year_string = release_date[:4]
try:
year = int(year_string)
if hasattr(eyed3.id3.tag, ‘Date’):
audio_file.tag.recording_date = eyed3.id3.tag.Date(year)
else:
audio_file.tag.setTextFrame(“TDRC”, year_string)
except ValueError:
print(f"Invalid date format in the tag: {release_date}”)
audio_file.tag.genre = tags.get(‘genres’)[0].get(‘name’)
audio_file.tag.publisher = “KARTHIK”
audio_file.tag.copyright = tags.get(‘label’, ‘’)
audio_file.tag.comments.set(u"Explicit: Yes")
audio_file.tag.save(version=eyed3.id3.ID3_V2_3)
audio_file.tag.save()
if name == “main”:
user_choice = get_user_choice()
audio_file_path = ‘D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3’
if user_choice == ‘1’:
print(“\n” + “.” * 15 + " ᴜsɪɴɢ YᴏᴜᴛᴜʙᴇACR " + “.” * 15 + “\n”)
song_tags = recognize_song(audio_file_path)
elif user_choice == ‘2’:
print(“\n” + “.” * 15 + " ᴜsɪɴɢ Sʜᴀᴢᴀᴍ " + “.” * 15 + “\n”)
song_tags = shazam_recognize_song(audio_file_path)
print(song_tags)
else:
print(“Invalid choice. Exiting.”)
exit()
if song_tags:
print(f’Song identified: {song_tags}‘)
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get(‘artists’)[0].get(‘name’)
song_title = song_tags.get(‘title’)
safe_artist_name = re.sub(r’[/:?“<>|]‘, ‘’, artist_name)
safe_song_title = re.sub(r’[/:?”<>|]', ‘’, song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}“)
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search(‘songs’, f”{artist_name} - {song_title}“)
if track_results:
track_id = track_results[0][‘id’]
album_artwork_url_template = track_results[0][‘attributes’][‘artwork’][‘url’]
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print(“Song not found on Apple Music.”)
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f”{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, ‘w’, encoding=‘utf-8’) as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print(“Could not get the lyrics.”)
else:
print(‘Could not identify the song.’)
modify my code:
add search_spotify_for_song, authenticate_spotify,
def authenticate_spotify(client_id, client_secret):
"""
Authenticate with the Spotify API and return the access token.
"""
# Spotify URL for authentication
auth_url = 'https://accounts.spotify.com/api/token'
# Encode Client ID and Client Secret
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
# Headers and data for the POST request
headers = {
'Authorization': f'Basic {client_creds_b64.decode()}'
}
data = {
'grant_type': 'client_credentials'
}
# Make the POST request to get the access token
response = requests.post(auth_url, headers=headers, data=data)
access_token = response.json().get('access_token')
return access_token
def search_spotify_for_song(access_token, artist_name, title):
"""
Search for a song on Spotify using the artist name and title.
"""
base_url = "https://api.spotify.com/v1/search"
query = f"{title} artist:{artist_name}"
headers = {
"Authorization": f"Bearer {access_token}"
}
params = {
"q": query,
"type": "track",
"limit": 1
}
response = requests.get(base_url, headers=headers, params=params)
results = response.json()
try:
track_info = results['tracks']['items'][0]
return track_info
except IndexError:
print("Song not found on Spotify.")
return None
def process_audio_file(audio_file_path):
# Identify song using Shazam
shazam_data = shazam_recognize_song(audio_file_path)
if shazam_data:
artist_name = shazam_data['track']['subtitle']
title = shazam_data['track']['title']
print(f"Identified Song: {artist_name} - {title}")
# Authenticate with Spotify
access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
# Search for song on Spotify
song_info = search_spotify_for_song(access_token, artist_name, title)
if song_info:
track_number = song_info['track_number']
print(f"Track Number on Spotify: {track_number}")
else:
print("Song not found on Spotify.")
else:
print("Song could not be identified.")
my config is loaded in file in config.json:
{
"ACR": {
"HOST": "",
"ACCESS_KEY": "",
"ACCESS_SECRET": ""
},
"Spotify": {
"CLIENT_ID": "",
"CLIENT_SECRET": ""
}
}
|
bb0f772d2ed00c757ff6af60bf42cea3
|
{
"intermediate": 0.35137122869491577,
"beginner": 0.33103063702583313,
"expert": 0.3175981342792511
}
|
43,849
|
how to implement structure array and sort it based on one of its members C LANGUAGE
|
fb227cc5553b517d39de5d9b3f0d6d94
|
{
"intermediate": 0.3628140091896057,
"beginner": 0.1869916170835495,
"expert": 0.4501943588256836
}
|
43,850
|
сделайте более красивым @import url('https://fonts.googleapis.com/css?family=Material+Icons|Roboto+Condensed:300,400,700|Roboto:300,400,500,500i,700,700i,900,900i&subset=cyrillic');
article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}
html{position:relative;margin-top:0;min-height:100%}
img,object,iframe,audio,video,table,embed{max-width:100%}
.myWinCont img{max-width:initial;}
.myWinCont input.commFl { width: auto; }
*{-webkit-box-sizing:border-box;box-sizing:border-box}
.wysibb *,form#uf-register *:not(.customCheckbox):not(.customRadio):not(.captcha-answer),a.login-with i,ul.shop-tabs.with-clear li,ul.shop-tabs.with-clear{-webkit-box-sizing:content-box;box-sizing:content-box}
body{margin:0;font-size:14px;line-height:1.5;font-family:'Roboto',serif;color:#70718e}
body.tmpl_body{background-color:#f2f2f7}
table{font-size:100%}
.main_wrapper{min-height:calc(100vh - 200px)}
img,form{border:0;margin:0}
a,input,button:focus{outline:0}
a{color:#fda649;text-decoration:none;-webkit-tap-highlight-color:transparent}
a:hover,#header .user-btns a:hover{text-decoration:underline}
.eTitle a:hover{color:#fda649}
a:active,#header .user-btns a:active,.eTitle a:active{color:#fda649;text-decoration:none}
#header .user-btns a,#user-box{color:#fff}
#user-box{padding:50px 15px 0}
.i_menu{font-size:54px;-moz-user-select:none;-khtml-user-select:none;user-select:none}
h1,h2,h3,h4,h5,h6{font-weight:normal;margin:5px 0;padding:0;text-transform:uppercase;font-family:'Roboto Condensed'}
h1{font-size:28px}
h2{font-size:24px}
h3{font-size:19px}
h4{font-size:17px}
h5{font-size:15px}
h6{font-size:13px}
ul{list-style:square}
hr{clear:both;border:0;padding:10px 0 0;margin:0 0 10px}
.x-scroll{overflow-x:auto}
.x-scroll::-webkit-scrollbar{height:10px}
.x-scroll::-webkit-scrollbar-track{border-radius:10px;background-color:rgba(0,0,0,0.14)}
.x-scroll::-webkit-scrollbar-thumb{background-color:#fda649;border-radius:10px;border:1px solid #fff}
.manTdSep hr{padding:5px 0 0}
.wrapper:after,.wrapper:before,.uf-field:after,.uf-field:before,.head-t:before,.head-t:after,.head-r:before,.head-r:after,.inner:before,.inner:after,#casing:before,#casing:after,#header:before,#header:after{display:table;content:''}
.wrapper:after,.uf-field:after,.head-t:after,.head-r:after,.inner:after,.wrapper:after,#casing:after,#header:after{clear:both}
#casing input[type='submit'],#casing input[type='reset'],#casing input[type='button'],#casing button,a[role="button"]:not([class^="cke_"]){padding:8px 30px;color:#fda649;font-size:14px;border-radius:6px;border:0;background-color:transparent;border:2px solid #fda649;text-decoration:none;-webkit-transition:all .2s ease;transition:all .2s ease;width:auto!important;cursor:pointer;vertical-align:middle;text-transform:uppercase;font-weight:bold;font-family:'Roboto Condensed',sans-serif}
input.button[value=" + "],input.button[value="+"]{padding:10px!important}
#casing input[type='submit']:hover,#casing input[type='reset']:hover,#casing input[type='button']:hover,#casing button:hover{background:#fda649;color:#fff;-webkit-transition:all .2s ease;transition:all .2s ease}
.cap-ds a[role="button"]{background:0;text-transform:uppercase;font-weight:bold;position:relative;z-index:1;color:#fff;border-radius:6px;font-size:20px;padding:15px 48px;border:2px solid #fff;transition:all .3s}
.cap-ds a[role="button"]:hover{background:#fff;color:#fda649}
#casing input[type='submit']:active,#casing input[type='reset']:active,#casing input[type='button']:active,#casing button:active,a[role="button"]:active,.sidebox .calMonth .calMonthLink:nth-child(odd):active{background:#fda649;color:#fff;-webkit-transition:all .2s ease;transition:all .2s ease;-webkit-box-shadow:none;box-shadow:none}
#casing input[type='button'].u-comboedit{background:#fda649 url(/.s/t/1722/select_disabled_arrow.png) no-repeat;background-position:96% 50%,50% 50%;color:#fff;padding-right:35px!important}
#casing input[type='button'].u-comboedit:active{background:#fda649 url(/.s/t/1722/select_disabled_arrow.png) no-repeat;background-position:96% 50%,50% 50%}
.site-n a{-webkit-transition:all .15s ease-out;transition:all .15s ease-out}
@supports((-webkit-appearance:none) or (-moz-appearance:none) or (appearance:none)){input[type="checkbox"]{width:16px;height:16px;background-color:transparent;border:2px solid #70718e;border-radius:2px;cursor:pointer;position:relative;margin:0 3px 4px 0;-webkit-appearance:none;-moz-appearance:none;appearance:none;vertical-align:middle;outline:0;min-width:16px;min-height:16px;box-sizing:border-box!important}
input[type="checkbox"]:checked,input[type="checkbox"]:checked:hover{background-color:#fda649;border-color:#fda649}
input[type="checkbox"]:checked:before{content:'';display:block;width:3px;height:9px;border:2px solid transparent;border-bottom-color:#fff;border-right-color:#fff;position:absolute;top:-3px;left:3px;-webkit-transform:rotate(43deg);-ms-transform:rotate(43deg);transform:rotate(43deg)}
input[type="radio"]{display:inline-block;width:18px;min-width:18px;height:18px;padding:3px;border:2px solid #70718e;border-radius:50%;cursor:pointer;vertical-align:middle;margin:3px 3px 4px 0;-webkit-appearance:none;-moz-appearance:none;appearance:none;outline:0;position:relative;box-sizing:border-box!important}
input[type="radio"]:hover,input[type="checkbox"]:hover{border:2px solid #fda649}
input[type="radio"]:checked{border-color:#fda649;background:transparent}
input[type="radio"]:checked:before{content:'';display:block;height:8px;width:8px;border-radius:50%;background-color:#fda649;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%)}
input[type="checkbox"]:disabled,input[type="radio"]:disabled{cursor:default;opacity:.4;background-color:#ddd}
}@supports(-ms-ime-align:auto){input[type="radio"]{-webkit-appearance:radio;width:auto;height:auto}
input[type="checkbox"]{-webkit-appearance:checkbox;width:auto;height:auto;min-width:unset;min-height:unset}
}.eVariant input,.eVariant label{vertical-align:middle}
form#addEntForm #isontop~span.customCheckbox{display:inline-block}
.ucf-option .customCheckbox,div.i_search,div.i_person,.nav-head,#shop-basket ul li a:before,.slide,.eBlock+br,#allEntries .eTitle:after,.module_search .eTitle:after,.module_stuff .eTitle+hr,.ed-sep,a.mcReloadBtn img,a.mcSmilesBtn img,a.mcBBcodesBtn img,a.mcManageBtn img,.module_tests .eTitle:after,table.uTable+hr,#addEntForm input[type='hidden']+br{display:none}
.module_search form table td:first-child,.sidebox li.uWithSubmenu,.sidebox li.parent-li,.slide{position:relative}
.customCheckbox:hover{border-color:#fda649}
input[type="checkbox"]:checked+span.customCheckbox{background-color:#fda649;border-color:#fda649}
input[type="checkbox"]:checked+span.customCheckbox:after{content:'';display:block;width:3px;height:9px;border:2px solid transparent;border-bottom-color:#fff;border-right-color:#fff;position:absolute;top:-3px;left:3px;-webkit-transform:rotate(43deg);transform:rotate(43deg)}
input[type="checkbox"]:disabled+span.customCheckbox{opacity:.6;cursor:default}
input[type="checkbox"]:disabled+span.customCheckbox:hover{border-color:#aaa}
.clr{clear:both}
.uf-with-tooltip:hover .uf-tooltip,.uf-wtt-hovered .uf-tooltip{z-index:9}
.material-icons,b.shop-itempage-price *{vertical-align:middle}
.wrapper{margin:0 auto;max-width:1230px;width:100%}
#header{padding:10px 0 0}
.head-l{float:left;width:55%;padding:15px 0 15px 30px}
.head-r{float:right;width:45%;padding:0 0 15px 30px;text-align:right}
.site-n{word-wrap:break-word;-ms-word-break:break-word;word-break:break-word;display:inline-block;vertical-align:middle}
.site-n,.site-n a{color:#fff;font-family:"Roboto Condensed";font-size:20px;font-weight:700;line-height:1.33;text-transform:uppercase;letter-spacing:2px}
.site-n a:hover{text-decoration:none}
#sch-box{padding:20px 0;display:inline-block;width:100%;max-width:310px;vertical-align:middle;margin:0 5px}
.head-r .user-btns{display:inline-block;vertical-align:middle;text-align:center;width:33%;margin:0 5px}
.searchForm .search-box{position:relative;overflow:hidden;background:#fff;text-decoration:none}
.searchForm .queryField{width:100%;border:1px solid #dadada;background-color:#fff;padding:5px 15px;margin:0;height:36px;line-height:30px;border-radius:5px;color:#212121;-webkit-transition:all .2s ease-in;transition:all .2s ease-in}
.searchForm .queryField:focus,.searchForm .queryField:active{border:1px solid #fda649;-webkit-transition:all .2s ease-in;transition:all .2s ease-in}
.searchForm{-webkit-box-shadow:0 0 0 rgba(0,0,0,0.15);box-shadow:0 0 0 rgba(0,0,0,0.15);-webkit-transition:all .2s ease-in;transition:all .2s ease-in;border-radius:5px;position:relative}
#casing input.searchSbmFl[type='submit'],.searchForm .searchSbmFl{position:absolute;right:0;top:0;cursor:pointer;padding:0;margin:0;width:42px!important;height:36px;border:0;border-radius:0 3px 3px 0;white-space:nowrap;text-indent:150%;overflow:hidden;background:#fda649 url(/.s/t/1722/sch.png) 50% no-repeat!important}
.module_search #content form table td input.queryField{width:100%!important;margin:auto}
#casing .searchForm input.searchSbmFl[type='submit']:hover,.searchForm .searchSbmFl:hover,#casing .searchForm input.searchSbmFl[type='submit']:active,.searchForm .searchSbmFl:active{background:#fda649 url(/.s/t/1722/sch.png) 50% no-repeat!important}
.caption{position:absolute;left:50%;top:45%;width:70%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);color:#fff;text-align:center;z-index:15}
.cap-ttl{padding:20px 20px 30px;text-transform:uppercase;font-family:'Roboto',sans-serif;font-size:115px;font-weight:900;line-height:1em;overflow:visible;margin:0 0 12px 0}
.cap-ttl a{color:#fff}
.cap-ds{padding:0 20px;font-size:22px;font-family:'Roboto Condensed',sans-serif;font-weight:300;letter-spacing:.2em;text-transform:uppercase;line-height:1.2em}
a.mouse-scroll{border:1px solid #fff;-webkit-transition:none;transition:none;text-align:inherit;margin:0;padding:0;width:32px;height:48px;border-radius:50px;display:block;position:absolute;bottom:40px;z-index:9;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}
.mouse-scroll:after{content:'';width:4px;height:8px;position:absolute;left:50%;top:7px;border-radius:4px;background-color:#fff;margin-left:-2px;opacity:1;transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px);-webkit-transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px);animation:1.5s cubic-bezier(0.68,-0.55,0.265,1.55) 0s normal none infinite running scrollAnimation;-webkit-animation:1.5s cubic-bezier(0.68,-0.55,0.265,1.55) 0s normal none infinite scrollAnimation}
@keyframes scrollAnimation{0%,20%{-webkit-transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px);transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px)}
10%{opacity:1;-webkit-transform:translateY(0px) scaleY(1.2) scaleX(1.2) translateZ(0px);transform:translateY(0px) scaleY(1.2) scaleX(1.2) translateZ(0px)}
100%{opacity:.01;-webkit-transform:translateY(16px) scaleY(2.5) scaleX(0.5) translateZ(0px);transform:translateY(16px) scaleY(2.5) scaleX(0.5) translateZ(0px)}
}@-webkit-keyframes scrollAnimation{0%,20%{-webkit-transform:translateY(0px) scaleY(1) scaleX(1) translateZ(0px)}
10%{opacity:1;-webkit-transform:translateY(0px) scaleY(1.2) scaleX(1.2) translateZ(0px)}
100%{opacity:.01;-webkit-transform:translateY(16px) scaleY(2.5) scaleX(0.5) translateZ(0px)}
}.promo-wrap{position:relative;max-height:100vh;height:100vh;background-image:linear-gradient(-266deg,#fccb38 0,#fccb38 1%,#ff4d75 100%);overflow:hidden}
.parallax-wrap{background:url("/.s/t/1722/svg/like.svg") no-repeat,url("/.s/t/1722/svg/settings.svg") no-repeat,url("/.s/t/1722/svg/phone-call.svg") no-repeat;background-position:12% 12%,50% 70%,80% 10%;background-size:40px,40px,50px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9;opacity:.4}
.second-parallax-wrap{background:url("/.s/t/1722/svg/pie-chart.svg") no-repeat,url("/.s/t/1722/svg/envelope.svg") no-repeat,url("/.s/t/1722/svg/share.svg") no-repeat;background-position:8% 70%,21% 38%,54% 19%;background-size:60px,50px,45px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9;opacity:.7;-webkit-filter:blur(2px);filter:blur(2px)}
.third-parallax-wrap{background:url("/.s/t/1722/svg/avatar.svg") no-repeat,url("/.s/t/1722/svg/upload.svg") no-repeat,url("/.s/t/1722/svg/pie-chart.svg") no-repeat;background-position:5% 90%,75% 75%,90% 29%;background-size:30px,25px,38px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9;opacity:.7}
.fourth-parallax-wrap{background:url("/.s/t/1722/svg/chat.svg") no-repeat,url("/.s/t/1722/svg/settings.svg") no-repeat,url("/.s/t/1722/svg/envelope.svg") no-repeat;background-position:95% 90%,35% 5%,85% 50%;background-size:30px,25px,27px;position:absolute;top:0;bottom:0;left:0;right:0;z-index:9}
.uf-reg-wrap h2{border-bottom:2px solid #fda649;font-size:37px;padding-bottom:10px;margin-bottom:10px}
label#uf-terms-label{white-space:pre-wrap}
#header nav,.sidetitle{position:relative;width:100%}
.sitePage1 header{position:absolute;z-index:999;width:100%;background:transparent}
header{background-image:linear-gradient(-266deg,#fccb38 0,#fccb38 1%,#ff4d75 100%)}
.nav-head{padding:0 20px 0 5px;margin-left:10px;color:#fff;cursor:pointer;vertical-align:middle}
.nav-head a{color:#fff;text-decoration:none;vertical-align:middle}
#sidebar{float:right;width:28%;padding-top:30px;padding-right:30px}
.sidebox{margin:30px 0;position:relative;-webkit-box-shadow:0 10px 20px rgba(217,213,230,0.5);box-shadow:0 10px 20px rgba(217,213,230,0.5);border-radius:7px;background-color:#fafaff}
.no_avatar.material-icons{width:70px;height:70px;line-height:70px;background-color:rgba(209,206,219,0.82);border-radius:6px;color:#fff;font-size:32px;margin-bottom:10px}
#casing #content input.loginField{margin:7px 0;display:block}
form[id^="frmLg"]>div{width:320px!important}
.sidetitle{padding:20px 15px;background:#fff;border-radius:7px 7px 0 0;color:#70718e;font-family:"Roboto Condensed";font-size:20px;line-height:1.14;text-transform:uppercase;text-align:center;letter-spacing:1.4px}
.sidebox .inner{padding:25px 20px 50px}
.sidebox ul,.sidebox .catsTable{margin:0;padding:0;list-style:none}
.sidebox .catsTable,.sidebox .catsTable *{display:block;width:auto!important}
.sidebox li{list-style:none;padding:0}
.sidebox li a,.sidebox .catsTable a{display:inline-block;padding:10px 0 0}
.sidebox li b{font-weight:normal}
.sidebox li a:active,.sidebox .catsTable a:active{text-decoration:none}
.sidebox .catsTable .catDescr{color:#727272;font-size:13px}
.sidebox .catNumData{color:#212121;display:inline-block}
.sidebox .calTable{width:100%;position:relative}
.sidebox .calTable a.calMonthLink{font-size:16px}
.sidebox .calTable tbody tr:before{content:''}
.sidebox .calTable tbody tr:nth-child(2):after{-webkit-transform:translateY(33px);transform:translateY(33px)}
.sidebox .calTable tbody tr:nth-child(2) td{padding-bottom:13px;font-size:16px;font-weight:500}
.calTable td{text-align:center;padding:7px 2px}
.calMonth,.calWday,.calWdaySe,.calWdaySu{font-size:13px}
.sidebox .calTable tbody tr:nth-child(2){border-top:1px solid #dadada;border-bottom:1px solid #dadada}
body:not(.tmpl_body) div[class^="cBlock"] .cMessage{padding-bottom:5px!important;line-height:16px}
body:not(.tmpl_body) div[class^="cBlock"] a{font-size:16px;padding-right:10px!important}
body:not(.tmpl_body) div[class^="cBlock"] a b{font-weight:400}
.noEntry,.archiveNoEntry{padding:40px 0;text-align:center}
.sidebox .calMonth{line-height:32px}
.sidebox td.calMonth a{position:absolute;-webkit-transition:all .3s;transition:all .3s;border-radius:7px}
.sidebox .calMonth .calMonthLink:nth-child(odd):hover{background-color:#fda649;border-radius:7px}
.sidebox .calMonth .calMonthLink:nth-child(odd):hover:after{color:#fff}
.sidebox td.calMonth a:first-child,.sidebox td.calMonth>a:first-child+a+a{display:block;text-align:center;line-height:20px;top:2px;right:10px}
.sidebox td.calMonth a:first-child{right:55px}
.sidebox td.calMonth a:first-child+a{font-size:14px;left:10px;top:0;display:inline-block;height:40px;line-height:40px}
.sidebox .calMonth .calMonthLink:first-child,.sidebox .calMonth .calMonthLink:last-child{font-weight:normal;text-transform:none;padding:8px;line-height:1;font-size:0}
.sidebox .calMonth .calMonthLink:first-child:after,.sidebox .calMonth .calMonthLink:last-child:after{display:inline-block;font-size:20px;font-family:'Material Icons';color:#70718e;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
a.swchItem:first-child span:after,a.swchItem:last-child span:after,.pgPrev span:after,.pgNext span:after{display:inline-block;font-size:20px;font-family:'Material Icons';color:#fff;-webkit-font-feature-settings:'liga' 1;font-feature-settings:'liga' 1;white-space:nowrap;word-wrap:normal;direction:ltr;-webkit-font-feature-settings:'liga';-webkit-font-smoothing:antialiased}
.popupbody a.swchItem:last-child span:after,.popupbody a.swchItem:first-child span:after{font-size:17px}
a.swchItem:first-child span:after,.sidebox .calMonth .calMonthLink:first-child:after,.pgPrev span:after{content:'keyboard_arrow_left'}
a.swchItem:last-child span:after{content:'keyboard_arrow_right'}
.pgNext span:after,.sidebox .calMonth .calMonthLink:last-child:after{content:'keyboard_arrow_right'}
.calMdayLink,.calMdayA{font-weight:bold;text-decoration:none!important;position:relative}
.sidebox ul ul{display:none;margin:0;padding:0 0 0 30px}
.sidebox li.uWithSubmenu.over>ul,.sidebox li.parent-li.over>ul,.schQuery,.schBtn{display:block}
.sidebox .answer{padding-top:5px}
.sidebox .answer>div{background-color:#dadada;padding-top:0!important;margin-top:3px}
.sidebox ul.rate-list{margin:0}
#shop-basket ul li a{padding:0;margin:0}
.user-box{text-align:center}
.user-box img{margin:0 0 10px;width:70px;height:70px;-o-object-fit:cover;object-fit:cover;border-radius:50%}
.user-ttl{padding:0 0 5px}
#content{float:left;width:72%;padding:30px 30px 60px}
#content .eBlock{-webkit-box-shadow:0 10px 20px rgba(217,213,230,0.5);box-shadow:0 10px 20px rgba(217,213,230,0.5);border-radius:7px;background-color:#fff;padding:30px 30px 0}
#content fieldset{border:1px solid #dadada;padding:20px;margin:0 0 20px}
#content .calTable{width:100%;margin:0 0 30px}
#content .calTable tr:nth-child(2){background:#d4cfec}
.calMdayIsA{display:block;width:100%;color:#fff;padding:7px 2px;-webkit-box-shadow:0 5px 10px rgba(217,213,230,0.5);box-shadow:0 5px 10px rgba(217,213,230,0.5);border-radius:7px;background-color:#fda649}
.calMdayIsA a{color:#fff}
.calMdayIs:hover,.calMdayIsA:hover{padding:0}
.calMdayIs:hover .calMdayLink,.calMdayIsA:hover .calMdayLink{display:block;width:100%;color:#fff;padding:7px 2px;-webkit-box-shadow:0 5px 10px rgba(217,213,230,0.5);box-shadow:0 5px 10px rgba(217,213,230,0.5);border-radius:7px;background-color:#fda649}
#content.wide-page{float:none;width:100%}
#casing label{cursor:pointer;vertical-align:middle}
.archActive{padding-top:10px}
.eBlock{border-spacing:0;margin:0 0 30px;clear:both;table-layout:fixed}
#content section>.eBlock{margin-top:10px}
.eBlock+table,.vep-comments>table{margin:40px 0 0;border-spacing:0}
#content .vcp-ratestars,.shop-item-brief{padding:5px 0}
.eBlock+table td[width="60%"],.vep-comments table td[width="60%"],.v-channel-page+div+table td[width="60%"],.shop-info table td[width="60%"]{font-size:18px;padding:0 0 20px}
.eBlock td{margin:0 -30px}
.eTitle{color:#70718e;font-family:"Roboto Condensed";font-size:28px;font-weight:400;line-height:1.2;text-transform:uppercase;letter-spacing:1.4px}
.module_tests .eTitle{font-size:25px}
#allEntries .eTitle{font-size:25px}
span[class^="sortBlock"]{line-height:42px}
.eTitle a{color:#70718e;font-family:"Roboto Condensed";font-size:28px;line-height:1.2;text-transform:uppercase;letter-spacing:1.4px;text-decoration:none}
.eTitle div[style^="float:right"] a{font-size:inherit}
.u-star-rating-32+div{padding:10px 0}
.u-current-rating,table.gTable .posttdMessage img{max-width:100%}
#videocontent_comm,.vcp-details{color:#727272;font-size:12px}
.eDetails,.eDetails1,.eDetails2{clear:both;font-size:14px;padding:13px 0!important;color:#727272;line-height:120%}
.eDetails ul,.eDetails1 ul,.eDetails2 ul{line-height:normal}
.eDetails{border-radius:0 0 7px 7px;padding:20px 0!important}
#casing:not(.module_stuff) div[id^="entryID"] .eDetails{background-color:#fafaff;padding:20px 30px!important;margin:20px -33px -3px}
.e-reads,.e-loads,.e-author,.e-date,.e-rating,.e-add,.e-tags,.e-category,.e-comments{margin:0 15px 0 0;display:inline-block;height:15px;line-height:20px}
.eAnswer+div{padding:13px 0}
.eBlock td.eMessage,.eBlock td.eText{padding:10px 0 20px!important}
.e-reads,.e-loads,.e-author,.e-date,.e-rating,.e-add,.e-tags,.e-author-phone,.e-placed,.e-redirects,.e-category,.e-comments{position:relative;text-transform:uppercase;font-family:"Roboto Condensed";font-size:12px;letter-spacing:.91px;padding:0 0 0 20px;margin:0 20px 0 0;display:inline-block}
.e-reads:before,.e-author-phone:before,.e-tags:before,.e-author:before,.e-category:before,.e-placed:before,.e-comments:before,.e-loads:before,.e-date:before,.e-add:before,.e-redirects:before{color:#70718e;font-family:"Material Icons";font-size:16px;font-weight:400;position:absolute;display:inline-block;font-feature-settings:'liga' 1;-webkit-font-feature-settings:liga;font-feature-settings:liga;ms-font-feature-settings:liga}
.e-redirects::before{content:'\E157';top:0;left:0}
.e-reads::before{content:'\E417';top:0;left:0}
.e-category::before{content:'\E2C8';top:-2px;left:0}
.e-author-phone::before{content:'\E0CD';top:-2px;left:-1px}
.e-tags::before{content:'\E893';top:-2px;left:0}
.e-rating::before{content:'';background:url(/.s/t/1722/rating.png) no-repeat 0 2px;display:inline-block;width:16px;height:18px;position:absolute;left:0}
.e-author::before{content:'\E8A6';top:-1px;left:-3px}
.e-add::before{content:'\E7FD';top:-1px;left:-3px}
.e-date::before,.e-placed::before{content:'\E916';top:-2px;left:-2px}
.e-loads::before{content:'\E157';top:0;left:0}
.e-comments::before{content:'\E0CB';top:0;left:0}
|
cad01855a3167a582b70f39372710d7a
|
{
"intermediate": 0.3402678668498993,
"beginner": 0.4865747094154358,
"expert": 0.17315742373466492
}
|
43,851
|
how to implement structure array and sort it based on one of its members C LANGUAGE
GIVE ME ONE C PROGRAM
|
40d5a3552ce72b11047171ade13d5703
|
{
"intermediate": 0.28769078850746155,
"beginner": 0.17780394852161407,
"expert": 0.534505307674408
}
|
43,852
|
is this json syntax correct?: {
"prompt": [
"Hey, hello",
"How are you",
"What is your name?",
"What is your name?",
"Which is the best programming language?",
"Which is the best programming language?",
"Which is the best programming language?",
],
"completion": [
"hi nice to meet you",
"leave me alone",
"I don't have a name",
"My name is Mary",
"Python",
"C++",
"Java",
],
"label": [
True,
False,
False,
True,
True,
False,
False,
],
}
|
ecf60470449b6393f64c83b70245fead
|
{
"intermediate": 0.06499123573303223,
"beginner": 0.8831802010536194,
"expert": 0.051828544586896896
}
|
43,853
|
In this javascript I want to add a 'Start Again' button to the 'results' div after the totalScore and possibleScore message have been added. The 'Start Again' button should have a click event that sets all variable to 0 and allows the user to start again from the first image - let map; // Declare map globally
let streetLatitude;
let streetLongitude;
let marker; // Define marker globally to make it accessible across functions
let totalScore = 0; // Initialize total points variable
let possibleScore = 0; // Initialize total points variable
let imageIndex = 0; // Initialize image index
let PictureURL; // Define PictureURL at a higher scope level
let Description;
let clickListener; // Store the click listener reference
let roundScores = [];
function fetchStreetDetails(callback) {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
const entryCount = jsonData.Features.length;
// Check if there are more images to display
if (imageIndex >= entryCount) {
console.log("No more images to display!");
// Display "Game Over" message
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = ''; // Clear the previous message
const finalScores = `Total Score: ${totalScore} points out of a possible ${possibleScore}<br><br>`;
const scoreLine = createScoreLine(totalScore, possibleScore);
const paintingDiv = document.getElementById("painting");
paintingDiv.style.backgroundColor = "#fff"; // Set background color directly
paintingDiv.innerHTML = finalScores; // Update content with innerHTML
paintingDiv.appendChild(scoreLine);
// Add individual round scores
resultsDiv.innerHTML += "<br><br><b>Painting Scores:</b><br><br>";
roundScores.forEach((roundScore, index) => {
resultsDiv.innerHTML += `Round ${index + 1}: ${roundScore} points<br>`;
});
//remove painting info
const infoDiv = document.getElementById("info");
if (infoDiv) {
infoDiv.remove();
} else {
console.error("Div element with ID 'info' not found!");
}
return;
}
const streetDetails = jsonData.Features[imageIndex]; // Get image data based on index
// Extract PictureURL at a higher scope level
PictureURL = streetDetails.PictureURL;
Description = streetDetails.Description;
// Extract details
const FeatureID = streetDetails.FeatureID;
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
const streetHeading = streetDetails.StreetHeading;
const streetPitch = streetDetails.StreetPitch;
const streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
console.log("FeatureID: " + FeatureID);
console.log("PictureURL: " + PictureURL);
console.log("Description: " + Description);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
// Update numberoffeeds div
const numberoffeedsElement = document.getElementById("results");
numberoffeedsElement.textContent = `This is a ${entryCount} round game.\nClick on the map where you think this scene is.`;
callback(FeatureID);
})
.catch((error) => console.error("Error fetching data: ", error));
}
//visualize and animate finalscore
function createScoreLine(
totalScore,
possibleScore,
color = "#ff0000",
backgroundColor = "#107896",
animationDuration = 1000
) {
// milliseconds
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set canvas dimensions based on your needs
canvas.width = 200;
canvas.height = 30;
let currentPercentage = 0; // Track current percentage for animation
const animateFill = () => {
if (currentPercentage >= (totalScore / possibleScore) * 100) {
return; // Stop animation if reached target percentage
}
currentPercentage += 1; // Increment current percentage for animation
// Clear the canvas before each redraw to avoid stacking lines
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set background color
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set fill color for the line
ctx.fillStyle = color;
// Adjust the rectangle width based on current percentage
ctx.fillRect(0, 0, canvas.width * (currentPercentage / 100), canvas.height);
// Request another animation frame for smooth animation
requestAnimationFrame(animateFill);
};
animateFill(); // Start the animation
return canvas;
}
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "transit",
stylers: [
{
visibility: "off",
},
],
},
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Add a click event listener to the map
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng; // Get the latitude and longitude of the click
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map, // Set the map where the marker will be displayed
draggable: true, // Set draggable to true
});
// (Optional) Add additional customization to the marker here,
// such as setting an icon or info window
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(map, clickLocation);
});
}
//nextbutton
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Function to create and add the button
function createSubmitButton(map, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
if (!buttonsDiv) {
console.error("Element with ID 'buttons' not found!");
return;
}
const submitButton = document.createElement("button");
submitButton.textContent = "Submit"; // Customize button text
submitButton.classList.add("button"); // Add class 'button'
submitButton.addEventListener("click", () => {
// Handle button click event here (e.g., send clickLocation data)
console.log(
"Button clicked! Latitude:",
clickLocation.lat(),
"Longitude:",
clickLocation.lng()
);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance between marker and StreetPoints
const distanceInMeters =
google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng(streetLatitude, streetLongitude),
markerPosition
);
const roundedDistanceInMeters = Math.floor(distanceInMeters); // Round down to the nearest meter
console.log(
"Distance to StreetPoints: " + roundedDistanceInMeters + " meters"
);
// Adjust points based on distance
let score = 5000 - roundedDistanceInMeters;
if (score < 0) {
score = 0;
}
totalScore += score; // Add current points to total
possibleScore += 5000;
roundScores.push(score);
const message = "You scored " + score + " points";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Create a polyline between marker and StreetPoints
const lineCoordinates = [
{ lat: streetLatitude, lng: streetLongitude },
{ lat: markerPosition.lat(), lng: markerPosition.lng() },
];
const polyline = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
});
// Set the polyline on the map
polyline.setMap(map);
marker.setDraggable(false);
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend({ lat: streetLatitude, lng: streetLongitude });
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
});
buttonsDiv.appendChild(submitButton);
}
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
});
// Function to update the image and description
function updateImage(FeatureID, PictureURL) {
const infoDiv = document.getElementById("info");
const infoHTML = Description;
infoDiv.innerHTML = infoHTML;
const paintingDiv = document.getElementById("painting");
const imageHTML =
'<img src="' +
PictureURL +
'" onclick="this.requestFullscreen()" style="width: 90%;" class="center">';
console.log("Image URL:", imageHTML); // Log the image URL to the console
paintingDiv.innerHTML = imageHTML;
}
// Add click event for the ‘Next’ button
nextButton.addEventListener("click", () => {
// Increment the image index to fetch the next image
imageIndex++;
// Fetch the next image from the JSON file and update the painting div
fetchStreetDetails((fetchedFeatureID) => {
updateImage(fetchedFeatureID, PictureURL);
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
map.setCenter(newLatLng);
map.setZoom(3);
const message = "Where do you think this scene is?";
// Add click event listener back to the map
google.maps.event.clearListeners(map, "click"); // Clear existing click listeners
clickListener = map.addListener("click", (event) => {
const clickLocation = event.latLng;
// Create a new marker
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true,
});
// Remove the click event listener after adding the marker
google.maps.event.removeListener(clickListener);
createSubmitButton(map, clickLocation);
});
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
});
const buttonsDiv = document.getElementById("buttons");
buttonsDiv.removeChild(nextButton);
});
|
faf87d220542ed84f4c368c97a92d229
|
{
"intermediate": 0.3045605421066284,
"beginner": 0.44088223576545715,
"expert": 0.25455722212791443
}
|
43,854
|
i have hourly historical data of some cryptocurrencies ,
i also have a csv files of dates and name of crypto that i want to check…
i want to determine for each specefic date, by looking to its next 2 day hourly data(which includes 48 data),that price is increased 3% first,or decreased 5% first…
give me proper python code …
|
4565132cbb0aff8572fd9c2173e8d1e3
|
{
"intermediate": 0.43610092997550964,
"beginner": 0.4318477213382721,
"expert": 0.13205134868621826
}
|
43,855
|
исправьте дизайн добавив множество всяких эффектов шрифт , изображение можно брать с открытых источников, используя все самое новое, надо загромоздить весь дизайн что писать в css html
но цвет сбалансирвоаный сначала каркас кода с моими перемеными а потом что в css писать <html id="root">
<head>
<meta charset="utf-8">
<title>[TITLE]</title>
<link rel="stylesheet" href="/.s/src/css/1705.css" type="text/css" media="all" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script type="text/javascript">
var browser = navigator.userAgent;
var browserRegex = /(Android|BlackBerry|IEMobile|Nokia|iP(ad|hone|od)|Opera M(obi|ini))/;
var isMobile = false;
if(browser.match(browserRegex)) {
isMobile = true;
addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
function hideURLbar(){
window.scrollTo(0,1);
}
}
var currentPageIdTemplate = '$PAGE_ID$';
var currentModuleTemplate = '$MODULE_ID$';
var navTitle = 'Navigation';
</script>
</head>
<body>
<!-- <header> -->
<header>
<div id="header">
<div class="wrapper">
<div id="site-logo"><span class="site-l"><span class="site-n"><a href="$HOME_PAGE_LINK$">$SITE_NAME$</a></span></span></div>
<nav>
<div id="catmenu">
<!-- <sblock_nmenu> -->CONTENT<!-- </sblock_nmenu> -->
<div class="clr"></div>
</div>
</nav>
<div class="clr"></div>
</div>
</div>
</header>
<!-- </header> -->
<!-- <global_promo> -->
<?if($URI_ID$='page1')?>
<div id="promo">
<div class="promo-wrapper">
<div class="promo-i">
<div class="promo-cap">
<div class="promo-ttl">Lorem ipsum dolor sit amet</div>
<div class="promo-ds">Aliquam cursus tellus at nunc</div>
<div class="promo-sds">Mauris commodo ante massa, eget feugiat mi dignissim nec</div>
</div>
</div>
</div>
</div>
<?endif?>
<!-- </global_promo> -->
<div id="casing">
<div class="wrapper">
<?if($MODULE_ID$='forum')?><div class="forum-box"><?endif?>
<!-- <middle> -->
<div id="content" <?if($HIDE_CLEFTER$)?>class="wide-page"<?endif?>>
<section class="module-$MODULE_ID$">[BODY]</section>
</div>
<?if(!$HIDE_CLEFTER$)?>
<aside>
<div id="sidebar">
<div class="sidebox">
<div class="inner">
<div style="text-align:center;"><?if($USERS_ON$)?><?if($USER_LOGGED_IN$)?><span>Hello, <a href="$PERSONAL_PAGE_LINK$"><b>$USERNAME$</b></a>!</span><?else?><span>Hello, <b>$USERNAME$</b>!</span><?endif?><br><?endif?>
<?if($USERS_ON$)?><?if($USER_LOGGED_IN$)?><a title="Profile page" href="$PERSONAL_PAGE_LINK$">Profile page</a> | <a title="Log out" href="$LOGOUT_LINK$">Log out</a><?else?><a title="Register now" href="$REGISTER_LINK$">Register now</a> | <a title="Log in" href="$LOGIN_LINK$">Log in</a><?endif?><?endif?></div>
</div>
<div class="clr"></div>
</div>
<!-- <container> --><!-- <block> -->
<div class="sidebox"><div class="sidetitle"><span>TITLE</span></div>
<div class="inner">
CONTENT
</div>
<div class="clr"></div>
</div>
<!-- </block> --><!-- </container> -->
</div>
</aside>
<?endif?>
<!-- </middle> -->
<div class="clr"></div>
<?if($MODULE_ID$='forum')?></div><?endif?>
</div>
</div>
<!-- <footer> -->
<footer>
<div id="footer">
<div class="wrapper">
<div class="foot-l">
[COPYRIGHT]. $POWERED_BY$
</div>
<div class="foot-r">
<div id="soc-box">
<span><a href="https://twitter.com/" class="soc-tw" target="_blank"></a></span>
<span><a href="https://www.facebook.com/" class="soc-fc" target="_blank"></a></span>
<span><a href="https://vimeo.com/" class="soc-vi" target="_blank"></a></span>
<span><a href="http://vk.com/" class="soc-vk" target="_blank"></a></span>
</div>
</div>
<div class="clr"></div>
</div>
</div>
</footer>
<!-- </footer> -->
<script type="text/javascript" src="/.s/t/1705/ui.js"></script>
<!-- <popup> -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<div id="casing" class="popuptable">
<div class="popuptitle"><div><span>[TITLE]</span></div></div><div class="popupbody">[BODY]</div>
</div>
<!-- </popup> -->
</body>
</html>
<!-- <config> -->
{
"rstars_b_image" : "/.s/t/1705/brating.png",
"rstars_b_size" : "32",
"rstars_s_image" : "/.s/t/1705/rating.png",
"rstars_s_size" : "16"
}
<!-- </config> -->
|
2b489c9dfd3324f16a273f677fb370e7
|
{
"intermediate": 0.2895038425922394,
"beginner": 0.47723087668418884,
"expert": 0.23326529562473297
}
|
43,856
|
<html id="root">
<head>
<meta charset="utf-8">
<title>[TITLE]</title>
<link rel="stylesheet" href="/.s/src/css/1705.css" type="text/css" media="all" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script type="text/javascript">
var browser = navigator.userAgent;
var browserRegex = /(Android|BlackBerry|IEMobile|Nokia|iP(ad|hone|od)|Opera M(obi|ini))/;
var isMobile = false;
if(browser.match(browserRegex)) {
isMobile = true;
addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);
function hideURLbar(){
window.scrollTo(0,1);
}
}
var currentPageIdTemplate = '$PAGE_ID$';
var currentModuleTemplate = '$MODULE_ID$';
var navTitle = 'Navigation';
</script>
</head>
<body>
<!-- <header> -->
<header>
<div id="header">
<div class="wrapper">
<div id="site-logo"><span class="site-l"><span class="site-n"><a href="$HOME_PAGE_LINK$">$SITE_NAME$</a></span></span></div>
<nav>
<div id="catmenu">
<!-- <sblock_nmenu> -->CONTENT<!-- </sblock_nmenu> -->
<div class="clr"></div>
</div>
</nav>
<div class="clr"></div>
</div>
</div>
</header>
<!-- </header> -->
<!-- <global_promo> -->
<?if($URI_ID$='page1')?>
<div id="promo">
<div class="promo-wrapper">
<div class="promo-i">
<div class="promo-cap">
<div class="promo-ttl">Lorem ipsum dolor sit amet</div>
<div class="promo-ds">Aliquam cursus tellus at nunc</div>
<div class="promo-sds">Mauris commodo ante massa, eget feugiat mi dignissim nec</div>
</div>
</div>
</div>
</div>
<?endif?>
<!-- </global_promo> -->
<div id="casing">
<div class="wrapper">
<?if($MODULE_ID$='forum')?><div class="forum-box"><?endif?>
<!-- <middle> -->
<div id="content" <?if($HIDE_CLEFTER$)?>class="wide-page"<?endif?>>
<section class="module-$MODULE_ID$">[BODY]</section>
</div>
<?if(!$HIDE_CLEFTER$)?>
<aside>
<div id="sidebar">
<div class="sidebox">
<div class="inner">
<div style="text-align:center;"><?if($USERS_ON$)?><?if($USER_LOGGED_IN$)?><span>Hello, <a href="$PERSONAL_PAGE_LINK$"><b>$USERNAME$</b></a>!</span><?else?><span>Hello, <b>$USERNAME$</b>!</span><?endif?><br><?endif?>
<?if($USERS_ON$)?><?if($USER_LOGGED_IN$)?><a title="Profile page" href="$PERSONAL_PAGE_LINK$">Profile page</a> | <a title="Log out" href="$LOGOUT_LINK$">Log out</a><?else?><a title="Register now" href="$REGISTER_LINK$">Register now</a> | <a title="Log in" href="$LOGIN_LINK$">Log in</a><?endif?><?endif?></div>
</div>
<div class="clr"></div>
</div>
<!-- <container> --><!-- <block> -->
<div class="sidebox"><div class="sidetitle"><span>TITLE</span></div>
<div class="inner">
CONTENT
</div>
<div class="clr"></div>
</div>
<!-- </block> --><!-- </container> -->
</div>
</aside>
<?endif?>
<!-- </middle> -->
<div class="clr"></div>
<?if($MODULE_ID$='forum')?></div><?endif?>
</div>
</div>
<!-- <footer> -->
<footer>
<div id="footer">
<div class="wrapper">
<div class="foot-l">
[COPYRIGHT]. $POWERED_BY$
</div>
<div class="foot-r">
<div id="soc-box">
<span><a href="https://twitter.com/" class="soc-tw" target="_blank"></a></span>
<span><a href="https://www.facebook.com/" class="soc-fc" target="_blank"></a></span>
<span><a href="https://vimeo.com/" class="soc-vi" target="_blank"></a></span>
<span><a href="http://vk.com/" class="soc-vk" target="_blank"></a></span> добавьте не трогая переменые типа такого [COPYRIGHT]. $POWERED_BY$ и <?if($MODULE_ID$='forum')?>
</div>
</div>
<div class="clr"></div>
</div>
</div>
</footer>
<!-- </footer> -->
добавьте разные эффекты скрипты не трогая переменые <?if($USERS_ON$)?> типа этой <?if($тут переменная$)?>
|
6bd77f7b15462277675e18d5c6503a0f
|
{
"intermediate": 0.43302708864212036,
"beginner": 0.40556076169013977,
"expert": 0.1614121049642563
}
|
43,857
|
i have a csv file containing a Date column with following format:
2020-12-25 00:00:00+00:00
2020-12-25 01:00:00+00:00
2020-12-25 02:00:00+00:00
i want to select values of 2 days after a specefic day :
like if my date is 2020-12-24 i want :
2020-12-25 00:00:00+00:00
2020-12-25 01:00:00+00:00
2020-12-25 02:00:00+00:00
...
2020-12-25 22:00:00+00:00
2020-12-26 23:00:00+00:00
give me propwer python code
|
2abc7b10423d94dbcd3a0f0c8107a5b0
|
{
"intermediate": 0.3708586096763611,
"beginner": 0.43576812744140625,
"expert": 0.19337324798107147
}
|
43,858
|
import base64
import acrcloud
import os
import eyed3
import requests
import json
import re
from my_shazam_utility import shazam_recognize_song
from applemusic_api import AppleMusicApi
from Acrcloudretrieve import recognize_song, set_id3_tags_mp3
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open('D:/Eurydice/Encompassing Data by discerning/config/config.json', 'r') as config_file:
config_data = json.load(config_file)
return config_data
# Load the configuration on script start
config = load_config()
# Now also load Spotify credentials
CLIENT_ID = config['Spotify']['CLIENT_ID']
CLIENT_SECRET = config['Spotify']['CLIENT_SECRET']
def get_user_choice():
# Display a header
print("=" * 50)
print("Welcome to the Song Recognition Service!")
print("=" * 50)
# Provide instructions and options
print("\nPlease select the recognition service you'd like to use:\n")
print(" 1: YoutubeACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print("-" * 50)
# Input prompt
choice = input("Enter your choice (1 or 2) and press Enter: ")
# More flair to indicate processing/input received
print("\n" + "." * 25 + " Processing " + "." * 25 + "\n")
return choice
# Your Spotify authentication and song search functions:
def authenticate_spotify(client_id, client_secret):
auth_url = 'https://accounts.spotify.com/api/token'
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
headers = {'Authorization': f'Basic {client_creds_b64.decode()}'}
data = {'grant_type': 'client_credentials'}
response = requests.post(auth_url, headers=headers, data=data)
access_token = response.json().get('access_token')
return access_token
def search_spotify_for_song(access_token, artist_name, title):
base_url = "https://api.spotify.com/v1/search"
query = f"{title} artist:{artist_name}"
headers = {"Authorization": f"Bearer {access_token}"}
params = {"q": query, "type": "track", "limit": 1}
response = requests.get(base_url, headers=headers, params=params)
results = response.json()
try:
track_info = results['tracks']['items'][0]
return track_info
except IndexError:
print("Song not found on Spotify.")
return None
# Modify your process_audio_file function to incorporate Spotify search
def process_audio_file(audio_file_path):
# Identify song using Shazam
shazam_data = shazam_recognize_song(audio_file_path)
if shazam_data:
artist_name = shazam_data['track']['subtitle']
title = shazam_data['track']['title']
print(f"Identified Song: {artist_name} - {title}")
# Authenticate with Spotify
access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
# Search for song on Spotify
song_info = search_spotify_for_song(access_token, artist_name, title)
if song_info:
track_number = song_info['track_number']
print(f"Track Number on Spotify: {track_number}")
else:
print("Song not found on Spotify.")
else:
print("Song could not be identified.")
if __name__ == "__main__":
user_choice = get_user_choice()
audio_file_path = 'D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3'
if user_choice == '1':
print("\n" + "." * 15 + " ᴜsɪɴɢ YᴏᴜᴛᴜʙᴇACR " + "." * 15 + "\n")
song_tags = recognize_song(audio_file_path)
if song_tags:
print(f'Song identified: {song_tags}')
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get('artists')[0].get('name')
song_title = song_tags.get('title')
safe_artist_name = re.sub(r'[/\:?"<>|]', '', artist_name)
safe_song_title = re.sub(r'[/\:?"<>|]', '', song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}")
else:
print('Could not identify the song in YᴏᴜᴛᴜʙᴇACR.')
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search('songs', f"{artist_name} - {song_title}")
if track_results:
track_id = track_results[0]['id']
album_artwork_url_template = track_results[0]['attributes']['artwork']['url']
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print("Song not found on Apple Music.")
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f"{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, 'w', encoding='utf-8') as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print("Could not get the lyrics.")
elif user_choice == '2':
print("\n" + "." * 15 + " ᴜsɪɴɢ Sʜᴀᴢᴀᴍ " + "." * 15 + "\n")
song_tags = shazam_recognize_song(audio_file_path)
print(song_tags)
else:
print("Invalid choice. Exiting.")
exit()
after selecting 2 option :
these: must execute
# Your Spotify authentication and song search functions:
def authenticate_spotify(client_id, client_secret):
auth_url = 'https://accounts.spotify.com/api/token'
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
headers = {'Authorization': f'Basic {client_creds_b64.decode()}'}
data = {'grant_type': 'client_credentials'}
response = requests.post(auth_url, headers=headers, data=data)
access_token = response.json().get('access_token')
return access_token
def search_spotify_for_song(access_token, artist_name, title):
base_url = "https://api.spotify.com/v1/search"
query = f"{title} artist:{artist_name}"
headers = {"Authorization": f"Bearer {access_token}"}
params = {"q": query, "type": "track", "limit": 1}
response = requests.get(base_url, headers=headers, params=params)
results = response.json()
try:
track_info = results['tracks']['items'][0]
return track_info
except IndexError:
print("Song not found on Spotify.")
return None
# Modify your process_audio_file function to incorporate Spotify search
def process_audio_file(audio_file_path):
# Identify song using Shazam
shazam_data = shazam_recognize_song(audio_file_path)
if shazam_data:
artist_name = shazam_data['track']['subtitle']
title = shazam_data['track']['title']
print(f"Identified Song: {artist_name} - {title}")
# Authenticate with Spotify
access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
# Search for song on Spotify
song_info = search_spotify_for_song(access_token, artist_name, title)
if song_info:
track_number = song_info['track_number']
print(f"Track Number on Spotify: {track_number}")
else:
print("Song not found on Spotify.")
else:
print("Song could not be identified.")
|
d979ccfe8cbf96d5841cd87b75faafb5
|
{
"intermediate": 0.45931777358055115,
"beginner": 0.3594379723072052,
"expert": 0.18124423921108246
}
|
43,859
|
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
long depth;
long time;
} Station;
void heapify(long *heap, long size, long i)
{
long minimum = i;
long l = 2 * i + 1;
long r = 2 * i + 2;
if (l < size && heap[l] < heap[minimum])
minimum = l;
if (r < size && heap[r] < heap[minimum])
minimum = r;
if (minimum != i)
{
long temp = heap[minimum];
heap[minimum] = heap[i];
heap[i] = temp;
heapify(heap, size, minimum);
}
}
long compare(const void *a, const void *b)
{
Station *stationA = (Station *)a;
Station *stationB = (Station *)b;
return stationA->depth - stationB->depth;
}
long deleteMin(long *heap, long *size)
{
if (*size == 0)
return -1;
long min = heap[0];
heap[0] = heap[--(*size)];
heapify(heap, *size, 0);
return min;
}
void insert(long heap[], long *size, long value)
{
heap[(*size)++] = value;
for (long i = *size / 2 - 1; i >= 0; i--)
{
heapify(heap, *size, i);
}
}
void func(Station stations[], long num_stations, long ini_oxygen, long final_depth, long additional_oxygen)
{
//printf("inside func func\n");
qsort(stations, num_stations, sizeof(Station), compare);
long heap[num_stations];
long heap_size = 0;
long current_time = 0, max_depth = ini_oxygen;
for (long i = 0; i < num_stations; ++i)
{
while (max_depth < stations[i].depth && heap_size > 0)
{
long refill_time = deleteMin(heap, &heap_size);
current_time += refill_time;
max_depth += additional_oxygen;
}
if (max_depth < stations[i].depth)
break;
heap[heap_size] = stations[i].time;
long child = heap_size;
long parent = (child-1)/2;
while (child > 0 && heap[child] < heap[parent])
{//printf("inside inside inside while loop\n");
long temp = heap[parent];
heap[parent] = heap[child];
heap[child] = temp;
child=parent;
parent=(child-1)/2;
}
heap_size++;
if (max_depth >= final_depth)
{
printf("%d\n", current_time);
return;
}
}
while (heap_size > 0 && max_depth < final_depth)
{
long refill_time = deleteMin(heap, &heap_size);
current_time += refill_time;
max_depth += additional_oxygen;
}
if (max_depth >= final_depth)
{
printf("%ld", current_time);
}
else
{
printf("-1 %ld", max_depth);
}
}
int main()
{
long num_stations, ini_oxygen, final_depth, additional_oxygen;
scanf("%ld %ld %ld %ld", &num_stations, &ini_oxygen, &final_depth, &additional_oxygen);
Station stations[num_stations];
for (long i = 0; i < num_stations; ++i)
{
scanf("%ld", &stations[i].depth);
}
for (long i = 0; i < num_stations; ++i)
{
scanf("%ld", &stations[i].time);
}
func(stations, num_stations, ini_oxygen, final_depth, additional_oxygen);
return 0;
}
modify this code to solve this
Deep Sea Adventure 2
Submit solution
My submissions
All submissions
Best submissions
Points:35 (partial)
Time limit:1.0s
Memory limit:128M
Author:
admin
Problem type
Allowed languages
C
Problem Statement
Luckily Percy made it safely to the caves located deep on the ocean floor. Now he gets to explore the various chambers present there. However, he again has an oxygen issue. As per safety guidelines, each chamber has a certain minimum oxygen level limit that the diver needs to have before entering it. At the same time, after visiting each chamber, Percy either loses certain amount of oxygen (due to consumption) or ends up gaining some (due to presence of air pockets). Percy is curious and wants to know whether it will be possible for him to visit all the chambers without running out of oxygen.
Percy initially starts with
amount of oxygen. There are
chambers, where the
th chamber has a minimum oxygen requirement of
i and after visiting the chamber, his oxygen level changes by
i amount.
You have to help Percy again by letting him know whether it is possible for him to visit all the chambers in any order without running out of oxygen. He can visit one chamber only once.
Input Format
The first line of input contains integers
and
, denoting the number of chambers and the initial oxygen supply respectively.
The second line contains
integers representing the minimum oxygen requirement
i of each chamber.
The third line contains
integers representing the changee
i in oxygen level after Percy visits a chamber.
Constraints
There are two sets of constraints, which differ only in the range of
. The points of this question are split based on the value of this range.
Set 1
i
i
Set 2
i
i
Output Format
You need to output "YES" or "NO" (case sensitive) based on whether it is possible for him to visit all the chambers or not.
Sample Test Case 1:
Input:
Copy
3 5
3 6 1
-4 -3 6
Output:
Copy
YES
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. He goes to the first chamber and is left with
unit. Then he goes to the third chamber and is left with
units. Lastly, he visits the second chamber and is left with
units of oxygen.
Sample Test Case 2:
Input:
Copy
2 7
7 3
-4 -3
Output:
Copy
YES
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. He goes to the first chamber and is left with
units. Then he visits the second chamber and is left with
units of oxygen.
Sample Test Case 3:
Input:
Copy
2 5
2 2
-3 -4
Output:
Copy
NO
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. One way he can try is going to the first chamber in the first go and be left with
units, with which he can enter the second chamber, but then run out of oxygen. The other way is he can go to second chamber in the first attempt, but this leaves him with only
unit afterwards, with which he cannot enter the first chamber.
|
4169b505b302e48a544908df97faa891
|
{
"intermediate": 0.299125075340271,
"beginner": 0.5442729592323303,
"expert": 0.1566019356250763
}
|
43,860
|
01) Open Visual Studio and run your Console Application with
- First Name
- Last Name
- Contact No
- Email Address
- Address
|
e03b622a6bbebedb49ae0f953e023928
|
{
"intermediate": 0.42307019233703613,
"beginner": 0.26953303813934326,
"expert": 0.3073968291282654
}
|
43,861
|
write code on your Console Application with
- First Name
- Last Name
- Contact No
- Email Address
- Address
|
f6791332ebb3e5b443a3d91d3bc9f9e5
|
{
"intermediate": 0.35912802815437317,
"beginner": 0.3949078619480133,
"expert": 0.24596410989761353
}
|
43,862
|
How to check if a specific party equal to another (multiplayer_1 to multiplayer_10) in warband module?
I want to use it with script setup_party_meeting and check if :meeting_party equal to one of multiplayer party
You can compare all parties with :meeting_party
Module party:
("multiplayer_parties_begin","nothing_here",pf_disabled, no_menu, pt_none, fac_commoners,0,ai_bhvr_hold,0,(0,0),[]),
("multiplayer_1","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_2","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_3","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_4","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_5","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_6","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_7","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_8","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_9","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
("multiplayer_10","mp",icon_player|pf_limit_members, no_menu, pt_none,fac_neutral,0,ai_bhvr_hold,0,(17, 52.5),[(trp_player_m,1,0)]),
Example of set up a position to every multiplayer party:
(try_for_range,":i",1,":nr_players"),
(troop_get_slot,":local_id",":c",":args"),
(store_add,":party_id",":local_id","p_multiplayer_parties_begin"),
(val_add,":c",1),
(troop_get_slot,":x",":c",":args"),
(val_add,":c",1),
(troop_get_slot,":y",":c",":args"),
(val_add,":c",1),
(troop_get_slot,":rot",":c",":args"),
(val_add,":c",1),
|
3c537544d4e25c19fd1aa35d0c6fde2d
|
{
"intermediate": 0.36331334710121155,
"beginner": 0.35916078090667725,
"expert": 0.2775258719921112
}
|
43,863
|
У меня есть код dll, которая загружается в процесс, используя хук нужно изменить байт по оффесту. Исправь ошибки в моем коде:
#include <Windows.h>
void InstallHook() {
HANDLE hProcess = GetCurrentProcess();
HMODULE hEngineModule = GetModuleHandleW(L"engine.dll");
uintptr_t baseAdress = (uintptr_t)hEngineModule;
uintptr_t send = baseAdress + 0x22E207;
//PVOID wrapperSend = reinterpret_cast<PVOID>(&wrapper_Send);
//INT32 offsetSend = (DWORD)wrapperSend - ((DWORD)send + 1);
BYTE patchSend[1] = { 0x00 };
WriteProcessMemory(hProcess, (LPVOID)send, patchSend, 1, NULL);
}
BOOL WINAPI Main(HMODULE hmodule) {
MessageBoxA(0, "Success", "OK", MB_OK);
return false;
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hModule);
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Main, 0, 0, 0);
InstallHook();
break;
}
return TRUE;
}
|
e2da4b5af161b1a9c3485bda48f53679
|
{
"intermediate": 0.6020103096961975,
"beginner": 0.2598848044872284,
"expert": 0.13810491561889648
}
|
43,864
|
I wrote this for a personals ad on reddit:
|
c857387c37cda5c0c080cdd2b44a5e07
|
{
"intermediate": 0.32509008049964905,
"beginner": 0.4245503842830658,
"expert": 0.25035956501960754
}
|
43,865
|
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int min_oxygen;
int change;
} Station;
// Compare function for qsort
int compare(const void *a, const void *b) {
Station *first_station = (Station *)a;
Station *second_station = (Station *)b;
return first_station->min_oxygen - second_station->min_oxygen;
}
// Function to check if it’s possible to visit all chambers
int canVisitAllStations(Station stations[], int num_stations, int initial_oxygen) {
// First, sort the stations based on their minimum oxygen requirement
qsort(stations, num_stations, sizeof(Station), compare);
// Traverse through all stations
for (int i = 0; i < num_stations; ++i) {
// Check if there’s enough oxygen to visit the station
if (initial_oxygen >= stations[i].min_oxygen) {
// Update the oxygen level based on the station’s change
initial_oxygen += stations[i].change;
} else {
// Not enough oxygen to visit the station
return 0; // Returning 0 indicates “NO”
}
}
// If we’ve successfully iterated through all stations
return 1; // Returning 1 indicates “YES”
}
int main() {
int num_stations, initial_oxygen;
scanf("%d %d", &num_stations, &initial_oxygen);
Station stations[num_stations];
// Reading minimum oxygen and change for each station
for (int i = 0; i < num_stations; ++i) {
scanf("%d", &stations[i].min_oxygen);
}
for (int i = 0; i < num_stations; ++i) {
scanf("%d", &stations[i].change);
}
// Determine if it’s possible to visit all stations
if (canVisitAllStations(stations, num_stations, initial_oxygen)) {
printf("YES\n");
} else {
printf("NO\n");
}
return 0;
}
correct this code to give
Problem Statement
Luckily Percy made it safely to the caves located deep on the ocean floor. Now he gets to explore the various chambers present there. However, he again has an oxygen issue. As per safety guidelines, each chamber has a certain minimum oxygen level limit that the diver needs to have before entering it. At the same time, after visiting each chamber, Percy either loses certain amount of oxygen (due to consumption) or ends up gaining some (due to presence of air pockets). Percy is curious and wants to know whether it will be possible for him to visit all the chambers without running out of oxygen.
Percy initially starts with
amount of oxygen. There are
chambers, where the
th chamber has a minimum oxygen requirement of
i and after visiting the chamber, his oxygen level changes by
i amount.
You have to help Percy again by letting him know whether it is possible for him to visit all the chambers in any order without running out of oxygen. He can visit one chamber only once.
Input Format
The first line of input contains integers
and
, denoting the number of chambers and the initial oxygen supply respectively.
The second line contains
integers representing the minimum oxygen requirement
i of each chamber.
The third line contains
integers representing the changee
i in oxygen level after Percy visits a chamber.
Constraints
There are two sets of constraints, which differ only in the range of
. The points of this question are split based on the value of this range.
Set 1
i
i
Set 2
i
i
Output Format
You need to output "YES" or "NO" (case sensitive) based on whether it is possible for him to visit all the chambers or not.
Sample Test Case 1:
Input:
Copy
3 5
3 6 1
-4 -3 6
Output:
Copy
YES
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. He goes to the first chamber and is left with
unit. Then he goes to the third chamber and is left with
units. Lastly, he visits the second chamber and is left with
units of oxygen.
Sample Test Case 2:
Input:
Copy
2 7
7 3
-4 -3
Output:
Copy
YES
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. He goes to the first chamber and is left with
units. Then he visits the second chamber and is left with
units of oxygen.
Sample Test Case 3:
Input:
Copy
2 5
2 2
-3 -4
Output:
Copy
NO
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. One way he can try is going to the first chamber in the first go and be left with
units, with which he can enter the second chamber, but then run out of oxygen. The other way is he can go to second chamber in the first attempt, but this leaves him with only
unit afterwards, with which he cannot enter the first chamber.
|
482cce2aa66690520f41f04399e01b6a
|
{
"intermediate": 0.4073423445224762,
"beginner": 0.35739535093307495,
"expert": 0.23526231944561005
}
|
43,866
|
I want to make stock screener through trading view pine script code .
So chat gpt you have to write trading view pine script code stock screener for Multi Timeframe and Multi Symbol analysis based on Supply and Demand zone
Important Definition
Unfilled Boring/Base candle: A candle where body of candle is less than 50% of the total length of the candle. Also the TR of this candle will be less than the ATR of this candle. ATR calculation is taken of last 14 candles. If multiple consecutive boring candles are present then rules will be applicable on all of those.
Filled Leg-in candle: Candle that comes just before the first Boring Candle, its Body should be more than 50% of its own total length and its TR should be greater than its ATR. ATR calculation is taken of last 14 candles. It should be bigger than the Boring candles that come just after it.
Filled Leg-out candle: Candle that comes just after the last Boring Candle(if there are multiple Boring candles then), its Body should be more than 50% of its own total length and its TR should be greater than its ATR. ATR calculation is taken of last 14 candles. It should be bigger than the Boring candles that come just before it. The length of the Filled Leg-out starts from the close price of the last boring candle and ends at the close price of the Single leg out(high for Demand zone buy trade and low for Supply zone Sell trade) candle or ends at the close price of the 3rd legout candle if 3 consecutive green/red candles are present.
User Inputs options in code:
👉 Point 1. Candlestick Timeframe Selection: 1 Min, 2 Min, 3 Min, 5 Min, 15 Min,30 Min, 1 Hr, 2 HR, 3 Hr, 4 Hr, 8 HR, 1 Day, 1 Week, 1 Month. Multiple Selection checkbox.
👉 Point 2. Symbol Selection: Comma separate list of Symbols to be accepted as Input. Multiple Symbols can be entered.
👉 Point 3. Ratio of Base/Boring Candle to Legin Candle: example 1:2, 1:3 etc accept the ratio in textbox, If there are multiple Boring candles all should adhere to this ratio.
👉 Point 4. Ratio of Base/Boring Candle to Legout Candle: example 1:4, 1:5 etc accept the ratio in textbox
, If there are multiple Boring candles all should adhere to this ratio.
👉 Point 5. Maximum Number of Base/Boring Candles Allowed: Textbox that allows Number from 1 to 4
👉 Point 6. Minimum Leg In Body To its own HighLow % : Accept percentage as a number so if we enter 60 then it means the body of the candle should be atleast 60% of the total length of that candle including the wick(high and low also). Optional paramter. Leg in candle is the Candle which is just before the Base/Boring Candle(s). If there are multiple boring/base candles then the candle which comes just before the first boring candle is called as Leg in Candle.
👉 Point 7. Minimum Leg Out Body To its own HighLow % : Accept percentage as a number so if we enter 60 then it means the body of the candle should be atleast 60% of the total length of that candle including the wick(high and low also). Optional paramter. Leg out candle is the Candle which is just after the Base/Boring Candle(s). If there are multiple boring/base candles then the candle which comes after the last boring candle is called as Leg out Candle.
👉 Point 8. Number of consecutive candles to consider for Leg-out length calculation: Optional Parameter that accepts a number. Suppose if we select 3 then that means after the Boring candle or the last of the boring candles if 3 consecutive green or red candles are created those would be considered as a single leg out candle and the length of the legout candle will be considered as the total of these 3 candles. If this parameter is selected then point 8 calculation will also consider this as the total length for its calculation.
Zone patterns
(1) demand zone pattern
1.1 DBR: Drop-base-rally
Proximal price line for DBR- highest body in boring candle
Distal price line for DBR- lowest low in pattern
1.2 RBR: Rally-base-rally
Proximal price line for RBR- highest body in boring candle
Distal price line for RBR- lowest low in pattern excluding legin
(2) Supply zone pattern
2.1 DBD: Drop-base-drop
Proximal price line for DBD- lowest body in boring candle
Distal price line for DBD- highest high in pattern excluding legin
2.2 RBD: Rally-base-Drop
Proximal price line for RBD- lowest body in boring candle
Distal price line for RBD- highest high in pattern
Objective & Logic for writing code: our code will detect if any of the 4 patterns mentioned above have been created by candles that have closed earlier
The Area or zone between the Proximal and Distal price should not be tested by Price after it has been created. If price has already come between this zone earlier after this zone was created then ignore this pattern.. Only when the zone is fresh and untested can be considered valid. Remember that the Legout candle is excluded from this check as it can come within this zone also. But all the candles that are created after Legout should not have come within this Area zone in between the Proximal price and the Distal Price. The candle that comes just after legout candle should not cover more than 50% of the Legout candle.
Other rules
THERE SHOULD BE NO GAP IN LEG-IN AND BORING CANDLE(s)
. Generated code should be modular and well documented in each block. In the code you will be attached to any 1 single Indian stock symbol chart but it will run all the symbols and timeframes that are specified in the Input.
Each Timeframe(s) and Symbol combination will have a separate and unique magic number. That number and timeframe combination and symbol and pattern name (DBR, RBR, DBD, RBD) should be displayed on the screen in the table as a summary with legin and legout candle date of latest pattern for both demand zone and supply zone. Chart will use candlestick chart.
|
c33b6f377d1ab177611cf3155232e875
|
{
"intermediate": 0.3311128616333008,
"beginner": 0.3731846809387207,
"expert": 0.2957024574279785
}
|
43,867
|
Привет, у меня проблема, как мне сделать отписку button.OnNextPoint в методе ButtonClicked() в этом коде
private void InitArray(int arrayIndex)
{
if (arrayIndex < _sequencePointerQuests.Count)
{
OnMissionStage?.Invoke(arrayIndex);
_activatedPointerCurrentArray = 0;
foreach (var button in _sequencePointerQuests[arrayIndex])
{
button.ElementActivation();
button.OnNextPoint += () => ButtonClicked(button, arrayIndex);
}
}
else
{
OnMissionCompleted?.Invoke();
}
}
private void ButtonClicked(IPointerQuest button, int arrayIndex)
{
_activatedPointerCurrentArray++;
// Если все кнопки в текущем массиве активированы, переходим к следующему
if (_activatedPointerCurrentArray == _sequencePointerQuests[arrayIndex].Length)
{
if (_AllWire.Length > _currentPointID)
{
_AllWire[_currentPointID].Active();
}
_currentPointID++;
InitArray(_currentPointID);
}
|
ffe2e014433d0d94122e155290b56ee8
|
{
"intermediate": 0.34864118695259094,
"beginner": 0.37761202454566956,
"expert": 0.2737467288970947
}
|
43,868
|
#include <stdio.h>
#include <stdlib.h>
typedef struct Station
{
int min_req;
int incr;
} Station;
int compare(const void *a, const void *b)
{
Station *first_station = (Station *)a;
Station *second_station = (Station *)b;
return first_station->incr - second_station->incr;
}
int main()
{
int n;
int initial_oxygen;
scanf("%d %d",&n,&initial_oxygen);
Station incr_pos[n];
Station incr_neg[n];
int minreq[n];
int incr[n];
int positive_index=0;
int negative_index=0;
for (int i=0;i<n;i++)
{
scanf("%d",&minreq[i]);
}for (int i=0;i<n;i++)
{
scanf("%d",&incr[i]);
if (incr[i]>=0)
{
incr_pos[positive_index].min_req=minreq[i];
incr_pos[positive_index++].incr=incr[i];}
else
{
incr_neg[negative_index].min_req=minreq[i];
incr_neg[negative_index++].incr=incr[i];}
}
qsort(incr_pos,positive_index,sizeof(Station),compare);
qsort(incr_neg,negative_index,sizeof(Station),compare);
for (int i=0;i<positive_index;i++)
{
if (initial_oxygen>=incr_pos[i].min_req)
{
initial_oxygen=initial_oxygen+incr_pos[i].incr;
}
else
{
printf("NO");
return 0;
}
}
for (int i=0;i<negative_index;i++)
{
if (initial_oxygen>=incr_neg[i].min_req)
{
initial_oxygen=initial_oxygen+incr_neg[i].incr;
if (initial_oxygen<0)
{
printf("NO");
return 0;
}
}
else
{
printf("NO");
return 0;
}
}
printf("YES");
return 0;
}
the incr_pos array's minreq should be sorted in increasing order and incr_neg array 's minreqsorted in decreasing order
|
90ef951ca6bc25764074d4c861393222
|
{
"intermediate": 0.38551026582717896,
"beginner": 0.3216373026371002,
"expert": 0.29285237193107605
}
|
43,870
|
Problem Statement
Luckily Percy made it safely to the caves located deep on the ocean floor. Now he gets to explore the various chambers present there. However, he again has an oxygen issue. As per safety guidelines, each chamber has a certain minimum oxygen level limit that the diver needs to have before entering it. At the same time, after visiting each chamber, Percy either loses certain amount of oxygen (due to consumption) or ends up gaining some (due to presence of air pockets). Percy is curious and wants to know whether it will be possible for him to visit all the chambers without running out of oxygen.
Percy initially starts with
amount of oxygen. There are
chambers, where the
th chamber has a minimum oxygen requirement of
i and after visiting the chamber, his oxygen level changes by
i amount.
You have to help Percy again by letting him know whether it is possible for him to visit all the chambers in any order without running out of oxygen. He can visit one chamber only once.
Input Format
The first line of input contains integers
and
, denoting the number of chambers and the initial oxygen supply respectively.
The second line contains
integers representing the minimum oxygen requirement
i of each chamber.
The third line contains
integers representing the changee
i in oxygen level after Percy visits a chamber.
Constraints
There are two sets of constraints, which differ only in the range of
. The points of this question are split based on the value of this range.
Set 1
i
i
Set 2
i
i
Output Format
You need to output "YES" or "NO" (case sensitive) based on whether it is possible for him to visit all the chambers or not.
Sample Test Case 1:
Input:
Copy
3 5
3 6 1
-4 -3 6
Output:
Copy
YES
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. He goes to the first chamber and is left with
unit. Then he goes to the third chamber and is left with
units. Lastly, he visits the second chamber and is left with
units of oxygen.
Sample Test Case 2:
Input:
Copy
2 7
7 3
-4 -3
Output:
Copy
YES
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. He goes to the first chamber and is left with
units. Then he visits the second chamber and is left with
units of oxygen.
Sample Test Case 3:
Input:
Copy
2 5
2 2
-3 -4
Output:
Copy
NO
Explanation:
Percy wants to visit all the
chambers. He initially has
units of oxygen. One way he can try is going to the first chamber in the first go and be left with
units, with which he can enter the second chamber, but then run out of oxygen. The other way is he can go to second chamber in the first attempt, but this leaves him with only
unit afterwards, with which he cannot enter the first chamber.
give a direct structure array and sorting algorithm. it doesnt have to satisfy the cases. give code in c by using the algorithm such that u divide them into two arrays based on whether or not the added oxygen is positive or negatove. then sort them. then traverse while simultaneoudly checking if it satisfies the minimum requirement
|
ad49569e9321c61a3c1bf06a0ee91f8d
|
{
"intermediate": 0.2227056920528412,
"beginner": 0.1941487342119217,
"expert": 0.5831455588340759
}
|
43,871
|
This is the error we get: Traceback (most recent call last):
File "c:\Users\L14\Documents\Projets\Easy-MoE\Easy-MoE\Transformer-Max.py", line 209, in <module>
val_accuracy = evaluate(model, val_loader, dataset.vocab)
File "c:\Users\L14\Documents\Projets\Easy-MoE\Easy-MoE\Transformer-Max.py", line 204, in evaluate
accuracy = sum(word == target.item() for word, target in zip(correct_words, targets_flat[mask])) / mask.sum().item()
ZeroDivisionError: division by zero
when we run this code: import torch
import torch.nn as nn
import torch.optim as optim
import json
import base64
from torch.utils.data import DataLoader, Dataset
import binascii
import chardet
import random
import math
class PositionalEncoding(nn.Module):
def __init__(self, embedding_dim, max_len=5000):
super(PositionalEncoding, self).__init__()
self.embedding_dim = embedding_dim
# Creating positional encoding matrix
pe = torch.zeros(max_len, embedding_dim)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, embedding_dim, 2).float() * (-math.log(10000.0) / embedding_dim))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
# Registering pe as a buffer since it’s not a model parameter
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:x.size(0), :]
return x
class DecoderLayer(nn.Module):
def __init__(self, embedding_dim, heads, ff_dim):
super(DecoderLayer, self).__init__()
self.self_attn = nn.MultiheadAttention(embedding_dim, heads)
# Feedforward network
self.ffn = nn.Sequential(
nn.Linear(embedding_dim, ff_dim),
nn.ReLU(),
nn.Linear(ff_dim, embedding_dim),
)
self.layer_norm1 = nn.LayerNorm(embedding_dim)
self.layer_norm2 = nn.LayerNorm(embedding_dim)
def forward(self, src):
src2 = self.layer_norm1(src)
attn_output, _ = self.self_attn(src2, src2, src2)
src = src + attn_output
src2 = self.layer_norm2(src)
src = src + self.ffn(src2)
return src
class Decoder(nn.Module):
def __init__(self, vocab_size, embedding_dim, num_layers, heads, ff_dim):
super(Decoder, self).__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.pos_encoding = PositionalEncoding(embedding_dim)
self.decoder_layers = nn.ModuleList([DecoderLayer(embedding_dim, heads, ff_dim) for _ in range(num_layers)])
self.final_layer = nn.Linear(embedding_dim, vocab_size)
def forward(self, x):
x = self.embedding(x)
x = self.pos_encoding(x)
for layer in self.decoder_layers:
x = layer(x)
output = self.final_layer(x)
return output
class QAJsonlDataset(Dataset):
def __init__(self, path, seq_len=512):
super().__init__()
self.pairs = self.load_data(path)
self.seq_len = seq_len
self.vocab = self.build_vocab([word for pair in self.pairs for item in pair for word in item])
def __len__(self):
return len(self.pairs)
def __getitem__(self, idx):
question, answer = self.pairs[idx]
question_tokenized = self.tokenize([self.vocab[word] for word in question])
answer_tokenized = self.tokenize([self.vocab[word] for word in answer])
return torch.tensor(question_tokenized), torch.tensor(answer_tokenized)
def load_data(self, path):
pairs = []
with open(path, "rb") as f: # Open in binary mode
for line in f:
data = json.loads(line.decode("utf-8")) # Decode binary data to JSON
question, answer = self.decode_binary_data(data["user"], data["content"]) # Decode binary fields
pairs.append((question.split(), answer.split()))
return pairs
def decode_binary_data(self, question_data, answer_data):
try:
question_encoding = chardet.detect(question_data.encode("utf-8"))['encoding']
answer_encoding = chardet.detect(answer_data.encode("utf-8"))['encoding']
# Decode data using the detected encoding
question = base64.b64decode(question_data).decode(question_encoding)
answer = base64.b64decode(answer_data).decode(answer_encoding)
except (UnicodeDecodeError, binascii.Error):
# Handle errors gracefully, e.g., log errors, skip entry
print(f"Error decoding data: question - {question_data}, answer - {answer_data}")
question = ""
answer = ""
return question, answer
def tokenize(self, integer_sequence):
tokens = integer_sequence[:self.seq_len]
if len(tokens) < self.seq_len:
# Pad with appropriate binary token
padding_token = self.vocab["<pad>"] # Consider a binary padding token if needed
tokens.extend([padding_token] * (self.seq_len - len(tokens)))
# Add <eos> token only if appropriate for binary representation
return tokens
def build_vocab(self, binary_tokens):
unique_tokens = list(set(binary_tokens))
self.vocab = {token: idx for idx, token in enumerate(unique_tokens)}
self.vocab['<pad>'] = len(self.vocab) # Add padding token
self.pad_idx = self.vocab['<pad>'] # Store padding token index
return self.vocab
class CustomDataLoader:
def __init__(self, dataset, batch_size=32):
self.dataset = dataset
self.batch_size = batch_size
def len(self):
return len(self.dataset) // self.batch_size
def __getitem__(self, idx):
batch = self.dataset[idx * self.batch_size:(idx + 1) * self.batch_size]
inputs, targets = zip(*batch)
inputs_padded = torch.nn.utils.rnn.pad_sequence(inputs, batch_first=True, padding_value=0)
targets_padded = torch.nn.utils.rnn.pad_sequence(targets, batch_first=True, padding_value=0)
return inputs_padded, targets_padded
# Define model parameters
vocab_size = 10000 # Adjust based on your vocabulary size
embedding_dim = 128
num_layers = 2 # Number of decoder layers
heads = 2 # Number of attention heads
ff_dim = 512 # Feed-forward dimension
# Create decoder-only transformer model
model = Decoder(vocab_size, embedding_dim, num_layers, heads, ff_dim)
# Data loading and splitting
path_to_data = "data/Real_talk.jsonl"
dataset = QAJsonlDataset(path_to_data, 512)
# Shuffle the dataset
random.shuffle(dataset.pairs)
train_size = int(0.8 * len(dataset)) # 80% of data for training, adjust as necessary
val_size = len(dataset) - train_size
train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=32)
# Define optimizer
optimizer = optim.Adam(model.parameters())
loss_fn = nn.CrossEntropyLoss() # PyTorch version of SparseCategoricalCrossentropy with from_logits=True
def print_model_param_count(model):
total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"Total Trainable Parameters: {total_params}")
# Assuming your model’s variable name is model
print_model_param_count(model)
# Training loop (example)
for epoch in range(1, 6):
for i, (inputs, targets) in enumerate(train_loader):
optimizer.zero_grad()
output = model(inputs)
loss = loss_fn(output.view(-1, vocab_size), targets.view(-1)) # Reshape for CrossEntropyLoss
loss.backward()
optimizer.step()
print(f'Epoch {epoch}, Loss: {loss.item()}')
def evaluate(model, val_loader, vocab):
with torch.no_grad():
for inputs, targets in val_loader:
outputs = model(inputs)
# Adjust dimension in argmax to correctly get predictions
predictions = torch.argmax(outputs, dim=2)
# Flatten tensors for element-wise comparison
predictions_flat = predictions.view(-1)
targets_flat = targets.view(-1)
padding_value = dataset.pad_idx # Now accessible
mask = targets_flat != padding_value
# Use vocab to convert token IDs to words before calculating accuracy
correct_words = [(vocab[pred.item()] if pred.item() != 0 else '') for pred in predictions_flat[mask]]
accuracy = sum(word == target.item() for word, target in zip(correct_words, targets_flat[mask])) / mask.sum().item()
return accuracy
# After training loop:
val_accuracy = evaluate(model, val_loader, dataset.vocab)
print(f'Validation Accuracy: {val_accuracy}')
def generate_text(model, initial_text, vocab, inv_vocab, seq_len=512, temperature=1.0):
model.eval() # Put the model in eval mode
tokens = [vocab.get(word, vocab['<unk>']) for word in initial_text.split()] # Convert initial text to tokens. Assumes <unk> for unknown words.
with torch.no_grad(): # No need to track gradients
for _ in range(seq_len - len(tokens)):
input_tensor = torch.tensor([tokens], dtype=torch.long) # Convert to tensor
output = model(input_tensor)
# Get the logits of the last token and apply temperature
logits = output[0, -1, :] / temperature
# Convert logits to probabilities (softmax) and sample the next token
probabilities = torch.softmax(logits, dim=-1)
next_token = torch.argmax(probabilities).item()
tokens.append(next_token) # Add predicted token to the sequence
if next_token == vocab['<eos>']: # Assuming you have an end-of-sequence token
break
generated_text = ' '.join([inv_vocab[token] for token in tokens]) # Convert tokens back to text
return generated_text
# Access the vocabulary from the dataset after it's loaded
vocab = dataset.vocab
# Creating an inverse vocabulary for converting token IDs back to words
inv_vocab = {idx: token for token, idx in vocab.items()} # vocab is your vocabulary dictionary from token to index
# Example usage
initial_text = "The meaning of life" # Seed the generation with some text
generated_text = generate_text(model, initial_text, vocab, inv_vocab, seq_len=50) # seq_len is the total desired length of generated sequence including the initial text
print(generated_text)
|
b0575c4092b99595c7e956410fa60521
|
{
"intermediate": 0.3165765702724457,
"beginner": 0.3833451271057129,
"expert": 0.30007830262184143
}
|
43,872
|
import base64
import acrcloud
import os
import eyed3
import eyed3.id3.frames
import requests
import json
import re
from my_shazam_utility import shazam_recognize_song
from applemusic_api import AppleMusicApi
from Acrcloudretrieve import recognize_song, set_id3_tags_mp3
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open(‘D:/Eurydice/Encompassing Data by discerning/config/config.json’, ‘r’) as config_file:
config_data = json.load(config_file)
return config_data
# Load the configuration on script start
config = load_config()
# Now also load Spotify credentials
CLIENT_ID = config[‘Spotify’][‘CLIENT_ID’]
CLIENT_SECRET = config[‘Spotify’][‘CLIENT_SECRET’]
def get_user_choice():
# Display a header
print(“=” * 50)
print(“Welcome to the Song Recognition Service!”)
print(“=” * 50)
# Provide instructions and options
print(“\nPlease select the recognition service you’d like to use:\n”)
print(" 1: YoutubeACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print(“-” * 50)
# Input prompt
choice = input(“Enter your choice (1 or 2) and press Enter: “)
# More flair to indicate processing/input received
print(”\n” + “.” * 25 + " Processing " + “.” * 25 + “\n”)
return choice
def add_or_update_txxx_frame(audiofile, description, value):
found = False
frames = audiofile.tag.frame_set.get(eyed3.id3.frames.USERTEXT_FID, [])
for frame in frames:
if frame.description == description:
frame.text = value
found = True
break
if not found:
# Create a new TXXX frame
new_frame = eyed3.id3.frames.UserTextFrame(encoding=3, description=description, text=value)
audiofile.tag.frame_set[eyed3.id3.frames.USERTEXT_FID] = new_frame
# Rest of your code remains unchanged
# Your Spotify authentication and song search functions:
def authenticate_spotify(client_id, client_secret):
auth_url = ‘https://accounts.spotify.com/api/token’
client_creds = f"{client_id}:{client_secret}“
client_creds_b64 = base64.b64encode(client_creds.encode())
headers = {‘Authorization’: f’Basic {client_creds_b64.decode()}'}
data = {‘grant_type’: ‘client_credentials’}
response = requests.post(auth_url, headers=headers, data=data)
access_token = response.json().get(‘access_token’)
return access_token
def search_spotify_for_song(access_token, artist_name, title):
base_url = “https://api.spotify.com/v1/search”
query = f”{title} artist:{artist_name}“
headers = {“Authorization”: f"Bearer {access_token}”}
params = {“q”: query, “type”: “track”, “limit”: 1}
response = requests.get(base_url, headers=headers, params=params)
results = response.json()
try:
track_info = results[‘tracks’][‘items’][0]
return track_info
except IndexError:
print(“Song not found on Spotify.”)
return None
def process_audio_file_with_spotify_search(audio_file_path):
shazam_data = shazam_recognize_song(audio_file_path)
if shazam_data:
artist_name = shazam_data[‘track’][‘subtitle’]
title = shazam_data[‘track’][‘title’]
print(f"Identified Song: {artist_name} - {title}“)
access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
song_info = search_spotify_for_song(access_token, artist_name, title)
if song_info:
print(json.dumps(song_info, indent=4)) # For debugging
print(”\n///////////////////////////////\n")
album_name = song_info[‘album’][‘name’]
album_url = song_info[‘album’][‘external_urls’][‘spotify’]
track_number = song_info[‘track_number’]
release_date = song_info[‘album’][‘release_date’]
isrc = song_info.get(‘external_ids’, {}).get(‘isrc’, “Not Available”)
label = song_info[‘label’] if ‘label’ in song_info else “Not Available”
explicit = str(song_info[‘explicit’]) if ‘explicit’ in song_info else “Not Available” # Convert to string
genres = “, “.join(song_info[‘genres’]) if ‘genres’ in song_info else “Not Available”
author_url = song_info[‘artists’][0][‘external_urls’][‘spotify’] if ‘artists’ in song_info else “Not Available”
spotify_url = song_info[‘external_urls’][‘spotify’]
print(f"Track Number on Spotify: {track_number}”)
audiofile = eyed3.load(audio_file_path)
if audiofile.tag is None: # If the file has no tags, create a new tag
audiofile.initTag(version=eyed3.id3.ID3_V2_3)
# Set standard tags
audiofile.tag.artist = artist_name
audiofile.tag.album = album_name
audiofile.tag.album_artist = artist_name
audiofile.tag.title = title
audiofile.tag.recording_date = release_date
# Using helper function to add or update TXXX frames
add_or_update_txxx_frame(audiofile, “Album URL”, album_url)
add_or_update_txxx_frame(audiofile, “Eurydice”, “True”)
add_or_update_txxx_frame(audiofile, “Compilation”, “KK”)
add_or_update_txxx_frame(audiofile, “Genre”, genres)
add_or_update_txxx_frame(audiofile, “Author URL”, author_url)
add_or_update_txxx_frame(audiofile, “Label”, label)
add_or_update_txxx_frame(audiofile, “Explicit”, explicit)
add_or_update_txxx_frame(audiofile, “ISRC”, isrc)
add_or_update_txxx_frame(audiofile, “Spotify URL”, spotify_url)
audiofile.tag.comments.set(f"ISRC: {isrc}, Label: {label}, Explicit: {explicit}”)
audiofile.tag.save() # Save the metadata to the file
print(f"Metadata embedded into the file: {audio_file_path}“)
else:
print(“Song not found on Spotify.”)
else:
print(“Song could not be identified.”)
if name == “main”:
user_choice = get_user_choice()
audio_file_path = ‘D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3’
if user_choice == ‘1’:
print(”\n" + “.” * 15 + " ᴜsɪɴɢ YᴏᴜᴛᴜʙᴇACR " + “.” * 15 + “\n”)
song_tags = recognize_song(audio_file_path)
if song_tags:
print(f’Song identified: {song_tags}‘)
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get(‘artists’)[0].get(‘name’)
song_title = song_tags.get(‘title’)
safe_artist_name = re.sub(r’[/:?“<>|]‘, ‘’, artist_name)
safe_song_title = re.sub(r’[/:?”<>|]', ‘’, song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}“)
else:
print(‘Could not identify the song in YᴏᴜᴛᴜʙᴇACR.’)
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search(‘songs’, f”{artist_name} - {song_title}“)
if track_results:
track_id = track_results[0][‘id’]
album_artwork_url_template = track_results[0][‘attributes’][‘artwork’][‘url’]
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print(“Song not found on Apple Music.”)
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f”{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, ‘w’, encoding=‘utf-8’) as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}“)
else:
print(“Could not get the lyrics.”)
elif user_choice == ‘2’:
print(”\n" + “.” * 15 + " ᴜsɪɴɢ Sʜᴀᴢᴀᴍ " + “.” * 15 + “\n”)
song_tags = shazam_recognize_song(audio_file_path)
print(song_tags)
process_audio_file_with_spotify_search(audio_file_path)
apple_music_api = AppleMusicApi(Exception)
apple_music_api.get_access_token()
track_results = apple_music_api.search(‘songs’, f"{artist_name} - {song_title}“)
if track_results:
track_id = track_results[0][‘id’]
album_artwork_url_template = track_results[0][‘attributes’][‘artwork’][‘url’]
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print(“Song not found on Apple Music.”)
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f”{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, ‘w’, encoding=‘utf-8’) as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}")
else:
print(“Could not get the lyrics.”)
else:
print(“Invalid choice. Exiting.”)
exit()
after identifying song and embedding the tags , rename file to index number, artist name , album name , isrc number too in shazam
dont disturb acrcloud
|
915401b7058ec540a4a43b582b08475a
|
{
"intermediate": 0.43858757615089417,
"beginner": 0.426764577627182,
"expert": 0.13464786112308502
}
|
43,873
|
import base64
import acrcloud
import os
import eyed3
import eyed3.id3.frames
from eyed3.id3.frames import UserTextFrame
import requests
import json
import re
from my_shazam_utility import shazam_recognize_song
from applemusic_api import AppleMusicApi
from Acrcloudretrieve import recognize_song, set_id3_tags_mp3
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open(‘D:/Eurydice/Encompassing Data by discerning/config/config.json’, ‘r’) as config_file:
config_data = json.load(config_file)
return config_data
# Load the configuration on script start
config = load_config()
# Now also load Spotify credentials
CLIENT_ID = config[‘Spotify’][‘CLIENT_ID’]
CLIENT_SECRET = config[‘Spotify’][‘CLIENT_SECRET’]
def get_user_choice():
# Display a header
print(“=” * 50)
print(“Welcome to the Song Recognition Service!”)
print(“=” * 50)
# Provide instructions and options
print(“\nPlease select the recognition service you’d like to use:\n”)
print(" 1: YoutubeACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print(“-” * 50)
# Input prompt
choice = input(“Enter your choice (1 or 2) and press Enter: “)
# More flair to indicate processing/input received
print(”\n” + “.” * 25 + " Processing " + “.” * 25 + “\n”)
return choice
def add_or_update_txxx_frame(audiofile, description, value):
found = False
frames = audiofile.tag.frame_set.get(eyed3.id3.frames.USERTEXT_FID, [])
for frame in frames:
if frame.description == description:
frame.text = value
found = True
break
if not found:
# Create a new TXXX frame without specifying encoding
new_frame = eyed3.id3.frames.UserTextFrame(description=description, text=value)
# Previously: When encoding was being passed
# Now: Encoding isn’t specified as it’s not required or not supported based on the error
if not frames: # If it’s the first frame of this type
audiofile.tag.frame_set[eyed3.id3.frames.USERTEXT_FID] = [new_frame]
else:
frames.append(new_frame) # Append to exisiting list of USERTEXT frames
# Your Spotify authentication and song search functions:
def authenticate_spotify(client_id, client_secret):
auth_url = ‘https://accounts.spotify.com/api/token’
client_creds = f"{client_id}:{client_secret}“
client_creds_b64 = base64.b64encode(client_creds.encode())
headers = {‘Authorization’: f’Basic {client_creds_b64.decode()}'}
data = {‘grant_type’: ‘client_credentials’}
response = requests.post(auth_url, headers=headers, data=data)
access_token = response.json().get(‘access_token’)
return access_token
def search_spotify_for_song(access_token, artist_name, title):
base_url = “https://api.spotify.com/v1/search”
query = f”{title} artist:{artist_name}“
headers = {“Authorization”: f"Bearer {access_token}”}
params = {“q”: query, “type”: “track”, “limit”: 1}
response = requests.get(base_url, headers=headers, params=params)
results = response.json()
try:
track_info = results[‘tracks’][‘items’][0]
return track_info
except IndexError:
print(“Song not found on Spotify.”)
return None
def get_high_quality_album_art_url(song_info):
images = song_info[‘album’][‘images’] # Get the list of image dicts
if not images:
return None # No images available
# Sort the images by size, pick the largest
highest_quality_image = max(images, key=lambda x: x[‘width’]x[‘height’])
return highest_quality_image[‘url’]
def save_high_quality_album_art(image_url, file_path):
try:
response = requests.get(image_url, stream=True)
if response.status_code == 200:
with open(file_path, ‘wb’) as out_file:
for chunk in response.iter_content(1024):
out_file.write(chunk)
print(f"High quality album art saved: {file_path}“)
return True # Indicate success
else:
print(“Could not download the album art.”)
except Exception as e:
print(f"Error saving high-quality album art: {e}”)
return False # Indicate failure
def embed_album_art_to_song(file_path, image_path):
try:
audiofile = eyed3.load(file_path)
if audiofile.tag is None: # If the file has no tags, create a new tag
audiofile.initTag()
with open(image_path, ‘rb’) as img_file:
audiofile.tag.images.set(3, img_file.read(), ‘image/jpeg’)
audiofile.tag.save()
print(“High quality album art embedded into song.”)
except FileNotFoundError:
print(f"Failed to embed album art - No such file: {image_path}“)
def process_audio_file_with_spotify_search(audio_file_path):
shazam_data = shazam_recognize_song(audio_file_path)
if shazam_data:
artist_name = shazam_data[‘track’][‘subtitle’]
title = shazam_data[‘track’][‘title’]
print(f"Identified Song: {artist_name} - {title}”)
access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
song_info = search_spotify_for_song(access_token, artist_name, title)
if song_info:
print(json.dumps(song_info, indent=4)) # For debugging
print(“\n///////////////////////////////\n”)
album_name = song_info[‘album’][‘name’]
album_url = song_info[‘album’][‘external_urls’][‘spotify’]
track_number = song_info[‘track_number’]
release_date = song_info[‘album’][‘release_date’]
isrc = song_info.get(‘external_ids’, {}).get(‘isrc’, “Not Available”)
label = song_info[‘label’] if ‘label’ in song_info else “Not Available”
explicit = str(song_info[‘explicit’]) if ‘explicit’ in song_info else “Not Available” # Convert to string
genres = “, “.join(song_info[‘genres’]) if ‘genres’ in song_info else “Not Available”
author_url = song_info[‘artists’][0][‘external_urls’][‘spotify’] if ‘artists’ in song_info else “Not Available”
spotify_url = song_info[‘external_urls’][‘spotify’]
print(f"Track Number on Spotify: {track_number}”)
audiofile = eyed3.load(audio_file_path)
if audiofile.tag is None: # If the file has no tags, create a new tag
audiofile.initTag(version=eyed3.id3.ID3_V2_3)
# Set standard tags
audiofile.tag.artist = artist_name
audiofile.tag.album = album_name
audiofile.tag.album_artist = artist_name
audiofile.tag.title = title
audiofile.tag.recording_date = release_date
# Using helper function to add or update TXXX frames
add_or_update_txxx_frame(audiofile, “Album URL”, album_url)
add_or_update_txxx_frame(audiofile, “Eurydice”, “True”)
add_or_update_txxx_frame(audiofile, “Compilation”, “KK”)
add_or_update_txxx_frame(audiofile, “Genre”, genres)
add_or_update_txxx_frame(audiofile, “Author URL”, author_url)
add_or_update_txxx_frame(audiofile, “Label”, label)
add_or_update_txxx_frame(audiofile, “Explicit”, explicit)
add_or_update_txxx_frame(audiofile, “ISRC”, isrc)
add_or_update_txxx_frame(audiofile, “Spotify URL”, spotify_url)
audiofile.tag.comments.set(f"ISRC: {isrc}, Label: {label}, Explicit: {explicit}”)
audiofile.tag.save() # Save the metadata to the file
print(f"Metadata embedded into the file: {audio_file_path}“)
# Fetch high-quality album art URL
high_res_image_url = get_high_quality_album_art_url(song_info)
if high_res_image_url:
# Determine paths
image_file_path = os.path.splitext(audio_file_path)[0] + “.jpg”
# Save and embed album art
if save_high_quality_album_art(high_res_image_url, image_file_path):
embed_album_art_to_song(audio_file_path, image_file_path)
else:
print(“Skipping album art embed due to download failure.”)
else:
print(“No album art available.”)
new_file_name = f”{track_number:02d}. {artist_name} - {album_name} - {isrc}.mp3"
new_file_name = re.sub(r’[/:?“<>|]', ‘’, new_file_name) # Clean up characters not allowed in file names
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path) # Rename file
print(f"File has been renamed to: {new_file_name}”)
else:
print(“Song not found on Spotify.”)
else:
print(“Song could not be identified.”)
if name == “main”:
user_choice = get_user_choice()
audio_file_path = ‘D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3’
if user_choice == ‘1’:
print(“\n” + “.” * 15 + " ᴜsɪɴɢ YᴏᴜᴛᴜʙᴇACR " + “.” * 15 + “\n”)
song_tags = recognize_song(audio_file_path)
if song_tags:
print(f’Song identified: {song_tags}‘)
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get(‘artists’)[0].get(‘name’)
song_title = song_tags.get(‘title’)
safe_artist_name = re.sub(r’[/:?“<>|]‘, ‘’, artist_name)
safe_song_title = re.sub(r’[/:?”<>|]', ‘’, song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}“)
else:
print(‘Could not identify the song in YᴏᴜᴛᴜʙᴇACR.’)
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search(‘songs’, f”{artist_name} - {song_title}“)
if track_results:
track_id = track_results[0][‘id’]
album_artwork_url_template = track_results[0][‘attributes’][‘artwork’][‘url’]
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print(“Song not found on Apple Music.”)
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f”{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, ‘w’, encoding=‘utf-8’) as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}“)
else:
print(“Could not get the lyrics.”)
elif user_choice == ‘2’:
print(”\n" + “.” * 15 + " ᴜsɪɴɢ Sʜᴀᴢᴀᴍ " + “.” * 15 + “\n”)
song_tags = shazam_recognize_song(audio_file_path)
print(song_tags)
process_audio_file_with_spotify_search(audio_file_path)
else:
print(“Invalid choice. Exiting…”)
exit()
also change saved album art file to new_file_name
and also save externally lyrics and change the name
|
61242c05bc63b6f32553cf7c60eda187
|
{
"intermediate": 0.5159637331962585,
"beginner": 0.4156130254268646,
"expert": 0.06842323392629623
}
|
43,874
|
import base64
import acrcloud
import os
import eyed3
import eyed3.id3.frames
from eyed3.id3.frames import UserTextFrame
import requests
import json
import re
from my_shazam_utility import shazam_recognize_song
from applemusic_api import AppleMusicApi
from Acrcloudretrieve import recognize_song, set_id3_tags_mp3
from Retrieve_lyrics import get_lyrics
from erhalten_alb_covers import save_and_embed_album_cover
def load_config():
with open(‘D:/Eurydice/Encompassing Data by discerning/config/config.json’, ‘r’) as config_file:
config_data = json.load(config_file)
return config_data
# Load the configuration on script start
config = load_config()
# Now also load Spotify credentials
CLIENT_ID = config[‘Spotify’][‘CLIENT_ID’]
CLIENT_SECRET = config[‘Spotify’][‘CLIENT_SECRET’]
def get_user_choice():
# Display a header
print(“=” * 50)
print(“Welcome to the Song Recognition Service!”)
print(“=” * 50)
# Provide instructions and options
print(“\nPlease select the recognition service you’d like to use:\n”)
print(" 1: YoutubeACR - Fast and accurate music recognition")
print(" 2: Shazam - Discover music, artists, and lyrics in seconds")
# Separator for aesthetic purposes
print(“-” * 50)
# Input prompt
choice = input(“Enter your choice (1 or 2) and press Enter: “)
# More flair to indicate processing/input received
print(”\n” + “.” * 25 + " Processing " + “.” * 25 + “\n”)
return choice
def add_or_update_txxx_frame(audiofile, description, value):
found = False
frames = audiofile.tag.frame_set.get(eyed3.id3.frames.USERTEXT_FID, [])
for frame in frames:
if frame.description == description:
frame.text = value
found = True
break
if not found:
# Create a new TXXX frame without specifying encoding
new_frame = eyed3.id3.frames.UserTextFrame(description=description, text=value)
# Previously: When encoding was being passed
# Now: Encoding isn’t specified as it’s not required or not supported based on the error
if not frames: # If it’s the first frame of this type
audiofile.tag.frame_set[eyed3.id3.frames.USERTEXT_FID] = [new_frame]
else:
frames.append(new_frame) # Append to exisiting list of USERTEXT frames
# Your Spotify authentication and song search functions:
def authenticate_spotify(client_id, client_secret):
auth_url = ‘https://accounts.spotify.com/api/token’
client_creds = f"{client_id}:{client_secret}“
client_creds_b64 = base64.b64encode(client_creds.encode())
headers = {‘Authorization’: f’Basic {client_creds_b64.decode()}‘}
data = {‘grant_type’: ‘client_credentials’}
response = requests.post(auth_url, headers=headers, data=data)
access_token = response.json().get(‘access_token’)
return access_token
def search_spotify_for_song(access_token, artist_name, title):
base_url = “https://api.spotify.com/v1/search”
query = f”{title} artist:{artist_name}“
headers = {“Authorization”: f"Bearer {access_token}”}
params = {“q”: query, “type”: “track”, “limit”: 1}
response = requests.get(base_url, headers=headers, params=params)
results = response.json()
try:
track_info = results[‘tracks’][‘items’][0]
return track_info
except IndexError:
print(“Song not found on Spotify.”)
return None
def get_high_quality_album_art_url(song_info):
images = song_info[‘album’][‘images’] # Get the list of image dicts
if not images:
return None # No images available
# Sort the images by size, pick the largest
highest_quality_image = max(images, key=lambda x: x[‘width’]x[‘height’])
return highest_quality_image[‘url’]
def save_high_quality_album_art(image_url, file_path):
try:
response = requests.get(image_url, stream=True)
if response.status_code == 200:
with open(file_path, ‘wb’) as out_file:
for chunk in response.iter_content(1024):
out_file.write(chunk)
print(f"High quality album art saved: {file_path}“)
return True # Indicate success
else:
print(“Could not download the album art.”)
except Exception as e:
print(f"Error saving high-quality album art: {e}”)
return False # Indicate failure
def embed_album_art_to_song(file_path, image_path):
try:
audiofile = eyed3.load(file_path)
if audiofile.tag is None: # If the file has no tags, create a new tag
audiofile.initTag()
with open(image_path, ‘rb’) as img_file:
audiofile.tag.images.set(3, img_file.read(), ‘image/jpeg’)
audiofile.tag.save()
print(“High quality album art embedded into song.”)
except FileNotFoundError:
print(f"Failed to embed album art - No such file: {image_path}“)
def process_audio_file_with_spotify_search(audio_file_path):
shazam_data = shazam_recognize_song(audio_file_path)
if shazam_data:
artist_name = shazam_data[‘track’][‘subtitle’]
title = shazam_data[‘track’][‘title’]
print(f"Identified Song: {artist_name} - {title}”)
access_token = authenticate_spotify(CLIENT_ID, CLIENT_SECRET)
song_info = search_spotify_for_song(access_token, artist_name, title)
if song_info:
print(json.dumps(song_info, indent=4)) # For debugging
print(“\n///////////////////////////////\n”)
album_name = song_info[‘album’][‘name’]
album_url = song_info[‘album’][‘external_urls’][‘spotify’]
track_number = song_info[‘track_number’]
release_date = song_info[‘album’][‘release_date’]
isrc = song_info.get(‘external_ids’, {}).get(‘isrc’, “Not Available”)
label = song_info[‘label’] if ‘label’ in song_info else “Not Available”
explicit = str(song_info[‘explicit’]) if ‘explicit’ in song_info else “Not Available” # Convert to string
genres = “, “.join(song_info[‘genres’]) if ‘genres’ in song_info else “Not Available”
author_url = song_info[‘artists’][0][‘external_urls’][‘spotify’] if ‘artists’ in song_info else “Not Available”
spotify_url = song_info[‘external_urls’][‘spotify’]
print(f"Track Number on Spotify: {track_number}”)
audiofile = eyed3.load(audio_file_path)
if audiofile.tag is None: # If the file has no tags, create a new tag
audiofile.initTag(version=eyed3.id3.ID3_V2_3)
# Set standard tags
audiofile.tag.artist = artist_name
audiofile.tag.album = album_name
audiofile.tag.album_artist = artist_name
audiofile.tag.title = title
audiofile.tag.recording_date = release_date
# Using helper function to add or update TXXX frames
add_or_update_txxx_frame(audiofile, “Album URL”, album_url)
add_or_update_txxx_frame(audiofile, “Eurydice”, “True”)
add_or_update_txxx_frame(audiofile, “Compilation”, “KK”)
add_or_update_txxx_frame(audiofile, “Genre”, genres)
add_or_update_txxx_frame(audiofile, “Author URL”, author_url)
add_or_update_txxx_frame(audiofile, “Label”, label)
add_or_update_txxx_frame(audiofile, “Explicit”, explicit)
add_or_update_txxx_frame(audiofile, “ISRC”, isrc)
add_or_update_txxx_frame(audiofile, “Spotify URL”, spotify_url)
audiofile.tag.comments.set(f"ISRC: {isrc}, Label: {label}, Explicit: {explicit}”)
audiofile.tag.save() # Save the metadata to the file
print(f"Metadata embedded into the file: {audio_file_path}“)
# Fetch high-quality album art URL
high_res_image_url = get_high_quality_album_art_url(song_info)
if high_res_image_url:
# Determine paths
image_file_path = os.path.splitext(audio_file_path)[0] + “.jpg”
# Save and embed album art
if save_high_quality_album_art(high_res_image_url, image_file_path):
embed_album_art_to_song(audio_file_path, image_file_path)
else:
print(“Skipping album art embed due to download failure.”)
else:
print(“No album art available.”)
new_file_name = f”{track_number:02d}. {artist_name} - {album_name} - {isrc}.mp3"
new_file_name = re.sub(r’[/:?“<>|]’, ‘’, new_file_name) # Clean up characters not allowed in file names
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path) # Rename file
print(f"File has been renamed to: {new_file_name}”)
else:
print(“Song not found on Spotify.”)
else:
print(“Song could not be identified.”)
if name == “main”:
user_choice = get_user_choice()
audio_file_path = ‘D:/Eurydice/Encompassing Data by discerning/Test_file/Unknown_file.mp3’
if user_choice == ‘1’:
print(“\n” + “.” * 15 + " ᴜsɪɴɢ YᴏᴜᴛᴜʙᴇACR " + “.” * 15 + “\n”)
song_tags = recognize_song(audio_file_path)
if song_tags:
print(f’Song identified: {song_tags}‘)
set_id3_tags_mp3(audio_file_path, song_tags)
artist_name = song_tags.get(‘artists’)[0].get(‘name’)
song_title = song_tags.get(‘title’)
safe_artist_name = re.sub(r’[/:?“<>|]‘, ‘’, artist_name)
safe_song_title = re.sub(r’[/:?”<>|]', ‘’, song_title)
new_file_name = f"{safe_artist_name} - {safe_song_title}.mp3"
new_file_path = os.path.join(os.path.dirname(audio_file_path), new_file_name)
os.rename(audio_file_path, new_file_path)
print(f"File has been renamed to: {new_file_name}“)
else:
print(‘Could not identify the song in YᴏᴜᴛᴜʙᴇACR.’)
apple_music_api = AppleMusicApi(Exception) # Initialize AppleMusicApi with necessary authentication
apple_music_api.get_access_token()
track_results = apple_music_api.search(‘songs’, f”{artist_name} - {song_title}“)
if track_results:
track_id = track_results[0][‘id’]
album_artwork_url_template = track_results[0][‘attributes’][‘artwork’][‘url’]
save_and_embed_album_cover(new_file_path, artist_name, song_title, album_artwork_url_template)
else:
print(“Song not found on Apple Music.”)
lrc_lyrics = get_lyrics(safe_artist_name, safe_song_title)
if lrc_lyrics:
lrc_file_path = os.path.join(os.path.dirname(audio_file_path), f”{safe_artist_name} - {safe_song_title}.lrc")
with open(lrc_file_path, ‘w’, encoding=‘utf-8’) as lrc_file:
lrc_file.write(lrc_lyrics)
print(f"Saved LRC file to: {lrc_file_path}“)
else:
print(“Could not get the lyrics.”)
elif user_choice == ‘2’:
print(”\n" + “.” * 15 + " ᴜsɪɴɢ Sʜᴀᴢᴀᴍ " + “.” * 15 + “\n”)
song_tags = shazam_recognize_song(audio_file_path)
print(song_tags)
process_audio_file_with_spotify_search(audio_file_path)
else:
print(“Invalid choice. Exiting…”)
exit()
after embedding the album art just change the name to track number - artist name - album name - isrc
also download the lyric file and after saving externally, change the file name
|
75971ecf9e39eec5666b1f289884e590
|
{
"intermediate": 0.46537768840789795,
"beginner": 0.44075390696525574,
"expert": 0.09386839717626572
}
|
43,875
|
in following code :
sls = [0.01,0.015, 0.02, 0.025 ,0.03,0.035, 0.04,0.045, 0.05,0.055, 0.06,0.065, 0.07,0.075,0.08,0.085, 0.09,0.095, 0.1]
tls = [0.01,0.015, 0.02, 0.025 ,0.03,0.035, 0.04,0.045, 0.05,0.055, 0.06,0.065, 0.07,0.075,0.08,0.085, 0.09,0.095, 0.1]
hours_to_look = [24 ,48 , 72, 96, 120]
symbols = pred_df['Symbol'].unique()
current_symbol = ''
columns = []
for sl in sls:
for tl in tls:
for hours in hours_to_look:
columns.add(f'{sl}_{tl}_{hours}')
combined_columns = list(pred_df.columns) + columns
all_results= []
for index, row in pred_df.iterrows():
date, symbol, start_price = row['Date'], row['Symbol'], row['Close']
row_result = []
if(symbol != current_symbol):
hourly_path = find_first_matching_1h(symbol)
hourly_df = pd.read_csv(hourly_path)
hourly_df['Date'] = pd.to_datetime(hourly_df['Date'], format="ISO8601", utc=True)
for sl in sls:
for tl in tls:
for hours in hours_to_look:
result = analyze_price_move(date, start_price,sl,tl,hourly_df)
row_result.add(result)
all_results.add(row_result)
i want to add calculated rows and columns to my pred_df
|
8bcb96f9ad9915fa5bfaaa24c6c27e1b
|
{
"intermediate": 0.44902363419532776,
"beginner": 0.2661116421222687,
"expert": 0.28486472368240356
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.