row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
37,746
hi
6d55861d9d9f192cd53cd42e5db55b4c
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,747
Şu c# wpf kodlarımda filmler butonuna basınca ekranda Filmler.xaml page sayfasını açıyor ancak titlebar yani control bar yok oluyor neden <ui:FluentWindow x:Class="İnatBox.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:İnatBox" mc:Ignorable="d" WindowStartupLocation="CenterScreen" ExtendsContentIntoTitleBar="True" WindowBackdropType="Auto" FontFamily="Segoe UI" WindowCornerPreference="Round" Title="İnatBox" Height="450" Width="800" FontWeight="Bold"> <Grid> <ui:TitleBar Title="İnatBox" VerticalAlignment="Top"/> <Viewbox Margin="120" VerticalAlignment="Center" HorizontalAlignment="Center" MaxWidth="750"> <DockPanel> <ui:TextBlock DockPanel.Dock="Top" Text="İnatBox" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="18" FontTypography="Title" FontWeight="Bold"/> <ui:Button x:Name="FilmlerButton" Content="Filmler" Click="FilmlerButton_Click" BorderThickness="0"/> <ui:Button x:Name="DizilerButton" Content="Diziler" Click="DizilerButton_Click" BorderThickness="0" Margin="12,0,0,0"/> </DockPanel> </Viewbox> </Grid> </ui:FluentWindow> <Page x:Class="İnatBox.Filmler" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:İnatBox" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800" Title="Filmler"> <Grid Margin="50"> <TextBlock Text="Merhaba" VerticalAlignment="Center" HorizontalAlignment="Center"/> </Grid> </Page>
debe2fccfea76e1625a8bd56bdf1a9e6
{ "intermediate": 0.22588634490966797, "beginner": 0.511181652545929, "expert": 0.2629319727420807 }
37,748
i have this json file "{ "title": "Antiques", "metadata": { "color": "#35C1E0" }, "data_schema": { "steps": [], "fields": [ { "name": "images", "step": 2, "type": { "name": "image", "validators": [] }, "position": 1, "component": { "data": [ { "add": "Add", "l10n": { "ar": { "add": "يسسب", "subtitle": "ذنتي بمتد نبيمتب نمشيستب شمسنيت بنشمسيت بمنشتسي بنمتشسي بنمشتس يبمنشتس يمنب يسمنتب ش" } }, "subtitle": "The first photo will be displayed in the search results, select the best one. You can upload up to 10 photos in JPG or PNG format. The maximum photo size is 10MB.", "nb_images": 9 } ], "name": "inputImageProduct" }, "form_group": 1, "label_read": "Image(s)", "label_write": "Image(s)", "placeholder": "Images", "l10n": { "ar": { "name": "AR", "pattern": 0, "error_message": "AR" }, "ru": { "name": "RU", "pattern": 0, "error_message": "RU" } } }, { "name": "description", "step": 1, "type": { "name": "string", "validators": [ { "name": "required", "pattern": ".{2,}", "error_message": "Description is required" }, { "name": "minimum", "pattern": 0, "error_message": "Description is too short" }, { "name": "maximum", "pattern": 4000, "error_message": "Description is too big" } ] }, "position": 1, "component": { "data": [], "name": "textArea" }, "form_group": 1, "label_read": "Description", "label_write": "Description", "placeholder": "Description", "l10n": { "ar": { "name": "AR", "pattern": 0, "error_message": "AR" }, "ru": { "name": "RU", "pattern": 0, "error_message": "RU" } } }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "يسبسيدي" }, "ru": { "name": "RU", "pattern": 0, "error_message": "RU" } }, "name": "tag", "step": 1, "type": { "name": "tag", "validators": [ { "l10n": { "ar": { "error_message": "الإسم {} الأول مطلوب" } }, "name": "maximum", "pattern": 7, "error_message": "maximum char {} " } ] }, "position": 1, "component": { "data": [], "name": "inputTag" }, "form_group": 1, "label_read": "Tag", "label_write": "Tag", "placeholder": "You can add up to {} tags" }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس" }, "ru": { "name": "RU", "pattern": 0, "error_message": "RU" } }, "name": "price", "step": 1, "type": { "name": "text", "validators": [ { "name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers" }, { "name": "required", "error_message": "required" } ] }, "position": 0, "component": { "data": [], "name": "inputPrice", "dependency": [ { "l10n": { "ar": { "label_read": "", "label_write": "", "placeholder": "يسيس ب" } }, "name": "negotiable", "step": -1, "type": { "name": "checkbox", "validators": [] }, "position": 1, "component": { "data": [], "name": "inputToggleCheckbox" }, "label_read": "Negotiable", "label_write": "Negotiable", "placeholder": "" } ] }, "form_group": 1, "label_read": "Price", "label_write": "Price", "placeholder": "AED" }, { "name": "fast sell", "step": 1, "type": { "name": "checkbox", "validators": [] }, "position": 1, "component": { "data": { "title": "Want to sell this ad faster", "description": "Your listing will be marked as a faster sell" }, "name": "inputToggleCheckbox" }, "form_group": 1, "label_read": "Fast Sell", "label_write": "Fast Sell", "placeholder": "", "l10n": { "ar": { "name": "AR", "pattern": 0, "error_message": "AR" }, "ru": { "name": "RU", "pattern": 0, "error_message": "RU" } } } ], "filters": [ { "l10n": { "ar": { "label_read": "تبوك", "placeholder": "" } }, "name": "type of ads", "type": { "name": "radio", "validators": [] }, "position": 1, "component": { "data": [ { "id": "11111", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Offers" }, { "id": "333333", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Auctions" }, { "id": "666666", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Live Auctions" } ], "name": "inputRadioRounded" }, "label_read": "Type of Ads", "placeholder": "", "filter_group": 1 }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "", "placeholder": "" } }, "name": "delivery methods", "step": 1, "type": { "name": "radio", "validators": [] }, "position": 1, "component": { "data": [ { "id": "11111", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Pick Up" }, { "id": "22222", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Delivery Service" } ], "name": "inputCheckboxRounded" }, "form_group": 2, "label_read": "Delivery Methods", "label_write": "", "placeholder": "" }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "", "placeholder": "" } }, "name": "payment methods", "step": 1, "type": { "name": "radio", "validators": [] }, "position": 1, "component": { "data": [ { "id": "11111", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "QR" }, { "id": "22222", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Cash" }, { "id": "22222", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Online Payment" } ], "name": "inputCheckboxRounded" }, "form_group": 2, "label_read": "Payment Methods", "label_write": "", "placeholder": "" }, { "l10n": { "ar": { "label_read": "سسيب بسيب", "label_write": "", "placeholder": "" } }, "name": "fast sell", "type": { "name": "checkbox", "validators": [] }, "position": 1, "component": { "data": [], "name": "inputCheckboxTic" }, "label_read": "Fast Sell", "placeholder": "", "filter_group": 4 }, { "l10n": { "ar": { "label_read": "تبوك", "placeholder": "" } }, "name": "ads posted", "type": { "name": "radio", "validators": [] }, "position": 1, "component": { "data": [ { "id": "11111", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "24 Hours" }, { "id": "222222", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "7 Days" }, { "id": "333333", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "All Time" } ], "name": "inputCheckboxRounded" }, "label_read": "Ads Posted", "placeholder": "", "filter_group": 5 }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "", "placeholder": "" } }, "name": "keyword", "step": 1, "type": { "name": "text", "validators": [] }, "position": 0, "component": { "data": [], "name": "inputSearchKeywords" }, "label_read": "Keyword", "label_write": "Keyword", "placeholder": "Type in the keyword", "filter_group": 7 }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "", "placeholder": "" } }, "name": "price", "type": { "name": "text", "validators": [ { "l10n": { "ar": { "error_message": "" } }, "name": "", "pattern": "", "error_message": "" }, { "l10n": { "ar": { "error_message": "" } }, "name": "", "pattern": "", "error_message": "" } ] }, "position": 1, "component": { "data": { "to": "To", "l10n": { "ar": { "to": "سيبسب", "from_text": "ثسبب" } }, "from_text": "From" }, "name": "inputTextDualPrice", "dependency": [ { "l10n": { "ar": { "label_read": "", "label_write": "", "placeholder": "يسيس ب" } }, "name": "negotiable", "step": -1, "type": { "name": "checkbox", "validators": [] }, "position": 1, "component": { "data": [], "name": "inputCheckboxTic" }, "label_read": "", "label_write": "", "placeholder": "Negotiable" } ] }, "label_read": "Price", "label_write": "", "placeholder": "", "filter_group": 3 }, { "l10n": { "ar": { "label_read": "تبوك", "placeholder": "سيبس" } }, "name": "emirate", "type": { "name": "radio", "validators": [] }, "position": 1, "component": { "data": [ { "id": "11111", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Dubai" }, { "id": "222222", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Abu Dhabi" }, { "id": "333333", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Ras Al Khaimah" }, { "id": "444444", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Sharjah" }, { "id": "555555", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Fujairah" }, { "id": "6666666", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Ajman" }, { "id": "777777", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Umm Al Quwain" }, { "id": "888888", "l10n": { "ar": { "name": "يسببسيب" } }, "name": "Al Ain" } ], "name": "inputCheckboxRoundedLocation" }, "label_read": "Emirate", "placeholder": "", "filter_group": 5 } ], "stepper": [ { "id": "", "data": { "l10n": { "ar": { "ad_title": "شي ثهته" } }, "ad_title": "Ad Title", "category": "Category", "background": true, "navigation": true }, "name": "search_product", "position": 1 }, { "id": "", "data": { "l10n": { "ar": { "ad_title": "شي ثهته" } }, "ad_title": "Product detailc", "category": "Product detail", "background": true }, "name": "product_detail", "position": 2 }, { "id": "", "data": { "l10n": { "ar": { "location": "سنتاي" } }, "location": "Location", "background": true, "navigation": true }, "name": "location", "position": 3 }, { "id": "", "data": { "l10n": { "ar": { "delivery": "يثمهد", "payment_methods": "حشغو وثفاخ" } }, "delivery": "Delivery", "background": true, "navigation": true, "payment_cells": [ { "id": "1", "alt": "", "hint": "How it works?", "icon": "/delivery-and-payment-method/qr-code.svg", "type": "qrcode", "title": "QR Code Release (Secure)", "additional": "+15 AED", "hint_modal": { "image": "/delivery-and-payment-method/hint.png", "steps": [ { "title": "The customer pays the full amount online, but it will be held in our system.", "subtitle": "To protect buyers and sellers from fraud, a mutual exchange can be performed from anywhere, at anytime, using our secure escrow service." }, { "title": "Once the buyer receives the item, they will scan the QR code to release the funds.", "subtitle": "The seller will allow the customer to scan a designated QR code, which confirms that the item has been received, causing the payment to be moved into the seller’s account immediately." } ], "title": "Release Online Payment to Seller Via QR Code" } }, { "id": "2", "alt": "", "icon": "/delivery-and-payment-method/cash.svg", "type": "default", "title": "Cash", "additional": "" }, { "id": "3", "alt": "", "icon": "/delivery-and-payment-method/debit-card.svg", "type": "default", "title": "Online Payment" }, { "id": "4", "alt": "", "icon": "/delivery-and-payment-method/cash.svg", "type": "default", "title": "Cash on Delivery" } ], "delivery_cells": [ { "id": "123", "alt": "", "icon": "/delivery-and-payment-method/pickup.svg", "type": "pickup", "title": "Pick Up", "subtitle": "To hand deliver the item to your buyer", "payment_ids": [ "1", "2" ] }, { "id": "957", "alt": "", "icon": "/delivery-and-payment-method/truck.svg", "type": "delivery-service", "title": "Delivery Service", "subtitle": "Please select the package size", "payment_ids": [ "3", "4" ], "package_sizes": [ { "id": "1", "alt": "", "icon": "/delivery-and-payment-method/small-box.png", "title": "Small", "subtitle": "E.g. Mobile" }, { "id": "2", "alt": "", "icon": "/delivery-and-payment-method/medium-box.png", "title": "Medium", "subtitle": "E.g. Guitar" }, { "id": "3", "alt": "", "icon": "/delivery-and-payment-method/large-box.png", "title": "Large", "subtitle": "E.g. TV" }, { "id": "4", "alt": "", "icon": "/delivery-and-payment-method/extra-large-box.png", "title": "Extra Large", "subtitle": "E.g. Fridge" } ], "delivery_method": [ { "icon": "", "title": "", "subtitle": "", "additional": "" }, { "icon": "", "title": "", "subtitle": "", "additional": "" }, { "icon": "", "title": "", "subtitle": "", "additional": "" } ] } ], "payment_methods": "Payment methods", "payment_methods_title": "Payment Methods ", "delivery_methods_title": "Delivery Methods" }, "name": "delivery_and_payment_methods", "position": 4 }, { "id": "", "data": { "l10n": { "ar": { "phone": "حاخر" } }, "phone": "Phone", "background": false, "navigation": false }, "name": "confirm_mobile_number", "position": 5 }, { "id": "", "data": { "background": false, "navigation": false }, "name": "review_your_ad", "position": 7 } ], "form_group": [ { "data": [ { "l10n": { "ar": { "title": "لقب" } }, "title": "" } ] }, { "data": [ { "l10n": { "ar": { "title": "لقب" } }, "title": "Images" } ] } ], "filter_group": [], "auction_fields": [ { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس" } }, "name": "initial_price", "step": 1, "type": { "name": "text", "validators": [ { "name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers" }, { "name": "required", "error_message": "required" } ] }, "position": 0, "component": { "data": [], "name": "inputPrice", "dependency": [] }, "form_group": 1, "label_read": "Initial price", "label_write": "Initial price", "placeholder": "AED" }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس" } }, "name": "reserve_price", "step": 1, "type": { "name": "text", "validators": [ { "name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers" }, { "name": "required", "error_message": "required" } ] }, "position": 0, "component": { "data": [], "name": "inputPrice", "dependency": [] }, "form_group": 1, "label_read": "Reserve price", "label_write": "Reserve price", "placeholder": "AED" }, { "l10n": { "ar": { "label_read": "", "label_write": "", "placeholder": "يسيس ب" } }, "name": "chat", "step": 1, "type": { "name": "checkbox", "validators": [] }, "position": 0, "component": { "data": { "title": "Turn on chat" }, "name": "inputToggleCheckbox", "dependency": [] }, "form_group": 1, "label_read": "Chat", "label_write": "Chat", "placeholder": "" }, { "name": "duration", "step": 1, "type": { "name": "select", "validators": [ { "name": "required", "error_message": "Duration is required" } ] }, "position": 0, "component": { "data": [ { "id": "1", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "2 Days", "seconds": 172800 }, { "id": "2", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "1 Week", "seconds": 604800 }, { "id": "3", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "2 Weeks", "seconds": 1209600 }, { "id": "4", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "3 Weeks", "seconds": 1814400 }, { "id": "5", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "4 Weeks", "seconds": 2419200 } ], "name": "inputDurationSelect" }, "form_group": 1, "label_read": "Duration", "label_write": "Duration", "placeholder": "Select" }, { "l10n": { "ar": { "label_read": "", "label_write": "", "placeholder": "يسيس ب" } }, "name": "enable_start_date", "step": 1, "type": { "name": "checkbox", "validators": [] }, "position": 0, "component": { "data": { "title": "Enable Scheduled auction" }, "name": "inputToggleCheckbox", "dependency": [ { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس" } }, "name": "start_date", "step": 1, "type": { "name": "text", "validators": [ { "name": "required", "error_message": "required" } ] }, "position": 0, "component": { "data": { "title": "Select a date and time" }, "name": "inputDatePicker", "dependency": [] }, "form_group": 1, "label_read": "Starts on", "label_write": "Starts on", "placeholder": "Starts on" } ] }, "form_group": 1, "label_read": "Scheduled auction", "label_write": "Scheduled auction", "placeholder": "" } ], "live_auction_fields": [ { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس" } }, "name": "initial_price", "step": 1, "type": { "name": "text", "validators": [ { "name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers" }, { "name": "required", "error_message": "required" } ] }, "position": 0, "component": { "data": [], "name": "inputPrice", "dependency": [] }, "form_group": 1, "label_read": "Initial price", "label_write": "Initial price", "placeholder": "AED" }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس" } }, "name": "reserve_price", "step": 1, "type": { "name": "text", "validators": [ { "name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers" }, { "name": "required", "error_message": "required" } ] }, "position": 0, "component": { "data": [], "name": "inputPrice", "dependency": [] }, "form_group": 1, "label_read": "Reserve price", "label_write": "Reserve price", "placeholder": "AED" }, { "l10n": { "ar": { "label_read": "", "label_write": "", "placeholder": "يسيس ب" } }, "name": "chat", "step": 1, "type": { "name": "checkbox", "validators": [] }, "position": 0, "component": { "data": { "title": "Turn on chat" }, "name": "inputToggleCheckbox", "dependency": [] }, "form_group": 1, "label_read": "Chat", "label_write": "Chat", "placeholder": "" }, { "name": "duration", "step": 1, "type": { "name": "select", "validators": [ { "name": "required", "error_message": "Duration is required" } ] }, "position": 0, "component": { "data": [ { "id": "1", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "30 minutes", "seconds": 1800 }, { "id": "2", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "45 minutes", "seconds": 2700 }, { "id": "3", "l10n": { "ar": { "name": "يسببسيب" } }, "label": "60 minutes", "seconds": 3600 } ], "name": "inputDurationSelect" }, "form_group": 1, "label_read": "Duration", "label_write": "Duration", "placeholder": "Select" }, { "l10n": { "ar": { "label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس" } }, "name": "start_date", "step": 1, "type": { "name": "text", "validators": [ { "name": "required", "error_message": "required" } ] }, "position": 0, "component": { "data": { "title": "Select a date and time" }, "name": "inputDatePicker", "dependency": [] }, "form_group": 1, "label_read": "Starts on", "label_write": "Starts on", "placeholder": "Starts on" } ] } }" I need a script to add l10n for all the objects with ar and ru if not found if we already have l18n with ar we should add ru "name": "minimum",
"pattern": 0,
"error_message": "Description is too short",
"l10n": {
"ar": {
"name": "ARA",
"pattern": 0,
"error_message": "ARABIC"
},
"ru": {
"name": "RUS",
"pattern": 0,
"error_message": "RUS" like this example
87fd02bb40d0670d0e9fff16c54131d1
{ "intermediate": 0.3433822691440582, "beginner": 0.4787066578865051, "expert": 0.17791101336479187 }
37,749
i have this json file "{"title": "Antiques", "metadata": {"color": "#35C1E0"}, "data_schema": {"steps": [], "fields": [{"name": "images", "step": 2, "type": {"name": "image", "validators": []}, "position": 1, "component": {"data": [{"add": "Add", "l10n": {"ar": {"add": "يسسب", "subtitle": "ذنتي بمتد نبيمتب نمشيستب شمسنيت بنشمسيت بمنشتسي بنمتشسي بنمشتس يبمنشتس يمنب يسمنتب ش"}}, "subtitle": "The first photo will be displayed in the search results, select the best one. You can upload up to 10 photos in JPG or PNG format. The maximum photo size is 10MB.", "nb_images": 9}], "name": "inputImageProduct"}, "form_group": 1, "label_read": "Image(s)", "label_write": "Image(s)", "placeholder": "Images"}, {"name": "description", "step": 1, "type": {"name": "string", "validators": [{"name": "required", "pattern": ".{2,}", "error_message": "Description is required"}, {"name": "minimum", "pattern": 0, "error_message": "Description is too short"}, {"name": "maximum", "pattern": 4000, "error_message": "Description is too big"}]}, "position": 1, "component": {"data": [], "name": "textArea"}, "form_group": 1, "label_read": "Description", "label_write": "Description", "placeholder": "Description"}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "يسبسيدي"}}, "name": "tag", "step": 1, "type": {"name": "tag", "validators": [{"l10n": {"ar": {"error_message": "الإسم {} الأول مطلوب"}}, "name": "maximum", "pattern": 7, "error_message": "maximum char {} "}]}, "position": 1, "component": {"data": [], "name": "inputTag"}, "form_group": 1, "label_read": "Tag", "label_write": "Tag", "placeholder": "You can add up to {} tags"}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس"}}, "name": "price", "step": 1, "type": {"name": "text", "validators": [{"name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers"}, {"name": "required", "error_message": "required"}]}, "position": 0, "component": {"data": [], "name": "inputPrice", "dependency": [{"l10n": {"ar": {"label_read": "", "label_write": "", "placeholder": "يسيس ب"}}, "name": "negotiable", "step": -1, "type": {"name": "checkbox", "validators": []}, "position": 1, "component": {"data": [], "name": "inputToggleCheckbox"}, "label_read": "Negotiable", "label_write": "Negotiable", "placeholder": ""}]}, "form_group": 1, "label_read": "Price", "label_write": "Price", "placeholder": "AED"}, {"name": "fast sell", "step": 1, "type": {"name": "checkbox", "validators": []}, "position": 1, "component": {"data": {"title": "Want to sell this ad faster", "description": "Your listing will be marked as a faster sell"}, "name": "inputToggleCheckbox"}, "form_group": 1, "label_read": "Fast Sell", "label_write": "Fast Sell", "placeholder": ""}], "filters": [{"l10n": {"ar": {"label_read": "تبوك", "placeholder": ""}}, "name": "type of ads", "type": {"name": "radio", "validators": []}, "position": 1, "component": {"data": [{"id": "11111", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Offers"}, {"id": "333333", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Auctions"}, {"id": "666666", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Live Auctions"}], "name": "inputRadioRounded"}, "label_read": "Type of Ads", "placeholder": "", "filter_group": 1}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "", "placeholder": ""}}, "name": "delivery methods", "step": 1, "type": {"name": "radio", "validators": []}, "position": 1, "component": {"data": [{"id": "11111", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Pick Up"}, {"id": "22222", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Delivery Service"}], "name": "inputCheckboxRounded"}, "form_group": 2, "label_read": "Delivery Methods", "label_write": "", "placeholder": ""}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "", "placeholder": ""}}, "name": "payment methods", "step": 1, "type": {"name": "radio", "validators": []}, "position": 1, "component": {"data": [{"id": "11111", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "QR"}, {"id": "22222", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Cash"}, {"id": "22222", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Online Payment"}], "name": "inputCheckboxRounded"}, "form_group": 2, "label_read": "Payment Methods", "label_write": "", "placeholder": ""}, {"l10n": {"ar": {"label_read": "سسيب بسيب", "label_write": "", "placeholder": ""}}, "name": "fast sell", "type": {"name": "checkbox", "validators": []}, "position": 1, "component": {"data": [], "name": "inputCheckboxTic"}, "label_read": "Fast Sell", "placeholder": "", "filter_group": 4}, {"l10n": {"ar": {"label_read": "تبوك", "placeholder": ""}}, "name": "ads posted", "type": {"name": "radio", "validators": []}, "position": 1, "component": {"data": [{"id": "11111", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "24 Hours"}, {"id": "222222", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "7 Days"}, {"id": "333333", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "All Time"}], "name": "inputCheckboxRounded"}, "label_read": "Ads Posted", "placeholder": "", "filter_group": 5}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "", "placeholder": ""}}, "name": "keyword", "step": 1, "type": {"name": "text", "validators": []}, "position": 0, "component": {"data": [], "name": "inputSearchKeywords"}, "label_read": "Keyword", "label_write": "Keyword", "placeholder": "Type in the keyword", "filter_group": 7}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "", "placeholder": ""}}, "name": "price", "type": {"name": "text", "validators": [{"l10n": {"ar": {"error_message": ""}}, "name": "", "pattern": "", "error_message": ""}, {"l10n": {"ar": {"error_message": ""}}, "name": "", "pattern": "", "error_message": ""}]}, "position": 1, "component": {"data": {"to": "To", "l10n": {"ar": {"to": "سيبسب", "from_text": "ثسبب"}}, "from_text": "From"}, "name": "inputTextDualPrice", "dependency": [{"l10n": {"ar": {"label_read": "", "label_write": "", "placeholder": "يسيس ب"}}, "name": "negotiable", "step": -1, "type": {"name": "checkbox", "validators": []}, "position": 1, "component": {"data": [], "name": "inputCheckboxTic"}, "label_read": "", "label_write": "", "placeholder": "Negotiable"}]}, "label_read": "Price", "label_write": "", "placeholder": "", "filter_group": 3}, {"l10n": {"ar": {"label_read": "تبوك", "placeholder": "سيبس"}}, "name": "emirate", "type": {"name": "radio", "validators": []}, "position": 1, "component": {"data": [{"id": "11111", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Dubai"}, {"id": "222222", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Abu Dhabi"}, {"id": "333333", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Ras Al Khaimah"}, {"id": "444444", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Sharjah"}, {"id": "555555", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Fujairah"}, {"id": "6666666", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Ajman"}, {"id": "777777", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Umm Al Quwain"}, {"id": "888888", "l10n": {"ar": {"name": "يسببسيب"}}, "name": "Al Ain"}], "name": "inputCheckboxRoundedLocation"}, "label_read": "Emirate", "placeholder": "", "filter_group": 5}], "stepper": [{"id": "", "data": {"l10n": {"ar": {"ad_title": "شي ثهته"}}, "ad_title": "Ad Title", "category": "Category", "background": true, "navigation": true}, "name": "search_product", "position": 1}, {"id": "", "data": {"l10n": {"ar": {"ad_title": "شي ثهته"}}, "ad_title": "Product detailc", "category": "Product detail", "background": true}, "name": "product_detail", "position": 2}, {"id": "", "data": {"l10n": {"ar": {"location": "سنتاي"}}, "location": "Location", "background": true, "navigation": true}, "name": "location", "position": 3}, {"id": "", "data": {"l10n": {"ar": {"delivery": "يثمهد", "payment_methods": "حشغو وثفاخ"}}, "delivery": "Delivery", "background": true, "navigation": true, "payment_cells": [{"id": "1", "alt": "", "hint": "How it works?", "icon": "/delivery-and-payment-method/qr-code.svg", "type": "qrcode", "title": "QR Code Release (Secure)", "additional": "+15 AED", "hint_modal": {"image": "/delivery-and-payment-method/hint.png", "steps": [{"title": "The customer pays the full amount online, but it will be held in our system.", "subtitle": "To protect buyers and sellers from fraud, a mutual exchange can be performed from anywhere, at anytime, using our secure escrow service."}, {"title": "Once the buyer receives the item, they will scan the QR code to release the funds.", "subtitle": "The seller will allow the customer to scan a designated QR code, which confirms that the item has been received, causing the payment to be moved into the seller’s account immediately."}], "title": "Release Online Payment to Seller Via QR Code"}}, {"id": "2", "alt": "", "icon": "/delivery-and-payment-method/cash.svg", "type": "default", "title": "Cash", "additional": ""}, {"id": "3", "alt": "", "icon": "/delivery-and-payment-method/debit-card.svg", "type": "default", "title": "Online Payment"}, {"id": "4", "alt": "", "icon": "/delivery-and-payment-method/cash.svg", "type": "default", "title": "Cash on Delivery"}], "delivery_cells": [{"id": "123", "alt": "", "icon": "/delivery-and-payment-method/pickup.svg", "type": "pickup", "title": "Pick Up", "subtitle": "To hand deliver the item to your buyer", "payment_ids": ["1", "2"]}, {"id": "957", "alt": "", "icon": "/delivery-and-payment-method/truck.svg", "type": "delivery-service", "title": "Delivery Service", "subtitle": "Please select the package size", "payment_ids": ["3", "4"], "package_sizes": [{"id": "1", "alt": "", "icon": "/delivery-and-payment-method/small-box.png", "title": "Small", "subtitle": "E.g. Mobile"}, {"id": "2", "alt": "", "icon": "/delivery-and-payment-method/medium-box.png", "title": "Medium", "subtitle": "E.g. Guitar"}, {"id": "3", "alt": "", "icon": "/delivery-and-payment-method/large-box.png", "title": "Large", "subtitle": "E.g. TV"}, {"id": "4", "alt": "", "icon": "/delivery-and-payment-method/extra-large-box.png", "title": "Extra Large", "subtitle": "E.g. Fridge"}], "delivery_method": [{"icon": "", "title": "", "subtitle": "", "additional": ""}, {"icon": "", "title": "", "subtitle": "", "additional": ""}, {"icon": "", "title": "", "subtitle": "", "additional": ""}]}], "payment_methods": "Payment methods", "payment_methods_title": "Payment Methods ", "delivery_methods_title": "Delivery Methods"}, "name": "delivery_and_payment_methods", "position": 4}, {"id": "", "data": {"l10n": {"ar": {"phone": "حاخر"}}, "phone": "Phone", "background": false, "navigation": false}, "name": "confirm_mobile_number", "position": 5}, {"id": "", "data": {"background": false, "navigation": false}, "name": "review_your_ad", "position": 7}], "form_group": [{"data": [{"l10n": {"ar": {"title": "لقب"}}, "title": ""}]}, {"data": [{"l10n": {"ar": {"title": "لقب"}}, "title": "Images"}]}], "filter_group": [], "auction_fields": [{"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس"}}, "name": "initial_price", "step": 1, "type": {"name": "text", "validators": [{"name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers"}, {"name": "required", "error_message": "required"}]}, "position": 0, "component": {"data": [], "name": "inputPrice", "dependency": []}, "form_group": 1, "label_read": "Initial price", "label_write": "Initial price", "placeholder": "AED"}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس"}}, "name": "reserve_price", "step": 1, "type": {"name": "text", "validators": [{"name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers"}, {"name": "required", "error_message": "required"}]}, "position": 0, "component": {"data": [], "name": "inputPrice", "dependency": []}, "form_group": 1, "label_read": "Reserve price", "label_write": "Reserve price", "placeholder": "AED"}, {"l10n": {"ar": {"label_read": "", "label_write": "", "placeholder": "يسيس ب"}}, "name": "chat", "step": 1, "type": {"name": "checkbox", "validators": []}, "position": 0, "component": {"data": {"title": "Turn on chat"}, "name": "inputToggleCheckbox", "dependency": []}, "form_group": 1, "label_read": "Chat", "label_write": "Chat", "placeholder": ""}, {"name": "duration", "step": 1, "type": {"name": "select", "validators": [{"name": "required", "error_message": "Duration is required"}]}, "position": 0, "component": {"data": [{"id": "1", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "2 Days", "seconds": 172800}, {"id": "2", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "1 Week", "seconds": 604800}, {"id": "3", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "2 Weeks", "seconds": 1209600}, {"id": "4", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "3 Weeks", "seconds": 1814400}, {"id": "5", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "4 Weeks", "seconds": 2419200}], "name": "inputDurationSelect"}, "form_group": 1, "label_read": "Duration", "label_write": "Duration", "placeholder": "Select"}, {"l10n": {"ar": {"label_read": "", "label_write": "", "placeholder": "يسيس ب"}}, "name": "enable_start_date", "step": 1, "type": {"name": "checkbox", "validators": []}, "position": 0, "component": {"data": {"title": "Enable Scheduled auction"}, "name": "inputToggleCheckbox", "dependency": [{"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس"}}, "name": "start_date", "step": 1, "type": {"name": "text", "validators": [{"name": "required", "error_message": "required"}]}, "position": 0, "component": {"data": {"title": "Select a date and time"}, "name": "inputDatePicker", "dependency": []}, "form_group": 1, "label_read": "Starts on", "label_write": "Starts on", "placeholder": "Starts on"}]}, "form_group": 1, "label_read": "Scheduled auction", "label_write": "Scheduled auction", "placeholder": ""}], "live_auction_fields": [{"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس"}}, "name": "initial_price", "step": 1, "type": {"name": "text", "validators": [{"name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers"}, {"name": "required", "error_message": "required"}]}, "position": 0, "component": {"data": [], "name": "inputPrice", "dependency": []}, "form_group": 1, "label_read": "Initial price", "label_write": "Initial price", "placeholder": "AED"}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس"}}, "name": "reserve_price", "step": 1, "type": {"name": "text", "validators": [{"name": "numeric", "pattern": "^(?:[0-9]+(?:.[0-9]{1,})?|.[0-9]{1,})$", "error_message": "Must contain only numbers"}, {"name": "required", "error_message": "required"}]}, "position": 0, "component": {"data": [], "name": "inputPrice", "dependency": []}, "form_group": 1, "label_read": "Reserve price", "label_write": "Reserve price", "placeholder": "AED"}, {"l10n": {"ar": {"label_read": "", "label_write": "", "placeholder": "يسيس ب"}}, "name": "chat", "step": 1, "type": {"name": "checkbox", "validators": []}, "position": 0, "component": {"data": {"title": "Turn on chat"}, "name": "inputToggleCheckbox", "dependency": []}, "form_group": 1, "label_read": "Chat", "label_write": "Chat", "placeholder": ""}, {"name": "duration", "step": 1, "type": {"name": "select", "validators": [{"name": "required", "error_message": "Duration is required"}]}, "position": 0, "component": {"data": [{"id": "1", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "30 minutes", "seconds": 1800}, {"id": "2", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "45 minutes", "seconds": 2700}, {"id": "3", "l10n": {"ar": {"name": "يسببسيب"}}, "label": "60 minutes", "seconds": 3600}], "name": "inputDurationSelect"}, "form_group": 1, "label_read": "Duration", "label_write": "Duration", "placeholder": "Select"}, {"l10n": {"ar": {"label_read": "تبوك", "label_write": "تبوك", "placeholder": "سيبس"}}, "name": "start_date", "step": 1, "type": {"name": "text", "validators": [{"name": "required", "error_message": "required"}]}, "position": 0, "component": {"data": {"title": "Select a date and time"}, "name": "inputDatePicker", "dependency": []}, "form_group": 1, "label_read": "Starts on", "label_write": "Starts on", "placeholder": "Starts on"}]}}" I need a script to add l10n for all the objects with ar and ru if not found if we already have l18n with ar we should add ru "name": "minimum",
"pattern": 0,
"error_message": "Description is too short",
"l10n": {
"ar": {
"name": "ARA",
"pattern": 0,
"error_message": "ARABIC"
},
"ru": {
"name": "RUS",
"pattern": 0,
"error_message": "RUS" like this example
e55637a655efe14422556998edb80e94
{ "intermediate": 0.379243403673172, "beginner": 0.4686514139175415, "expert": 0.1521051675081253 }
37,750
block_cards_query = sa.text(f""" UPDATE cards SET is_blocked = 1 WHERE id IN ( SELECT card_id FROM cards_skill_links JOIN skills ON skills.id = cards_skill_links.skill_id AND skills.is_blocked = 1 AND skills.address IN ({addresses}) ) """)。 增加一个判断条件,如果 card.skill 为null , 也设置 is_blocked = 1
76b1c5ef446b2788e4dae233b7efa873
{ "intermediate": 0.3506597578525543, "beginner": 0.36668309569358826, "expert": 0.2826571762561798 }
37,751
i have this file json and I need a script to add l10n for all the objects with ar and ru if not found if we already have l18n with ar we should add ru "name": "minimum",
"pattern": 0,
"error_message": "Description is too short",
"l10n": {
"ar": {
"name": "ARA",
"pattern": 0,
"error_message": "ARABIC"
},
"ru": {
"name": "RUS",
"pattern": 0,
"error_message": "RUS" like this example
40ec9a292112096f25877747be8699a2
{ "intermediate": 0.495678186416626, "beginner": 0.2962002754211426, "expert": 0.20812156796455383 }
37,752
How can I change TWIG templates for a Shopware Theme I bought and installed?
b4865142d79cdc53db04263d84f2d7ec
{ "intermediate": 0.5146918892860413, "beginner": 0.28228750824928284, "expert": 0.20302052795886993 }
37,753
I have the code below, Please just change the pin out-put for my 6 LEDs and assign the PD1 to PD6 pin of ATmega 32A #define F_CPU 16000000UL // 16 MHz clock #include <avr/io.h> #include <util/delay.h> // Define potentiometer ADC channel (PA0 = ADC0) #define potPin 0 // Define digital I/O pins for LEDs #define led1 PD4 #define led2 PD5 #define led3 PD6 #define led4 PD7 #define led5 PB0 #define led6 PB1 #define SAMPLES_TO_AVERAGE 10 // Number of samples to average for ADC void adc_init() { // Initialize ADC ADMUX = (1<<REFS0); // Select AVcc as reference voltage and ADC0 as input channel ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0); // Enable ADC and set prescaler to 128 } uint16_t adc_read(uint8_t ch) { // Select ADC channel with safety mask and without changing the reference voltage selection ADMUX = (ADMUX & 0xF0) | (ch & 0x0F); // Start single conversion ADCSRA |= (1<<ADSC); // Wait until conversion is complete while (ADCSRA & (1<<ADSC)); return ADC; } uint16_t adc_read_average(uint8_t ch) { uint32_t sum = 0; for (int i = 0; i < SAMPLES_TO_AVERAGE; ++i) { sum += adc_read(ch); } return (uint16_t)(sum / SAMPLES_TO_AVERAGE); } int main(void) { // Set up the LED pins as output DDRD |= (1<<led1) | (1<<led2) | (1<<led3) | (1<<led4); DDRB |= (1<<led5) | (1<<led6); // Initialize ADC adc_init(); while(1) { // Read the value from the potentiometer and average it uint16_t potValue = adc_read_average(potPin); // Map the potentiometer value from the given range (65 - 337) to (0 - 1023) uint16_t mappedValue = (uint32_t)(potValue - 65) * 1023 / (337 - 65); // Define thresholds based on the number of LEDs uint16_t threshold1 = 170; // First threshold uint16_t threshold2 = 341; // Second threshold uint16_t threshold3 = 512; // Third threshold uint16_t threshold4 = 683; // Fourth threshold uint16_t threshold5 = 854; // Fifth threshold // Turn off all LEDs to start with PORTD &= ~((1<<led1) | (1<<led2) | (1<<led3) | (1<<led4)); PORTB &= ~((1<<led5) | (1<<led6)); // Determine which LEDs to light up based on the mappedValue if (mappedValue >= threshold5) { PORTD |= (1<<led1) | (1<<led2) | (1<<led3) | (1<<led4); PORTB |= (1<<led5) | (1<<led6); } else if (mappedValue >= threshold4) { PORTD |= (1<<led1) | (1<<led2) | (1<<led3) | (1<<led4); PORTB |= (1<<led5); } else if (mappedValue >= threshold3) { PORTD |= (1<<led1) | (1<<led2) | (1<<led3) | (1<<led4); } else if (mappedValue >= threshold2) { PORTD |= (1<<led1) | (1<<led2) | (1<<led3); } else if (mappedValue >= threshold1) { PORTD |= (1<<led1) | (1<<led2); } else { // Ensure led1 is always turned on regardless of the value PORTD |= (1<<led1); } // Small delay to reduce flickering _delay_ms(30); } }
b5e63551cfd254cc0222c07d37f256ae
{ "intermediate": 0.44291403889656067, "beginner": 0.31188490986824036, "expert": 0.2452010214328766 }
37,754
Make a window that contains open image button, below it add previous button next to next button. Below it add a "rest" checkbox. Next to the checkbox is a spinbox. Below everything add total images in the folder label, and below that is label that show the image name When open image is pressed, it opens a folder, lists the image content. Filter by extension jpg, Png, gif, webp. Then list it, add number to it and then save it to folder_index. If i open a second folder, it resets and load the list from the new folder instead, unless the new folder is the same as the current, then do not reset the list The next button will call a random image from the folder index and add it to history. The previous button will load the previously shown images in order. When the previous button reach the beginning of the history, it's still active but does nothing. The next button will go to the next image in history, until it reaches the end, then load up new next images to the history like usual. At this point i ca cycle through the history with next and previous button. Show every image in the folder once before showing a previously shown image. If the rest button is enabled, every (spinbox value) of images shown set by the spinbox, it'll call a function that set the label to say "rest" Instead of the image name for every (spinbox value) of img name. It doesn't stop the next button or affect the history, it just show the "rest" Text every (spinbox value) instead of the image name when active. When i press previous while the rest checkbox is enabled, it just goes through the history unaffected by the rest function. Do not disable any button. Use straight quotationmark and not curved quotes for the code.
89579887ed292c9af8c88b4363f07de1
{ "intermediate": 0.3392355740070343, "beginner": 0.3723621070384979, "expert": 0.28840234875679016 }
37,755
What is the output? a = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) print (a[0:1, 1:41)
fffbc6f81a40b9274f8ba6dde6861936
{ "intermediate": 0.3071928918361664, "beginner": 0.4433096647262573, "expert": 0.24949750304222107 }
37,756
i have this code to update json file "import json def get_dict(filename): with open(filename, 'r', encoding='utf-8') as json_file: data_dictionary = json.load(json_file) return data_dictionary def add_l10n(obj, languages=('ar', 'ru')): obj['l10n'] = obj.get('l10n', {'ar': {}, 'ru': {}}) for lang in languages: if lang not in obj['l10n']: obj['l10n'][lang] = {key: lang.upper() for key in obj['l10n'].get('ar', {})} def update_component_list(comp_list): new_comp_list = [] for comp in comp_list: if 'l10n' not in comp: comp['l10n'] = {'ar': {}, 'ru': {}} add_l10n(comp) if 'component' in comp and 'data' in comp['component']: comp['component']['data'] = update_data(comp['component']['data']) new_comp_list.append(comp) return new_comp_list def update_fields(fields): for field in fields: if 'component' in field and 'data' in field['component']: field['component']['data'] = update_data(field['component']['data']) if 'l10n' not in field: field['l10n'] = {'ar': {}, 'ru': {}} add_l10n(field) return fields def update_filters(filters): for filter_item in filters: if 'l10n' not in filter_item: filter_item['l10n'] = {'ar': {}, 'ru': {}} add_l10n(filter_item) if 'data' in filter_item: filter_item['data'] = update_data(filter_item['data']) return filters def update_data(data_list): new_data_list = [] for data_item in data_list: if not isinstance(data_item, dict): # If it's a string, wrap it in a dictionary data_item = {'name': data_item} if 'l10n' not in data_item: data_item['l10n'] = {'ar': {}, 'ru': {}} add_l10n(data_item) new_data_list.append(data_item) return new_data_list def update_validators(validators): for v in validators: if 'l10n' not in v: v['l10n'] = {'ar': {}, 'ru': {}} add_l10n(v) return validators def process_component_data(comp_data): if isinstance(comp_data, list): return update_component_list(comp_data) return comp_data def update_auction_fields(auction_fields): new_auction_fields = [] for af in auction_fields: af['type']['validators'] = update_validators(af['type'].get('validators', [])) af['component']['data'] = process_component_data(af['component'].get('data', [])) if 'dependency' in af['component']: af['component']['dependency'] = update_component_list(af['component']['dependency']) new_auction_fields.append(af) return new_auction_fields def final_dict(data_dict, new_file_name): data_dict['data_schema']['steps'] = update_component_list(data_dict['data_schema'].get('steps', [])) data_dict['data_schema']['fields'] = update_auction_fields(data_dict['data_schema'].get('fields', [])) with open(new_file_name, 'w', encoding='utf-8') as new_json_file: json.dump(data_dict, new_json_file, ensure_ascii=False, indent=2) if __name__ == "__main__": file_path = '1.json' filename = file_path.split('.')[0] new_file_name = f'{filename}_updated.json' data_dict = get_dict(file_path) data_dict['data_schema']['steps'] = update_component_list(data_dict['data_schema'].get('steps', [])) data_dict['data_schema']['fields'] = update_auction_fields(data_dict['data_schema'].get('fields', [])) data_dict['data_schema']['fields'] = update_fields(data_dict['data_schema']['fields']) data_dict['data_schema']['filters'] = update_filters(data_dict['data_schema'].get('filters', [])) with open(new_file_name, 'w', encoding='utf-8') as new_json_file: json.dump(data_dict, new_json_file, ensure_ascii=False, indent=2) print("Script finished!")" can you add in component there is filed named data also should be updated
3951601a12b96f0b1c0499429a1d9036
{ "intermediate": 0.4920024275779724, "beginner": 0.3364696204662323, "expert": 0.1715279370546341 }
37,757
import java.util.*; public class xyz {public static void main(String args[]){ Scanner in=new Scanner(System.in); int n,m,i; n=in.nextInt(); i=in.nextInt(); m=Math.max(n,i); System.out.println(m);}} to find max correct the incorrect
cfe83edda4e2c7bdede03ada18f81d52
{ "intermediate": 0.3497479259967804, "beginner": 0.3995101749897003, "expert": 0.2507418394088745 }
37,758
import java.util.*; public class xyz {public static void main(String args[]){ Scanner in=new Scanner(System.in); int n,m,i; n=in.nextInt(); i=in.nextInt(); m=Math.max(n,i); System.out.println(m);}} to find max correct the incorrect
830035b88308ac509579b5d91611adf7
{ "intermediate": 0.3497479259967804, "beginner": 0.3995101749897003, "expert": 0.2507418394088745 }
37,759
hi, when I ask you I want you just spit the answer so answer everything straight to the point, no explaination needed
a4e93efce7cae7b41fc2bfa36452ecfa
{ "intermediate": 0.3450835645198822, "beginner": 0.2503427565097809, "expert": 0.40457361936569214 }
37,760
I need some sort of method to determine rhe language of a webpages content, i dont wanna use any apks or resource intense AI.i need a way to do this pretty fast while maintaining accuracy.
772a62487ba7ed14546571d24ca4b804
{ "intermediate": 0.24017369747161865, "beginner": 0.2285560816526413, "expert": 0.5312702059745789 }
37,761
In unity, using C#, I'm calling the SwitchState() function from the Update(), but what's wrong with the SwitchState() function? void Update(){ void SwitchState() { if (healthSlider.value <= 0 && !isDead) { isDead = true; beautify.sepiaIntensity = 1f; StartCoroutine(CharacterDeath()); } else if (healthSlider.value > 0 && healthSlider.value < (Health / 5.5f)) { beautify.sepiaIntensity = 1f; isInjured = true; } else if (healthSlider.value > (Health / 5.5f) && healthSlider.value < (Health / 4)) { beautify.sepiaIntensity = 0.90f; isInjured = true; } else if (healthSlider.value > (Health / 4) && healthSlider.value < (Health / 2)) { beautify.sepiaIntensity = 0.65f; isInjured = true; } else if (healthSlider.value > (Health / 2) && healthSlider.value < (Health / 1.3f)) { beautify.sepiaIntensity = 0.35f; isInjured = false; } else if (healthSlider.value > (Health / 1.3f)) { beautify.sepiaIntensity = 0f; isInjured = false; } if (isInjured && !isDead && !isSuiciding) { if (woundedPoseRig != null && shotgun.activeInHierarchy == true) { woundedPoseRig.weight = 1f; } m_Animator.SetBool("isInjured", true); BloodScreenFx.SetBool("50Health", true); BloodScreenFx.SetBool("100Health", false); if (Time.time - timePainSoundPlayed < 4f) return; HeartbeatAudioSource.clip = Heartbeat; HeartbeatAudioSource.Play(); int n = Random.Range(1, Painsounds.Length); AudioClip painSounds = Painsounds[n]; if (!audioSource.isPlaying) { audioSource.PlayOneShot(painSounds); Painsounds[n] = Painsounds[0]; Painsounds[0] = painSounds; timePainSoundPlayed = Time.time; } } if (!isInjured || isDead || isSuiciding) { if (woundedPoseRig != null && shotgun.activeInHierarchy == true) { woundedPoseRig.weight = 0f; } m_Animator.SetBool("isInjured", false); BloodScreenFx.SetBool("50Health", false); BloodScreenFx.SetBool("100Health", true); HeartbeatAudioSource.clip = Heartbeat; HeartbeatAudioSource.Stop(); } }
8a1c5988b604423f6987cc8a29d0a6d4
{ "intermediate": 0.3956073522567749, "beginner": 0.409993439912796, "expert": 0.19439922273159027 }
37,762
In unity, using C#, i'm calling the SwitchState() function from the Update(), but what's wrong with the SwitchState() function? void Update(){ SwitchState();} void SwitchState() { if (healthSlider.value <= 0 && !isDead) { isDead = true; beautify.sepiaIntensity = 1f; StartCoroutine(CharacterDeath()); } else if (healthSlider.value > 0 && healthSlider.value < (Health / 5.5f)) { beautify.sepiaIntensity = 1f; isInjured = true; } else if (healthSlider.value > (Health / 5.5f) && healthSlider.value < (Health / 4)) { beautify.sepiaIntensity = 0.90f; isInjured = true; } else if (healthSlider.value > (Health / 4) && healthSlider.value < (Health / 2)) { beautify.sepiaIntensity = 0.65f; isInjured = true; } else if (healthSlider.value > (Health / 2) && healthSlider.value < (Health / 1.3f)) { beautify.sepiaIntensity = 0.35f; isInjured = false; } else if (healthSlider.value > (Health / 1.3f)) { beautify.sepiaIntensity = 0f; isInjured = false; } if (isInjured && !isDead && !isSuiciding) { if (woundedPoseRig != null && shotgun.activeInHierarchy == true) { woundedPoseRig.weight = 1f; } m_Animator.SetBool("isInjured", true); BloodScreenFx.SetBool("50Health", true); BloodScreenFx.SetBool("100Health", false); if (Time.time - timePainSoundPlayed < 4f) return; HeartbeatAudioSource.clip = Heartbeat; HeartbeatAudioSource.Play(); int n = Random.Range(1, Painsounds.Length); AudioClip painSounds = Painsounds[n]; if (!audioSource.isPlaying) { audioSource.PlayOneShot(painSounds); Painsounds[n] = Painsounds[0]; Painsounds[0] = painSounds; timePainSoundPlayed = Time.time; } } if (!isInjured || isDead || isSuiciding) { if (woundedPoseRig != null && shotgun.activeInHierarchy == true) { woundedPoseRig.weight = 0f; } m_Animator.SetBool("isInjured", false); BloodScreenFx.SetBool("50Health", false); BloodScreenFx.SetBool("100Health", true); HeartbeatAudioSource.clip = Heartbeat; HeartbeatAudioSource.Stop(); } }
c4d190972d7a3b819f123a372973ec4d
{ "intermediate": 0.3385806977748871, "beginner": 0.34152916073799133, "expert": 0.31989017128944397 }
37,763
Исправь в коде: df_conv['first_salary_dt'] - df_conv['ticket_created_dt'] Данную ошибку: TypeError: unsupported operand type(s) for -: 'NaTType' and 'datetime.date'
1c9fe71981fa8af5ff1dbb62f9b454dc
{ "intermediate": 0.3210446536540985, "beginner": 0.35526585578918457, "expert": 0.3236894905567169 }
37,764
loop in python that repeats 50 times
cce1e5ffb7085fc35708b1dda37a52ef
{ "intermediate": 0.186788871884346, "beginner": 0.5682216882705688, "expert": 0.24498941004276276 }
37,765
In unity, using C#, i'm calling a ToggleCrouch function from the Update(). What are the issues with this function? void Update(){ StartCoroutine(ToggleCrouch());} IEnumerator ToggleCrouch() { for (int i = 0; i < m_Animator.layerCount; i++) { if (m_Animator.GetLayerName(i) == BaseLayer) { AnimatorStateInfo stateInfo = m_Animator.GetCurrentAnimatorStateInfo(i); if (stateInfo.IsName("Base Layer.Sneak v2-SM.Move Tree")) { isCrouching = true; stealthFX.SetBool("Stealth", true); yield return new WaitForSeconds(2); } if (stateInfo.IsName("Base Layer.WalkRunPivot v2-SM.Move Tree")) { isCrouching = false; stealthFX.SetBool("Stealth", false); yield return new WaitForSeconds(2); } } } yield return new WaitForSeconds(2); }
266fdc357a39c23af96b89e58b4203e0
{ "intermediate": 0.42950090765953064, "beginner": 0.3746408224105835, "expert": 0.19585828483104706 }
37,766
hi
10b94dd38689ac8c4efe254c11713b54
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,767
explain idx, image_path = image_info
b25620a6ed3e4964eea39f4b610008e5
{ "intermediate": 0.35403212904930115, "beginner": 0.27994590997695923, "expert": 0.366021990776062 }
37,768
In unity, using C#, I added an event Crouch() on the first frame of the crouch animation. The crouch function is like so : public void Crouch() { isCrouching = !isCrouching; // Toggle the crouching state stealthFX.SetBool("Stealth", isCrouching); } This toggle the bool isCrouching upon the first frame of the animation. But how do I check if the animation is transitioning or exiting so that the bool is toggled off?
d81422029e260d57bd68d428e46170ad
{ "intermediate": 0.5416860580444336, "beginner": 0.2948339283466339, "expert": 0.1634800136089325 }
37,769
hi
6caa164f7441ae8c855a38d6f4ed1e81
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,770
Called from the Update() method, the following function allows to toggle on/off the bool isCrouching. Is there any issues with this function? void ToggleCrouch() { AnimatorStateInfo stateInfo = m_Animator.GetCurrentAnimatorStateInfo(0); if (stateInfo.IsName("Base Layer.Sneak v2-SM.Move Tree")) { isCrouching = true; stealthFX.SetBool("Stealth", true); } if (stateInfo.IsName("Base Layer.WalkRunPivot v2-SM.Move Tree")) { isCrouching = false; stealthFX.SetBool("Stealth", false); } }
dfeb3ba92b0ebd49a7e853a5e6403439
{ "intermediate": 0.4643596112728119, "beginner": 0.29535576701164246, "expert": 0.24028466641902924 }
37,771
A code[ class ImageViewer: def __init__(self, root): self.SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".JPG", ".JPEG", ".BMP", ".GIF", ".webp", ".WEBP") self.button_style = {"font": ("consolas", 11), "fg": "white", "bg": "#3c3c3c", "relief": "flat"} self.bgcolor = "#242424" self.button_width = 3 #self.image_loading_queue = Queue(maxsize=5) self.switch_timestamps = [] self.root = root self.root.geometry("800x600") # Initial window size self.root.title("Jestur Viewer") self.root.configure(bg=self.bgcolor) # Set window background color self.root.attributes("-topmost", True) # Make the window stay on top self.image_folder = "" self.image_files = [] self.current_image_index = 0 def select_folder(self): self.image_folder = filedialog.askdirectory() if self.image_folder: image_files = os.listdir(self.image_folder) # Get all files in the selected folder self.image_files = [file for file in image_files if file.endswith(self.SUPPORTED_EXTENSIONS)] # Filter image files self.rotated = 0 if len(self.image_files) > 0: self.current_image_index = 0 self.canvas.pack(fill=tk.BOTH, expand=True) self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=5) self.root.title("Jesturing in " + self.image_folder) self.canvas.config(bg=self.bgcolor, highlightthickness=0) self.display_image() self.start_button.config(**self.button_style) else: messagebox.showinfo("No Image Files", "The selected folder does not contain any image files.") self.image_folder = "" self.root.title("Jestur") def load_image(self, image_path): image = Image.open(image_path) # Check if the image has EXIF data if "exif" in image.info: exif_data = piexif.load(image.info["exif"]) if piexif.ImageIFD.Orientation in exif_data["0th"]: orientation = exif_data["0th"][piexif.ImageIFD.Orientation] if orientation == 3: image = image.rotate(180, expand=True) elif orientation == 6: image = image.rotate(-90, expand=True) elif orientation == 8: image = image.rotate(90, expand=True) if self.is_greyscale: image = image.convert("L") if self.is_mirrored: image = image.transpose(Image.FLIP_LEFT_RIGHT) if self.rotated != 0: image = image.rotate(self.rotated, expand=True) aspect_ratio = image.width / image.height canvas_width = self.canvas.winfo_width() canvas_height = self.canvas.winfo_height() max_width = min(canvas_width, int(aspect_ratio * canvas_height)) max_height = min(canvas_height, int(canvas_width / aspect_ratio)) scale_factor = min(max_width / image.width, max_height / image.height) new_width = int(image.width * scale_factor) new_height = int(image.height * scale_factor) if new_width > 0 and new_height > 0: resized_image = image.resize((new_width, new_height), Image.BICUBIC) self.photo = ImageTk.PhotoImage(resized_image) self.canvas.delete("all") self.canvas.create_image(canvas_width // 2, canvas_height // 2, image=self.photo) def display_image(self): if self.image_folder != "" and len(self.image_files) > 0: if self.update_switch_timestamps(): # Show the text of the image name instead of loading the actual image image_name = self.image_files[self.current_image_index] self.canvas.delete("all") # Clear the canvas self.canvas.create_text( self.canvas.winfo_width() // 2, self.canvas.winfo_height() // 2, text=image_name, fill="white" ) # Schedule the image load with a delay if self.timer is not None: self.root.after_cancel(self.timer) # Cancel existing timer to avoid conflicts self.timer = self.root.after(500, self.load_image_delayed) # Set a new timer to load the image after 500ms else: # Load the image normally if not quick-switching image_path = os.path.join(self.image_folder, self.image_files[self.current_image_index]) threading.Thread(target=self.load_image, args=(image_path,)).start() def load_image_delayed(self): # This method will be called after the 500ms delay if no keypress happens if self.timer is not None: self.root.after_cancel(self.timer) # Cancel the existing timer self.timer = None # Clear the timer ID image_path = os.path.join(self.image_folder, self.image_files[self.current_image_index]) threading.Thread(target=self.load_image, args=(image_path,)).start() if not self.is_paused: self.timer = self.set_timer_interval self.root.after(500, self.start_timer) def next_image(self, event=None): if self.image_folder != "": self.current_image_index = random.randint(0, len(self.image_files) - 1) # Randomly select self.display_image() # Reset the timer interval to the stored set timer interval self.timer_interval = self.set_timer_interval def previous_image(self, event=None): if self.image_folder != "": self.current_image_index = random.randint(0, len(self.image_files) - 1) # Randomly select the next image index self.display_image() self.timer_interval = self.set_timer_interval # Use the stored set timer interval ] B code[ class ImageApp: def __init__(self, root): self.root = root self.current_folder = None self.folder_index = [] self.history = [] self.history_index = -1 self.total_images = 0 self.rest_interval = 5 self.rest_counter = 0 self.rest_var = tk.IntVar() # Tkinter variable to hold the state of the checkbox self.open_button = tk.Button(root, text="Open Image", command=self.open_folder) self.open_button.pack() self.previous_button = tk.Button(root, text="Previous", command=self.previous_image) self.previous_button.pack(side='left') self.next_button = tk.Button(root, text="Next", command=self.next_image) self.next_button.pack(side='left') self.rest_checkbox = tk.Checkbutton(root, text="Rest", variable=self.rest_var) self.rest_checkbox.pack(side='left') self.spin_value = tk.IntVar(value=self.rest_interval) self.spinbox = tk.Spinbox(root, from_=1, to=100, textvariable=self.spin_value) self.spinbox.pack(side='left') self.total_images_label = tk.Label(root, text="Total images in folder: 0") self.total_images_label.pack() self.image_name_label = tk.Label(root, text="Image Name") self.image_name_label.pack() def open_folder(self): folder_path = filedialog.askdirectory() if folder_path and folder_path != self.current_folder: self.current_folder = folder_path self.folder_index = self.get_image_list(folder_path) self.total_images = len(self.folder_index) self.total_images_label.config(text=f"Total images in folder: {self.total_images}") self.history.clear() self.history_index = -1 # Reset the rest counter and show self.rest_counter = 0 if self.folder_index: # If there are images in the folder, display one self.add_image_to_history() self.display_image(self.history[self.history_index]) else: self.image_name_label.config(text="No images found") def get_image_list(self, folder_path): extensions = ('.jpg', '.jpeg', '.png', '.gif', '.webp') image_list = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith(extensions)] numbered_list = list(enumerate(image_list)) return numbered_list def previous_image(self): if self.history_index > 0: self.history_index -= 1 self.display_image(self.history[self.history_index]) def next_image(self): # We will display "Rest" on every (spin_value + 1) image if (self.rest_counter + 1) % (self.spin_value.get() + 1) == 0 and self.rest_var.get() == 1: self.image_name_label.config(text="Rest") else: if self.history_index < len(self.history) - 1: self.history_index += 1 else: if self.total_images == len(self.history): self.history_index = 0 else: self.add_image_to_history() self.display_image(self.history[self.history_index]) self.rest_counter += 1 def add_image_to_history(self): remaining_images = set(range(self.total_images)) - set(idx for idx, img in self.history) if remaining_images: next_image_index = random.choice(list(remaining_images)) next_image = self.folder_index[next_image_index] self.history.append(next_image) self.history_index += 1 def display_image(self, image_info): # Image displayed logic here idx, image_path = image_info image_name = os.path.basename(image_path) self.image_name_label.config(text=image_name) ] B code is just calling image name while code A is to show image. B code has the new behaviour that i want. give me A code function to call image with B code behaviour. or in other words to integrate new B code behaviour to A code. the b code is not to be changed. give me new A code
7d9586aa229dc539b932f428eecabcdb
{ "intermediate": 0.344588965177536, "beginner": 0.4136984348297119, "expert": 0.24171258509159088 }
37,772
Şu kodlarımda mesela yüzlerce kart ekleyip kaydırma çubuğu ile alta dopru kaydırınca textbox da yok oluyor bağımsız olsun ve hiç kaybolmasın <ui:FluentWindow x:Class="ShadeBox.Views.Windows.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:ShadeBox.Views.Windows" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml" Title="{Binding ViewModel.ApplicationTitle, Mode=OneWay}" MinWidth="1300" Height="650" d:DataContext="{d:DesignInstance local:MainWindow, IsDesignTimeCreatable=True}" d:DesignHeight="450" d:DesignWidth="1000" ExtendsContentIntoTitleBar="True" WindowBackdropType="Mica" WindowCornerPreference="Round" WindowStartupLocation="CenterScreen" mc:Ignorable="d"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <ui:NavigationView x:Name="NavigationView" Grid.Row="1" Padding="42,0,42,0" BreadcrumbBar="{Binding ElementName=BreadcrumbBar}" FooterMenuItemsSource="{Binding ViewModel.FooterMenuItems, Mode=OneWay}" FrameMargin="0" IsBackButtonVisible="Visible" IsPaneToggleVisible="True" MenuItemsSource="{Binding ViewModel.MenuItems, Mode=OneWay}" PaneDisplayMode="LeftFluent"> <ui:NavigationView.Header> <ui:BreadcrumbBar x:Name="BreadcrumbBar" Margin="42,32,42,20" /> </ui:NavigationView.Header> <ui:NavigationView.ContentOverlay> <Grid> <ui:SnackbarPresenter x:Name="SnackbarPresenter" /> </Grid> </ui:NavigationView.ContentOverlay> </ui:NavigationView> <ContentPresenter x:Name="RootContentDialog" Grid.Row="0" Grid.RowSpan="2" /> <ui:TitleBar x:Name="TitleBar" Title="{Binding ViewModel.ApplicationTitle}" Grid.Row="0" CloseWindowByDoubleClickOnIcon="True"> <ui:TitleBar.Icon> <ui:ImageIcon Source="pack://application:,,,/Assets/wpfui-icon-256.png" /> </ui:TitleBar.Icon> </ui:TitleBar> </Grid> </ui:FluentWindow>
2431c63d808b70e94ad31a9b408a5063
{ "intermediate": 0.2674051523208618, "beginner": 0.6199740767478943, "expert": 0.1126207485795021 }
37,773
if [3,3,1] be a eigenvector of a matrix, is [-3,-3,-1] count eigenvector of that matrix too?
4660f9b73ea0238d38a6a8fc00981bd3
{ "intermediate": 0.37097597122192383, "beginner": 0.1813836395740509, "expert": 0.44764038920402527 }
37,774
make a tk button to open D:/dir/folder in python
345556ee5886615633ec4526271da7f1
{ "intermediate": 0.4008897840976715, "beginner": 0.24367845058441162, "expert": 0.35543179512023926 }
37,775
subprocess.Popen(f'explorer /select,"{self.path_to_open}"') only opens explorer, not the folder or file unlike os.startfile(self.image_folder)
73b68ddef542d7a9cb3a3ba83c3031b7
{ "intermediate": 0.3455600142478943, "beginner": 0.35211002826690674, "expert": 0.3023299276828766 }
37,776
programmation = self.get_programmation_with_groupes_and_artistes() File "C:\Users\alexa\Desktop\sae-fest-iuto-back\Code\appli\../BD\EvenementBD.py", line 117, in get_programmation_with_groupes_and_artistes programmation.append((Groupe(idG, None, nomG, descriptionG), Evenement(idE, idG, idL, nomE, heureDebutE, heureFinE, dateDebutE, dateFinE), Membre_Groupe(idMG, idG, nomMG, prenomMG, nomDeSceneMG, descriptionA))) File "C:\Users\alexa\Desktop\sae-fest-iuto-back\Code\appli\../BD\BD.py", line 322, in __init__ self.__heurePassage = self.timedelta_to_time(heurePassage) if isinstance(heurePassage, timedelta) else datetime.strptime(heurePassage, '%H:%M').time() TypeError: strptime() argument 1 must be str, not None def get_programmation_with_groupes_and_artistes(self): try: query = text(""" SELECT e.idE, e.idG, g.nomG, g.descriptionG, e.idL, e.nomE, e.heureDebutE, e.heureFinE, e.dateDebutE, e.dateFinE, mg.idMG, mg.nomMG, mg.prenomMG, mg.nomDeSceneMG, mg.descriptionA FROM EVENEMENT e LEFT JOIN GROUPE g ON e.idG = g.idG LEFT JOIN MEMBRE_GROUPE mg ON g.idG = mg.idG """) programmation = [] result = self.connexion.get_connexion().execute(query) for idE, idG, nomG, descriptionG, idL, nomE, heureDebutE, heureFinE, dateDebutE, dateFinE, idMG, nomMG, prenomMG, nomDeSceneMG, descriptionA in result: programmation.append((Groupe(idG, None, nomG, descriptionG), Evenement(idE, idG, idL, nomE, heureDebutE, heureFinE, dateDebutE, dateFinE), Membre_Groupe(idMG, idG, nomMG, prenomMG, nomDeSceneMG, descriptionA))) return programmation except SQLAlchemyError as e: print(f"La requête a échoué : {e}") from datetime import datetime, date, time, timedelta class Faq: def __init__(self, idFaq: int, question: str, reponse: str): self._idFaq = idFaq self._question = question self._reponse = reponse def get_idFaq(self): return self._idFaq def get_question(self): return self._question def get_reponse(self): return self._reponse def to_dict(self): return { "idFaq": self._idFaq, "question": self._question, "reponse": self._reponse } class User: def __init__(self, idUser: int, pseudoUser: str, mdpUser: str, emailUser: str, statutUser: str): self.__idUser = idUser self.__pseudoUser = pseudoUser self.__mdpUser = mdpUser self.__emailUser = emailUser self.__statutUser = statutUser def get_idUser(self): return self.__idUser def get_pseudoUser(self): return self.__pseudoUser def get_mdpUser(self): return self.__mdpUser def get_emailUser(self): return self.__emailUser def get_statutUser(self): return self.__statutUser def set_pseudoUser(self, pseudoUser): self.__pseudoUser = pseudoUser def set_mdpUser(self, mdpUser): self.__mdpUser = mdpUser def set_emailUser(self, emailUser): self.__emailUser = emailUser def to_dict(self): return { "idUser": self.__idUser, "pseudoUser": self.__pseudoUser, "emailUser": self.__emailUser } class Festival: def __init__(self, idF: int, nomF: str, villeF: str, dateDebutF: str, dateFinF: str): self.__idF = idF self.__nomF = nomF self.__villeF = villeF self.__dateDebutF = dateDebutF if isinstance(dateDebutF, date) else datetime.strptime(dateDebutF, '%Y-%m-%d').date() self.__dateFinF = dateFinF if isinstance(dateFinF, date) else datetime.strptime(dateFinF, '%Y-%m-%d').date() def get_idF(self): return self.__idF def get_nomF(self): return self.__nomF def get_villeF(self): return self.__villeF def get_dateDebutF(self): return self.__dateDebutF def get_dateFinF(self): return self.__dateFinF def __repr__(self): return f"({self.__idF}, {self.__nomF}, {self.__villeF}, {self.__dateDebutF}, {self.__dateFinF})" def to_dict(self): return { "idF": self.__idF, "nomF": self.__nomF, "villeF": self.__villeF, "dateDebutF": self.__dateDebutF.isoformat(), "dateFinF": self.__dateFinF.isoformat() } class Type_Billet: def __init__(self, idType: int, duree: int): self.__idType = idType self.__duree = duree def get_idType(self): return self.__idType def get_duree(self): return self.__duree def set_duree(self, duree): self.__duree = duree def to_dict(self): return { "idType": self.__idType, "duree": self.__duree } class Billet: def __init__(self, idB: int, idF: int, idType: int, idS: int, prix: int, dateAchat: str, dateDebutB: str, dateFinB: str): self.__idB = idB self.__idF = idF self.__idType = idType self.__idS = idS self.__prix = prix self.__dateAchat = dateAchat if isinstance(dateAchat, date) else datetime.strptime(dateAchat, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() if dateDebutB != None and dateFinB != None: self.__dateDebutB = dateDebutB if isinstance(dateDebutB, date) else datetime.strptime(dateDebutB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() self.__dateFinB = dateFinB if isinstance(dateFinB, date) else datetime.strptime(dateFinB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() else: self.__dateDebutB = None self.__dateFinB = None def get_idB(self): return self.__idB def get_idFestival(self): return self.__idF def get_idType(self): return self.__idType def get_idSpectateur(self): return self.__idS def get_prix(self): return self.__prix def get_dateAchat(self): return self.__dateAchat def get_dateDebutB(self): return self.__dateDebutB def get_dateFinB(self): return self.__dateFinB def set_idType(self, idType): self.__idType = idType def set_idSpectateur(self, idS): self.__idS = idS def set_prix(self, prix): self.__prix = prix def set_dateAchat(self, dateAchat): self.__dateAchat = dateAchat def set_dateDebutB(self, dateDebutB): self.__dateDebutB = dateDebutB def set_dateFinB(self, dateFinB): self.__dateFinB = dateFinB def to_dict(self): return { "idB": self.__idB, "idF": self.__idF, "idType": self.__idType, "idS": self.__idS, "prix": self.__prix, "dateAchat": self.__dateAchat.isoformat(), "dateDebutB": self.__dateDebutB.isoformat(), "dateFinB": self.__dateFinB.isoformat() } class Lieu: def __init__(self, idL: int, idF: int, nomL: str, adresseL: str, jaugeL: int): self.__idL = idL self.__idF = idF self.__nomL = nomL self.__adresseL = adresseL self.__jaugeL = jaugeL def get_idL(self): return self.__idL def get_idFestival(self): return self.__idF def get_nomL(self): return self.__nomL def get_adresseL(self): return self.__adresseL def get_jaugeL(self): return self.__jaugeL def set_nomL(self, nomL): self.__nomL = nomL def set_adresseL(self, adresseL): self.__adresseL = adresseL def set_jaugeL(self, jaugeL): self.__jaugeL = jaugeL def to_dict(self): return { "idL": self.__idL, "idF": self.__idF, "nomL": self.__nomL, "adresseL": self.__adresseL, "jaugeL": self.__jaugeL } class Hebergement: def __init__(self, idH: int, nomH: str, limitePlacesH: int, adresseH: int): self.__idH = idH self.__nomH = nomH self.__limitePlacesH = limitePlacesH self.__adresseH = adresseH def get_idH(self): return self.__idH def get_nomH(self): return self.__nomH def get_limitePlacesH(self): return self.__limitePlacesH def get_adresseH(self): return self.__adresseH def set_nomH(self, nomH): self.__nomH = nomH def set_limitePlacesH(self, limitePlacesH): self.__limitePlacesH = limitePlacesH def set_adresseH(self, adresseH): self.__adresseH = adresseH def to_dict(self): return { "idH": self.__idH, "nomH": self.__nomH, "limitePlacesH": self.__limitePlacesH, "adresseH": self.__adresseH } class Programmer: def __init__(self, idF: int, idL: int, idH: int, dateArrivee: str, heureArrivee: str, dateDepart: str, heureDepart: str): self.__idF = idF self.__idL = idL self.__idH = idH self.__dateArrivee = dateArrivee if isinstance(dateArrivee, date) else datetime.strptime(dateArrivee, '%Y-%m-%d').date() self.__heureArrivee = self.timedelta_to_time(heureArrivee) if isinstance(heureArrivee, timedelta) else datetime.strptime(heureArrivee, '%H:%M').time() self.__dateDepart = dateDepart if isinstance(dateDepart, date) else datetime.strptime(dateDepart, '%Y-%m-%d').date() self.__heureDepart = self.timedelta_to_time(heureDepart) if isinstance(heureDepart, timedelta) else datetime.strptime(heureDepart, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idFestival(self): return self.__idF def get_idLieu(self): return self.__idL def get_idHebergement(self): return self.__idH def get_dateArrivee(self): return self.__dateArrivee def get_heureArrivee(self): return self.__heureArrivee def get_dateDepart(self): return self.__dateDepart def get_heureDepart(self): return self.__heureDepart def to_dict(self): return { "idF": self.__idF, "idL": self.__idL, "idH": self.__idH, "dateArrivee": self.__dateArrivee.isoformat(), "heureArrivee": self.__heureArrivee.strftime("%H:%M:%S"), "dateDepart": self.__dateDepart.isoformat(), "heureDepart": self.__heureDepart.strftime("%H:%M:%S") } class Groupe: def __init__(self, idG: int, idH: int, nomG: str, descriptionG: str, datePassage: str = None, heurePassage: str = None, isSaved: bool = False, heureFinPassage: str = None): self.__idG = idG self.__idH = idH self.__nomG = nomG self.__descriptionG = descriptionG self.__heurePassage = self.timedelta_to_time(heurePassage) if isinstance(heurePassage, timedelta) else datetime.strptime(heurePassage, '%H:%M').time() self.__datePassage = datePassage if isinstance(datePassage, date) else datetime.strptime(datePassage, '%Y-%m-%d').date() self.__isSaved = isSaved self.__heureFinPassage = heureFinPassage if heureFinPassage == None else self.timedelta_to_time(heureFinPassage) if isinstance(heureFinPassage, timedelta) else datetime.strptime(heureFinPassage, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idG(self): return self.__idG def get_idHebergement(self): return self.__idH def get_nomG(self): return self.__nomG def get_descriptionG(self): return self.__descriptionG def set_idHebergement(self, idH): self.__idH = idH def set_nomG(self, nomG): self.__nomG = nomG def set_descriptionG(self, descriptionG): self.__descriptionG = descriptionG def to_dict(self): return { "idG": self.__idG, "idH": self.__idH, "nomG": self.__nomG, "descriptionG": self.__descriptionG, "datePassage": self.__datePassage.isoformat(), "heurePassage": self.__heurePassage.strftime("%H:%M:%S"), "isSaved": self.__isSaved, "heureFinPassage": self.__heureFinPassage.strftime("%H:%M:%S") if self.__heureFinPassage != None else "" } def set_nomG(self, nomG): self.__nomG = nomG def set_heurePassage(self, heurePassage): self.__heurePassage = heurePassage def set_datePassage(self, datePassage): self.__datePassage = datePassage def get_heurePassage(self): return self.__heurePassage def get_datePassage(self): return self.__datePassage def get_isSaved(self): return self.__isSaved def set_isSaved(self, isSaved): self.__isSaved = isSaved def set_descriptionG(self, descriptionG): self.__descriptionG = descriptionG # class Groupe: # def __init__(self, idG: int, idH: int, nomG: str, descriptionG: str): # self._idG = idG # self._idH = idH # self._nomG = nomG # self._descriptionG = descriptionG # def get_idG(self): # return self._idG # def get_idHebergement(self): # return self._idH # def get_nomG(self): # return self._nomG # def get_descriptionG(self): # return self._descriptionG # def get_datePassage(self): # return "2021-05-20" # def get_heurePassage(self): # return "20:00:00" # def to_dict(self): # return { # "idG": self._idG, # "nomG": self._nomG, # "descriptionG": self._descriptionG, # "datePassage": seFlf.get_datePassage(), # "heurePassage": self.get_heurePassage() # } class Membre_Groupe: def __init__(self, idMG: int, idG, nomMG: str, prenomMG: str, nomDeSceneMG: str, descriptionA: str): self.__idMG = idMG self.__idG = idG self.__nomMG = nomMG self.__prenomMG = prenomMG self.__nomDeSceneMG = nomDeSceneMG self.__descriptionA = descriptionA def get_idMG(self): return self.__idMG def get_idGroupe(self): return self.__idG def get_nomMG(self): return self.__nomMG def get_prenomMG(self): return self.__prenomMG def get_nomDeSceneMG(self): return self.__nomDeSceneMG def get_descriptionA(self): return self.__descriptionA def set_nomMG(self, nomMG): self.__nomMG = nomMG def set_prenomMG(self, prenomMG): self.__prenomMG = prenomMG def set_nomDeSceneMG(self, nomDeSceneMG): self.__nomDeSceneMG = nomDeSceneMG def set_descriptionA(self, descriptionA): self.__descriptionA = descriptionA def __repr__(self): return f"({self.__idMG}, {self.__idG}, {self.__nomMG}, {self.__prenomMG}, {self.__nomDeSceneMG})" def to_dict(self): return { "idMG": self.__idMG, "idG": self.__idG, "nomMG": self.__nomMG, "prenomMG": self.__prenomMG, "nomDeSceneMG": self.__nomDeSceneMG, "descriptionA": self.__descriptionA } def set_nomMG(self, nomMG): self.__nomMG = nomMG def set_prenomMG(self, prenomMG): self.__prenomMG = prenomMG def set_nomDeSceneMG(self, nomDeSceneMG): self.__nomDeSceneMG = nomDeSceneMG class Instrument: def __init__(self, idI: int, nomI: str): self.__idI = idI self.__nomI = nomI def get_idI(self): return self.__idI def get_nomI(self): return self.__nomI def set_nomI(self, nomI): self.__nomI = nomI def to_dict(self): return { "idI": self.__idI, "nomI": self.__nomI } class Style_Musical: def __init__(self, idSt: int, nomSt: str): self.__idSt = idSt self.__nomSt = nomSt def get_idSt(self): return self.__idSt def get_nomSt(self): return self.__nomSt def set_nomSt(self, nomSt): self.__nomSt = nomSt def to_dict(self): return { "idSt": self.__idSt, "nomSt": self.__nomSt } class Lien_Video: def __init__(self, idLV: int, idG: int, video: str): self.__idLV = idLV self.__idG = idG self.__video = video def get_idLV(self): return self.__idLV def get_idGroupe(self): return self.__idG def get_video(self): return self.__video def to_dict(self): return { "idLV": self.__idLV, "idG": self.__idG, "video": self.__video } class Lien_Reseaux_Sociaux: def __init__(self, idLRS: int, idG: int, reseau: str): self.__idLRS = idLRS self.__idG = idG self.__reseau = reseau def get_idLRS(self): return self.__idLRS def get_idGroupe(self): return self.__idG def get_reseau(self): return self.__reseau def to_dict(self): return { "idLRS": self.__idLRS, "idG": self.__idG, "reseau": self.__reseau } class Lien_Reseaux_Sociaux_Membre: def init(self, idLRSM: int, idMG: int, reseau: str, URL: str): self.__idLRSM = idLRSM self.__idMG = idMG self.__reseau = reseau self.__URL = URL def get_idLRSM(self): return self.__idLRSM def get_idMG(self): return self.__idMG def get_reseau(self): return self.__reseau def get_URL(self): return self.__URL def to_dict(self): return { "idLRSM": self.__idLRSM, "idMG": self.__idMG, "reseau": self.__reseau, "URL": self.__URL } class Evenement: def __init__(self, idE: int, idG: int, idL: int, nomE: str, heureDebutE: str, heureFinE: str, dateDebutE: str, dateFinE: str): self.__idE = idE self.__idG = idG self.__idL = idL self.__nomE = nomE self.__heureDebutE = self.timedelta_to_time(heureDebutE) if isinstance(heureDebutE, timedelta) else datetime.strptime(heureDebutE, '%H:%M').time() self.__heureFinE = self.timedelta_to_time(heureFinE) if isinstance(heureFinE, timedelta) else datetime.strptime(heureFinE, '%H:%M').time() self.__dateDebutE = dateDebutE if isinstance(dateDebutE, date) else datetime.strptime(dateDebutE, "%Y-%m-%d").date() self.__dateFinE = dateFinE if isinstance(dateFinE, date) else datetime.strptime(dateFinE, "%Y-%m-%d").date() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idE(self): return self.__idE def get_idG(self): return self.__idG def get_idL(self): return self.__idL def get_nomE(self): return self.__nomE def get_heureDebutE(self): return self.__heureDebutE def get_heureFinE(self): return self.__heureFinE def get_dateDebutE(self): return self.__dateDebutE def get_dateFinE(self): return self.__dateFinE def set_idG(self, idG): self.__idG = idG def set_idL(self, idL): self.__idL = idL def set_nomE(self, nomE): self.__nomE = nomE def set_heureDebutE(self, heureDebutE): self.__heureDebutE = heureDebutE def set_heureFinE(self, heureFinE): self.__heureFinE = heureFinE def set_dateDebutE(self, dateDebutE): self.__dateDebutE = dateDebutE def set_dateFinE(self, dateFinE): self.__dateFinE = dateFinE def to_dict(self): return { "idE": self.__idE, "idG": self.__idG, "idL": self.__idL, "nomE": self.__nomE, "heureDebutE": self.__heureDebutE.strftime("%H:%M:%S") if self.__heureDebutE else None, "heureFinE": self.__heureFinE.strftime("%H:%M:%S") if self.__heureFinE else None, "dateDebutE": self.__dateDebutE.isoformat() if self.__dateDebutE else None, "dateFinE": self.__dateFinE.isoformat() if self.__dateFinE else None } class Activite_Annexe: def __init__(self, idE: int, typeA: str, ouvertAuPublic: bool): self.__idE = idE self.__typeA = typeA self.__ouvertAuPublic = ouvertAuPublic def get_idEvenement(self): return self.__idE def get_typeA(self): return self.__typeA def get_ouvertAuPublic(self): return self.__ouvertAuPublic def to_dict(self): return { "idE": self.__idE, "typeA": self.__typeA, "ouvertAuPublic": self.__ouvertAuPublic } class Concert: def __init__(self, idE: int, tempsMontage: str, tempsDemontage: str): self.__idE = idE self.__tempsMontage = self.timedelta_to_time(tempsMontage) if isinstance(tempsMontage, timedelta) else datetime.strptime(tempsMontage, '%H:%M').time() self.__tempsDemontage = self.timedelta_to_time(tempsDemontage) if isinstance(tempsDemontage, timedelta) else datetime.strptime(tempsDemontage, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idEvenement(self): return self.__idE def get_tempsMontage(self): return self.__tempsMontage def get_tempsDemontage(self): return self.__tempsDemontage def to_dict(self): return { "idE": self.__idE, "tempsMontage": self.__tempsMontage.strftime("%H:%M:%S"), "tempsDemontage": self.__tempsDemontage.strftime("%H:%M:%S") } class Groupe_Style: def __init__(self, idG: int, idSt: int): self.__idG = idG self.__idSt = idSt def get_idG(self): return self.__idG def get_idSt(self): return self.__idSt def to_dict(self): return { "idG": self.__idG, "idSt": self.__idSt } from datetime import datetime, date, time, timedelta class Faq: def __init__(self, idFaq: int, question: str, reponse: str): self._idFaq = idFaq self._question = question self._reponse = reponse def get_idFaq(self): return self._idFaq def get_question(self): return self._question def get_reponse(self): return self._reponse def to_dict(self): return { "idFaq": self._idFaq, "question": self._question, "reponse": self._reponse } class User: def __init__(self, idUser: int, pseudoUser: str, mdpUser: str, emailUser: str, statutUser: str): self.__idUser = idUser self.__pseudoUser = pseudoUser self.__mdpUser = mdpUser self.__emailUser = emailUser self.__statutUser = statutUser def get_idUser(self): return self.__idUser def get_pseudoUser(self): return self.__pseudoUser def get_mdpUser(self): return self.__mdpUser def get_emailUser(self): return self.__emailUser def get_statutUser(self): return self.__statutUser def set_pseudoUser(self, pseudoUser): self.__pseudoUser = pseudoUser def set_mdpUser(self, mdpUser): self.__mdpUser = mdpUser def set_emailUser(self, emailUser): self.__emailUser = emailUser def to_dict(self): return { "idUser": self.__idUser, "pseudoUser": self.__pseudoUser, "emailUser": self.__emailUser } class Festival: def __init__(self, idF: int, nomF: str, villeF: str, dateDebutF: str, dateFinF: str): self.__idF = idF self.__nomF = nomF self.__villeF = villeF self.__dateDebutF = dateDebutF if isinstance(dateDebutF, date) else datetime.strptime(dateDebutF, '%Y-%m-%d').date() self.__dateFinF = dateFinF if isinstance(dateFinF, date) else datetime.strptime(dateFinF, '%Y-%m-%d').date() def get_idF(self): return self.__idF def get_nomF(self): return self.__nomF def get_villeF(self): return self.__villeF def get_dateDebutF(self): return self.__dateDebutF def get_dateFinF(self): return self.__dateFinF def __repr__(self): return f"({self.__idF}, {self.__nomF}, {self.__villeF}, {self.__dateDebutF}, {self.__dateFinF})" def to_dict(self): return { "idF": self.__idF, "nomF": self.__nomF, "villeF": self.__villeF, "dateDebutF": self.__dateDebutF.isoformat(), "dateFinF": self.__dateFinF.isoformat() } class Type_Billet: def __init__(self, idType: int, duree: int): self.__idType = idType self.__duree = duree def get_idType(self): return self.__idType def get_duree(self): return self.__duree def to_dict(self): return { "idType": self.__idType, "duree": self.__duree } class Spectateur: def __init__(self, idS: int, idUser: int, nomS: str, prenomS: str): self.__idS = idS self.__idUser = idUser self.__nomS = nomS self.__prenomS = prenomS def get_idS(self): return self.__idS def get_idUser(self): return self.__idUser def get_nomS(self): return self.__nomS def get_prenomS(self): return self.__prenomS def set_nomS(self, nomS): self.__nomS = nomS def set_prenomS(self, prenomS): self.__prenomS = prenomS def to_dict(self): return { "idS": self.__idS, "idUser": self.__idUser, "nomS": self.__nomS, "prenomS": self.__prenomS } class Billet: def __init__(self, idB: int, idF: int, idType: int, idS: int, prix: int, dateAchat: str, dateDebutB: str, dateFinB: str): self.__idB = idB self.__idF = idF self.__idType = idType self.__idS = idS self.__prix = prix self.__dateAchat = dateAchat if isinstance(dateAchat, date) else datetime.strptime(dateAchat, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() if dateDebutB != None and dateFinB != None: self.__dateDebutB = dateDebutB if isinstance(dateDebutB, date) else datetime.strptime(dateDebutB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() self.__dateFinB = dateFinB if isinstance(dateFinB, date) else datetime.strptime(dateFinB, '%Y-%m-%d').date() or datetime.strptime('0000-00-00', '%Y-%m-%d %H:%M:%S').date() else: self.__dateDebutB = None self.__dateFinB = None def get_idB(self): return self.__idB def get_idFestival(self): return self.__idF def get_idType(self): return self.__idType def get_idSpectateur(self): return self.__idS def get_prix(self): return self.__prix def get_dateAchat(self): return self.__dateAchat def get_dateDebutB(self): return self.__dateDebutB def get_dateFinB(self): return self.__dateFinB def set_idType(self, idType): self.__idType = idType def set_idSpectateur(self, idS): self.__idS = idS def set_prix(self, prix): self.__prix = prix def set_dateAchat(self, dateAchat): self.__dateAchat = dateAchat def set_dateDebutB(self, dateDebutB): self.__dateDebutB = dateDebutB def set_dateFinB(self, dateFinB): self.__dateFinB = dateFinB def to_dict(self): return { "idB": self.__idB, "idF": self.__idF, "idType": self.__idType, "idS": self.__idS, "prix": self.__prix, "dateAchat": self.__dateAchat.isoformat(), "dateDebutB": self.__dateDebutB.isoformat(), "dateFinB": self.__dateFinB.isoformat() } class Lieu: def __init__(self, idL: int, idF: int, nomL: str, adresseL: str, jaugeL: int): self.__idL = idL self.__idF = idF self.__nomL = nomL self.__adresseL = adresseL self.__jaugeL = jaugeL def get_idL(self): return self.__idL def get_idFestival(self): return self.__idF def get_nomL(self): return self.__nomL def get_adresseL(self): return self.__adresseL def get_jaugeL(self): return self.__jaugeL def set_nomL(self, nomL): self.__nomL = nomL def set_adresseL(self, adresseL): self.__adresseL = adresseL def set_jaugeL(self, jaugeL): self.__jaugeL = jaugeL def to_dict(self): return { "idL": self.__idL, "idF": self.__idF, "nomL": self.__nomL, "adresseL": self.__adresseL, "jaugeL": self.__jaugeL } class Hebergement: def __init__(self, idH: int, nomH: str, limitePlacesH: int, adresseH: int): self.__idH = idH self.__nomH = nomH self.__limitePlacesH = limitePlacesH self.__adresseH = adresseH def get_idH(self): return self.__idH def get_nomH(self): return self.__nomH def get_limitePlacesH(self): return self.__limitePlacesH def get_adresseH(self): return self.__adresseH def set_nomH(self, nomH): self.__nomH = nomH def set_limitePlacesH(self, limitePlacesH): self.__limitePlacesH = limitePlacesH def set_adresseH(self, adresseH): self.__adresseH = adresseH def to_dict(self): return { "idH": self.__idH, "nomH": self.__nomH, "limitePlacesH": self.__limitePlacesH, "adresseH": self.__adresseH } class Programmer: def __init__(self, idF: int, idL: int, idH: int, dateArrivee: str, heureArrivee: str, dateDepart: str, heureDepart: str): self.__idF = idF self.__idL = idL self.__idH = idH self.__dateArrivee = dateArrivee if isinstance(dateArrivee, date) else datetime.strptime(dateArrivee, '%Y-%m-%d').date() self.__heureArrivee = self.timedelta_to_time(heureArrivee) if isinstance(heureArrivee, timedelta) else datetime.strptime(heureArrivee, '%H:%M').time() self.__dateDepart = dateDepart if isinstance(dateDepart, date) else datetime.strptime(dateDepart, '%Y-%m-%d').date() self.__heureDepart = self.timedelta_to_time(heureDepart) if isinstance(heureDepart, timedelta) else datetime.strptime(heureDepart, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idFestival(self): return self.__idF def get_idLieu(self): return self.__idL def get_idHebergement(self): return self.__idH def get_dateArrivee(self): return self.__dateArrivee def get_heureArrivee(self): return self.__heureArrivee def get_dateDepart(self): return self.__dateDepart def get_heureDepart(self): return self.__heureDepart def to_dict(self): return { "idF": self.__idF, "idL": self.__idL, "idH": self.__idH, "dateArrivee": self.__dateArrivee.isoformat(), "heureArrivee": self.__heureArrivee.strftime("%H:%M:%S"), "dateDepart": self.__dateDepart.isoformat(), "heureDepart": self.__heureDepart.strftime("%H:%M:%S") } class Membre_Groupe: def __init__(self, idMG: int, idG, nomMG: str, prenomMG: str, nomDeSceneMG: str, descriptionA: str): self.__idMG = idMG self.__idG = idG self.__nomMG = nomMG self.__prenomMG = prenomMG self.__nomDeSceneMG = nomDeSceneMG self.__descriptionA = descriptionA def get_idMG(self): return self.__idMG def get_idGroupe(self): return self.__idG def get_nomMG(self): return self.__nomMG def get_prenomMG(self): return self.__prenomMG def get_nomDeSceneMG(self): return self.__nomDeSceneMG def get_descriptionA(self): return self.__descriptionA def __repr__(self): return f"({self.__idMG}, {self.__idG}, {self.__nomMG}, {self.__prenomMG}, {self.__nomDeSceneMG})" def to_dict(self): return { "idMG": self.__idMG, "idG": self.__idG, "nomMG": self.__nomMG, "prenomMG": self.__prenomMG, "nomDeSceneMG": self.__nomDeSceneMG, "descriptionA": self.__descriptionA } def set_nomMG(self, nomMG): self.__nomMG = nomMG def set_prenomMG(self, prenomMG): self.__prenomMG = prenomMG def set_nomDeSceneMG(self, nomDeSceneMG): self.__nomDeSceneMG = nomDeSceneMG def set_descriptionA(self, descriptionA): self.__descriptionA = descriptionA class Instrument: def __init__(self, idI: int, nomI: str): self.__idI = idI self.__nomI = nomI def get_idI(self): return self.__idI def get_nomI(self): return self.__nomI def to_dict(self): return { "idI": self.__idI, "nomI": self.__nomI } class Style_Musical: def __init__(self, idSt: int, nomSt: str): self.__idSt = idSt self.__nomSt = nomSt def get_idSt(self): return self.__idSt def get_nomSt(self): return self.__nomSt def to_dict(self): return { "idSt": self.__idSt, "nomSt": self.__nomSt } class Lien_Video: def __init__(self, idLV: int, idG: int, video: str): self.__idLV = idLV self.__idG = idG self.__video = video def get_idLV(self): return self.__idLV def get_idGroupe(self): return self.__idG def get_video(self): return self.__video def to_dict(self): return { "idLV": self.__idLV, "idG": self.__idG, "video": self.__video } class Lien_Reseaux_Sociaux: def __init__(self, idLRS: int, idG: int, reseau: str): self.__idLRS = idLRS self.__idG = idG self.__reseau = reseau def get_idLRS(self): return self.__idLRS def get_idGroupe(self): return self.__idG def get_reseau(self): return self.__reseau def to_dict(self): return { "idLRS": self.__idLRS, "idG": self.__idG, "reseau": self.__reseau } class Lien_Reseaux_Sociaux_Membre: def __init__(self, idLRSM: int, idMG: int, reseau: str, URL: str): self.__idLRSM = idLRSM self.__idMG = idMG self.__reseau = reseau self.__URL = URL def get_idLRSM(self): return self.__idLRSM def get_idMG(self): return self.__idMG def get_reseau(self): return self.__reseau def get_URL(self): return self.__URL def to_dict(self): return { "idLRSM": self.__idLRSM, "idMG": self.__idMG, "reseau": self.__reseau, "URL": self.__URL } class Evenement: def __init__(self, idE: int, idG: int, idL: int, nomE: str, heureDebutE: str, heureFinE: str, dateDebutE: str, dateFinE: str): self.__idE = idE self.__idG = idG self.__idL = idL self.__nomE = nomE self.__heureDebutE = self.timedelta_to_time(heureDebutE) if isinstance(heureDebutE, timedelta) else datetime.strptime(heureDebutE, '%H:%M').time() self.__heureFinE = self.timedelta_to_time(heureFinE) if isinstance(heureFinE, timedelta) else datetime.strptime(heureFinE, '%H:%M').time() self.__dateDebutE = dateDebutE if isinstance(dateDebutE, date) else datetime.strptime(dateDebutE, "%Y-%m-%d").date() self.__dateFinE = dateFinE if isinstance(dateFinE, date) else datetime.strptime(dateFinE, "%Y-%m-%d").date() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idE(self): return self.__idE def get_idG(self): return self.__idG def get_idL(self): return self.__idL def get_nomE(self): return self.__nomE def get_heureDebutE(self): return self.__heureDebutE def get_heureFinE(self): return self.__heureFinE def get_dateDebutE(self): return self.__dateDebutE def get_dateFinE(self): return self.__dateFinE def set_idG(self, idG): self.__idG = idG def set_idL(self, idL): self.__idL = idL def set_nomE(self, nomE): self.__nomE = nomE def set_heureDebutE(self, heureDebutE): self.__heureDebutE = heureDebutE def set_heureFinE(self, heureFinE): self.__heureFinE = heureFinE def set_dateDebutE(self, dateDebutE): self.__dateDebutE = dateDebutE def set_dateFinE(self, dateFinE): self.__dateFinE = dateFinE def to_dict(self): return { "idE": self.__idE, "idG": self.__idG, "idL": self.__idL, "nomE": self.__nomE, "heureDebutE": self.__heureDebutE.strftime("%H:%M:%S") if self.__heureDebutE else None, "heureFinE": self.__heureFinE.strftime("%H:%M:%S") if self.__heureFinE else None, "dateDebutE": self.__dateDebutE.isoformat() if self.__dateDebutE else None, "dateFinE": self.__dateFinE.isoformat() if self.__dateFinE else None } class Activite_Annexe: def __init__(self, idE: int, typeA: str, ouvertAuPublic: bool): self.__idE = idE self.__typeA = typeA self.__ouvertAuPublic = ouvertAuPublic def get_idEvenement(self): return self.__idE def get_typeA(self): return self.__typeA def get_ouvertAuPublic(self): return self.__ouvertAuPublic def to_dict(self): return { "idE": self.__idE, "typeA": self.__typeA, "ouvertAuPublic": self.__ouvertAuPublic } class Concert: def __init__(self, idE: int, tempsMontage: str, tempsDemontage: str): self.__idE = idE self.__tempsMontage = self.timedelta_to_time(tempsMontage) if isinstance(tempsMontage, timedelta) else datetime.strptime(tempsMontage, '%H:%M').time() self.__tempsDemontage = self.timedelta_to_time(tempsDemontage) if isinstance(tempsDemontage, timedelta) else datetime.strptime(tempsDemontage, '%H:%M').time() @staticmethod def timedelta_to_time(td): return (datetime.min + td).time() def get_idEvenement(self): return self.__idE def get_tempsMontage(self): return self.__tempsMontage def get_tempsDemontage(self): return self.__tempsDemontage def to_dict(self): return { "idE": self.__idE, "tempsMontage": self.__tempsMontage.strftime("%H:%M:%S"), "tempsDemontage": self.__tempsDemontage.strftime("%H:%M:%S") } class Groupe_Style: def __init__(self, idG: int, idSt: int): self.__idG = idG self.__idSt = idSt def get_idG(self): return self.__idG def get_idSt(self): return self.__idSt def to_dict(self): return { "idG": self.__idG, "idSt": self.__idSt }
911e99ff67ab62e32d4fcc5f88128246
{ "intermediate": 0.3344615399837494, "beginner": 0.5392231345176697, "expert": 0.12631525099277496 }
37,777
In unity, using animation rigging, i want my head to move when shooting. What do you suggest to do and what component are involved to make such a thing?
e77fbd20618c256cf62ed447f1d58d03
{ "intermediate": 0.377358078956604, "beginner": 0.3097063899040222, "expert": 0.3129355013370514 }
37,778
In Unity, how to check if an animation is in transition, then do stuff?
9e0ff3c4f2c87eee3f5799693f5c70f9
{ "intermediate": 0.6013883352279663, "beginner": 0.20340873301029205, "expert": 0.19520293176174164 }
37,779
def pintoggle(self): if self.root.attributes("-topmost", True): self.root.attributes("-topmost", False) else : self.root.attributes("-topmost", True) make the method toggle on top true to false and vice versa
616cf5f993edd97502a3e7bdac124b06
{ "intermediate": 0.34902259707450867, "beginner": 0.3471183180809021, "expert": 0.3038591146469116 }
37,780
Write an sql command the add rows to a table in [P2 Relational DB].dbo called Timeseries Tags (int)(noavg) The table has 3 columns, Tagname, Value and Timestamp for every entry the Tagname column should be 'A.R_ShiftNumTest' The value of the column 'Value' should follow the sequence 2,3,2,4,3,4,3,5,4,1,5,1,5,2,1,3 The third column is called 'Timestamp' the first column should contain a timestamp starting at 2022-11-23 18:00:00.000 and advancing by 12 hours for each entry You should create enough entries to reach 2023-01-17 06:00:00.000
3a3748f9c23b0f227a3b0a201ba1edb7
{ "intermediate": 0.4323357343673706, "beginner": 0.24298661947250366, "expert": 0.32467761635780334 }
37,781
difference between clojure and kotlin
7257a07c772b8ff11ea94a7f10d71312
{ "intermediate": 0.5227661728858948, "beginner": 0.2864740788936615, "expert": 0.19075970351696014 }
37,782
here: def get_dfs_means(dfs: list): common_index = dfs[0].index columns = pd.Index(sorted(set(col for df in dfs for col in df.columns))) sums = pd.DataFrame(0, index=common_index, columns=columns) counts = pd.DataFrame(0, index=common_index, columns=columns) for df in dfs: sums[df.columns] += df counts[df.columns] += 1 means = sums.div(counts.replace(0, pd.NA)) means.columns = [int(x) for x in means.columns] means = means.loc[:,means.columns.sort_values()] means.columns = [str(int(j)/1000) + "k" if int(j) > 500 else j for j in means.columns] return means I want to get the median now
4c2c3816c46ccb8d310f2b8c28a12f52
{ "intermediate": 0.4111744165420532, "beginner": 0.33831968903541565, "expert": 0.25050589442253113 }
37,783
Create a JS to parse and filter the data from useless information and only information in which GPT would find useful for determining Playwright selectors from the different elements of a page. The cleaned data should be within GPT token size. Output the entire JS example of this. For example, some useless data would be things like: - The text-content of paragraphs - Script tags - Text or values of html attributes longer than 50 chars - .... Output nothing but JS
20dbcd4a040d80bdb8992dd52f6a6a45
{ "intermediate": 0.5150132775306702, "beginner": 0.15722371637821198, "expert": 0.3277629315853119 }
37,784
i am trying to make a webapp (intended for smartphones) which has a lets say a 5x6 grid of numbers in it. if i click a random number "x" in the grid, the page shows a label which shows the result x+10. is it possible to add eye tracking technology to this? the procedure i am aiming for goes like this - webapp tells user to close eyes for a few seconds, and then open them , and focus eyes on a particular number. the eye tracking software then calculates the location the eyes are seeing on the grid, takes the number on the location and then give x+10. this must be done with the inbuilt smartphone camera, the front one to be specific. can this kind of webapp be made?
b770bb2824971e17a82e41f962e16224
{ "intermediate": 0.35322684049606323, "beginner": 0.22272135317325592, "expert": 0.42405182123184204 }
37,785
how to make changes in python code by api endpoint?
bbd4cb9930e7ae79dc0ff12c3e266b5a
{ "intermediate": 0.6983709335327148, "beginner": 0.16152070462703705, "expert": 0.1401083767414093 }
37,786
Explain to me this code using System.Collections.Generic; using UnityEngine; using UnityEngine.Serialization; namespace Cards { public class HandController : MonoBehaviour { [Header("Card Settings")] [SerializeField] private bool cardUprightWhenSelected = true; [SerializeField] private bool cardTilt = true; [Header("Hand Settings")] [SerializeField] [Range(0, 5)] private float selectionSpacing = 1; [SerializeField] private Vector3 curveStart = new Vector3(2f, -0.7f, 0); [SerializeField] private Vector3 curveEnd = new Vector3(-2f, -0.7f, 0); [SerializeField] private Vector2 handOffset = new Vector2(0, -0.3f); [SerializeField] private Vector2 handSize = new Vector2(9, 1.7f); [SerializeField] private float minimumDistanceToSelected = 2f; [Header("References")] public Transform discardTransform; public Transform exhaustTransform; public Transform drawTransform; public LayerMask selectableLayer; public LayerMask targetLayer; public Camera cam = null; public List<CardBase> hand; // Cards currently in hand #region Cache /*protected FxManager FxManager => FxManager.Instance; protected AudioManager AudioManager => AudioManager.Instance; protected GameManager GameManager => GameManager.Instance; protected CombatManager CombatManager => CombatManager.Instance; protected CollectionManager CollectionManager => CollectionManager.Instance; protected UIManager UIManager => UIManager.Instance;*/ private Plane _plane; // world XY plane, used for mouse position raycasts private Vector3 _a, _b, _c; // Used for shaping hand into curve private int _selected = -1; // Card index that is nearest to mouse private int _dragged = -1; // Card index that is held by mouse (inside of hand) private CardBase _heldCard; // Card that is held by mouse (when outside of hand) private Vector3 _heldCardOffset; private Vector2 _heldCardTilt; private Vector2 _force; private Vector3 _mouseWorldPos; private Vector2 _prevMousePos; private Vector2 _mousePosDelta; private Rect _handBounds; private bool _mouseInsideHand; private bool updateHierarchyOrder = false; private bool showDebugGizmos = true; private Camera _mainCam; public bool IsDraggingActive { get; private set; } = true; #endregion #region Setup private void Awake() { _mainCam = Camera.main; } private void Start() { InitHand(); } private void InitHand() { _a = transform.TransformPoint(curveStart); _b = transform.position; _c = transform.TransformPoint(curveEnd); _handBounds = new Rect((handOffset - handSize / 2), handSize); _plane = new Plane(-Vector3.forward, transform.position); _prevMousePos = Input.mousePosition; } #endregion #region Process private void Update() { // -------------------------------------------------------- // HANDLE MOUSE & RAYCAST POSITION // -------------------------------------------------------- if (!IsDraggingActive) return; var mousePos = HandleMouseInput(out var count, out var sqrDistance, out var mouseButton); // -------------------------------------------------------- // HANDLE CARDS IN HAND // -------------------------------------------------------- HandleCardsInHand(count, mouseButton, sqrDistance); // -------------------------------------------------------- // HANDLE DRAGGED CARD // (Card held by mouse, inside hand) // -------------------------------------------------------- HandleDraggedCardInsideHand(mouseButton, count); // -------------------------------------------------------- // HANDLE HELD CARD // (Card held by mouse, outside of the hand) // -------------------------------------------------------- HandleDraggedCardOutsideHand(mouseButton, mousePos); } #endregion #region Methods public void EnableDragging() => IsDraggingActive = true; public void DisableDragging() => IsDraggingActive = false; private Vector2 HandleMouseInput(out int count, out float sqrDistance, out bool mouseButton) { Vector2 mousePos = Input.mousePosition; // Allows mouse to go outside game window but keeps cards within window // If mouse doesn't need to go outside, could use "Cursor.lockState = CursorLockMode.Confined;" instead mousePos.x = Mathf.Clamp(mousePos.x, 0, Screen.width); mousePos.y = Mathf.Clamp(mousePos.y, 0, Screen.height); // Mouse movement velocity if (cardTilt) TiltCard(mousePos); // Get world position from mouse GetMouseWorldPosition(mousePos); // Get distance to current selected card (for comparing against other cards later, to find closest) GetDistanceToCurrentSelectedCard(out count, out sqrDistance); // Check if mouse is inside hand bounds CheckMouseInsideHandBounds(out mouseButton); return mousePos; } private void HandleCardsInHand(int count, bool mouseButton, float sqrDistance) { for (var i = 0; i < count; i++) { var card = hand[i]; var cardTransform = card.transform; // Set to inactive material if not enough mana required to use card //card.SetInactiveMaterialState(GameManager.PersistentGameplayData.CurrentMana < card.CardData.ManaCost); var noCardHeld = _heldCard == null; // Whether a card is "held" (outside of hand) var onSelectedCard = noCardHeld && _selected == i; var onDraggedCard = noCardHeld && _dragged == i; // Get Position along Curve (for card positioning) float selectOffset = 0; //if (noCardHeld) //selectOffset = 0.02f * Mathf.Clamp01(1 - Mathf.Abs(Mathf.Abs(i - _selected) - 1) / (float) count * 3) * Mathf.Sign(i - _selected); var t = (count > 1 ? (float)i / (count - 1) : 0.5f) + selectOffset * selectionSpacing; var p = GetCurvePoint(_a, _b, _c, t); var d = (p - _mouseWorldPos).sqrMagnitude; var mouseCloseToCard = d < 1f; var mouseHoveringOnSelected = onSelectedCard && mouseCloseToCard && _mouseInsideHand; // && mouseInsideHand // Handle Card Position & Rotation //Vector3 cardUp = p - (transform.position + Vector3.down * 7); var cardUp = GetCurveNormal(_a, _b, _c, t); //var cardPos = p + (mouseHoveringOnSelected ? cardTransform.up * 0.3f : Vector3.zero); var cardForward = Vector3.forward; var cardPos = p; if (mouseHoveringOnSelected) { cardTransform.localScale = Vector3.one * 1.2f; cardPos.y = 1f; } else { cardTransform.localScale = Vector3.one; } /* Card Tilt is disabled when in hand as they can clip through eachother :( if (cardTilt && onSelectedCard && mouseButton) { cardForward -= new Vector3(heldCardOffset.x, heldCardOffset.y, 0); }*/ // Sorting Order if (mouseHoveringOnSelected || onDraggedCard) { // When selected bring card to front if (cardUprightWhenSelected) cardUp = Vector3.up; cardPos.z = transform.position.z - 0.2f; } else { cardPos.z = transform.position.z + t * 0.5f; } // Rotation cardTransform.rotation = Quaternion.RotateTowards(cardTransform.rotation, Quaternion.LookRotation(cardForward, cardUp), 80f * Time.deltaTime); // Handle Start Dragging if (mouseHoveringOnSelected) { var mouseButtonDown = Input.GetMouseButtonDown(0); if (mouseButtonDown) { _dragged = i; _heldCardOffset = cardTransform.position - _mouseWorldPos; _heldCardOffset.z = -0.1f; } } // Handle Card Position if (onDraggedCard && mouseButton) { // Held by mouse / dragging cardPos = _mouseWorldPos + _heldCardOffset; cardTransform.position = cardPos; } else { cardPos = Vector3.MoveTowards(cardTransform.position, cardPos, 10f * Time.deltaTime); cardTransform.position = cardPos; } // Get Selected Card // if (GameManager.PersistentGameplayData.CanSelectCards) // { //float d = (p - mouseWorldPos).sqrMagnitude; if (_mouseInsideHand) { if (d < sqrDistance) { sqrDistance = d; _selected = i; } } else { _selected = -1; } // } // else // { // _selected = -1; // _dragged = -1; // } // Debug Gizmos if (showDebugGizmos) { var c = new Color(0, 0, 0, 0.2f); if (i == _selected) { c = Color.red; if (sqrDistance > 2) c = Color.blue; } Debug.DrawLine(p, _mouseWorldPos, c); } } } private void HandleDraggedCardOutsideHand(bool mouseButton, Vector2 mousePos) { if (_heldCard != null) { var cardTransform = _heldCard.transform; var cardUp = Vector3.up; var cardPos = _mouseWorldPos + _heldCardOffset; var cardForward = Vector3.forward; if (cardTilt && mouseButton) cardForward -= new Vector3(_heldCardTilt.x, _heldCardTilt.y, 0); // Bring card to front cardPos.z = transform.position.z - 0.2f; // Handle Position & Rotation cardTransform.rotation = Quaternion.RotateTowards(cardTransform.rotation, Quaternion.LookRotation(cardForward, cardUp), 80f * Time.deltaTime); cardTransform.position = cardPos; //CombatManager.HighlightCardTarget(_heldCard.CardData.CardActionDataList[0].ActionTargetType); //if (!canSelectCards || cardTransform.position.y <= transform.position.y + 0.5f) { // if (!GameManager.PersistentGameplayData.CanSelectCards || _mouseInsideHand) // { // // || sqrDistance <= 2 // // Card has gone back into hand // AddCardToHand(_heldCard, _selected); // _dragged = _selected; // _selected = -1; // _heldCard = null; // // CombatManager.DeactivateCardHighlights(); // // return; // } var mouseButtonUp = Input.GetMouseButtonUp(0); if (!mouseButtonUp) return; _heldCard = null; cardTransform.gameObject.GetComponent<Card3D>().Discard(); } } /*private void PlayCard(Vector2 mousePos) { // Use Card var mouseButtonUp = Input.GetMouseButtonUp(0); if (!mouseButtonUp) return; //Remove highlights CombatManager.DeactivateCardHighlights(); bool backToHand = true; if (GameManager.PersistentGameplayData.CanUseCards && GameManager.PersistentGameplayData.CurrentMana >= _heldCard.CardData.ManaCost) { RaycastHit hit; var mainRay = _mainCam.ScreenPointToRay(mousePos); var _canUse = false; CharacterBase selfCharacter = CombatManager.CurrentMainAlly; CharacterBase targetCharacter = null; _canUse = _heldCard.CardData.UsableWithoutTarget || CheckPlayOnCharacter(mainRay, _canUse, ref selfCharacter, ref targetCharacter); if (_canUse) { backToHand = false; _heldCard.Use(selfCharacter,targetCharacter,CombatManager.CurrentEnemiesList,CombatManager.CurrentAlliesList); } } if (backToHand) // Cannot use card / Not enough mana! Return card to hand! AddCardToHand(_heldCard, _selected); _heldCard = null; } /*private bool CheckPlayOnCharacter(Ray mainRay, bool _canUse, ref CharacterBase selfCharacter, ref CharacterBase targetCharacter) { RaycastHit hit; if (Physics.Raycast(mainRay, out hit, 1000, targetLayer)) { var character = hit.collider.gameObject.GetComponent<ICharacter>(); if (character != null) { var checkEnemy = (_heldCard.CardData.CardActionDataList[0].ActionTargetType == ActionTargetType.Enemy && character.GetCharacterType() == CharacterType.Enemy); var checkAlly = (_heldCard.CardData.CardActionDataList[0].ActionTargetType == ActionTargetType.Ally && character.GetCharacterType() == CharacterType.Ally); if (checkEnemy || checkAlly) { _canUse = true; selfCharacter = CombatManager.CurrentMainAlly; targetCharacter = character.GetCharacterBase(); } } } return _canUse; }*/ private void HandleDraggedCardInsideHand(bool mouseButton, int count) { if (!mouseButton) { // Stop dragging _heldCardOffset = Vector3.zero; _dragged = -1; } if (_dragged != -1) { var card = hand[_dragged]; if (mouseButton && !_mouseInsideHand) { // && sqrDistance > 2.1f //if (cardPos.y > transform.position.y + 0.5) { // Card is outside of the hand, so is considered "held" ready to be used // Remove from hand, so that cards in hand fill the hole that the card left _heldCard = card; RemoveCardFromHand(_dragged); count--; _dragged = -1; } } if (_heldCard == null && mouseButton && _dragged != -1 && _selected != -1 && _dragged != _selected) { // Move dragged card MoveCardToIndex(_dragged, _selected); _dragged = _selected; } } private void CheckMouseInsideHandBounds(out bool mouseButton) { var point = transform.InverseTransformPoint(_mouseWorldPos); _mouseInsideHand = _handBounds.Contains(point); mouseButton = Input.GetMouseButton(0); } private void GetDistanceToCurrentSelectedCard(out int count, out float sqrDistance) { count = hand.Count; sqrDistance = 1000; if (_selected >= 0 && _selected < count) { var t = ((float)_selected) / (count - 1); var p = GetCurvePoint(_a, _b, _c, t); sqrDistance = (p - _mouseWorldPos).sqrMagnitude; //Debug.Log(sqrDistance); } } private void GetMouseWorldPosition(Vector2 mousePos) { var ray = cam.ScreenPointToRay(mousePos); if (_plane.Raycast(ray, out var enter)) _mouseWorldPos = ray.GetPoint(enter); } private void TiltCard(Vector2 mousePos) { _mousePosDelta = (mousePos - _prevMousePos) * new Vector2(1600f / Screen.width, 900f / Screen.height) * Time.deltaTime; _prevMousePos = mousePos; var tiltStrength = 3f; var tiltDrag = 3f; var tiltSpeed = 50f; _force += (_mousePosDelta * tiltStrength - _heldCardTilt) * Time.deltaTime; _force *= 1 - tiltDrag * Time.deltaTime; _heldCardTilt += _force * (Time.deltaTime * tiltSpeed); // these calculations probably aren't correct, but hey, they work...? :P if (showDebugGizmos) { Debug.DrawRay(_mouseWorldPos, _mousePosDelta, Color.red); Debug.DrawRay(_mouseWorldPos, _heldCardTilt, Color.cyan); } } #endregion #region Cyan Methods /// <summary> /// Obtains a point along a curve based on 3 points. Equal to Lerp(Lerp(a, b, t), Lerp(b, c, t), t). /// </summary> public static Vector3 GetCurvePoint(Vector3 a, Vector3 b, Vector3 c, float t) { t = Mathf.Clamp01(t); float oneMinusT = 1f - t; return (oneMinusT * oneMinusT * a) + (2f * oneMinusT * t * b) + (t * t * c); } /// <summary> /// Obtains the derivative of the curve (tangent) /// </summary> public static Vector3 GetCurveTangent(Vector3 a, Vector3 b, Vector3 c, float t) { return 2f * (1f - t) * (b - a) + 2f * t * (c - b); } /// <summary> /// Obtains a direction perpendicular to the tangent of the curve /// </summary> public static Vector3 GetCurveNormal(Vector3 a, Vector3 b, Vector3 c, float t) { Vector3 tangent = GetCurveTangent(a, b, c, t); return Vector3.Cross(tangent, Vector3.forward); } /// <summary> /// Moves the card in hand from the currentIndex to the toIndex. If you want to move a card that isn't in hand, use AddCardToHand /// </summary> public void MoveCardToIndex(int currentIndex, int toIndex) { if (currentIndex == toIndex) return; // Same index, do nothing CardBase card = hand[currentIndex]; hand.RemoveAt(currentIndex); hand.Insert(toIndex, card); if (updateHierarchyOrder) { card.transform.SetSiblingIndex(toIndex); } } /// <summary> /// Adds a card to the hand. Optional param to insert it at a given index. /// </summary> public void AddCardToHand(CardBase card, int index = -1) { if (index < 0) { // Add to end hand.Add(card); index = hand.Count - 1; } else { // Insert at index hand.Insert(index, card); } if (updateHierarchyOrder) { card.transform.SetParent(transform); card.transform.SetSiblingIndex(index); } } /// <summary> /// Remove the card at the specified index from the hand. /// </summary> public void RemoveCardFromHand(int index) { if (updateHierarchyOrder) { CardBase card = hand[index]; card.transform.SetParent(transform.parent); card.transform.SetSiblingIndex(transform.GetSiblingIndex() + 1); } hand.RemoveAt(index); } #endregion #region Editor #if UNITY_EDITOR private void OnDrawGizmos() { Gizmos.matrix = transform.localToWorldMatrix; Gizmos.color = Color.blue; Gizmos.DrawSphere(curveStart, 0.03f); //Gizmos.DrawSphere(Vector3.zero, 0.03f); Gizmos.DrawSphere(curveEnd, 0.03f); Vector3 p1 = curveStart; for (int i = 0; i < 20; i++) { float t = (i + 1) / 20f; Vector3 p2 = GetCurvePoint(curveStart, Vector3.zero, curveEnd, t); Gizmos.DrawLine(p1, p2); p1 = p2; } if (_mouseInsideHand) { Gizmos.color = Color.red; } Gizmos.DrawWireCube(handOffset, handSize); } #endif #endregion } }
418b087e949551fef8ecb04a2272229c
{ "intermediate": 0.5549015402793884, "beginner": 0.3298584222793579, "expert": 0.11524006724357605 }
37,787
self.button_hid = False self.root.bind("<Enter>", self.toggle_label_visibility) self.root.bind("<Leave>", self.toggle_label_visibility) def toggle_label_visibility(self, event): #global button_visible if self.button_hid: # Hide the label if it’s currently visible self.main_frame.pack_forget() else: # Show the label if it’s currently hidden self.main_frame.pack() # Flip the flag self.button_hid = not self.button_hid how to add small delay so it doesn't flicker
6c7856ec24ab9dfd34cbd8985ffd8b3a
{ "intermediate": 0.3000572919845581, "beginner": 0.2683406174182892, "expert": 0.43160200119018555 }
37,788
do you know what is ootii motion controller?
4d23fa59b6083cc0d2c39137ab947a14
{ "intermediate": 0.3523835837841034, "beginner": 0.31988656520843506, "expert": 0.32772985100746155 }
37,789
hi
b4e1de8adcbfe54aece79822f639801a
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,790
In unity, using C#, why can't i access my character script from another script? I want to access PlayerVitals from the Sneak_v2 script. Here is the Sneak_v2 script, from ootii motion controller : using UnityEngine; using com.ootii.Cameras; using com.ootii.Geometry; using com.ootii.Helpers; #if UNITY_EDITOR using UnityEditor; #endif namespace com.ootii.Actors.AnimationControllers { /// <summary> /// The sneak is a slow move that keeps the character facing forward. /// /// This motion will force the camera into the third-person-fixed mode. /// </summary> [MotionName("Sneak")] [MotionDescription("A forward facing motion that looks like the actor is sneaking. The motion is slower than a walk and has the actor strafe instead of turn.")] public class Sneak_v2 : MotionControllerMotion { // Values to average public const int SMOOTHING_BASE = 20; // Enum values for the motion public const int PHASE_UNKNOWN = 0; public const int PHASE_START = 620; public const int PHASE_START_OLD = 600; public const int PHASE_END = 610; /// <summary> /// Units per second to move. Set to '0' to use root-motion /// </summary> public float _MovementSpeed = 0f; public float MovementSpeed { get { return _MovementSpeed; } set { _MovementSpeed = value; } } /// <summary> /// Determines if the actor rotates based on the input /// </summary> public bool _RotateWithInput = false; public bool RotateWithInput { get { return _RotateWithInput; } set { _RotateWithInput = value; if (_RotateWithInput) { _RotateWithCamera = false; } } } /// <summary> /// Determines if the actor rotates to face the direction the /// camera is facing /// </summary> public bool _RotateWithCamera = true; public bool RotateWithCamera { get { return _RotateWithCamera; } set { _RotateWithCamera = value; if (_RotateWithCamera) { _RotateWithInput = false; } } } /// <summary> /// Desired degrees of rotation per second /// </summary> public float _RotationSpeed = 180f; public float RotationSpeed { get { return _RotationSpeed; } set { _RotationSpeed = value; } } /// <summary> /// Number of samples to use for smoothing /// </summary> public int _SmoothingSamples = 20; public int SmoothingSamples { get { return _SmoothingSamples; } set { _SmoothingSamples = value; mInputX.SampleCount = _SmoothingSamples; mInputY.SampleCount = _SmoothingSamples; mInputMagnitude.SampleCount = _SmoothingSamples; } } /// <summary> /// Determines if the actor rotation should be linked to the camera /// </summary> protected bool mLinkRotation = false; /// <summary> /// Fields to help smooth out the mouse rotation /// </summary> protected float mYaw = 0f; protected float mYawTarget = 0f; protected float mYawVelocity = 0f; /// <summary> /// We use these classes to help smooth the input values so that /// movement doesn't drop from 1 to 0 immediately. /// </summary> protected FloatValue mInputX = new FloatValue(0f, SMOOTHING_BASE); protected FloatValue mInputY = new FloatValue(0f, SMOOTHING_BASE); protected FloatValue mInputMagnitude = new FloatValue(0f, SMOOTHING_BASE); /// <summary> /// Store the stance we're coming from /// </summary> protected int mStoredStance = EnumControllerStance.TRAVERSAL; /// <summary> /// Default constructor /// </summary> public Sneak_v2() : base() { _Category = EnumMotionCategories.WALK; _Priority = 6; _ActionAlias = "Change Stance"; #if UNITY_EDITOR if (_EditorAnimatorSMName.Length == 0) { _EditorAnimatorSMName = "Sneak v2-SM"; } #endif } /// <summary> /// Controller constructor /// </summary> /// <param name="rController">Controller the motion belongs to</param> public Sneak_v2(MotionController rController) : base(rController) { _Category = EnumMotionCategories.WALK; _Priority = 6; _ActionAlias = "Change Stance"; #if UNITY_EDITOR if (_EditorAnimatorSMName.Length == 0) { _EditorAnimatorSMName = "Sneak v2-SM"; } #endif } /// <summary> /// Awake is called after all objects are initialized so you can safely speak to other objects. This is where /// reference can be associated. /// </summary> public override void Awake() { base.Awake(); // Initialize the smoothing variables SmoothingSamples = _SmoothingSamples; } /// <summary> /// Tests if this motion should be started. However, the motion /// isn't actually started. /// </summary> /// <returns></returns> public override bool TestActivate() { if (!mIsStartable) { return false; } if (!mMotionController.IsGrounded) { return false; } if (mMotionLayer.ActiveMotion == null) { if (mMotionController.Stance == EnumControllerStance.STEALTH) { return true; } } // Test for an input change if (mMotionController._InputSource != null && mMotionController._InputSource.IsEnabled) { if (mMotionController._InputSource.IsJustPressed(_ActionAlias)) { if (mMotionController.Stance != EnumControllerStance.STEALTH) { mStoredStance = mMotionController.Stance; mMotionController.Stance = EnumControllerStance.STEALTH; return true; } else { mMotionController.Stance = mStoredStance; } } } // If we get here, we should not be in the stance return false; } /// <summary> /// Tests if the motion should continue. If it shouldn't, the motion /// is typically disabled /// </summary> /// <returns></returns> public override bool TestUpdate() { if (mIsActivatedFrame) { return true; } if (!mMotionController.IsGrounded) { return false; } if (mIsAnimatorActive && !IsInMotionState) { return false; } if (mMotionController.Stance != EnumControllerStance.STEALTH) { return false; } // Test if we stop sneak due to a change in state if (mMotionLayer._AnimatorStateID == STATE_IdlePose) { mMotionController.Stance = mStoredStance; return false; } // Otherwise, stay in return true; } /// <summary> /// Raised when a motion is being interrupted by another motion /// </summary> /// <param name="rMotion">Motion doing the interruption</param> /// <returns>Boolean determining if it can be interrupted</returns> public override bool TestInterruption(MotionControllerMotion rMotion) { // Since we're dealing with a blend tree, keep the value until the transition completes mMotionController.ForcedInput.x = mInputX.Average; mMotionController.ForcedInput.y = mInputY.Average; return true; } /// <summary> /// Called to start the specific motion. If the motion /// were something like 'jump', this would start the jumping process /// </summary> /// <param name="rPrevMotion">Motion that this motion is taking over from</param> public override bool Activate(MotionControllerMotion rPrevMotion) { mLinkRotation = false; // Used to make the sample frame rate independent float lFPSPercent = Mathf.Clamp((0.0166f / Time.deltaTime), 0.5f, 5.0f); int lSmoothingSamples = (int)(_SmoothingSamples * lFPSPercent); mInputX.SampleCount = lSmoothingSamples; mInputY.SampleCount = lSmoothingSamples; mInputMagnitude.SampleCount = lSmoothingSamples; // Force the character's stance to change mMotionController.Stance = EnumControllerStance.STEALTH; // Trigger the change in the animator mMotionController.SetAnimatorMotionPhase(mMotionLayer.AnimatorLayerIndex, PHASE_START, true); // Register this motion with the camera if (_RotateWithCamera && mMotionController.CameraRig is BaseCameraRig) { ((BaseCameraRig)mMotionController.CameraRig).OnPostLateUpdate -= OnCameraUpdated; ((BaseCameraRig)mMotionController.CameraRig).OnPostLateUpdate += OnCameraUpdated; } // Allow the base to finish return base.Activate(rPrevMotion); } /// <summary> /// Called to stop the motion. If the motion is stopable. Some motions /// like jump cannot be stopped early /// </summary> public override void Deactivate() { // Register this motion with the camera if (mMotionController.CameraRig is BaseCameraRig) { ((BaseCameraRig)mMotionController.CameraRig).OnPostLateUpdate -= OnCameraUpdated; } // Deactivate base.Deactivate(); } /// <summary> /// Allows the motion to modify the root-motion velocities before they are applied. /// /// NOTE: /// Be careful when removing rotations as some transitions will want rotations even /// if the state they are transitioning from don't. /// </summary> /// <param name="rDeltaTime">Time since the last frame (or fixed update call)</param> /// <param name="rUpdateIndex">Index of the update to help manage dynamic/fixed updates. [0: Invalid update, >=1: Valid update]</param> /// <param name="rVelocityDelta">Root-motion linear velocity relative to the actor's forward</param> /// <param name="rRotationDelta">Root-motion rotational velocity</param> /// <returns></returns> public override void UpdateRootMotion(float rDeltaTime, int rUpdateIndex, ref Vector3 rMovement, ref Quaternion rRotation) { rRotation = Quaternion.identity; // Override root motion if we're meant to if (_MovementSpeed > 0f) { rMovement.x = mMotionController.State.InputX; rMovement.y = 0f; rMovement.z = mMotionController.State.InputY; rMovement = rMovement.normalized * (_MovementSpeed * rDeltaTime); } } /// <summary> /// Updates the motion over time. This is called by the controller /// every update cycle so animations and stages can be updated. /// </summary> /// <param name="rDeltaTime">Time since the last frame (or fixed update call)</param> /// <param name="rUpdateIndex">Index of the update to help manage dynamic/fixed updates. [0: Invalid update, >=1: Valid update]</param> public override void Update(float rDeltaTime, int rUpdateIndex) { mMovement = Vector3.zero; mRotation = Quaternion.identity; // Test if we stop sneak due to a change in stance. We do this here to transition if (mMotionController.State.AnimatorStates[mMotionLayer._AnimatorLayerIndex].MotionPhase == 0 && mMotionController._InputSource != null && mMotionController._InputSource.IsEnabled) { if (mMotionController._InputSource.IsJustPressed(_ActionAlias)) { // We have to use the forced value our we'll change the current blend value as we transition mMotionController.ForcedInput.x = mInputX.Average; mMotionController.ForcedInput.y = mInputY.Average; mMotionController.SetAnimatorMotionPhase(mMotionLayer._AnimatorLayerIndex, PHASE_END, 0, true); } } // Grab the state info MotionState lState = mMotionController.State; // Convert the input to radial so we deal with keyboard and gamepad input the same. float lInputX = lState.InputX; float lInputY = lState.InputY; float lInputMagnitude = lState.InputMagnitudeTrend.Value; InputManagerHelper.ConvertToRadialInput(ref lInputX, ref lInputY, ref lInputMagnitude, 0.5f); // Smooth the input mInputX.Add(lInputX); mInputY.Add(lInputY); mInputMagnitude.Add(lInputMagnitude); // Use the smoothed values for input mMotionController.State.InputX = mInputX.Average; mMotionController.State.InputY = mInputY.Average; mMotionController.State.InputMagnitudeTrend.Replace(mInputMagnitude.Average); // If we're not dealing with an ootii camera rig, we need to rotate to the camera here if (_RotateWithCamera && !(mMotionController.CameraRig is BaseCameraRig)) { OnCameraUpdated(rDeltaTime, rUpdateIndex, null); } // Rotate as needed if (!_RotateWithCamera && _RotateWithInput) { RotateUsingInput(rDeltaTime, ref mRotation); } } /// <summary> /// Create a rotation velocity that rotates the character based on input /// </summary> /// <param name="rDeltaTime"></param> /// <param name="rAngularVelocity"></param> private void RotateUsingInput(float rDeltaTime, ref Quaternion rRotation) { // If we don't have an input source, stop if (mMotionController._InputSource == null) { return; } // Determine this frame's rotation float lYawDelta = 0f; float lYawSmoothing = 0.1f; if (mMotionController._InputSource.IsViewingActivated) { lYawDelta = mMotionController._InputSource.ViewX * _RotationSpeed * rDeltaTime; } mYawTarget = mYawTarget + lYawDelta; // Smooth the rotation lYawDelta = (lYawSmoothing <= 0f ? mYawTarget : Mathf.SmoothDampAngle(mYaw, mYawTarget, ref mYawVelocity, lYawSmoothing)) - mYaw; mYaw = mYaw + lYawDelta; // Use this frame's smoothed rotation if (lYawDelta != 0f) { rRotation = Quaternion.Euler(0f, lYawDelta, 0f); } } /// <summary> /// When we want to rotate based on the camera direction, we need to tweak the actor /// rotation AFTER we process the camera. Otherwise, we can get small stutters during camera rotation. /// /// This is the only way to keep them totally in sync. It also means we can't run any of our AC processing /// as the AC already ran. So, we do minimal work here /// </summary> /// <param name="rDeltaTime"></param> /// <param name="rUpdateCount"></param> /// <param name="rCamera"></param> private void OnCameraUpdated(float rDeltaTime, int rUpdateIndex, BaseCameraRig rCamera) { if (mMotionController._CameraTransform == null) { return; } float lToCameraAngle = Vector3Ext.HorizontalAngleTo(mMotionController._Transform.forward, mMotionController._CameraTransform.forward, mMotionController._Transform.up); if (!mLinkRotation && Mathf.Abs(lToCameraAngle) <= _RotationSpeed * rDeltaTime) { mLinkRotation = true; } if (!mLinkRotation) { float lRotationAngle = Mathf.Abs(lToCameraAngle); float lRotationSign = Mathf.Sign(lToCameraAngle); lToCameraAngle = lRotationSign * Mathf.Min(_RotationSpeed * rDeltaTime, lRotationAngle); } Quaternion lRotation = Quaternion.AngleAxis(lToCameraAngle, Vector3.up); mActorController.Yaw = mActorController.Yaw * lRotation; mActorController._Transform.rotation = mActorController.Tilt * mActorController.Yaw; } #region Editor Functions // ************************************************************************************************** // Following properties and function only valid while editing // ************************************************************************************************** #if UNITY_EDITOR /// <summary> /// Creates input settings in the Unity Input Manager /// </summary> public override void CreateInputManagerSettings() { if (!InputManagerHelper.IsDefined(_ActionAlias)) { InputManagerEntry lEntry = new InputManagerEntry(); lEntry.Name = _ActionAlias; lEntry.PositiveButton = "t"; lEntry.Gravity = 1000; lEntry.Dead = 0.001f; lEntry.Sensitivity = 1000; lEntry.Type = InputManagerEntryType.KEY_MOUSE_BUTTON; lEntry.Axis = 0; lEntry.JoyNum = 0; InputManagerHelper.AddEntry(lEntry, true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX lEntry = new InputManagerEntry(); lEntry.Name = _ActionAlias; lEntry.PositiveButton = "joystick button 11"; // Left stick click lEntry.Gravity = 1; lEntry.Dead = 0.3f; lEntry.Sensitivity = 1; lEntry.Type = InputManagerEntryType.KEY_MOUSE_BUTTON; lEntry.Axis = 0; lEntry.JoyNum = 0; InputManagerHelper.AddEntry(lEntry, true); #else lEntry = new InputManagerEntry(); lEntry.Name = _ActionAlias; lEntry.PositiveButton = "joystick button 8"; // Left stick click lEntry.Gravity = 1; lEntry.Dead = 0.3f; lEntry.Sensitivity = 1; lEntry.Type = InputManagerEntryType.KEY_MOUSE_BUTTON; lEntry.Axis = 0; lEntry.JoyNum = 0; InputManagerHelper.AddEntry(lEntry, true); #endif } } /// <summary> /// Allow the constraint to render it's own GUI /// </summary> /// <returns>Reports if the object's value was changed</returns> public override bool OnInspectorGUI() { bool lIsDirty = false; if (EditorHelper.TextField("Action Alias", "Action alias that triggers the motion.", ActionAlias, mMotionController)) { lIsDirty = true; ActionAlias = EditorHelper.FieldStringValue; } GUILayout.Space(5f); if (EditorHelper.FloatField("Movement Speed", "Units per second to move. '0' means use root-motion if it exists. Another option is to set the speed values on the animator state nodes.", MovementSpeed, mMotionController)) { lIsDirty = true; MovementSpeed = EditorHelper.FieldFloatValue; } GUILayout.Space(5f); if (EditorHelper.BoolField("Rotate with Camera", "Determines if the actor rotates to face the direction of the camera.", RotateWithCamera, mMotionController)) { lIsDirty = true; RotateWithCamera = EditorHelper.FieldBoolValue; } if (EditorHelper.BoolField("Rotate with Input", "Determines if the actor rotates based on the input.", RotateWithInput, mMotionController)) { lIsDirty = true; RotateWithInput = EditorHelper.FieldBoolValue; } if (EditorHelper.FloatField("Rotation Speed", "Degrees per second to rotate.", RotationSpeed, mMotionController)) { lIsDirty = true; RotationSpeed = EditorHelper.FieldFloatValue; } GUILayout.Space(5f); if (EditorHelper.IntField("Smoothing Samples", "The more samples the smoother movement is, but the less responsive.", SmoothingSamples, mMotionController)) { lIsDirty = true; SmoothingSamples = EditorHelper.FieldIntValue; } return lIsDirty; } #endif #endregion #region Auto-Generated // ************************************ START AUTO GENERATED ************************************ /// <summary> /// These declarations go inside the class so you can test for which state /// and transitions are active. Testing hash values is much faster than strings. /// </summary> public static int STATE_IdlePose = -1; public static int STATE_MoveTree = -1; public static int TRANS_AnyState_MoveTree = -1; public static int TRANS_EntryState_MoveTree = -1; public static int TRANS_MoveTree_IdlePose = -1; /// <summary> /// Determines if we're using auto-generated code /// </summary> public override bool HasAutoGeneratedCode { get { return true; } } /// <summary> /// Used to determine if the actor is in one of the states for this motion /// </summary> /// <returns></returns> public override bool IsInMotionState { get { int lStateID = mMotionLayer._AnimatorStateID; int lTransitionID = mMotionLayer._AnimatorTransitionID; if (lStateID == STATE_IdlePose && lTransitionID == 0) { return true; } if (lStateID == STATE_MoveTree && lTransitionID == 0) { return true; } if (lTransitionID == TRANS_AnyState_MoveTree) { return true; } if (lTransitionID == TRANS_EntryState_MoveTree) { return true; } if (lTransitionID == TRANS_MoveTree_IdlePose) { return true; } return false; } } /// <summary> /// Used to determine if the actor is in one of the states for this motion /// </summary> /// <returns></returns> public override bool IsMotionState(int rStateID) { if (rStateID == STATE_IdlePose) { return true; } if (rStateID == STATE_MoveTree) { return true; } return false; } /// <summary> /// Used to determine if the actor is in one of the states for this motion /// </summary> /// <returns></returns> public override bool IsMotionState(int rStateID, int rTransitionID) { if (rStateID == STATE_IdlePose && rTransitionID == 0) { return true; } if (rStateID == STATE_MoveTree && rTransitionID == 0) { return true; } if (rTransitionID == TRANS_AnyState_MoveTree) { return true; } if (rTransitionID == TRANS_EntryState_MoveTree) { return true; } if (rTransitionID == TRANS_MoveTree_IdlePose) { return true; } return false; } /// <summary> /// Preprocess any animator data so the motion can use it later /// </summary> public override void LoadAnimatorData() { TRANS_AnyState_MoveTree = mMotionController.AddAnimatorName("AnyState -> Base Layer.Sneak v2-SM.Move Tree"); TRANS_EntryState_MoveTree = mMotionController.AddAnimatorName("Entry -> Base Layer.Sneak v2-SM.Move Tree"); STATE_IdlePose = mMotionController.AddAnimatorName("Base Layer.Sneak v2-SM.IdlePose"); STATE_MoveTree = mMotionController.AddAnimatorName("Base Layer.Sneak v2-SM.Move Tree"); TRANS_MoveTree_IdlePose = mMotionController.AddAnimatorName("Base Layer.Sneak v2-SM.Move Tree -> Base Layer.Sneak v2-SM.IdlePose"); } #if UNITY_EDITOR private AnimationClip m14306 = null; private AnimationClip m14708 = null; private AnimationClip m14710 = null; private AnimationClip m14712 = null; private AnimationClip m14716 = null; private AnimationClip m14714 = null; private AnimationClip m14718 = null; private AnimationClip m14704 = null; private AnimationClip m14706 = null; private AnimationClip m14702 = null; /// <summary> /// Creates the animator substate machine for this motion. /// </summary> protected override void CreateStateMachine() { // Grab the root sm for the layer UnityEditor.Animations.AnimatorStateMachine lRootStateMachine = _EditorAnimatorController.layers[mMotionLayer.AnimatorLayerIndex].stateMachine; UnityEditor.Animations.AnimatorStateMachine lSM_21500 = _EditorAnimatorController.layers[mMotionLayer.AnimatorLayerIndex].stateMachine; UnityEditor.Animations.AnimatorStateMachine lRootSubStateMachine = null; // If we find the sm with our name, remove it for (int i = 0; i < lRootStateMachine.stateMachines.Length; i++) { // Look for a sm with the matching name if (lRootStateMachine.stateMachines[i].stateMachine.name == _EditorAnimatorSMName) { lRootSubStateMachine = lRootStateMachine.stateMachines[i].stateMachine; // Allow the user to stop before we remove the sm if (!UnityEditor.EditorUtility.DisplayDialog("Motion Controller", _EditorAnimatorSMName + " already exists. Delete and recreate it?", "Yes", "No")) { return; } // Remove the sm //lRootStateMachine.RemoveStateMachine(lRootStateMachine.stateMachines[i].stateMachine); break; } } UnityEditor.Animations.AnimatorStateMachine lSM_21546 = lRootSubStateMachine; if (lSM_21546 != null) { for (int i = lSM_21546.entryTransitions.Length - 1; i >= 0; i--) { lSM_21546.RemoveEntryTransition(lSM_21546.entryTransitions[i]); } for (int i = lSM_21546.anyStateTransitions.Length - 1; i >= 0; i--) { lSM_21546.RemoveAnyStateTransition(lSM_21546.anyStateTransitions[i]); } for (int i = lSM_21546.states.Length - 1; i >= 0; i--) { lSM_21546.RemoveState(lSM_21546.states[i].state); } for (int i = lSM_21546.stateMachines.Length - 1; i >= 0; i--) { lSM_21546.RemoveStateMachine(lSM_21546.stateMachines[i].stateMachine); } } else { lSM_21546 = lSM_21500.AddStateMachine(_EditorAnimatorSMName, new Vector3(192, -696, 0)); } UnityEditor.Animations.AnimatorState lS_22652 = lSM_21546.AddState("IdlePose", new Vector3(504, 72, 0)); lS_22652.speed = 1f; lS_22652.motion = m14306; UnityEditor.Animations.AnimatorState lS_21796 = lSM_21546.AddState("Move Tree", new Vector3(264, 72, 0)); lS_21796.speed = 1f; UnityEditor.Animations.BlendTree lM_15642 = CreateBlendTree("Blend Tree", _EditorAnimatorController, mMotionLayer.AnimatorLayerIndex); lM_15642.blendType = UnityEditor.Animations.BlendTreeType.FreeformCartesian2D; lM_15642.blendParameter = "InputX"; lM_15642.blendParameterY = "InputY"; #if !(UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3) lM_15642.useAutomaticThresholds = true; #endif lM_15642.AddChild(m14708, new Vector2(0f, 0.7f)); UnityEditor.Animations.ChildMotion[] lM_15642_0_Children = lM_15642.children; lM_15642_0_Children[lM_15642_0_Children.Length - 1].mirror = false; lM_15642_0_Children[lM_15642_0_Children.Length - 1].timeScale = 1.2f; lM_15642.children = lM_15642_0_Children; lM_15642.AddChild(m14710, new Vector2(-0.7f, 0.7f)); UnityEditor.Animations.ChildMotion[] lM_15642_1_Children = lM_15642.children; lM_15642_1_Children[lM_15642_1_Children.Length - 1].mirror = false; lM_15642_1_Children[lM_15642_1_Children.Length - 1].timeScale = 1.1f; lM_15642.children = lM_15642_1_Children; lM_15642.AddChild(m14712, new Vector2(0.7f, 0.7f)); UnityEditor.Animations.ChildMotion[] lM_15642_2_Children = lM_15642.children; lM_15642_2_Children[lM_15642_2_Children.Length - 1].mirror = false; lM_15642_2_Children[lM_15642_2_Children.Length - 1].timeScale = 1.1f; lM_15642.children = lM_15642_2_Children; lM_15642.AddChild(m14716, new Vector2(-0.7f, 0f)); UnityEditor.Animations.ChildMotion[] lM_15642_3_Children = lM_15642.children; lM_15642_3_Children[lM_15642_3_Children.Length - 1].mirror = false; lM_15642_3_Children[lM_15642_3_Children.Length - 1].timeScale = 1.1f; lM_15642.children = lM_15642_3_Children; lM_15642.AddChild(m14714, new Vector2(0f, 0f)); UnityEditor.Animations.ChildMotion[] lM_15642_4_Children = lM_15642.children; lM_15642_4_Children[lM_15642_4_Children.Length - 1].mirror = false; lM_15642_4_Children[lM_15642_4_Children.Length - 1].timeScale = 1.3f; lM_15642.children = lM_15642_4_Children; lM_15642.AddChild(m14718, new Vector2(0.7f, 0f)); UnityEditor.Animations.ChildMotion[] lM_15642_5_Children = lM_15642.children; lM_15642_5_Children[lM_15642_5_Children.Length - 1].mirror = false; lM_15642_5_Children[lM_15642_5_Children.Length - 1].timeScale = 1.5f; lM_15642.children = lM_15642_5_Children; lM_15642.AddChild(m14704, new Vector2(-0.7f, -0.7f)); UnityEditor.Animations.ChildMotion[] lM_15642_6_Children = lM_15642.children; lM_15642_6_Children[lM_15642_6_Children.Length - 1].mirror = false; lM_15642_6_Children[lM_15642_6_Children.Length - 1].timeScale = 1.5f; lM_15642.children = lM_15642_6_Children; lM_15642.AddChild(m14706, new Vector2(0.7f, -0.7f)); UnityEditor.Animations.ChildMotion[] lM_15642_7_Children = lM_15642.children; lM_15642_7_Children[lM_15642_7_Children.Length - 1].mirror = false; lM_15642_7_Children[lM_15642_7_Children.Length - 1].timeScale = 1.5f; lM_15642.children = lM_15642_7_Children; lM_15642.AddChild(m14702, new Vector2(0f, -0.7f)); UnityEditor.Animations.ChildMotion[] lM_15642_8_Children = lM_15642.children; lM_15642_8_Children[lM_15642_8_Children.Length - 1].mirror = false; lM_15642_8_Children[lM_15642_8_Children.Length - 1].timeScale = 1.5f; lM_15642.children = lM_15642_8_Children; lS_21796.motion = lM_15642; // Create the transition from the any state. Note that 'AnyState' transitions have to be added to the root UnityEditor.Animations.AnimatorStateTransition lT_21654 = lRootStateMachine.AddAnyStateTransition(lS_21796); lT_21654.hasExitTime = false; lT_21654.hasFixedDuration = true; lT_21654.exitTime = 0.9f; lT_21654.duration = 0.2f; lT_21654.offset = 0f; lT_21654.mute = false; lT_21654.solo = false; lT_21654.canTransitionToSelf = true; lT_21654.interruptionSource = (UnityEditor.Animations.TransitionInterruptionSource)0; lT_21654.AddCondition(UnityEditor.Animations.AnimatorConditionMode.Equals, 620f, "L0MotionPhase"); UnityEditor.Animations.AnimatorStateTransition lT_22654 = lS_21796.AddTransition(lS_22652); lT_22654.hasExitTime = false; lT_22654.hasFixedDuration = true; lT_22654.exitTime = 0.9f; lT_22654.duration = 0.2f; lT_22654.offset = 0f; lT_22654.mute = false; lT_22654.solo = false; lT_22654.canTransitionToSelf = true; lT_22654.interruptionSource = (UnityEditor.Animations.TransitionInterruptionSource)0; lT_22654.AddCondition(UnityEditor.Animations.AnimatorConditionMode.Equals, 610f, "L0MotionPhase"); } /// <summary> /// Gathers the animations so we can use them when creating the sub-state machine. /// </summary> public override void FindAnimations() { m14306 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Idling/unity_Idle_IdleToIdlesR.fbx/IdlePose.anim", "IdlePose"); m14708 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakForward.anim", "SneakForward"); m14710 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakForwardLeft.anim", "SneakForwardLeft"); m14712 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakForwardRight.anim", "SneakForwardRight"); m14716 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakLeft.anim", "SneakLeft"); m14714 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakIdle.anim", "SneakIdle"); m14718 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakRight.anim", "SneakRight"); m14704 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakBackwardLeft.anim", "SneakBackwardLeft"); m14706 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakBackwardRight.anim", "SneakBackwardRight"); m14702 = FindAnimationClip("Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakBackward.anim", "SneakBackward"); // Add the remaining functionality base.FindAnimations(); } /// <summary> /// Used to show the settings that allow us to generate the animator setup. /// </summary> public override void OnSettingsGUI() { UnityEditor.EditorGUILayout.IntField(new GUIContent("Phase ID", "Phase ID used to transition to the state."), PHASE_START); m14306 = CreateAnimationField("IdlePose", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Idling/unity_Idle_IdleToIdlesR.fbx/IdlePose.anim", "IdlePose", m14306); m14708 = CreateAnimationField("Move Tree.SneakForward", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakForward.anim", "SneakForward", m14708); m14710 = CreateAnimationField("Move Tree.SneakForwardLeft", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakForwardLeft.anim", "SneakForwardLeft", m14710); m14712 = CreateAnimationField("Move Tree.SneakForwardRight", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakForwardRight.anim", "SneakForwardRight", m14712); m14716 = CreateAnimationField("Move Tree.SneakLeft", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakLeft.anim", "SneakLeft", m14716); m14714 = CreateAnimationField("Move Tree.SneakIdle", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakIdle.anim", "SneakIdle", m14714); m14718 = CreateAnimationField("Move Tree.SneakRight", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakRight.anim", "SneakRight", m14718); m14704 = CreateAnimationField("Move Tree.SneakBackwardLeft", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakBackwardLeft.anim", "SneakBackwardLeft", m14704); m14706 = CreateAnimationField("Move Tree.SneakBackwardRight", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakBackwardRight.anim", "SneakBackwardRight", m14706); m14702 = CreateAnimationField("Move Tree.SneakBackward", "Assets/ootii/Assets/MotionController/Content/Animations/Humanoid/Sneaking/Unity_Sneak.fbx/SneakBackward.anim", "SneakBackward", m14702); // Add the remaining functionality base.OnSettingsGUI(); } #endif // ************************************ END AUTO GENERATED ************************************ #endregion } }
fe482bf01a74a736abde01ea276afb0e
{ "intermediate": 0.5043640732765198, "beginner": 0.3039897680282593, "expert": 0.19164617359638214 }
37,791
ml-agents 的teamid怎么用
908f087d41cdec90aec212fc45f0bb73
{ "intermediate": 0.30955591797828674, "beginner": 0.26158615946769714, "expert": 0.4288578927516937 }
37,792
What does an etherium orc20 address look like
a7a8194921591654d192f1ce1b6f3a50
{ "intermediate": 0.3667448163032532, "beginner": 0.21118289232254028, "expert": 0.42207226157188416 }
37,793
i'm trying to make a chrome extension that prints hello next to h1 and then prints to console the number of words, why doesn't this work? const article = document.querySelector("article"); // `document.querySelector` may return null if the selector doesn't match anything. if (article) { const text = article.textContent; const wordMatchRegExp = /[^\s]+/g; // Regular expression const words = text.matchAll(wordMatchRegExp); const wordCount = Array.from(words).length; // Convert iterator to array and get length console.log(`Number of words: ${wordCount}`); const readingTime = Math.round(wordCount / 200); const helloMessage = document.createElement("p"); helloMessage.classList.add("color-secondary-text", "type--caption"); helloMessage.textContent = "Hello"; const heading = article.querySelector("h1"); const date = article.querySelector("time")?.parentNode; (heading ?? date).insertAdjacentElement("afterend", helloMessage); }
7858c3eaa7799778fc8e0b3fe488a5bd
{ "intermediate": 0.5232394933700562, "beginner": 0.3135627210140228, "expert": 0.1631978154182434 }
37,794
Give the characteristics of the warring countries during Civil War in Columbia in 1854: Denotes the first and second sides of the conflict. - [AS1] Army size of first country; - [AS2] Army size of second country; - [GL1] Geographical location of first country (check one) (number 0-7) 0. Greenland 1. North America 2. South America 3. Europe 4. Asia 5. Middle East 6. Africa 7. Australia - [GL2] Geographical location of second country (also one note) - [RL1] Religion of first country. (check one) (number 0-11) 0. Catholicism 1. Protestantism 2. Orthodoxy 3. Sunni Islam 4. Shia Islam 5. Hinduism 6. Buddhism 7. Judaism 8. Religions of Africa 9. Taoism 10. Confucianism 11. Unknown or atheism - [RL2] Religion of second country (same as above) - [List of PH1{n}, where n - number 0-6] Political characteristics of first country. (check those that apply) (0 - no, 1 - yes) 0. [PH10] Monarchy 1. [PH11] Republic 2. [PH12] Unitary state 3. [PH13] Federation 4. [PH14] Totalitarianism 5. [PH15] Authoritarianism 6. [PH16] Democracy - [List of PH2{n}] Political features of second country (same as above) - [ED1] Education level of the population of first country. Percent float value from 0 to 1 - [ED2] Education level of the population of second country. Percent float value from 0 to 1 - [WF1] Wealth of fossil resources of first country. Percent float value from 0 to 1 - [WF2] Fossil resource wealth of second country Percent float value from 0 to 1 - [MR1] Percentage of first country's maritime border. Float value from 0 to 1 (0% - landlocked, 100% - island country) - [MR2] Percentage of maritime border of second country. - [AT1] Average annual air temperature first country. Float value from 0 to 1, where 0= -30 celsius degrees, 1=50 celsius degrees - [AT2] Average annual air temperature of second country. Outcome of the conflict (check one): - [V1] = Victory of the first side (0 - no, 1 - yes) - [V2] = Victory of the second side (0 - no, 1 - yes) - [DR] = Draw (0 - no, 1 - yes) - [CSF] = Ceasefire (0 - no, 1 - yes) - [QUO] = Status quo (0 - no, 1 - yes) - [CFT] Duration of the conflict in months (number of months) All data about the country helps in times of armed conflict. If some data is not exactly disclosed, try to find the maximum possible and plausible, for example, analyze neighboring countries and the situation in the world at the time of the military conflict. Try to keep the data as consistent as possible with historical information. The result must be presented as a sequence of 34 numeric values separated by a space. Format: [AS1] [AS2] [GL1] [GL2] [RL1] [RL2] [PH10] [PH11] [PH12] [PH13] [PH14] [PH15] [PH16] [PH20] [PH21] [PH22] [PH23] [PH24] [PH25] [PH26] [ED1] [ED2] [WF1] [WF2] [MR1] [MR2] [AT1] [AT2] [V1] [V2] [DR] [CSF] [QUO] [CFT]
4523e255a7bbb41929c5072173ec89d0
{ "intermediate": 0.3414610028266907, "beginner": 0.3968229293823242, "expert": 0.2617160677909851 }
37,795
Give the characteristics of the warring countries during Civil War in Columbia in 1854: Denotes the first and second sides of the conflict. - [AS1] Army size of first country; - [AS2] Army size of second country; - [GL1] Geographical location of first country (check one) (number 0-7) 0. Greenland 1. North America 2. South America 3. Europe 4. Asia 5. Middle East 6. Africa 7. Australia - [GL2] Geographical location of second country (also one note) - [RL1] Religion of first country. (check one) (number 0-11) 0. Catholicism 1. Protestantism 2. Orthodoxy 3. Sunni Islam 4. Shia Islam 5. Hinduism 6. Buddhism 7. Judaism 8. Religions of Africa 9. Taoism 10. Confucianism 11. Unknown or atheism - [RL2] Religion of second country (same as above) - [List of PH1{n}, where n - number 0-6] Political characteristics of first country. (check those that apply) (0 - no, 1 - yes) 0. [PH10] Monarchy 1. [PH11] Republic 2. [PH12] Unitary state 3. [PH13] Federation 4. [PH14] Totalitarianism 5. [PH15] Authoritarianism 6. [PH16] Democracy - [List of PH2{n}] Political features of second country (same as above) - [ED1] Education level of the population of first country. Percent float value from 0 to 1 - [ED2] Education level of the population of second country. Percent float value from 0 to 1 - [WF1] Wealth of fossil resources of first country. Percent float value from 0 to 1 - [WF2] Fossil resource wealth of second country Percent float value from 0 to 1 - [MR1] Percentage of first country’s maritime border. Float value from 0 to 1 (0% - landlocked, 100% - island country) - [MR2] Percentage of maritime border of second country. - [AT1] Average annual air temperature first country. Float value from 0 to 1, where 0= -30 celsius degrees, 1=50 celsius degrees - [AT2] Average annual air temperature of second country. Outcome of the conflict (check one): - [V1] = Victory of the first side (0 - no, 1 - yes) - [V2] = Victory of the second side (0 - no, 1 - yes) - [DR] = Draw (0 - no, 1 - yes) - [CSF] = Ceasefire (0 - no, 1 - yes) - [QUO] = Status quo (0 - no, 1 - yes) - [CFT] Duration of the conflict in months (number of months) All data about the country helps in times of armed conflict. If some data is not exactly disclosed, try to find the maximum possible and plausible, for example, analyze neighboring countries and the situation in the world at the time of the military conflict. Try to keep the data as consistent as possible with historical information. The result must be presented as a sequence of 34 numeric values separated by a space. Format: [AS1] [AS2] [GL1] [GL2] [RL1] [RL2] [PH10] [PH11] [PH12] [PH13] [PH14] [PH15] [PH16] [PH20] [PH21] [PH22] [PH23] [PH24] [PH25] [PH26] [ED1] [ED2] [WF1] [WF2] [MR1] [MR2] [AT1] [AT2] [V1] [V2] [DR] [CSF] [QUO] [CFT]
efcd0537a33fafe3c7e67ac6f07387c7
{ "intermediate": 0.3243172764778137, "beginner": 0.3008924722671509, "expert": 0.3747902810573578 }
37,796
Why this below code is giving me this error: “Expected expression” Code: import os from time import sleep from flask import Flask, request, jsonify from openai import OpenAI from flask_cors import CORS, cross_origin from dotenv import load_dotenv import requests from io import BytesIO import json load_dotenv() OPENAI_API_KEY = os.getenv(“OPENAI_API_KEY”) app = Flask(name) CORS(app, supports_credentials=True) # Init client client = OpenAI(api_key=OPENAI_API_KEY) def read_config(): with open(‘config.json’, ‘r’) as config_file: config = json.load(config_file) return config @app.route(“/test”, methods=[“POST”]) @cross_origin(supports_credentials=True) def create(): config = read_config() data = request.json topic = data.get(“topic”, “”) assistant = client.beta.assistants.create( name=“assistant”, instructions=“You are a helpful assistant”, model=“gpt-4-1106-preview”, ) thread = client.beta.threads.create() prompt = config.get(f’prompt1',“topic”) client.beta.threads.messages.create( thread_id=thread.id, role=“user”, content=prompt ) run = client.beta.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id ) # Check if the Run requires action while True: run_status = client.beta.threads.runs.retrieve( thread_id=thread.id, run_id=run.id ) print(f"Run status: {run_status.status}“) if run_status.status == “completed”: break sleep(1) messages = client.beta.threads.messages.list(thread_id=thread.id) response = messages.data[0].content[0].text.value print(f"Assistant response: {response}”) return jsonify({“assistant_id”: assistant.id, “goals”: response}) if name == “main”: app.run(host=“0.0.0.0”, port=8080)
07f2e5fdcaff4d9018597aee6c217079
{ "intermediate": 0.5304986238479614, "beginner": 0.38148918747901917, "expert": 0.08801225572824478 }
37,797
def create_card(recipient, years, closing, sender): # Set up the background and create text elements stage.set_background("sky_13e") yrs = codesters.Text(years + " years!!", 0, 200) yrs.set_size(2) text1 = codesters.Text("Dear " + recipient + ",", 0, 100) text2 = codesters.Text("Hope your special day is filled with joy!", 0, 50) text3 = codesters.Text(closing + ",", 0, 0) text4 = codesters.Text("Best wishes,", 0, -50) # Create a sprite (e.g., penguin) and get user input sprite = codesters.Sprite("penguin") sprite.set_size(0.5) sprite.set_speed(2) # Ask for user input recipient = sprite.ask("What is the name of the birthday person?") years = sprite.ask("How old will this person be?") closing = sprite.ask("How do you want to close your card? (love, from, sincerely, etc.)") sender = sprite.ask("What is your name?") # Hide the sprite after obtaining user input sprite.hide() # Display the greeting card stage.wait(1) # Wait for a moment before displaying the card # Call the function with user input create_card("", "", "", "") # 1) Create a function that takes parameters for a greeting card - Must have a background with at least 2 sprites - Must have at least three different text parameters # 2) Ask for user input to get values for the function parameters - Ask for receivers names - Ask for giver's name - Third is your choice # 3) Pass the user input variable into the function in the call line **** Extra credit, use parameters and ask input to dictate how many sprites show on the card. **** Ask for the type of card to receive (at least two different card choices and all previous requirements)
390e95bff8a9a286fd7a16797ffc4795
{ "intermediate": 0.4103005826473236, "beginner": 0.2826741635799408, "expert": 0.3070251941680908 }
37,798
I have a spreadsheet in which is recorded from row 2 downwards , row by row, clients bookings of Space required. Column A is for the Dates of the booking Column B is for the persons name who made the booking Column C is for the Space required Column D is for the Start Time of the booking for the Space required Column E is for the End Time of the booking for the Space required Column F is for the name of the Client who requested the booking Column G is for Notes partaining to the booking In column A, are the Dates of the bookings and they are arranged in descending order. In column A, I can also have multiple rows of the same Date for different areas of Space required. In column C, is the Space required. In column C, I can have multiple rows of the same Space for different Times of the same Date the Space is required. In column C, if the row value is 'nb', there is no booking for that specific Date recorded in the same row at column A. In column D, are the Start Times for the required use of the Space as recorded in the same row at column C. In column D, I can have multiple rows of the same Start Times for the same Dates, but which will be for different Space requirements of the same Date. If the Start Time in column C is 12:00:00 AM, there is no booking for that Date recorded in the same row at column A. In column E, are the End Times for the required use of the Space as recorded in the same row at column C. In column E, I can have multiple rows of the same End Times for the same Dates, but which will be for different Space requirements of the same Date. I need a VBA code that will determine the latest End Time for each date or multiple entries of the same date, and append to column V the value 'Close' on the same row where the latest End Time is found.
045067a33095febf77f9ebd36c796ec7
{ "intermediate": 0.4330638647079468, "beginner": 0.2394144982099533, "expert": 0.32752159237861633 }
37,799
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; contract Ultimate FaceOff { using MessageHashUtils for bytes32; using ECDSA for bytes32; using Strings for uint256; error NoFaceNoPlace(); // Mapping to store addresses mapping (address ⇒ bool) public winners; // Function to save an address if the signature is valid function participate (bytes memory signature) public { // Construct the message from msg.sender and a fixed string bytes32 message = keccak256(abi.encodePacked(msg.sender, "calyptus")); bytes32 ethSigned Message = message.toEthSignedMessageHash(); // Recover the signer address from the signature address recoveredAddress = ethSignedMessage.recover(signature); // Check if the address starts with the specified prefix if (!startsWith(toAsciiString (recovered Address), "Oxface")) { revert NoFaceNoPlace(); } // Save the msg.sender address in the mapping winners [msg.sender] = true; } // Other internal functions // Check out full contract on Etherscan Sepolia } Epic Face-Off Alert! To emerge victorious, you have to get your address in the winner mapping and share your address in the comments 💻 Platform: Sepolia Smart Contract Address: 0x2e285201e2bc6b5aa17c5829e6d80d5f6022d809
c13aba0bf2d61241bb950b87933eec94
{ "intermediate": 0.41412386298179626, "beginner": 0.2975565195083618, "expert": 0.2883197069168091 }
37,800
i need road map for dsa in python dictionary format like {"topic":['element1','element 2','element 3']}
5d3a32d02b9761f93161f9c50049bcd5
{ "intermediate": 0.3429062068462372, "beginner": 0.12928679585456848, "expert": 0.5278071165084839 }
37,801
in this javascript for leaflet.js the user can keep clicking on the map to add new markers. When a new marker is added I want to remove the previous marker from the map - var userMarker = L.marker(e.latlng).addTo(map); userMarkers.push(userMarker.getLatLng());
47389279e191fcc699a4aab9cb23e192
{ "intermediate": 0.369038850069046, "beginner": 0.33327716588974, "expert": 0.297683984041214 }
37,802
hi
3858bbeafa5e0682aa50964d136500c3
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,803
hello
f1ebf77b78c84c67833ade0bf3b81690
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
37,804
improve this code let [n, m, q, ..]: [i32] = lines .next() .unwrap() .split(' ') .map(|s| s.trim().parse().unwrap()) .collect::<Vec<_>>()[..] else { unreachable!() };
55dcdef9155e513438535fe35fc75b80
{ "intermediate": 0.26753297448158264, "beginner": 0.509182333946228, "expert": 0.22328472137451172 }
37,805
improve this code let [n, m, q, ..]: [i32] = lines .next() .unwrap() .split(' ') .map(|s| s.trim().parse().unwrap()) .collect::<Vec<_>>()[..] else { unreachable!() };
87ea8bedda8b9664c04dc7cb1e4ccaea
{ "intermediate": 0.28349894285202026, "beginner": 0.5047945976257324, "expert": 0.21170645952224731 }
37,806
how does union find help solving graph based problems
2f4e5c1c71fdcea748f3498d0b30f9d7
{ "intermediate": 0.3168516159057617, "beginner": 0.28358590602874756, "expert": 0.39956244826316833 }
37,807
import torch import torch.nn as nn import torch.nn.functional as F from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm # Define the Expert module class Expert(nn.Module): def __init__(self, input_dim, hidden_dim): super(Expert, self).__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.activation = nn.ReLU() self.fc2 = nn.Linear(hidden_dim, input_dim) def forward(self, x): x = self.activation(self.fc1(x)) x = self.fc2(x) return x # Define the MoELayer module class MoELayer(nn.Module): def __init__(self, num_experts, input_dim, hidden_dim): super(MoELayer, self).__init__() self.experts = nn.ModuleList([Expert(input_dim, hidden_dim) for _ in range(num_experts)]) self.gate = nn.Linear(input_dim, num_experts) def forward(self, x): gating_distribution = F.softmax(self.gate(x), dim=1) expert_outputs = torch.stack([expert(x) for expert in self.experts], dim=1) output = torch.einsum('bi,bij->bj', gating_distribution, expert_outputs) # This efficiently computes the weighted sum of expert outputs return output # Define the SelectionMechanism module class SelectionMechanism(nn.Module): def __init__(self, input_dim, state_dim): super(SelectionMechanism, self).__init__() self.selection_layer = nn.Linear(input_dim + state_dim, state_dim) def forward(self, state, u): # Ensure both state and u have a batch dimension (state already has it) combined = torch.cat((state, u), dim=1) new_state = self.selection_layer(combined) return new_state # Define the StateSpaceMamba module class StateSpaceMamba(nn.Module): def __init__(self, input_dim, state_dim, num_experts, hidden_dim): super(StateSpaceMamba, self).__init__() self.state_dim = state_dim self.state = nn.Parameter(torch.zeros(1, state_dim)) self.input_layer = nn.Linear(input_dim, state_dim) self.selection_mechanism = SelectionMechanism(input_dim, state_dim) self.moe_layer = MoELayer(num_experts, state_dim, hidden_dim) def forward(self, input_sequence): batch_size = input_sequence.size(0) # Assuming the input is [batch_size, seq_length, input_dim] outputs = [] state = torch.zeros(batch_size, self.state_dim).to(input_sequence.device) # Initialize state for the current batch # Debugging: print shapes before loop print("input_sequence shape at forward entry:", input_sequence.shape) print("Initial state shape at forward entry:", state.shape) for u in input_sequence.split(1, dim=1): # Corrected: split along dimension 1 (time/sequence) u = u.squeeze(1) # Corrected: Remove the sequence dimension which is now dim 1 due to split # Debugging: Print shapes inside loop print("Input shape (u) at loop:", u.shape) state = self.selection_mechanism(state, u) print("State shape after selection mechanism:", state.shape) u_projected = self.input_layer(u) print("Input projection (u_projected) shape:", u_projected.shape) output = self.moe_layer(u_projected + state) print("Output shape after MoE layer:", output.shape) outputs.append(output) # Debugging: print shape of individual outputs and final stacked output print("Individual outputs shapes:", [o.shape for o in outputs]) output_tensor = torch.stack(outputs, dim=1) # Corrected: stack along dimension 1 (time/sequence) print("Stacked output shape:", output_tensor.shape) return output_tensor # Load the dataset try: print("Loading dataset...") with open("C:/Users/Dell-PC/Desktop/The-Physics-Dataset.txt", "r") as f: text = f.read() except FileNotFoundError: print("Error: Dataset file not found.") exit(1) # Tokenize the text try: print("Tokenizing text...") tokenizer = get_tokenizer("basic_english") tokens = tokenizer(text.lower()) except Exception as e: print("Error occurred during tokenization:", str(e)) exit(1) # Build the vocabulary try: print("Building vocabulary...") vocab = build_vocab_from_iterator([tokens], specials=["<unk>", "<pad>", "<sos>", "<eos>"]) vocab.set_default_index(vocab["<unk>"]) numericalized_tokens = [vocab["<sos>"]] + [vocab[token] for token in tokens] + [vocab["<eos>"]] vocab_size = len(vocab) print("Vocabulary size:", vocab_size) except Exception as e: print("Error occurred during vocabulary building:", str(e)) exit(1) # Prepare the input sequence batch_size = 24 seq_length = 12 # This is the “token” size we observed in the debug outputs vocab_size = len(vocab) num_batches = (len(numericalized_tokens) - 1) // (batch_size * seq_length) if len(numericalized_tokens) < (batch_size * seq_length): print(f"Error: Dataset is too small for the chosen batch size and sequence length. Tokens available: {len(numericalized_tokens)}") exit(1) # Calculate the number of batches and ensure it’s not zero if num_batches == 0: print(f"Error: Number of batches is zero. Check if your dataset is large enough or consider reducing batch size/sequence length.") exit(1) numericalized_tokens = numericalized_tokens[:num_batches * batch_size * seq_length] input_sequence = torch.tensor(numericalized_tokens).view(-1, batch_size, seq_length) input_sequence = input_sequence.float() # Ensure input_sequence is of type float print("input_sequence shape:", input_sequence.shape) print("input_sequence dimension:", input_sequence.dim()) # Define the model using actual input_dim which corresponds to seq_length num_experts = 4 state_dim = 128 hidden_dim = 128 input_dim = seq_length # Corrected to use seq_length instead of vocab_size model = StateSpaceMamba(input_dim, state_dim, num_experts, hidden_dim) learning_rate = 0.001 print("model state shape:", model.state.shape) print("model state dimension:", model.state.dim()) # Training loop try: print("Training model…") def train(model, data, num_batches, batch_size, seq_length, output_features, epochs): model.train() loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) loss_history = [] for epoch in tqdm(range(epochs)): total_loss = 0.0 for i in range(num_batches): batch_start_index = i * batch_size inputs = data[batch_start_index:batch_start_index + batch_size, :-1] # Exclude last column for inputs targets = data[batch_start_index:batch_start_index + batch_size, 1:] # Exclude first column for targets targets = targets.reshape(-1) # Flatten the targets to [batch_size * seq_length] optimizer.zero_grad() outputs = model(inputs) outputs = outputs.reshape(-1, output_features) # [batch_size * seq_length, output_features] loss = loss_fn(outputs, targets) loss.backward() optimizer.step() total_loss += loss.item() epoch_loss = total_loss / (num_batches * batch_size * seq_length) loss_history.append(epoch_loss) print(f"Epoch {epoch}, Loss: {epoch_loss}") return loss_history output_features = vocab_size # Make sure output_features matches the number of classes for prediction epochs = 10 loss_history = train(model, input_sequence, num_batches, batch_size, seq_length, output_features, epochs) # Plot loss history plt.plot(loss_history) plt.xlabel("Epochs") plt.ylabel("Loss") plt.title("Training Loss History") plt.show() except Exception as e: print("Error occurred during training:", str(e)) exit(1) # Generate function try: print("Generating text...") def generate(model, start_seq, length, temperature=0.8): model.eval() state = model.state numericalized_start = torch.tensor([vocab[token] for token in tokenizer(start_seq.lower())], dtype=torch.long).unsqueeze(0) input_seq = numericalized_start generated_sequence = [] for i in range(length): output = model(input_seq) # Sample from the network as a multinomial distribution output_prob = F.softmax(output[:, -1] / temperature, dim=-1).detach() predicted_index = torch.multinomial(output_prob, 1).item() generated_sequence.append(predicted_index) input_seq = torch.cat((input_seq, torch.tensor([[predicted_index]])), dim=1) return " ".join(vocab.lookup_tokens(generated_sequence)) # Generating a sample start_seq = "The fundamental concepts of physics" # Start of sequence to begin text generation generated_text = generate(model, start_seq, length=100) # Length of generated sequence print(generated_text) except Exception as e: print("Error occurred during text generation:", str(e)) exit(1)
55649085c505f7d314c5f0a5c863822f
{ "intermediate": 0.30583521723747253, "beginner": 0.40679270029067993, "expert": 0.28737205266952515 }
37,808
class Example: """ A example node Class methods ------------- INPUT_TYPES (dict): Tell the main program input parameters of nodes. Attributes ---------- RETURN_TYPES (`tuple`): The type of each element in the output tulple. RETURN_NAMES (`tuple`): Optional: The name of each output in the output tulple. FUNCTION (`str`): The name of the entry-point method. For example, if `FUNCTION = "execute"` then it will run Example().execute() OUTPUT_NODE ([`bool`]): If this node is an output node that outputs a result/image from the graph. The SaveImage node is an example. The backend iterates on these output nodes and tries to execute all their parents if their parent graph is properly connected. Assumed to be False if not present. CATEGORY (`str`): The category the node should appear in the UI. execute(s) -> tuple || None: The entry point method. The name of this method must be the same as the value of property `FUNCTION`. For example, if `FUNCTION = "execute"` then this method's name must be `execute`, if `FUNCTION = "foo"` then it must be `foo`. """ def __init__(self): pass @classmethod def INPUT_TYPES(s): """ Return a dictionary which contains config for all input fields. Some types (string): "MODEL", "VAE", "CLIP", "CONDITIONING", "LATENT", "IMAGE", "INT", "STRING", "FLOAT". Input types "INT", "STRING" or "FLOAT" are special values for fields on the node. The type can be a list for selection. Returns: `dict`: - Key input_fields_group (`string`): Can be either required, hidden or optional. A node class must have property `required` - Value input_fields (`dict`): Contains input fields config: * Key field_name (`string`): Name of a entry-point method's argument * Value field_config (`tuple`): + First value is a string indicate the type of field or a list for selection. + Secound value is a config for type "INT", "STRING" or "FLOAT". """ return { "required": { "image": ("IMAGE",), "int_field": ("INT", { "default": 0, "min": 0, #Minimum value "max": 4096, #Maximum value "step": 64, #Slider's step "display": "number" # Cosmetic only: display as "number" or "slider" }), "float_field": ("FLOAT", { "default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "round": 0.001, #The value represeting the precision to round to, will be set to the step value by default. Can be set to False to disable rounding. "display": "number"}), "print_to_screen": (["enable", "disable"],), "string_field": ("STRING", { "multiline": False, #True if you want the field to look like the one on the ClipTextEncode node "default": "Hello World!" }), }, } RETURN_TYPES = ("IMAGE",) #RETURN_NAMES = ("image_output_name",) FUNCTION = "test" #OUTPUT_NODE = False CATEGORY = "Example" def test(self, image, string_field, int_field, float_field, print_to_screen): if print_to_screen == "enable": print(f"""Your input contains: string_field aka input text: {string_field} int_field: {int_field} float_field: {float_field} """) #do some processing on the image, in this example I just invert it image = 1.0 - image return (image,) # A dictionary that contains all nodes you want to export with their names # NOTE: names should be globally unique NODE_CLASS_MAPPINGS = { "Example": Example } # A dictionary that contains the friendly/humanly readable titles for the nodes NODE_DISPLAY_NAME_MAPPINGS = { "Example": "Example Node" } 这个是comfyui的 custom node 的 示例代码,能帮我改写出一个excel文件。 load 和。viewer 的代码吗?
d11152304f6d73e0230731f0c5a0604f
{ "intermediate": 0.3154536485671997, "beginner": 0.4873485863208771, "expert": 0.1971977800130844 }
37,809
hi
f45d289c77c71f7706121ce3b4b442dd
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,810
Using quasar, how do I make a reveal panel (aria-expanded) that's accessible
74bb28be126bc43c0dcb55f941e2ac1b
{ "intermediate": 0.364148885011673, "beginner": 0.21406418085098267, "expert": 0.421786904335022 }
37,811
Using quasar, how do I make a reveal dropdown (aria-expanded) that's accessible
e71626d8202c657931b1d83dd8ffee09
{ "intermediate": 0.37453052401542664, "beginner": 0.15492597222328186, "expert": 0.47054344415664673 }
37,812
In FORTH Reverse a string supplied as (addr length).
012956ae9820e17c746c586a83a7b19b
{ "intermediate": 0.3619292378425598, "beginner": 0.3406812250614166, "expert": 0.2973894774913788 }
37,813
Using quasar, how do I make a reveal dropdown (aria-expanded) that's accessible
ee44643c1078ae62f9188ff33ffe8282
{ "intermediate": 0.37453052401542664, "beginner": 0.15492597222328186, "expert": 0.47054344415664673 }
37,814
hi
ddd384578c24dccb3a9e04908e81bb58
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,815
who are you
9f4809dd9fab75ac2d74bbe81bbeb94d
{ "intermediate": 0.45451608300209045, "beginner": 0.2491701990365982, "expert": 0.29631373286247253 }
37,816
How to create tensorflow model to resolve MEP clashes in Revit using similar dataset : NameClash17Distance-0.070mDescriptionHardStatusNewClash Point530006.387m, 183829.066m, 38.183mGrid LocationF-9 : Level 02Date Created2023/11/19 13:33 Item 1 Element ID2398559LayerLevel 02PathFile ->Project 02_TP01.nwd ->Project 02_ME_TP01.nwc ->Level 02 ->Ducts ->Rectangular Duct ->M_Duct_Rectangular_RectangularDW144SquareBendFlanged_KS1 ->Rectangular Duct ->HM_Supply AirItem NameHM_Supply AirItem TypeSolid Item 2 Element ID2485763LayerLevel 02PathFile ->Project 02_TP01.nwd ->Project 02_PL_TP01.nwc ->Level 02 ->Pipe Insulations ->Pipe Insulation ->M_PipeInsulation_Type2_KS1 ->Pipe Insulation ->CHW FlowItem NameCHW FlowItem TypeSolid
cc3a99e00eada327f48b44f398b44c1c
{ "intermediate": 0.2590504586696625, "beginner": 0.18977533280849457, "expert": 0.5511741638183594 }
37,817
hi
2b2a63647d2cd13554f80d46f7200948
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,818
In C write a library to minipulate rational fractions of the form a/b, and perform arithmetical and comparison operations on them.
cac41a3d770192f1b17e85fe558f3ccc
{ "intermediate": 0.6837568879127502, "beginner": 0.06666043400764465, "expert": 0.2495826631784439 }
37,819
In C write a version of the 'Animals' guessing game, you can use a temporary file to hold the data tree generated if desired?
d80481f8acd0fb412ea7ce4c77b24979
{ "intermediate": 0.41521862149238586, "beginner": 0.16954591870307922, "expert": 0.4152354598045349 }
37,820
In Pascal - write a program to convert a currency value into a set of notes and coins, based on a defined set of values such as $20,$10,$5,$1, 50c, 20c, 10c, 5c, 2c . Keep track of amounts in and out of a nominal till at the same time.
aec89a9eee179ed498eddb65c83521bd
{ "intermediate": 0.36836010217666626, "beginner": 0.25518175959587097, "expert": 0.37645816802978516 }
37,821
Hello , I am a data science student and I want to create a dataset on Banking Customer Acquisition, but I'm not getting all data in one single dataset, which is why I would need to combine multiple datasets into one single dataset, give me some solutions on how I can combine multiple datasets into one
edc72b88d36f9743e6c225415c546f68
{ "intermediate": 0.3201834559440613, "beginner": 0.1923331320285797, "expert": 0.4874834418296814 }
37,822
Generate PI in Z80 assembler. Use appropriate series expansions as required.
3292d49bedc4a4ff8dc6273876f8a453
{ "intermediate": 0.40299567580223083, "beginner": 0.2292184680700302, "expert": 0.36778587102890015 }
37,823
translate to rust ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> q; for (int i = 0; i < n; i++){ cin >> A[i]; dist[i] = vector<int>(m, 1e9); for (int j = 0; j < m; j++){ if (A[i][j] == 'v'){ dist[i][j] = 0; bfsQ.push({i, j}); } if (A[i][j] == '#'){ islandi = i; islandj = j; } } }
b1a42be50d1e40ebd79a35f8edf9f50e
{ "intermediate": 0.35090044140815735, "beginner": 0.4281461238861084, "expert": 0.22095336019992828 }
37,824
What verilog of VHDL logic code would make a chip with two inputs (advance and reset) , that simulates the nominal logic of a typical 4 aspect signal in the UK?
b25bfef9665648937c7f6c45097a8eef
{ "intermediate": 0.2582370936870575, "beginner": 0.23987841606140137, "expert": 0.501884400844574 }
37,825
proof of hoeffding's inequality
0473f65fc43b6f1ef283e705c993a2c0
{ "intermediate": 0.4371680021286011, "beginner": 0.33828407526016235, "expert": 0.22454789280891418 }
37,826
Can you write a VBA code that will do the following. Read from B2 downwards. If it finds a date with the time 00:00 and the next row down has the same date but with a time that is not 00:00 The delete the row with the same date but with a time 00:00. 19/01/2024 18:30 20/01/2024 00:00 21/01/2024 00:00 (delete this row, the next row down has same date with a time tht is not 00:00) 21/01/2024 17:30
60f7133f0b679d70813fd4dfdad755d0
{ "intermediate": 0.4400368332862854, "beginner": 0.2374626100063324, "expert": 0.3225005567073822 }
37,827
if i cancel, what will self.image_folder = filedialog.askdirectory() return
12a3dcb2c537956a8381115a94c903bb
{ "intermediate": 0.32513877749443054, "beginner": 0.394395112991333, "expert": 0.2804661691188812 }
37,828
Generate star system with ChatGPT version of StarGen
7a29e5dd22e3d7e4f6ad511d9e304c95
{ "intermediate": 0.3358064293861389, "beginner": 0.17620883882045746, "expert": 0.4879847466945648 }
37,829
def load_image(self, image_path): image = Image.open(image_path) # Check if the image has EXIF data if "exif" in image.info: exif_data = piexif.load(image.info["exif"]) if piexif.ImageIFD.Orientation in exif_data["0th"]: orientation = exif_data["0th"][piexif.ImageIFD.Orientation] if orientation == 3: image = image.rotate(180, expand=True) elif orientation == 6: image = image.rotate(-90, expand=True) elif orientation == 8: image = image.rotate(90, expand=True) if self.is_greyscale: image = image.convert("L") if self.is_mirrored: image = image.transpose(Image.FLIP_LEFT_RIGHT) if self.rotated != 0: image = image.rotate(self.rotated, expand=True) aspect_ratio = image.width / image.height canvas_width = self.canvas.winfo_width() canvas_height = self.canvas.winfo_height() max_width = min(canvas_width, int(aspect_ratio * canvas_height)) max_height = min(canvas_height, int(canvas_width / aspect_ratio)) scale_factor = min(max_width / image.width, max_height / image.height) new_width = int(image.width * scale_factor) new_height = int(image.height * scale_factor) if new_width > 0 and new_height > 0: resized_image = image.resize((new_width, new_height), Image.BICUBIC) self.photo = ImageTk.PhotoImage(resized_image) self.canvas.delete("all") self.canvas.create_image(canvas_width // 2, canvas_height // 2, image=self.photo) add a simple grid on top of the shown image in the canvas of 3x3x3 if grid=a else grid=b of a golden ratio grid and grid=c of 4x4 grid
23accda8f9d3d71b09c9ad7e210293dd
{ "intermediate": 0.3735700845718384, "beginner": 0.4695928692817688, "expert": 0.1568370908498764 }
37,830
How do I add the time (not just the day, like the hour) to this: createdDate.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
8e864f3ea3c95aaab69304a9a18c08b6
{ "intermediate": 0.519477903842926, "beginner": 0.22517019510269165, "expert": 0.2553519010543823 }
37,831
Can you write a VBA code that can do the following. From Row 2 going downwards, Check the dates in column A, For every group of dates that are the same, check their corresponding times in column E. For the group of dates that are the same then row with the lates time in column E, write the value 'Close' in column H. If the date in column A is singular and not part of a group of the same dates, then also write the value 'Close' into column H.
174d4c9c69ddf0445406b1b05c00619a
{ "intermediate": 0.35444438457489014, "beginner": 0.24739161133766174, "expert": 0.39816397428512573 }
37,832
hi
cbf5cf4b8255f414b7a44378fbfce488
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,833
import os from typing import List from llama_index import ( SimpleDirectoryReader, Document, StorageContext, load_index_from_storage ) from llama_index.node_parser import SentenceWindowNodeParser from llama_index.llms import OpenAI from llama_index.embeddings import OpenAIEmbedding from llama_index import ServiceContext from llama_index import VectorStoreIndex from llama_index.indices.postprocessor import MetadataReplacementPostProcessor from llama_index.indices.postprocessor import SentenceTransformerRerank from llama_index.llms import OpenAI # for loading environment variables from decouple import config from trulens_eval import Feedback, Tru, TruLlama from trulens_eval.feedback import Groundedness from trulens_eval.feedback.provider.openai import OpenAI as OpenAITruLens import numpy as np # set env variables os.environ[“OPENAI_API_KEY”] = config(“OPENAI_API_KEY”) # load document documents = SimpleDirectoryReader( input_dir=“…/dataFiles/” ).load_data(show_progress=True) # merge pages into one document = Document(text=“\n\n”.join([doc.text for doc in documents])) def create_indexes( documents: Document, index_save_dir: str, window_size: int = 4, llm_model: str = “gpt-3.5-turbo”, temperature: float = 0.1 ): node_parser = SentenceWindowNodeParser.from_defaults( window_size=window_size, window_metadata_key=“window”, original_text_metadata_key=“original_text”, ) # creating OpenAI gpt-3.5-turbo LLM and OpenAIEmbedding model llm = OpenAI(model=llm_model, temperature=temperature) embed_model = OpenAIEmbedding() # creating the service context sentence_context = ServiceContext.from_defaults( llm=llm, embed_model=embed_model, node_parser=node_parser, ) if not os.path.exists(index_save_dir): # creating the vector store index index = VectorStoreIndex.from_documents( [document], service_context=sentence_context ) # make vector store persistant index.storage_context.persist(persist_dir=index_save_dir) else: # load vector store indexed if they exist index = load_index_from_storage( StorageContext.from_defaults(persist_dir=index_save_dir), service_context=sentence_context ) return index def create_query_engine( sentence_index: VectorStoreIndex, similarity_top_k: int = 6, rerank_top_n: int = 5, rerank_model: str = “BAAI/bge-reranker-base”, ): # add meta data replacement post processor postproc = MetadataReplacementPostProcessor( target_metadata_key=“window” ) # link: https://huggingface.co/BAAI/bge-reranker-base rerank = SentenceTransformerRerank( top_n=rerank_top_n, model=rerank_model ) sentence_window_engine = sentence_index.as_query_engine( similarity_top_k=similarity_top_k, node_postprocessors=[postproc, rerank] ) return sentence_window_engine # create index index = create_indexes( documents=documents, index_save_dir=“./sentence_window_size_10_index”, window_size=3, llm_model=“gpt-3.5-turbo”, temperature=0.1 ) # create query engine sentence_window_engine = create_query_engine( sentence_index=index, similarity_top_k=5, rerank_top_n=2, ) # RAG pipeline evals tru = Tru(database_file=“…/default.sqlite”) openai = OpenAITruLens() grounded = Groundedness(groundedness_provider=OpenAITruLens()) # Define a groundedness feedback function f_groundedness = Feedback(grounded.groundedness_measure_with_cot_reasons).on( TruLlama.select_source_nodes().node.text ).on_output( ).aggregate(grounded.grounded_statements_aggregator) # Question/answer relevance between overall question and answer. f_qa_relevance = Feedback(openai.relevance).on_input_output() # Question/statement relevance between question and each context chunk. f_qs_relevance = Feedback(openai.qs_relevance).on_input().on( TruLlama.select_source_nodes().node.text ).aggregate(np.mean) tru_query_engine_recorder = TruLlama(sentence_window_engine, app_id=‘sentence_window_size_10’, feedbacks=[f_groundedness, f_qa_relevance, f_qs_relevance]) eval_questions = [] with open(“./eval_questions.txt”, “r”) as eval_qn: for qn in eval_qn: qn_stripped = qn.strip() eval_questions.append(qn_stripped) def run_eval(eval_questions: List[str]): for qn in eval_questions: # eval using context window with tru_query_engine_recorder as recording: sentence_window_engine.query(qn) run_eval(eval_questions=eval_questions) # run dashboard tru.run_dashboard() from typing import List from llama_index import ( Document, VectorStoreIndex, SimpleDirectoryReader, ServiceContext, ) from llama_index.retrievers import RecursiveRetriever from llama_index.query_engine import RetrieverQueryEngine from llama_index.node_parser import SimpleNodeParser from llama_index.embeddings import OpenAIEmbedding from llama_index.schema import IndexNode from llama_index.llms import OpenAI # for loading environment variables from decouple import config import os from trulens_eval import Feedback, Tru, TruLlama from trulens_eval.feedback import Groundedness from trulens_eval.feedback.provider.openai import OpenAI as OpenAITruLens import numpy as np # set env variables os.environ[“OPENAI_API_KEY”] = config(“OPENAI_API_KEY”) # create LLM and Embedding Model embed_model = OpenAIEmbedding() llm = OpenAI(model=“gpt-3.5-turbo”) service_context = ServiceContext.from_defaults( embed_model=embed_model, llm=llm) # load data documents = SimpleDirectoryReader( input_dir=“…/dataFiles”).load_data(show_progress=True) doc_text = “\n\n”.join([d.get_content() for d in documents]) docs = [Document(text=doc_text)] # create nodes parser node_parser = SimpleNodeParser.from_defaults(chunk_size=1024) # split into nodes base_nodes = node_parser.get_nodes_from_documents(documents=docs) # set document IDs for idx, node in enumerate(base_nodes): node.id_ = f"node-{idx}“ # create parent child documents sub_chunk_sizes = [128, 256, 512] sub_node_parsers = [ SimpleNodeParser.from_defaults(chunk_size=c, chunk_overlap=0) for c in sub_chunk_sizes ] all_nodes = [] for base_node in base_nodes: for n in sub_node_parsers: sub_nodes = n.get_nodes_from_documents([base_node]) sub_inodes = [ IndexNode.from_text_node(sn, base_node.node_id) for sn in sub_nodes ] all_nodes.extend(sub_inodes) # also add original node to node original_node = IndexNode.from_text_node(base_node, base_node.node_id) all_nodes.append(original_node) all_nodes_dict = {n.node_id: n for n in all_nodes} # creating index index = VectorStoreIndex(nodes=all_nodes, service_context=service_context) # creating a chunk retriever vector_retriever_chunk = index.as_retriever(similarity_top_k=2) retriever_chunk = RecursiveRetriever( “vector”, retriever_dict={“vector”: vector_retriever_chunk}, node_dict=all_nodes_dict, verbose=True, ) query_engine_chunk = RetrieverQueryEngine.from_args( retriever_chunk, service_context=service_context ) # RAG pipeline evals tru = Tru(database_file=”…/default.sqlite") openai = OpenAITruLens() grounded = Groundedness(groundedness_provider=OpenAITruLens()) # Define a groundedness feedback function f_groundedness = Feedback(grounded.groundedness_measure_with_cot_reasons).on( TruLlama.select_source_nodes().node.text ).on_output( ).aggregate(grounded.grounded_statements_aggregator) # Question/answer relevance between overall question and answer. f_qa_relevance = Feedback(openai.relevance).on_input_output() # Question/statement relevance between question and each context chunk. f_qs_relevance = Feedback(openai.qs_relevance).on_input().on( TruLlama.select_source_nodes().node.text ).aggregate(np.mean) tru_query_engine_recorder = TruLlama(query_engine_chunk, app_id=‘Parent_document_retrieval’, feedbacks=[f_groundedness, f_qa_relevance, f_qs_relevance]) eval_questions = [] with open(“./eval_questions.txt”, “r”) as eval_qn: for qn in eval_qn: qn_stripped = qn.strip() eval_questions.append(qn_stripped) def run_eval(eval_questions: List[str]): for qn in eval_questions: # eval using context window with tru_query_engine_recorder as recording: query_engine_chunk.query(qn) run_eval(eval_questions=eval_questions) # run dashboard tru.run_dashboard() from typing import List from llama_index import ( StorageContext, VectorStoreIndex, SimpleDirectoryReader, ServiceContext, load_index_from_storage ) from llama_index.node_parser import SimpleNodeParser from llama_index.embeddings import OpenAIEmbedding from llama_index.llms import OpenAI from llama_index.query_engine import RetrieverQueryEngine from trulens_eval import Feedback, Tru, TruLlama from trulens_eval.feedback import Groundedness from trulens_eval.feedback.provider.openai import OpenAI as OpenAITruLens import numpy as np # for loading environment variables from decouple import config import os # set env variables os.environ[“OPENAI_API_KEY”] = config(“OPENAI_API_KEY”) # create LLM and Embedding Model embed_model = OpenAIEmbedding() llm = OpenAI(model=“gpt-3.5-turbo”) service_context = ServiceContext.from_defaults( embed_model=embed_model, llm=llm) # check if data indexes already exists if not os.path.exists(“./storage”): # load data documents = SimpleDirectoryReader( input_dir=“…/dataFiles”).load_data(show_progress=True) # create nodes parser node_parser = SimpleNodeParser.from_defaults(chunk_size=1024) # split into nodes base_nodes = node_parser.get_nodes_from_documents(documents=documents) # creating index index = VectorStoreIndex(nodes=base_nodes, service_context=service_context) # store index index.storage_context.persist() else: # load existing index storage_context = StorageContext.from_defaults(persist_dir=“./storage”) index = load_index_from_storage(storage_context=storage_context) # create retriever retriever = index.as_retriever(similarity_top_k=2) # query retriever engine query_engine = RetrieverQueryEngine.from_args( retriever=retriever, service_context=service_context ) # RAG pipeline evals tru = Tru(database_file=“…/default.sqlite”) openai = OpenAITruLens() grounded = Groundedness(groundedness_provider=OpenAITruLens()) # Define a groundedness feedback function f_groundedness = Feedback(grounded.groundedness_measure_with_cot_reasons).on( TruLlama.select_source_nodes().node.text ).on_output( ).aggregate(grounded.grounded_statements_aggregator) # Question/answer relevance between overall question and answer. f_qa_relevance = Feedback(openai.relevance).on_input_output() # Question/statement relevance between question and each context chunk. f_qs_relevance = Feedback(openai.qs_relevance).on_input().on( TruLlama.select_source_nodes().node.text ).aggregate(np.mean) tru_query_engine_recorder = TruLlama(query_engine, app_id=‘Basic_RAG’, feedbacks=[f_groundedness, f_qa_relevance, f_qs_relevance]) eval_questions = [] with open(“./eval_questions.txt”, “r”) as eval_qn: for qn in eval_qn: qn_stripped = qn.strip() eval_questions.append(qn_stripped) def run_eval(eval_questions: List[str]): for qn in eval_questions: # eval using context window with tru_query_engine_recorder as recording: query_engine.query(qn) run_eval(eval_questions=eval_questions) # run dashboard tru.run_dashboard() can you combine above three code into one streamlit app using advance oops technique, use streamlit tab to switch between code
ccaf45976a54373cf51f6307915d00eb
{ "intermediate": 0.33991456031799316, "beginner": 0.30491527915000916, "expert": 0.35517019033432007 }
37,834
Your branch and 'origin/main' have diverged, and have 1 and 1 different commits each, respectively. (use "git pull" to merge the remote branch into yours)
4aef7ba65080ed79e93697e1fbf0a4c3
{ "intermediate": 0.32774198055267334, "beginner": 0.30348607897758484, "expert": 0.36877188086509705 }
37,835
I have a table with Headers. Can you please write me a VBA code that will sort the table column A to H, sorted by H Smallest to Largest
7167a32908bbe7711069720e09d68e94
{ "intermediate": 0.41792958974838257, "beginner": 0.16079957783222198, "expert": 0.4212709069252014 }
37,836
need potential knowledge in inference api of huggingface.co, but towards javascript, not python. look what I've made. add more parameters: <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chat with GPT-2 XL</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; flex-direction: column; align-items: center; height: 100vh; } #chatContainer { width: 50%; height: 400px; margin-bottom: 10px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; } #messageInput { width: calc(50% - 22px); padding: 10px; margin-bottom: 10px; } #sendButton, #clearButton { padding: 10px 20px; } </style> </head> <body> <div id="chatContainer"></div> <input type="text" id="messageInput" placeholder="Type your message here…"> <button id="sendButton">Send</button> <button id="clearButton">Clear</button> <script> const chatContainer = document.getElementById('chatContainer'); const messageInput = document.getElementById('messageInput'); const sendButton = document.getElementById('sendButton'); // WARNING: The token should be managed securely, not like this. const apiToken = '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'; // Replace with your actual API token sendButton.addEventListener('click', function() { const userInput = messageInput.value.trim(); if (userInput === "") return; chatContainer.innerHTML += "You: " + userInput + "<br/>"; messageInput.value = ""; // Prepare the payload to send to the model const payload = { inputs: userInput, parameters: { max_length: 100, // You can set this higher or adjust as needed num_return_sequences: 1 // Set this to 1 to get a single response } }; // Make the API call fetch('https://api-inference.huggingface.co/models/gpt2-xl', { method: 'POST', headers: { 'Authorization': 'Bearer ' + apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { // Assume the response returned is an object and catch otherwise try { const aiText = data[0].generated_text; chatContainer.innerHTML += "AI: " + aiText + "<br/>"; } catch (error) { chatContainer.innerHTML += "AI did not return a valid response.<br/>"; } chatContainer.scrollTop = chatContainer.scrollHeight; }) .catch(error => { console.error('Error:', error); chatContainer.innerHTML += "Error: " + error.message + "<br/>"; }); }); // Clear button event listener document.getElementById('clearButton').addEventListener('click', function() { chatContainer.innerHTML = ''; }); </script> </body> </html>
f4fbd3737e6189e99871a26220e7650c
{ "intermediate": 0.4219822883605957, "beginner": 0.32155928015708923, "expert": 0.2564584016799927 }
37,837
How do I use ThreadLocal.withInitial to prevent CompletableFuture from choking a thread
45a3bed6ab43470b3599cd5ffa570390
{ "intermediate": 0.566379964351654, "beginner": 0.177015483379364, "expert": 0.25660455226898193 }
37,838
need potential knowledge in inference api of huggingface.co, but towards javascript, not python. look what I’ve made. add more parameters: <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Chat with GPT-2 XL</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; flex-direction: column; align-items: center; height: 100vh; } #chatContainer { width: 50%; height: 400px; margin-bottom: 10px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; } #messageInput { width: calc(50% - 22px); padding: 10px; margin-bottom: 10px; } #sendButton, #clearButton { padding: 10px 20px; } </style> </head> <body> <div id=“chatContainer”></div> <input type=“text” id=“messageInput” placeholder=“Type your message here…”> <button id=“sendButton”>Send</button> <button id=“clearButton”>Clear</button> <script> const chatContainer = document.getElementById(‘chatContainer’); const messageInput = document.getElementById(‘messageInput’); const sendButton = document.getElementById(‘sendButton’); // WARNING: The token should be managed securely, not like this. const apiToken = ‘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’; // Replace with your actual API token sendButton.addEventListener(‘click’, function() { const userInput = messageInput.value.trim(); if (userInput === “”) return; chatContainer.innerHTML += "You: " + userInput + “<br/>”; messageInput.value = “”; // Prepare the payload to send to the model const payload = { inputs: userInput, parameters: { max_length: 100, // You can set this higher or adjust as needed num_return_sequences: 1 // Set this to 1 to get a single response } }; // Make the API call fetch(‘https://api-inference.huggingface.co/models/gpt2-xl’, { method: ‘POST’, headers: { ‘Authorization’: 'Bearer ’ + apiToken, ‘Content-Type’: ‘application/json’ }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { // Assume the response returned is an object and catch otherwise try { const aiText = data[0].generated_text; chatContainer.innerHTML += "AI: " + aiText + “<br/>”; } catch (error) { chatContainer.innerHTML += “AI did not return a valid response.<br/>”; } chatContainer.scrollTop = chatContainer.scrollHeight; }) .catch(error => { console.error(‘Error:’, error); chatContainer.innerHTML += "Error: " + error.message + “<br/>”; }); }); // Clear button event listener document.getElementById(‘clearButton’).addEventListener(‘click’, function() { chatContainer.innerHTML = ‘’; }); </script> </body> </html> Sure! Your current implementation provides a simple chat interface for interacting with GPT-2 XL through the Hugging Face Inference API. The code can be extended by adding more parameters to the API request, which can refine the behavior of the model. Here’s how you can add more parameters to your script: // … sendButton.addEventListener(‘click’, function() { const userInput = messageInput.value.trim(); if (userInput === “”) return; chatContainer.innerHTML += "You: " + userInput + “<br/>”; messageInput.value = “”; // Prepare the payload with additional parameters const payload = { inputs: userInput, parameters: { max_length: 100, // Max length of the output temperature: 0.7, // Sampling temperature top_k: 40, // The number of highest probability vocabulary tokens to keep for top-k-filtering top_p: 0.9, // Nucleus sampling (top-p) cumulative probability num_return_sequences: 1, // Number of outputs to generate repetition_penalty: 1.2, // Penalize repetition return_full_text: false // Generate only the newly added words by the model }, options: { use_cache: false // Whether to use the model’s cache or not } }; // Make the API call // … }); By introducing these parameters, you give the model more detailed instructions on how you’d like it to generate text. This can influence the creativity, randomness, and coherence of the outputs. Here’s a brief explanation of the parameters: - temperature: Controls randomness in the generation process. Lower values make the model more deterministic, while higher values encourage more creativity and diversity. - top_k: Limits the number of highest probability tokens considered during generation. - top_p: Nucleus sampling selects from the smallest possible set of tokens whose cumulative probability exceeds top_p, promoting diversity in generation. - repetition_penalty: Increases or decreases the likelihood of tokens based on how often they’ve appeared; useful for reducing repetition. - return_full_text: If false, the API returns only the portion of text that was generated by the model, omitting the original prompt from the API’s response. - use_cache: Determines whether the model should use its internal cache to produce results. Disabling this may be useful when you expect completely independent outputs, though it is typically left enabled for continuous conversation. Remember, using these parameters can affect the computational resources required and the response time from the API. Be considerate of your usage based on the performance required and potentially associated costs. not sure how this gpt2 final version should be adjusted, you seems know it much better if you knowledgeable in inference api. now integrate your adjustments into original code and output full code, simply. Sure! I can integrate the new parameters into the original code you have provided. Here’s the modified version of your HTML/JavaScript with the additional parameters included: <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Chat with GPT-2 XL</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; flex-direction: column; align-items: center; height: 100vh; } #chatContainer { width: 50%; height: 400px; margin-bottom: 10px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; } #messageInput { width: calc(50% - 22px); padding: 10px; margin-bottom: 10px; } #sendButton, #clearButton { padding: 10px 20px; } </style> </head> <body> <div id=“chatContainer”></div> <input type=“text” id=“messageInput” placeholder=“Type your message here…”> <button id=“sendButton”>Send</button> <button id=“clearButton”>Clear</button> <script> const chatContainer = document.getElementById(‘chatContainer’); const messageInput = document.getElementById(‘messageInput’); const sendButton = document.getElementById(‘sendButton’); const clearButton = document.getElementById(‘clearButton’); // WARNING: The token should be managed securely, not like this. const apiToken = ‘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’; // Replace with your actual API token sendButton.addEventListener(‘click’, function() { const userInput = messageInput.value.trim(); if (userInput === “”) return; chatContainer.innerHTML += "You: " + userInput + “<br/>”; messageInput.value = “”; // Prepare the payload to send to the model with additional parameters const payload = { inputs: userInput, parameters: { max_length: 100, temperature: 0.7, top_k: 40, top_p: 0.9, num_return_sequences: 1, repetition_penalty: 1.2, return_full_text: false }, options: { use_cache: true } }; // Make the API call fetch(‘https://api-inference.huggingface.co/models/gpt2-xl’, { method: ‘POST’, headers: { ‘Authorization’: 'Bearer ’ + apiToken, ‘Content-Type’: ‘application/json’ }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { // Assume the response returned is an object and catch otherwise try { const aiText = data[0].generated_text; chatContainer.innerHTML += "AI: " + aiText + “<br/>”; } catch (error) { chatContainer.innerHTML += “AI did not return a valid response.<br/>”; } chatContainer.scrollTop = chatContainer.scrollHeight; }) .catch(error => { console.error(‘Error:’, error); chatContainer.innerHTML += "Error: " + error.message + “<br/>”; }); }); // Clear button event listener clearButton.addEventListener(‘click’, function() { chatContainer.innerHTML = ‘’; }); </script> </body> </html> In the updated code, I’ve added new parameters to the payload object within the sendButton event listener. Additionally, I set use_cache to true within the options object to enable the model’s cache (this is generally desired for conversation-like exchanges). Please replace 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 with your actual API token which you would preferably fetch from a secure source or environment variable for security reasons, rather than hardcoding in the JavaScript file. backend (inference api) seems returns no errors, but gpt2 going nuts: “You: ew AI: y was killed in the line of duty. He’s a veteran who served his country honorably, and he deserves our respect,” said U.S. Rep. Scott Perry (R-Pa.). “I am very proud to have him as my friend.” The House passed legislation Wednesday that would award Purple Hearts to those wounded or killed by friendly fire in combat zones. The bill will now move on to the Senate for consideration.". where could be problem? can you answer gpt2 something for testing? The GPT-2 model response you’re seeing is characteristic of large language models. These models generate text based on patterns they’ve learned during training on large datasets. It’s important to note that the models don’t understand context or intention in the human sense; they produce text based on input prompts and learned statistical associations. The response that GPT-2 generated in your example seems unrelated to the input “ew”, and there could be several reasons for this: 1. The model’s randomness, as controlled by parameters like temperature, can lead to unpredictable text generation. 2. The input prompt is too vague or lacks context, making it difficult for the model to generate a coherent and relevant response. 3. The model is not equipped with the necessary mechanism to handle short or ambiguous prompts effectively. For better interactions with language models like GPT-2, consider these tips: - Provide clearer, more detailed prompts to guide the model’s response. - Use the model’s parameters to control creativity and randomness. For instance, a lower temperature results in less random responses. - Incorporate mechanisms to handle very short or uninformative prompts, which might involve giving the user feedback to enter more detailed queries. To conduct a simple test, let’s ask GPT-2 a straightforward question. You might simulate this by entering something like “What is the capital of France?” into the chat interface. Remember, when using AI models for user-facing applications, it’s also important to implement safeguards against inappropriate or harmful outputs. This could involve using content moderation tools or fine-tuning the model with curated datasets to guide its behavior. If you’re consistently receiving unrelated or nonsensical responses, you may need to further debug your frontend code or look into more advanced usage of the API, sometimes requiring custom preprocessing or postprocessing of the model’s input and output respectively. “sometimes requiring custom preprocessing or postprocessing of the model’s input and output respectively.”. doing it strictly in javascript in web browser. also, I often got 503 http code from inference api that says “error “Model openai-community/gpt2-xl is currently loading” estimated_time 257.2708740234375”. maybe there’s in inference api documentation something to fix that issue and wait for model or something? also, atach all params to sliders and give them default values as need. output your more advanced implementation of this gpt2 chat. If you’re frequently receiving HTTP 503 errors with the message that the “Model is currently loading”, it’s likely because the model is being loaded into the Hugging Face server’s memory, which can take some time, especially for larger models like GPT-2 XL. This is a common occurrence when using cloud-based AI models, as they might be unloaded from the server to free up resources when not in use. To mitigate this issue, Hugging Face’s API provides a wait_for_model parameter which, if set to true, tells the API to wait for the model to load before timing out. Below, I’ve updated your JavaScript code to include a wait_for_model parameter and to attach the model parameters to HTML range sliders with default values: <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Chat with GPT-2 XL</title> <link rel=“stylesheet” href=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.css”> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; height: 100vh; } .container { width: 50%; margin-bottom: 20px; } #chatContainer { height: 400px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; } #controlPanel { display: flex; justify-content: space-between; margin-bottom: 10px; } .slider-label { display: block; margin-bottom: 5px; } .slider { margin-bottom: 20px; } #parameterValues { font-size: 12px; } #messageInput { padding: 10px; width: calc(100% - 22px); margin-bottom: 10px; } #sendButton, #clearButton { padding: 10px 20px; } </style> </head> <body> <div class=“container”> <div id=“chatContainer”></div> <input type=“text” id=“messageInput” placeholder=“Type your message here…”> <div id=“controlPanel”> <button id=“sendButton”>Send</button> <button id=“clearButton”>Clear</button> </div> <div id=“parameterValues”></div> <!-- Sliders for parameters --> <div class=“slider” id=“temperatureSlider”></div> <div class=“slider” id=“topKSlider”></div> <div class=“slider” id=“topPSlider”></div> </div> <script src=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.js”></script> <script> const chatContainer = document.getElementById(‘chatContainer’); const messageInput = document.getElementById(‘messageInput’); const sendButton = document.getElementById(‘sendButton’); const clearButton = document.getElementById(‘clearButton’); const temperatureSlider = document.getElementById(‘temperatureSlider’); const topKSlider = document.getElementById(‘topKSlider’); const topPSlider = document.getElementById(‘topPSlider’); const parameterValues = document.getElementById(‘parameterValues’); // WARNING: The token should be managed securely, not like this. const apiToken = ‘your_api_token’; // Replace with your actual API token // Initialize sliders and set default values noUiSlider.create(temperatureSlider, { start: 0.7, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); noUiSlider.create(topKSlider, { start: 40, step: 1, range: { ‘min’: 0, ‘max’: 80, }, }); noUiSlider.create(topPSlider, { start: 0.9, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); // Function to update parameter values text function updateParameterValues() { const temperature = temperatureSlider.noUiSlider.get(); const topK = topKSlider.noUiSlider.get(); const topP = topPSlider.noUiSlider.get(); parameterValues.textContent = Temperature: ${temperature}, Top K: ${topK}, Top P: ${topP}; } // Update the parameter values text on slide temperatureSlider.noUiSlider.on(‘update’, updateParameterValues); topKSlider.noUiSlider.on(‘update’, updateParameterValues); topPSlider.noUiSlider.on(‘update’, updateParameterValues); // Initial update of parameter values text updateParameterValues(); sendButton.addEventListener(‘click’, function() { const userInput = messageInput.value.trim(); if (userInput === “”) return; chatContainer.innerHTML += "You: " + userInput + “<br/>”; messageInput.value = “”; // Read the slider values for parameters const temperature = parseFloat(temperatureSlider.noUiSlider.get()); const topK = parseInt(topKSlider.noUiSlider.get()); const topP = parseFloat(topPSlider.noUiSlider.get()); // Prepare the payload to send to the model with additional parameters const payload = { inputs: userInput, parameters: { max_length: 100, temperature: temperature, top_k: topK, top_p: topP, num_return_sequences: 1, repetition_penalty: 1.2, return_full_text: false }, options: { wait_for_model: true } }; // Make the API call fetch(‘https://api-inference.huggingface.co/models/gpt2-xl’, { method: ‘POST’, headers: { ‘Authorization’: 'Bearer ’ + apiToken, ‘Content-Type’: ‘application/json’ }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { // Assume the response returned is an object and catch otherwise try { const aiText = data.error || data[0].generated_text; chatContainer.innerHTML += "AI: " + aiText + “<br/>”; } catch (error) { chatContainer.innerHTML += “AI did not return a valid response.<br/>”; } chatContainer.scrollTop = chatContainer.scrollHeight; }) .catch(error => { console.error(‘Error:’, error); chatContainer.innerHTML += "Error: " + error.message + “<br/>”; }); }); // Clear button event listener clearButton.addEventListener(‘click’, function() { chatContainer.innerHTML = ‘’; }); </script> </body> </html> Please follow these steps to complete your testing: 1. Replace your_api_token with your actual Hugging Face API token. 2. Launch the updated code in your web browser. 3. Adjust the sliders for Temperature, Top K, and Top P to set the model parameters to your desired values. 4. Use the input field to send messages to GPT-2 XL and receive responses. By setting wait_for_model: true in the options, the API should now wait until the model is fully loaded before attempting to generate a response, which helps avoid the 503 errors you’ve been experiencing. The sliders offer a user-friendly way to adjust the parameters live, and the updated code displays the current settings under the sliders. no, never use backicks in template literals, this is a total mess. fix that line through + and ’ as normal: parameterValues.textContent = Temperature: {temperature}, Top K: {topK}, Top P: ${topP}; Certainly! We can revert the string interpolation using template literals back to regular string concatenation with the + operator and quotes: // Function to update parameter values text function updateParameterValues() { const temperature = temperatureSlider.noUiSlider.get(); const topK = topKSlider.noUiSlider.get(); const topP = topPSlider.noUiSlider.get(); parameterValues.textContent = 'Temperature: ’ + temperature + ', Top K: ’ + topK + ', Top P: ’ + topP; } By updating this line, you avoid using template literals and stick to more traditional string concatenation. This keeps the code in line with your requirements to not use backticks within template literals. ok, it answered something: “You: What is the capital of France? AI: The city of Paris is the capital of France. The name Paris derives from the Latin word parva, which means “town”. The French language has no equivalent to this English term for a town and the meaning was lost in the Middle Ages. It appears that the word “Paris” came into use as early as 1634 when Jean-François de La Fontaine used it as the title of his play Les Avignons (1635).”. now will be nice if you add an indicator that model is loading somewhere when actual response text is “currently loading” and http code 503, but problem that it returns no any code or response while “wait_for_model: true”. not sure how to make an indicator here. any ideas? When “wait_for_model” is set to true, the Hugging Face API will wait for the model to be ready before it sends back a response. This means your JavaScript code will not get an immediate HTTP status code or response while the model is loading, thus making it challenging to display a loading indicator based on the API response. However, we can implement a loading indicator based on the assumption that if a response is taking an unusually long time, the model might be loading. We could display a loading message or animation when the “Send” button is clicked, and then remove the message or animation when the response from the API is received. I’ll provide an example below of how to integrate a simple loading text indicator into your chat interface. <!-- Add the following line to your HTML where you want the loading indicator to appear --> <div id=“loadingIndicator” style=“display: none;”>Loading…</div> <script> const loadingIndicator = document.getElementById(‘loadingIndicator’); // … sendButton.addEventListener(‘click’, function() { // Display the loading indicator loadingIndicator.style.display = ‘block’; // Prepare the rest of your API call code // … // Fetch call (no changes here) fetch(‘https://api-inference.huggingface.co/models/gpt2-xl’, { // … }) .then(response => response.json()) .then(data => { // Hide the loading indicator loadingIndicator.style.display = ‘none’; // Process the response // … }) .catch(error => { // Hide the loading indicator loadingIndicator.style.display = ‘none’; // Handle the error console.error(‘Error:’, error); chatContainer.innerHTML += "Error: " + error.message + “<br/>”; }); }); // Clear button event listener clearButton.addEventListener(‘click’, function() { chatContainer.innerHTML = ‘’; }); // … </script> Adding the loadingIndicator div to your HTML and toggling the display property in the script will create the effect of a loading indicator. You could replace the “Loading…” text with a spinner or any other form of animation by adjusting the CSS and HTML as necessary. This implementation will show the loading indicator whenever a message is sent until a response is received, helping users understand that the system is processing their request. "However, we can implement a loading indicator based on the assumption". no, I got better idea here. we will let one response pass. we will set wait for model to false by default, and when we get http code 503 and exact text inside response “currently loading”, then we will switch to wait for model true. is that ok? because we will press send button once, and if there's 503 http code and text in response is “currently loading”, then we will simply automatically resend that queue but with wait for model option enabled and our indicator showing that model is actually loading right now.
5f118751b7f3457918d241dd6d5ccf41
{ "intermediate": 0.3528766930103302, "beginner": 0.37327152490615845, "expert": 0.27385181188583374 }
37,839
“sometimes requiring custom preprocessing or postprocessing of the model’s input and output respectively.”. doing it strictly in javascript in web browser. also, I often got 503 http code from inference api that says “error “Model openai-community/gpt2-xl is currently loading” estimated_time 257.2708740234375”. maybe there’s in inference api documentation something to fix that issue and wait for model or something? also, atach all params to sliders and give them default values as need. output your more advanced implementation of this gpt2 chat. If you’re frequently receiving HTTP 503 errors with the message that the “Model is currently loading”, it’s likely because the model is being loaded into the Hugging Face server’s memory, which can take some time, especially for larger models like GPT-2 XL. This is a common occurrence when using cloud-based AI models, as they might be unloaded from the server to free up resources when not in use. To mitigate this issue, Hugging Face’s API provides a wait_for_model parameter which, if set to true, tells the API to wait for the model to load before timing out. Below, I’ve updated your JavaScript code to include a wait_for_model parameter and to attach the model parameters to HTML range sliders with default values: <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Chat with GPT-2 XL</title> <link rel=“stylesheet” href=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.css”> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; height: 100vh; } .container { width: 50%; margin-bottom: 20px; } #chatContainer { height: 400px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; } #controlPanel { display: flex; justify-content: space-between; margin-bottom: 10px; } .slider-label { display: block; margin-bottom: 5px; } .slider { margin-bottom: 20px; } #parameterValues { font-size: 12px; } #messageInput { padding: 10px; width: calc(100% - 22px); margin-bottom: 10px; } #sendButton, #clearButton { padding: 10px 20px; } </style> </head> <body> <div class=“container”> <div id=“chatContainer”></div> <input type=“text” id=“messageInput” placeholder=“Type your message here…”> <div id=“controlPanel”> <button id=“sendButton”>Send</button> <button id=“clearButton”>Clear</button> </div> <div id=“parameterValues”></div> <!-- Sliders for parameters --> <div class=“slider” id=“temperatureSlider”></div> <div class=“slider” id=“topKSlider”></div> <div class=“slider” id=“topPSlider”></div> </div> <script src=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.js”></script> <script> const chatContainer = document.getElementById(‘chatContainer’); const messageInput = document.getElementById(‘messageInput’); const sendButton = document.getElementById(‘sendButton’); const clearButton = document.getElementById(‘clearButton’); const temperatureSlider = document.getElementById(‘temperatureSlider’); const topKSlider = document.getElementById(‘topKSlider’); const topPSlider = document.getElementById(‘topPSlider’); const parameterValues = document.getElementById(‘parameterValues’); // WARNING: The token should be managed securely, not like this. const apiToken = ‘your_api_token’; // Replace with your actual API token // Initialize sliders and set default values noUiSlider.create(temperatureSlider, { start: 0.7, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); noUiSlider.create(topKSlider, { start: 40, step: 1, range: { ‘min’: 0, ‘max’: 80, }, }); noUiSlider.create(topPSlider, { start: 0.9, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); // Function to update parameter values text function updateParameterValues() { const temperature = temperatureSlider.noUiSlider.get(); const topK = topKSlider.noUiSlider.get(); const topP = topPSlider.noUiSlider.get(); parameterValues.textContent = Temperature: ${temperature}, Top K: ${topK}, Top P: ${topP}; } // Update the parameter values text on slide temperatureSlider.noUiSlider.on(‘update’, updateParameterValues); topKSlider.noUiSlider.on(‘update’, updateParameterValues); topPSlider.noUiSlider.on(‘update’, updateParameterValues); // Initial update of parameter values text updateParameterValues(); sendButton.addEventListener(‘click’, function() { const userInput = messageInput.value.trim(); if (userInput === “”) return; chatContainer.innerHTML += "You: " + userInput + “<br/>”; messageInput.value = “”; // Read the slider values for parameters const temperature = parseFloat(temperatureSlider.noUiSlider.get()); const topK = parseInt(topKSlider.noUiSlider.get()); const topP = parseFloat(topPSlider.noUiSlider.get()); // Prepare the payload to send to the model with additional parameters const payload = { inputs: userInput, parameters: { max_length: 100, temperature: temperature, top_k: topK, top_p: topP, num_return_sequences: 1, repetition_penalty: 1.2, return_full_text: false }, options: { wait_for_model: true } }; // Make the API call fetch(‘https://api-inference.huggingface.co/models/gpt2-xl’, { method: ‘POST’, headers: { ‘Authorization’: 'Bearer ’ + apiToken, ‘Content-Type’: ‘application/json’ }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { // Assume the response returned is an object and catch otherwise try { const aiText = data.error || data[0].generated_text; chatContainer.innerHTML += "AI: " + aiText + “<br/>”; } catch (error) { chatContainer.innerHTML += “AI did not return a valid response.<br/>”; } chatContainer.scrollTop = chatContainer.scrollHeight; }) .catch(error => { console.error(‘Error:’, error); chatContainer.innerHTML += "Error: " + error.message + “<br/>”; }); }); // Clear button event listener clearButton.addEventListener(‘click’, function() { chatContainer.innerHTML = ‘’; }); </script> </body> </html> Please follow these steps to complete your testing: 1. Replace your_api_token with your actual Hugging Face API token. 2. Launch the updated code in your web browser. 3. Adjust the sliders for Temperature, Top K, and Top P to set the model parameters to your desired values. 4. Use the input field to send messages to GPT-2 XL and receive responses. By setting wait_for_model: true in the options, the API should now wait until the model is fully loaded before attempting to generate a response, which helps avoid the 503 errors you’ve been experiencing. The sliders offer a user-friendly way to adjust the parameters live, and the updated code displays the current settings under the sliders. no, never use backicks in template literals, this is a total mess. fix that line through + and ’ as normal: parameterValues.textContent = Temperature: {temperature}, Top K: {topK}, Top P: ${topP}; Certainly! We can revert the string interpolation using template literals back to regular string concatenation with the + operator and quotes: // Function to update parameter values text function updateParameterValues() { const temperature = temperatureSlider.noUiSlider.get(); const topK = topKSlider.noUiSlider.get(); const topP = topPSlider.noUiSlider.get(); parameterValues.textContent = 'Temperature: ’ + temperature + ', Top K: ’ + topK + ', Top P: ’ + topP; } By updating this line, you avoid using template literals and stick to more traditional string concatenation. This keeps the code in line with your requirements to not use backticks within template literals. ok, it answered something: “You: What is the capital of France? AI: The city of Paris is the capital of France. The name Paris derives from the Latin word parva, which means “town”. The French language has no equivalent to this English term for a town and the meaning was lost in the Middle Ages. It appears that the word “Paris” came into use as early as 1634 when Jean-François de La Fontaine used it as the title of his play Les Avignons (1635).”. now will be nice if you add an indicator that model is loading somewhere when actual response text is “currently loading” and http code 503, but problem that it returns no any code or response while “wait_for_model: true”. not sure how to make an indicator here. any ideas? "However, we can implement a loading indicator based on the assumption". no, I got better idea here. we will let one response pass. we will set wait for model to false by default, and when we get http code 503 and exact text inside response “currently loading”, then we will switch to wait for model true. is that ok? because we will press send button once, and if there's 503 http code and text in response is “currently loading”, then we will simply automatically resend that queue but with wait for model option enabled and our indicator showing that model is actually loading right now.
58c1c22ccde247b4be053950bc8f3fe3
{ "intermediate": 0.546787440776825, "beginner": 0.35226014256477356, "expert": 0.1009524017572403 }
37,840
If you’re frequently receiving HTTP 503 errors with the message that the “Model is currently loading”, it’s likely because the model is being loaded into the Hugging Face server’s memory, which can take some time, especially for larger models like GPT-2 XL. This is a common occurrence when using cloud-based AI models, as they might be unloaded from the server to free up resources when not in use. To mitigate this issue, Hugging Face’s API provides a wait_for_model parameter which, if set to true, tells the API to wait for the model to load before timing out. Below, I’ve updated your JavaScript code to include a wait_for_model parameter and to attach the model parameters to HTML range sliders with default values: <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Chat with GPT-2 XL</title> <link rel=“stylesheet” href=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.css”> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; height: 100vh; } .container { width: 50%; margin-bottom: 20px; } #chatContainer { height: 400px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; } #controlPanel { display: flex; justify-content: space-between; margin-bottom: 10px; } .slider-label { display: block; margin-bottom: 5px; } .slider { margin-bottom: 20px; } #parameterValues { font-size: 12px; } #messageInput { padding: 10px; width: calc(100% - 22px); margin-bottom: 10px; } #sendButton, #clearButton { padding: 10px 20px; } </style> </head> <body> <div class=“container”> <div id=“chatContainer”></div> <input type=“text” id=“messageInput” placeholder=“Type your message here…”> <div id=“controlPanel”> <button id=“sendButton”>Send</button> <button id=“clearButton”>Clear</button> </div> <div id=“parameterValues”></div> <!-- Sliders for parameters --> <div class=“slider” id=“temperatureSlider”></div> <div class=“slider” id=“topKSlider”></div> <div class=“slider” id=“topPSlider”></div> </div> <script src=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.js”></script> <script> const chatContainer = document.getElementById(‘chatContainer’); const messageInput = document.getElementById(‘messageInput’); const sendButton = document.getElementById(‘sendButton’); const clearButton = document.getElementById(‘clearButton’); const temperatureSlider = document.getElementById(‘temperatureSlider’); const topKSlider = document.getElementById(‘topKSlider’); const topPSlider = document.getElementById(‘topPSlider’); const parameterValues = document.getElementById(‘parameterValues’); // WARNING: The token should be managed securely, not like this. const apiToken = ‘your_api_token’; // Replace with your actual API token // Initialize sliders and set default values noUiSlider.create(temperatureSlider, { start: 0.7, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); noUiSlider.create(topKSlider, { start: 40, step: 1, range: { ‘min’: 0, ‘max’: 80, }, }); noUiSlider.create(topPSlider, { start: 0.9, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); // Function to update parameter values text function updateParameterValues() { const temperature = temperatureSlider.noUiSlider.get(); const topK = topKSlider.noUiSlider.get(); const topP = topPSlider.noUiSlider.get(); parameterValues.textContent = Temperature: ${temperature}, Top K: ${topK}, Top P: ${topP}; } // Update the parameter values text on slide temperatureSlider.noUiSlider.on(‘update’, updateParameterValues); topKSlider.noUiSlider.on(‘update’, updateParameterValues); topPSlider.noUiSlider.on(‘update’, updateParameterValues); // Initial update of parameter values text updateParameterValues(); sendButton.addEventListener(‘click’, function() { const userInput = messageInput.value.trim(); if (userInput === “”) return; chatContainer.innerHTML += "You: " + userInput + “<br/>”; messageInput.value = “”; // Read the slider values for parameters const temperature = parseFloat(temperatureSlider.noUiSlider.get()); const topK = parseInt(topKSlider.noUiSlider.get()); const topP = parseFloat(topPSlider.noUiSlider.get()); // Prepare the payload to send to the model with additional parameters const payload = { inputs: userInput, parameters: { max_length: 100, temperature: temperature, top_k: topK, top_p: topP, num_return_sequences: 1, repetition_penalty: 1.2, return_full_text: false }, options: { wait_for_model: true } }; // Make the API call fetch(‘https://api-inference.huggingface.co/models/gpt2-xl’, { method: ‘POST’, headers: { ‘Authorization’: 'Bearer ’ + apiToken, ‘Content-Type’: ‘application/json’ }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { // Assume the response returned is an object and catch otherwise try { const aiText = data.error || data[0].generated_text; chatContainer.innerHTML += "AI: " + aiText + “<br/>”; } catch (error) { chatContainer.innerHTML += “AI did not return a valid response.<br/>”; } chatContainer.scrollTop = chatContainer.scrollHeight; }) .catch(error => { console.error(‘Error:’, error); chatContainer.innerHTML += "Error: " + error.message + “<br/>”; }); }); // Clear button event listener clearButton.addEventListener(‘click’, function() { chatContainer.innerHTML = ‘’; }); </script> </body> </html> Please follow these steps to complete your testing: 1. Replace your_api_token with your actual Hugging Face API token. 2. Launch the updated code in your web browser. 3. Adjust the sliders for Temperature, Top K, and Top P to set the model parameters to your desired values. 4. Use the input field to send messages to GPT-2 XL and receive responses. By setting wait_for_model: true in the options, the API should now wait until the model is fully loaded before attempting to generate a response, which helps avoid the 503 errors you’ve been experiencing. The sliders offer a user-friendly way to adjust the parameters live, and the updated code displays the current settings under the sliders. no, never use backicks in template literals, this is a total mess. fix that line through + and ’ as normal: parameterValues.textContent = Temperature: {temperature}, Top K: {topK}, Top P: ${topP}; Certainly! We can revert the string interpolation using template literals back to regular string concatenation with the + operator and quotes: // Function to update parameter values text function updateParameterValues() { const temperature = temperatureSlider.noUiSlider.get(); const topK = topKSlider.noUiSlider.get(); const topP = topPSlider.noUiSlider.get(); parameterValues.textContent = 'Temperature: ’ + temperature + ', Top K: ’ + topK + ', Top P: ’ + topP; } By updating this line, you avoid using template literals and stick to more traditional string concatenation. This keeps the code in line with your requirements to not use backticks within template literals. "However, we can implement a loading indicator based on the assumption". no, I got better idea here. we will let one response pass. we will set wait for model to false by default, and when we get http code 503 and exact text inside response “currently loading”, then we will switch to wait for model true. is that ok? because we will press send button once, and if there's 503 http code and text in response is “currently loading”, then we will simply automatically resend that queue but with wait for model option enabled and our indicator showing that model is actually loading right now.
400f148c0f7dd62a89f00f7ac826c801
{ "intermediate": 0.36113786697387695, "beginner": 0.45581936836242676, "expert": 0.1830427646636963 }
37,841
"However, we can implement a loading indicator based on the assumption". no, I got better idea here. we will let one response pass. we will set wait for model to false by default, and when we get http code 503 and exact text inside response “currently loading”, then we will switch to wait for model true. is that ok? because we will press send button once, and if there's 503 http code and text in response is “currently loading”, then we will simply automatically resend that queue but with wait for model option enabled and our indicator showing that model is actually loading right now.
63cc346c86b723ce89be23769abb43b4
{ "intermediate": 0.4204365015029907, "beginner": 0.21697020530700684, "expert": 0.36259326338768005 }
37,842
“However, we can implement a loading indicator based on the assumption”. no, I got better idea here. we will let one response pass. we will set wait for model to false by default, and when we get http code 503 and exact text inside response “currently loading”, then we will switch to wait for model true. is that ok? because we will press send button once, and if there’s 503 http code and text in response is “currently loading”, then we will simply automatically resend that queue but with wait for model option enabled and our indicator showing that model is actually loading right now.: here’s code in which need to implement my idea: <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Chat with GPT-2 XL</title> <link rel=“stylesheet” href=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.css”> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; height: 100vh; } .container { width: 50%; margin-bottom: 20px; } #chatContainer { height: 400px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; } #controlPanel { display: flex; justify-content: space-between; margin-bottom: 10px; } .slider-label { display: block; margin-bottom: 5px; } .slider { margin-bottom: 20px; } #parameterValues { font-size: 12px; } #messageInput { padding: 10px; width: calc(100% - 22px); margin-bottom: 10px; } #sendButton, #clearButton { padding: 10px 20px; } </style> </head> <body> <div class=“container”> <div id=“chatContainer”></div> <input type=“text” id=“messageInput” placeholder=“Type your message here…”> <div id=“controlPanel”> <button id=“sendButton”>Send</button> <button id=“clearButton”>Clear</button> </div> <div id=“parameterValues”></div> <!-- Sliders for parameters --> <div class=“slider” id=“temperatureSlider”></div> <div class=“slider” id=“topKSlider”></div> <div class=“slider” id=“topPSlider”></div> </div> <script src=“https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.6.3/nouislider.min.js”></script> <script> const chatContainer = document.getElementById(‘chatContainer’); const messageInput = document.getElementById(‘messageInput’); const sendButton = document.getElementById(‘sendButton’); const clearButton = document.getElementById(‘clearButton’); const temperatureSlider = document.getElementById(‘temperatureSlider’); const topKSlider = document.getElementById(‘topKSlider’); const topPSlider = document.getElementById(‘topPSlider’); const parameterValues = document.getElementById(‘parameterValues’); // WARNING: The token should be managed securely, not like this. const apiToken = ‘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’; // Replace with your actual API token // Initialize sliders and set default values noUiSlider.create(temperatureSlider, { start: 0.7, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); noUiSlider.create(topKSlider, { start: 40, step: 1, range: { ‘min’: 0, ‘max’: 80, }, }); noUiSlider.create(topPSlider, { start: 0.9, step: 0.1, range: { ‘min’: 0.1, ‘max’: 1.0, }, }); function updateParameterValues() { const temperature = temperatureSlider.noUiSlider.get(); const topK = topKSlider.noUiSlider.get(); const topP = topPSlider.noUiSlider.get(); parameterValues.textContent = 'Temperature: ’ + temperature + ', Top K: ’ + topK + ', Top P: ’ + topP; } // Update the parameter values text on slide temperatureSlider.noUiSlider.on(‘update’, updateParameterValues); topKSlider.noUiSlider.on(‘update’, updateParameterValues); topPSlider.noUiSlider.on(‘update’, updateParameterValues); // Initial update of parameter values text updateParameterValues(); sendButton.addEventListener(‘click’, function() { const userInput = messageInput.value.trim(); if (userInput === “”) return; chatContainer.innerHTML += "You: " + userInput + “<br/>”; messageInput.value = “”; // Read the slider values for parameters const temperature = parseFloat(temperatureSlider.noUiSlider.get()); const topK = parseInt(topKSlider.noUiSlider.get()); const topP = parseFloat(topPSlider.noUiSlider.get()); // Prepare the payload to send to the model with additional parameters const payload = { inputs: userInput, parameters: { max_length: 100, temperature: temperature, top_k: topK, top_p: topP, num_return_sequences: 1, repetition_penalty: 1.2, return_full_text: false }, options: { wait_for_model: true } }; // Make the API call fetch(‘https://api-inference.huggingface.co/models/gpt2-xl’, { method: ‘POST’, headers: { ‘Authorization’: 'Bearer ’ + apiToken, ‘Content-Type’: ‘application/json’ }, body: JSON.stringify(payload), }) .then(response => response.json()) .then(data => { // Assume the response returned is an object and catch otherwise try { const aiText = data.error || data[0].generated_text; chatContainer.innerHTML += "AI: " + aiText + “<br/>”; } catch (error) { chatContainer.innerHTML += “AI did not return a valid response.<br/>”; } chatContainer.scrollTop = chatContainer.scrollHeight; }) .catch(error => { console.error(‘Error:’, error); chatContainer.innerHTML += "Error: " + error.message + “<br/>”; }); }); // Clear button event listener clearButton.addEventListener(‘click’, function() { chatContainer.innerHTML = ‘’; }); </script> </body> </html> no, never use backicks in template literals, this is a total mess. implement into original code my idea and never use template literals through backtikcks ever. output strictly full code according to original, simply. include html,css,javascript and all, including my idea.
7be540fee6906f6c839152cd0f4d79bd
{ "intermediate": 0.37941691279411316, "beginner": 0.4173085391521454, "expert": 0.20327450335025787 }
37,843
package com.example.myapplication; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.FullScreenContentCallback; import com.google.android.gms.ads.LoadAdError; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.gms.ads.interstitial.InterstitialAd; import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback; public class MainActivity extends AppCompatActivity { private InterstitialAd mInterstitialAd; private Button mInterstitialButton; private AdRequest adRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MobileAds.initialize(this, new OnInitializationCompleteListener() { @Override public void onInitializationComplete(InitializationStatus initializationStatus) { } }); final boolean[] volt = {false}; AdView mAdView = findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); Button bannerbutton = findViewById(R.id.BannerbtnAds); bannerbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!volt[0]) { mAdView.loadAd(adRequest); mAdView.setVisibility(View.VISIBLE); volt[0] = true; } else { mAdView.setVisibility(View.GONE); volt[0] = false; } } }); InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest, new InterstitialAdLoadCallback() { @Override public void onAdLoaded(@NonNull InterstitialAd interstitialAd) { // The mInterstitialAd reference will be null until // an ad is loaded. mInterstitialAd = interstitialAd; } @Override public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) { // Handle the error mInterstitialAd = null; } }); Button button = findViewById(R.id.IntbtnAds); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mInterstitialAd != null) { mInterstitialAd.show(MainActivity.this); } else { Log.d("TAG", "The interstitial ad wasn't ready yet."); } } }); } } The interstitial ad shows only once, after that: The interstitial ad has been shown. How can I fix it?
1199e023282cbf1e61096aac42b31db4
{ "intermediate": 0.41211867332458496, "beginner": 0.42780300974845886, "expert": 0.16007833182811737 }
37,844
Help me create a Mixture of Expert LSTM models, with pytorch and numpy
1480d23c410e55269565c1e424a12747
{ "intermediate": 0.19038791954517365, "beginner": 0.059165362268686295, "expert": 0.7504467368125916 }
37,845
I want a VBA code that can do the following. From A2 go down the column and if the day of the date changes, on the row where it cahnges add the value "Close" to column I
4d91a20c2a134084faca747906480126
{ "intermediate": 0.33468741178512573, "beginner": 0.31694307923316956, "expert": 0.3483695089817047 }