עבור לתוכן

פינגווין

משתמש רשום
  • הצטרפות

  • ביקר לאחרונה

  1. יש לי פרויקט שרץ מצוין בצורה לוקאלית, אך לאחר שהעליתי אותו לענן (ויש לי מסד נתונים בענן) - יש בעיה כאשר אני נכנסת ע"י קישור לפרויקט שלי. בלוגים של הסרבר מופיע שיש בעיה במחרוזת החיבור למסד הנתונים- שיש שם פרמטר name, וזה שגוי. בדקתי, הדפסתי ואף ניסיתי מחרוזת חיבור של מישהו אחר שכן עבד לו אותו פרויקט, אך השגיאה נותרה כמו שהייתה. הרבה זמן אני מנסה לפתור את הבעיה שלי, ללא הצלחה. אם מישהו יוכל לעזור לי בעניין- אני מאד אשמח. תודה רבה.warn.pdf
  2. יש לי קוד פייתון תקול: 1. למה לאחר שאני עושה הרשמה או כניסה- מוחזרת לי שגיאה 500? 2. למה קובץ ה-JSON לא נוצר ולא שומר את המשתמש הנוכחי? ואם הוא כן שומר- שומר לי כל פעם רק על השחקן הנוכחי ודורס את כל השחקנים? 3. למה כשנשמרים שחקנים חדשים בקובץ ה-JSON הם נשמרים ללא הפרמטר של COUNT_WIN, וכתוצאה מכך נוצר לי אובייקט לא שלם? (אני חושבת שזה גורם להרבה שגיאות) 4. למה כשאני רוצה שחק לאחר הרשמה או כניסה עדיין מופיעה לי ההודעה שאני צריכה לעשות log_in? 5. מיד כשאני מריצה את הלקוח מופיעה לי השגיאה הבאה: הקובץ לא נמצא או שהוא ריק — ניסיתי להכניס את הקובץ שלי מספר פעמים לבינה מלאכותית בשביל שתפתור לי את הבעיות, אך זה לא עזר. — אני מאד אשמח אם תוכלו לעזור לי. תודה מראש! להלן הקוד שלי: class User: def __init__(self, userName, id, password, countWin=0, countTimes=0, words=None): self.userName = userName self.id = id self.password = password self.countTimes = countTimes self.words = words if words else set() self.countWin = countWin def __str__(self): return (f"userName: {self.userName}; id: {self.id}; password: {self.password};" f"countTimes: {self.countTimes}; words: {self.words}; countWin: {self.countWin};") from flask import Flask, request, jsonify, abort, make_response, session from flask_cors import CORS from User import User import json import random import os import time # תיעוד קוד app = Flask(__name__) CORS(app, supports_credentials=True) usersFile = 'Users.json' # טעינת משתמשים מקובץ ה- JSON def load_users(): """Load users from the JSON file.""" try: if not os.path.exists(usersFile) or os.path.getsize(usersFile) == 0: print("The file users.json is missing or empty.") return [] with open(usersFile, 'r') as file: data = json.load(file) # !!! וידוא שמבנה הקובץ תקין !!! if not isinstance(data, list): print("Error: Invalid JSON structure in users.json.") return [] print(data) return [User(**user) for user in data] # קריאת ה-JSON והמרה לאובייקטים של משתמשים except FileNotFoundError: print("File not found. Initializing with an empty list.") return [] # return {} except json.JSONDecodeError as e: # כאן מודיעים על שגיאה עם קובץ JSON print(f"Error decoding JSON: {e}") return [] # return {} # רשימת המשתמשים users = load_users() # משתמש נוכחי # currentUser: User = None # global currentUser currentUser = None # שמירת משתמשים לקובץ ה- JSON @app.route('/save_users', methods=['POST']) def save_users(): """Save users to the JSON file.""" try: with open(usersFile, 'w') as file: # json.dump([user.__dict__ for user in users], file) # , ensure_ascii=False) # print(currentUser.__dict__) # print(currentUser.__dict__, file) print(users.__str__()) json.dump([user.__dict__ for user in users], file, ensure_ascii=False, indent=4) # שמירת כל המשתמשים בקובץ בפורמט יפה print("Users saved successfully!") print(file.readlines()) except Exception as e: print(f"Error saving users: {e}") abort(500) # !!!!! שגיאה 500 עם הדפסת הסיבה # הרשמה @app.route('/register', methods=['POST']) def register(): # data = request.json global currentUser currentUser = None # !!!! הוספת טיפול בשגיאות בעת גישה ל-JSON או session try: data = request.json # !!! בדיקה אם קלט לא תקין !!! if not data or 'userName' not in data or 'password' not in data: return jsonify({"message": "Invalid input data"}), 400 except Exception as e: print(f"Error processing request: {e}") abort(500) users = load_users() # !!! בדיקה אם המשתמש כבר קיים !!! if any(user.userName == data['userName'] for user in users): return jsonify({"message": "User already exists."}) _id = len(users) + 1 new_user = User(data['userName'], _id, data['password']) print(new_user.__str__()) response = make_response(jsonify({"message": "sign in successfully."})) response.set_cookie("userId", str(new_user.id), max_age=600, httponly=True, secure=False, samesite='None') session['userName'] = new_user.userName print(f"Hello {new_user.userName}") users.append(new_user) currentUser = new_user save_users() # שמירת המשתמשים לאחר הוספת המשתמש החדש # global currentUser # print(f"Hello {data['userName']}") # return jsonify({"message": "User registered successfully."}) return response # התחברות @app.route('/logIn', methods=['POST']) def logIn(): # data = request.json # # userName = data['userName'] # # password = data['password'] # if not data.get('userName') or not data.get('password'): # return jsonify({"message": "Invalid input data."}) # !!!! ודא שהמשתנה 'currentUser' מאותחל בעת ההרשמה או הכניסה global currentUser currentUser = None # !!!! הוספת טיפול בשגיאות בעת גישה ל-JSON או session try: data = request.get_json() # !!! בדיקה אם קלט לא תקין !!! if not data or 'userName' not in data or 'password' not in data: return jsonify({"message": "Invalid input data"}), 400 except Exception as e: print(f"Error processing request: {e}") abort(500) # userName = data.get('userName') # password = data.get('password') # for i in users: # if i.userName == userName and i.password == password: # response = make_response(jsonify({"message": "logIn successfully."})) # response.set_cookie("userId", str(i.id), max_age=600, httponly=True, secure=False, samesite='None') # session['userName'] = userName # print(f"Hello {userName}") # # global currentUser # currentUser = i # return response # return jsonify({"message": "You need to signIn."}) # !!! בדיקת פרטי כניסה !!! for user in users: if user.userName == data['userName'] and user.password == data['password']: currentUser = user response = make_response(jsonify({"message": "logged in successfully."})) response.set_cookie("userId", str(user.id), max_age=600, httponly=True, secure=False, samesite='None') session['userName'] = user.userName print(f"Hello {user.userName}") return response return jsonify({"message": "Invalid username or password."}) # דקורטור לוודא שהמשתמש מחובר def login_required(f): def decorated_function(*args, **kwargs): userId = request.cookies.get('userId') if not userId or not session.get('userName'): # בדיקה אם המשתמש מחובר return jsonify({"message": "You didn't logIn or your playing time is over.\n You need to log in first."}) # register() return f(*args, **kwargs) decorated_function.__name__ = f.__name__ # תיקון שם הפונקציה return decorated_function # רשימת המילים עבור המשחק def load_words(): try: with open('allWords.txt', 'r') as file: print(file.read().strip().split(',')) return file.read().strip().split(',') except FileNotFoundError: return [] # מהלך המשחק @app.route('/play/<int:num>', methods=['POST']) @login_required def play(num): try: words = load_words() if not words: return jsonify({"message": "No words available."}) random.shuffle(words) # ערבוב המילים word = words[num % len(words)] return jsonify({"word": word, "length": len(word)}) except Exception as e: # !!! טיפול בשגיאות במשחק !!! print(f"Error during game: {e}") abort(500) # הסטורית משחקים @app.route('/history', methods=['GET']) @login_required def history(): userId = request.cookies.get('userId') user = next((u for u in users if str(u.id) == userId), None) if user: return jsonify({"message": f"You have played: {user.countTimes} games with words: {user.words.__str__()}, and " f"you won: {user.countWin} times"}) return jsonify({"message": "User not found."}) # יציאה מהמשחק @app.route('/logOut', methods=['POST']) @login_required def logOut(): # session.pop('userName', None) # !!! ניקוי session בעת התנתקות !!! session.clear() return jsonify({"message": "Logged out successfully."}) if __name__ == '__main__': app.run(debug=True) import json from requests import session import time import Server import User basic_url = "http://127.0.0.1:5000" # יצירת אובייקט session sess = session() usersFile= 'Users.json' # תפריט למשתמש def menu(): print("1. sign_in") print("2. log_in") print("3. game") print("4. history") print("5. exit") # הרשמה def register(): global currentUser userName = input("Enter your name: ") password = input("Enter a password: ") response = sess.post(f"{basic_url}/register", json={'userName': userName, 'password': password}) if response.status_code == 200: print(Server.users.__str__()) print(response.text) elif response.status_code == 400: print(response.json()["message"]) else: print(response.status_code) # כניסה def logIn(): global currentUser userName = input("Enter your name: ") password = input("Enter a password: ") response = sess.post(f"{basic_url}/logIn", json={'userName': userName, 'password': password}) if response.status_code == 200: print(Server.users.__str__()) print(response.text) elif response.status_code == 401: print(response.json()["message"]) else: print(response.status_code) # שלבי ה'המן תלוי' def draw_hangman(stage): stages = [ "x-------x", "x-------x\n|\n|\n|\n|\n|", "x-------x\n| |\n|\n|\n|", "x-------x\n| |\n| 0\n|\n|", "x-------x\n| |\n| 0\n| |\n|", "x-------x\n| |\n| 0\n| \\|/\n|", "x-------x\n| |\n| 0\n| \\|/\n| \\", "x-------x\n| |\n| 0\n| \\|/\n| \\ /\n|" ] return stages[stage] # עדכון המשתמש בקובץ ה-JSON def update_user(user): with open(usersFile, 'r') as file: # while True: # u = file.readline() # if u.userName == user.userName and u.password == user.password: # u.replace('') # file.__next__() users = json.load(file) for u in users: if u['userName'] == user.userName and u['password'] == user.password: u.update(user.__dict__) with open(usersFile, 'w') as f: # שמירת כל המשתמשים בקובץ json.dump(users, f, ensure_ascii=False, indent=4) # מהלך המשחק def play(): num = int(input("Enter a number to start the game: ")) response = sess.post(f"{basic_url}/play/{num}") if response.status_code != 200: print(response.json()["message"]) # הודעת שגיאה return data = response.json() if 'word' not in data: # בדיקה אם המפתח 'word' לא קיים print("Error: " + data["message"]) return word = data['word'] length = data['length'] print(word, length) # w='' # for i in len(word): # w+='_' w = ['_' for _ in range(length)] # # w = '_' * response.json()['length'] # יצירת רשימה של _ לפי אורך המילה print(f"You need to guess this word: {w}") # print(f"You need to guess this word: {''.join(w)}") wrongGuesses = 0 guessedLetters = [] while wrongGuesses < 6 and '_' in w: guess = input("Enter a letter: ") if guess in guessedLetters: print("You've already guessed that letter.") continue guessedLetters.append(guess) if guess in word: print("Good guess!") # for i in len(w): # if word[i] == guess: # w['guess'] = guess for i in range(len(word)): if word[i] == guess: w[i] = guess # עדכון ה-guess במיקום הנכון print(w) # print(''.join(w)) else: wrongGuesses += 1 print(draw_hangman(wrongGuesses)) print(f"There are only {6 - wrongGuesses} wrong times left") # for user in Server.users: # if user.userName == Server.currentUser.userName and user.password == Server.currentUser.password: # user.countTimes += 1 # if wrongGuesses != 6: # user.countWin += 1 # update_user(Server.currentUser) # sess.post(f"{basic_url}/save_users") if wrongGuesses != 6: Server.currentUser.countTimes+=1 Server.currentUser.countWin+=1 # return {f"message": f"You won!. The word is: {word}"} # return {f"message": f"You lost! The word was: {word}"} print(f"You won! The word is: {word}") else: Server.currentUser.countTimes+=1 print(f"You lost! The word was: {word}") update_user(Server.currentUser) sess.post(f"{basic_url}/save_users") # הסטורית משתמש def history(): response = sess.get(f"{basic_url}/history") if response.status_code == 200: # return response.json()["message"] # return response.json()["message"] print(response.json()["message"]) else: print(response.json()["message"]) # יציאה מהמשחק def logOut(): response = sess.post(f"{basic_url}/logOut") print(response.text) def main(): while True: menu() choice = input("Choose an option: ") if choice == '1': register() elif choice == '2': logIn() elif choice == '3': play() elif choice == '4': history() elif choice == '5': logOut() break else: print("wrong choice") return if __name__ == '__main__': main() קובץ allWords.txt: apple, banana, tangerine, plum, orange, cucumber, tomato, caret, date, grape, melon, watermelon, squash, pepper, eggplant, avocado, lemon, nectarine
  3. יש לי את הקוד הבא: מחלקת HtmlElement: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace p2 { public class HtmlElement { public string id { get; set; } public string name { get; set; } public List<string> attributes { get; set; } public List<string> classes { get; set; } public string innerHtml { get; set; } public HtmlElement parent { get; set; } public List<HtmlElement> children { get; set; } public HtmlElement() { attributes = new List<string>(); classes = new List<string>(); children = new List<HtmlElement>(); } public override string ToString() { return "["+"id: "+id+", name: "+name+", attributes: "+attributes.ToString()+", classes: "+classes.ToString() +", innerHtml: "+innerHtml+", parent: "+parent+", children: "+children.ToString()+" ]"; } } } מחלקת HtmlHelper: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace p2 { public class HtmlHelper { private readonly static HtmlHelper instance = new HtmlHelper(); public static HtmlHelper Instance => instance; public string[] openCloseTags { get; set; } public string[] openTags { get; set; } public HtmlHelper() { openCloseTags= JsonSerializer.Deserialize<string[]>(File.ReadAllText("seed/HtmlTags.json")); openTags = JsonSerializer.Deserialize<string[]>(File.ReadAllText("seed/HtmlVoidTags.json")); } } } Program: using p2; using System.Text.RegularExpressions; var html = await Load("https://hebrewbooks.org/beis"); var cleanHtml = new Regex(@"\s+").Replace(html, " "); var htmlLines = new Regex("<(.*?)>").Split(cleanHtml).Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); var htmlE = "<div id=\"my-id\" class=\"my-class-1 my-class-2\" width=\"100%\">text</div>"; var attributes = new Regex("([^\\s]*?)=\"(.*?)\"").Matches(htmlE); //HtmlHelper a = new HtmlHelper(); //Console.WriteLine(); Console.ReadLine(); var handler = new HttpClientHandler(); async Task<string> Load(string url) { HttpClient client = new HttpClient(); var response = await client.GetAsync(url); var html = await response.Content.ReadAsStringAsync(); return html; } //בניית העץ HtmlElement root = new HtmlElement(); root.name = htmlLines[0]; root.parent = null; HtmlElement tElement = new HtmlElement(); string tempElement; string pattern = @"(\w+)=[""']?([^""' >]+)[""']?"; List<string> allTags = new List<string>(); foreach (var tag in HtmlHelper.Instance.openTags) allTags.Add(tag); foreach (var tag in HtmlHelper.Instance.openCloseTags) allTags.Add(tag); for (int i = 1; i < htmlLines.Count; i++) { var l = htmlLines[i].Split(" "); tempElement = l[0]; if (tempElement == "/html") break; if (tempElement[0] == '/') { tElement = tElement.parent; } else { if (tempElement == "html") { HtmlElement obj = new HtmlElement(); obj.name = tempElement; obj.parent = root; root.children.Add(obj); tElement = obj; } else { if (allTags.Contains(tempElement)) { HtmlElement obj = new HtmlElement(); obj.name = tempElement; obj.parent = tElement; var strLine = htmlLines[i].Substring(tempElement.Length); MatchCollection maches = Regex.Matches(strLine, pattern); foreach (Match m in maches) { obj.attributes.Add(m.Groups[1].Value); if (m.Groups[1].Value == "class") { foreach (var v in m.Groups[2].Value.Split(" ")) obj.classes.Add(v); } else if (m.Groups[1].Value == "id") obj.id = m.Groups[2].Value; } tElement.children.Add(obj); if (HtmlHelper.Instance.openCloseTags.Contains(tempElement)) { tElement = obj; } break; } else tElement.innerHtml = htmlLines[i]; } } HtmlElement ht = root; } Console.ReadLine(); כל הזמן נופלת לי שגיאה שה-root שלי null, וגם כל אוביקט מסוג HtmlElement הוא null כלומר יש איזה שגיאה בקוד.
  4. אני מעוניין למחוק שורות ריקות מקובצי טקסט בתוך תיקייה מסוימת באמצאות קוד C#. המטרה שלי היא שמחיקת השורות הריקות תתבצע ישירות בקבצים המקוריים, ולא שהקבצים יועתקו או שיהיו קבצים זמניים וכו’. כאשר ניסיתי לעשות זאת בעצמי, או שלא הגעתי לתוצאה, או שקיבלתי תוצאות רק בהעתק, ולא כמו שאני מעוניינת - שהשינויים יתבצעו ישירות בקבצי המקור! תודה מראש.
  5. מסיבות אישיות, אני רוצה עזרה דווקא מכאן ולא מ- chatgpt!
  6. פינגווין הצטרף לפורומים
  7. אני עובדת עם ב-C# WINFORM. יש לי list_box ואני רוצה לחפש בו מילה מסוימת ואז לצבוע את המילה שנמצאה ב-list_box בצבע ייחודי. כיצד עושים זאת? תודה מראש.