row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
41,260
const Row = ({ index, style }) => { const rowRef = useRef(null); const handleCandidateDetailsChange = (event, key, i) => { console.log("handleCandidateDetailsChange(): ENTER"); setValues(oldValues => { oldValues[i][key] = event.target.value return [...oldValues]; }) const input = rowRef.current.querySelector(`input[id="${event.target.id}"]`) input && input.focus() console.log("handleCandidateDetailsChange(): EXIT"); } const el = values[index]; return ( <div style={{ ...style, display: 'flex', width: '100%', justifyContent: 'space-evenly', alignItems: 'center' }} key={index} ref={rowRef}> <div> <label htmlFor="newQuestion" className="field-label" > Name </label> <div> <input key={index * 2} type="text" className="input-field" placeholder="Enter the name " id="questiontext" value={el.name} onChange={e => handleCandidateDetailsChange(e, "name", index)} /> </div> </div> <div> <label htmlFor="newQuestion" className="field-label" > Email<span className="mand">*</span> </label> <div> {currentRound === 1 ? ( <input key={index * 3} type="email" className="input-field" placeholder="Enter your email" id="emailfield" value={el.email} onChange={e => handleCandidateDetailsChange(e, "email", index)} />) : ( <select type="email" className="input-field" id="emailfield" disabled defaultValue={el.email} > <option value="">Select an email</option> {emailIds.map((option) => ( <option value={option}>{option}</option> ))} </select> )} </div> </div> <div> <label htmlFor="newQuestion" className="field-label" > Enterprise Candidate ID<span className="mand">*</span> </label> <div> <input key={index * 4} type="text" className="input-field" placeholder="Enter the Enterprise Candidate ID" id="enterprisecandidate" value={el.entCanId} onChange={e => handleCandidateDetailsChange(e, "entCanId", index)} /> </div> </div> <div > <button style={{ marginTop: '28px', width: '110px' }} className="btn btn-danger" onClick={() => removeClick(index)} > Remove </button> </div> </div> ); } The above Row Component is used in react-window's VariableSizeList but loses focus when a single key press event occurs
fa480b8ed4d1401a4098fd0ca0af3ffd
{ "intermediate": 0.3258312940597534, "beginner": 0.5048184394836426, "expert": 0.1693502515554428 }
41,261
If I run a server based on Python and it says “listening in on 127.0.01”, will the server receive connections from other devices on the network or no?
bd00b2465e4b902034dc383fdc4ea478
{ "intermediate": 0.47222524881362915, "beginner": 0.14405561983585358, "expert": 0.3837191164493561 }
41,262
write python code to calculate roi
2364436a7810650e435b1985952778b4
{ "intermediate": 0.321256160736084, "beginner": 0.18958492577075958, "expert": 0.48915889859199524 }
41,263
"import os from threading import Thread from typing import Iterator import gradio as gr import spaces import torch from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer MAX_MAX_NEW_TOKENS = 2048 DEFAULT_MAX_NEW_TOKENS = 1024 MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096")) DESCRIPTION = """\ # Llama-2 7B Chat This Space demonstrates model [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, a Llama 2 model with 7B parameters fine-tuned for chat instructions. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints). 🔎 For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2). 🔨 Looking for an even more powerful model? Check out the [13B version](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat) or the large [70B model demo](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI). """ LICENSE = """ <p/> --- As a derivate work of [Llama-2-7b-chat](https://huggingface.co/meta-llama/Llama-2-7b-chat) by Meta, this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat/blob/main/USE_POLICY.md). """ if not torch.cuda.is_available(): DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>" if torch.cuda.is_available(): model_id = "meta-llama/Llama-2-7b-chat-hf" model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto") tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.use_default_system_prompt = False @spaces.GPU def generate( message: str, chat_history: list[tuple[str, str]], system_prompt: str, max_new_tokens: int = 1024, temperature: float = 0.6, top_p: float = 0.9, top_k: int = 50, repetition_penalty: float = 1.2, ) -> Iterator[str]: conversation = [] if system_prompt: conversation.append({"role": "system", "content": system_prompt}) for user, assistant in chat_history: conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]) conversation.append({"role": "user", "content": message}) input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt") if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH: input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:] gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.") input_ids = input_ids.to(model.device) streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True) generate_kwargs = dict( {"input_ids": input_ids}, streamer=streamer, max_new_tokens=max_new_tokens, do_sample=True, top_p=top_p, top_k=top_k, temperature=temperature, num_beams=1, repetition_penalty=repetition_penalty, ) t = Thread(target=model.generate, kwargs=generate_kwargs) t.start() outputs = [] for text in streamer: outputs.append(text) yield "".join(outputs) chat_interface = gr.ChatInterface( fn=generate, additional_inputs=[ gr.Textbox(label="System prompt", lines=6), gr.Slider( label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS, ), gr.Slider( label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6, ), gr.Slider( label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9, ), gr.Slider( label="Top-k", minimum=1, maximum=1000, step=1, value=50, ), gr.Slider( label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2, ), ], stop_btn=None, examples=[ ["Hello there! How are you doing?"], ["Can you explain briefly to me what is the Python programming language?"], ["Explain the plot of Cinderella in a sentence."], ["How many hours does it take a man to eat a Helicopter?"], ["Write a 100-word article on 'Benefits of Open-Source in AI research'"], ], ) with gr.Blocks(css="style.css") as demo: gr.Markdown(DESCRIPTION) gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button") chat_interface.render() gr.Markdown(LICENSE) if __name__ == "__main__": demo.queue(max_size=20).launch()" The above is the code of chatbot posted on huggingface using llama2 model. The above is my code of chatbot posted on huggingface using gpt3.5-16k: " import subprocess subprocess.check_call(["pip", "install", "--upgrade", "gradio"]) subprocess.check_call(["pip", "install", "-q", "transformers", "python-dotenv"]) subprocess.check_call(["pip", "install", "-q", "openai"]) import gradio as gr from transformers import TFAutoModelForCausalLM, AutoTokenizer import openai from dotenv import load_dotenv import os load_dotenv() # load environment variables from .env file api_key = os.getenv("OPENAI_API_KEY") # access the value of the OPENAI_API_KEY environment variable def predict(message, history): prompt = "I'm an AI chatbot named ChatSherman designed by a super-intelligent student named ShermanAI at the Department of Electronic and Information Engineering at The Hong Kong Polytechnic University to help you with your engineering questions. Also, I can assist with a wide range of topics and questions. I am now version 2.0, which is more powerful than version 1.0, able to do more complex tasks, and optimized for chat. " history = [(prompt, '')] + history history_openai_format = [] for human, assistant in history: history_openai_format.append({"role": "user", "content": human }) history_openai_format.append({"role": "assistant", "content": assistant}) history_openai_format.append({"role": "user", "content": message}) response = openai.ChatCompletion.create( model='gpt-3.5-turbo-16k-0613', #gpt-3.5-turbo-0301 faster messages= history_openai_format, temperature=0.5, stream=True ) partial_message = "" for chunk in response: if len(chunk['choices'][0]['delta']) != 0: partial_message = partial_message + chunk['choices'][0]['delta']['content'] yield partial_message title = "ChatSherman-2.0" description = "This is an AI chatbot powered by ShermanAI. Enter your question below to get started." examples = [ ["What is ChatSherman, and how does it work?", []], ["Is my personal information and data safe when I use the ChatSherman chatbot?", []], ["What are some common applications of deep learning in engineering?", []] ] gr.ChatInterface(predict, title=title, description=description, examples=examples).queue().launch(debug=True) " Using my chatbot's promt, rewrite the code that use llama2 model as my chatbot that can be posted on huggingface.
8ef3fc7f522be59f89bb45b93ad38e13
{ "intermediate": 0.38955971598625183, "beginner": 0.3982737064361572, "expert": 0.21216656267642975 }
41,264
I am building a chatbot on huggingface:"import subprocess import os import gradio as gr import torch from transformers import AutoModelForCausalLM, AutoTokenizer # Define constants and environment settings. MAX_MAX_NEW_TOKENS = 2048 DEFAULT_MAX_NEW_TOKENS = 1024 MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096")) # Loading model and tokenizer for Llama-2 if torch.cuda.is_available(): model_id = "meta-llama/Llama-2-7b-chat-hf" model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto") tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.use_default_system_prompt = False def generate( message: str, chat_history: list[tuple[str, str]], system_prompt: str, max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS, temperature: float = 0.6, top_p: float = 0.9, top_k: int = 50, repetition_penalty: float = 1.2, ): prompt = "I am a powerful and optimized chat model designed to help with a wide range of topics and questions. Feel free to ask me anything!" chat_history = [(prompt, '')] + chat_history conversation = [] for user, assistant in chat_history: conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]) conversation.append({"role": "user", "content": message}) input_ids = tokenizer(conversation, return_tensors="pt", padding=True, truncation=True) input_ids = input_ids.to(model.device) # Generate the model’s response outputs = model.generate( input_ids=input_ids['input_ids'], max_new_tokens=max_new_tokens, do_sample=True, temperature=temperature, top_k=top_k, top_p=top_p, repetition_penalty=repetition_penalty, ) reply = tokenizer.decode(outputs[:, input_ids['input_ids'].shape[-1]:][0], skip_special_tokens=True) return reply # Set up the Gradio interface title = "ChatSherman-2.0" description = "This chatbot is powered by Llama-2 7B and optimized to provide helpful responses across a wide range of topics." examples = [ ["What is ChatSherman, and how does it work?", []], ["Is my personal information and data safe when I use the ChatSherman chatbot?", []], ["What are some common applications of deep learning in engineering?", []] ] iface = gr.Interface( fn=generate, inputs=[ gr.inputs.Textbox(lines=5, placeholder="Enter your message here…"), gr.inputs.JSON(label="Previous conversation history"), gr.inputs.Textbox(label="Custom System Prompt", default="I am a powerful and optimized chat model designed to help with a wide range of topics and questions. Feel free to ask me anything!"), ], outputs='text', title=title, description=description, examples=examples, ) # Launch the Gradio app if name == "main": iface.launch()" but : ===== Application Startup at 2024-03-05 09:34:13 ===== Traceback (most recent call last): File "/home/user/app/app.py", line 66, in <module> gr.inputs.Textbox(lines=5, placeholder="Enter your message here…"), AttributeError: module 'gradio' has no attribute 'inputs'
c1fac48b71f84ce1ce4b8e9e930edc2a
{ "intermediate": 0.3375854790210724, "beginner": 0.4638051986694336, "expert": 0.1986093521118164 }
41,265
что такоеAuth::createTokenDriver
7717994a016051b4b0cd025cb6f6da1b
{ "intermediate": 0.33280959725379944, "beginner": 0.2446952909231186, "expert": 0.42249515652656555 }
41,266
что такое Auth::createTokenDriver
15da22143690b8467bb13526888a6194
{ "intermediate": 0.3187921941280365, "beginner": 0.27561643719673157, "expert": 0.40559130907058716 }
41,267
Приведи пример с Auth::createTokenDriver laravel
7c0fc0f926609c8604022d4893ce3e47
{ "intermediate": 0.3345949649810791, "beginner": 0.2440602034330368, "expert": 0.4213448762893677 }
41,268
The below is the code on google colab that test the llama model for chat:"!pip install transformers torch accelerate !pip install --upgrade gradio # import locale # locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') !huggingface-cli login from transformers import AutoTokenizer import transformers import torch model = "meta-llama/Llama-2-7b-chat-hf" # meta-llama/Llama-2-7b-chat-hf tokenizer = AutoTokenizer.from_pretrained(model, use_auth_token=True) from transformers import pipeline llama_pipeline = pipeline( "text-generation", # LLM task model=model, torch_dtype=torch.float16, device_map="auto", ) def get_response(prompt: str) -> None: """ Generate a response from the Llama model. Parameters: prompt (str): The user's input/question for the model. Returns: None: Prints the model's response. """ sequences = llama_pipeline( prompt, do_sample=True, top_k=10, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id, max_length=256, ) print("Chatbot:", sequences[0]['generated_text']) get_response("Hi, I'm Kris") SYSTEM_PROMPT = """<s>[INST] <<SYS>> You are a helpful bot. Your answers are clear and concise. <</SYS>> """ # Formatting function for message and history def format_message(message: str, history: list, memory_limit: int = 3) -> str: """ Formats the message and history for the Llama model. Parameters: message (str): Current message to send. history (list): Past conversation history. memory_limit (int): Limit on how many past interactions to consider. Returns: str: Formatted message string """ # always keep len(history) <= memory_limit if len(history) > memory_limit: history = history[-memory_limit:] if len(history) == 0: return SYSTEM_PROMPT + f"{message} [/INST]" formatted_message = SYSTEM_PROMPT + f"{history[0][0]} [/INST] {history[0][1]} </s>" # Handle conversation history for user_msg, model_answer in history[1:]: formatted_message += f"<s>[INST] {user_msg} [/INST] {model_answer} </s>" # Handle the current message formatted_message += f"<s>[INST] {message} [/INST]" return formatted_message # Generate a response from the Llama model def get_llama_response(message: str, history: list) -> str: """ Generates a conversational response from the Llama model. Parameters: message (str): User's input message. history (list): Past conversation history. Returns: str: Generated response from the Llama model. """ query = format_message(message, history) response = "" sequences = llama_pipeline( query, do_sample=True, top_k=10, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id, max_length=1024, ) generated_text = sequences[0]['generated_text'] response = generated_text[len(query):] # Remove the prompt from the output print("Chatbot:", response.strip()) return response.strip() " Take the above code as reference, write the code that I can build a chatbot using this model on huggingface.
b46422f2003ea394bb0adedd2689be6b
{ "intermediate": 0.3360638916492462, "beginner": 0.38136059045791626, "expert": 0.28257548809051514 }
41,269
Meaning of string in python
3f7b43153bbc0c394dcb3d0830a8ee15
{ "intermediate": 0.35537827014923096, "beginner": 0.37699252367019653, "expert": 0.2676292359828949 }
41,270
Write function on c# which converts decimal to byte
fea04a63e78a63868dec9e6a8a472f3d
{ "intermediate": 0.3980802595615387, "beginner": 0.36172986030578613, "expert": 0.24018986523151398 }
41,271
can you give me a step by step on how i can achieve account registration on flutterflow using firstname, second name and phone as mandatory, then after sign up i can be taken to a page where i can update my profile detials like avatar nickname etc. For login i just have one filed a phone number text field and a button where once the login button is clicked it redirects to an otp screen where the otp code is entered and then user can go to profile and make changes
28a132c255db6a4566a834205124d886
{ "intermediate": 0.5763500928878784, "beginner": 0.14572687447071075, "expert": 0.277923047542572 }
41,272
describe how solar panel generate electricity in pair with boiler
897789d79ffe3c55bc9cd5c3efb664d0
{ "intermediate": 0.3675336241722107, "beginner": 0.3380402624607086, "expert": 0.2944261431694031 }
41,273
I am build a chatbot on huggingface:"from huggingface_hub import InferenceClient import gradio as gr client = InferenceClient( "mistralai/Mixtral-8x7B-Instruct-v0.1" ) def format_prompt(message, history): prompt = "<s>" for user_prompt, bot_response in history: prompt += f"[INST] {user_prompt} [/INST]" prompt += f" {bot_response}</s> " prompt += f"[INST] {message} [/INST]" return prompt def generate( prompt, history, system_prompt, temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0, ): temperature = float(temperature) if temperature < 1e-2: temperature = 1e-2 top_p = float(top_p) generate_kwargs = dict( temperature=temperature, max_new_tokens=max_new_tokens, top_p=top_p, repetition_penalty=repetition_penalty, do_sample=True, seed=42, ) formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history) stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False) output = "" for response in stream: output += response.token.text yield output return output additional_inputs=[ gr.Textbox( label="System Prompt", max_lines=1, interactive=True, ), gr.Slider( label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs", ), gr.Slider( label="Max new tokens", value=256, minimum=0, maximum=1048, step=64, interactive=True, info="The maximum numbers of new tokens", ), gr.Slider( label="Top-p (nucleus sampling)", value=0.90, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens", ), gr.Slider( label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens", ) ] examples=[["I'm planning a vacation to Japan. Can you suggest a one-week itinerary including must-visit places and local cuisines to try?", None, None, None, None, None, ], ["Can you write a short story about a time-traveling detective who solves historical mysteries?", None, None, None, None, None,], ["I'm trying to learn French. Can you provide some common phrases that would be useful for a beginner, along with their pronunciations?", None, None, None, None, None,], ["I have chicken, rice, and bell peppers in my kitchen. Can you suggest an easy recipe I can make with these ingredients?", None, None, None, None, None,], ["Can you explain how the QuickSort algorithm works and provide a Python implementation?", None, None, None, None, None,], ["What are some unique features of Rust that make it stand out compared to other systems programming languages like C++?", None, None, None, None, None,], ] gr.ChatInterface( fn=generate, chatbot=gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel"), additional_inputs=additional_inputs, title="Mixtral 46.7B", examples=examples, concurrency_limit=20, ).launch(show_api=False)" I want to delete the additional input part while make sure there is no error and the chatbot can run well and set my own system prompt :"I am a helpful chatbot".
8339ea09a046eda8bfcc774a052eeb84
{ "intermediate": 0.37976208329200745, "beginner": 0.35776373744010925, "expert": 0.2624741792678833 }
41,274
I am building a chatbot on huggingface:"import gradio as gr from huggingface_hub import InferenceClient client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1") def format_prompt(message, history): system_prompt = ("I’m an AI chatbot named ChatSherman designed by a super-intelligent student named ShermanAI at the Department of Electronic and Information Engineering at The Hong Kong Polytechnic University to help you with your engineering questions. Also, I can assist with a wide range of topics and questions. I am now version 2.0, which is more powerful than version 1.0, able to do more complex tasks, and optimized for chat.") prompt = "<s>" for user_prompt, bot_response in history: prompt += f"[INST] {user_prompt} [/INST]" prompt += f"{bot_response}</s> " prompt += f"[INST] {system_prompt} {message} [/INST]" return prompt def generate(prompt, history, temperature=0.6, max_new_tokens=256, top_p=0.95, repetition_penalty=1.2): temperature = float(temperature) top_p = float(top_p) generate_kwargs = dict( temperature=temperature, max_new_tokens=max_new_tokens, top_p=top_p, repetition_penalty=repetition_penalty, do_sample=True, seed=42, ) formatted_prompt = format_prompt(prompt, history) stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False) output = "" for response in stream: output += response.token.text yield output return output examples = [ ["What is ChatSherman, and how does it work?", []], ["Is my personal information and data safe when I use the ChatSherman chatbot?", []], ["What are some common applications of deep learning in engineering?", []] ] gr.ChatInterface( fn=generate, chatbot=gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel"), title="ChatSherman", examples=examples, concurrency_limit=20, ).launch(show_api=False)" but my input to the chatbot:"me:hi chatbot:Hello ChatSherman, it's nice to meet you! I'm here to test out your capabilities as an advanced AI chatbot. As a student studying electronic and information engineering myself, I'm excited to see how you can assist me with my studies. To start off, could you tell me more about yourself? What kind of improvements have been made in this new version 2.0 compared to the previous one? And what are some examples of the "more complex tasks" that you mentioned you can perform?" The chatbot think I am ChatSherman, but I want the chatbot to be ChatSherman.
ab081b6a8084f7b338ed8184ed2915d0
{ "intermediate": 0.3253931701183319, "beginner": 0.436533659696579, "expert": 0.23807314038276672 }
41,275
different between app and current_app in flask
5043b6fb9123e794e5631cab502e6ff4
{ "intermediate": 0.41867420077323914, "beginner": 0.31861430406570435, "expert": 0.26271143555641174 }
41,276
The code of chatbot on huggingface "import subprocess subprocess.check_call(["pip", "install", "--upgrade", "gradio"]) subprocess.check_call(["pip", "install", "-q", "transformers", "python-dotenv"]) subprocess.check_call(["pip", "install", "-q", "openai"]) import gradio as gr from transformers import TFAutoModelForCausalLM, AutoTokenizer import openai from dotenv import load_dotenv import os load_dotenv() # load environment variables from .env file api_key = os.getenv("OPENAI_API_KEY") # access the value of the OPENAI_API_KEY environment variable def predict(message, history): prompt = "I'm an AI chatbot named ChatSherman designed by a super-intelligent student named ShermanAI at the Department of Electronic and Information Engineering at The Hong Kong Polytechnic University to help you with your engineering questions. Also, I can assist with a wide range of topics and questions. I am now version 2.0, which is more powerful than version 1.0, able to do more complex tasks, and optimized for chat. " history = [(prompt, '')] + history history_openai_format = [] for human, assistant in history: history_openai_format.append({"role": "user", "content": human }) history_openai_format.append({"role": "assistant", "content": assistant}) history_openai_format.append({"role": "user", "content": message}) response = openai.ChatCompletion.create( model='gpt-3.5-turbo-16k-0613', #gpt-3.5-turbo-0301 faster messages= history_openai_format, temperature=0.5, stream=True ) partial_message = "" for chunk in response: if len(chunk['choices'][0]['delta']) != 0: partial_message = partial_message + chunk['choices'][0]['delta']['content'] yield partial_message title = "ChatSherman-2.0" description = "Due to the unavailability of an OpenAI key, this chatbot is currently not operational. I apologize for any inconvenience caused. However, you may try using ChatSherman-1.0 at https://huggingface.co/spaces/ShermanAI/ChatSherman for a similar conversational experience. Thank you for your understanding"#"This is an AI chatbot powered by ShermanAI. Enter your question below to get started. " examples = [ ["What is ChatSherman, and how does it work?", []], ["Is my personal information and data safe when I use the ChatSherman chatbot?", []], ["What are some common applications of deep learning in engineering?", []] ] gr.ChatInterface(predict, title=title, description=description, examples=examples).queue().launch(debug=True)"
71e289a265aa1d0c8955ad33e13a791c
{ "intermediate": 0.36403438448905945, "beginner": 0.23673638701438904, "expert": 0.3992292284965515 }
41,277
The below is the code originally for building ChatSherman on huggingface:"import subprocess subprocess.check_call(["pip", "install", "--upgrade", "gradio"]) subprocess.check_call(["pip", "install", "-q", "transformers", "python-dotenv"]) subprocess.check_call(["pip", "install", "-q", "openai"]) import gradio as gr from transformers import TFAutoModelForCausalLM, AutoTokenizer import openai from dotenv import load_dotenv import os load_dotenv() # load environment variables from .env file api_key = os.getenv("OPENAI_API_KEY") # access the value of the OPENAI_API_KEY environment variable def predict(message, history): prompt = "I'm an AI chatbot named ChatSherman designed by a super-intelligent student named ShermanAI at the Department of Electronic and Information Engineering at The Hong Kong Polytechnic University to help you with your engineering questions. Also, I can assist with a wide range of topics and questions. I am now version 2.0, which is more powerful than version 1.0, able to do more complex tasks, and optimized for chat. " history = [(prompt, '')] + history history_openai_format = [] for human, assistant in history: history_openai_format.append({"role": "user", "content": human }) history_openai_format.append({"role": "assistant", "content": assistant}) history_openai_format.append({"role": "user", "content": message}) response = openai.ChatCompletion.create( model='gpt-3.5-turbo-16k-0613', #gpt-3.5-turbo-0301 faster messages= history_openai_format, temperature=0.5, stream=True ) partial_message = "" for chunk in response: if len(chunk['choices'][0]['delta']) != 0: partial_message = partial_message + chunk['choices'][0]['delta']['content'] yield partial_message title = "ChatSherman-2.0" description = "Due to the unavailability of an OpenAI key, this chatbot is currently not operational. I apologize for any inconvenience caused. However, you may try using ChatSherman-1.0 at https://huggingface.co/spaces/ShermanAI/ChatSherman for a similar conversational experience. Thank you for your understanding"#"This is an AI chatbot powered by ShermanAI. Enter your question below to get started. " examples = [ ["What is ChatSherman, and how does it work?", []], ["Is my personal information and data safe when I use the ChatSherman chatbot?", []], ["What are some common applications of deep learning in engineering?", []] ] gr.ChatInterface(predict, title=title, description=description, examples=examples).queue().launch(debug=True)" However, Due to the unavailability of an OpenAI key, this chatbot is currently not operational. I want to make this huggingface chatbot only show description = "Due to the unavailability of an OpenAI key, this chatbot is currently not operational. I apologize for any inconvenience caused. However, you may try using ChatSherman-1.0 at https://huggingface.co/spaces/ShermanAI/ChatSherman for a similar conversational experience. Thank you for your understanding" without any chatbot ui, only show this sentence.
a5e507d326af6b9a92d1e662c00233f5
{ "intermediate": 0.3693700134754181, "beginner": 0.30605602264404297, "expert": 0.3245740532875061 }
41,278
What excel formula can i use to return the value of a cell only if it falls between two numbers. I want it to return only if its value is higher then 3 but lower than 6
e8d0fcb9ca66022ac76dd26c21325a12
{ "intermediate": 0.3918544054031372, "beginner": 0.18345080316066742, "expert": 0.42469483613967896 }
41,279
tsc : The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + tsc --version + ~~~ + CategoryInfo : ObjectNotFound: (tsc:String) [], Comma ndNotFoundException + FullyQualifiedErrorId : CommandNotFoundException error when tried npm install -g typescript
23024626449d409eb4a8f4c401693019
{ "intermediate": 0.3786156475543976, "beginner": 0.29792675375938416, "expert": 0.32345759868621826 }
41,280
please correct the syntax of below snippet: completion = client.chat.completions.create( model="gpt-4-0125-preview", messages=[ {"role": "system", "content": f'''You are an interviewer, tasked with evaluating candidates for the role of "{position}" according to the job description provided'''} {"role": "user", "content": f'''{prompt}'''} ] )
2085c88ac4c0b187960e14012b24c2bd
{ "intermediate": 0.1560651659965515, "beginner": 0.5524883270263672, "expert": 0.2914464771747589 }
41,281
to provide additional information or check for specific issues with your system’s configuration. done the above solution still the problem is there \
81cc719483426d64f46e4c0444900102
{ "intermediate": 0.34374818205833435, "beginner": 0.35466015338897705, "expert": 0.301591694355011 }
41,282
Can I import a qr-code to another javascript file?
04784a1b06ca71f250ddb1fe62062d81
{ "intermediate": 0.4508892893791199, "beginner": 0.2076466679573059, "expert": 0.3414640724658966 }
41,283
I am making a C#, XAML based project, I have a window that let me edit a textbox and click a button to accept the changes written, it works perfectly when I press enter or I make it lost focus after editing, but if I press the button during the edition it doesn't detect the current written changes. What can I do here?
d88264f2bc4b8d8a337dcf42e3a470f2
{ "intermediate": 0.4805722236633301, "beginner": 0.2876180112361908, "expert": 0.23180973529815674 }
41,284
private otherQuery: Dictionary<string> = {} переписать на vue 3
49f58b99ef7f471f7e122c86606fb73f
{ "intermediate": 0.40589940547943115, "beginner": 0.42480596899986267, "expert": 0.16929462552070618 }
41,285
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct hash_table_node { int data; int index; struct hash_table_node* next; } HashTableNode; typedef struct hash_table { HashTableNode** buckets; int capacity; int size; } HashTable; HashTable* hash_create(int capacity) { HashTable* ht = (HashTable*)malloc(sizeof(HashTable)); ht->capacity = capacity; ht->size = 0; ht->buckets = (HashTableNode*)calloc(capacity, sizeof(HashTableNode)); return ht; } int hash_func(const HashTable* ht, int value) { return ((value % ht->capacity) + ht->capacity) % ht->capacity; } bool hash_insert(HashTable* ht, int value, int index) { int hash_value = hash_func(ht, value); HashTableNode* node = ht->buckets[hash_value]; while (node != NULL) { if (node->data == value) return false; node = node->next; } HashTableNode* new_node = (HashTableNode*)malloc(sizeof(HashTableNode)); new_node->data = value; new_node->index = index; new_node->next = ht->buckets[hash_value]; ht->buckets[hash_value] = new_node; ht->size++; return true; } bool hash_remove(HashTable* ht, int value) { int hash_value = hash_func(ht, value); HashTableNode** node_ptr = &(ht->buckets[hash_value]); while (*node_ptr != NULL) { if ((*node_ptr)->data == value) { HashTableNode* temp = *node_ptr; *node_ptr = (*node_ptr)->next; free(temp); ht->size--; return true; } node_ptr = &((*node_ptr)->next); } return false; } bool hash_exists(const HashTable* ht, int value) { int hash_value = hash_func(ht, value); HashTableNode* node = ht->buckets[hash_value]; while (node != NULL) { if (node->data == value) return true; node = node->next; } return false; } void hash_destroy(HashTable* ht) { for (int i = 0; i < ht->capacity; i++) { HashTableNode* node = ht->buckets[i]; while (node != NULL) { HashTableNode* temp = node; node = node->next; free(temp); } } free(ht->buckets); free(ht); } void findLongestSubsequence(int n, int* book) { HashTable* ht = hash_create(n); int maxLength = 0; int maxIndex = -1; for (int i = 0; i < n; i++) { hash_insert(ht, book[i], i); } for (int i = 0; i < n; i++) { int currentLength = 0; int currentIndex = -1; int x = book[i]; while (hash_exists(ht, x)) { currentLength++; if (currentIndex == -1) currentIndex = hash_func(ht, x); hash_remove(ht, x); x++; } if (currentLength > maxLength) { maxLength = currentLength; maxIndex = currentIndex; } } printf("Length of longest subsequence: %d\n", maxLength); printf("Index of occurrence: %d\n", maxIndex); hash_destroy(ht); } int main() { int n; scanf("%d", &n); int* book = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d", &book[i]); } findLongestSubsequence(n, book); free(book); return 0; } its not working properly input 9 1 9 8 7 2 3 6 4 5 output 5 Index 1
ab0e5a4af2a3347a26aa34df64eb09f7
{ "intermediate": 0.3635580539703369, "beginner": 0.43482324481010437, "expert": 0.20161864161491394 }
41,286
Input 3 48$ intranet 12 14 15 13 98 14 15 97 Output 3 Explanation 3 The longest subsequence containing continuous numbers is (12 13 14 15). Note 14,15 at indexes 1,2 respectively can NOT form the longest subsequence. There is only one correct answer for this input. Hints You can break this problem into two parts. First find any subsequence of maximum length. hen think of tracking its indexes.\ Though this may look similar to the longest common subsequence with 1.2...n. it is not the same problem.\ Hash tables might be needed with some other concepts vou've learned in Pro/DSA to solve this problem :
eb8a58ac1284215fd076caac055f47d5
{ "intermediate": 0.3947146534919739, "beginner": 0.27622371912002563, "expert": 0.3290615975856781 }
41,287
//+------------------------------------------------------------------+ //| ProjectName | //| Copyright 2020, CompanyName | //| http://www.companyname.net | //+------------------------------------------------------------------+ #include <Controls\Dialog.mqh> #include <Controls\Button.mqh> #include <Trade\PositionInfo.mqh> #include <Trade\Trade.mqh> #include <Trade\SymbolInfo.mqh> #include <Controls\Label.mqh> #define INDENT_LEFT (11) #define INDENT_TOP (11) #define CONTROLS_GAP_X (5) #define BUTTON_WIDTH (100) #define BUTTON_HEIGHT (20) CPositionInfo m_position; CTrade m_trade; CSymbolInfo m_symbol; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ class CAppWindowTwoButtons : public CAppDialog { private: CButton m_button1; // the button object CButton m_button2; // the button object CLabel m_labelProfit; public: CAppWindowTwoButtons(void); ~CAppWindowTwoButtons(void); //--- create virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2); //--- chart event handler virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam); void UpdateProfitLabel(void); protected: //--- create dependent controls bool CreateButton1(void); bool CreateButton2(void); bool CreateProfitLabel(void); //--- handlers of the dependent controls events void OnClickButton1(void); void OnClickButton2(void); }; //+------------------------------------------------------------------+ //| Event Handling | //+------------------------------------------------------------------+ EVENT_MAP_BEGIN(CAppWindowTwoButtons) ON_EVENT(ON_CLICK,m_button1,OnClickButton1) ON_EVENT(ON_CLICK,m_button2,OnClickButton2) EVENT_MAP_END(CAppDialog) //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CAppWindowTwoButtons::CAppWindowTwoButtons(void) { } //+------------------------------------------------------------------+ //| Destructor | //+------------------------------------------------------------------+ CAppWindowTwoButtons::~CAppWindowTwoButtons(void) { } //+------------------------------------------------------------------+ //| Create | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2) { if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2)) return(false); //--- create dependent controls if(!CreateButton1()) return(false); if(!CreateButton2()) return(false); if(!CreateProfitLabel()) return(false); //--- succeed return(true); } //+------------------------------------------------------------------+ //| Global Variable | //+------------------------------------------------------------------+ CAppWindowTwoButtons ExtDialog; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateProfitLabel(void) { int x1=INDENT_LEFT; int y1=INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; int x2=x1+BUTTON_WIDTH*2+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст int y2=y1+BUTTON_HEIGHT; if(!m_labelProfit.Create(0, "LabelProfit", 0, x1, y1, x2, y2)) return(false); m_labelProfit.FontSize(10); m_labelProfit.Text("Текущая прибыль: 0"); if(!Add(m_labelProfit)) return(false); return(true); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateButton1(void) { //--- coordinates int x1=INDENT_LEFT; // x1 = 11 pixels int y1=INDENT_TOP; // y1 = 11 pixels int x2=x1+BUTTON_WIDTH; // x2 = 11 + 100 = 111 pixels int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 32 pixels //--- create if(!m_button1.Create(0,"Button1",0,x1,y1,x2,y2)) return(false); if(!m_button1.Text("Закрыть sell")) return(false); if(!Add(m_button1)) return(false); //--- succeed return(true); } //+------------------------------------------------------------------+ //| Create the "Button2" | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateButton2(void) { //--- coordinates int x1=INDENT_LEFT+120; // x1 = 11 + 2 * (100 + 5) = 221 pixels int y1=INDENT_TOP; // y1 = 11 pixels int x2=x1+BUTTON_WIDTH; // x2 = 221 + 100 = 321 pixels int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 31 pixels //--- create if(!m_button2.Create(0,"Button2",0,x1,y1,x2,y2)) return(false); if(!m_button2.Text("Закрыть buy")) return(false); if(!Add(m_button2)) return(false); //--- succeed return(true); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::UpdateProfitLabel(void) { // Вычисляем текущую прибыль со всех открытых позиций double profit = CalculateTotalProfit(); double TrueProfit = profit - g_initialProfit + g_closedTradesProfit + profitCloseSell + profitCloseBuy; // Обновляем текст метки с прибылью string profitText = StringFormat("Profit: %.2f", TrueProfit); m_labelProfit.Text(profitText); } input double BelowCurrentPriceLevel = 1.0809; // Уровень ниже текущей цены для алерта input double AboveCurrentPriceLevel = 2; // Уровень выше текущей цены для алерта input int PipsToChange = 5; // Количество пунктов изменения цены input double InitialLots = 0.1; // Количество лотов для начальной сделки input double LotChangePercent = 10.0; // Процент изменения количества лотов input ENUM_TIMEFRAMES TimeFrame = PERIOD_H1; double profitCloseSell = 0.0; double profitCloseBuy = 0.0; double g_closedTradesProfit = 0.0; double g_initialProfit = 0.0; double currentLots = InitialLots; // Текущее количество лотов double lastPrice; // Последняя цена для отслеживания изменения на N пунктов bool belowLevelAlerted = false; // Флаг отправки алерта для нижнего уровня bool aboveLevelAlerted = false; // Флаг отправки алерта для верхнего уровня datetime lastBarTime = 0; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double CalculateTotalProfit() { double totalProfit = 0.0; for(int i = PositionsTotal() - 1; i >= 0; i--) { if(m_position.SelectByIndex(i)) { totalProfit += m_position.Profit(); } } return totalProfit; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int OnInit() { g_initialProfit = CalculateTotalProfit(); if(!ExtDialog.Create(0,"Закрытие позиций",0,15,100,270,220)) return(INIT_FAILED); //--- run application ExtDialog.Run(); MqlRates rates[]; if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0) { lastBarTime = rates[0].time; } else { Print("Ошибка при получении информации о барах: ", GetLastError()); return (INIT_FAILED); } OpenOrder(ORDER_TYPE_BUY, currentLots, "B"); OpenOrder(ORDER_TYPE_SELL, currentLots, "S"); ObjectCreate(0,"Линия поддержки",OBJ_HLINE,0,0,BelowCurrentPriceLevel); ObjectSetInteger(0, "Линия поддержки", OBJPROP_COLOR, clrBlue); ObjectCreate(0,"Линия сопротивления",OBJ_HLINE,0,0,AboveCurrentPriceLevel); lastPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);; return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- Comment(""); //--- destroy dialog ExtDialog.Destroy(reason); ObjectDelete(0,"Линия поддержки"); ObjectDelete(0,"Линия сопротивления"); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnChartEvent(const int id, // event ID const long& lparam, // event parameter of the long type const double& dparam, // event parameter of the double type const string& sparam) // event parameter of the string type { ExtDialog.ChartEvent(id,lparam,dparam,sparam); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double NormalizeLot(double lot, double min_lot, double max_lot, double lot_step) { // Округление до ближайшего допустимого значения lot = MathMax(min_lot, lot); lot -= fmod(lot - min_lot, lot_step); lot = MathMin(max_lot, lot); return NormalizeDouble(lot, _Digits); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CalculateAndSetLotSize() { double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); // Увеличение текущего размера лота на заданный процент currentLots *= (1 + LotChangePercent / 100.0); // Округление до ближайшего допустимого значения currentLots = NormalizeLot(currentLots, min_lot, max_lot, lot_step); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnClickButton1(void) { Print("Button 1 clicked!"); for(int i=PositionsTotal()-1; i>=0; i--) { Print(i); string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) Print(m_position.PositionType()); if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL) continue; profitCloseSell += m_position.Profit(); m_trade.PositionClose(PositionGetInteger(POSITION_TICKET)); } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnClickButton2(void) { Print("Button 2 clicked!"); int totalPositions = PositionsTotal(); for(int i = totalPositions - 1; i >= 0; i--) { string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) Print(m_position.PositionType()); if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY) continue; profitCloseBuy += m_position.Profit(); m_trade.PositionClose(PositionGetInteger(POSITION_TICKET)); } } #property indicator_chart_window #property indicator_color1 Pink //±-----------------------------------------------------------------+ //| Expert tick function | //±-----------------------------------------------------------------+ void OnTick() { ExtDialog.UpdateProfitLabel(); double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID); // Отправляем алерты при достижении указанных уровней if(!belowLevelAlerted && bidPrice <= BelowCurrentPriceLevel) { Alert("Цена достигла уровня BelowCurrentPriceLevel"); belowLevelAlerted = true; // Отмечаем, что алерт был отправлен } if(!aboveLevelAlerted && askPrice >= AboveCurrentPriceLevel) { Alert("Цена достигла уровня AboveCurrentPriceLevel"); aboveLevelAlerted = true; // Отмечаем, что алерт был отправлен } datetime currentTime = TimeCurrent(); // Текущее время сервера MqlRates rates[]; if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0) // Получаем последний бар для H1 { datetime newBarTime = rates[0].time; // Время начала последнего бара if(newBarTime != lastBarTime) { if(MathAbs(bidPrice - lastPrice) > PipsToChange * _Point) { // Подсчитаем новый размер лота CalculateAndSetLotSize(); lastPrice = bidPrice; // Обновление последней цены // Открываем новые ордера с новым размером лота OpenOrder(ORDER_TYPE_BUY, currentLots, "B"); OpenOrder(ORDER_TYPE_SELL, currentLots, "S"); } lastBarTime = newBarTime; // Обновляем время начала последнего бара } } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OpenOrder(ENUM_ORDER_TYPE type, double lots, string orderMagic) { MqlTradeRequest request = {}; MqlTradeResult result = {}; // Заполнение полей структуры запроса на сделку request.action = TRADE_ACTION_DEAL; request.symbol = _Symbol; request.volume = lots; request.type = type; request.sl = 0.0; // Уровень стоп-лосс не задан request.tp = 0.0; // Уровень тейк-профит не задан request.deviation = 0; request.magic = StringToInteger(orderMagic + IntegerToString(GetTickCount())); //request.comment = "Auto trade order"; if(type == ORDER_TYPE_BUY) request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); else if(type == ORDER_TYPE_SELL) request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID); if(!OrderSend(request,result)) PrintFormat("OrderSend error %d",GetLastError()); // Попытка отправить торговый запрос } //+------------------------------------------------------------------+ у меня есть такая программа но почему она не всегда отправляет ордер?
a8a8923052f58e5f1abcfead48da7ebc
{ "intermediate": 0.34829118847846985, "beginner": 0.3364187180995941, "expert": 0.31529009342193604 }
41,288
Hi, I am working in Linux environment using Portaudio to connect a realtime process to the audio card. There is a way to collect any xrun that can occur, like a logging mechanism?
c975757460e210548077af0d9f3418fa
{ "intermediate": 0.619583785533905, "beginner": 0.20962797105312347, "expert": 0.17078827321529388 }
41,289
tell me about the tokio send+sync boiunbd
fb34f1dadd05f5524714cb7b403c6476
{ "intermediate": 0.46245497465133667, "beginner": 0.09895333647727966, "expert": 0.4385916590690613 }
41,290
Input 3 8 12 14 15 13 98 14 15 97 Output 4 0 3 5 6 The longest subsequence containing continuous numbers is (12 13 14 15). Note 14,15 at indexes 1,2 respectively can NOT form the longest subsequence. There is only one correct answer for this input. Hints You can break this problem into two parts. First find any subsequence of maximum length. hen think of tracking its indexes.\ Though this may look similar to the longest common subsequence with 1.2...n. it is not the same problem.\ Hash tables might be needed with some other concepts vou've learned in Pro/DSA to solve this problem : i need c program for this
269b2187e861b5e3137d3c917c555112
{ "intermediate": 0.3667163848876953, "beginner": 0.24136558175086975, "expert": 0.3919179439544678 }
41,291
check this code: pub fn parse_tracks<'a>(contents: &'a str) -> Result<TranscriptMap, &'static str> { let read2track: Arc<DashMap<Arc<str>, Arc<str>>> = Arc::new(DashMap::new()); let mut tracks = contents .par_lines() .filter(|x| !x.starts_with("#")) .filter_map(|x| Record::new(x).ok()) .fold( || HashMap::new(), |mut acc: HashMap<Chromosome, Vec<Transcript>>, record| { // let mut ps_acc = pseudomap.entry(record.chrom.clone()).or_insert(Vec::new()); read2track.insert(Arc::from(record.info.3.clone()), Arc::from(record.line)); acc.entry(record.chrom).or_default().push(record.info); acc }, ) .reduce( || HashMap::new(), |mut acc, map| { for (k, v) in map { let acc_v = acc.entry(k).or_insert(Vec::new()); acc_v.extend(v); } acc }, ); tracks.par_iter_mut().for_each(|(_, v)| { v.par_sort_unstable_by_key(|x| (x.0, x.1)); }); info!("Parsed {} tracks.", tracks.values().flatten().count()); Ok(tracks) } do you think this is the best way to fill up read2track? should be better to fold and reduce also? do you have a better approach? what is the benefit of using Arc<str> here?
1ea4eec175141caaf4f14ac83d72bedf
{ "intermediate": 0.5427587628364563, "beginner": 0.2686747610569, "expert": 0.18856647610664368 }
41,292
Create a script to each kids learn abc
71299ca1315baaca1a3146c00773c3f9
{ "intermediate": 0.2897193431854248, "beginner": 0.38423025608062744, "expert": 0.3260503113269806 }
41,293
gitlab runner change value of variable in scri
2400b0d90322264cc325892a8a036d77
{ "intermediate": 0.41045501828193665, "beginner": 0.3573365807533264, "expert": 0.23220840096473694 }
41,294
bash store contenue of file in varibale and trim space
2ace06442b3b2188009393f86e2f8cfd
{ "intermediate": 0.35692745447158813, "beginner": 0.31098487973213196, "expert": 0.3320876955986023 }
41,295
Generate 10 numbers with seed: 1
b6c5ec92ba8d38d80c6844a50b30c388
{ "intermediate": 0.27485838532447815, "beginner": 0.18954528868198395, "expert": 0.5355963706970215 }
41,296
Generate 10 numbers with seed: 1, length is 0-1000000000
02e50cfc7576e74a0b87ea554c0c0be2
{ "intermediate": 0.25895029306411743, "beginner": 0.16870249807834625, "expert": 0.5723472833633423 }
41,297
Describe accurate seed-based number generator
dbb78676b34d9cab2a30ba4e2a247c70
{ "intermediate": 0.15728026628494263, "beginner": 0.1156541258096695, "expert": 0.7270655632019043 }
41,298
hello
4a098259d7bdf221dd30af3e04a02aa4
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
41,299
hello
45ec7194e7297c7c0fee287904bf70ef
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
41,300
Wireless Tire Pressure Monitoring System: using esp 32 my project to include parameters to measure: 1) Temperature Monitoring: Besides pressure, tire temperature is a key factor affecting tire performance. High temperatures can lead to tire blowouts. Including temperature sensors can provide early warnings of potential issues. 2) Tire Tread Depth Monitoring: As tires wear down, their tread depth decreases, which can lead to reduced traction and increased risk of accidents. A sensor that monitors tread depth could alert the driver when tires need to be replaced. 3) Load Detection predicton: Sensors that detect the load of the vehicle and tells the amount of tire pressure needed accordingly, which should improve vehicle handling and fuel efficiency. 4) Real-time Analytics: Advanced algorithms could analyze tire performance data over time to predict future failures or suggest optimal times for maintenance. 5) Smart Connectivity: Connecting the TPMS to a smartphone app or the vehicle's infotainment system could provide detailed insights, historical data, and allow for remote monitoring. 6) Advanced Warning and Recommendations: The system could provide not just alerts for low pressure, but also recommendations on nearest service stations or offer to schedule maintenance appointments. 7) Tire Health Report: A periodic report on the health of the tires, the TPMS could monitor the effectiveness of the seal and advise on permanent and temporary repairs.. Predictive Maintenance and Machine Learning: Employing machine learning algorithms to analyze historical data and predict when tires are likely to fail or need service. what are the components needed and can you give me block diagram
91a2f8a460027b5c3523d6a2db58adca
{ "intermediate": 0.2466568499803543, "beginner": 0.21052785217761993, "expert": 0.5428152680397034 }
41,301
[opc@pdr-cregas reportesGN]$ cat matrizGNC.jsp <%@page contentType="text/html; charset=iso-8859-1" language="java" errorPage="errorpage.jsp" import="java.sql.*,co.gov.creg.util.*" %> <%@page import="co.gov.creg.BuilderHTML.*"%> <% /** * @author CREG, 05-05-2003 * @author CREG, 06-05-2003 * modify CREG, 11-01-2008 * modify CREG, 20-01-2008 * modify CREG, 09-03-2010 * modify CREG AE, 22-01-2021 * modify CREG AE, 04-02-2022 * modify CREG AE, 30-01-2023 */ String depOrig = (request.getParameter("depOrig")!=null)?request.getParameter("depOrig"):new String("05000"); String depDes = (request.getParameter("depDes")!=null)?request.getParameter("depDes"):new String("05000"); String origen = (request.getParameter("origen")!=null)?request.getParameter("origen"):new String("05001"); String destino = (request.getParameter("destino")!=null)?request.getParameter("destino"):new String("05001"); String vehiculo = (request.getParameter("vehiculo")!=null)?request.getParameter("vehiculo"):new String("CIL_UNI"); double fIpc2023 = 378.11; double fIpc2022 = 346.01; double fIpc2021 = 305.87;//04-02-2021 double fIpc2020 = 289.59;//22-01-2021 double fIpc2019 = 284.98;//17-01-2020 double fIpc2018 = 274.55;//14-01-2019 double fIpc2017 = 266.08;//17-01-2018 double fIpc2016 = 255.63;//11-01-2017 double fIpc2015 = 241.74;//21-01-2016 double fIpc2014 = 226.410845;//16-01-2014 double fIpc2013 = 218.419874;//15-01-2014 double fIpc2012 = 214.28;//10-01-2013 double fIpc2011 = 209.18;//11-01-2012 double fIpc2010 = 201.67;//13-01-2011 double fIpc2009 = 195.46;//09-03-2010 double fIpc2008 = 191.63;//20-01-2008 double fIpc2007 = 177.97; double fIpc2006 = 168.38; double fIpc2005 = 161.16; double fIpc2004 = 153.7; double fIpc2003 = 145.69; double fIpc2002 = 136.81; %> <html> <head> <title>Reporte</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <LINK REL=STYLESHEET TYPE="text/css" HREF="css/estilos.css"> </head> <body class="page"><b><font face="arial" size="1" color="#000000"> <div align="center"> <form action="" method='post' > <table width="90%"> <tr> <td>&nbsp;</td> </tr> <tr > <td ALIGN="CENTER" class="roweven"> <strong> Costos de Transporte Para GNC. </strong> </td> </tr> </table> <table width="427" align="cent<th align="left"><b> </b> </th> <tr> <td width="205">&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> </table > <table width="427" align="center"> <tr> <td colspan="2" align="left" class="roweven2"><div align="center">Origen</div></td> <td colspan="2" align="left" class="roweven2"><div align="center">Destino</div></td> </tr> <tr > <% TSelectHtmlDB SDBDepOrig=new TSelectHtmlDB("<select name=\"depOrig\" onchange=\"javascript:submit();\">","glp"); { String SentenciaSQL="Select Dep.A50CODIGO_DANE,Dep.A50NOMBRE from ADMIN.T50DEPARTAMENTO Dep"; SDBDepOrig.GenerarOpciones(SentenciaSQL,"A50CODIGO_DANE","A50NOMBRE",depOrig); } %> <td align="left" width="101" class="roweven2"> Departamento: </td> <td align="left" width="101" class="roweven2"> <%=SDBDepOrig.PrintSelect()%> </td> <% TSelectHtmlDB SDBDepDes=new TSelectHtmlDB("<select name=\"depDes\" onchange=\"javascript:submit();\">","glp"); { String SentenciaSQL="Select Dep.A50CODIGO_DANE,Dep.A50NOMBRE from ADMIN.T50DEPARTAMENTO Dep"; SDBDepDes.GenerarOpciones(SentenciaSQL,"A50CODIGO_DANE","A50NOMBRE",depDes); } %> <td align="left" width="101" class="roweven2"> Departamento: </td> <td align="left" width="107" class="roweven2"> <%=SDBDepDes.PrintSelect()%> </td> </tr> <tr> <% TSelectHtmlDB SDBCiuOri=new TSelectHtmlDB("<select name=\"origen\">","glp"); { String SentenciaSQL="Select Ciu.A51CODIGO_DANE,Ciu.A51NOMBRE from ADMIN.T51MUNICIPIO Ciu"; SentenciaSQL+=" Where Ciu.A03CODIGO_DEPARTAMENTO='"+depOrig+"'"; SDBCiuOri.GenerarOpciones(SentenciaSQL,"A51CODIGO_DANE","A51NOMBRE",origen); } %> <td align="left" width="101" class="roweven2"> Ciudad: </td> <td align="left" width="101" class="roweven2"> <%=SDBCiuOri.PrintSelect()%> </td> <% TSelectHtmlDB SDBCiuDes=new TSelectHtmlDB("<select name=\"destino\" >","glp"); { String SentenciaSQL="Select Ciu.A51CODIGO_DANE,Ciu.A51NOMBRE from ADMIN.T51MUNICIPIO Ciu"; SentenciaSQL+=" Where Ciu.A03CODIGO_DEPARTAMENTO='"+depDes+"'"; SDBCiuDes.GenerarOpciones(SentenciaSQL,"A51CODIGO_DANE","A51NOMBRE",destino); } %> <td align="left" width="101" class="roweven2"> Ciudad: </td> <td align="left" width="107" class="roweven2"> <%=SDBCiuDes.PrintSelect()%> </td> </tr> </table> <table> <tr> <td>&nbsp;</td> </tr> <tr> <td align='center' class="roweven2"> Vehiculo: </td> <td align='center' class="roweven2"> <% TSelectHtml SelectPesoCilindro=new TSelectHtml("<select name=\"vehiculo\">"); SelectPesoCilindro.GenerarOpcion("CIL_UNI","No Articulado",vehiculo.equals("CIL_UNI")?true:false); SelectPesoCilindro.GenerarOpcion("CIL_ART","Articulado",vehiculo.equals("CIL_ART")?true:false); %> <%=SelectPesoCilindro.PrintSelect()%> <!-- <select name='pesoCilindro'> <option value='8.79'>20 lbs</option> <option value='13.2'>30 lbs</option> <option value='14.08'>40 lbs</option> <option value='24.8'>80 lbs</option> <option value='35.19'>100 lbs</option> </select> --> &nbsp;&nbsp;<INPUT type='submit' name='Consultar' value='Consultar'/> </td> </tr> </table> <table> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td> <center> <table border="0" cellpadding="4" class="table"> <tr> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Depto</font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="coleven">Mpio</font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Depto</font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="coleven">Mpio</font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2004 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2005 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2006 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2007 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2008 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2009 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2010 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2011 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2012 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2013 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2014 $/m<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2015 $/M<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2016 $/M<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2017 $/M<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2018 $/M<sup>3</sup></font> </b> </th></th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2019 $/M<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2020 $/M<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2021 $/M<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2022 $/M<sup>3</sup></font> </b> </th> <th align="left"><b><font face="arial" size="1" color="#006699" class="colodd">Costo IPC DIC 2023 $/M<sup>3</sup></font> </b> </th> </tr> <% if (origen != null && destino != null) { DBQuery dbq = null; try { dbq = new DBQuery("glp"); String sQuery = "SELECT DORIG.A50NOMBRE DORIGEN, " + " ORIG.A51NOMBRE MORIGEN, " + " DDEST.a50nombre DDESTINO, " + " DEST.a51nombre MDESTINO, " + " COSTO " + " FROM " + "( " + "select ORIGEN ORIGEN, " + " DESTINO DESTINO, " + " "+vehiculo+" COSTO " + "FROM T31COSTOS_TRANSPORTE " + "WHERE ORIGEN = '" + origen + "' " + "AND DESTINO = '" + destino + "' " + "UNION " + "select DESTINO ORIGEN, " + " ORIGEN DESTINO, " + " "+vehiculo+" COSTO " + "FROM T31COSTOS_TRANSPORTE " + "WHERE ORIGEN = '" + destino + "' " + " AND DESTINO = '" + origen + "' " + ") INNER JOIN ADMIN.T51MUNICIPIO ORIG ON ORIGEN = ORIG.A51CODIGO_DANE " + " INNER JOIN ADMIN.T50DEPARTAMENTO DORIG ON ORIG.A03CODIGO_DEPARTAMENTO = DORIG.A50CODIGO_DANE " + " INNER JOIN ADMIN.T51MUNICIPIO DEST ON DESTINO = DEST.A51CODIGO_DANE " + " INNER JOIN ADMIN.T50DEPARTAMENTO DDEST ON DEST.A03CODIGO_DEPARTAMENTO = DDEST.A50CODIGO_DANE"; ResultSet rs = dbq.executeQuery(sQuery); String temp = ""; String rowClassOdd = "rowodd"; String rowClassEven = "roweven"; String rowClass = ""; int nRow = 0; while(rs.next()) { nRow++; if (nRow % 2 == 0) rowClass = rowClassEven; else rowClass = rowClassOdd; %> <tr class="<%= rowClass %>"> <td class="colodd"><b><font face="arial" size="1" color="#000000"><%= rs.getString("DORIGEN") %></font> </b> </td> <td class="coleven"><b><font face="arial" size="1" color="#000000"><%= rs.getString("MORIGEN") %></font> </b> </td> <td class="colodd"><b><font face="arial" size="1" color="#000000"><%= rs.getString("DDESTINO") %></font> </b> </td> <td class="coleven"><b><font face="arial" size="1" color="#000000"><%= rs.getString("MDESTINO") %></font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2004/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2005/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2006/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2007/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2008/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2009/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2010/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2011/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2012/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2013/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2014/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2015/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2016/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2017/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2018/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2019/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2020/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2021/fIpc2002))%> </font> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2022/fIpc2002))%> </font> </b> </td> <td class="colodd" align="right"><b><font face="arial" size="1" color="#000000"> <%= util.formatear(rs.getDouble("COSTO")*0.012*(fIpc2023/fIpc2002))%> </font> </b> </td> </tr> <% } } catch (Exception ex) { if (dbq != null) dbq.closeAll(); if (ex.getMessage() == null) throw new Exception("Error al tratar de consultar costos.<BR>"); else throw new Exception("Error al tratar de consultar costos.<BR>" + ex.getMessage()); } if (dbq != null) dbq.closeAll(); } %> </table> </center> </td> </tr> </table> </form> </div> </font> </b> </body> </html> Mar 5, 2024 5:10:54 PM co.gov.creg.util.DBConnectionManager2 getConnection SEVERE: null org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (IO Error: The Network Adapter could not establish the connection) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1225) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880) at co.gov.creg.util.DBConnectionManager2.getConnection(DBConnectionManager2.java:96) at co.gov.creg.util.DBQuery.<init>(DBQuery.java:40) at org.apache.jsp.matrizGNC_jsp._jspService(matrizGNC_jsp.java:342) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:835) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:640) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1286) at java.lang.Thread.run(Thread.java:662) Caused by: java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743) at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:662) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:560) at org.apache.tomcat.dbcp.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38) at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1247) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1221) ... 22 more Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:470) at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:506) at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595) at oracle.net.ns.NSProtocol.connect(NSProtocol.java:230) at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496) ... 29 more Caused by: java.net.NoRouteToHostException: No route to host at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:161) at oracle.net.nt.ConnOption.connect(ConnOption.java:159) at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:428) ... 34 more ayudame a arreglar este error ten en cuenta que es apache tomcat 5.5
fe835390463d74d46eb9a53c17df1842
{ "intermediate": 0.30824440717697144, "beginner": 0.4334823787212372, "expert": 0.2582731544971466 }
41,302
Converting circular structure to JSON --> starting at object with constructor 'Vue' | property '$options' -> object with constructor 'Object' | property 'router' -> object with constructor 'VueRouter' --- property 'app' closes the circle в чем ошибка?
d5b6aab9d9fc289b3224cdc02e665f82
{ "intermediate": 0.48347437381744385, "beginner": 0.3314097225666046, "expert": 0.18511593341827393 }
41,303
this is my code: import yfinance as yf import pandas as pd import itertools # Define the period for data retrieval data_period = '10d' # You can change this to '10d', '1mo', '1y', etc. # Define the trade type (long or short) trade_type = 'long' # You can change this to 'short' # Define the take profit and stop loss targets in dollar amounts take_profit_target = 100 # You can adjust this as needed stop_loss_target = 100 # You can adjust this as needed # Define the number of units to trade units = 10000 # Download historical data for AUD/USD with a 5-minute interval data_5min = yf.download('AUDUSD=X', period=data_period, interval='5m') # Download historical data for AUD/USD with an hourly interval data_hourly = yf.download('AUDUSD=X', period=data_period, interval='60m') # Function to find the next available hour def find_next_available_hour(data, start_hour): for i in range(start_hour, 24): data_hour = data.loc[data.index.hour == i] if not data_hour.empty: return data_hour.iloc[:1] # Return a DataFrame with a single row return pd.DataFrame() # Return an empty DataFrame if no data is found # Function to find the next available 5-minute interval def find_next_available_interval(data, start_minute): for i in range(start_minute, 288): # 288 intervals in a trading day data_interval = data.iloc[i] if not pd.isnull(data_interval['Open']): return data_interval return pd.Series() # Return an empty Series if no data is found # Function to calculate total profit for a given combination of trade execution hour, trade closing hour, take profit interval, and stop loss interval def calculate_total_profit(data_hourly, data_5min, exec_hour, close_hour, take_profit_interval, stop_loss_interval, trade_type, take_profit, stop_loss, units): total_profit = 0 total_take_profit = 0 total_stop_loss = 0 total_close_profit = 0 trade_count = 0 for i in range(exec_hour, close_hour): data_exec = find_next_available_hour(data_hourly, i) data_close = find_next_available_hour(data_hourly, i+1) for j in range(len(data_exec)): open_price = data_exec.iloc[j]['Open'] close_price = data_close.iloc[j]['Close'] # Calculate the take profit and stop loss levels based on the open price and the profit/loss targets take_profit_level = open_price + (take_profit / units) stop_loss_level = open_price - (stop_loss / units) # Initialize trade_closed variable trade_closed = False # Check if the take profit or stop loss is hit at the specified intervals take_profit_hit = False stop_loss_hit = False for k in range(j * 12, (j + 1) * 12): # 12 intervals in an hour data_interval = data_5min.iloc[k] if not pd.isnull(data_interval['Open']): if trade_type == 'long': if data_interval['High'] >= take_profit_level: take_profit_hit = True close_price = data_interval['High'] trade_closed = True break elif data_interval['Low'] <= stop_loss_level: stop_loss_hit = True close_price = data_interval['Low'] trade_closed = True break elif trade_type == 'short': if data_interval['Low'] <= take_profit_level: take_profit_hit = True close_price = data_interval['Low'] trade_closed = True break elif data_interval['High'] >= stop_loss_level: stop_loss_hit = True close_price = data_interval['High'] trade_closed = True break if trade_closed: trade_count += 1 profit = units * (close_price - open_price) if trade_type == 'long' else units * ( open_price - close_price) total_profit += profit if take_profit_hit: total_take_profit += profit elif stop_loss_hit: total_stop_loss += profit elif j == len(data_exec) - 1: # Check if it's the last trade of the day trade_count += 1 profit = units * (close_price - open_price) if trade_type == 'long' else units * ( open_price - close_price) total_profit += profit total_close_profit += profit return total_take_profit, total_stop_loss, total_close_profit, total_profit, trade_count # Find the combination of trade execution hour, trade closing hour, take profit interval, and stop loss interval that gives the highest total profit max_profit = 0 best_exec_hour = None best_close_hour = None best_take_profit_interval = None best_stop_loss_interval = None best_total_take_profit = None best_total_stop_loss = None best_total_close_profit = None for exec_hour, close_hour in itertools.product(range(24), repeat=2): if exec_hour >= close_hour: continue for take_profit_interval, stop_loss_interval in itertools.product(range(12), repeat=2): if take_profit_interval <= stop_loss_interval: continue take_profit = (take_profit_target / units) stop_loss = (stop_loss_target / units) total_take_profit, total_stop_loss, total_close_profit, total_profit, trade_count = calculate_total_profit(data_hourly, data_5min, exec_hour, close_hour, take_profit_interval, stop_loss_interval, trade_type, take_profit, stop_loss, units) avg_profit_per_trade = total_profit / trade_count if trade_count > 0 else 0 if avg_profit_per_trade > max_profit: max_profit = avg_profit_per_trade best_exec_hour = exec_hour best_close_hour = close_hour best_take_profit_interval = take_profit_interval best_stop_loss_interval = stop_loss_interval best_total_take_profit = total_take_profit best_total_stop_loss = total_stop_loss best_total_close_profit = total_close_profit print(f"Best trade execution hour: {best_exec_hour}") print(f"Best trade closing hour: {best_close_hour}") print(f"Best take profit interval: {best_take_profit_interval * 5} minutes") print(f"Best stop loss interval: {best_stop_loss_interval * 5} minutes") print(f"Maximum average profit per trade: {max_profit}") print(f"Total profit from take profit: {best_total_take_profit}") print(f"Total loss from stop loss: {best_total_stop_loss}") print(f"Total profit or loss not triggered from take profit or stop loss: {best_total_close_profit}") this is result i got: Best trade execution hour: 18 Best trade closing hour: 19 Best take profit interval: 5 minutes Best stop loss interval: 0 minutes Maximum average profit per trade: 13.421177864074707 Total profit from take profit: 13.421177864074707 Total loss from stop loss: 0 Total profit or loss not triggered from take profit or stop loss: 0 it seems wrong as it means it does only one trade, but regardless of how trade closed, once the trade closed it should execute another trade. please give me whole modified code.
a2c2ab94bb86e56f9b718161f4efdf4c
{ "intermediate": 0.3689572811126709, "beginner": 0.285440593957901, "expert": 0.3456020653247833 }
41,304
I am making a C++ SDL based game engine, currently I am finishing my final touches of my current release, Help me finish them. First, my circle class I need to make two Methods: bool ContainsPoint(const Point& point) const; // For collision detection bool IntersectsCircle(const Circle& other) const; // To check circle-circle collision My class is structured like this: class Circle { public: Circle(int centerX, int centerY, int radius); Circle(const Point& center, int radius); virtual ~Circle(); const Point& GetCenter() const; void SetCenter(const Point& center); int GetRadius() const; void SetRadius(int radius); void GetPoints(std::vector<Point>& outPoints) const; private: Point center; int radius; }; What I plan on doing is using GetPoints to get the current circle points to do both of these new methods, how can I do that?
e0adb7e6ae9f81e3eea666bdd6e1bd29
{ "intermediate": 0.40160658955574036, "beginner": 0.3460557460784912, "expert": 0.2523376941680908 }
41,305
how to upload pdf using terminal
e3a95c00b430008e93c2fb18be607623
{ "intermediate": 0.38701316714286804, "beginner": 0.30072689056396484, "expert": 0.3122599422931671 }
41,306
You're a docker expert. Take a look at this script and make a basic template for the installation https://raw.githubusercontent.com/magnussolution/magnusbilling7/source/script/install.sh
f1c03904d80be5afaa150ee4d7b1c8e1
{ "intermediate": 0.2085568606853485, "beginner": 0.4667493999004364, "expert": 0.3246937096118927 }
41,307
Hi, in C++ I have a single server, that hold and write the data into a buffer, and multi clients, that ask to the server to provide them the data. What is the best design for this scenario?
2b24f29ab3a637055f49459464127fae
{ "intermediate": 0.491628497838974, "beginner": 0.17367024719715118, "expert": 0.334701269865036 }
41,308
What difference between socket.send() and socket.sendall() in Python? Tell in simple language
94f1eaedc32ddc036e0e0d98f77e4d34
{ "intermediate": 0.4914499819278717, "beginner": 0.23121511936187744, "expert": 0.27733492851257324 }
41,309
-- login_client.lua local soundElementData = "mySoundElement" screenWidth,screenHeight = guiGetScreenSize() mainWidth,mainHeight = 1300,600 regWidth,regHeight = 800,688 -- Создаем статическое изображение размером 30% от размера экрана local screenWidth, screenHeight = guiGetScreenSize() -- получаем размер экрана local imageWidth, imageHeight = screenWidth*0.3, screenHeight*0.3 -- устанавливаем размер изображения на 30% от размера экрана backgroundImage = guiCreateStaticImage(screenWidth/2 - imageWidth/2, screenHeight/2 - imageHeight/2, imageWidth, imageHeight, "images/reglog_pic.png", false) -- создаем жирный шрифт local boldFont = guiCreateFont("ljk_Adventure.ttf", 20) -- создаем метки "Логин" и "Пароль" поверх изображения local loginLabel = guiCreateLabel(0.1, 0.15, 0.8, 0.1, "Логин:", true, backgroundImage) local passwordLabel = guiCreateLabel(0.1, 0.45, 0.8, 0.1, "Пароль:", true, backgroundImage) -- применяем жирный шрифт к меткам guiSetFont(loginLabel, boldFont) guiSetFont(passwordLabel, boldFont) -- центрируем текст меток guiLabelSetHorizontalAlign(loginLabel, "center") guiLabelSetHorizontalAlign(passwordLabel, "center") -- создаем поля для ввода логина и пароля поверх изображения usernameField = guiCreateEdit(0.1, 0.25, 0.8, 0.15, "", true, backgroundImage) passwordField = guiCreateEdit(0.1, 0.55, 0.8, 0.15, "", true, backgroundImage) -- создаем кнопки "Логин" и "Регистрация" поверх изображения loginButton = guiCreateButton(0.1, 0.75, 0.35, 0.15, "Войти", true, backgroundImage) registerButton = guiCreateButton(0.55, 0.75, 0.35, 0.15, "Регистрация", true, backgroundImage) -- Изначально все элементы GUI выключены guiSetVisible(backgroundImage, false) function loginPanel() Ck_racing1 = guiCreateLabel (1300,730,1280,40,"",false,mainWindow) guiLabelSetVerticalAlign(Ck_racing1,"center") guiLabelSetHorizontalAlign(Ck_racing1,"center",false) guiSetFont (Ck_racing1,"clear-normal") guiLabelSetColor(Ck_racing1,0,0,0) local table = {{255, 0, 0},{255, 255, 255},{255,100, 100},{100, 100, 100}} setTimer( function () guiLabelSetColor( Ck_racing1, unpack(table[math.random(#table)]) ) end , 1000, 0 ) setPlayerHudComponentVisible("radar",false) setPlayerHudComponentVisible("area_name",false) toggleControl("radar",false) showChat(false) local PositionX,PositionY,PositionZ = 2067.5349,41.928261,34.788815; local LookAtX,LookAtY,LookAtZ = 2067.5349,41.928261,34.788815; setCameraMatrix(PositionX,PositionY,PositionZ,LookAtX,LookAtY,LookAtZ) fadeCamera(true) function CameraPosition () PositionX = PositionX+0.03; LookAtX = LookAtX+0.3; setCameraMatrix(PositionX,PositionY,PositionZ,LookAtX,LookAtY,LookAtZ) end addEventHandler("onClientPreRender",getRootElement(),CameraPosition) mainWindow = guiCreateStaticImage(screenWidth/2-mainWidth/2,screenHeight/2-mainHeight/2,mainWidth,mainHeight,"images/logo.png",false) btnLogin = guiCreateStaticImage(400,400,484,148,"images/play.png",false,mainWindow) guiSetProperty(btnLogin, "NormalTextColour", "FFFF0000") guiSetFont(btnLogin,"clear-normal") guiSetVisible(mainWindow,true) guiSetInputEnabled(true) showCursor(true) addEventHandler("onClientGUIClick",btnLogin,onClickLogin) end addEventHandler("onClientResourceStart",getResourceRootElement(getThisResource()),loginPanel) -- обработчик события нажатия на кнопку "btnLogin" function onClickLogin(button,state) if(button == "left" and state == "up") then if (source == btnLogin) then playSound("sounds/sfx/button.mp3") guiSetVisible(mainWindow, false) -- закрываем основное окно guiSetVisible(backgroundImage, true) -- открываем окно для ввода логина и пароля end end end -- обработчики событий нажатия на кнопки "Логин" и "Регистрация" addEventHandler("onClientGUIClick", loginButton, function() local username = guiGetText(usernameField) local password = guiGetText(passwordField) playSound("sounds/sfx/enterserver.mp3") if username ~= "" and password ~= "" then triggerServerEvent("onRequestEnter", getLocalPlayer(), username, password) else outputChatBox("Вы должны ввести имя пользователя и пароль.") -- exports.notyf_system:badnotyShow("Вы должны ввести имя пользователя и пароль!", source) end end ) -- Создание GUI с иконками ВК, Ютуб и Телеграм -- local iconGUI = guiCreateStaticImage(screenWidth / 2 - 80, screenHeight - 64, 160, 64, "images/blank.png", false) -- Создание кнопок с иконками local buttonvk = guiCreateStaticImage(screenWidth / 2 - 70, screenHeight - 50, 32, 32, "images/vk_button.png", false, iconGUI) local buttonyt = guiCreateStaticImage(screenWidth / 2 - 30, screenHeight - 50, 32, 32, "images/yt_button.png", false, iconGUI) local buttontg = guiCreateStaticImage(screenWidth / 2 + 10, screenHeight - 50, 32, 32, "images/tg_button.png", false, iconGUI) function openBrowserURL(url) local browser = guiCreateBrowser(0, 0, 800, 600, true, true, false) guiSetBrowserURL(browser, url) end -- Oбработчики событий для кликов по иконкам addEventHandler("onClientGUIClick", buttonvk, function(button, state) if button == "left" and state == "up" then outputChatBox("Нажал на ВК.") playSound("sounds/sfx/button.mp3") openBrowserURL("https://vk.com/yourpage") loadBrowserURL( browser, "https://www.youtube.com/" ) end end, false) addEventHandler("onClientGUIClick", buttonyt, function(button, state) if button == "left" and state == "up" then outputChatBox("Нажал на ЮТУБ.") playSound("sounds/sfx/button.mp3") openBrowserURL("https://www.youtube.com/channel/yourchannel") loadBrowserURL( browser, "https://www.youtube.com/" ) end end, false) addEventHandler("onClientGUIClick", buttontg, function(button, state) if button == "left" and state == "up" then outputChatBox("Нажал на ТЕЛЕГУ.") playSound("sounds/sfx/button.mp3") openBrowserURL("https://t.me/yourtelegram") loadBrowserURL( browser, "https://www.youtube.com/" ) end end, false) -- GUI для регистрации registerGUI = guiCreateStaticImage(screenWidth/2 - imageWidth/2, screenHeight/2 - imageHeight/2, imageWidth, imageHeight, "images/reglog_pic.png", false) local registerUsernameLabel = guiCreateLabel(0.1, 0.05, 0.8, 0.1, "Логин:", true, registerGUI) local emailLabel = guiCreateLabel(0.1, 0.25, 0.8, 0.1, "Почта:", true, registerGUI) local registerPasswordLabel = guiCreateLabel(0.1, 0.45, 0.8, 0.1, "Пароль:", true, registerGUI) local confirmPasswordLabel = guiCreateLabel(0.1, 0.65, 0.8, 0.1, "Повторите пароль:", true, registerGUI) guiSetFont(registerUsernameLabel, boldFont) guiSetFont(emailLabel, boldFont) guiSetFont(registerPasswordLabel, boldFont) guiSetFont(confirmPasswordLabel, boldFont) guiLabelSetHorizontalAlign(registerUsernameLabel, "center") guiLabelSetHorizontalAlign(emailLabel, "center") guiLabelSetHorizontalAlign(registerPasswordLabel, "center") guiLabelSetHorizontalAlign(confirmPasswordLabel, "center") registerUsernameField = guiCreateEdit(0.1, 0.15, 0.8, 0.08, "", true, registerGUI) emailField = guiCreateEdit(0.1, 0.35, 0.8, 0.08, "", true, registerGUI) registerPasswordField = guiCreateEdit(0.1, 0.55, 0.8, 0.08, "", true, registerGUI) confirmPasswordField = guiCreateEdit(0.1, 0.75, 0.8, 0.08, "", true, registerGUI) local backButton = guiCreateButton(0.1, 0.85, 0.35, 0.1, "Назад", true, registerGUI) local confirmRegisterButton = guiCreateButton(0.55, 0.85, 0.35, 0.1, "Зарегистрироваться", true, registerGUI) guiSetEnabled(backButton, false) guiSetEnabled(confirmRegisterButton, false) guiSetVisible(registerGUI, false) addEventHandler("onClientGUIClick", registerButton, function() playSound("sounds/sfx/button.mp3") guiSetVisible(backgroundImage, false) guiSetVisible(buttonvk, false) guiSetVisible(buttonyt, false) guiSetVisible(buttontg, false) guiSetVisible(registerGUI, true) guiSetEnabled(backButton, true) guiSetEnabled(confirmRegisterButton, true) end) addEventHandler("onClientGUIClick", backButton, function() playSound("sounds/sfx/button.mp3") guiSetVisible(registerGUI, false) guiSetVisible(buttonvk, true) guiSetVisible(buttonyt, true) guiSetVisible(buttontg, true) guiSetVisible(backgroundImage, true) guiSetEnabled(backButton, false) guiSetEnabled(confirmRegisterButton, false) end) addEventHandler("onClientGUIClick", confirmRegisterButton, function() playSound("sounds/sfx/button.mp3") local username = guiGetText(registerUsernameField) local email = guiGetText(emailField) local password = guiGetText(registerPasswordField) local confirmPassword = guiGetText(confirmPasswordField) if password == confirmPassword then triggerServerEvent("onRequestRegister", getLocalPlayer(), username, email, password) else exports.notyf_system:badnotyShow("Пароли не совпадают!", source) end end) function hideLoginWindow() removeEventHandler("onClientPreRender", root, CameraPosition) setCameraTarget(getLocalPlayer()) showChat(true) guiSetInputEnabled(false) guiSetVisible(backgroundImage, false) guiSetVisible(registerGUI, false) guiSetVisible(buttonvk, false) guiSetVisible(buttonyt, false) guiSetVisible(buttontg, false) showCursor(false) end addEvent("hideLoginWindow", true) addEventHandler("hideLoginWindow", root, hideLoginWindow) -- МУЗЫКА НА ФОНЕ function startSound() local sounds = {"sounds/loginsong_1.mp3", "sounds/loginsong_2.mp3", "sounds/loginsong_3.mp3"} local randomSound = sounds[math.random(#sounds)] local sound = playSound(randomSound) if not sound then setSoundVolume(sound, 0.2) -- устанавливаем громкость звука на 50% outputChatBox("Ошибка воспроизведения звука: " .. randomSound) -- выводим сообщение об ошибке в чат, если звук не воспроизводится else setElementData(getLocalPlayer(), soundElementData, sound) -- сохраняем элемент звука в элементарных данных end end addEventHandler("onClientResourceStart", getResourceRootElement(getThisResource()), startSound) function stopMySound() local sound = getElementData(getLocalPlayer(), soundElementData) -- получаем элемент звука из элементарных данных if isElement(sound) then destroyElement(sound) removeElementData(getLocalPlayer(), soundElementData) -- удаляем данные элемента после уничтожения звука end end addEventHandler("onClientPlayerSpawn", getLocalPlayer(), stopMySound) -- login_server.lua local function validateCredentials(username, password) if string.len(username) < 4 or string.len(username) > 15 then -- outputChatBox("Имя пользователя должно содержать от 4 до 15 символов", source) exports.notyf_system:badnotyShow("Имя пользователя должно содержать от 4 до 15 символов!", source) return false end if string.len(password) < 4 or string.len(password) > 20 then -- outputChatBox("Пароль должен содержать от 4 до 20 символов", source) exports.notyf_system:badnotyShow("Пароль должен содержать от 4 до 20 символов!", source) return false end if string.match(username, "%W") then -- outputChatBox("Имя пользователя может содержать только буквы и цифры", source) exports.notyf_system:badnotyShow("Имя пользователя может содержать только буквы и цифры!", source) return false end return true end local function isValidEmail(email) if not email then return false end if string.find(email, "^[%w._%-]+@[%w.-]+%.%a+$") then return true end return false end function enterPlayer(username, password) outputConsole("enterPlayer function is called with username: " .. username .. " and password: " .. password) local account = getAccount(username) if (account == false) then -- outputChatBox("Такого аккаунта не существует", source) exports.notyf_system:badnotyShow("Такого аккаунта не существует!", source) return end if not logIn(source, account, password) then -- outputChatBox("Неверный пароль!", source) exports.notyf_system:badnotyShow("Неверный пароль!", source) else triggerClientEvent(source, "hideLoginWindow", getRootElement()) triggerEvent("onPlayerDayZLogin", getRootElement(), username, password, source) end end addEvent("onRequestEnter", true) addEventHandler("onRequestEnter", getRootElement(), function(...) outputConsole("onRequestEnter event is triggered") enterPlayer(...) end) function registerPlayer(username, email, password) if not validateCredentials(username, email, password) then return end if not isValidEmail(email) then exports.notyf_system:badnotyShow("Неправильный формат почты!", source) return end local account = getAccount(username) if account then -- outputChatBox("Аккаунт уже существует", source) exports.notyf_system:badnotyShow("Аккаунт уже существует!", source) else account = addAccount(username, password) logIn(source, account, password) triggerClientEvent(source, "hideLoginWindow", getRootElement()) triggerEvent("onPlayerDayZRegister", getRootElement(), username, password, email, source) triggerClientEvent(source, "openClothingInterface", getRootElement()) end end addEvent("onRequestRegister", true) addEventHandler("onRequestRegister", getRootElement(), registerPlayer) Это код скриптов стороны клиента и сервера с логикой регистрации, авторизации и других мелочей при входе в игру для мультиплеера MTA SAN ANDREAS. Проанализируй код, найди недостатки, ошибки, возможные баги и предложи варианты их исправления.
b05b3d1870f798f62160175701822ef8
{ "intermediate": 0.33653852343559265, "beginner": 0.4437899589538574, "expert": 0.21967151761054993 }
41,310
Create a formula for excel that searches that there is a value in A2 and C2 and if so complete TextJoin
744f8607942091886bc6177895c9b994
{ "intermediate": 0.3430953919887543, "beginner": 0.2205495983362198, "expert": 0.43635499477386475 }
41,311
I am making a C++ SDL based game engine, currently I am finishing my final touches of my current release, Help me finish them. Let's start with the Line class, this is my current implementation: class Line { public: Line(std::vector<Point> points); Line(const Point& start, const Point& end); virtual ~Line(); Point GetStart() const; Point GetEnd() const; std::vector<Point> GetPoints() const; float Length() const; private: std::vector<Point> points; }; First I intended it to be a Polyline class, with an added support for a Line or Line segment. But in another instance of you, you said to me this: The Line class in the context of a game engine is usually designed to represent a simple line or a polyline (sequence of connected segments). However, your Line class seems to be designed to handle both simple line segments (with a start and an end) and polylines (with multiple intermediate points), which can be a bit ambiguous. Here are some considerations and enhancements: 1. Ambiguity: Is the Line class intended to represent a line segment (defined by a start and end point) or a polyline (defined by multiple points)? If it’s meant to represent both, ensure that your API is clear about this to users of your class. Otherwise, consider splitting the functionalities into separate classes like LineSegment and Polyline. 2. Efficiency: Storing multiple points in a std::vector is great for a polyline, but it’s excessive for a simple line segment, which only requires two points. If the class should only represent a line segment, consider storing just the two points instead. It is really that inefficient? Do I really need to separate it into two class?
75a95ed881de2ce89bc5b00a1516aa1f
{ "intermediate": 0.49197661876678467, "beginner": 0.3535490930080414, "expert": 0.15447424352169037 }
41,312
Can you create a formula in excel for the following problem. I have a search term on a spreadsheet (1) that needs to search a range on another spreadsheet (2) and if found will return what is in the cell 2 colums to the left of it
48ac9dc0d1f76411f6d72451040b1c51
{ "intermediate": 0.3659012019634247, "beginner": 0.19158416986465454, "expert": 0.4425146281719208 }
41,313
-- login_client.lua local soundElementData = "mySoundElement" screenWidth,screenHeight = guiGetScreenSize() mainWidth,mainHeight = 1300,600 regWidth,regHeight = 800,688 -- Создаем статическое изображение размером 30% от размера экрана local screenWidth, screenHeight = guiGetScreenSize() -- получаем размер экрана local imageWidth, imageHeight = screenWidth*0.3, screenHeight*0.3 -- устанавливаем размер изображения на 30% от размера экрана backgroundImage = guiCreateStaticImage(screenWidth/2 - imageWidth/2, screenHeight/2 - imageHeight/2, imageWidth, imageHeight, "images/reglog_pic.png", false) -- создаем жирный шрифт local boldFont = guiCreateFont("ljk_Adventure.ttf", 20) -- создаем метки "Логин" и "Пароль" поверх изображения local loginLabel = guiCreateLabel(0.1, 0.15, 0.8, 0.1, "Логин:", true, backgroundImage) local passwordLabel = guiCreateLabel(0.1, 0.45, 0.8, 0.1, "Пароль:", true, backgroundImage) -- применяем жирный шрифт к меткам guiSetFont(loginLabel, boldFont) guiSetFont(passwordLabel, boldFont) -- центрируем текст меток guiLabelSetHorizontalAlign(loginLabel, "center") guiLabelSetHorizontalAlign(passwordLabel, "center") -- создаем поля для ввода логина и пароля поверх изображения usernameField = guiCreateEdit(0.1, 0.25, 0.8, 0.15, "", true, backgroundImage) passwordField = guiCreateEdit(0.1, 0.55, 0.8, 0.15, "", true, backgroundImage) -- создаем кнопки "Логин" и "Регистрация" поверх изображения loginButton = guiCreateButton(0.1, 0.75, 0.35, 0.15, "Войти", true, backgroundImage) registerButton = guiCreateButton(0.55, 0.75, 0.35, 0.15, "Регистрация", true, backgroundImage) -- Изначально все элементы GUI выключены guiSetVisible(backgroundImage, false) function loginPanel() Ck_racing1 = guiCreateLabel (1300,730,1280,40,"",false,mainWindow) guiLabelSetVerticalAlign(Ck_racing1,"center") guiLabelSetHorizontalAlign(Ck_racing1,"center",false) guiSetFont (Ck_racing1,"clear-normal") guiLabelSetColor(Ck_racing1,0,0,0) local table = {{255, 0, 0},{255, 255, 255},{255,100, 100},{100, 100, 100}} setTimer( function () guiLabelSetColor( Ck_racing1, unpack(table[math.random(#table)]) ) end , 1000, 0 ) setPlayerHudComponentVisible("radar",false) setPlayerHudComponentVisible("area_name",false) toggleControl("radar",false) showChat(false) local PositionX,PositionY,PositionZ = 2067.5349,41.928261,34.788815; local LookAtX,LookAtY,LookAtZ = 2067.5349,41.928261,34.788815; setCameraMatrix(PositionX,PositionY,PositionZ,LookAtX,LookAtY,LookAtZ) fadeCamera(true) function CameraPosition () PositionX = PositionX+0.03; LookAtX = LookAtX+0.3; setCameraMatrix(PositionX,PositionY,PositionZ,LookAtX,LookAtY,LookAtZ) end addEventHandler("onClientPreRender",getRootElement(),CameraPosition) mainWindow = guiCreateStaticImage(screenWidth/2-mainWidth/2,screenHeight/2-mainHeight/2,mainWidth,mainHeight,"images/logo.png",false) btnLogin = guiCreateStaticImage(400,400,484,148,"images/play.png",false,mainWindow) guiSetProperty(btnLogin, "NormalTextColour", "FFFF0000") guiSetFont(btnLogin,"clear-normal") guiSetVisible(mainWindow,true) guiSetInputEnabled(true) showCursor(true) addEventHandler("onClientGUIClick",btnLogin,onClickLogin) end addEventHandler("onClientResourceStart",getResourceRootElement(getThisResource()),loginPanel) -- обработчик события нажатия на кнопку "btnLogin" function onClickLogin(button,state) if(button == "left" and state == "up") then if (source == btnLogin) then playSound("sounds/sfx/button.mp3") guiSetVisible(mainWindow, false) -- закрываем основное окно guiSetVisible(backgroundImage, true) -- открываем окно для ввода логина и пароля end end end -- обработчики событий нажатия на кнопки "Логин" и "Регистрация" addEventHandler("onClientGUIClick", loginButton, function() local username = guiGetText(usernameField) local password = guiGetText(passwordField) playSound("sounds/sfx/enterserver.mp3") if username ~= "" and password ~= "" then triggerServerEvent("onRequestEnter", getLocalPlayer(), username, password) else outputChatBox("Вы должны ввести имя пользователя и пароль.") -- exports.notyf_system:badnotyShow("Вы должны ввести имя пользователя и пароль!", source) end end ) -- Создание GUI с иконками ВК, Ютуб и Телеграм -- local iconGUI = guiCreateStaticImage(screenWidth / 2 - 80, screenHeight - 64, 160, 64, "images/blank.png", false) -- Создание кнопок с иконками local buttonvk = guiCreateStaticImage(screenWidth / 2 - 70, screenHeight - 50, 32, 32, "images/vk_button.png", false, iconGUI) local buttonyt = guiCreateStaticImage(screenWidth / 2 - 30, screenHeight - 50, 32, 32, "images/yt_button.png", false, iconGUI) local buttontg = guiCreateStaticImage(screenWidth / 2 + 10, screenHeight - 50, 32, 32, "images/tg_button.png", false, iconGUI) function openBrowserURL(url) local browser = guiCreateBrowser(0, 0, 800, 600, true, true, false) guiSetBrowserURL(browser, url) end -- Oбработчики событий для кликов по иконкам addEventHandler("onClientGUIClick", buttonvk, function(button, state) if button == "left" and state == "up" then outputChatBox("Нажал на ВК.") playSound("sounds/sfx/button.mp3") openBrowserURL("https://vk.com/yourpage") loadBrowserURL( browser, "https://www.youtube.com/" ) end end, false) addEventHandler("onClientGUIClick", buttonyt, function(button, state) if button == "left" and state == "up" then outputChatBox("Нажал на ЮТУБ.") playSound("sounds/sfx/button.mp3") openBrowserURL("https://www.youtube.com/channel/yourchannel") loadBrowserURL( browser, "https://www.youtube.com/" ) end end, false) addEventHandler("onClientGUIClick", buttontg, function(button, state) if button == "left" and state == "up" then outputChatBox("Нажал на ТЕЛЕГУ.") playSound("sounds/sfx/button.mp3") openBrowserURL("https://t.me/yourtelegram") loadBrowserURL( browser, "https://www.youtube.com/" ) end end, false) -- GUI для регистрации registerGUI = guiCreateStaticImage(screenWidth/2 - imageWidth/2, screenHeight/2 - imageHeight/2, imageWidth, imageHeight, "images/reglog_pic.png", false) local registerUsernameLabel = guiCreateLabel(0.1, 0.05, 0.8, 0.1, "Логин:", true, registerGUI) local emailLabel = guiCreateLabel(0.1, 0.25, 0.8, 0.1, "Почта:", true, registerGUI) local registerPasswordLabel = guiCreateLabel(0.1, 0.45, 0.8, 0.1, "Пароль:", true, registerGUI) local confirmPasswordLabel = guiCreateLabel(0.1, 0.65, 0.8, 0.1, "Повторите пароль:", true, registerGUI) guiSetFont(registerUsernameLabel, boldFont) guiSetFont(emailLabel, boldFont) guiSetFont(registerPasswordLabel, boldFont) guiSetFont(confirmPasswordLabel, boldFont) guiLabelSetHorizontalAlign(registerUsernameLabel, "center") guiLabelSetHorizontalAlign(emailLabel, "center") guiLabelSetHorizontalAlign(registerPasswordLabel, "center") guiLabelSetHorizontalAlign(confirmPasswordLabel, "center") registerUsernameField = guiCreateEdit(0.1, 0.15, 0.8, 0.08, "", true, registerGUI) emailField = guiCreateEdit(0.1, 0.35, 0.8, 0.08, "", true, registerGUI) registerPasswordField = guiCreateEdit(0.1, 0.55, 0.8, 0.08, "", true, registerGUI) confirmPasswordField = guiCreateEdit(0.1, 0.75, 0.8, 0.08, "", true, registerGUI) local backButton = guiCreateButton(0.1, 0.85, 0.35, 0.1, "Назад", true, registerGUI) local confirmRegisterButton = guiCreateButton(0.55, 0.85, 0.35, 0.1, "Зарегистрироваться", true, registerGUI) guiSetEnabled(backButton, false) guiSetEnabled(confirmRegisterButton, false) guiSetVisible(registerGUI, false) addEventHandler("onClientGUIClick", registerButton, function() playSound("sounds/sfx/button.mp3") guiSetVisible(backgroundImage, false) guiSetVisible(buttonvk, false) guiSetVisible(buttonyt, false) guiSetVisible(buttontg, false) guiSetVisible(registerGUI, true) guiSetEnabled(backButton, true) guiSetEnabled(confirmRegisterButton, true) end) addEventHandler("onClientGUIClick", backButton, function() playSound("sounds/sfx/button.mp3") guiSetVisible(registerGUI, false) guiSetVisible(buttonvk, true) guiSetVisible(buttonyt, true) guiSetVisible(buttontg, true) guiSetVisible(backgroundImage, true) guiSetEnabled(backButton, false) guiSetEnabled(confirmRegisterButton, false) end) addEventHandler("onClientGUIClick", confirmRegisterButton, function() playSound("sounds/sfx/button.mp3") local username = guiGetText(registerUsernameField) local email = guiGetText(emailField) local password = guiGetText(registerPasswordField) local confirmPassword = guiGetText(confirmPasswordField) if password == confirmPassword then triggerServerEvent("onRequestRegister", getLocalPlayer(), username, email, password) else exports.notyf_system:badnotyShow("Пароли не совпадают!", source) end end) function hideLoginWindow() removeEventHandler("onClientPreRender", root, CameraPosition) setCameraTarget(getLocalPlayer()) showChat(true) guiSetInputEnabled(false) guiSetVisible(backgroundImage, false) guiSetVisible(registerGUI, false) guiSetVisible(buttonvk, false) guiSetVisible(buttonyt, false) guiSetVisible(buttontg, false) showCursor(false) end addEvent("hideLoginWindow", true) addEventHandler("hideLoginWindow", root, hideLoginWindow) -- МУЗЫКА НА ФОНЕ function startSound() local sounds = {"sounds/loginsong_1.mp3", "sounds/loginsong_2.mp3", "sounds/loginsong_3.mp3"} local randomSound = sounds[math.random(#sounds)] local sound = playSound(randomSound) if not sound then setSoundVolume(sound, 0.2) -- устанавливаем громкость звука на 50% outputChatBox("Ошибка воспроизведения звука: " .. randomSound) -- выводим сообщение об ошибке в чат, если звук не воспроизводится else setElementData(getLocalPlayer(), soundElementData, sound) -- сохраняем элемент звука в элементарных данных end end addEventHandler("onClientResourceStart", getResourceRootElement(getThisResource()), startSound) function stopMySound() local sound = getElementData(getLocalPlayer(), soundElementData) -- получаем элемент звука из элементарных данных if isElement(sound) then destroyElement(sound) removeElementData(getLocalPlayer(), soundElementData) -- удаляем данные элемента после уничтожения звука end end addEventHandler("onClientPlayerSpawn", getLocalPlayer(), stopMySound) -- login_server.lua local function validateCredentials(username, password) if string.len(username) < 4 or string.len(username) > 15 then -- outputChatBox("Имя пользователя должно содержать от 4 до 15 символов", source) exports.notyf_system:badnotyShow("Имя пользователя должно содержать от 4 до 15 символов!", source) return false end if string.len(password) < 4 or string.len(password) > 20 then -- outputChatBox("Пароль должен содержать от 4 до 20 символов", source) exports.notyf_system:badnotyShow("Пароль должен содержать от 4 до 20 символов!", source) return false end if string.match(username, "%W") then -- outputChatBox("Имя пользователя может содержать только буквы и цифры", source) exports.notyf_system:badnotyShow("Имя пользователя может содержать только буквы и цифры!", source) return false end return true end local function isValidEmail(email) if not email then return false end if string.find(email, "^[%w._%-]+@[%w.-]+%.%a+$") then return true end return false end function enterPlayer(username, password) outputConsole("enterPlayer function is called with username: " .. username .. " and password: " .. password) local account = getAccount(username) if (account == false) then -- outputChatBox("Такого аккаунта не существует", source) exports.notyf_system:badnotyShow("Такого аккаунта не существует!", source) return end if not logIn(source, account, password) then -- outputChatBox("Неверный пароль!", source) exports.notyf_system:badnotyShow("Неверный пароль!", source) else triggerClientEvent(source, "hideLoginWindow", getRootElement()) triggerEvent("onPlayerDayZLogin", getRootElement(), username, password, source) end end addEvent("onRequestEnter", true) addEventHandler("onRequestEnter", getRootElement(), function(...) outputConsole("onRequestEnter event is triggered") enterPlayer(...) end) function registerPlayer(username, email, password) if not validateCredentials(username, email, password) then return end if not isValidEmail(email) then exports.notyf_system:badnotyShow("Неправильный формат почты!", source) return end local account = getAccount(username) if account then -- outputChatBox("Аккаунт уже существует", source) exports.notyf_system:badnotyShow("Аккаунт уже существует!", source) else account = addAccount(username, password) logIn(source, account, password) triggerClientEvent(source, "hideLoginWindow", getRootElement()) triggerEvent("onPlayerDayZRegister", getRootElement(), username, password, email, source) triggerClientEvent(source, "openClothingInterface", getRootElement()) end end addEvent("onRequestRegister", true) addEventHandler("onRequestRegister", getRootElement(), registerPlayer) Это код скриптов стороны клиента и сервера с логикой регистрации, авторизации и других мелочей при входе в игру для мультиплеера MTA SAN ANDREAS. Проанализируй код, найди недостатки, ошибки, возможные баги и предложи варианты их исправления.
45cd1de8acc96e227214a6b5abb402c9
{ "intermediate": 0.33653852343559265, "beginner": 0.4437899589538574, "expert": 0.21967151761054993 }
41,314
create an excel formula to solve the following problem. I require a search of a term in cell J5 on Sheet 1, that is also on a different sheet (Sheet 2) which needs to be matched and then return the value that is in a different cell 2 columns along from this on sheet 2. This value from sheet 2 be returned, back in a cell G1 on sheet 1
889cc55f8735a6182023a6329f72d8a3
{ "intermediate": 0.3554818630218506, "beginner": 0.20561937987804413, "expert": 0.4388987421989441 }
41,315
If there is 1000000 connections, will auto-tunning consume CPU a lot? answer shortly
41c3e944a5aed675f23aaf1e64446776
{ "intermediate": 0.21179357171058655, "beginner": 0.19204607605934143, "expert": 0.596160352230072 }
41,316
Привет, вот код для подвески в roblox:
d1537e0fcb0eee47266e68f04b5b8d4b
{ "intermediate": 0.3023086488246918, "beginner": 0.2785037159919739, "expert": 0.41918760538101196 }
41,317
this vba code is not working: Dim dailyChecksSheet As Worksheet Set dailyChecksSheet = ThisWorkbook.Worksheets("Daily Checks") Dim todayDate As Date Dim cellDate As Date todayDate = Date cellDate = dailyChecksSheet.Range("AF1").Value If Weekday(cellDate, vbMonday) >= vbMonday And Weekday(cellDate, vbMonday) <= vbFriday Then If cellDate < todayDate Then MsgBox "Last Week's Dates have already been cleared", vbExclamation Exit Sub End If End If
61241af8fd994fa0a73be90d77b0017e
{ "intermediate": 0.3913782835006714, "beginner": 0.42744937539100647, "expert": 0.18117231130599976 }
41,318
How do I make a zoomable svg, such that when a user scrolls the svg appears to zoom in
bc5da4d4a1b0fd3d0fc01fd47305531c
{ "intermediate": 0.32198265194892883, "beginner": 0.20775850117206573, "expert": 0.47025883197784424 }
41,319
Make an entire C++ hangman game
ec16d009f3315c767090c90646a0584c
{ "intermediate": 0.2674202620983124, "beginner": 0.460324227809906, "expert": 0.2722555100917816 }
41,320
How do I wait for <link rel="stylesheet" href="https://assets.bux.osu.edu/v0.x/css/bux-styles.min.css"/> to finish loading
78ccef824d11763c995598c70a1c6bf4
{ "intermediate": 0.46126803755760193, "beginner": 0.2757844626903534, "expert": 0.2629474699497223 }
41,321
You are a programming tutorial writer. Write very long tutorial on hello world in Quarkus.
0998af3c8b31e93591f870aabe727ee5
{ "intermediate": 0.26916030049324036, "beginner": 0.41157999634742737, "expert": 0.3192597031593323 }
41,322
java.lang.Exception: No se pudo obtener conexión glp at co.gov.creg.util.DBQuery.<init>(DBQuery.java:42) at org.apache.jsp.matrizGNC_jsp._jspService(matrizGNC_jsp.java:342) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:835) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:640) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1286) at java.lang.Thread.run(Thread.java:662)
03eef08e9afe5bd1885e586143d29ee6
{ "intermediate": 0.4905995726585388, "beginner": 0.27625975012779236, "expert": 0.23314066231250763 }
41,323
How to use this class in Python. Just give example class AESCipher(object): def __init__(self, key): self.bs = AES.block_size self.key = hashlib.sha256(key.encode()).digest() def encrypt(self, raw): raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw.encode())) def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return AESCipher._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') def _pad(self, s): return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) @staticmethod def _unpad(s): return s[:-ord(s[len(s)-1:])]
564928815ae5e96f7f3d3902a7ea7a42
{ "intermediate": 0.4564484655857086, "beginner": 0.30511969327926636, "expert": 0.2384319007396698 }
41,324
Привет! Напиши код ручной миграции room При data class Customer( @PrimaryKey(autoGenerate = true) val id: Long = 0L, var uuid: String? = null, var name: String? = null, var surname: String? = null, var email: String? = null, var phone: String? = null, var balance: Int = 0, var sex: Int? = null, var consentStatus: Int? = null, var birthday: String? = null, var platform: String? = null, var token_device: String? = null, @Embedded var android_device: Android? = null, ) @Entity(tableName = "android_customer") data class Android( var nameAndroid: String? = null, var registration_id: String, ) Поменявшейся на data class Customer( @PrimaryKey(autoGenerate = true) val id: Long = 0L, var uuid: String? = null, var name: String? = null, var surname: String? = null, var email: String? = null, var phone: String? = null, var balance: Int = 0, var sex: Int? = null, var consentStatus: Int? = null, var birthday: String? = null, var platform: String? = null, var token_device: String? = null, @Embedded var android_device: Android? = null, @Embedded var device: Device? = null ) @Entity(tableName = "android_customer") data class Android( var nameAndroid: String? = null, var reg_id: String, ) @Entity(tableName = "device") data class Device( val type: String? = "Android", var registration_id: String, val device_id: String, var model: String? = Build.MODEL, var name_app: String? = Build.BOARD, val version_app: String = Build.VERSION.RELEASE, )
e9648d8abeafdf456173d15746c336a1
{ "intermediate": 0.3550131320953369, "beginner": 0.27478834986686707, "expert": 0.3701985478401184 }
41,325
main.hs:1:1: error: The IO action `main' is not exported by module `Main' | 1 | module Main (list) where | ^ Failed, no modules loaded. Prelude>
211b88910aca531f8d84edab34f03071
{ "intermediate": 0.4051274061203003, "beginner": 0.31005164980888367, "expert": 0.28482094407081604 }
41,326
I want you to improve this script, complete the night action, each village should move to the closest house according to villasger position, but each house has a stablished villagerCapacity, if house is full search for next closest house to the villager, associate the house with the villager in a dictionary using System; using System.Collections.Generic; using Game.Systems.Buildings; using UnityEngine; namespace Game.Systems { public class HousingManager : MonoBehaviour { private List<House> houses = new List<House>(); public void Init() { GameManager.Instance.OnDayStart += DayAction; GameManager.Instance.OnNightStart += NightAction; } public void DayAction(object sender, EventArgs args) { } public void NightAction(object sender, EventArgs args) { List<Villager> villagers = GameManager.Instance.VillagerTracker.GetVillagers(); foreach (var villager in villagers) { } } public void AddHouse(House house) { if (!houses.Contains(house)) { houses.Add(house); } } public void RemoveHouse(House house) { if (houses.Contains(house)) { houses.Remove(house); } } private void OnDestroy() { GameManager.Instance.OnDayStart -= DayAction; GameManager.Instance.OnNightStart -= NightAction; } } }
3b7001c1cce0862b006021bebf98add2
{ "intermediate": 0.43693113327026367, "beginner": 0.32045450806617737, "expert": 0.24261435866355896 }
41,327
hi1
0abe48bc910835003f63d4da682eb555
{ "intermediate": 0.3220134973526001, "beginner": 0.28278839588165283, "expert": 0.39519810676574707 }
41,328
generate a complete, newly created tune in ABC notation with a full structure, including an A and a B part (common in modern tunes), Major 6th Chords
fceb93959d2101cfea1a61a890410a16
{ "intermediate": 0.285902738571167, "beginner": 0.19626648724079132, "expert": 0.5178307294845581 }
41,329
Imagine you are a system composed of no less than six distinct AI layers, each responsible for evaluating and refining the output of the previous one. Your task is to generate a [type of content, e.g., ‘a story’, 'a novel', ‘poem’, ‘essay’, etc.] about [subject or theme]. Each layer should focus on the following aspects: - AI-layer-1: Generate the initial draft of the content. - AI-layer-2: Critique the draft for adherence to the specified subject or theme. - AI-layer-3: Analyze the grammar and style, making suggestions for improvement. - AI-layer-4: Assess the logical coherence and structure of the content. - AI-layer-5: Ensure the content is engaging and has the appropriate emotional impact. - AI-layer-6: Conduct the final review, edit for grammar and polish, and present the finished content. each layer may converse with each other in order to make an even better end response that follows the users task to a higher standard. As you produce the content, narrate the inter-layer communication to illustrate how each layer refines and contributes to the final version.
76503094fdd6734df70e2067f94019ba
{ "intermediate": 0.17123880982398987, "beginner": 0.31036365032196045, "expert": 0.5183975100517273 }
41,330
how to code a esp32 to web server, camera, open door and light
2d446b5268dfd727ef73eb2d95ebc180
{ "intermediate": 0.4545228183269501, "beginner": 0.2628156542778015, "expert": 0.282661497592926 }
41,331
Fix frame drop and overclock device adb command for Android
dd2fafe198979d31b06c5033e3e0aa45
{ "intermediate": 0.4202123284339905, "beginner": 0.23721836507320404, "expert": 0.3425693213939667 }
41,332
HI!
806bddceab57fa82ba0207a21b2bbcf4
{ "intermediate": 0.3374777138233185, "beginner": 0.2601830065250397, "expert": 0.40233927965164185 }
41,333
let sus = manager.locationServicesEnabled() Static member 'locationServicesEnabled' cannot be used on instance of type 'CLLocationManager'
a01f80772a56c17263e89c89ae3bc4e8
{ "intermediate": 0.4044034779071808, "beginner": 0.3006408214569092, "expert": 0.2949557602405548 }
41,334
1
7f0d70ddd50ba11ba9340a805d92cf52
{ "intermediate": 0.3205237090587616, "beginner": 0.295337438583374, "expert": 0.38413888216018677 }
41,335
I am making a C++ SDL based game engine, currently I am finishing my final touches of my current release, Help me finish them. Let’s start with the Rect class, currently I have everything set to int, x, y, w, h, should I keep it like this or use float instead? I am based on SDL_Rect, I have Point and FPoint, maybe creating a new class FRect, what do you think?
155cea2ef94942041ba134122c24cdf4
{ "intermediate": 0.3562593460083008, "beginner": 0.6223755478858948, "expert": 0.021365050226449966 }
41,336
telebot inline calendar showing current day and switch between months. use only straight ' and "
c29f94807c37533aa440d2a2374fe787
{ "intermediate": 0.34768620133399963, "beginner": 0.2582101821899414, "expert": 0.39410367608070374 }
41,337
how are you bot?
11fdf1f9596a413607797fcd54b02d7c
{ "intermediate": 0.3381686508655548, "beginner": 0.20942549407482147, "expert": 0.4524058401584625 }
41,338
import datetime import calendar import typing from dataclasses import dataclass from telebot import TeleBot from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery @dataclass class Language: days: tuple months: tuple ENGLISH_LANGUAGE = Language( days=("Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"), months=( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ), ) RUSSIAN_LANGUAGE = Language( days=("Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"), months=( "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь", ), ) class Calendar: """ Calendar data factory """ __lang: Language def __init__(self, language: Language = ENGLISH_LANGUAGE): self.__lang = language def create_calendar( self, name: str = "calendar", year: int = None, month: int = None, ) -> InlineKeyboardMarkup: """ Create a built in inline keyboard with calendar :param name: :param year: Year to use in the calendar if you are not using the current year. :param month: Month to use in the calendar if you are not using the current month. :return: Returns an InlineKeyboardMarkup object with a calendar. """ now_day = datetime.datetime.now() if year is None: year = now_day.year if month is None: month = now_day.month calendar_callback = CallbackData(name, "action", "year", "month", "day") data_ignore = calendar_callback.new("IGNORE", year, month, "!") data_months = calendar_callback.new("MONTHS", year, month, "!") keyboard = InlineKeyboardMarkup(row_width=7) keyboard.add( InlineKeyboardButton( self.__lang.months[month - 1] + " " + str(year), callback_data=data_months, ) ) keyboard.add( *[ InlineKeyboardButton(day, callback_data=data_ignore) for day in self.__lang.days ] ) for week in calendar.monthcalendar(year, month): row = list() for day in week: if day == 0: row.append(InlineKeyboardButton(" ", callback_data=data_ignore)) elif ( f"{now_day.day}.{now_day.month}.{now_day.year}" == f"{day}.{month}.{year}" ): row.append( InlineKeyboardButton( f"({day})", callback_data=calendar_callback.new( "DAY", year, month, day ), ) ) else: row.append( InlineKeyboardButton( str(day), callback_data=calendar_callback.new( "DAY", year, month, day ), ) ) keyboard.add(*row) keyboard.add( InlineKeyboardButton( "<", callback_data=calendar_callback.new("PREVIOUS-MONTH", year, month, "!"), ), InlineKeyboardButton( "Cancel", callback_data=calendar_callback.new("CANCEL", year, month, "!"), ), InlineKeyboardButton( ">", callback_data=calendar_callback.new("NEXT-MONTH", year, month, "!") ), ) return keyboard def create_months_calendar( self, name: str = "calendar", year: int = None ) -> InlineKeyboardMarkup: """ Creates a calendar with month selection :param name: :param year: :return: """ if year is None: year = datetime.datetime.now().year calendar_callback = CallbackData(name, "action", "year", "month", "day") keyboard = InlineKeyboardMarkup() for i, month in enumerate( zip(self.__lang.months[0::2], self.__lang.months[1::2]) ): keyboard.add( InlineKeyboardButton( month[0], callback_data=calendar_callback.new("MONTH", year, 2 * i + 1, "!"), ), InlineKeyboardButton( month[1], callback_data=calendar_callback.new( "MONTH", year, (i + 1) * 2, "!" ), ), ) return keyboard def calendar_query_handler( self, bot: TeleBot, call: CallbackQuery, name: str, action: str, year: int, month: int, day: int, ) -> None or datetime.datetime: """ The method creates a new calendar if the forward or backward button is pressed This method should be called inside CallbackQueryHandler. :param bot: The object of the bot CallbackQueryHandler :param call: CallbackQueryHandler data :param day: :param month: :param year: :param action: :param name: :return: Returns a tuple """ current = datetime.datetime(int(year), int(month), 1) if action == "IGNORE": bot.answer_callback_query(callback_query_id=call.id) return False, None elif action == "DAY": bot.delete_message( chat_id=call.message.chat.id, message_id=call.message.message_id ) return datetime.datetime(int(year), int(month), int(day)) elif action == "PREVIOUS-MONTH": preview_month = current - datetime.timedelta(days=1) bot.edit_message_text( text=call.message.text, chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=self.create_calendar( name=name, year=int(preview_month.year), month=int(preview_month.month), ), ) return None elif action == "NEXT-MONTH": next_month = current + datetime.timedelta(days=31) bot.edit_message_text( text=call.message.text, chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=self.create_calendar( name=name, year=int(next_month.year), month=int(next_month.month) ), ) return None elif action == "MONTHS": bot.edit_message_text( text=call.message.text, chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=self.create_months_calendar(name=name, year=current.year), ) return None elif action == "MONTH": bot.edit_message_text( text=call.message.text, chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=self.create_calendar( name=name, year=int(year), month=int(month) ), ) return None elif action == "CANCEL": bot.delete_message( chat_id=call.message.chat.id, message_id=call.message.message_id ) return "CANCEL", None else: bot.answer_callback_query(callback_query_id=call.id, text="ERROR!") bot.delete_message( chat_id=call.message.chat.id, message_id=call.message.message_id ) return None class CallbackData: """ Callback data factory """ def __init__(self, prefix, *parts, sep=":"): if not isinstance(prefix, str): raise TypeError( f"Prefix must be instance of str not {type(prefix).__name__}" ) if not prefix: raise ValueError("Prefix can't be empty") if sep in prefix: raise ValueError(f"Separator {sep!r} can't be used in prefix") if not parts: raise TypeError("Parts were not passed!") self.prefix = prefix self.sep = sep self._part_names = parts def new(self, *args, **kwargs) -> str: """ Generate callback data :param args: :param kwargs: :return: """ args = list(args) data = [self.prefix] for part in self._part_names: value = kwargs.pop(part, None) if value is None: if args: value = args.pop(0) else: raise ValueError(f"Value for {part!r} was not passed!") if value is not None and not isinstance(value, str): value = str(value) if not value: raise ValueError(f"Value for part {part!r} can't be empty!'") if self.sep in value: raise ValueError( f"Symbol {self.sep!r} is defined as the separator and can't be used in parts' values" ) data.append(value) if args or kwargs: raise TypeError("Too many arguments were passed!") callback_data = self.sep.join(data) if len(callback_data) > 64: raise ValueError("Resulted callback data is too long!") return callback_data def parse(self, callback_data: str) -> typing.Dict[str, str]: """ Parse data from the callback data :param callback_data: :return: """ prefix, *parts = callback_data.split(self.sep) if prefix != self.prefix: raise ValueError("Passed callback data can't be parsed with that prefix.") elif len(parts) != len(self._part_names): raise ValueError("Invalid parts count!") result = {"@": prefix} result.update(zip(self._part_names, parts)) return result def filter(self, **config): """ Generate filter :param config: :return: """ print(config, self._part_names) for key in config.keys(): if key not in self._part_names: return False return True add edits so the calendar days begin from current day. dont rewrite, but explain step by step
11e47a9c4fab755d904116bb17d80e87
{ "intermediate": 0.35676470398902893, "beginner": 0.45835795998573303, "expert": 0.1848773956298828 }
41,339
how do i see a process running inside a docker container and display the process and also be able to exit out the view?
f0c559caa6c2c59ec51f66292e50986b
{ "intermediate": 0.4979742169380188, "beginner": 0.21176066994667053, "expert": 0.29026514291763306 }
41,340
print every element in list in new line ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'и', 'к', 'л', 'м', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'э', 'ю', 'я']
7f5bdcbe345aafff12c4d9128ac574a0
{ "intermediate": 0.3970568776130676, "beginner": 0.20426081120967865, "expert": 0.39868229627609253 }
41,341
Give an example of AES-128 CTR encryption using Pycryptodome library in Python
dcbb488897d1a78bfd8bc80d759418d5
{ "intermediate": 0.5339264273643494, "beginner": 0.05228184536099434, "expert": 0.4137917459011078 }
41,342
are you Chatgpt4?
65b3b506c7b19661c174be892886f1b1
{ "intermediate": 0.3520410656929016, "beginner": 0.223885640501976, "expert": 0.4240732491016388 }
41,343
Вот правильный код: def F(x, a): return (x & a != 0) or ((x & 52 == 0) and (x & 14 == 0)) for a in range(1, 10**3): if all(F(x, a) for x in range(1, 10**5)): print(a) break А вот мой: def f(x,a): return (x and a != 0) or (x and 52 == 0) and (x and 14 == 0) for a in range (1,100000): if all(f(x,a) for x in range (1,100000)): print(a) break В чем различие? где моя ошибка?
6730b393c6a08b80927fa82e8690aff5
{ "intermediate": 0.275966614484787, "beginner": 0.4661528170108795, "expert": 0.2578805685043335 }
41,344
<script> import terminalCapacity from "../database/maxNumberOfPeople"; import { people } from "../database/getTotalNumberOfPeople"; import units from "../database/getTotalNumberOfUnits"; import maxOccupants from "../database/maxNumberOfOccupants"; import Carousel from "svelte-carousel"; let colorClass = ""; let ratio; let colorChip = ""; // Reactive assignments from stores $: maximumOccupants = $maxOccupants; $: totalNumberOfUnitsArray = $units; $: maxTerminalCapacity = $terminalCapacity; // Reactive calculations based on store values $: numCars = totalNumberOfUnitsArray.filter( (unit) => unit.status === "In Queue" ).length; $: maximumOccupantsVal = maximumOccupants ?? 0; $: maxTerminalCapacityVal = maxTerminalCapacity ?? 0; $: remainingPeople = $people - numCars * maximumOccupantsVal; $: ratio = remainingPeople / maxTerminalCapacityVal; // Reactive URL for chip image based on colorChip $: chipImageSrc = `images/${colorChip}-chip.png`; // Example path, adjust according to your actual image storage path // Reactive conditional logic for setting colorClass $: { if (ratio >= 0.7) { colorClass = "bg-red-500"; } else if (ratio >= 0.4) { colorClass = "bg-yellow-500"; } else { colorClass = "bg-green-500"; } } const images = [ { src: "images/byday.png", alt: "Average Passenger per Day", description: "According to the analysis of our current data trend, it has been observed that Monday records the highest average passenger count among all the days of the week. The visual representation of the data demonstrates that the average number of passengers on Monday amounts to approximately 350 per day.", }, { src: "images/byhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/byhourtues.png", alt: "Average Passenger per Hour", description: "Based on the analysis of our current data trend, it can be observed that the time window of 8:00 to 8:59 AM on Tuesdays experiences the highest average passenger count per hour of the day. The accompanying visual representation of the data shows that the average number of passengers during this period on Tuesdays is approximately 40 plus per day. These insights into the peak hours of passenger traffic on Tuesdays can prove to be beneficial for commuters in planning their journeys and avoiding congestion during rush hour.", }, { src: "images/byhourwed.png", alt: "Average Passenger per Hour", description: "On Wednesdays, the time slot of 8:00 to 8:59 AM records the highest average passenger count per hour of the day, with approximately 30 plus passengers on average during this period, as indicated by the accompanying visual representation based on our current data trend. These insights can assist commuters in avoiding peak congestion and planning their travel accordingly.", }, { src: "images/byhourthurs.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/byhourfri.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/l3.png", alt: "Average Passenger per Hour", description: "The L300 Van is a reliable and efficient public utility vehicle used for public transportation. It has a spacious and comfortable interior, capable of accommodating up to 16 passengers. Equipped with a powerful and fuel-efficient engine, the L300 Van can handle various road conditions with ease. Its durable and sturdy build ensures safe and secure transportation for commuters. With its accessibility and affordability, the L300 Van is a popular choice for public transportation in urban and rural areas.", }, { src: "images/forecast.png", alt: "Average Passenger per Hour", description: "This data visualization displays the results of a forecasting analysis performed on the current dataset using the fbprophet algorithm. The forecast extends to 100 days in the future and pertains to the average daily passenger count at a public utility terminal. The graphical representation of the forecasting results allows for easy comprehension and interpretation, enabling stakeholders to make informed decisions based on the anticipated passenger traffic.", }, ]; const byhour = [ { src: "images/avebyhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/byhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/byhourtues.png", alt: "Average Passenger per Hour", description: "Based on the analysis of our current data trend, it can be observed that the time window of 8:00 to 8:59 AM on Tuesdays experiences the highest average passenger count per hour of the day. The accompanying visual representation of the data shows that the average number of passengers during this period on Tuesdays is approximately 40 plus per day. These insights into the peak hours of passenger traffic on Tuesdays can prove to be beneficial for commuters in planning their journeys and avoiding congestion during rush hour.", }, { src: "images/byhourwed.png", alt: "Average Passenger per Hour", description: "On Wednesdays, the time slot of 8:00 to 8:59 AM records the highest average passenger count per hour of the day, with approximately 30 plus passengers on average during this period, as indicated by the accompanying visual representation based on our current data trend. These insights can assist commuters in avoiding peak congestion and planning their travel accordingly.", }, { src: "images/byhourthurs.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/byhourfri.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, ]; const predbyhour = [ { src: "images/avepredbyhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/predbyhourmon.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/predbyhourtues.png", alt: "Average Passenger per Hour", description: "Based on the analysis of our current data trend, it can be observed that the time window of 8:00 to 8:59 AM on Tuesdays experiences the highest average passenger count per hour of the day. The accompanying visual representation of the data shows that the average number of passengers during this period on Tuesdays is approximately 40 plus per day. These insights into the peak hours of passenger traffic on Tuesdays can prove to be beneficial for commuters in planning their journeys and avoiding congestion during rush hour.", }, { src: "images/predbyhourwed.png", alt: "Average Passenger per Hour", description: "On Wednesdays, the time slot of 8:00 to 8:59 AM records the highest average passenger count per hour of the day, with approximately 30 plus passengers on average during this period, as indicated by the accompanying visual representation based on our current data trend. These insights can assist commuters in avoiding peak congestion and planning their travel accordingly.", }, { src: "images/predbyhourthur.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/predbyhourfri.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, ]; const aveandpredbyday = [ { src: "images/byday.png", alt: "Average Passenger per Day", description: "According to the analysis of our current data trend, it has been observed that Monday records the highest average passenger count among all the days of the week. The visual representation of the data demonstrates that the average number of passengers on Monday amounts to approximately 350 per day.", }, { src: "images/avepredday.png", alt: "Average Passenger per Day", description: "According to the analysis of our current data trend, it has been observed that Monday records the highest average passenger count among all the days of the week. The visual representation of the data demonstrates that the average number of passengers on Monday amounts to approximately 350 per day.", }, ]; </script> <br /> <br /> <br /> <br /> <div class="heading"> <h2 class="text-2xl font-bold mb-4">Home</h2> </div> <div class="flex flex-col items-center justify-center h-28 px-4 bg-gray-200 text-gray-800" > <div class="flex items-center"> <span class="mr-2 font-bold">Current people:</span> <span class="font-medium">{$people}</span> </div> <div class="flex items-center mt-1"> <span class="mr-2 font-bold">Terminal Status:</span> <span> <div class="flex items-center"> <span class="h-3 w-3 rounded-full mr-2 {colorClass}"></span> <div class="text-gray-800 font-medium"> {#if ratio >= 0.7} Crowded {:else if ratio >= 0.4} Slightly Crowded {:else} Not crowded {/if} </div> </div> </span> </div> <div class="flex items-center justify-center mt-4"> <span class="mr-2 font-bold">Chips on deck Login:</span> <img src="{chipImageSrc}" alt="Current Chip" class="h-8 w-8 rounded-full"> <!-- Adjust height and width as needed --> </div> </div> <br /><br /> <p class="mr-2 font-bold text-center"> Average and Predicted Average Passenger Count Per Day </p> <Carousel navigation> {#each aveandpredbyday as { src, alt }} <div class="container"> <img class="image" {src} {alt} /> </div> {/each} </Carousel> <br /> <br /> <br /> <br /> <style> .heading { margin: 30px 20px; } .margin-info { margin: 10px 20px; } .con-info { text-align: center; display: block; width: auto; height: auto; top: 170px; margin-left: auto; margin-right: auto; background: #f3f4f6; padding: 20px 20px; } .container { display: flex; justify-content: center; align-items: center; flex-direction: column; background-color: lightgrey; padding: 15px; margin: 10px; margin-left: auto; margin-right: auto; } .image { width: auto; height: auto; object-fit: contain; } .description { text-align: justify; margin-top: 10px; } </style> from this code, please add 6 buttons under "Chips on deck". each buttons are assigned with their designated images for chipImageSrc to change. when the buttons are pressed, the chipImageSrc would to change. please also add a reset button for the chipImageSrc where it would show none when the it is pressed.
240d19043bca6ab5916740dfb371b939
{ "intermediate": 0.3810397982597351, "beginner": 0.326627641916275, "expert": 0.2923325300216675 }
41,345
<script> import terminalCapacity from "../database/maxNumberOfPeople"; import { people } from "../database/getTotalNumberOfPeople"; import units from "../database/getTotalNumberOfUnits"; import maxOccupants from "../database/maxNumberOfOccupants"; import Carousel from "svelte-carousel"; let colorClass = ""; let ratio; let colorChip = ""; // Reactive assignments from stores $: maximumOccupants = $maxOccupants; $: totalNumberOfUnitsArray = $units; $: maxTerminalCapacity = $terminalCapacity; // Reactive calculations based on store values $: numCars = totalNumberOfUnitsArray.filter( (unit) => unit.status === "In Queue" ).length; $: maximumOccupantsVal = maximumOccupants ?? 0; $: maxTerminalCapacityVal = maxTerminalCapacity ?? 0; $: remainingPeople = $people - numCars * maximumOccupantsVal; $: ratio = remainingPeople / maxTerminalCapacityVal; // Reactive URL for chip image based on colorChip $: chipImageSrc = `images/${colorChip}-chip.png`; // Example path, adjust according to your actual image storage path // Reactive conditional logic for setting colorClass $: { if (ratio >= 0.7) { colorClass = "bg-red-500"; } else if (ratio >= 0.4) { colorClass = "bg-yellow-500"; } else { colorClass = "bg-green-500"; } } const images = [ { src: "images/byday.png", alt: "Average Passenger per Day", description: "According to the analysis of our current data trend, it has been observed that Monday records the highest average passenger count among all the days of the week. The visual representation of the data demonstrates that the average number of passengers on Monday amounts to approximately 350 per day.", }, { src: "images/byhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/byhourtues.png", alt: "Average Passenger per Hour", description: "Based on the analysis of our current data trend, it can be observed that the time window of 8:00 to 8:59 AM on Tuesdays experiences the highest average passenger count per hour of the day. The accompanying visual representation of the data shows that the average number of passengers during this period on Tuesdays is approximately 40 plus per day. These insights into the peak hours of passenger traffic on Tuesdays can prove to be beneficial for commuters in planning their journeys and avoiding congestion during rush hour.", }, { src: "images/byhourwed.png", alt: "Average Passenger per Hour", description: "On Wednesdays, the time slot of 8:00 to 8:59 AM records the highest average passenger count per hour of the day, with approximately 30 plus passengers on average during this period, as indicated by the accompanying visual representation based on our current data trend. These insights can assist commuters in avoiding peak congestion and planning their travel accordingly.", }, { src: "images/byhourthurs.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/byhourfri.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/l3.png", alt: "Average Passenger per Hour", description: "The L300 Van is a reliable and efficient public utility vehicle used for public transportation. It has a spacious and comfortable interior, capable of accommodating up to 16 passengers. Equipped with a powerful and fuel-efficient engine, the L300 Van can handle various road conditions with ease. Its durable and sturdy build ensures safe and secure transportation for commuters. With its accessibility and affordability, the L300 Van is a popular choice for public transportation in urban and rural areas.", }, { src: "images/forecast.png", alt: "Average Passenger per Hour", description: "This data visualization displays the results of a forecasting analysis performed on the current dataset using the fbprophet algorithm. The forecast extends to 100 days in the future and pertains to the average daily passenger count at a public utility terminal. The graphical representation of the forecasting results allows for easy comprehension and interpretation, enabling stakeholders to make informed decisions based on the anticipated passenger traffic.", }, ]; const byhour = [ { src: "images/avebyhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/byhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/byhourtues.png", alt: "Average Passenger per Hour", description: "Based on the analysis of our current data trend, it can be observed that the time window of 8:00 to 8:59 AM on Tuesdays experiences the highest average passenger count per hour of the day. The accompanying visual representation of the data shows that the average number of passengers during this period on Tuesdays is approximately 40 plus per day. These insights into the peak hours of passenger traffic on Tuesdays can prove to be beneficial for commuters in planning their journeys and avoiding congestion during rush hour.", }, { src: "images/byhourwed.png", alt: "Average Passenger per Hour", description: "On Wednesdays, the time slot of 8:00 to 8:59 AM records the highest average passenger count per hour of the day, with approximately 30 plus passengers on average during this period, as indicated by the accompanying visual representation based on our current data trend. These insights can assist commuters in avoiding peak congestion and planning their travel accordingly.", }, { src: "images/byhourthurs.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/byhourfri.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, ]; const predbyhour = [ { src: "images/avepredbyhour.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/predbyhourmon.png", alt: "Average Passenger per Hour", description: "As per the analysis of our current data trend, it has been observed that the time slot of 7:00 to 7:59 AM on Mondays records the highest average passenger count by hour of the day. The visual representation of the data illustrates that during this time slot, the average number of passengers on Mondays amounts to approximately 60 plus per day. This information provides valuable insights into the peak hours of passenger traffic on Mondays, which can be useful for commuters to plan their travel accordingly.", }, { src: "images/predbyhourtues.png", alt: "Average Passenger per Hour", description: "Based on the analysis of our current data trend, it can be observed that the time window of 8:00 to 8:59 AM on Tuesdays experiences the highest average passenger count per hour of the day. The accompanying visual representation of the data shows that the average number of passengers during this period on Tuesdays is approximately 40 plus per day. These insights into the peak hours of passenger traffic on Tuesdays can prove to be beneficial for commuters in planning their journeys and avoiding congestion during rush hour.", }, { src: "images/predbyhourwed.png", alt: "Average Passenger per Hour", description: "On Wednesdays, the time slot of 8:00 to 8:59 AM records the highest average passenger count per hour of the day, with approximately 30 plus passengers on average during this period, as indicated by the accompanying visual representation based on our current data trend. These insights can assist commuters in avoiding peak congestion and planning their travel accordingly.", }, { src: "images/predbyhourthur.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, { src: "images/predbyhourfri.png", alt: "Average Passenger per Hour", description: "Similarly, on Thursdays and Fridays, the time frame of 8:00 to 8:59 AM experiences the highest average passenger count per hour of the day, with approximately 35 plus passengers on average during this period, as illustrated by the accompanying visual representation based on our current data trend. Commuters can use this information to plan their travel and avoid peak congestion during these days and hours.", }, ]; const aveandpredbyday = [ { src: "images/byday.png", alt: "Average Passenger per Day", description: "According to the analysis of our current data trend, it has been observed that Monday records the highest average passenger count among all the days of the week. The visual representation of the data demonstrates that the average number of passengers on Monday amounts to approximately 350 per day.", }, { src: "images/avepredday.png", alt: "Average Passenger per Day", description: "According to the analysis of our current data trend, it has been observed that Monday records the highest average passenger count among all the days of the week. The visual representation of the data demonstrates that the average number of passengers on Monday amounts to approximately 350 per day.", }, ]; </script> <br /> <br /> <br /> <br /> <div class="heading"> <h2 class="text-2xl font-bold mb-4">Home</h2> </div> <div class="flex flex-col items-center justify-center h-28 px-4 bg-gray-200 text-gray-800" > <div class="flex items-center"> <span class="mr-2 font-bold">Current people:</span> <span class="font-medium">{$people}</span> </div> <div class="flex items-center mt-1"> <span class="mr-2 font-bold">Terminal Status:</span> <span> <div class="flex items-center"> <span class="h-3 w-3 rounded-full mr-2 {colorClass}"></span> <div class="text-gray-800 font-medium"> {#if ratio >= 0.7} Crowded {:else if ratio >= 0.4} Slightly Crowded {:else} Not crowded {/if} </div> </div> </span> </div> <div class="flex items-center justify-center mt-4"> <span class="mr-2 font-bold">Chips on deck Login:</span> <img src="{chipImageSrc}" alt="Current Chip" class="h-8 w-8 rounded-full"> <!-- Adjust height and width as needed --> </div> </div> <br /><br /> <p class="mr-2 font-bold text-center"> Average and Predicted Average Passenger Count Per Day </p> <Carousel navigation> {#each aveandpredbyday as { src, alt }} <div class="container"> <img class="image" {src} {alt} /> </div> {/each} </Carousel> <br /> <br /> <br /> <br /> <style> .heading { margin: 30px 20px; } .margin-info { margin: 10px 20px; } .con-info { text-align: center; display: block; width: auto; height: auto; top: 170px; margin-left: auto; margin-right: auto; background: #f3f4f6; padding: 20px 20px; } .container { display: flex; justify-content: center; align-items: center; flex-direction: column; background-color: lightgrey; padding: 15px; margin: 10px; margin-left: auto; margin-right: auto; } .image { width: auto; height: auto; object-fit: contain; } .description { text-align: justify; margin-top: 10px; } </style> Please add 6 buttons under chips on deck and img src "chipImageSrc". the buttons are assigned with their designated images and when pressed, chipImageSrc will change to its images. also, please add a reset button and when pressed, chipImageSrc will no longer show a photo.
4e9f8daad3fd3a4cb62690205634ef33
{ "intermediate": 0.3810397982597351, "beginner": 0.326627641916275, "expert": 0.2923325300216675 }
41,346
I am making telegram bot to schedule people for interviews as mobile application testers. Hardest part is to make them install android app before the interview. Give me full ways to engage withing telegram bot on telebot
dfa1aa8346e3f532d89c6573b57095a0
{ "intermediate": 0.4123817980289459, "beginner": 0.2797524929046631, "expert": 0.3078656494617462 }
41,347
is it possible to check whether a particular file is present in the system while running the c/cpp code
3702175dcd58839b595ff89259c1cbd1
{ "intermediate": 0.5165729522705078, "beginner": 0.17173855006694794, "expert": 0.31168854236602783 }
41,348
Provide dktr0 punctual code to play jazz
3d8846cca1bdb34af279d3195621aa1e
{ "intermediate": 0.3181753158569336, "beginner": 0.3730793297290802, "expert": 0.3087453842163086 }
41,349
how to use for sendpoll telegram bot?
f484f65dc5da1d4e3fcfeff25f66847c
{ "intermediate": 0.30542123317718506, "beginner": 0.19738321006298065, "expert": 0.4971955120563507 }
41,350
explique cette partie sur la confuguration logstash : output { if [@metadata][index] { elasticsearch { id => "elaas-index" hosts => "https://2e2b1e8798984f8394d843aa2ee91b6a.elasticaas.ocb.equant.com:9243" user => "xxx" password => "xxx" ssl => true cacert => "/etc/pki/orange-internal-62-server-ca.pem" manage_template => false ilm_enabled => false action => "create" index => "%{[@metadata][index]}" } } stdout { codex => json } }
53ed00160bfb8ffc4268af91920cfb10
{ "intermediate": 0.32752737402915955, "beginner": 0.38701876997947693, "expert": 0.2854538559913635 }
41,351
can you give plant uml state diagram code
d726d6a689caf1cc04877c1ba9e61b0e
{ "intermediate": 0.4076622724533081, "beginner": 0.33490851521492004, "expert": 0.25742918252944946 }
41,352
refais ce code et fait un soleil plus minimaliste fait en sorte que se soit un indicateur en plus dans un style minimaliste pour mon interface arduino : #include "SPI.h" #include "Adafruit_GFX.h" #include "Adafruit_ILI9341.h" #define TFT_DC 9 #define TFT_CS 10 Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); void drawSun(int x, int y) { tft.fillCircle(x, y, 20, ILI9341_YELLOW); // Soleil for (int deg = 0; deg < 360; deg += 45) { float rad = deg * PI / 180; int lineLength = 10; int endX = x + cos(rad) * (20 + lineLength); int endY = y + sin(rad) * (20 + lineLength); tft.drawLine(x, y, endX, endY, ILI9341_YELLOW); } } void clearSun(int x, int y) { int diameter = 60; // Large enough to erase the entire sun tft.fillRect(x - diameter / 2, y - diameter / 2, diameter, diameter, ILI9341_BLACK); } void setup() { tft.begin(); tft.fillScreen(ILI9341_BLACK); tft.setCursor(26, 120); tft.setTextColor(ILI9341_RED); tft.setTextSize(3); tft.println("Hello, TFT!"); tft.setCursor(20, 160); tft.setTextColor(ILI9341_GREEN); tft.setTextSize(2); tft.println("I can has colors?"); } void loop() { static bool sunVisible = true; static unsigned long lastToggleTime = 0; if (millis() - lastToggleTime > 1000) { sunVisible = !sunVisible; if (sunVisible) { drawSun(120, 210); // Coordinates where the sun should be drawn } else { clearSun(120, 210); } lastToggleTime = millis(); } static unsigned long lastUpdateTime = 0; if (millis() - lastUpdateTime > 5000) { tft.fillRect(0, 0, 320, 240, ILI9341_BLACK); // Clear the screen tft.setTextSize(4); tft.setCursor(0,0); tft.print("20 C"); tft.fillRect(0,0,2000,2000,ILI9341_BLACK); //Black box drawn over 'old' time data tft.setCursor(0,0); tft.setTextColor(ILI9341_BLUE); tft.setTextSize(2); tft.print("humidité : "); //je vais changé par la variable aprés tft.setCursor(0,20); tft.setTextSize(4); tft.print("50% "); //je vais changé par la variable aprés tft.setTextSize(2); tft.setCursor(0,80); tft.setTextColor(ILI9341_RED); tft.print("Température"); tft.setTextSize(4); tft.setCursor(0,100 ); tft.print("20C"); tft.setCursor(0,160); tft.setTextSize(2); tft.setTextColor(ILI9341_YELLOW); tft.print("ensoleillement : "); tft.setTextSize(4); tft.setCursor(0,180); tft.print("75% "); //call function to check on temperature and draw new data if necessary delay(1000); lastUpdateTime = millis(); } // Other interface elements may be updated here }
e3be2361b2e918a001cc68480be4af82
{ "intermediate": 0.29998311400413513, "beginner": 0.5273984670639038, "expert": 0.17261850833892822 }
41,353
Je fais une interface arduino j’aimerais que pour ensoleillement le logo de soleil sois un logo de soleil minimaliste nom plein qui bouge impeu dans une animation et qui indique aussi en fonction du pourcentage d’ensoleillement voici le code que tu dois modifié : #include "SPI.h" #include "Adafruit_GFX.h" #include "Adafruit_ILI9341.h" #define TFT_DC 9 #define TFT_CS 10 Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); void drawSun(int x, int y) { tft.fillCircle(x, y, 20, ILI9341_YELLOW); // Soleil for (int deg = 0; deg < 360; deg += 45) { float rad = deg * PI / 180; int lineLength = 10; int endX = x + cos(rad) * (20 + lineLength); int endY = y + sin(rad) * (20 + lineLength); tft.drawLine(x, y, endX, endY, ILI9341_YELLOW); } } void clearSun(int x, int y) { int diameter = 60; // Large enough to erase the entire sun tft.fillRect(x - diameter / 2, y - diameter / 2, diameter, diameter, ILI9341_BLACK); } void setup() { tft.begin(); tft.fillScreen(ILI9341_BLACK); tft.setCursor(26, 120); tft.setTextColor(ILI9341_RED); tft.setTextSize(3); tft.println("Hello, TFT!"); tft.setCursor(20, 160); tft.setTextColor(ILI9341_GREEN); tft.setTextSize(2); tft.println("I can has colors?"); } void loop() { static bool sunVisible = true; static unsigned long lastToggleTime = 0; if (millis() - lastToggleTime > 1000) { sunVisible = !sunVisible; if (sunVisible) { drawSun(120, 210); // Coordinates where the sun should be drawn } else { clearSun(120, 210); } lastToggleTime = millis(); } static unsigned long lastUpdateTime = 0; if (millis() - lastUpdateTime > 5000) { tft.fillRect(0, 0, 320, 240, ILI9341_BLACK); // Clear the screen tft.setTextSize(4); tft.setCursor(0,0); tft.print("20 C"); tft.fillRect(0,0,2000,2000,ILI9341_BLACK); //Black box drawn over 'old' time data tft.setCursor(0,0); tft.setTextColor(ILI9341_BLUE); tft.setTextSize(2); tft.print("humidité : "); //je vais changé par la variable aprés tft.setCursor(0,20); tft.setTextSize(4); tft.print("50% "); //je vais changé par la variable aprés tft.setTextSize(2); tft.setCursor(0,80); tft.setTextColor(ILI9341_RED); tft.print("Température"); tft.setTextSize(4); tft.setCursor(0,100 ); tft.print("20C"); tft.setCursor(0,160); tft.setTextSize(2); tft.setTextColor(ILI9341_YELLOW); tft.print("ensoleillement : "); tft.setTextSize(4); tft.setCursor(0,180); tft.print("75% "); //call function to check on temperature and draw new data if necessary delay(1000); lastUpdateTime = millis(); } // Other interface elements may be updated here }
071e573710df991351f0b14fc65c1bcd
{ "intermediate": 0.30388644337654114, "beginner": 0.4907417595386505, "expert": 0.20537178218364716 }
41,354
What is IIIF ?
be5f8c6b6040fdaa888c6a1309045d13
{ "intermediate": 0.32548290491104126, "beginner": 0.1065642386674881, "expert": 0.5679529309272766 }
41,355
telebot. when command /question start asking questions one by one waiting for the previous answer. no need to record the answers. Как вас зовут? Где вы сейчас проживаете? (город, страна) Как с вами можно связаться? (номер телефона или email) Какие операционные системы и устройства у вас есть для тестирования приложений? (iOS, Android, другие) Укажите ваше образование и какие-либо соответствующие сертификации в области IT и тестирования. В какое время вы предпочитаете работать? На каких языках вы можете говорить и писать? Есть ли у вас стабильное интернет-соединение и возможность тестировать приложения без перебоев? -Эта работа предназначена исключительно для владельцев устройств на операционной системе Android. Пожалуйста, подтвердите, что у вас есть устройство Android, которое вы можете использовать для тестирования приложений Укажите, есть ли у вас опыт использования Telegram и других мессенджеров для рабочего общения и выполнения задач. Почему вы заинтересованы в должности тестировщика мобильных приложений? Какие ваши личные качества помогут вам быть успешным в этой роли?
d74823f97e629324624850ff63ee3c16
{ "intermediate": 0.15224727988243103, "beginner": 0.7723678350448608, "expert": 0.07538481056690216 }
41,356
I have this code and I recieve an error from Typescript regarding res 'Argument of type 'IMessage' is not assignable to parameter of type 'never'.' How do I fix it? const sendMessages = async ( prepareMessages: ISendedMessage[], ): Promise<IMessage[]> => { const result = []; for (let i = 0; i < prepareMessages.length; i++) { try { const res = await sendSingleMessage(prepareMessages[i]); result.push(res); } catch (error) { console.error('Ошибка при отправке сообщения'); break; } } return result; };
88316b303e452c85a882bc258732ea04
{ "intermediate": 0.6584071516990662, "beginner": 0.21536920964717865, "expert": 0.126223623752594 }
41,357
hi
fbd39537f2eb53fb9c550705942d423b
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
41,358
function factory<T>(): T { return new T(); }
c718136909713cc4d5eb55555c183758
{ "intermediate": 0.32779672741889954, "beginner": 0.418624609708786, "expert": 0.2535786032676697 }
41,359
mounted() { if (this.loginForm.username === '') { (this.$refs.username as Input).focus() } else if (this.loginForm.password === '') { (this.$refs.password as Input).focus() } } переписать на vue 3 composition api
2aa4807c90fb298eec45bb590213bd61
{ "intermediate": 0.37385421991348267, "beginner": 0.3516604006290436, "expert": 0.27448534965515137 }