diff --git "a/4546.jsonl" "b/4546.jsonl" new file mode 100644--- /dev/null +++ "b/4546.jsonl" @@ -0,0 +1,664 @@ +{"seq_id":"210306788","text":"import threading\nimport requests\nfrom http.server import HTTPServer\n\n\nfrom periskop_client.handler import exception_http_handler\nfrom periskop_client.models import HTTPContext\n\n\ndef err_func():\n return 1 / 0\n\n\ndef test_integration(collector, exporter):\n try:\n err_func()\n except Exception as exception:\n collector.report(exception)\n collector.report_with_context(exception,\n HTTPContext(\"GET\", \"http://example.com\", {\"Cache-Control\": \"no-cache\"}))\n server_address = ('', 8686)\n httpd = HTTPServer(server_address, exception_http_handler(path=\"/-/exceptions\", exporter=exporter))\n t = threading.Thread(target=httpd.serve_forever)\n t.daemon = True\n t.start()\n response = requests.get(\"http://localhost:8686/-/exceptions\")\n assert response.status_code == 200\n assert response.json()['aggregated_errors'][0]['total_count'] == 2\n","sub_path":"tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"56131398","text":"import os\nimport speech_recognition as sr\nimport datetime as dt\nimport pyttsx3\nimport wikipedia\nimport webbrowser\nimport pygame\nimport random\nimport smtplib\n\n#setup the speaking assistant\nengine = pyttsx3.init(\"nsss\")\nvoices = engine.getProperty(\"voices\")\n# print(voices)\nengine.setProperty(\"voice\", voices[7].id)\n\n\n\ndef speak(audio):\n \"\"\"Will relay a message back to the user\"\"\"\n engine.say(audio)\n engine.runAndWait()\n\ndef wishMe():\n \"\"\"Greet the user with basic hello\"\"\"\n hour = int(dt.datetime.now().hour)\n if hour>= 0 and hour<12:\n speak(\"Good Morning\")\n elif hour>=12 and hour<18:\n speak(\"Good afternoon!\")\n else:\n speak(\"Good Evening\")\n\n speak(\"I am your personal assistant! How may I help you?\")\n\ndef takeCommand():\n \"\"\"Will take a voice command from user, and return a string output\"\"\"\n\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening...\")\n r.pause_threshold = 1\n audio = r.listen(source)\n try:\n print(\"Recognizing... \")\n voice_input = r.recognize_google(audio, language=\"en-US\")\n print(f\"The user said: {voice_input}\\n\")\n except Exception as e:\n # print(e)\n print(\"Please say that again\")\n return \"None\"\n return voice_input\n\n\ndef musiconloop(song, keyword):\n \"\"\"Will play music files\"\"\"\n pygame.mixer.init()\n pygame.mixer.music.load(song)\n pygame.mixer.music.play()\n while True:\n inp = input(f\"Please enter {keyword} to continue: \")\n if inp == keyword:\n pygame.mixer.music.stop()\n break;\n\ndef sendEmail(recipient, content):\n \"\"\"Will send a personal email\"\"\"\n server = smtplib.SMTP(\"smtp@gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.login(\"youremail@gmail.com\", \"password\")\n server.sendmail(\"youremail@gmail.com\", recipient, content)\n server.close()\n\ndef main():\n wishMe()\n\n while True:\n voice_command = takeCommand().lower()\n print(f\"lower case: {voice_command}\")\n if \"wikipedia\" == voice_command:\n continue\n if \"wikipedia\" in voice_command:\n speak(\"Searching Wikipedia...\")\n voice_command = voice_command.replace(\"wikipedia\", \"\")\n results = wikipedia.summary(voice_command, sentences=2)\n print(results)\n speak(\"According to wikipedia,\" + results)\n elif \"open youtube\" in voice_command or \"open youtube.com\" in voice_command:\n webbrowser.open(\"https://www.youtube.com\")\n elif \"open google\" in voice_command or \"open google.com\" in voice_command:\n webbrowser.open(\"https://www.google.ca\")\n elif \"open facebook\" in voice_command or \"open facebook.com\" in voice_command:\n webbrowser.open(\"https://www.facebook.com\")\n elif \"play music\" in voice_command or \"put on a song\" in voice_command:\n mus_dir = os.chdir(r\"/Users/husseinnagri/Music/iTunes/iTunes Media/Music/Unknown Artist/Unknown Album\")\n songs = os.listdir(mus_dir)\n print(songs)\n for song in songs:\n if \".mp3\" in song:\n continue\n elif \".mp3\" not in song:\n songs.remove(song)\n musiconloop(random.choice(songs), \"done\")\n\n elif \"the time\" in voice_command or \"time\" in voice_command:\n strTime = dt.datetime.now().strftime(\"%H:%M:%S\")\n speak(f\"The time is {strTime} right now!\")\n\n elif \"open code\" in voice_command:\n os.system(\"open -a /Applications/Xcode.app \")\n\n elif \"what is your name\" in voice_command:\n speak(\"My name is Jarvis! I will be your personal assistant.\")\n elif \"send email\" in voice_command:\n try:\n speak(\"What should I say? \")\n email_content = takeCommand()\n to = \"husseinnagri@hotmail.com\"\n sendEmail(to, email_content)\n speak(\"The email has been sent!\")\n except Exception as e:\n print(e)\n speak(\"Sorry, the email could not be sent!\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"284826527","text":"# Taking a number for stars\nnum = int(input('Enter an integer: '))*2 - 1\n# Making variables for making stars\na = num\nb = 0\nc = 0\noutput = ''\nstar = '*'\n\n# Printing stars\nwhile a >= 1:\n b = 0\n output = ''\n while b < a:\n output = output + star\n b = b+1\n for sss in range(c):\n print(' ', end = '')\n print(output)\n a = a-2\n c = c+1\n","sub_path":"lab 05/lab5_p4.py","file_name":"lab5_p4.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"465994497","text":"import os\nimport re\nfrom urllib.parse import urlparse\n\n\ndef to_file_name(base_url):\n _, ext = os.path.splitext(urlparse(base_url).path)\n if ext:\n url, ext = os.path.splitext(base_url)\n else:\n ext = '.html'\n url = base_url\n url_parts = re.split('[^a-zA-Z0-9]+', url)\n url_parts.pop(0)\n max_len = 10\n while len(url_parts) > max_len:\n url_parts.pop(0)\n return '-'.join(url_parts) + ext\n","sub_path":"page_loader/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4107718","text":"# Autor: Juan Carlos Flores García, A01376511\r\n\r\n# Descripción: Programa que convierte las horas del formato de 24 horas al formato de 12 horas.\r\n\r\n\r\n# La siguiente función convierte las horas del formato de 24 horas al formato de 12 horas.\r\ndef convertirFormatoHorario(horas, minutos, segundos):\r\n if (0 <= horas <= 23) and (0 <= minutos <= 59) and (0 <= segundos <= 59):\r\n\r\n if horas < 12:\r\n horas = horas - 12\r\n return (\"%d: %02d: %02d am\" % (horas, minutos, segundos))\r\n else:\r\n return (\"%d: %02d: %02d pm\" % (horas, minutos, segundos))\r\n\r\n else:\r\n return (\"Error\")\r\n\r\n\r\n# La función principal lee los valores de horas, minutos y segundos además de imprimir las horas en el formato de 12.\r\ndef main ():\r\n\r\n horas = int(input(\"Teclea las horas: \"))\r\n minutos = int(input(\"Teclea los minutos: \"))\r\n segundos = int(input(\"Teclea los segundos: \"))\r\n\r\n print(convertirFormatoHorario(horas, minutos, segundos))\r\n\r\n#Llamada a la funcion main.\r\nmain()","sub_path":"Reloj.py","file_name":"Reloj.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"442258918","text":"import csv\r\nimport random\r\nimport math\r\nimport operator\r\n\r\n\r\n# 1- Loading Data Set from the csv file\r\n# Loading data set from the csv file\r\n# Appending training and test sets into two different arrays\r\ndef Load_Data_Set(file_name, split, training_set=[], test_set=[]):\r\n with open(file_name, 'r') as csvFile:\r\n lines = csv.reader(csvFile)\r\n data_set = list(lines)\r\n for row in range(len(data_set) - 1):\r\n for col in range(4):\r\n data_set[row][col] = float(data_set[row][col])\r\n if random.random() < split:\r\n training_set.append(data_set[row])\r\n else:\r\n test_set.append(data_set[row])\r\n\r\n\r\n# Testing (Load_Data_Set) function's output\r\ndef test_Load_Data_Set():\r\n Training_Set = []\r\n Test_Set = []\r\n Load_Data_Set('iris.data.txt', 0.65, Training_Set, Test_Set)\r\n print('Number of Train Sets : ' + str(len(Training_Set)))\r\n print('Number of Test Sets : ' + str(len(Test_Set)))\r\n\r\n\r\n# 2- Similarity\r\n# In order to make predictions we need to calculate the similarity between\r\n# any two given data instances. This is needed so that we can locate the k most similar data instances\r\n# in the training dataset for a given member of the test dataset and in turn make a prediction.\r\n# Given that all four flower measurements are numeric and have the same units,\r\n# we can directly use the Euclidean distance measure. This is defined as the square root of the sum of the squared\r\n# differences between the two arrays of numbers (read that again a few times and let it sink in).\r\ndef Eculidian_Distance(instance1, instance2, length):\r\n distance = 0\r\n for col in range(length):\r\n distance += pow(instance1[col] - instance2[col], 2)\r\n return math.sqrt(distance)\r\n\r\n\r\n# Testing (Eculidian_Distance) function's output\r\ndef test_Eculidian_Distance():\r\n data1 = [2, 2, 2, 'a']\r\n data2 = [4, 4, 4, 'b']\r\n distance = Eculidian_Distance(data1, data2, 3)\r\n print('distance : ' + str(distance))\r\n\r\n\r\n# 3- Neighbors\r\n# Now that we have a similarity measure, we can use it collect the k most similar instances for a given unseen instance.\r\n# This is a straight forward process of calculating the distance for all instances and selecting\r\n# a subset with the smallest distance values.\r\n# Below is the getNeighbors function that returns k most similar neighbors from the training\r\n# set for a given test instance (using the already defined euclideanDistance function)\r\ndef Get_Neighbors(training_set, test_instance, k):\r\n All_Distances = []\r\n length = len(test_instance) - 1\r\n for row in range(len(training_set)):\r\n dist = Eculidian_Distance(training_set[row], test_instance, length)\r\n All_Distances.append((training_set[row], dist))\r\n # Sorting the array depending on the first parameter\r\n All_Distances.sort(key=operator.itemgetter(1))\r\n neighbors = []\r\n for x in range(k):\r\n neighbors.append(All_Distances[x][0])\r\n return neighbors\r\n\r\n\r\n# Testing (Get_Neighbors) function's output\r\ndef test_Get_Neighbors():\r\n traing_test = [[2, 2, 2, 'a'], [4, 4, 4, 'b']]\r\n test_instance = [5, 5, 5]\r\n k = 1\r\n neighbors = Get_Neighbors(traing_test, test_instance, k)\r\n print(neighbors)\r\n\r\n\r\n# 4- Response\r\n# Once we have located the most similar neighbors for a test instance, the next task is to devise a\r\n# predicted response based on those neighbors. We can do this by allowing each neighbor to vote for their class\r\n# attribute, and take the majority vote as the prediction. Below provides a function for getting the majority voted\r\n# response from a number of neighbors. It assumes the class is the last attribute for each neighbor.\r\ndef Get_Response(neighbors):\r\n classVotes = {}\r\n for x in range(len(neighbors)):\r\n response = neighbors[x][-1]\r\n if response in classVotes:\r\n classVotes[response] += 1\r\n else:\r\n classVotes[response] = 1\r\n sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)\r\n return sortedVotes[0][0]\r\n\r\n\r\n# Testing (Get_Response) function's output\r\ndef test_Get_Response():\r\n neighbors = [[1, 1, 1, 'a'], [2, 2, 2, 'a'], [3, 3, 3, 'b']]\r\n response = Get_Response(neighbors)\r\n print(response)\r\n\r\n\r\n# 5- Accuracy\r\n# We have all of the pieces of the kNN algorithm in place. An important remaining concern\r\n# is how to evaluate the accuracy of predictions.\r\n# An easy way to evaluate the accuracy of the model is to calculate a ratio of the total\r\n# correct predictions out of all predictions made, called the classification accuracy.\r\n# Below is the getAccuracy function that sums the total correct predictions and returns the accuracy\r\n# as a percentage of correct classifications.\r\ndef Get_Accuracy(testSet, predictions):\r\n correct = 0\r\n for x in range(len(testSet)):\r\n if testSet[x][-1] == predictions[x]:\r\n correct += 1\r\n return (correct / float(len(testSet))) * 100.0\r\n\r\n\r\n# Testing (Get_Accuracy) function's output\r\ndef test_Get_Accuracy():\r\n testSet = [[1, 1, 1, 'a'], [2, 2, 2, 'a'], [3, 3, 3, 'b']]\r\n predictions = ['a', 'a', 'a']\r\n accuracy = Get_Accuracy(testSet, predictions)\r\n print(accuracy)\r\n\r\n\r\n# 6- Main function\r\ndef main():\r\n # Preparing data\r\n Training_Set = []\r\n Test_Set = []\r\n split = 0.67\r\n Load_Data_Set('iris.data.txt', split, Training_Set, Test_Set)\r\n print('Train set : ' + str(len(Training_Set)))\r\n print('Test set : ' + str(len(Test_Set)))\r\n # Generate Predictions\r\n predictions = []\r\n k = 3\r\n for row in range(len(Test_Set)):\r\n neighbors = Get_Neighbors(Training_Set, Test_Set[row], k)\r\n result = Get_Response(neighbors)\r\n predictions.append(result)\r\n print('Predicted = ' + str(result) + ', Actual = ' + str(Test_Set[row][-1]))\r\n accuracy = Get_Accuracy(Test_Set, predictions)\r\n print('Accuracy : ' + str(accuracy) + '%')\r\n\r\n\r\nmain()\r\n","sub_path":"KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268199168","text":"import pytest\n\nfrom petisco import CorrelationId\nfrom petisco.domain.entities.client_id import ClientId\nfrom petisco.domain.entities.user_id import UserId\nfrom petisco.events.event import Event\n\n\nclass UserCreated(Event):\n user_id: UserId\n client_id: ClientId\n version: str\n correlation_id: CorrelationId = None\n\n def __init__(\n self,\n user_id: UserId,\n client_id: ClientId,\n correlation_id: CorrelationId,\n version: str = \"1.0.0\",\n ):\n self.user_id = user_id\n self.client_id = client_id\n self.correlation_id = correlation_id\n self.version = version\n super().__init__()\n\n\n@pytest.mark.unit\ndef test_should_create_an_event_and_check_to_dict_from_dict(\n given_any_user_id, given_any_client_id, given_any_correlation_id\n):\n\n event = UserCreated(\n user_id=given_any_user_id,\n client_id=given_any_client_id,\n correlation_id=given_any_correlation_id,\n )\n\n event_dict = event.to_dict()\n\n retrieved_event = UserCreated.from_dict(event_dict)\n\n assert event == retrieved_event\n assert event.user_id == given_any_user_id\n assert event.client_id == given_any_client_id\n\n\n@pytest.mark.unit\ndef test_should_create_an_event_and_check_to_json_from_json(\n given_any_user_id, given_any_client_id, given_any_correlation_id\n):\n\n event = UserCreated(\n user_id=given_any_user_id,\n client_id=given_any_client_id,\n correlation_id=given_any_correlation_id,\n )\n\n event_json = event.to_json()\n retrieved_event = UserCreated.from_json(event_json)\n\n assert event == retrieved_event\n\n\n@pytest.mark.unit\ndef test_should_load_an_event_agnostically(\n given_any_user_id, given_any_client_id, given_any_correlation_id\n):\n\n event = UserCreated(\n user_id=given_any_user_id,\n client_id=given_any_client_id,\n correlation_id=given_any_correlation_id,\n )\n\n event_json = event.to_json()\n agnostic_event = Event.from_json(event_json)\n\n assert event == agnostic_event\n","sub_path":"tests/unit/events/test_event.py","file_name":"test_event.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92177857","text":"#!/usr/bin/env python3\nimport math\nfrom os import path\n\nprime_file = path.dirname(path.abspath(__file__)) + '/data/prime.txt'\n\nclass PrimeFinder():\n def __init__(self, prime_file):\n # Load primes\n self.file = open(prime_file, 'r+')\n self.base_prime = [2]\n line = self.file.readline()\n while line is not '':\n n = int(line.rstrip('\\n'))\n self.base_prime.append(n)\n line = self.file.readline()\n\n def find_cache(self, n):\n return n in self.base_prime\n\n def check_is_prime(self, n, add_to_cache = True):\n print('>> No cache used for %d' % n)\n n_is_prime = True\n\n for x in range(2, math.ceil(math.sqrt(n))):\n if n % x is 0:\n n_is_prime = False\n break\n\n if n_is_prime and add_to_cache:\n self.base_prime.append(n)\n self.file.write('%d\\n' % n)\n\n def check(self, n):\n return self.find_cache(n) or self.check_is_prime(n, True)\n\n\nif __name__ == '__main__':\n pf = PrimeFinder(prime_file)\n n = int(input())\n if pf.check(n):\n print ('Yes, %d is a prime.' % n)\n else:\n print ('No, %d is not a prime.' % n)\n","sub_path":"Challenge I - Prime Numbers/clever.py","file_name":"clever.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"619651268","text":"'''\n/*문제 정보 */\n2805번 - 나무 자르기\n난이도 - 실버 2\n/*풀이 방법 */\n1부터 n 까지 도는 방식으로는 시간초과가 걸린다.\n이분탐색으로 mid 의 값과 비교해 답을 구했다.\n'''\nimport sys\ninput = sys.stdin.readline\n\nn, m = map(int,input().split())\ntree = list(map(int, input().split()))\n\nstart = 1\nend = max(tree)\nmid = 0\n\nwhile start <= end:\n mid = (start + end) // 2\n ans = 0\n for i in tree:\n if i > mid:\n ans += (i - mid)\n if ans > m:\n break\n if ans >= m:\n start = mid + 1\n else:\n end = mid - 1\n\nprint(end)\n'''\n/*오답 노트*/\n오답1 : 시간초과\nimport sys\ninput = sys.stdin.readline\n\nn, m = map(int,input().split())\ntree = list(map(int, input().split()))\n\ncut_tree = 0\nmeter = max(tree)\n\nwhile 1:\n meter -= 1\n for i in range(n):\n if tree[i] - meter >= 0:\n cut_tree += tree[i] - meter\n if cut_tree == m:\n print(meter)\n break\n cut_tree = 0\n \nif tree[i] - meter >= 0: \n cut_tree += tree[i] - meter\n if cut_tree > m:\n break\n 나무를 더하는 과정에서 이미 m 을 넘으면 break 를 걸어줘도 시간초과\n\n/*느낀 점*/\n if num >= m :\n break\n 이분탐색이어도 이 if 문을 걸지 않으면 시간 초과가 걸렸다.\n'''","sub_path":"season2/season2/week9/sunghoon/2805.py","file_name":"2805.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"190785220","text":"#CH05-Lab08 사용자가 원하는 도형 그리기\r\n\r\nimport turtle\r\nt = turtle.Turtle( )\r\nt.shape(\"turtle\")\r\nx1 = int(input(\"큰 원의 중심좌표 x1: \"))\r\ny1 = int(input(\"큰 원의 중심좌표 y1: \"))\r\nr1 = int(input(\"큰 원의 반지름: \"))\r\nx2 = int(input(\"작은 원의 중심좌표 x2: \"))\r\ny2 = int(input(\"작은 원의 중심좌표 y2: \"))\r\nr2 = int(input(\"작은 원의 반지름: \"))\r\n\r\nt.penup( )\r\nt.goto(x1, y1)\r\nyy1 = y1 - r1\t\t# circle( )의 특성으로 인해 원을 그리는 위치 조정\r\nt.goto(x1, yy1)\r\nt.pendown( )\r\nt.circle(r1)\r\n\r\nt.penup( )\r\nt.goto(x2, y2)\r\nyy2 = y2 - r2\t\t# circle( )의 특성으로 인해 원을 그리는 위치 조정\r\nt.goto(x2, yy2)\r\nt.pendown( )\r\nt.circle(r2)\r\n\r\ndist = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5 \t#두 원의 중심사이의 거리\r\n\r\nif dist == 0:\r\n turtle.write(\"동심원\")\r\nelif dist == r1 - r2:\r\n turtle.write(\"내접\")\r\nelif r1 - r2 < dist < r1 + r2:\r\n turtle.write(\"두 점에서 만납니다.\")\r\nelif dist > r1 + r2:\r\n turtle.write(\"만나지 않고 외부에 있습니다.\")\r\nelif dist == r1 + r2:\r\n turtle.write(\"외접\")\r\nelif dist < r1 - r2:\r\n turtle.write(\"만나지 않고 내부에 있습니다.\")\r\n\r\n\r\n","sub_path":"CH05-Lab09.py","file_name":"CH05-Lab09.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"452152696","text":"#!/usr/bin/python3\n\nimport sys\n\nwidth = 100\nheight = 100\nz = 0\ndata = [[], []]\n\nfile = open(sys.argv[1])\nfor line in file:\n words = line.strip().split(' ')\n for word in words:\n while word.startswith('['): word = word[1:]\n while word.endswith(']'): word = word[:-1]\n try:\n value = float(word)\n data[z].append(word)\n z = (z + 1) % 2\n except ValueError:\n pass\n \n\npadding_height = 5\npadding_width = 5\n\nassert len(data[0]) == width * height\nassert len(data[1]) == width * height\n\ndef printLayer(z):\n effectiveWidth = width + 2 * padding_width\n\n string = '[*,*,' + str(z + 1) + '] : '\n for i in range(effectiveWidth): string = string + str(i + 1) + ' '\n string = string + ':='\n print(string)\n\n for i in range(padding_height):\n string = str(i + 1)\n for j in range(effectiveWidth): string = string + ' 0'\n print(string)\n\n index = 0\n for i in range(height):\n string = str(i + 1 + padding_height)\n for j in range(padding_width): string = string + ' 0'\n for j in range(width):\n string = string + ' ' + str(data[z][index])\n index = index + 1\n for j in range(padding_width): string = string + ' 0'\n print(string)\n\n for i in range(padding_height):\n string = str(i + 1 + height + padding_height)\n for j in range(effectiveWidth): string = string + ' 0'\n print(string)\n\nprint('param x_ :=')\nprintLayer(0)\nprintLayer(1)\nprint(';\\n')\n\n","sub_path":"python/convertInputReal.py","file_name":"convertInputReal.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"32625164","text":"\"\"\"\nconvert hitgraphs to network-x and prepare graphs for graph-nets\n\"\"\"\nimport numpy as np\nfrom datasets.graph import load_graph\nimport networkx as nx\n\nimport os\nimport glob\nimport re\n\ndef calc_dphi(phi1, phi2):\n \"\"\"Computes phi2-phi1 given in range [-pi,pi]\"\"\"\n dphi = phi2 - phi1\n if dphi > np.pi:\n dphi -= 2*np.pi\n if dphi < -np.pi:\n dphi += 2*np.pi\n return dphi\n\ndef get_edge_features(in_node, out_node):\n # input are the features of incoming and outgoing nodes\n # they are ordered as [r, phi, z]\n in_r, in_phi, in_z = in_node\n out_r, out_phi, out_z = out_node\n\n in_r3 = np.sqrt(in_r**2 + in_z**2)\n out_r3 = np.sqrt(out_r**2 + out_z**2)\n\n in_theta = np.arccos(in_z/in_r3)\n in_eta = -np.log(np.tan(in_theta/2.0))\n out_theta = np.arccos(out_z/out_r3)\n out_eta = -np.log(np.tan(out_theta/2.0))\n deta = out_eta - in_eta\n dphi = calc_dphi(out_phi, in_phi)\n dR = np.sqrt(deta**2 + dphi**2)\n dZ = in_z - out_z\n return np.array([deta, dphi, dR, dZ])\n\n\ndef hitsgraph_to_networkx_graph(G):\n n_nodes, n_edges = G.Ri.shape\n\n graph = nx.DiGraph()\n\n ## add nodes\n for i in range(n_nodes):\n graph.add_node(i, pos=G.X[i], solution=0.0)\n\n for iedge in range(n_edges):\n in_node_id = G.Ri[:, iedge].nonzero()[0][0]\n out_node_id = G.Ro[:, iedge].nonzero()[0][0]\n\n # distance as features\n in_node_features = G.X[in_node_id]\n out_node_features = G.X[out_node_id]\n distance = get_edge_features(in_node_features, out_node_features)\n # add edges, bi-directions\n graph.add_edge(in_node_id, out_node_id, distance=distance, solution=G.y[iedge])\n graph.add_edge(out_node_id, in_node_id, distance=distance, solution=G.y[iedge])\n # add \"solution\" to nodes\n graph.node[in_node_id].update(solution=G.y[iedge])\n graph.node[out_node_id].update(solution=G.y[iedge])\n\n # add global features, not used for now\n graph.graph['features'] = np.array([0.])\n return graph\n\n\ndef graph_to_input_target(graph):\n def create_feature(attr, fields):\n return np.hstack([np.array(attr[field], dtype=float) for field in fields])\n\n input_node_fields = (\"pos\",)\n input_edge_fields = (\"distance\",)\n target_node_fields = (\"solution\",)\n target_edge_fields = (\"solution\",)\n\n input_graph = graph.copy()\n target_graph = graph.copy()\n\n for node_index, node_feature in graph.nodes(data=True):\n input_graph.add_node(\n node_index, features=create_feature(node_feature, input_node_fields)\n )\n target_graph.add_node(\n node_index, features=create_feature(node_feature, target_node_fields)\n )\n\n for receiver, sender, features in graph.edges(data=True):\n input_graph.add_edge(\n sender, receiver, features=create_feature(features, input_edge_fields)\n )\n target_graph.add_edge(\n sender, receiver, features=create_feature(features, target_edge_fields)\n )\n\n input_graph.graph['features'] = input_graph.graph['features'] = np.array([0.0])\n return input_graph, target_graph\n\n\ndef inputs_generator(base_dir_, n_train_fraction=-1):\n base_dir = base_dir_\n\n file_patten = base_dir.format(1000, 0).replace('1000', '*')\n all_files = glob.glob(file_patten)\n n_events = len(all_files)\n evt_ids = [int(re.search('event00000([0-9]*)_g000.npz', os.path.basename(x)).group(1))\n for x in all_files]\n\n section_patten = base_dir.format(1000, 0).replace('_g000', '_g[0-9]*[0-9]*[0-9]')\n n_sections = len(glob.glob(section_patten))\n n_total = n_events*n_sections\n\n n_tr_fr = n_train_fraction if n_train_fraction > 0 else 0.7\n n_max_evt_id_tr = int(n_events * n_tr_fr)\n n_test = n_events - n_max_evt_id_tr\n\n print(\"Total Events: {} with {} sections, total {} files \".format(\n n_events, n_sections, n_total))\n print(\"Training data: [{}, {}] events, total {} files\".format(0, n_max_evt_id_tr-1, n_max_evt_id_tr*n_sections))\n print(\"Testing data: [{}, {}] events, total {} files\".format(n_max_evt_id_tr, n_events, n_test*n_sections))\n\n\n # keep track of training events\n global _evt_id_tr_\n _evt_id_tr_ = 0\n global _sec_id_tr_\n _sec_id_tr_ = 0\n ## keep track of testing events\n global _evt_id_te_\n _evt_id_te_ = n_max_evt_id_tr\n global _sec_id_te_\n _sec_id_te_ = 0\n\n def generate_input_target(n_graphs, is_train=True):\n global _evt_id_tr_\n global _sec_id_tr_\n global _evt_id_te_\n global _sec_id_te_\n input_graphs = []\n target_graphs = []\n igraphs = 0\n while igraphs < n_graphs:\n # determine while file to read\n if is_train:\n file_name = base_dir.format(evt_ids[_evt_id_tr_], _sec_id_tr_)\n _sec_id_tr_ += 1\n if _sec_id_tr_ == n_sections:\n _evt_id_tr_ += 1\n _sec_id_tr_ = 0\n if _evt_id_tr_ >= n_max_evt_id_tr:\n _evt_id_tr_ = 0\n else:\n file_name = base_dir.format(evt_ids[_evt_id_te_], _sec_id_te_)\n _sec_id_te_ += 1\n if _sec_id_te_ == n_sections:\n _evt_id_te_ += 1\n _sec_id_te_ = 0\n if _evt_id_te_ >= n_events:\n _evt_id_te_ = n_max_evt_id_tr\n\n\n graph = hitsgraph_to_networkx_graph(load_graph(file_name))\n input_graph, output_graph = graph_to_input_target(graph)\n input_graphs.append(input_graph)\n target_graphs.append(output_graph)\n igraphs += 1\n\n return input_graphs, target_graphs\n\n return generate_input_target\n","sub_path":"nx_graph/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":5753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"192576308","text":"import urllib.request\nimport urllib\nimport urllib.parse\nimport requests\nimport base64\nimport pyaudio\nimport wave\nimport json\nimport pygame\nimport time\n\ndef recordWave():\n\n CHUNK = 1024 # frame per buffer\n FORMAT = pyaudio.paInt16\n CHANNELS = 1 #???\n RATE = 8000 # sampling frequency ,8000 is perfect to recognize human voice\n RECORD_SECONDS = 3\n WAVE_OUTPUT_FILENAME = \"record.wav\"\n\n p = pyaudio.PyAudio()\n # create a pyaudio object\n\n stream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\n # step up a pyaudio.steam to record\n\n print(\"* recording\") # show this on the screen\n\n frames = []\n\n for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n frames.append(data)\n\n print(\"* done\")\n\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(RATE)\n wf.writeframes(b''.join(frames))\n wf.close()\n\n\ndef readWave(file = r'output.mp3', t = 4):\n pygame.mixer.init()\n track = pygame.mixer.music.load(file)\n pygame.mixer.music.play()\n time.sleep(t)\n pygame.mixer.music.stop()\n\n\n\ndef replyByTuring(Question = '你好'):\n # reply the question by turing robot\n\n KEY = '7f2a9fe108b346b08d8c807622c9a54b'\n url = 'http://www.tuling123.com/openapi/api'\n USER_ID = 'robotGameUser'\n location = '安徽省合肥市'\n Question = bytes(Question, encoding = 'utf-8')\n\n data_post = {\"key\": KEY,\n \"info\": Question,\n \"userid\": USER_ID,\n \"loc\": location\n }\n\n Answer = requests.post(url, data=data_post)\n result = json.loads(Answer.text)\n code = result[\"code\"]\n\n if code == 100000:\n # only text\n text = result['text']\n print(text + '\\n')\n return text\n\n elif code == 200000:\n # text and url\n text = result['text']\n print(text + '\\n', result[\"url\"])\n return text\n\n elif code == 302000:\n # news : text, list\n text = result['text']\n print(text + '\\n')\n for new in result[\"list\"]:\n print(\"%s - %s\\n\" % (new[\"article\"], new[\"source\"]))\n\n elif code == 308000:\n # recipe\n text = result['text']\n print(text + '\\n')\n for item in result[\"list\"]:\n print(\"%s:\\n\" % item[\"name\"])\n print(\"%s\\n\" % item[\"detailurl\"])\n\n else:\n print('我好像不太明白')\n return '我好像不太明白'\n\n\nclass BaiduRest(object):\n '''\n\n '''\n\n\n '''\n Important Parameter List\n self.app_id\n self.api_key\n self.api_secret\n self.taken_str\n '''\n\n def __init__(self, app_id, api_key, api_secret):\n # token approval\n self.token_url = \"https://openapi.baidu.com/oauth/2.0/token?\" \\\n \"grant_type=client_credentials&\" \\\n \"client_id=%s&client_secret=%s\"\n # synthesis\n self.getVoice_url = \"http://tsn.baidu.com/text2audio?\" \\\n \"tex=%s&lan=zh&cuid=%s&ctp=1&tok=%s\"\n # recognition\n self.upVoice_url = 'http://vop.baidu.com/server_api'\n self.app_id = app_id\n self.getToken(api_key, api_secret)\n return\n\n\n def getToken(self, api_key, api_secret):\n # get token approval\n token_url = self.token_url % (api_key, api_secret)\n r_str = urllib.request.urlopen(token_url).read()\n token_data = json.loads(r_str)\n self.token_str = token_data['access_token'] #Done!!!\n\n\n def getVoice(self, text, filename):\n # speech synthesis\n # submit file to 'Rest Port'\n get_url = self.getVoice_url % (urllib.parse.quote(text),\n self.app_id, self.token_str)\n voice_data = urllib.request.urlopen(get_url).read() #Done!!!\n # save the voice\n voice_fp = open(filename,'wb+')\n voice_fp.write(voice_data)\n voice_fp.close()\n\n\n def getText(self, filename):\n # speech recognition\n\n data = {}\n data['format'] = 'wav' # 'pcm' 'amr'\n data['rate'] = 8000\n data['channel'] = 1\n data['cuid'] = self.app_id\n data['token'] = self.token_str\n wav_fp = open(filename,'rb')\n voice_data = wav_fp.read()\n data['len'] = len(voice_data)\n data['speech'] = base64.b64encode(voice_data).decode('utf-8')\n # some setting\n post_data = json.dumps(data)\n r_data = urllib.request.urlopen(self.upVoice_url,\n data = bytes(post_data,\n encoding=\"utf-8\")).read()\n # submit file to 'Rest Port'\n result = json.loads(r_data)\n err_no = result['err_no']\n\n if not err_no:\n return result['result'][0]\n\n\n\nif __name__ == \"__main__\":\n\n Baidu_API_KEY = 'oihKzGMPGdnKWPt3tjMzeyCi'\n Baidu_SECRET_KEY = '209147fc271524c22d8b3dd5e5b55025'\n # Initialize the Baidu AipSpeech\n\n bdr = BaiduRest(\"test_python\", Baidu_API_KEY, Baidu_SECRET_KEY)\n # test.txt -> test.mp3\n\n while True:\n recordWave()\n # recording, save the voice into 'record.wav'\n\n Question = bdr.getText('record.wav')\n # get text from the recorded voice\n\n print(Question)\n\n if Question == None:\n continue\n\n if u'退出' in Question or u'关闭' in Question or u'拜拜' in Question:\n break\n\n elif Question == None or (not isinstance(Question, str)):\n continue\n\n elif u'介绍' in Question and (u'自���' in Question or u'自我' in Question):\n readWave(r'self-introduce.mp3', 8)\n continue\n\n Answer = replyByTuring(Question)\n # Turing robot give the answer (Format = str)\n bdr.getVoice(Answer, \"output.mp3\") # !!!!FILE#%$^\n if u'天气' in Question:\n readWave('output.mp3', 5)\n continue\n # test.wav -> test.txt\n readWave()\n # read the reply","sub_path":"Data/Voice/Python/codes/mass/Baidu--aip.py","file_name":"Baidu--aip.py","file_ext":"py","file_size_in_byte":6234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"414634383","text":"class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n '''递归,回溯解法'''\n ret = []\n n = len(nums)\n\n def helper(tmp, i):\n ret.append(tmp)\n for j in range(i, n):\n helper(tmp + [nums[j]], j + 1)\n helper([],0)\n return ret\n","sub_path":"Week_03/78.子集.py","file_name":"78.子集.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"588773012","text":"import time\n\nstart = time.time()\ngiven = 100\nproduct = 1\nfor n in range ( 1 , (given +1 ) ):\n product = product * n\n # print (product)\nm = 10\nanswer = 0\nr1 = 0\nr2 = (product % m ) \nwhile(product % m) != product:\n r1 = ((product % (10*m)) - (product % m))/m\n answer = answer + r1 \n m = m * 10\n #print (answer , r1 , r2 , m )\nfinalanswer = answer + (product % 10)\nprint (finalanswer)\nend = time.time()\nprint ( end- start)\n","sub_path":"EulerProject-solvedExamples/Problem 20.py","file_name":"Problem 20.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"562601943","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2016 Comunitea All Rights Reserved\n# $Jesús Ventosinos Mayor $\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp import models, fields, api, exceptions, _\n\n\nclass StockProductionLot(models.Model):\n\n _inherit = 'stock.production.lot'\n\n @api.model\n def _search(self, args, offset=0, limit=0, order=None, count=False,\n access_rights_uid=None):\n if self._context.get('product_id', False) and \\\n self._context.get('location_id', False):\n location = self._context.get('location_id', False)\n stock_ids = [x.lot_stock_id.id for x in self.env['stock.warehouse'].search([])]\n is_stock = self.env['stock.location'].search([('id', 'child_of', stock_ids), ('id', '=', location)])\n if is_stock:\n quants = self.env['stock.quant'].search(\n [('location_id', '=', self._context.get('location_id')),\n ('product_id', '=', self._context.get('product_id')),\n ('lot_id', '!=', False)])\n lot_ids = [x.lot_id.id for x in quants]\n args = [('id', 'in', lot_ids)] + args\n return super(StockProductionLot, self)._search(\n args, offset, limit, order, count=count,\n access_rights_uid=access_rights_uid)\n","sub_path":"project-addons/stock_transfer_only_available/models/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173725599","text":"#\n# [14] Longest Common Prefix\n#\n# https://leetcode.com/problems/longest-common-prefix/description/\n#\n# algorithms\n# Easy (31.74%)\n# Total Accepted: 292.1K\n# Total Submissions: 920.1K\n# Testcase Example: '[\"flower\",\"flow\",\"flight\"]'\n#\n# Write a function to find the longest common prefix string amongst an array of\n# strings.\n# \n# If there is no common prefix, return an empty string \"\".\n# \n# Example 1:\n# \n# \n# Input: [\"flower\",\"flow\",\"flight\"]\n# Output: \"fl\"\n# \n# \n# Example 2:\n# \n# \n# Input: [\"dog\",\"racecar\",\"car\"]\n# Output: \"\"\n# Explanation: There is no common prefix among the input strings.\n# \n# \n# Note:\n# \n# All given inputs are in lowercase letters a-z.\n# \n#\nclass Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if len(strs) == 0: \n return \"\"\n minString = min(strs)\n maxString = max(strs)\n for i, c in enumerate(minString):\n if maxString[i] != c:\n return minString[:i]\n return minString\n\n# s = Solution()\n# print(s.longestCommonPrefix([\"abc\", \"abd\", \"abdg\"]))","sub_path":"14.longest-common-prefix.python3.py","file_name":"14.longest-common-prefix.python3.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"599595156","text":"from selenium import webdriver\n\n# Chrome のオプションを設定する\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--headless\")\n\n# Selenium Server に接続する\ndriver = webdriver.Remote(\n command_executor=\"http://localhost:4444/wd/hub\",\n desired_capabilities=options.to_capabilities(),\n options=options,\n)\n\n# Selenium 経由でブラウザを操作する\ndriver.get(\"https://qiita.com\")\nprint(driver.current_url)\n\n# スクリーンショットの取得\nFILENAME = \"qiita.png\"\nw = driver.execute_script(\"return document.body.scrollWidth;\")\nh = driver.execute_script(\"return document.body.scrollHeight;\")\ndriver.set_window_size(w, h)\n\nresult_screenshot = driver.save_screenshot(FILENAME)\nif result_screenshot is False:\n print(\"An error has occurred while getting screenshot.\")\n\n# ページの一番下までスクロール\ndriver.execute_script('scroll(0, document.body.scrollHeight)')\n \n# ブラウザを終了する\ndriver.quit()\n","sub_path":"src/headless.py","file_name":"headless.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"480593749","text":"import datetime\nimport json\nimport os\nimport subprocess\nimport tempfile\nimport time\nimport boto3\nimport sys\n\nPAYLOAD_SIZE = 262000\nDATASETS_TABLE_NAME = os.environ['DATASETS_TABLE']\nREFERENCE_GENOME = os.environ['REFERENCE_GENOME']\nPLUGIN_CONSEQUENCE_SNS_TOPIC_ARN = os.environ['PLUGIN_CONSEQUENCE_SNS_TOPIC_ARN']\nPLUGIN_UPDOWNSTREAM_SNS_TOPIC_ARN = os.environ['PLUGIN_UPDOWNSTREAM_SNS_TOPIC_ARN']\nos.environ['PATH'] += ':' + os.environ['LAMBDA_TASK_ROOT']\nsns = boto3.client('sns')\ndynamodb = boto3.client('dynamodb')\ns3 = boto3.resource('s3')\n\n#testing done\ndef overlap_feature(all_coords,all_changes):\n results = []\n BUCKET_NAME = 'svep'\n keys = ['sorted_filtered_Homo_sapiens.GRCh38.98.chr.gtf.gz', 'sorted_filtered_Homo_sapiens.GRCh38.98.chr.gtf.gz.tbi']\n for KEY in keys:\n local_file_name = '/tmp/'+KEY\n s3.Bucket(BUCKET_NAME).download_file(KEY, local_file_name)\n\n for idx, coord in enumerate(all_coords):\n chr, pos = coord.split('\\t')\n loc = chr+\":\"+pos+\"-\"+pos\n changes = all_changes[idx]\n data={}\n args = ['tabix','/tmp/sorted_filtered_Homo_sapiens.GRCh38.98.chr.gtf.gz',loc]\n query_process = subprocess.Popen(args, stdout=subprocess.PIPE,stderr=subprocess.PIPE, cwd='/tmp',encoding='ascii')\n mainData = query_process.stdout.read().rstrip('\\n').split('\\n')\n data = {\n 'chrom':chr,\n 'pos':pos,\n 'ref':changes.split('\\t')[0],\n 'alt':changes.split('\\t')[1],\n 'data':mainData\n }\n results.append(data)\n\n return results\n\ndef get_size(obj, seen=None):\n \"\"\"Recursively finds size of objects\"\"\"\n size = sys.getsizeof(obj)\n if seen is None:\n seen = set()\n obj_id = id(obj)\n if obj_id in seen:\n return 0\n # Important mark as seen *before* entering recursion to gracefully handle\n # self-referential objects\n seen.add(obj_id)\n if isinstance(obj, dict):\n size += sum([get_size(v, seen) for v in obj.values()])\n size += sum([get_size(k, seen) for k in obj.keys()])\n elif hasattr(obj, '__dict__'):\n size += get_size(obj.__dict__, seen)\n elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):\n size += sum([get_size(i, seen) for i in obj])\n return size\n\ndef updateDataset(APIid,batchID,counter):\n kwargs = {\n 'TableName': DATASETS_TABLE_NAME,\n 'Key': {\n 'APIid': {\n 'S': APIid,\n },\n },\n 'UpdateExpression': 'ADD filesCount :c ',\n 'ExpressionAttributeValues': { ':c' :{'N':str(counter)} },\n }\n print('Updating Count of files: {}'.format(json.dumps(kwargs)))\n dynamodb.update_item(**kwargs)\n kwargs = {\n 'TableName': DATASETS_TABLE_NAME,\n 'Key': {\n 'APIid': {\n 'S': APIid,\n },\n },\n 'UpdateExpression': 'DELETE batchID :b ',\n 'ExpressionAttributeValues': { ':b' :{'SS':[batchID]} },\n }\n print('Deleting batch id item: {}'.format(json.dumps(kwargs)))\n dynamodb.update_item(**kwargs)\n\ndef publish_consequences_plugin(slice_data,APIid,batchID,lastBatchID):\n topics = [PLUGIN_CONSEQUENCE_SNS_TOPIC_ARN,PLUGIN_UPDOWNSTREAM_SNS_TOPIC_ARN]\n num = len(topics)\n kwargs = {}\n finalData = len(slice_data) - 1\n snsData = []\n tot_size = 0\n counter = 0\n for idx, slice_datum in enumerate(slice_data):\n print(json.dumps(slice_datum))\n cur_size = get_size(slice_datum)\n tot_size += cur_size\n if(tot_size < PAYLOAD_SIZE):\n snsData.append(slice_datum)\n else:\n counter += 1\n uniqueBatchID = batchID +\"_\"+str(counter)\n print(uniqueBatchID)\n for topic in topics:\n #\"TopicArn\": PLUGIN_CONSEQUENCE_SNS_TOPIC_ARN,\n kwargs[\"TopicArn\"] = topic\n kwargs['Message'] = json.dumps({ \"snsData\" : snsData, \"APIid\":APIid,\"batchID\":uniqueBatchID,\"lastBatchID\":0})\n print('Publishing to SNS: {}'.format(json.dumps(kwargs)))\n response = sns.publish(**kwargs)\n print('Received Response: {}'.format(json.dumps(response)))\n snsData = []\n tot_size = cur_size\n snsData.append(slice_datum)\n\n if(idx == finalData):\n counter += 1\n uniqueBatchID = batchID +\"_\"+str(counter)\n print(uniqueBatchID)\n files = counter * num\n for topic in topics:\n kwargs[\"TopicArn\"] = topic\n kwargs['Message'] = json.dumps({ \"snsData\" : snsData, \"APIid\":APIid,\"batchID\":uniqueBatchID,\"lastBatchID\":lastBatchID})\n print('Publishing to SNS: {}'.format(kwargs))\n response = sns.publish(**kwargs)\n print('Received Response: {}'.format(json.dumps(response)))\n updateDataset(APIid,batchID,files)\n\n\n\n\n\ndef annotate_slice(all_coords, all_changes,APIid,batchID,lastBatchID):\n overlap_list = overlap_feature(all_coords,all_changes)\n publish_consequences_plugin(overlap_list,APIid,batchID,lastBatchID)\n\ndef lambda_handler(event, context):\n print('Event Received: {}'.format(json.dumps(event)))\n ################test#################\n #message = json.loads(event['Message'])\n #######################################\n message = json.loads(event['Records'][0]['Sns']['Message'])\n coords = message['coords']\n changes = message['changes']\n APIid = message['APIid']\n batchID = message['batchID']\n lastBatchID = message['lastBatchID']\n annotate_slice(coords,changes,APIid,batchID,lastBatchID)\n","sub_path":"lambda/queryGTF/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":5657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"592213964","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\nfrom tensorflow.keras.preprocessing.image import load_img , img_to_array , ImageDataGenerator\r\nfrom numpy import expand_dims\r\n\r\n# data augmentation\r\n# 1. 보통은 상하반전 대신, 좌우반전을 한다. 그래도 넣어서 나쁠건 없음.\r\n# 2. cnn의 크기가 어느정도 커지면 회전이 들어가도 분류를 잘하기에, 회전은 잘 하지 않는다. 그래도 넣어서 나쁠건 없음.\r\n\r\n\r\n\r\n# 0 . data import\r\nimg1=load_img(\"C:/Users/82104/Desktop/fer2013/all_images/00000001.jpg\")\r\ndata = img_to_array(img1)\r\ndata.shape # 자동으로 rgb로 만들어줌. (채널 : 3)\r\n\r\nplt.imshow(img1)\r\n# plt.imshow(data/255) 와 같다.\r\n\r\n# 1. horizontal and vertical shift augmentation\r\n# 1) horizontal\r\nsamples = data[np.newaxis,:]\r\n# samples = np.expand_dims(data,0) 과 같음.\r\n\r\ndatagen = ImageDataGenerator(width_shift_range=[-10,10])\r\n# 움직일 폭을 결정. -10 또는 10 pixel 만 정확하게 움직임.\r\n# 만약 0과 1사이의 scalar 값을 주게되면, pixel의 해당 비율로 인식하여\r\n# 그 값 내에서 좌우 이동을 시킨다.\r\n\r\nit = datagen.flow(samples,batch_size=1)\r\n# it은 iter의 약자\r\n# datagen.flow(x_train,y_train,batch_size = 32)\r\n# batch_size 만큼 데이터 생성\r\nfig = plt.figure(figsize=(11,11)) # 9개짜리 figure받을 공간 생성\r\n\r\nfor i in range(9) :\r\n plt.subplot(3,3,i+1)\r\n batch = it.next()\r\n # next는 자체의 함수 혹은 매서드. datagen.flow에서는 method로 갖는다.\r\n # 자체로는 못쓰고, 보통 iter함수와 같이 쓴다.\r\n # 즉, iterator로 만들어주고, 거기서 next를 쓰는것.\r\n\r\n image = batch[0].astype('uint8')\r\n # batch에는 1개 값만 저장되고, 그 값의 차원은 (1,48,48,3) 임.\r\n # batch[0]은 (48,48,3)의 차원을 출력.\r\n plt.imshow(image)\r\n\r\n# 2) vertical\r\nsamples = data[np.newaxis,:]\r\ndatagen = ImageDataGenerator(height_shift_range=0.5)\r\n# height_shift_range 는 width_shift_range 와 같다.\r\n\r\nit = datagen.flow(samples,batch_size=1)\r\nfig = plt.figure(figsize=(11,11))\r\n\r\nfor i in range(9):\r\n plt.subplot(330+1+i)\r\n # 331 ~ 339 로, (3,3,1)~(3,3,9) 를 세자리 정수로도 받을 수 있음.\r\n\r\n batch = it.next()\r\n image = batch[0].astype('uint8')\r\n plt.imshow(image)\r\n\r\n\r\n# 2. horizontal and vertical flip augmentation\r\n\r\nsamples = expand_dims(data,0)\r\ndatagen = ImageDataGenerator(horizontal_flip=True,\r\n vertical_flip=True)\r\nit = datagen.flow(samples,batch_size=1)\r\nfig = plt.figure(figsize=(11,11))\r\n\r\nfor i in range(9):\r\n plt.subplot(330+1+i)\r\n batch = it.next()\r\n image = batch[0].astype('uint8')\r\n plt.imshow(image)\r\nplt.show()\r\n\r\n# 3. random rotation augmentation\r\n\r\nsamples = expand_dims(data,0)\r\ndatagen = ImageDataGenerator(rotation_range=90)\r\n# 좌,우로 최대 90도까지 회전할수 있다는 뜻.\r\nit = datagen.flow(samples,batch_size=1)\r\n\r\nfig = plt.figure(figsize=(11,11))\r\n\r\nfor i in range(9):\r\n plt.subplot(330+1+i)\r\n batch = it.next()\r\n image = batch[0].astype('uint8')\r\n plt.imshow(image)\r\nplt.show()\r\n\r\n# 4. random brightness augmentation\r\n\r\nsamples = expand_dims(data,0)\r\ndatagen = ImageDataGenerator(brightness_range=[0.2,1.0])\r\n# 0이 제일 어두운 값이며, 1이 제일 밝은 값.\r\n# 이 안에서 밝기를 조절하게 됨.\r\n\r\nit = datagen.flow(samples,batch_size=1)\r\n\r\nfig = plt.figure(figsize=(11,11))\r\nfor i in range(9):\r\n plt.subplot(330+1+i)\r\n batch = it.next()\r\n image = batch[0].astype('uint8')\r\n plt.imshow(image)\r\nplt.show()\r\n\r\n# 5. random zoom augmentation\r\n\r\nsamples = expand_dims(data,0)\r\ndatagen = ImageDataGenerator(zoom_range=[0.5,1])\r\n# 소수 혹은 정수를 다 받음.\r\n# 값이 클수록 실제 사진은 zoom됨. 즉 작아지는거임.\r\n# 1의 값이 기본.\r\n\r\nit = datagen.flow(samples,batch_size=1)\r\n\r\n\r\nfig = plt.figure(figsize=(11,11))\r\nfor i in range(9):\r\n plt.subplot(330+1+i)\r\n batch = it.next()\r\n image = batch[0].astype('uint8')\r\n plt.imshow(image)\r\nplt.show()\r\n\r\n\r\n# 6. all together\r\n\r\nsamples = expand_dims(data,0)\r\ndatagen = ImageDataGenerator(\r\n zoom_range=[0.5,1.0],\r\n brightness_range=[0.5,1.0],\r\n rotation_range=30,\r\n horizontal_flip = True,\r\n vertical_flip = True,\r\n height_shift_range = 0.1,\r\n width_shift_range = 0.1)\r\n\r\nit = datagen.flow(samples,batch_size=1)\r\nfig = plt.figure(figsize=(13,13))\r\n\r\nfor i in range(12):\r\n plt.subplot(4,3,1+i)\r\n batch = it.next()\r\n image = batch[0].astype('uint8')\r\n plt.imshow(image)\r\n\r\nplt.show()\r\n\r\n\r\n# 7. example\r\n\r\n(x_train,y_train), (x_test,y_test) = tf.keras.datasets.cifar10.load_data()\r\ny_train = tf.keras.utils.to_categorical(y_train,num_classes=10)\r\ny_test = tf.keras.utils.to_categorical(y_test,num_classes=10)\r\n\r\ndatagen = ImageDataGenerator(\r\n featurewise_center=True,\r\n featurewise_std_normalization=True,\r\n rotation_range=20,\r\n width_shift_range=0.2,\r\n height_shift_range=0.2,\r\n horizontal_flip=True,\r\n vertical_flip=True,\r\n fill_mode=\"constant\",\r\n cval=0)\r\ndatagen.fit(x_train)\r\n\r\n# simple cnn\r\ninputs = tf.keras.Input(shape=(32,32,3))\r\nx=tf.keras.layers.Conv2D(filters=16, kernel_size=(3,3),\r\n activation='relu', input_shape=(32,32,3), strides = (1,1) , name='Conv2D_layer1')(inputs)\r\nx=(tf.keras.layers.MaxPooling2D((2, 2), name='Maxpooling1_2D'))(x)\r\nx=tf.keras.layers.Conv2D(filters=16, kernel_size=(3,3),\r\n activation='relu', strides = (1,1) , name='Conv2D_layer2')(x)\r\nx= tf.keras.layers.MaxPooling2D((2, 2), name='Maxpooling2_2D')(x)\r\nx = tf.keras.layers.Flatten(name='Flatten')(x)\r\nx=tf.keras.layers.Dropout(0.3)(x)\r\nx=tf.keras.layers.Dense(32, activation='relu', name='Hidden_layer')(x)\r\noutputs =tf.keras.layers.Dense(10, activation='softmax', name='Output_layer')(x)\r\n\r\n\r\n\r\n\r\n## data argumentation\r\nmodel=tf.keras.Model(inputs=inputs,outputs=outputs)\r\nmodel.summary()\r\nmodel.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy'])\r\nmodel.fit_generator(datagen.flow(x_train,y_train,batch_size=32),\r\n steps_per_epoch=len(x_train)/32,epochs=1)\r\n_, acc = model.evaluate(x_test,y_test,batch_size=32)\r\nprint(\"\\nAccuracy: {:.4f}, F1 Score: {:.4f}\".format(acc,1))\r\n\r\n## normal data\r\nmodel2=tf.keras.Model(inputs=inputs,outputs=outputs)\r\nmodel2.summary()\r\nmodel2.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy'])\r\nmodel2.fit(x_train,y_train, batch_size=32,epochs=1)\r\n\r\n_, acc = model2.evaluate(x_test,y_test,batch_size=32)\r\nprint(\"\\nAccuracy: {:.4f}, F1 Score: {:.4f}\".format(acc,1))","sub_path":"Self_study/2019_Winter/My Project/Code/Pycharm/Step2/07. FER_Augmentation - 2020.02.25(TUE).py","file_name":"07. FER_Augmentation - 2020.02.25(TUE).py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"211710309","text":"import random\n\nuser_options = ['(r)Rock','(p)Paper','(s)Scissors','(q)Quit']\ncomp_options = ['Rock','Paper','Scissors']\nwinning_cases = [('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')]\nvalid_choices = {\n 'rock': 'Rock',\n 'paper': 'Paper',\n 'scissors': 'Scissors',\n 'quit': 'quit',\n 'r': 'Rock',\n 'p': 'Paper',\n 's': 'Scissors',\n 'q': 'quit'\n}\n\n# Display player choices\ndef showOptions(): \n print('Choose one:')\n for x in user_options:\n print(x)\n\nshowOptions()\n\nplayer_score = 0\ncomp_score = 0\n\nwhile True:\n # PROMPT PLAYER FOR INPUT\n player_choice = input('Enter Choice(case-insensitive): ').lower()\n\n # Check for valid input\n if not valid_choices.get(player_choice, None):\n print('\\nPlease enter a valid choice.')\n showOptions()\n continue\n elif valid_choices.get(player_choice) == 'quit':\n break\n\n player = valid_choices[player_choice]\n\n # Generate random number for comp choice \n comp = comp_options[random.randint(0,2)]\n \n #Display player and comp choices\n print('----------------------------')\n print(' Result: ')\n print(f'You: {player} | Comp: {comp}')\n\n # Check for draw\n if player == comp:\n print(\"It's a Draw\")\n # Player Wins\n elif (player,comp) in winning_cases:\n print(f'{player} beats {comp}')\n print('You Win!!!')\n player_score += 1\n # Player Loses\n else: \n print(f'{comp} beats {player}')\n print('You Lose :(')\n comp_score += 1\n print('----------------------------')\n print('Current Score:')\n print(f'You: {player_score} | Comp: {comp_score}')\n print('----------------------------\\n')\nprint('\\nThanks for playing!\\n')\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"595349511","text":"import string\nfrom functools import partial as p\n\nimport pytest\nfrom tests.helpers.agent import Agent\nfrom tests.helpers.assertions import has_datapoint_with_dim, has_datapoint_with_metric_name, tcp_socket_open\nfrom tests.helpers.util import container_ip, run_container, wait_for\n\npytestmark = [pytest.mark.collectd, pytest.mark.postgresql, pytest.mark.monitor_with_endpoints]\n\nCONFIG_TEMP = string.Template(\n \"\"\"\nmonitors:\n - type: collectd/postgresql\n host: $host\n port: 5432\n username: \"username1\"\n password: \"password1\"\n queries:\n - name: \"exampleQuery\"\n minVersion: 60203\n maxVersion: 200203\n statement: |\n SELECT coalesce(sum(n_live_tup), 0) AS live, coalesce(sum(n_dead_tup), 0) AS dead FROM pg_stat_user_tables;\n results:\n - type: gauge\n instancePrefix: live\n valuesFrom:\n - live\n databases:\n - name: test\n username: \"test_user\"\n password: \"test_pwd\"\n interval: 5\n expireDelay: 10\n sslMode: disable\n\"\"\"\n)\n\nENV = [\"POSTGRES_USER=test_user\", \"POSTGRES_PASSWORD=test_pwd\", \"POSTGRES_DB=test\"]\n\n\ndef test_postgresql():\n with run_container(\"postgres:10\", environment=ENV) as cont:\n host = container_ip(cont)\n config = CONFIG_TEMP.substitute(host=host)\n assert wait_for(p(tcp_socket_open, host, 5432), 60), \"service didn't start\"\n\n with Agent.run(config) as agent:\n assert wait_for(\n p(has_datapoint_with_dim, agent.fake_services, \"plugin\", \"postgresql\")\n ), \"Didn't get postgresql datapoints\"\n assert wait_for(p(has_datapoint_with_metric_name, agent.fake_services, \"pg_blks.toast_hit\"))\n","sub_path":"tests/monitors/collectd_postgresql/postgresql_test.py","file_name":"postgresql_test.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"384096506","text":"from __future__ import print_function\nimport numpy as np\nimport cv2\n\nimage = cv2.imread(\"next.png\")\norig = image.copy()\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\ndetector = cv2.FeatureDetector_create(\"FAST\")\nkps = detector.detect(gray)\nprint(\"# of keypoints:{}\".format(len(kps)))\n\nfor kp in kps:\n r = int(0.5 * kp.size)\n (x, y) = np.int0(kp.pt)\n cv2.circle(image, (x, y), r, (0, 255, 255), 2)\n\ncv2.imshow(\"Image\", np.hstack([orig, image]))\ncv2.waitKey(0)\n\n","sub_path":"Moudel10/Keypoint/fast/fast.py","file_name":"fast.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"224260798","text":"\ndef censura(black_list,sentence,new_word):\n new_blacklist=[]\n for i in black_list:\n new_blacklist.append(i.lower())\n black_list=new_blacklist\n a=sentence.split(\" \")\n rvalue=\"\"\n for i in a:\n if((',' in i) or ('.' in i) or (';' in i)):\n special=i[len(i)-1]\n #print(special)\n d=i.replace(\",\", \"\")\n #print(d)\n d=d.replace(\".\", \"\")\n #print(d)\n d=d.replace(\";\", \"\")\n #print(d)\n if d.lower() in black_list:\n if new_word =='*':\n rvalue = rvalue + ('*'*len(d)) + special + \" \"\n else:\n rvalue = rvalue + new_word + special + \" \"\n else: \n rvalue = rvalue + d + special + \" \"\n elif i.lower() in black_list:\n if new_word =='*':\n rvalue = rvalue + ('*'*len(i)) + \" \"\n else:\n rvalue = rvalue + new_word + \" \"\n else:\n rvalue = rvalue + i + \" \"\n \n return rvalue[:-1] #Para que no salga el ultimo espacio\n\n\ndef validar(sentence1,function,maxlen):\n if(abs(len(sentence1)-len(function))>maxlen):\n return False\n return True\n\nif __name__ == '__main__':\n black_list = ['popo','sangre','muerte','maldito']\n sentence = \"El animal maldito se acerco con una mirada de muerte. Manchas de sangre cubrian el suelo\"\n new_word = \"*\"\n print(sentence)\n print(censura(black_list,sentence,new_word))\n print(validar(sentence,censura(black_list,sentence,new_word),2))\n","sub_path":"ene-jun-2020/EmilioBarreraGonzalez/practica8/censura.py","file_name":"censura.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"529845736","text":"\"\"\"\n.. module:: testsequencer\n :platform: Darwin, Linux, Unix, Windows\n :synopsis: Module containing the base :class:`TestSequencer` type which is use to control\n the flow of the automation environment startup and test execution sequence.\n\n.. moduleauthor:: Myron Walker \n\"\"\"\n\n__author__ = \"Myron Walker\"\n__copyright__ = \"Copyright 2020, Myron W Walker\"\n__credits__ = []\n__version__ = \"1.0.0\"\n__maintainer__ = \"Myron Walker\"\n__email__ = \"myron.walker@gmail.com\"\n__status__ = \"Development\" # Prototype, Development or Production\n__license__ = \"MIT\"\n\nfrom typing import Dict, Sequence\n\nimport logging\nimport json\nimport os\nimport sys\nimport uuid\n\nimport akit.environment.activate # pylint: disable=unused-import\nfrom akit.environment.context import ContextUser\n\nfrom akit.jsos import CHAR_RECORD_SEPERATOR\nfrom akit.mixins.scope import inherits_from_scope_mixin\nfrom akit.paths import get_path_for_output\nfrom akit.results import ResultContainer, ResultType\nfrom akit.testing.unittest.testcollector import TestCollector\n\n\nlogger = logging.getLogger(\"AKIT\")\n\nclass TEST_SEQUENCER_PHASES:\n \"\"\"\n Indicates the current state of the sequencer.\n \"\"\"\n Initial = 0\n Discovery = 1\n Collection = 2\n Graph = 3\n Traversal = 4\n\nclass TestSequencer(ContextUser):\n \"\"\"\n The :class:`TestSequencer` is a state machine that helps to orchestrate the flow fo the test run. It ensures\n that the steps of the test flow are consistent between runs.\n \"\"\"\n\n def __init__(self, jobtitle: str, root: str, includes: Sequence[str], excludes: Sequence[str]):\n \"\"\"\n Creates a 'TestSequencer' object which is used to discover the tests and control the flow of a test run.\n\n :param jobtitle: The name of the test job.\n :param root: The path to the root folder that is the base of the tests.\n :param includes: List of expressions used to determine which tests to include.\n (scope):(package).(package)@(module)#(testname)\n :param excludes: List of expressions used to determine which tests to exclued from the included tests.\n\n \"\"\"\n self._jobtitle = jobtitle\n self._root = root\n self._includes = includes\n self._excludes = excludes\n self._integrations = []\n self._references = []\n self._scopes = []\n self._scope_roots = []\n self._import_errors = []\n self._testpacks = []\n return\n\n def __enter__(self):\n \"\"\"\n Provides 'with' statement scope semantics for the :class:`TestSequencer`\n \"\"\"\n return self\n\n def __exit__(self, ex_type, ex_inst, ex_tb):\n \"\"\"\n Provides 'with' statement scope semantics for the :class:`TestSequencer`\n \"\"\"\n return False\n\n @property\n def import_errors(self):\n \"\"\"\n A list of import errors that were encountered during the sequencing of the test run.\n \"\"\"\n return self._import_errors\n\n @property\n def testnodes(self):\n \"\"\"\n \"\"\"\n return self._testpacks\n\n @property\n def testpacks(self):\n \"\"\"\n A list of :class:`TestPack` objects that are included in the test run.\n \"\"\"\n return self._testpacks\n\n def attach_to_environment(self, landscape, constraints: Dict={}):\n \"\"\"\n Goes through all the integrations and provides them with an opportunity to\n attach to the test environment.\n \"\"\"\n\n results_dir = get_path_for_output()\n \n environment_dict = {}\n environment_dict.update(os.environ)\n \n for key in environment_dict.keys():\n if key.find(\"PASSWORD\") > -1:\n environment_dict[key] = \"(hidden)\"\n\n packages = {}\n for mname, mobj in sys.modules.items():\n if mname.find(\".\") == -1 and hasattr(mobj, \"__file__\"):\n packages[mname] = mobj.__file__\n\n startup_dict = {\n \"environment\": environment_dict,\n \"command\": \" \".join(sys.argv),\n \"packages\": packages\n }\n\n startup_full = os.path.join(results_dir, \"startup-configuration.json\")\n with open(startup_full, 'w') as suf:\n json.dump(startup_dict, suf, indent=True)\n\n for integ, _ in self._integrations:\n integ.attach_to_environment(landscape)\n\n return\n\n def collect_resources(self):\n \"\"\"\n Goes through all the integrations and provides them with an opportunity to\n collect shared resources that are required for testing.\n \"\"\"\n\n for integ, _ in self._integrations:\n integ.collect_resources()\n\n return\n\n def discover(self, test_module=None, include_integrations: bool=True):\n \"\"\"\n Initiates the discovery phase of the test run.\n \"\"\"\n collector = TestCollector(self._root, excludes=self._excludes, test_module=test_module)\n\n # Discover the tests, integration points, and scopes. If test modules is not None then\n # we are running tests from an individual module and we can limit discovery to the test module\n for inc_item in self._includes:\n collector.collect_references(inc_item)\n\n collector.expand_testpacks()\n\n self._references = collector.references\n\n testcount = len(self._references)\n if testcount > 0:\n if include_integrations:\n self._integrations = collector.collect_integrations()\n self._testpacks = collector.collect_testpacks()\n self._import_errors = collector.import_errors\n\n return testcount\n\n def establish_integration_order(self):\n \"\"\"\n Re-orders the integrations based on any declared precedences.\n \"\"\"\n\n for integ, _ in self._integrations:\n integ.establish_integration_order()\n\n return\n\n def establish_connectivity(self):\n \"\"\"\n Goes through all the integrations and provides them with an opportunity to\n establish connectivity with the test resource or resources they are integrating\n into the automation run.\n \"\"\"\n\n for integ, _ in self._integrations:\n integ.establish_connectivity()\n\n return\n\n def execute_tests(self, runid: str, recorder, sequencer):\n \"\"\"\n Called in order to execute the tests contained in the :class:`TestPacks` being run.\n \"\"\"\n exit_code = 0\n\n res_name = \"\"\n\n root_container = ResultContainer(runid, res_name, ResultType.JOB)\n recorder.record(root_container)\n\n for tpack in sequencer():\n self._traverse_testpack(tpack, recorder, parent_inst=runid)\n\n return exit_code\n\n def record_import_errors(self, outputfilename: str):\n \"\"\"\n Method that writes out the import errors to the active results directory.\n \"\"\"\n with open(outputfilename, 'w') as ief:\n for modname, filename, errmsg in self._import_errors.values():\n ief.write(CHAR_RECORD_SEPERATOR)\n ieitem = {\n \"module\": modname,\n \"filename\": filename,\n \"trace\": errmsg.splitlines(False)\n }\n json.dump(ieitem, ief, indent=4)\n\n return\n\n def _traverse_testpack(self, testpack, recorder, parent_inst=None):\n \"\"\"\n This function is called in order to traverse the execution of a TestPack and its associated scope tree. The\n `_traverse_testpack` method calls the scopes_enter method which intern will call scope_enter on its inherited scopes\n creating the correct test scope required by all of the tests in the `TestPack`. It will then run all of the tests\n that belong to the `TestPack` and then call scopes_exit in order to tear down any scopes no longer needed by any\n `TestPack`. The scopes can be shared scopes that can be shared across `TestPack`(s) and the scopes are reference\n counted in order to know when the last `TestPack` is finished using the scope.\n \"\"\"\n testpack_key = testpack.__module__ + \".\" + testpack.__name__\n logger.info(\"TESTPACK ENTER: %s\" % testpack_key)\n\n try:\n res_inst = str(uuid.uuid4())\n\n result_container = ResultContainer(res_inst, testpack_key, ResultType.TEST_CONTAINER, parent_inst=parent_inst)\n recorder.record(result_container)\n\n self._enter_testpack(testpack)\n\n for _, tref in testpack.test_references.items():\n\n testinst = None\n try:\n # Create an instance of the test case using the test reference\n testinst = tref.create_instance(recorder)\n except Exception: # pylint: disable=broad-except\n logger.exception(\"Error creating test instance.\")\n raise\n\n try:\n # Run the test, it shouldn't raise any exceptions unless a stop\n # is raised or a framework exception occurs\n testinst.run(result_container.result_inst)\n except Exception: # pylint: disable=broad-except\n logger.exception(\"Error running test instance.\")\n raise\n finally:\n try:\n self._exit_testpack(testpack)\n except Exception: # pylint: disable=broad-except\n logger.exception(\"Error exiting testpack.\")\n raise\n\n logger.info(\"TESTPACK EXIT: %s%s\" % (testpack_key, os.linesep))\n\n return\n\n def _enter_testpack(self, leaf_scope): # pylint: disable=no-self-use\n rev_mro = list(leaf_scope.__mro__)\n rev_mro.reverse()\n\n for nxt_cls in rev_mro:\n if inherits_from_scope_mixin(nxt_cls):\n # We only want to call scope_enter when we find the type it is directly\n # implemented on\n if \"scope_enter\" in nxt_cls.__dict__:\n nxt_cls.scope_enter()\n if not hasattr(nxt_cls, \"scope_enter_count\"):\n nxt_cls.scope_enter_count = 1\n else:\n nxt_cls.scope_enter_count += 1\n\n return\n\n def _exit_testpack(self, leaf_scope): # pylint: disable=no-self-use\n norm_mro = list(leaf_scope.__mro__)\n\n for nxt_cls in norm_mro:\n if inherits_from_scope_mixin(nxt_cls):\n if \"scope_enter\" in nxt_cls.__dict__:\n # We only want to call scope_enter when we find the type it is directly\n # implemented on\n if \"scope_exit\" in nxt_cls.__dict__:\n nxt_cls.scope_exit()\n\n if hasattr(nxt_cls, \"scope_enter_count\"):\n nxt_cls.scope_enter_count -= 1\n else:\n logger.error(\"The scope class '%s' should have had a 'scope_enter_count' class variable.\" % nxt_cls.__name__)\n elif \"scope_exit\" in nxt_cls.__dict__:\n nxt_cls.scope_exit()\n logger.warn(\"Found 'scope_exit' on class '%s' which did not have a 'scope_enter'.\" % nxt_cls.__name__)\n return\n","sub_path":"packages/akit/testing/unittest/testsequencer.py","file_name":"testsequencer.py","file_ext":"py","file_size_in_byte":11418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"445799","text":"import tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\ntf.random.set_seed(1)\nnp.random.seed(1)\n\n\nclass LSTM(keras.Model):\n\n def __init__(self, units):\n super(LSTM, self).__init__()\n\n # [b, 64]\n self.state0 = [tf.zeros([batch_size, units]), tf.zeros([batch_size, units])]\n self.state1 = [tf.zeros([batch_size, units]), tf.zeros([batch_size, units])]\n\n # transform text to embedding representation\n # [b, 100] => [b, 100, 150]\n self.embedding = layers.Embedding(input_dim=total_words, output_dim=embedding_len, input_length=max_review_len)\n\n # units=64\n self.rnn_cell0 = layers.LSTMCell(units, dropout=0.5)\n self.rnn_cell1 = layers.LSTMCell(units, dropout=0.5)\n\n # 全连接层\n # [b, 100, 150] => [b, 64] => [b, 1]\n self.out = layers.Dense(1)\n\n def call(self, inputs, training=None):\n \"\"\"\n net(x) net(x, training=True) :train mode\n net(x, training=False): test\n :param inputs: [b, 80]\n :param training:\n :return:\n \"\"\"\n # [b, 100]\n x = inputs\n # embedding: [b, 100] => [b, 100, 150]\n x = self.embedding(x)\n # rnn cell compute\n # [b, 100, 150] => [b, 64]\n state0 = self.state0\n state1 = self.state1\n for word in tf.unstack(x, axis=1):\n # word: [b, 150]\n # h1 = x*wxh+h0*whh\n # out0: [b, 64]\n out0, state0 = self.rnn_cell0(word, state0, training)\n # out1: [b, 64]\n out1, state1 = self.rnn_cell1(out0, state1, training)\n\n # out: [b, 64] => [b, 1]\n x = self.out(out1)\n # p(y is pos|x)\n prob = tf.sigmoid(x)\n\n return prob\n\n\nif __name__ == '__main__':\n # 批处理,批训练,发挥现代CPU和GPU的优势\n batch_size = 128\n\n # 词汇表大小\n total_words = 10000\n\n # 每个句子的最大长度\n max_review_len = 100\n\n # 每个词的表示向量的维度数\n embedding_len = 150\n\n (x_train, y_train), (x_test, y_test) = keras.datasets.imdb.load_data(num_words=total_words)\n x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=max_review_len)\n x_test = keras.preprocessing.sequence.pad_sequences(x_test, maxlen=max_review_len)\n\n db_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n db_train = db_train.shuffle(1000).batch(batch_size, drop_remainder=True)\n db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n db_test = db_test.batch(batch_size, drop_remainder=True)\n\n units = 64\n epochs = 4\n\n model = LSTM(units)\n model.compile(optimizer=keras.optimizers.Adam(0.001), loss=tf.losses.BinaryCrossentropy(), metrics=['accuracy'],\n experimental_run_tf_function=False)\n model.fit(db_train, epochs=epochs, validation_data=db_test)\n\n for var in model.trainable_variables:\n print(var.name, var.shape)\n\n print('evaluate:')\n model.evaluate(db_test)\n","sub_path":"Ch09/Ch09-1.py","file_name":"Ch09-1.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"272248929","text":"# -*- coding: utf-8 -*-\n\nimport time\nfrom operator import itemgetter\n\nfrom odoo import api, models, _\nfrom odoo.exceptions import UserError\n\n\nclass ReportPartnerTransaction(models.AbstractModel):\n _name = 'report.partner_transaction_report.report_partner_transaction'\n\n def _formatted(self, value, digit):\n formatted = ('%.' + str(digit) + 'f') % value\n return formatted\n\n def _format(self, value, currency=False):\n if self.env.context.get('no_format'):\n return value\n currency_id = currency or self.env.user.company_id.currency_id\n if currency_id.is_zero(value):\n value = abs(value)\n # res = formatLang(self.env, value, currency_obj=currency_id)\n formatted = ('%.' + '2' + 'f') % value\n res = formatted\n if currency_id and currency_id.symbol:\n if currency_id.position == 'after':\n res = '%s %s' % (res, currency_id.symbol)\n elif currency_id and currency_id.position == 'before':\n res = '%s %s' % (currency_id.symbol, res)\n return res\n\n def get_lines(self, data):\n lines = {}\n for partner in self.env['res.partner'].browse(data['form']['partner_ids']):\n partner_type = data['form']['type']\n if partner_type == 'customer':\n invoice_type = ['out_invoice', 'out_refund']\n else:\n invoice_type = ['in_refund', 'in_invoice']\n customer_invoices = self._get_invoices(data, partner, invoice_type)\n payment_group = self._get_payment_group(data, partner, partner_type)\n if customer_invoices or payment_group:\n currency = self._get_moves_by_currency(data, partner, invoice_type, partner_type)\n lines.update({partner.id: {'title': partner.name,\n 'currency': currency}})\n return lines\n\n def _get_moves_by_currency(self, data, partner, invoice_type, partner_type):\n currency_lines = []\n for currency in self.env['res.currency'].search([]):\n globle_dict_list = []\n lines = []\n total_currency = {}\n grand_total_debit = 0.0\n grand_total_credit = 0.0\n total_invoice = self._get_invoices(data, partner, invoice_type, 'initial').filtered(\n lambda x: x.currency_id == currency)\n for inv in total_invoice:\n if inv.type in ['out_refund', 'in_invoice']:\n grand_total_credit += inv.amount_total\n else:\n grand_total_debit += inv.amount_total\n\n total_payment_group = self._get_payment_group(data, partner, partner_type, 'initial')\n total_currency_payment_group = self.filter_currency_payment_group(total_payment_group, currency)\n for cpg in total_currency_payment_group:\n amount = 0.0\n payment_line_currency = cpg.payment_ids and cpg.payment_ids[0].currency_id or cpg.currency2_id\n amount = sum(cpg.payment_ids.mapped('amount'))\n\n if payment_line_currency.id != currency.id and cpg.manual_currency_rate:\n if currency.id != self.env.user.company_id.currency_id.id:\n amount = amount / cpg.manual_currency_rate\n else:\n amount = amount * cpg.manual_currency_rate\n if partner_type == 'customer':\n grand_total_credit += amount\n else:\n grand_total_debit += amount\n\n grand_total_balance = grand_total_debit - grand_total_credit\n\n initial_balance = {\n 'debit': self._format(grand_total_debit, currency),\n 'credit': self._format(grand_total_credit, currency),\n 'balance': self._format(grand_total_balance, currency),\n 'title': _(\"Initial Balance\"),\n 'line_type': 'total',\n }\n\n balance = grand_total_balance\n total_debit = grand_total_debit\n total_credit = grand_total_credit\n\n invoices = self._get_invoices(data, partner, invoice_type).filtered(lambda x: x.currency_id == currency)\n for inv in invoices:\n debit = credit = 0.0\n if inv.type == ['out_refund', 'in_invoice']:\n credit = inv.amount_total\n else:\n debit = inv.amount_total\n globle_dict_list.append({\n 'obj': inv,\n 'date': inv.date_invoice,\n 'line_type': 'invoice',\n 'doc_type': inv.journal_document_type_id.display_name,\n 'number': inv.display_name,\n 'reference': inv.name,\n 'debit': debit,\n 'credit': credit,\n 'currency_rate': inv.manual_currency_rate,\n 'amount_in_currency': credit if inv.type == ['out_refund', 'in_invoice'] else debit,\n })\n\n payment_group = self._get_payment_group(data, partner, partner_type)\n currency_payment_group = self.filter_currency_payment_group(payment_group, currency)\n for cpg in currency_payment_group:\n payment_line_currency = cpg.currency2_id\n payment_amount = 0.0\n for pay in cpg.payment_ids:\n payment_amount += pay.amount or 0.0\n payment_line_currency = pay.currency_id\n\n debit = credit = 0.0\n amount_in_currency = payment_amount\n amount = payment_amount\n if cpg.manual_currency_rate and payment_line_currency.id != currency.id:\n if currency.id != self.env.user.company_id.currency_id.id:\n amount = payment_amount / cpg.manual_currency_rate\n else:\n amount = payment_amount * cpg.manual_currency_rate\n\n if partner_type == 'customer':\n credit = amount\n else:\n debit = amount\n\n globle_dict_list.append({\n 'obj': cpg,\n 'line_type': 'payment',\n 'date': cpg.payment_date,\n 'doc_type': cpg.receiptbook_id.display_name,\n 'number': cpg.display_name,\n 'reference': cpg.name,\n 'debit': debit,\n 'credit': credit,\n 'currency_rate': cpg.manual_currency_rate,\n 'amount_in_currency': amount_in_currency,\n 'payment_currency': payment_line_currency,\n })\n sorted_globle_dict_list = sorted(globle_dict_list, key=itemgetter('date'))\n for dict in sorted_globle_dict_list:\n if dict.get('line_type') == 'payment':\n total_credit += dict['credit']\n total_debit += dict['debit']\n balance += dict['debit'] - dict['credit']\n values = {\n 'title': dict['number'],\n 'line_type': dict['line_type'],\n 'date': dict['date'],\n 'doc_type': dict['doc_type'],\n 'number': dict['number'],\n 'reference': dict['reference'],\n 'currency_rate': self._formatted(dict['currency_rate'], 6),\n 'amount_in_currency': self._format(dict['amount_in_currency'], dict['payment_currency']),\n 'debit': self._format(dict['debit'], currency),\n 'credit': self._format(dict['credit'], currency),\n 'balance': self._format(balance, currency)\n }\n lines.append(values)\n if data['form']['level'] == 'detailed':\n lines = self.get_account_payment_line(dict['obj'], lines, currency, partner_type)\n\n else:\n total_credit += dict['credit']\n total_debit += dict['debit']\n balance += dict['debit'] - dict['credit']\n lines.append({\n 'title': dict['number'],\n 'line_type': dict['line_type'],\n 'date': dict['date'],\n 'doc_type': dict['doc_type'],\n 'number': dict['number'],\n 'reference': dict['reference'],\n 'currency_rate': self._formatted(dict['currency_rate'], 6),\n 'amount_in_currency': self._format(dict['amount_in_currency'], currency),\n 'debit': self._format(dict['debit'], currency),\n 'credit': self._format(dict['credit'], currency),\n 'balance': self._format(balance, currency)\n })\n if sorted_globle_dict_list:\n total_currency = {\n 'title': _(\"Total Currency: \") + currency.name,\n 'line_type': 'total',\n 'debit': self._format(total_debit, currency),\n 'credit': self._format(total_credit, currency),\n 'balance': self._format(balance, currency)\n }\n\n if lines:\n currency_lines.append({'currency': {'title': _('Currency: ') + currency.name,\n 'initial_balance': initial_balance,\n 'lines': lines,\n 'total': total_currency}\n })\n return currency_lines\n\n def get_account_payment_line(self, payment_group_line, lines, currency, partner_type):\n line_currency = currency\n payment_total_debit = 0.0\n payment_total_credit = 0.0\n payment_total_balance = 0.0\n for payment in payment_group_line.payment_ids:\n name = payment.display_name or \"\"\n if payment_group_line.unmatched_amount:\n name = _(\"Advance\")\n debit = credit = 0.0\n currency_amount = amount = payment.unmatched_amount and payment.unmatched_amount or payment.amount\n if payment.currency_id.id != line_currency.id and payment_group_line.manual_currency_rate:\n if line_currency.id != self.env.user.company_id.currency_id.id:\n amount = amount / payment_group_line.manual_currency_rate\n else:\n amount = amount * payment_group_line.manual_currency_rate\n\n if partner_type == 'customer':\n credit = amount\n else:\n debit = amount\n\n balance = debit - credit\n\n payment_total_debit += debit\n payment_total_credit += credit\n payment_total_balance += balance\n\n invoice_number = payment.display_name\n lines.append({\n 'title': name,\n 'line_type': 'payment_line',\n 'date': payment.payment_date,\n 'doc_type': payment.receiptbook_id.display_name,\n 'number': invoice_number,\n 'reference': '',\n 'currency_rate': self._formatted(payment_group_line.manual_currency_rate, 6),\n 'amount_in_currency': self._format(currency_amount, payment.currency_id),\n 'debit': self._format(debit, line_currency),\n 'credit': self._format(credit, line_currency),\n 'balance': self._format(balance, line_currency),\n })\n payment_line_currency = payment_group_line.payment_ids and payment_group_line.payment_ids[0].currency_id \\\n or payment_group_line.currency2_id\n for aml in payment_group_line.matched_move_line_ids.filtered(lambda x: x.invoice_id):\n amount = aml.with_context(payment_group_id=payment_group_line.id).payment_group_matched_amount\n currency_amount = aml.with_context(payment_group_id=payment_group_line.id).payment_group_matched_amount\n debit = credit = 0.0\n if payment_line_currency.id != self.env.user.company_id.currency_id.id \\\n and line_currency.id != self.env.user.company_id.currency_id.id:\n amount = currency_amount = aml.with_context(\n payment_group_id=payment_group_line.id).payment_group_matched_amount_currency\n if payment_line_currency.id != line_currency.id and payment_group_line.manual_currency_rate:\n if line_currency.id == self.env.user.company_id.currency_id.id:\n currency_amount = currency_amount / payment_group_line.manual_currency_rate\n amount = currency_amount * payment_group_line.manual_currency_rate\n else:\n amount = credit / payment_group_line.manual_currency_rate\n if partner_type == 'customer':\n credit = amount\n else:\n debit = amount\n\n balance = debit - credit\n\n payment_total_debit += debit\n payment_total_credit += credit\n payment_total_balance += balance\n\n invoice_number = aml.invoice_id.display_name\n\n lines.append({\n 'title': invoice_number,\n 'line_type': 'payment_line',\n 'date': aml.date,\n 'doc_type': payment_group_line.receiptbook_id.display_name,\n 'number': invoice_number,\n 'reference': '',\n 'currency_rate': self._formatted(payment_group_line.manual_currency_rate, 6),\n 'amount_in_currency': self._format(currency_amount, payment_line_currency),\n 'debit': self._format(debit, line_currency),\n 'credit': self._format(credit, line_currency),\n 'balance': self._format(balance, line_currency),\n })\n\n lines.append({\n 'line_type': 'total',\n 'title': \"Total\",\n 'debit': self._format(payment_total_debit, line_currency),\n 'credit': self._format(payment_total_credit, line_currency),\n 'balance': self._format(payment_total_balance, line_currency),\n })\n return lines\n\n def get_currency_section(self, payment_group_line):\n if payment_group_line.matched_move_line_ids:\n filter_payment = payment_group_line.matched_move_line_ids.filtered(lambda i: i.invoice_id)\n if filter_payment:\n return filter_payment[0].invoice_id.currency_id\n else:\n if payment_group_line.unmatched_amount and payment_group_line.payment_ids:\n return payment_group_line.payment_ids[0].currency_id\n\n def _get_invoices(self, data, partner, invoice_type, case=False):\n domain = [('partner_id', '=', partner.id),\n ('state', 'not in', ['draft', 'cancel']),\n ('type', 'in', invoice_type)]\n if case == 'initial':\n domain += [('date_invoice', '<', data['form']['initial_date'])]\n else:\n domain += [('date_invoice', '>=', data['form']['initial_date']),\n ('date_invoice', '<=', data['form']['end_date'])]\n # TODO: Ver si afecta el order a a hora de sumar el balance inicial\n return self.env['account.invoice'].search(domain, order='date_invoice')\n\n def _get_payment_group(self, data, partner, partner_type, case=False):\n domain = [('partner_id', '=', partner.id),\n ('partner_type', '=', partner_type),\n ('state', '!=', 'draft')]\n if case == 'initial':\n domain += [('payment_date', '<', data['form']['initial_date'])]\n else:\n domain += [('payment_date', '>=', data['form']['initial_date']),\n ('payment_date', '<=', data['form']['end_date'])]\n # TODO: Ver si afecta el order a a hora de sumar el balance inicial\n return self.env['account.payment.group'].search(domain, order='payment_date')\n\n def filter_currency_payment_group(self, payment_group, currency):\n filter_payment_group = payment_group.filtered(\n lambda x: x.mapped('matched_move_line_ids').filtered(\n lambda i: i.invoice_id and i.invoice_id.currency_id.id == currency.id)\n or (not x.matched_move_line_ids and x.unmatched_amount and x.mapped('payment_ids').filtered(\n lambda p: p.currency_id and p.currency_id.id == currency.id)))\n return filter_payment_group\n\n @api.multi\n def render_html(self, docids, data=None):\n self.model = self.env.context.get('active_model')\n docs = self.env[self.model].browse(self.env.context.get('active_ids', []))\n lines = self.get_lines(data)\n if not lines:\n raise UserError(_('There is no information for the selected filters.'))\n docargs = {\n 'doc_ids': self.ids,\n 'doc_model': self.model,\n 'data': data['form'],\n 'docs': docs,\n 'time': time,\n 'lines': lines,\n }\n return self.env['report'].render('partner_transaction_report.report_partner_transaction', docargs)\n","sub_path":"moogah_development_extra_arg/partner_transaction_report/report/bi_partner_transaction_report.py","file_name":"bi_partner_transaction_report.py","file_ext":"py","file_size_in_byte":17628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"349622454","text":"import random\nimport threading\nimport time\nimport logging\n\nlogging.basicConfig(format='%(asctime)s.%(msecs)03d [%(threadName)s] - %(message)s', datefmt='%H:%M:%S', level=logging.INFO)\n\nheladeras = []\n\nbotellasSobrantes = 0\nlatasSobrantes = 0\n\nlocalBotellas = 0\nlocalLatas = 0\n\nsemaforoProveedor = threading.Semaphore(1)\nsemaforoHeladera = threading.Semaphore(1)\n\ncantidadHeladeras = 3\ncantidadProveedores = 2\n\n# No dar importancia a este archivo, esta de ejemplo para mi nada mas\n\nclass Heladera(threading.Thread):\n def __init__(self, id):\n super().__init__()\n self.botellas = []\n self.latas = []\n self.id = id\n\n def id(self):\n return self.id\n\n def hBotellas(self):\n return len(self.botellas)\n\n def hLatas(self):\n return len(self.latas)\n\n def meterBotellas(self):\n global localBotellas\n\n logging.info(f'Ahora en el local hay {localBotellas}')\n time.sleep(2)\n\n while (localBotellas > 0) & (self.hBotellas() < 10):\n self.botellas.append(0)\n localBotellas = localBotellas - 1\n\n def meterLatas(self):\n global localLatas\n\n logging.info(f'Ahora en el local hay {localLatas}')\n time.sleep(2)\n\n while (localLatas > 0) & (self.hLatas() < 15):\n self.latas.append(0)\n localLatas = localLatas - 1\n\n def hayEspacio(self):\n return (self.hBotellas() < 10) | (self.hLatas() < 15)\n\n def run(self):\n semaforoHeladera.acquire()\n while (self.hayEspacio()):\n self.meterBotellas()\n self.meterLatas()\n\n logging.info(f'En la heladera {self.id} hay {self.hBotellas()} botellas y {self.hLatas()} latas')\n time.sleep(2)\n logging.info(f'Sobraron {botellasSobrantes} botellas y {latasSobrantes} latas')\n time.sleep(2)\n semaforoProveedor.release()\n \n logging.info(f'La heladera {self.id} esta llena con {self.hBotellas()} botellas y {self.hLatas()} latas')\n time.sleep(1)\n semaforoHeladera.release()\n\nclass Local(threading.Thread):\n def __init__(self):\n super().__init__()\n\n def comenzarALlenar(self):\n for i in range(cantidadHeladeras):\n heladeras[i].start()\n\n\n def run(self):\n self.comenzarALlenar()\n \n\nclass Proveedores(threading.Thread):\n def __init__(self, monitorProveedor):\n super().__init__()\n self.monitorProveedor = monitorProveedor\n\n def cantidadBotellas(self):\n return random.randint(1, 10)\n\n def cantidadLatas(self):\n return random.randint(1, 10)\n\n def generarCervezas(self):\n global botellasAEntregar, latasAEntregar\n\n botellasAEntregar = self.cantidadBotellas()\n latasAEntregar = self.cantidadLatas()\n logging.info(f'Listo para entregar {botellasAEntregar} botellas y {latasAEntregar} latas')\n time.sleep(2)\n\n def entregarBotellas(self):\n global botellasAEntregar, localBotellas\n\n time.sleep(2)\n\n while (botellasAEntregar > 0):\n localBotellas = localBotellas + 1\n botellasAEntregar = botellasAEntregar - 1\n\n logging.info(f'Entregué al local {localBotellas} botellas. Me quedé con {botellasAEntregar}')\n\n def entregarLatas(self):\n global latasAEntregar, localLatas\n\n time.sleep(2)\n\n while (latasAEntregar > 0):\n localLatas = localLatas + 1\n latasAEntregar = latasAEntregar - 1\n\n logging.info(f'Entregué al local {localLatas} latas. Me quedé con {latasAEntregar}')\n\n def run(self):\n #while(True):\n semaforoProveedor.acquire()\n self.generarCervezas()\n self.entregarBotellas()\n self.entregarLatas()\n time.sleep(3)\n Local().start()\n \n \n\n\nmonitorProveedor = threading.Condition()\n\nfor i in range(cantidadHeladeras):\n heladeras.append(Heladera(i))\n\nfor i in range(cantidadProveedores):\n Proveedores(monitorProveedor).start()\n","sub_path":"tp-base-ignorar.py","file_name":"tp-base-ignorar.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"565256337","text":"import sys\nimport platform\nimport asyncio\nimport json\nfrom io import StringIO\nfrom contextvars import ContextVar\nfrom typing import Dict, Any, List, Optional, Union, Awaitable, cast\n\nfrom zmq.sugar.socket import Socket\n\nfrom akernel.comm import comm\nfrom akernel.comm.manager import CommManager\nfrom akernel.display import display\nimport akernel.IPython\nfrom akernel.IPython import core\nfrom .connect import connect_channel\nfrom .message import receive_message, send_message, create_message, check_message\nfrom .execution import pre_execute\nfrom .traceback import get_traceback\nfrom ._version import __version__\n\n\nPARENT_HEADER_VAR: ContextVar = ContextVar(\"parent_header\")\n\nKERNEL: \"Kernel\"\n\n\nsys.modules[\"ipykernel.comm\"] = comm\nsys.modules[\"IPython.display\"] = display\nsys.modules[\"IPython\"] = akernel.IPython\nsys.modules[\"IPython.core\"] = core\n\n\nclass Kernel:\n\n shell_channel: Socket\n iopub_channel: Socket\n control_channel: Socket\n connection_cfg: Dict[str, Union[str, int]]\n stop: asyncio.Event\n restart: bool\n key: str\n comm_manager: CommManager\n kernel_mode: str\n running_cells: Dict[int, asyncio.Task]\n task_i: int\n execution_count: int\n execution_state: str\n globals: Dict[str, Any]\n locals: Dict[str, Any]\n\n def __init__(\n self,\n kernel_mode: str,\n connection_file: str,\n ):\n global KERNEL\n KERNEL = self\n self.comm_manager = CommManager()\n self.loop = asyncio.get_event_loop()\n self.kernel_mode = kernel_mode\n self.running_cells = {}\n self.task_i = 0\n self.execution_count = 1\n self.execution_state = \"starting\"\n self.globals = {\n \"asyncio\": asyncio,\n \"print\": self.print,\n \"__task__\": self.task,\n \"_\": None,\n }\n self.locals = {}\n if kernel_mode == \"react\":\n code = \"import ipyx; globals()['ipyx'] = ipyx\"\n exec(code, self.globals, self.locals)\n with open(connection_file) as f:\n self.connection_cfg = json.load(f)\n self.key = cast(str, self.connection_cfg[\"key\"])\n self.restart = False\n self.interrupted = False\n self.msg_cnt = 0\n self.shell_channel = connect_channel(\"shell\", self.connection_cfg)\n self.iopub_channel = connect_channel(\"iopub\", self.connection_cfg)\n self.control_channel = connect_channel(\"control\", self.connection_cfg)\n msg = self.create_message(\n \"status\", content={\"execution_state\": self.execution_state}\n )\n send_message(msg, self.iopub_channel, self.key)\n self.execution_state = \"idle\"\n self.stop = asyncio.Event()\n while True:\n try:\n self.loop.run_until_complete(self.main())\n except KeyboardInterrupt:\n self.interrupt()\n else:\n if not self.restart:\n break\n finally:\n self.shell_task.cancel()\n self.control_task.cancel()\n\n def interrupt(self):\n self.interrupted = True\n for task in self.running_cells.values():\n task.cancel()\n self.running_cells = {}\n\n async def main(self) -> None:\n self.shell_task = asyncio.create_task(self.listen_shell())\n self.control_task = asyncio.create_task(self.listen_control())\n while True:\n # run until shutdown request\n await self.stop.wait()\n if self.restart:\n # kernel restart\n self.stop.clear()\n else:\n # kernel shutdown\n break\n\n async def listen_shell(self) -> None:\n while True:\n # let a chance to execute a blocking cell\n await asyncio.sleep(0)\n # if there was a blocking cell execution, and it was interrupted,\n # let's ignore all the following execution requests until the pipe\n # is empty\n if self.interrupted and not await check_message(self.shell_channel):\n self.interrupted = False\n res = await receive_message(self.shell_channel)\n assert res is not None\n idents, msg = res\n msg_type = msg[\"header\"][\"msg_type\"]\n parent_header = msg[\"header\"]\n if msg_type == \"kernel_info_request\":\n msg = self.create_message(\n \"kernel_info_reply\",\n parent_header=parent_header,\n content={\n \"status\": \"ok\",\n \"protocol_version\": \"5.5\",\n \"implementation\": \"akernel\",\n \"implementation_version\": __version__,\n \"language_info\": {\n \"name\": \"python\",\n \"version\": platform.python_version(),\n \"mimetype\": \"text/x-python\",\n \"file_extension\": \".py\",\n },\n \"banner\": \"Python \" + sys.version,\n },\n )\n send_message(msg, self.shell_channel, self.key, idents[0])\n msg = self.create_message(\n \"status\",\n parent_header=parent_header,\n content={\"execution_state\": self.execution_state},\n )\n send_message(msg, self.iopub_channel, self.key)\n elif msg_type == \"execute_request\":\n self.execution_state = \"busy\"\n code = msg[\"content\"][\"code\"]\n msg = self.create_message(\n \"status\",\n parent_header=parent_header,\n content={\"execution_state\": self.execution_state},\n )\n send_message(msg, self.iopub_channel, self.key)\n if self.interrupted:\n self.finish_execution(idents, parent_header, None, no_exec=True)\n continue\n msg = self.create_message(\n \"execute_input\",\n parent_header=parent_header,\n content={\"code\": code, \"execution_count\": self.execution_count},\n )\n send_message(msg, self.iopub_channel, self.key)\n react = self.kernel_mode == \"react\"\n traceback, exception = pre_execute(\n code, self.globals, self.locals, self.execution_count, react=react\n )\n if traceback:\n self.finish_execution(\n idents,\n parent_header,\n self.execution_count,\n traceback=traceback,\n exception=exception,\n )\n else:\n task = asyncio.create_task(\n self.execute_and_finish(\n idents,\n parent_header,\n self.task_i,\n self.execution_count,\n code,\n )\n )\n self.running_cells[self.task_i] = task\n self.task_i += 1\n self.execution_count += 1\n elif msg_type == \"comm_info_request\":\n self.execution_state = \"busy\"\n msg2 = self.create_message(\n \"status\",\n parent_header=parent_header,\n content={\"execution_state\": self.execution_state},\n )\n send_message(msg2, self.iopub_channel, self.key)\n if \"target_name\" in msg[\"content\"]:\n target_name = msg[\"content\"][\"target_name\"]\n comms: List[str] = []\n msg2 = self.create_message(\n \"comm_info_reply\",\n parent_header=parent_header,\n content={\n \"status\": \"ok\",\n \"comms\": {\n comm_id: {\"target_name\": target_name}\n for comm_id in comms\n },\n },\n )\n send_message(msg2, self.shell_channel, self.key, idents[0])\n self.execution_state = \"idle\"\n msg2 = self.create_message(\n \"status\",\n parent_header=parent_header,\n content={\"execution_state\": self.execution_state},\n )\n send_message(msg2, self.iopub_channel, self.key)\n elif msg_type == \"comm_msg\":\n self.comm_manager.comm_msg(None, None, msg)\n\n async def listen_control(self) -> None:\n while True:\n res = await receive_message(self.control_channel)\n assert res is not None\n idents, msg = res\n msg_type = msg[\"header\"][\"msg_type\"]\n parent_header = msg[\"header\"]\n if msg_type == \"shutdown_request\":\n self.restart = msg[\"content\"][\"restart\"]\n msg = self.create_message(\n \"shutdown_reply\",\n parent_header=parent_header,\n content={\"restart\": self.restart},\n )\n send_message(msg, self.control_channel, self.key, idents[0])\n if self.restart:\n self.globals = {\n \"asyncio\": asyncio,\n \"print\": self.print,\n \"__task__\": self.task,\n \"_\": None,\n }\n self.locals = {}\n if self.kernel_mode == \"react\":\n code = \"import ipyx; globals()['ipyx'] = ipyx\"\n exec(code, self.globals, self.locals)\n self.execution_count = 1\n self.stop.set()\n\n async def execute_and_finish(\n self,\n idents: List[bytes],\n parent_header: Dict[str, Any],\n task_i: int,\n execution_count: int,\n code: str,\n ) -> None:\n PARENT_HEADER_VAR.set(parent_header)\n traceback, exception = [], None\n try:\n result = await self.locals[\"__async_cell__\"]()\n except KeyboardInterrupt:\n self.interrupt()\n except Exception as e:\n exception = e\n traceback = get_traceback(code, e, execution_count)\n else:\n if result is not None:\n self.globals[\"_\"] = result\n if getattr(result, \"_repr_mimebundle_\", None) is not None:\n data = result._repr_mimebundle_()\n display.display(data, raw=True)\n elif getattr(result, \"_ipython_display_\", None) is not None:\n result._ipython_display_()\n else:\n msg = self.create_message(\n \"stream\",\n parent_header=parent_header,\n content={\"name\": \"stdout\", \"text\": f\"{repr(result)}\\n\"},\n )\n send_message(msg, self.iopub_channel, self.key)\n finally:\n self.finish_execution(\n idents,\n parent_header,\n execution_count,\n exception=exception,\n traceback=traceback,\n )\n if task_i in self.running_cells:\n del self.running_cells[task_i]\n\n def finish_execution(\n self,\n idents: List[bytes],\n parent_header: Dict[str, Any],\n execution_count: Optional[int],\n exception: Optional[Exception] = None,\n no_exec: bool = False,\n traceback: List[str] = [],\n ) -> None:\n if no_exec:\n status = \"aborted\"\n else:\n if traceback:\n status = \"error\"\n assert exception is not None\n msg = create_message(\n \"error\",\n parent_header=parent_header,\n content={\n \"ename\": type(exception).__name__,\n \"evalue\": exception.args[0],\n \"traceback\": traceback,\n },\n )\n send_message(msg, self.iopub_channel, self.key)\n else:\n status = \"ok\"\n msg = self.create_message(\n \"execute_reply\",\n parent_header=parent_header,\n content={\"status\": status, \"execution_count\": execution_count},\n )\n send_message(msg, self.shell_channel, self.key, idents[0])\n self.execution_state = \"idle\"\n msg = self.create_message(\n \"status\",\n parent_header=parent_header,\n content={\"execution_state\": self.execution_state},\n )\n send_message(msg, self.iopub_channel, self.key)\n\n def task(self, cell_i: int = -1) -> Awaitable:\n if cell_i < 0:\n i = self.task_i - 1 + cell_i\n else:\n i = cell_i\n if i in self.running_cells:\n return self.running_cells[i]\n return asyncio.sleep(0)\n\n def print(\n self,\n *objects,\n sep: str = \" \",\n end: str = \"\\n\",\n file=sys.stdout,\n flush: bool = False,\n ) -> None:\n if file is sys.stdout:\n name = \"stdout\"\n elif file is sys.stderr:\n name = \"stderr\"\n else:\n print(*objects, sep, end, file, flush)\n return\n f = StringIO()\n print(*objects, sep=sep, end=end, file=f, flush=True)\n text = f.getvalue()\n f.close()\n msg = self.create_message(\n \"stream\",\n parent_header=PARENT_HEADER_VAR.get(),\n content={\"name\": name, \"text\": text},\n )\n send_message(msg, self.iopub_channel, self.key)\n\n def create_message(\n self,\n msg_type: str,\n content: Dict = {},\n parent_header: Dict[str, Any] = {},\n ) -> Dict[str, Any]:\n msg = create_message(\n msg_type, content=content, parent_header=parent_header, msg_cnt=self.msg_cnt\n )\n self.msg_cnt += 1\n return msg\n","sub_path":"akernel/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":14431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"216825848","text":"from django_filters import rest_framework as filters\nfrom .models import Review, Order\n\n\nclass ProductFilter(filters.FilterSet):\n\n price = filters.RangeFilter()\n name = filters.CharFilter(field_name=\"name\", lookup_expr=\"icontains\")\n description = filters.CharFilter(field_name=\"description\", lookup_expr=\"icontains\")\n\n\nclass ReviewFilter(filters.FilterSet):\n\n class Meta:\n model = Review\n fields = [\"user\", \"product\", \"created_at\"]\n\n\nclass OrderFilter(filters.FilterSet):\n\n price = filters.RangeFilter(field_name='total_price')\n ordered_products = filters.NumberFilter(field_name='ordered_products', method='products_filter')\n creation = filters.DateFromToRangeFilter(field_name='created_at')\n update = filters.DateFromToRangeFilter(field_name='updated_at')\n\n class Meta:\n model = Order\n fields = [\"status\", \"created_at\", \"updated_at\"]\n\n def products_filter(self, queryset, name, value):\n query = queryset.filter(ordered_products__product=value)\n return query\n","sub_path":"shop_api/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566709187","text":"import os\nimport copy\nimport datetime\n\n\nPATH_DIR = os.path.dirname(os.path.realpath(__file__))\nPATH_EXISTS = os.path.join(PATH_DIR, 'price_exists.csv')\nPATH_INCOME = os.path.join(PATH_DIR, 'price_input.csv')\n\n\ndef get_pricelist(path):\n \"\"\"\n Получение списка словарей из файла данных\n Args:\n path (str): путь к файлу данных\n Returns:\n data (list): список словарей с одинаковыми ключами, соответствующими названию колонок файла\n \"\"\"\n data = []\n with open(path, 'r') as f:\n lines = [l.replace('\\n', '').split(';') for l in f.readlines()]\n data = [dict(zip(lines[0], l)) for l in lines[1:]]\n\n # Конвертируем данные файла в соответствующий каждой колонке формат\n for d in data:\n for k, v in d.items():\n if k in ('begin', 'end'):\n d[k] = datetime.datetime.strptime(v, '%d.%m.%Y %H:%M:%S')\n else:\n d[k] = int(v)\n\n return data\n\n\ndef group_n_flat(data, keys=None):\n \"\"\"\n Группировка списка словарей в один по переданным ключам\n Args:\n data (list): список словарей, содержащих исходные данные (строки файла)\n keys (list): список ключей, по которым будут собираться данные\n Returns:\n result (dict): словарь, значения которого представлены в виде плоского словаря (дата/значение)\n \"\"\"\n keys = keys or ('code', 'number', 'dept')\n\n result = {}\n for row in data.copy():\n key = tuple([row.pop(k) for k in keys])\n result.setdefault(key, {}).update(dict.fromkeys([row['begin'], row['end']], row['value']))\n\n return result\n\n\ndef merge_data(exists, income):\n \"\"\"\n Слияние текущих и входящих данных\n Args:\n exists (dict): исходные данные\n income (dict): входящие данные\n Returns:\n merged (dict): результат слияния\n \"\"\"\n merged = copy.deepcopy(exists)\n for kin, vin in income.items():\n merged.setdefault(kin, {'db_op': 'insert'}).update(vin)\n\n return merged\n\n\ndef prepare_for_save(merged):\n \"\"\"\n Подготовка данных к сохранению в БД\n Args:\n merged (dict): собранные данные\n force_update (boolean): флаг принудительного обновления всех данных\n Returns:\n result (list): список словарей\n \"\"\"\n\n result = []\n for k, values in merged.items():\n _prev = None\n code, number, dept = k\n\n for ix, dtk in enumerate(sorted(values.keys())):\n if ix:\n # пропускаем первое значение, потому как по нему определяется нижняя граница первой записи\n value = values[dtk]\n result.append({\n 'product_code': str(code),\n 'number': int(number),\n 'depart': int(dept),\n 'begin': _prev,\n 'end': dtk,\n 'value': value,\n })\n\n _prev = dtk\n\n return result\n\n\nif __name__ == '__main__':\n exists = group_n_flat(get_pricelist(PATH_EXISTS))\n income = group_n_flat(get_pricelist(PATH_INCOME))\n merged = merge_data(exists, income)\n result = prepare_for_save(merged)\n\n print(result)","sub_path":"ahistory/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"238339210","text":"from bs4 import BeautifulSoup\nimport traceback\nimport re\nimport requests\nfrom config.config import HEADERS, PROXIES, IS_DAILI\n\ndef login_by_mobile(validate_token, mobile, sms_url, conn, cursor, logger): # 获取到短信验证码后登录,提取最新sid(身份认证信息)\n try:\n if len(sms_url) != 0: #该变量为空的话说明不是网上的接码平台号码 需手动输入短信验证码\n logger.info('[{}]正在获取短信验证码'.format(mobile))\n html = requests.get(sms_url, headers=HEADERS)\n if html.status_code == 200:\n Soup = BeautifulSoup(html.content, 'lxml')\n # print(aSoup)\n trList = Soup.find_all(name='tbody')[0].find_all(name='tr')\n if trList:\n for tr in trList:\n tdContent = tr.find_all(name='td')[2].string\n if '【饿了么】' in tdContent:\n validate_code = re.findall('验证码是(.*?),', tdContent, re.S)[0]\n logger.info('[{}]短信验证码识别成功,验证码为{}'.format(mobile, validate_code))\n dict = {\"mobile\": \"{}\".format(mobile), \"validate_token\": \"{}\".format(validate_token),\n \"validate_code\": \"{}\".format(validate_code)}\n login_by_mobile_url = 'https://h5.ele.me/restapi/eus/login/login_by_mobile'\n r = requests.post(login_by_mobile_url, headers=HEADERS, data=dict,\n proxies=PROXIES if IS_DAILI else None, timeout=25)\n if r.status_code == 200:\n if 'SID' in r.cookies and 'USERID' in r.cookies:\n SID = r.cookies['SID']\n users_id = r.cookies['USERID']\n logger.info('[{}]获取成功,新的SID为[{}],userid为[{}]'.format(mobile, SID, users_id))\n result = {'status': 0, 'sid': SID}\n cursor.execute(\"select mobile from eleme_id\")\n id_values = str(cursor.fetchall())\n cursor.execute(\"select mobile from eleme_xh\")\n xh_values = str(cursor.fetchall())\n if '{}'.format(mobile) in id_values:\n cursor.execute(\n \"UPDATE eleme_id SET sid = '{}', users_id = '{}' WHERE mobile = '{}'\".format(SID, users_id, mobile))\n conn.commit()\n logger.info('[{}]新的SID已写入成功_eleme_id'.format(mobile))\n if '{}'.format(mobile) in xh_values:\n cursor.execute(\"UPDATE eleme_xh SET sid = '{}', users_id = '{}' WHERE mobile = '{}'\".format(SID, users_id, mobile))\n conn.commit()\n logger.info('[{}]新的SID已写入成功_eleme_xh'.format(mobile))\n return result\n else:\n result = {'status': 1, 'message': '未找到,sid获取出错~{},{}'.format(r.text, r.cookies)}\n return result\n else:\n result = {'status': 1, 'message': '短信验证出错~{}'.format(\n r.text)} # 这种情况一般是短信验证码错误,接码网站上最新的饿了么短信不是你前15秒发的,刚好也有人用此号码接了饿了么短信\n return result\n else:\n result = {'status': 1, 'message': '未找到饿了么短信'}\n return result\n else:\n result = {'status': 1, 'message': 'trList列表为空'}\n return result\n else:\n result = {'status': 1, 'message': '接码平台地址访问出错了~{}'.format(html.status_code)}\n return result\n except:\n result = {'status': 1, 'message': 'Error: {}'.format(traceback.format_exc())}\n return result","sub_path":"backup_py/wxBot/eleme/login/login_by_mobile.py","file_name":"login_by_mobile.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"455634070","text":"import unittest\nfrom app import services\nfrom app.utils import push\n\n\nclass TestUtilsPush(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(TestUtilsPush, self).__init__(*args, **kwargs)\n self._site_data = None\n self._domain_data = None\n self._ip_data = None\n\n @property\n def site_data(self):\n if self._site_data is None:\n sites = [\"https://www.baidu.com\", \"https://www.qq.com/\"]\n site_data = services.fetch_site(sites, concurrency=2)\n self._site_data = site_data\n\n return self._site_data\n\n @property\n def domain_data(self):\n if self._domain_data is None:\n _domain_data = services.build_domain_info([\"www.baidu.com\", \"www.qq.com\"])\n domain_data = []\n for x in _domain_data:\n domain_data.append(x.dump_json(flag=False))\n self._domain_data = domain_data\n\n return self._domain_data\n\n @property\n def ip_data(self):\n if self._ip_data is None:\n _ip_data = services.build_domain_info([\"www.baidu.com\", \"www.qq.com\"])\n ip_data = []\n for x in services.port_scan([\"1.1.1.1\"]):\n x[\"geo_asn\"] = {\n \"number\": 13335,\n \"organization\": \"Cloudflare, Inc.\"\n }\n ip_data.append(x)\n self._ip_data = ip_data\n\n return self._ip_data\n\n def test_message_push_domain(self):\n asset_map = {\n \"site\": self.site_data,\n \"domain\": self.domain_data,\n \"task_name\": \"灯塔测试域名\"\n }\n asset_counter = {\n \"site\": 10,\n \"domain\": 10\n }\n p = push.Push(asset_map=asset_map, asset_counter=asset_counter)\n ret = p.push_dingding()\n self.assertTrue(ret)\n\n def test_message_push_ip(self):\n asset_map = {\n \"site\": self.site_data,\n \"ip\": self.ip_data,\n \"task_name\": \"灯塔测试 IP\"\n }\n asset_counter = {\n \"site\": 10,\n \"ip\": 10\n }\n p = push.Push(asset_map=asset_map, asset_counter=asset_counter)\n ret = p.push_dingding()\n self.assertTrue(ret)\n\n def test_push_email_domain(self):\n asset_map = {\n \"site\": self.site_data,\n \"domain\": self.domain_data,\n \"task_name\": \"灯塔测试域名\"\n }\n asset_counter = {\n \"site\": 10,\n \"domain\": 10\n }\n\n p = push.Push(asset_map=asset_map, asset_counter=asset_counter)\n ret = p.push_email()\n self.assertTrue(ret)\n\n def test_push_email_ip(self):\n asset_map = {\n \"site\": self.site_data,\n \"ip\": self.ip_data,\n \"task_name\": \"灯塔测试 IP\"\n }\n asset_counter = {\n \"site\": 10,\n \"ip\": 10\n }\n\n p = push.Push(asset_map=asset_map, asset_counter=asset_counter)\n ret = p.push_email()\n self.assertTrue(ret)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_utils_push.py","file_name":"test_utils_push.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"154163033","text":"import colorama\nfrom colorama import Fore, Back, Style\n\n\nclass Tile:\n x = None\n y = None\n piece = None\n chess_color = None\n background_color = None\n\n def __init__(self, x, y, chess_color):\n self.x = x\n self.y = y\n assert (chess_color == \"white\" or chess_color == \"black\")\n self.chess_color = chess_color\n self.set_background_color()\n\n def set_background_color(self):\n if self.chess_color == \"white\":\n self.background_color = Back.LIGHTWHITE_EX\n else:\n self.background_color = \"\"\n\n def add_piece(self, p):\n self.piece = p\n\n def get_piece(self):\n return self.piece\n\n def remove_piece(self):\n self.piece = None\n\n def check_if_free(self):\n if self.piece is None:\n return True\n return False\n\n def __repr__(self):\n return str(self)\n\n def __str__(self):\n ret = \"\"\n ret += self.background_color\n if self.piece is None:\n ret += \" \"\n else:\n if self.piece.color == \"white\":\n ret += Style.BRIGHT + Fore.BLUE\n else:\n ret += Style.DIM + Fore.RED\n ret += f\" {self.piece.symbol} \"\n ret += Style.RESET_ALL\n return ret\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"294814223","text":"import gi\nimport pandas as pd\nfrom matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg\nimport matplotlib.pyplot as plt\n\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\n\n\nclass Plotter:\n def __init__(self):\n self.column_names = False\n self.drop_nan = False\n self.df = None\n\n self.builder = Gtk.Builder()\n self.builder.add_from_file(\"plotter.glade\")\n self.builder.connect_signals(self)\n\n self.window = self.builder.get_object(\"window1\")\n self.window.show_all()\n\n def load_table(self, filename):\n if filename is not None:\n fn = filename.split(\"/\")[-1]\n if self.column_names:\n df = pd.read_csv(filename, engine=\"python\")\n else:\n df = pd.read_csv(filename, engine=\"python\", header=None)\n header_list = [\"column\" + str(x) for x in range(len(df.iloc[0]))]\n df.columns = header_list\n if self.drop_nan:\n df = df.dropna()\n\n self.df = df\n\n def on_open_dialog(self, widget):\n dialog = self.builder.get_object(\"dialog\")\n response = dialog.run()\n if response == Gtk.ResponseType.OK:\n filename = dialog.get_filename()\n self.load_table(filename)\n elif response == Gtk.ResponseType.CANCEL:\n dialog.close()\n dialog.close()\n\n def on_close_dialog(self, widget, event):\n return self.builder.get_object(\"dialog\").hide_on_delete()\n\n def on_column_switch(self, switch, gparam):\n self.column_names = bool(switch.get_active())\n\n def on_nan_switch(self, switch, gparam):\n self.drop_nan = bool(switch.get_active())\n\n def on_plot(self, button):\n if self.df is None:\n return\n canvas_window = self.builder.get_object(\"plot1\")\n if canvas_window.get_child():\n canvas_window.show_all()\n return\n fig = plt.figure()\n df = self.df\n x = list(df.columns)[3]\n y = list(df.columns)[5]\n fig.add_subplot().scatter(df[x], df[y])\n plt.xlabel(x)\n plt.ylabel(y)\n\n canvas = FigureCanvasGTK3Agg(fig)\n canvas.set_size_request(800, 600)\n canvas_window.add(canvas)\n canvas_window.show_all()\n\n def on_plot_close(self, widget, event):\n return self.builder.get_object(\"plot1\").hide_on_delete()\n\n def on_destroy(self, event):\n Gtk.main_quit()\n\n\nif __name__ == \"__main__\":\n Plotter()\n Gtk.main()\n","sub_path":"plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"49369079","text":"import arcade.key\nfrom random import randint\n\nclass Model:\n def __init__(self, world, x, y, angle):\n self.world = world\n self.x = x\n self.y = y\n self.angle = 0\n def hit(self, other, hitSize):\n return (abs(self.x - other.x) <= hitSize) and (abs(self.y - other.y) <= hitSize)\n\nclass Gold(Model):\n def __init__(self, world, x, y):\n super().__init__(world, x, y, 0)\n\n def randomLocation(self):\n self.x = randint(0, self.world.width-1)\n self.y = randint(0, self.world.height-1)\n\nclass Ship(Model):\n DIR_HOR = 0\n DIR_VIR = 1\n def __init__(self, world, x, y):\n super().__init__(world, x, y, 0)\n self.direction = Ship.DIR_VIR\n\n def switchDirection(self):\n if(self.direction == Ship.DIR_HOR):\n self.direction = Ship.DIR_VIR\n self.angle = 0\n else:\n self.direction = Ship.DIR_HOR\n self.angle = -90\n\n def update(self, delta):\n if(self.direction == Ship.DIR_VIR):\n if(self.y > self.world.height):\n self.y = 0\n self.y +=5\n if(self.direction == Ship.DIR_HOR):\n if(self.x > self.world.width):\n self.x = 0\n self.x += 5\n\nclass World:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.score = 0\n\n self.gold = Gold(self, 400, 400)\n self.ship = Ship(self, 100, 100)\n\n def update(self, delta):\n self.ship.update(delta)\n\n if(self.ship.hit(self.gold, 15)):\n self.gold.randomLocation()\n self.score+=1\n\n\n def on_key_press(self, key, key_modifiers):\n if(key == arcade.key.SPACE):\n self.ship.switchDirection()\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"378588687","text":"from web3 import HTTPProvider\nfrom contract import Contract, W3\nimport unittest\nimport time\n\nw3 = W3().instance()\n\nclass MyTest(unittest.TestCase):\n def test_timed(self):\n\n price_per_token = 1000\n token_value = 2\n\n #Tokens\n base_token = Contract(\"ERC20Mintable\", w3, {\"owner\": w3.eth.accounts[0], \"args\": []})\n tether = Contract(\"ERC20Mintable\", w3, {\"owner\": w3.eth.accounts[0], \"args\": []})\n \n base_token.instance.mint(w3.eth.accounts[0], 100, transact={'from': w3.eth.accounts[0]})\n tether.instance.mint(w3.eth.accounts[1], 100000, transact={'from': w3.eth.accounts[0]})\n \n #Crowdsale\n block = w3.eth.getBlock(\"latest\")[\"timestamp\"]\n timed_crowdsale = Contract(\"TimedCrowdsale\", w3, {\"owner\": w3.eth.accounts[0], \"args\":[block + 5,block + 10, base_token.address, w3.eth.accounts[0], [tether.address], [price_per_token]]})\n base_token.instance.transfer(timed_crowdsale.address,100, transact={'from': w3.eth.accounts[0]})\n \n #before\n with self.assertRaises(ValueError):\n tether.instance.approve(timed_crowdsale.address,token_value*price_per_token, transact={'from': w3.eth.accounts[1]})\n timed_crowdsale.instance.invest(token_value*price_per_token,tether.address, transact={'from': w3.eth.accounts[1]})\n\n time.sleep(6) \n\n #opened\n tether.instance.approve(timed_crowdsale.address,token_value*price_per_token, transact={'from': w3.eth.accounts[1]})\n timed_crowdsale.instance.invest(token_value*price_per_token,tether.address, transact={'from': w3.eth.accounts[1]})\n\n time.sleep(6)\n \n #closed\n with self.assertRaises(ValueError):\n tether.instance.approve(timed_crowdsale.address,token_value*price_per_token, transact={'from': w3.eth.accounts[1]})\n timed_crowdsale.instance.invest(token_value*price_per_token,tether.address, transact={'from': w3.eth.accounts[1]})\n \n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/E2E_TimedCrowdsale.py","file_name":"E2E_TimedCrowdsale.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"490153935","text":"from base_handler import BaseHandler\nfrom database.blogs import Post\n\nclass Edit(BaseHandler):\n def get(self, pst):\n post = Post.get_post(pst)\n if self.user:\n self.render(\"edit.html\", subject=post.subject, content=post.content, pst=pst)\n else:\n self.redirect('/login')\n\n def post(self, pst):\n if self.user:\n subject = self.request.get('subject')\n content = self.request.get('content')\n pst = self.request.get('post_id')\n if subject and content:\n p = Post.get_post(pst)\n p.subject = subject\n p.content = content\n p.put()\n self.redirect('/permalink/%s' % str(p.key().id()))\n else:\n error = \"subject and content, please!\"\n self.render(\"edit.html\", subject=subject, content=content, pst=pst, error=error)\n else:\n self.redirect('login')\n","sub_path":"handler/edit.py","file_name":"edit.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"100148015","text":"'''\n@ Description: To see this problem and to get database dive into https://www.kaggle.com/c/titanic/overview\n'''\n\n########################### Importing libs ###################################\n\nimport numpy as np\nimport pandas as pd \nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import cross_val_score, GridSearchCV\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder, StandardScaler\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.wrappers.scikit_learn import KerasClassifier\n\n########################### Data visualizing #################################\n\ndataset_train = pd.read_csv('dataset/train.csv')\ndataset_test = pd.read_csv('dataset/test.csv')\n\nsns.factorplot('Sex', data=dataset_train, kind='count')\nsns.factorplot('Pclass',data=dataset_train,hue='Sex',kind='count')\n\n######################### Data Prprocessing ##################################\n\n# Drop nan rows\ndataset_train = dataset_train.dropna(subset = ['Embarked'])\n\n# Replace nan by the mean\ndataset_train['Age'] = dataset_train['Age'].fillna(int(dataset_train['Age'].mean()))\ndataset_train['Fare'] = dataset_train['Fare'].fillna(dataset_train['Fare'].mean())\ndataset_test['Age'] = dataset_test['Age'].fillna(int(dataset_test['Age'].mean()))\ndataset_test['Fare'] = dataset_test['Fare'].fillna(dataset_test['Fare'].mean())\n\n# Training set\nx_train = dataset_train.iloc[:,np.r_[2,4:8,9,11]].values\ny_train = dataset_train.iloc[:,1].values\n\n# Encoding categorical data (One Hot Encoder)\nle = LabelEncoder()\nx_train[:,1] = le.fit_transform(x_train[:,1])\nct = ColumnTransformer([('onehotencoder',OneHotEncoder(),[6])], remainder='passthrough')\nx_train = np.array(ct.fit_transform(x_train), dtype=np.float64)\nx_train = x_train[:, 1:]\n\n# Feature Scaling\nsc_x = StandardScaler()\nx_train = sc_x.fit_transform(x_train)\n\n# Testing set\nx_test = dataset_test.iloc[:,np.r_[1,3:7,8,10]].values\n\n# Encoding categorical data (One Hot Encoder)\nle = LabelEncoder()\nx_test[:,1] = le.fit_transform(x_test[:,1])\nct = ColumnTransformer([('onehotencoder',OneHotEncoder(),[6])], remainder='passthrough')\nx_test = np.array(ct.fit_transform(x_test), dtype=np.float64)\nx_test = x_test[:, 1:]\n\n# Feature Scaling\nx_test = sc_x.transform(x_test)\n\n########################## Make an ANN #######################################\n\nclassifier = Sequential()\n\nclassifier.add(Dense(units=64, kernel_initializer = 'normal', activation = 'relu', input_shape = (8,)))\n\nclassifier.add(Dropout(rate=0.2))\n\nclassifier.add(Dense(units=128, kernel_initializer = 'normal', activation = 'relu'))\n\nclassifier.add(Dropout(rate=0.2))\n\nclassifier.add(Dense(units=256, kernel_initializer = 'normal', activation = 'relu'))\n\nclassifier.add(Dropout(rate=0.2))\n\nclassifier.add(Dense(units=128, kernel_initializer = 'normal', activation = 'relu'))\n\nclassifier.add(Dropout(rate=0.3))\n\nclassifier.add(Dense(units = 1, kernel_initializer = 'normal', activation = 'sigmoid'))\n\nclassifier.compile(optimizer = 'rmsprop', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\nclassifier.fit(x = x_train, y = y_train, batch_size = 32, epochs = 200)\n\n########################## Making the Predictions ############################\n\n# Predicting the Test set results\ny_pred = classifier.predict(x_test)\ny_pred = (y_pred > 0.5)\ny_pred = y_pred.astype(int)\n\n# Generate the csv file\ncsvString = ''\ncsvString += 'PassengerId,Survived\\n'\nfor i in range(892,1310):\n csvString += str(i)+','+str(y_pred[i-892][0])+'\\n'\n\nwith open('gender_submission.csv','w') as file:\n file.write(csvString)\n\n########################## Evaluating ########################################\n\n# Evaluating the ANN with k-fold cross validation\n\ndef build_classifier():\n classifier = Sequential()\n classifier.add(Dense(units=64, kernel_initializer = 'normal', activation = 'relu', input_shape = (8,)))\n classifier.add(Dropout(rate=0.2))\n classifier.add(Dense(units=128, kernel_initializer = 'normal', activation = 'relu'))\n classifier.add(Dropout(rate=0.3))\n classifier.add(Dense(units=256, kernel_initializer = 'normal', activation = 'relu'))\n classifier.add(Dropout(rate=0.3))\n classifier.add(Dense(units=512, kernel_initializer = 'normal', activation = 'relu'))\n classifier.add(Dropout(rate=0.3))\n classifier.add(Dense(units = 1, kernel_initializer = 'normal', activation = 'sigmoid'))\n classifier.compile(optimizer = 'rmsprop', loss = 'binary_crossentropy', metrics = ['accuracy']) \n return classifier\n\nclassifier = KerasClassifier(build_fn = build_classifier, batch_size = 32, epochs = 500)\naccuracies = cross_val_score(estimator = classifier, X = x_train, y = y_train, cv = 10)\nmean = accuracies.mean() # mean\nvariance = accuracies.std() # variance\n\n########################## finding the Hyper-parameters ######################\n\ndef build_classifier():\n classifier = Sequential()\n classifier.add(Dense(units=64, kernel_initializer = 'normal', activation = 'relu', input_shape = (8,)))\n classifier.add(Dropout(rate=0.2))\n classifier.add(Dense(units=128, kernel_initializer = 'normal', activation = 'relu'))\n classifier.add(Dropout(rate=0.3))\n classifier.add(Dense(units=256, kernel_initializer = 'normal', activation = 'relu'))\n classifier.add(Dropout(rate=0.3))\n classifier.add(Dense(units=512, kernel_initializer = 'normal', activation = 'relu'))\n classifier.add(Dropout(rate=0.3))\n classifier.add(Dense(units = 1, kernel_initializer = 'normal', activation = 'sigmoid'))\n classifier.compile(optimizer = 'rmsprop', loss = 'binary_crossentropy', metrics = ['accuracy']) \n return classifier\n\n \nclassifier = KerasClassifier(build_fn = build_classifier)\nparameters = {\n 'batch_size':[12 ,25, 32],\n 'epochs':[100, 250, 500],\n 'optimizer':['adam','rmsprop', 'SGD', 'adamax'],\n 'units_1':[6, 12, 24, 32],\n 'units_2':[6, 12, 24, 32],\n 'kernel_initializer':['uniform','random_uniform', 'glorot_uniform'],\n 'activation':['linear', 'tanh', 'relu']\n }\n\ngrid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 10)\ngrid_search = grid_search.fit(x_train, y_train)\n\nbest_parameters = grid_search.best_params_\nbest_accuracy = grid_search.best_score_\n","sub_path":"Deep Learning/Supervised Learning/Artificial Neural Network/Titanic/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"569965936","text":"from flask_restful import Resource\nfrom flask import current_app as app\nfrom flask import request\nfrom ..data_service.db_service import fakeDB\nfrom geocollage import db\nfrom geocollage.models.post import Post\nfrom geocollage.models.user import User\n\n\nclass Posts(Resource):\n def get(self):\n app.logger.info('GET posts')\n posts = Post.query.all()\n return [post.to_dict() for post in posts]\n def post(self):\n # print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')\n # print(request)\n title = request.get_json().get('title')\n content = request.get_json().get('content')\n user_id = request.get_json().get('user_id')\n if not title or not content or not user_id:\n return {'error': 'missing required data'}\n verified_user = User.query.get(user_id)\n if not verified_user:\n return {'error': 'invalid user'}\n post = Post(title=title, content=content, user_id=user_id)\n db.session.add(post)\n db.session.commit()\n return post.to_dict()\n","sub_path":"geocollage/resources/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"8235563","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nHomework 3 Parts 2 & 3\r\nCreated on Wed Feb 12 14:21:04 2020\r\n\r\n@author: Emily Springer\r\n\"\"\"\r\n\r\nimport PIL\r\nfrom PIL import ImageFilter\r\n\r\nim = PIL.Image.open(r\"C:\\Caltech\\Ph21\\hw3\\image.jpg\")\r\n\r\nprint(im.format, im.size, im.mode)\r\n\r\nimageWithEdges = im.filter(ImageFilter.FIND_EDGES)\r\nim.show()\r\nimageWithEdges.show()\r\n\r\n","sub_path":"hw3/hw3p2.py","file_name":"hw3p2.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"499017357","text":"## Constants used by this program\nCONSONANTS = \"bcdfghjklmnpqrstvwyz\"\nVOWELS = \"aeiou\" \npairs = []\n\ndef convert_pin(pin): #joins pairs of letters in list(word)\n word = []\n def pair_pin(pin): #divide pin into pairs and append into list(pairs)\n while pin:\n pairs.append(pin % 100)\n pin = int(pin // 100)\n\n def convert_pair(): #converts pairs of numbers into letters\n while pairs:\n x = pairs.pop()\n word.append(CONSONANTS[x // 5])\n word.append(VOWELS[x % 5])\n try:\n pair_pin(pin)\n convert_pair()\n 1 / pin\n except:\n return ValueError\n print(\"\".join(word))\n return \"\".join(word) \n\nconvert_pin(4327)\n","sub_path":"old/others/connor_pins.py","file_name":"connor_pins.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"565354623","text":"\"\"\"Various functions related to ingestion of previously reported unknown dependencies.\"\"\"\n\nfrom datetime import datetime as dt, timedelta\nfrom f8a_report.helpers.graph_report_generator import find_ingested_epv\nfrom f8a_report.helpers.s3_helper import S3Helper\nimport logging\n\nlogger = logging.getLogger(__file__)\n\n\nclass UnknownDepsReportHelper:\n \"\"\"Utility functions for reporting ingestion of reported unknown dependencies.\n\n Lists Previous Day Unknown Dependencies from Previous Day Daily Report\n \"\"\"\n\n def __init__(self):\n \"\"\"Init method for UnknownDepReportHelper.\"\"\"\n self.s3 = S3Helper()\n\n @staticmethod\n def get_obj_key(past_date):\n \"\"\"Get s3 object key.\"\"\"\n logger.info(\"Building key for v1.\")\n return f'daily/{past_date}.json'\n\n def get_unknown_list(self, result):\n \"\"\"Create a list of unknown deps.\"\"\"\n ecosystem_list = ['npm', 'maven', 'pypi', 'golang']\n unknown_deps_list = {}\n for eco in ecosystem_list:\n deps = []\n if result:\n unknown_deps = result.get('stacks_summary', {}).get(eco, {}). \\\n get('unique_unknown_dependencies_with_frequency', {})\n for k, v in unknown_deps.items():\n pkg_ver = k.split()\n try:\n pkg, ver = pkg_ver[0], pkg_ver[1]\n deps.append({'name': pkg, 'version': ver})\n except IndexError:\n logger.info(\"Incorrect name value pair found in unknown list {}\".format(k))\n unknown_deps_list[eco] = deps\n return unknown_deps_list\n\n def get_past_unknown_deps(self):\n \"\"\"Retrieve the list of unknown deps.\"\"\"\n logger.info(\"Fetching past unknown deps.\")\n # find out the previous date\n today = dt.today()\n past_date = (today - timedelta(days=1)).strftime('%Y-%m-%d')\n\n # Get the report of the previous date\n past_obj_key = self.get_obj_key(past_date)\n result = self.s3.read_json_object(bucket_name=self.s3.report_bucket_name,\n obj_key=past_obj_key)\n\n # Return the list of unknown dependencies found\n return self.get_unknown_list(result)\n\n def get_current_ingestion_status(self):\n \"\"\"Generate ingestion report for previously unknown dependecies.\"\"\"\n # Get the past unknown dependencies\n unknown_deps = self.get_past_unknown_deps()\n ingestion_report = {}\n\n # Check for the known one's among those\n for eco, deps in unknown_deps.items():\n ingestion_report[eco] = find_ingested_epv(eco, deps)\n # Report the ingested repositories\n return ingestion_report\n\n\nclass UnknownDepsReportHelperV2(UnknownDepsReportHelper):\n \"\"\"Unknown Dep Report Helper for v2.\"\"\"\n\n @staticmethod\n def get_obj_key(past_date):\n \"\"\"Get s3 object key.\"\"\"\n logger.info(\"Building key for v2.\")\n return f'v2/daily/{past_date}.json'\n","sub_path":"f8a_report/helpers/unknown_deps_report_helper.py","file_name":"unknown_deps_report_helper.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"238940337","text":"n = int(input())\na = input().split(\" \")\ncount = 0\nlst = []\nc = 0\nfor i in a:\n count += int(i)\nprint(count)\nfor i in range(count):\n for j in range(len(a)):\n lst.append(j)\n for k in range(1, int(j+1)):\n c += k\n lst.append(c)\n print(lst)\n if i not in lst:\n print(i)\n\n","sub_path":"Practice/SmallestIntValue.py","file_name":"SmallestIntValue.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"315788788","text":"import sysv_ipc\nimport random\n\nclass Carte:\n\tdef __init__(self, couleur, nb):\n\t\tself.couleur = couleur\n\t\tself.nb = nb\n\tdef __str__(self):\n\t\treturn self.couleur+\" \"+str(self.nb)\n\n\ndef Board(developMode):\n\tglobal bmq\n\tglobal vmq\n\tglobal stack\n\tglobal pile\n\tbmq = sysv_ipc.MessageQueue(60)\n\tvmq = sysv_ipc.MessageQueue(40)\n\tstack = []\n\tpile = []\n\n\t\"\"\"\n\tBoard message queue : \n\t1 - To player 1\n\t2 - To player 2\n\t3 - From Player\n\t7 - Endgame\n\t9 - Send 5 card\n\t10 - Send key autoryze\n\t\"\"\"\n\t# Function that check the validity of the card played\n\tdef checkCard(cardstr):\n\t\tst = stack[len(stack)-1] \n\t\tcardstr = cardstr.split(\" \")\n\t\tcard = Carte(cardstr[0], int(cardstr[1]))\n\t\tif card.couleur == st.couleur :\n\t\t\tif abs(card.nb - st.nb)==1 or abs(card.nb - st.nb)==9:\n\t\t\t\treturn True\n\t\t\telse : return False\n\t\telse :\n\t\t\tif card.nb == st.nb :\n\t\t\t\treturn True\n\t\t\telse : return False \n\n\tdef displayBoard(developMode):\n\t\tcard = stack[len(stack)-1]\n\t\tif developMode :\n\t\t\tprint(card)\n\t\telse : \n\t\t\tm = \"3:\"+str(card)+\":\"+str(len(pile))\n\t\t\tvmq.send(m.encode(), type = 3)\n\n\n\tfor i in range(1,11):\n\t\tpile.append(Carte(\"Rouge\", i))\n\t\tpile.append(Carte(\"Bleu\", i))\n\t\n\trandint = random.randint(0, (len(pile)-1))\n\tstack.append(pile.pop(randint))\n\n\t# Send the key autorise for each player\n\tkeyPackP1 = \"1:a:z:e:r:t:y:u:i:o:p\"\t# Pack off the key used by player 1\n\tkeyPackP2 = \"2:m:l:k:j:h:g:f:d:s:q\"\t# Pack off the key used by player 2\n\tbmq.send(keyPackP1.encode(), type = 10)\n\tbmq.send(keyPackP2.encode(), type = 10)\n\n\t# Send the hand of each player\n\tmsghand1 = str(pile.pop(random.randint(0, (len(pile)-1))))\n\tmsghand2 = str(pile.pop(random.randint(0, (len(pile)-1))))\n\n\tfor i in range(4):\n\t\tmsghand1 += \":\"+str(pile.pop(random.randint(0, (len(pile)-1))))\n\t\tmsghand2 += \":\"+str(pile.pop(random.randint(0, (len(pile)-1))))\t\n\tbmq.send(msghand1.encode(), type = 9)\n\tbmq.send(msghand2.encode(), type = 9)\n\t\n\twhile True : \n\t\tdisplayBoard(developMode)\n\t\t# Waiting for a player message\n\t\ttry : \n\t\t\tm, t = bmq.receive(type = 3)\n\t\texcept sysv_ipc.ExistentialError :\n\t\t\tbreak\n\t\tm = m.decode().split(\":\")\n\n\t\t# If a player has finished\n\t\tif m[1] == \"gameDone\":\n\t\t\tbmq.send(m[0].encode(), type=7)\n\t\t\tbreak\n\t\t\n\t\t# If a player has a penality\n\t\telif m[1] == \"penalty\" : \n\t\t\t# If the limit of card is not reached, send a card\n\t\t\tif int(m[2]) < 10:\n\t\t\t\tcard = str(pile.pop(random.randint(0,len(pile)-1)))\n\t\t\t# If it is, send nothing\n\t\t\telse :\n\t\t\t\tcard = \"\"\n\t\t\tbmq.send(card.encode(), type = int(m[0]))\n\n\t\t\t# If pile\n\t\t\tif len(pile)==0:\n\t\t\t\tempty =\"\"\n\t\t\t\tbmq.send(empty.encode(), type = 7)\t\t\n\t\t\t\tbreak\n\n\t\t# Else => a player play a card \n\t\telse :\n\t\t\t# If the card is valid, send the same card\n\t\t\tif checkCard(m[1]) :\n\t\t\t\tcard = m[1].split(\" \")\n\t\t\t\tbmq.send(m[1].encode(), type = int(m[0]))\n\t\t\t\tstack.append(Carte(card[0], int(card[1])))\n\n\t\t\telse :\n\t\t\t\t# If the limit of card is not reached, send a card\n\t\t\t\tif int(m[2]) < 10:\n\t\t\t\t\tcard = str(pile.pop(random.randint(0,len(pile)-1)))\n\t\t\t\t# If it is, send nothing\n\t\t\t\telse :\n\t\t\t\t\tcard = \"\"\n\t\t\t\tbmq.send(card.encode(), type = int(m[0]))\n\t\t\t\t\n\t\t\t\t# If pile is empty\n\t\t\t\tif len(pile)==0:\n\t\t\t\t\tempty =\"\"\n\t\t\t\t\tbmq.send(empty.encode(), type = 7)\t\t\n\t\t\t\t\tbreak\n\n\t\t\t\t\n\n\n","sub_path":"FreakOut/Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"392806905","text":"import os\nimport time\nimport random\nimport urllib\nimport requests\nimport sys\nimport shutil\nimport zipfile\nfrom xml.dom.minidom import parse\nfrom bs4 import BeautifulSoup as bs\nimport xml.dom.minidom as xdm\nprint(\"Please input epubee link, exit to quit:\")\nprint(\"Example:http://reader.obook.vip/books/mobile/62/6244a56007d3b59ac79d0e870b455b6e/\")\ncache_path=\"cache\"\nbook_path=\"book\"\nwhile True:\n book_link=input()\n if \"reader.obook.vip/books/mobile\" in book_link:\n break\n elif \"exit\" in book_link:\n sys.exit()\n else:\n print(\"[-] E:Invailed link, please check your link and retry!\")\nisCacheExists=os.path.exists(cache_path)\nif isCacheExists:\n shutil.rmtree(cache_path)#清除旧文件夹\n print(\"[*] Cache cleared successfully\")\n os.makedirs(cache_path)#建立新文件夹\nelse:\n os.makedirs(cache_path)\nisBookExists=os.path.exists(book_path)\nif not isBookExists:\n os.makedirs(book_path)\nopf_link=book_link+\"content.opf\"\nfor i in range(1,11):\n try:\n urllib.request.urlretrieve(opf_link,\"{}//content.opf\".format(cache_path))\n break\n except Exception as e:\n print(\"[-] E:{}\".format(e))\n print(\"[-] Retrying {} of 10 times\".format(i))\n time.sleep(random.randint(1,4))\nisOpfExists=os.path.exists(cache_path+\"//content.opf\")\nif isOpfExists:\n print(\"[+] Opf file download successfully\")\nelse:\n print(\"[-] Opf file download failed, please check your internet connection!\")\n sys.exit()\nxml_doom=xdm.parse(\"{}//content.opf\".format(cache_path))\nbook_info=xml_doom.documentElement\nbook_name=book_info.getElementsByTagName(\"dc:title\")\n#print(book_name[0].childNodes[0].data)\nname=book_name[0].childNodes[0].data\nbook_author=book_info.getElementsByTagName(\"dc:creator\")\n#print(book_author[0].childNodes[0].data)\nauthor=book_author[0].childNodes[0].data\nbook_content=book_info.getElementsByTagName(\"item\")\nmax_num=len(book_content)\nnum=1\nprint(\"[*] Opf file analyze successfully\")\nprint(\"[*] Downloading contents...\")\nfor b_item in book_content:\n #print(b_item.getAttribute(\"href\"))\n for j in range(1,50):\n try:\n item=b_item.getAttribute(\"href\")\n if \"/\" in item:\n sub_link=item.split(\"/\")\n sub_path=\"{}//{}\".format(cache_path,sub_link[0])\n isSubExists=os.path.exists(sub_path)\n if not isSubExists:\n os.makedirs(sub_path)\n urllib.request.urlretrieve(\"{}{}\".format(book_link,item),\"{}//{}\".format(sub_path,sub_link[1]))\n elif \"html\" in item:\n #urllib.request.urlretrieve(\"{}{}\".format(book_link,item),\"{}//{}\".format(cache_path,item))\n r=requests.get(\"{}{}\".format(book_link,item),timeout=5)\n soup=bs(r.content,\"html5lib\")\n try:\n soup.find('div',class_=\"readertop\").decompose()\n soup.find('div',class_=\"readermenu\").decompose()\n soup.find('div',class_=\"reader-to-vip c-pointer\").decompose()\n except:\n print(\"[*] Nothing to remove\")\n f=open(\"{}//{}\".format(cache_path,item),'w',encoding='utf-8')\n f.write(str(soup))\n f.close()\n else:\n urllib.request.urlretrieve(\"{}{}\".format(book_link,item),\"{}//{}\".format(cache_path,item))\n break\n except Exception as e:\n print(\"[-] E:{}\".format(e))\n print(\"[-] Retrying {} of 50 times\".format(j))\n time.sleep(random.randint(1,4))\n print(\"[*] {} of {} items downloaded\".format(num,max_num))\n num+=1\nprint(\"[+] Content download successfully\")\nf=open(\"{}//mimetype\".format(cache_path),'w',encoding='utf-8')\nf.write(\"application/epub+zip\")\nf.close()\nprint(\"[*] Mimetype file create successfully\")\nos.makedirs(\"{}//META-INF\".format(cache_path))\nf=open(\"{}//META-INF//container.xml\".format(cache_path),'w',encoding='utf-8')\nf.write('\\n\\n \\n \\n \\n')\nf.close()\nprint(\"[*] Meta info create successfully\")\nnew_book=zipfile.ZipFile(\"{}//tmp.zip\".format(book_path),'w')\nprint(\"[*] Packaging...\")\npack=os.walk(cache_path)\nfor current_path,subfolders,filesname in pack:\n for file in filesname:\n src=os.path.join(current_path,file)\n dst=src.replace(cache_path,\"\",1)\n #print(\"{},{}\".format(src,dst))\n new_book.write(src,arcname=dst,compress_type=zipfile.ZIP_STORED)\nnew_book.close()\nos.rename(\"{}//tmp.zip\".format(book_path),\"{}//{}-{}.epub\".format(book_path,name,author))\nprint(\"[*] {}-{} download successfully\".format(name,author))\nos.system(\"pause\")\n","sub_path":"Project_epubee_win.py","file_name":"Project_epubee_win.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"382174081","text":"'''\nA simple program used to spit out random secuances of hex with db as the first\ntwo letters and as the last to. takes a bit of time to prosess\n'''\nimport binascii\nimport os\nimport cgitb\ncgitb.enable()\n\n\ndef main():\n '''Main Looping part'''\n print(\"Content-type: text/plain\\n\")\n loopnum = 0\n while loopnum < 50:\n data = binascii.hexlify(os.urandom(16)).decode('utf8')\n if data[0] == 'd' and data[1] == 'b' and data[-2] == 'd' \\\n and data[-1] == 'b':\n\n if loopnum < 9:\n collon = ' : '\n else:\n collon = ' : '\n\n print(str(loopnum+1) + collon + data)\n loopnum += 1\n\nif __name__ == '__main__':\n main()\n","sub_path":"webapp/donoteverrun.py","file_name":"donoteverrun.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"555680963","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 30 17:30:07 2020\n\n@author: qtckp\n\"\"\"\n\n\nimport pandas as pd\nfrom textblob import TextBlob\nfrom googletrans import Translator\n\ntranslator = Translator()\n\n\ndf1 = pd.read_table('per_phonemic.tsv', header=None)\n\ndef trans(txt):\n try:\n res = translator.translate(txt, src='fa', dest='en').text\n except:\n res = 'CANNNNNNOT'\n return res\n\n\ndf1[2] = pd.Series([txt.replace('\\u200c','') for txt in df1[0]])\n\ndf1[3] = pd.Series([trans(txt) for txt in df1[2]])\n\n# ', '.join(df1[0].values)\n\ndf1.to_csv('transformed.csv')\n\n\n\n# compare with tihu\n\nimport json\n\nwith open('tihudict.json','r') as f:\n tihu = json.load(f)\n\n\ndef get_unique(lst):\n r = set()\n for elem in lst:\n r = r.union(set(elem))\n return r\n\n\ngoal = get_unique(tihu.values())\n\nhave = get_unique(df1[4])\n\nto_delete = have.difference(goal)\n\n\ninds = [k for k in range(len(df1)) if df1.iloc[k,2] in tihu and set(df1.iloc[k,4]).intersection(to_delete) != set()]\n\ncomp = df1.iloc[inds,:]\ncomp['target'] = pd.Series([tihu[key] for key in comp[2]], index = comp.index)\n\n\ndef replacenator(text):\n from_=['ʃ','ɑː','ɒː','ɔː','tʰ','æ','ɾ','j','uː','ɣ','ʔ ','iː','d ʒ','ɪ','d͡ʒ','#','xʷ','t̪']\n to_=['S','A','A','A','t','a','r','y','A','q','','i','j','i','j','','x','t']\n for f, t in zip(from_,to_):\n text = text.replace(f,t)\n return text\n\ndf1[4] = pd.Series([replacenator(a) for a in df1[1]])\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"transform dict/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92796398","text":"import matplotlib.pyplot as plt\nimport pandas as pd\n\ndef india_Daily_Status(case_time_series):\n ########## Getting the Required Data ########## \n data = case_time_series.copy()\n Daily_Confirmed=data['Daily Confirmed'].tail(15)\n Daily_Recovered=data['Daily Recovered'].tail(15)\n Daily_Deceased=data['Daily Deceased'].tail(15)\n date = pd.to_datetime(data['Date'].tail(15))\n\n ########## Line Plot ########## \n plt.figure()\n plt.rc('xtick', labelsize=8)\n plt.rc('ytick', labelsize=8)\n plt.plot(date, Daily_Confirmed, marker='o')\n plt.plot(date, Daily_Recovered, marker='o')\n plt.plot(date, Daily_Deceased, marker='o')\n plt.title(\"Last 15 daily days Status\")\n plt.xlabel('Date')\n plt.ylabel('Number of people')\n plt.legend([\"Confirmed\", \"Recovered\", \"Deceased\"])\n plt.grid(True)\n for a, b in zip(date, Daily_Confirmed):\n plt.text(a, b, str(b))\n for a, b in zip(date, Daily_Recovered):\n plt.text(a, b, str(b))\n for a, b in zip(date, Daily_Deceased):\n plt.text(a, b, str(b))\n plt.show()","sub_path":"India_Daily_Status.py","file_name":"India_Daily_Status.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"97494660","text":"\nimport os\nimport numpy\n\nclass Experiment:\n# Class for the experiment for the application \n\tdef __init__(self, log_path):\n\t\t# Initializing the base attribute of the experiment\n\t\tself.source_log = log_path\n\t\tself.launch_parameters = self.extract_params(log_path)\n\t\tself.comment = ''\n\t\tif self.check_file(log_path):\n\t\t\t# print(\"Not a log file\")\n\t\t\t# Marking the errors of input or execution errors for further separation\n\t\t\tself.comment = 'Error in datafile import. Required rerun on the params {0}'.format(self.launch_parameters)\n\t\telse:\n\t\t\tself.launch_data = self.readlog(log_path)\n\t\t\tself.data_extract = self.log_max_time(log_path)\n\t\t\t# print (\"Experiment {0} inited\".format(self.source_log))\n\t\t\t\n\tdef __repr__(self):\n\t\toutput = ''\n\t\toutput += '* Log path:\\n* {0}\\n'.format(self.source_log)\n\t\toutput += '* Launch parameters of the experiment: \\n'\n\t\tfor parameter in self.launch_parameters:\n\t\t\toutput += '* {0} : {1}\\n'.format(parameter,self.launch_parameters[parameter])\n\t\tif self.comment:\n\t\t\toutput += '* Comment: {0}'.format(self.comment)\n\t\toutput += '* Max time between processes in log:\\n'\n\t\tfor key in self.data_extract:\n\t\t\toutput += '* {0} : {1}\\n'.format(key,self.data_extract[key])\n\t\treturn output\n\t\n\tdef print(self,mode = ''):\n\t\tprint('* Log path:\\n* {0}'.format(self.source_log))\n\t\tprint('* Launch parameters of the experiment: ')\n\t\tfor parameter in self.launch_parameters:\n\t\t\tprint('* {0} : {1}'.format(parameter, self.launch_parameters[parameter]))\n\t\tif self.comment:\n\t\t\tprint('* Comment: {0}'.format(self.comment))\n\t\tprint('* Max time between processes in log:')\n\t\tfor key in self.data_extract:\n\t\t\tprint('* {0} : {1}'.format(key, self.data_extract[key]))\n\t\tif mode:\n\t\t\tprint('* Full data of logfile:')\n\t\t\tfor key in self.launch_data:\n\t\t\t\tprint ('* {0} : '.format(key))\n\t\t\t\tfor proc in self.launch_data[key]:\n\t\t\t\t\tprint('* {0} : {1}'.format(proc, self.launch_data[key][proc]))\n\n\tdef check_file(self, logfile):\n\t\t# Checking the input file to be a log file for the experiment, checking the correctness of the format and errrors\n\t\t# TODO:\n\t\t# move to the regexp in the check and try to formalize the checking of the file correctness.\n\t\t# print('Check method')\n\t\tfiledata = open(logfile,'r')\n\t\tif (filedata.read(32))=='--------------------------------':\n\t\t\t# print(\"Error file\")\n\t\t\tfiledata.close()\n\t\t\treturn 1\n\t\telse:\n\t\t\tfiledata.close()\n\t\t\treturn 0\n\n\tdef extract_params(self, logfile):\n\t\t# Getting params from the logfile\n\t\t#TODO:\n\t\t#implement abstract parameters set for this method\n\t\t# print('Extract method')\n\t\tlinewords = logfile.split('/')\n\t\tparams = linewords[-1].split('_')\n\t\t# print (params)\n\t\tparams_data = {}\n\t\tparams_data['Procs'] = int(params[1][1:])\n\t\tparams_data['Problem_size'] = int(params[2][:-1]) * 1000\n\t\tparams_data['Levels'] = int(params[3][1:])\n\t\tparams_data['Tolerance'] = int(params[4][1:])\n\t\treturn params_data\n\n\tdef readlog(self, logfile):\n\t\t# Reading data from log file\n\t\t# print('Readlog method')\n\t\tfiledata = open(logfile, \"r\")\n\t\t# print (filedata.readlines())\n\t\tlog_data = {}\n\t\tfor line in filedata.readlines():\n\t\t\t# print (line)\n\t\t\tif line == \"\" or line =='\\n' or line.find(\":\") == -1:\n\t\t\t\t# print (\"Line Skiped\")\n\t\t\t\tcontinue\n\t\t\t# print ('Line is : \" {0} \"'.format(line))\n\t\t\trank_number = int(line.split(\":\")[0].split(' ')[1][:-1])\n\t\t\t# print('Rank is \" {0} \"'.format(rank_number))\n\t\t\tstep_number = line.split(\":\")[0].split(' ')[-1]\n\t\t\t# print ('Step is: \" {0} \"'.format(step_number))\n\t\t\tstep_time = float(line.split(\":\")[1])\n\t\t\t# print ('Step time is: \" {0} \"'.format(step_time))\n\t\t\t# print (log_data.get(step_number))\n\t\t\tif log_data.get(step_number) == None:\n\t\t\t\tlog_data[step_number] = {}\n\t\t\tlog_data[step_number][rank_number] = step_time\n\t\t\t# print (log_data.get(step_number))\n\t\n\t\t# print(log_data)\n\t\tfiledata.close()\n\t\treturn log_data\n\n\tdef log_max_time(self, logfile):\n\t\t# Getting maximum time from log\n\t\tlog_data = self.readlog(logfile) # Possible to avoid double call of readlog for the same file\n\t\tlog_max_time = {}\n\t\t# print(log_data)\n\t\t# print(log_data.keys())\n\t\tfor key in log_data.keys():\n\t\t\t\tlog_max_time[key] = max(log_data[key].values())\n\t\t# print(log_max_time)\n\t\treturn log_max_time\n\n\n\nclass MergedExperiment(Experiment):\n# Class for the set of the set of applications launches with the same parameters\n\tdef __init__(self, experiment_obj):\n\t\t# Initializing the base parameters\n\t\tself.source_log = {experiment_obj.source_log,} \n\t\tself.launch_parameters = experiment_obj.launch_parameters\n\t\tself.launch_data = {}\n\t\tself.data_extract = {}\n\t\tself.comment = set()\n\t\tfor key in experiment_obj.launch_data.keys():\n\t\t\tself.launch_data[key] = [experiment_obj.launch_data[key]]\n\t\tfor key in experiment_obj.data_extract.keys():\n\t\t\tself.data_extract[key] = [experiment_obj.data_extract[key]]\n\t\t# self.data_extract = experiment_obj.data_extract\n\t\tself.comment.add(experiment_obj.comment)\n\n\tdef merge(self, experiment_obj):\n\t\t# Method for merging data of new experiment with existing\n\t\tif self.launch_parameters == experiment_obj.launch_parameters:\n\t\t\t# print('Merge is possible')\n\t\t\tself.source_log.add(experiment_obj.source_log)\n\t\t\tfor key in experiment_obj.launch_data.keys():\n\t\t\t\tself.launch_data[key].append(experiment_obj.launch_data[key])\n\t\t\tfor key in experiment_obj.data_extract.keys():\n\n\t\t\t\tself.data_extract[key].append(experiment_obj.data_extract[key])\n\t\t\treturn 0\n\t\telse:\n\t\t\t# print('Error: Merge is impossible')\n\t\t\treturn 1\n\n\n\nclass Timing:\n\t# Class for the time of the parameters set and execution time for the application launch\n\tdef __init__(self, params, time):\n\t\tself.params = params\n\t\tself.time = time\n\n\tdef __eq__(self, other):\n\t\treturn self.params == other.params\n\n\t# def __lt__(self, other):\n\t# \tfor param in self.params:\n\t# \t\tif self.params[param] None:\n \"\"\"Changes the worm attributes by the food-type\"\"\"\n\n if type == FoodType.faster:\n worm.updateSpeed(food_type_factors['faster'])\n elif type == FoodType.slower:\n worm.updateSpeed(food_type_factors['slower'])\n elif type == FoodType.bigger:\n worm.updateRadius(food_type_factors['bigger'])\n elif type == FoodType.smaller:\n worm.updateRadius(food_type_factors['smaller'])\n\n\nclass Food(Circle):\n \"\"\"Child class from Circle-class\"\"\"\n\n def __init__(self, coord, energy, surface, angle = 0, speed = default_food['speed'], id = None):\n super().__init__(coord, 1, (0, 255, 0), surface, angle, speed)\n self.energy = energy\n if self.angle == 0:\n self.angle = random() * 2*math.pi\n self.vector = []\n self.vector.append(math.cos(self.angle) * self.speed)\n self.vector.append(math.sin(self.angle) * self.speed)\n self.ttl = 1000\n\n if id is None:\n self.id = Food.id_counter\n Food.id_counter += 1\n else:\n self.id = id\n\n self.type = randint(0, food_type_factors['count'])\n self.color = FoodType.getColor(self.type)\n self.radius = FoodType.getRadius(self.type)\n\n self.updatedByServer = False\n\n id_counter = 0\n\n # indexes for getData and updateByData (better then strings, for the multiplayer):\n d_coord = 0\n d_radius = 1\n d_energy = 2\n d_angle = 3\n d_speed = 4\n d_id = 5\n d_type = 6\n d_color = 7\n d_ttl = 8\n\n def getData(self) -> dict:\n \"\"\"generates data of this food-object for the webSocket-client\"\"\"\n\n data = {\n Food.d_coord: self.coord,\n Food.d_radius: self.radius,\n Food.d_energy: self.energy,\n Food.d_angle: self.angle,\n Food.d_speed: self.speed,\n Food.d_id: self.id,\n Food.d_type: self.type,\n Food.d_color: self.color,\n Food.d_ttl: self.ttl\n }\n\n return data\n\n def updateByData(self, data: dict) -> None:\n \"\"\"update this food-object with the data provided by the webSocket-server\"\"\"\n\n self.coord = data[Food.d_coord]\n self.radius = data[Food.d_radius]\n self.energy = data[Food.d_energy]\n self.angle = data[Food.d_angle]\n self.speed = data[Food.d_speed]\n self.type = data[Food.d_type]\n self.color = data[Food.d_color]\n self.ttl = data[Food.d_ttl]\n\n self.updatedByServer = True\n\n\ndef addFood(surface) -> Food:\n \"\"\"creates a new food object an add it to the foodHolder-list\"\"\"\n\n newFood = Food(\n coord=[randint(0, screen_resolution[0]), randint(0, screen_resolution[1])],\n energy=2,\n surface=surface\n )\n foodHolder.append(newFood)\n\n return newFood\n","sub_path":"scripts/food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"335122370","text":"from PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\n\nfrom time import time\n\nimport glob\nimport numpy as np\nimport os\nfrom pathlib import Path\n\n\nfrom ..Widgets.MainWidget import MainWidget\nfrom ..Models.Model import Model\nfrom ..Other.Dialogs import open_file_dialog\n\nclass Controller(object):\n def __init__(self):\n\n self.directory = {'Home' : str(Path.home()) + '/Documents/Work/Experiments/'}\n # self.directory = {'Home' : str(Path.home()) + '/Desktop'}\n # print(self.directory['Home'])\n\n self.widget = MainWidget()\n\n self.model = Model(widget = self.widget)\n\n self.plotted = 0\n\n self.create_signals()\n\n self.widget.show()\n\n def create_signals(self):\n \n self.widget.load_image.clicked.connect(self.load_image)\n self.widget.im_widget.left_mouse_clicked.connect(self.update_ind)\n self.widget.im_widget.mouse_scrolled.connect(self.scroll_zoom)\n self.widget.im_widget.mouse_double.connect(self.zoom_fill)\n self.widget.im_widget.mouse_zoom.connect(self.box_zoom)\n\n self.widget.wid_x_txt.editingFinished.connect(self.check_wid)\n self.widget.wid_y_txt.editingFinished.connect(self.check_wid)\n self.widget.skip_x_txt.editingFinished.connect(self.check_skip)\n self.widget.skip_y_txt.editingFinished.connect(self.check_skip)\n\n self.widget.gauss_sm_cb.clicked.connect(self.update_all)\n self.widget.gauss_x_txt.editingFinished.connect(self.check_gauss)\n self.widget.gauss_y_txt.editingFinished.connect(self.check_gauss)\n\n self.widget.log_btn.clicked.connect(self.log)\n self.widget.exp_btn.clicked.connect(self.exp)\n self.widget.sqrt_btn.clicked.connect(self.sqrt)\n\n self.widget.dIdx_btn.clicked.connect(self.dIdx)\n self.widget.dIdy_btn.clicked.connect(self.dIdy)\n self.widget.dI_btn.clicked.connect(self.dI)\n\n self.model.im_changed.connect(self.update_all)\n\n self.widget.closeEvent = self.close_event\n\n\n def check_wid(self):\n # print('check_wid', self.widget.im_widget.axes.get_xlim(), self.widget.im_widget.axes.get_ylim())\n new_wid_x = int(float(self.widget.wid_x_txt.text())/2)\n new_wid_y = int(float(self.widget.wid_y_txt.text())/2)\n if new_wid_x != self.model.xwd or new_wid_y != self.model.ywd:\n self.update_lines()\n\n def check_skip(self):\n # print('check_skip', self.widget.im_widget.axes.get_xlim(), self.widget.im_widget.axes.get_ylim())\n new_skip_x = int(float(self.widget.skip_x_txt.text()))\n new_skip_y = int(float(self.widget.skip_y_txt.text()))\n if new_skip_x != self.model.skip[1] or new_skip_y != self.model.skip[0]:\n self.update_all()\n\n def check_gauss(self):\n if self.widget.gauss_sm_cb.isChecked():\n self.update_all()\n\n def update_all(self):\n # print('update_all', self.widget.im_widget.axes.get_xlim(), self.widget.im_widget.axes.get_ylim())\n self.calc_plot_image()\n self.plot_image()\n self.update_lines()\n\n def update_lines(self):\n self.calc_lineouts()\n self.plot_lineouts()\n self.plot_lineout_lines()\n\n\n def update_ind(self, x, y):\n one = (x > 0) and (x 0) and (y=0 and lim[1]= len(y):\n ind = [i for i in range(lim[0], len(y)-1)]\n\n\n yl = [np.min(y[ind]), np.max(y[ind])]\n rng = yl[1]-yl[0]\n new_yl = [yl[0]-0.05*rng, yl[1]+0.05*rng]\n self.widget.hor_lineout_widget.axes.set_ylim(new_yl)\n self.widget.hor_lineout_widget.draw()\n\n\n x = self.model.line['ver']['x']\n y = self.model.line['ver']['y']\n lim = self.model.ylim\n self.widget.ver_lineout_widget.plot_lineout(x=x, y=y, axis=0, lim=lim)\n\n if lim[0]>=0 and lim[1]= len(x):\n ind = [i for i in range(lim[0], len(x)-1)]\n\n xl = [np.min(x[ind]), np.max(x[ind])]\n\n x_rng = xl[1]-xl[0]\n new_xl = [xl[0]-0.05*x_rng, xl[1]+0.05*x_rng]\n self.widget.ver_lineout_widget.axes.set_xlim(new_xl)\n self.widget.ver_lineout_widget.draw()\n\n def plot_lineout_lines(self):\n\n # print('plot_lineout_lines', self.widget.im_widget.axes.get_xlim(), self.widget.im_widget.axes.get_ylim())\n while len(self.widget.im_widget.axes.patches) > 0:\n self.widget.im_widget.axes.patches[-1].remove()\n\n y0 = 1\n ywd = self.model.im.shape[0]\n xwd = self.model.xwd *2\n x0 = self.model.ind[0]-xwd/2\n xl = np.array([self.model.ind[0], self.model.ind[0]])\n yl = np.array(self.widget.hor_lineout_widget.axes.get_ylim())\n\n self.widget.hor_lineout_widget.plot_lineout_reg(xl, yl, x0, yl[0], xwd, yl[1]-yl[0])\n if self.model.xwd > 1:\n self.widget.im_widget.plot_rect(x0, y0, xwd, ywd)\n\n x0 = 1\n xwd = self.model.im.shape[1]\n ywd = self.model.ywd *2\n y0 = self.model.ind[1]-ywd/2\n yl = np.array([self.model.ind[1], self.model.ind[1]])\n xl = np.array(self.widget.ver_lineout_widget.axes.get_xlim())\n\n self.widget.ver_lineout_widget.plot_lineout_reg(xl, yl, xl[0], y0, xl[1]-xl[0], ywd)\n if self.model.ywd > 1:\n self.widget.im_widget.plot_rect(x0, y0, xwd, ywd)\n\n self.widget.im_widget.remove_lineout_lines()\n self.widget.im_widget.plot_lineout_lines(self.model)\n\n def log(self):\n self.widget.exp_btn.setChecked(False)\n self.widget.sqrt_btn.setChecked(False)\n self.update_all()\n\n def exp(self):\n self.widget.sqrt_btn.setChecked(False)\n self.widget.log_btn.setChecked(False)\n self.update_all()\n\n def sqrt(self):\n self.widget.log_btn.setChecked(False)\n self.widget.exp_btn.setChecked(False)\n self.update_all()\n\n def dIdx(self):\n self.widget.dIdy_btn.setChecked(False)\n self.widget.dI_btn.setChecked(False)\n self.update_all()\n\n def dIdy(self):\n self.widget.dIdx_btn.setChecked(False)\n self.widget.dI_btn.setChecked(False)\n self.update_all()\n\n def dI(self):\n self.widget.dIdx_btn.setChecked(False)\n self.widget.dIdy_btn.setChecked(False)\n self.update_all()\n\n\n\n def scroll_zoom(self, step):\n if self.model.im is not None:\n xl = np.array(self.widget.im_widget.axes.get_xlim())\n yl = np.array(self.widget.im_widget.axes.get_ylim())\n\n\n if xl[0]-step < xl[1]+step and yl[0]-step < yl[1]+step:\n xl[0] -= step\n xl[1] += step\n\n yl[0] -= step\n yl[1] += step\n\n self.widget.im_widget.axes.set_xlim(xl)\n self.widget.im_widget.axes.set_ylim(yl)\n\n\n self.widget.im_widget.draw()\n\n self.update_lines()\n\n def box_zoom(self, x0, x1, y0, y1):\n if self.model.im is not None:\n self.widget.im_widget.axes.set_xlim([x0, x1])\n self.widget.im_widget.axes.set_ylim([y0, y1])\n self.widget.im_widget.draw()\n\n self.update_lines()\n\n def zoom_fill(self):\n if self.model.im is not None:\n self.widget.im_widget.axes.set_xlim([1, self.model.im.shape[1]])\n self.widget.im_widget.axes.set_ylim([1, self.model.im.shape[0]])\n self.update_lines()\n\n def close_event(self, ev):\n QApplication.closeAllWindows()\n ev.accept() \n\n\n\n","sub_path":"im_line/Controllers/Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":12119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61718762","text":"import datetime\nfrom time import ctime\nimport ntplib\nimport os\n\nservidor=\"time.windows.com\"\nt1=datetime.datetime.now()\ntry:\n t1=datetime.datetime.now()\n cliente_ntp=ntplib.NTPClient()\n respuesta=cliente_ntp.request(servidor)\n hora_actual = datetime.datetime.strptime(ctime(respuesta.tx_time), \"%a %b %d %H:%M:%S %Y\")\n t2=datetime.datetime.now()\n ajus=(t2-t1)/2\n hora_fin=hora_actual+ajus\n print(\"Hora inicial: \"+str(t1.time())+\"\\nHora de recepción: \"+str(t2.time()))\n print(\"Hora recibida: \"+str(hora_actual)+\"\\nAjuste: \"+str(ajus))\n print(\"Reloj: \"+str(hora_fin))\n os.system('date --set \"%s\"' %hora_fin)\nexcept:print(\"El servidor no estba disponible\")","sub_path":"Práctica 4.py","file_name":"Práctica 4.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"302830844","text":"\nimport inspect\n\nfrom functools import total_ordering\n\n\ndef infile_type(*types):\n def wrap(func):\n func.infile_type = set(types)\n return func\n return wrap\n\n\ndef outfile_type(*types):\n def wrap(func):\n func.outfile_type = set(types)\n return func\n return wrap\n\n\n@total_ordering\nclass EncoderFormatInfo:\n def __init__(self, quality, size):\n self.quality = quality\n self.size = size\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n def __lt__(self, other):\n return self.quality < other.quality\n\n\nclass RegisterMeta(type):\n def __new__(mcs, name, bases, attrs):\n new_class = super().__new__(mcs, name, bases, attrs)\n new_class.register(new_class)\n return new_class\n\n\nclass RegisterCls(metaclass=RegisterMeta):\n all = None\n\n @classmethod\n def register(cls, new_class):\n # don't register the base classes themselves, only child classes\n if 'all' in new_class.__dict__:\n return\n\n cls.do_register(new_class)\n\n @classmethod\n def do_register(cls, new_class):\n for c in cls.__mro__:\n if 'all' in c.__dict__ and isinstance(c.all, list):\n c.all.append(new_class)\n\n @classmethod\n def list(cls):\n return (c for c in cls.all if c.is_available())\n\n @staticmethod\n def is_available():\n return True\n\n\nclass EncoderBase:\n @classmethod\n def list(cls, format_):\n encoders = super().list()\n\n # sort the encoders by how well they support this format\n default = EncoderFormatInfo(quality=0, size=0)\n\n def keyfunc(encoder):\n formatinfo = getattr(encoder, cls.formatinfo)\n return formatinfo.get(format_, default)\n\n encoders = sorted(encoders, key=keyfunc, reverse=True)\n\n return encoders\n\n @staticmethod\n def calculate_formatinfo():\n \"\"\"\n Some encoders use other encoders. Their output quality thus depends on which other encoders are available.\n This function should be used to calculate the encoder's output quality based on which features are available.\n\n If the calculation results in a different-than-registered quality, this function should return True.\n\n :return: Whether the encoder's quality value or availability has changed\n \"\"\"\n return False\n\n @classmethod\n def finalize_formatinfo(cls):\n \"\"\"\n Some encoders use other encoders. Their output quality thus depends on which other encoders are available.\n This function calls each registered encoder's calculate_formatinfo() function until NONE of them return True.\n \"\"\"\n while True:\n repeat = False\n for encoder in cls.all:\n if encoder.calculate_formatinfo():\n repeat = True\n\n if not repeat:\n break\n\n @classmethod\n def best(cls, format_, key):\n encoders = cls.all\n\n default_info = EncoderFormatInfo(quality=0, size=0)\n format_infos = (getattr(enc, cls.formatinfo).get(format_, default_info) for enc in encoders)\n\n values = [getattr(info, key) for info in format_infos]\n\n if values:\n return max(values)\n return 0\n\n\nclass ImageEncoder(EncoderBase, RegisterCls):\n all = []\n formatinfo = 'encoder_info_static'\n\n @classmethod\n def save_static_image(cls, image, format_):\n \"\"\"\n Given an Image instance and a string representing the file format,\n encode the image in the given format.\n\n This function should raise UnsupportedFormat if it doesn't support the format.\n\n :param image: the Image instance to encode\n :param format_: the file format to encode as\n :return: a bytes object containing the encoded image data\n \"\"\"\n raise NotImplementedError(cls)\n\n\nclass AnimationEncoder(EncoderBase, RegisterCls):\n all = []\n formatinfo = 'encoder_info_animated'\n\n @classmethod\n def save_animation(cls, image, outfile, format_):\n \"\"\"\n Given an AnimatedImage instance and a string representing the file format,\n encode the image in the given format.\n\n This function should raise UnsupportedFormat if it doesn't support the format.\n\n :param image: the AnimatedImage instance to encode\n :param outfile: where to write the image to (a file-like object or file path)\n :param format_: the file format to encode as\n :return: a bytes object containing the encoded image data\n \"\"\"\n raise NotImplementedError(cls)\n\n\nclass AllEncoder(ImageEncoder, AnimationEncoder):\n all = None\n\n\nclass DecoderBase(RegisterCls):\n pass\n\n\nclass ImageDecoder(DecoderBase):\n all = []\n\n\nclass AnimationDecoder(DecoderBase):\n all = []\n \n @classmethod\n def load_animation(cls, image_cls, file_, format_=None,\n start_time=0, end_time=None,\n skip_frames=0, num_frames=None):\n \n # Not all decoders support all features. Those are arguments that the\n # decoder supports will be passed; the others will be emulated or, if\n # that's not possible, an exception will be thrown\n \n kwargs = {}\n sig = inspect.signature(cls._load_animation)\n \n for param, default in {'start_time': 0,\n 'end_time': None,\n 'skip_frames': 0,\n 'num_frames': None}.items():\n if param in sig.parameters:\n kwargs[param] = locals()[param]\n \n # now let the decoder do its work and then postprocess its output\n frames_itr = cls._load_animation(image_cls, file_,\n format_=format_,\n **kwargs)\n \n # skip the specified amount of time\n if 'start_time' not in kwargs and start_time > 0:\n total = 0\n for frame in frames_itr:\n total += frame.duration\n if total >= start_time:\n break\n \n # stop when we hit the end\n if 'end_time' not in kwargs and end_time is not None:\n def trim(itr, duration):\n total = 0\n for frame in itr:\n total += frame.duration\n if total >= duration:\n frame.duration -= total - duration\n yield frame\n break\n \n yield frame\n \n frames_itr = trim(frames_itr, end_time - start_time)\n \n # drop the specified number of frames\n if 'skip_frames' not in kwargs:\n for _ in zip(range(skip_frames), frames_itr):\n pass\n \n # yield the specified number of frames\n if 'num_frames' not in kwargs and num_frames is not None:\n frames_itr = (frame for _, frame in zip(range(num_frames), frames_itr))\n \n return frames_itr\n\n\nclass AllDecoder(ImageDecoder, AnimationDecoder):\n all = None\n\n\nclass EncoderPostprocessor(RegisterCls):\n all = []\n\n @classmethod\n def list(cls, format_):\n return super().list() # FIXME: filter by format\n","sub_path":"animation_editor/image_backends/encoders_decoders/encoder_decoder_base.py","file_name":"encoder_decoder_base.py","file_ext":"py","file_size_in_byte":7331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"259983316","text":"import logging\nimport json\nfrom osgeo import gdal\nfrom osgeo import ogr\n\ngdal.SetConfigOption(\"PG_LIST_ALL_TABLES\", \"YES\")\n\ndef get_pg_layers(connString):\n conn = ogr.Open(connString)\n layerList = []\n for i in conn:\n daLayer = i.GetName()\n if daLayer not in layerList:\n layerList.append(daLayer)\n\n layerList.sort()\n\n for j in layerList:\n print(j)\n conn.Destroy()\n\n return layerList\n\ndef GetPGLayerFieldTypes( lyr_name, connString ):\n conn = ogr.Open(connString)\n\n lyr = conn.GetLayer( lyr_name )\n if lyr is None:\n print(\"lyr is None\")\n\n lyrDefn = lyr.GetLayerDefn()\n for i in range( lyrDefn.GetFieldCount() ):\n fieldName = lyrDefn.GetFieldDefn(i).GetName()\n fieldTypeCode = lyrDefn.GetFieldDefn(i).GetType()\n fieldType = lyrDefn.GetFieldDefn(i).GetFieldTypeName(fieldTypeCode)\n fieldWidth = lyrDefn.GetFieldDefn(i).GetWidth()\n GetPrecision = lyrDefn.GetFieldDefn(i).GetPrecision()\n\n print(fieldName + \" - \" + fieldType+ \" \" + str(fieldWidth) + \" \" + str(GetPrecision))\n\n conn.Destroy()\n\n# Connect to postgreSQL database\nlogger = logging.getLogger('PostgreSQL to graph')\ncredential_file_path = '/Users/duccioa/CLOUD/01_Cloud/01_Work/04_Projects/0031_CrossMap/04_Admin/03_Credentials/crossmapDB_credentials.json'\nwith open(credential_file_path) as data_file:\n credential_json = json.load(data_file)\n\ncredentials = credential_json['crossmap_database_credentials']['localhost']\nhost = credentials['host']\nport = credentials['port']\ndatabase = credentials['database']\nuser = credentials['user']\npassword = credentials['password']\ndriver = credentials['driver']\nconnection_string = f\"PG: host={host} dbname={database} user={user} password={password}\"\n\nlayer_list = get_pg_layers(connection_string)\n\nGetPGLayerFieldTypes('paris.osm_line_idf_view', connection_string)\n\nconn = ogr.Open(connection_string)\nosm_line_view = conn['paris.osm_line_idf_view']\nschemas = osm_line_view.schema\ni=0\nfor schema in schemas:\n print(i, \": \", schema.GetName())\n i += 1\n\n# From connection to the database, extract a table\nx = conn.ExecuteSQL(\"SELECT * FROM paris.osm_line_idf_view where highway in ('residential', 'unclassified', 'tertiary', 'primary', 'secondary', 'steps', 'pedestrian', 'living_street', 'motorway', 'primary_link', 'trunk', 'secondary_link', 'road', 'contruction', 'tertiary_link')\")\n# Extract row 0 of the table\nfields = ['name', 'osm_id']\nf = x[0]\n\n\n\ngt = []\nfor i in range(0, 100):\n row = x[i]\n g = row.geometry()\n geom_type = g.GetGeometryType()\n print(f\"{i}:\\t{geom_type}\")\n gt.append(geom_type)\n\ngt.unique()\n\nrow = x[0]\nname = row['name']\nosm_id = row['osm_id']\ng = row.geometry()\n\nattrs = {\"name\":name, \"osm_id\":osm_id}\nedges = edges_from_line(g, attrs, simplify=False, geom_attrs=True, export_geom='Wkt')\nfor edge in edges:\n print(edge)","sub_path":"02_Code/Python/postgres2graph.py","file_name":"postgres2graph.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"651263453","text":"from socket import *\nimport sys\n\ntry:\n input = raw_input\nexcept:\n input = input\n\nip = \"\"\nif len(sys.argv) == 2:\n ip = sys.argv[1]\nelse:\n ip = input(\"Please input the target ip: \")\n\nPORT = 80\nMESSAGE = \"Hello\"\n\ns = socket(AF_INET, SOCK_DGRAM)\ns.sendto(MESSAGE, (ip, PORT))\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"18632423","text":"__author__ = 'RobertaBtt'\n\n\nclass PermMissingElem:\n\n def solution(A):\n\n n = len(A)+1\n result = n * (n + 1)//2\n\n return result - sum(A)\n\n\nprint(PermMissingElem.solution([1,2,3,5,6,7,8,4]))\n","sub_path":"src/Codility/CodilityPermMissingElem.py","file_name":"CodilityPermMissingElem.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"627874100","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n__author__ = \"Chen\"\n\"\"\"\n家庭收支調查-所得收入者職業別平均每人\"所得收入總計\" ↓ 2020-10-27\nhttps://data.gov.tw/dataset/131148\n家庭收支調查-所得收入者職業別平均每人\"非消費支出\" ↓ 2020-11-18\nhttps://data.gov.tw/dataset/132281\n家庭收支調查-所得收入者職業別平均每人\"可支配所得\" ↓ 2020-09-23\nhttps://data.gov.tw/dataset/130027\n主要欄位 ↓\nYear、臺灣地區、民意代表及主管及經理人員、專業人員、技術員及助理專業人員、\n事務支援人員、服務及銷售工作人員、農林漁牧業生產人員、技藝有關工作人員、\n機械設備操作及組裝人員、基層技術工及勞力工、其他\n\"\"\"\n\nimport sys\nfrom xml.etree import ElementTree\nimport urllib.request as httplib # 3.x\n\nimport pymysql as MySQLdb # pip install MySQLdb\ndb = MySQLdb.connect(host=\"127.0.0.1\", user=\"admin\", passwd=\"admin\", db=\"mydatabase\")\ncursor = db.cursor()\n\ntry:\n # 家庭收支調查 - 所得收入者職業別平均每人\"所得收入總計\" 最後更新時間 2020 - 10 - 27\n # url = \"https://www.dgbas.gov.tw/public/data/open/localstat/086-%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E8%80%85%E8%81%B7%E6%A5%AD%E5%88%A5%E5%B9%B3%E5%9D%87%E6%AF%8F%E4%BA%BA%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E7%B8%BD%E8%A8%88.xml\"\n # 非消費性支出\n # url =https://www.dgbas.gov.tw/public/data/open/localstat/088-%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E8%80%85%E8%81%B7%E6%A5%AD%E5%88%A5%E5%B9%B3%E5%9D%87%E6%AF%8F%E4%BA%BA%E9%9D%9E%E6%B6%88%E8%B2%BB%E6%94%AF%E5%87%BA.xml\n # 可支配所得\n url=\"https://www.dgbas.gov.tw/public/data/open/localstat/085-%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E8%80%85%E8%81%B7%E6%A5%AD%E5%88%A5%E5%B9%B3%E5%9D%87%E6%AF%8F%E4%BA%BA%E5%8F%AF%E6%94%AF%E9%85%8D%E6%89%80%E5%BE%97.xml\"\n req = httplib.Request(url)\n reponse = httplib.urlopen(req)\n if reponse.code == 200:\n if (sys.version_info > (3, 0)):\n # contents=reponse.read().decode(reponse.headers.get_content_charset())\n contents = reponse.read().decode(\"UTF-8\")\n else:\n contents = reponse.read()\n\n print(contents)\n root = ElementTree.fromstring(contents)\n\n t0 = root.findall(\"Data\")\n t1 = root.findall(\"Data/Year\")\n t2 = root.findall(\"Data/臺灣地區\")\n t3 = root.findall(\"Data/民意代表及主管及經理人員\")\n t4 = root.findall(\"Data/專業人員\")\n t5 = root.findall(\"Data/技術員及助理專業人員\")\n t6 = root.findall(\"Data/事務支援人員\")\n t7 = root.findall(\"Data/服務及銷售工作人員\")\n t8 = root.findall(\"Data/農林漁牧業生產人員\")\n t9 = root.findall(\"Data/技藝有關工作人員\")\n t10 = root.findall(\"Data/機械設備操作及組裝人員\")\n t11 = root.findall(\"Data/基層技術工及勞力工\")\n t12 = root.findall(\"Data/其他\")\n\n #listYear = []\n #for x in range(0, len(t0)):\n # listYear.append(t1[x].text)\n\n # 印出所有資料\n for x in range(0, len(t0)):\n print(\"年份:\", t1[x].text)\n print(\"台灣地區平均每人所得收入總計:\", t2[x].text)\n print(\" \")\n print(\"民意代表及主管及經理人員:\", t3[x].text)\n print(\"專業人員:\", t4[x].text)\n print(\"技術員及助理專業人員:\", t5[x].text)\n print(\"事務支援人員:\", t6[x].text)\n print(\"服務及銷售工作人員:\", t7[x].text)\n print(\"農林漁牧業生產人員:\", t8[x].text)\n print(\"技藝有關工作人員:\", t9[x].text)\n print(\"機械設備操作及組裝人員:\", t10[x].text)\n print(\"基層技術工及勞力工:\", t11[x].text)\n print(\"其他:\", t12[x].text)\n print(\"----------------------------\")\n print(\" \")\n\n for x in range(0,len(t0)):\n str1 = \"INSERT INTO `income` (`id`, `year`, `taiwan`, `supervisor`, `professionals`, `assistant`, `support`, `service`, `production`, `artisan`, `assembler`, `labor`, `other`)\" + \\\n \" VALUES ('[value-1]','[value-2]','[value-3]','[value-4]','[value-5]','[value-6]','[value-7]','[value-8]','[value-9]','[value-10]','[value-11]','[value-12]','[value-13]')\"\n str1 = str1.replace(\"[value-1]\", \"null\")\n str1 = str1.replace(\"[value-2]\", t1[x].text)\n str1 = str1.replace(\"[value-3]\", t2[x].text)\n str1 = str1.replace(\"[value-4]\", t3[x].text)\n str1 = str1.replace(\"[value-5]\", t4[x].text)\n str1 = str1.replace(\"[value-6]\", t5[x].text)\n str1 = str1.replace(\"[value-7]\", t6[x].text)\n str1 = str1.replace(\"[value-8]\", t7[x].text)\n str1 = str1.replace(\"[value-9]\", t8[x].text)\n str1 = str1.replace(\"[value-10]\", t9[x].text)\n str1 = str1.replace(\"[value-11]\", t10[x].text)\n str1 = str1.replace(\"[value-12]\", t11[x].text)\n str1 = str1.replace(\"[value-13]\", t12[x].text)\n # print(str1)\n cursor.execute(str1)\n\n db.commit()\n db.close()\n print(\"====資料量====\")\n print(len(t0))\nexcept:\n print(\"error\")\n","sub_path":"專03-MySQL/可支配所得/03-延續專2-可支配所得XML-匯入.py","file_name":"03-延續專2-可支配所得XML-匯入.py","file_ext":"py","file_size_in_byte":5306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"608744347","text":"# GROUP: local\n# CONDA: lofreq = 2.1.5\n\nimport subprocess\nfrom pathlib import Path\n\n\ndef main(fname_bam, fname_reference, fname_result, fname_result_haplos, dname_work):\n dname_work.mkdir(parents=True, exist_ok=True)\n subprocess.run(\n [\n \"lofreq\",\n \"call\",\n \"-f\",\n fname_reference.resolve(),\n \"-o\",\n fname_result.resolve(),\n fname_bam.resolve(),\n ],\n cwd=dname_work,\n check=True,\n )\n open(fname_result_haplos, \"a\").close()\n\n\nif __name__ == \"__main__\":\n main(\n Path(snakemake.input.fname_bam),\n Path(snakemake.input.fname_reference),\n Path(snakemake.output.fname_result),\n Path(snakemake.output.fname_result_haplos),\n Path(snakemake.output.dname_work),\n )\n","sub_path":"resources/auxiliary_workflows/benchmark/resources/method_definitions/lofreq_local_haplo.py","file_name":"lofreq_local_haplo.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"559435303","text":"startPhrase = \"This is \"\nverse = [\"the house that Jack built.\", \n \"the malt that lay in \", \n \"the rat that ate \", \n \"the cat that killed \", \n \"the dog that worried \", \n \"the cow with the crumpled horn that tossed \", \n \"the maiden all forlorn that milked \", \n \"the man all tattered and torn that kissed \", \n \"the priest all shaven and shorn that married \", \n \"the rooster that crowed in the morn that woke \", \n \"the farmer sowing his corn that kept \", \n \"the horse and the hound and the horn that belonged to \"]\n\ndef recite(start_verse, end_verse):\n output = []\n for i in range(start_verse-1, end_verse):\n temp = startPhrase + \"\".join(verse[i::-1])\n output.append(temp)\n return output \nprint(recite(1,12))","sub_path":"house/house.py","file_name":"house.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"549292666","text":"\nfrom zipfile import ZipFile\n\nfrom randomizer import VERSION\n\nbase_name = \"Wind Waker Randomizer \" + VERSION\nzip_name = base_name.replace(\" \", \"_\") + \".zip\"\n\nwith ZipFile(\"./dist/\" + zip_name, \"w\") as zip:\n zip.write(\"./dist/%s.exe\" % base_name, arcname=\"%s.exe\" % base_name)\n zip.write(\"README.txt\")\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"421405856","text":"from operator import itemgetter\r\n\r\nclass Language:\r\n def __init__(self, id_lan, l):\r\n self.id_lan = id_lan\r\n self.l = l\r\n\r\nclass Library:\r\n def __init__(self, id_det, name, soft_cost, id_lan):\r\n self.id_lan = id_lan\r\n self.id_det = id_det\r\n self.name = name\r\n self.soft_cost = soft_cost\r\n\r\nclass LibLan:\r\n def __init__(self, id_det, id_lan):\r\n self.id_det = id_det\r\n self.id_lan = id_lan\r\n\r\nlibs = [\r\n Library(1, 'Emoji', 500, 1),\r\n Library(2, 'Pandas', 700, 1),\r\n Library(3, 'Console Paint', 1000, 2),\r\n Library(11, 'GraphABC', 1500, 3),\r\n Library(22, 'Math', 1200, 4),\r\n Library(33, 'Guava', 2000, 5),\r\n]\r\nlangs = [\r\n Language(1, 'Python'),\r\n Language(2, 'C#'),\r\n Language(3, 'Pascal'),\r\n Language(4, 'AC++'),\r\n Language(5, 'Java'),\r\n]\r\ncross = [\r\n LibLan(1, 1),\r\n LibLan(2, 2),\r\n LibLan(3, 3),\r\n LibLan(3, 4),\r\n LibLan(3, 5),\r\n LibLan(11, 1),\r\n LibLan(22, 2),\r\n LibLan(33, 3),\r\n LibLan(33, 4),\r\n LibLan(33, 5),\r\n]\r\n\r\ndef main():\r\n \"\"\"Основная функция\"\"\"\r\n one_to_many = [(e.name, e.soft_cost, d.l)\r\n for d in langs\r\n for e in libs\r\n if e.id_lan == d.id_lan]\r\n\r\n many_to_many_temp = [(d.l, ed.id_lan, ed.id_det)\r\n for d in langs\r\n for ed in cross\r\n if d.id_lan == ed.id_lan]\r\n\r\n many_to_many = [(e.name, e.soft_cost, lang_name)\r\n for lang_name, id_lan, id_det in many_to_many_temp\r\n for e in libs if e.id_det == id_det]\r\n\r\n print('Задание №1')\r\n res1 = {}\r\n for d in langs:\r\n if d.l.lower().startswith('a'):\r\n d_emps = list(filter(lambda i: i[2] == d.l, one_to_many))\r\n d_emps_name = [x for x, _, _ in d_emps]\r\n res1[d.l] = d_emps_name\r\n print(res1)\r\n\r\n print('\\nЗадание №2')\r\n res_12_unsorted = []\r\n for d in langs:\r\n d_emps = list(filter(lambda i: i[2] == d.l, many_to_many))\r\n if len(d_emps) > 0:\r\n d_sals = [sal for _, sal, _ in d_emps]\r\n d_sals_max = max(d_sals)\r\n res_12_unsorted.append((d.l, d_sals_max))\r\n\r\n res_12 = sorted(res_12_unsorted, key=itemgetter(1), reverse=True)\r\n print(res_12)\r\n\r\n print('\\nЗадание №3')\r\n res_11 = sorted(many_to_many, key=itemgetter(2))\r\n print(res_11)\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"RK1/RK1.py","file_name":"RK1.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645055988","text":"\"\"\"\npygama's command line interface utilities.\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport sys\n\nimport numpy as np\n\nimport pygama\nimport pygama.logging\nfrom pygama.dsp import build_dsp\nfrom pygama.hit import build_hit\nfrom pygama.lgdo import show\nfrom pygama.raw import build_raw\n\n\ndef pygama_cli():\n \"\"\"pygama's command line interface.\n\n Defines the command line interface (CLI) of the package, which exposes some\n of the most used functions to the console. This function is added to the\n ``entry_points.console_scripts`` list and defines the ``pygama`` executable\n (see ``setuptools``' documentation). To learn more about the CLI, have a\n look at the help section:\n\n .. code-block:: console\n\n $ pygama --help\n $ pygama build-raw --help # help section for a specific sub-command\n \"\"\"\n\n parser = argparse.ArgumentParser(\n prog=\"pygama\", description=\"pygama's command-line interface\"\n )\n\n # global options\n parser.add_argument(\n \"--version\", action=\"store_true\", help=\"\"\"Print pygama version and exit\"\"\"\n )\n parser.add_argument(\n \"--verbose\",\n \"-v\",\n action=\"store_true\",\n help=\"\"\"Increase the program verbosity\"\"\",\n )\n parser.add_argument(\n \"--debug\",\n \"-d\",\n action=\"store_true\",\n help=\"\"\"Increase the program verbosity to maximum\"\"\",\n )\n\n subparsers = parser.add_subparsers()\n\n add_lh5ls_parser(subparsers)\n add_build_raw_parser(subparsers)\n add_build_dsp_parser(subparsers)\n add_build_hit_parser(subparsers)\n\n if len(sys.argv) < 2:\n parser.print_usage(sys.stderr)\n sys.exit(1)\n\n args = parser.parse_args()\n\n if args.verbose:\n pygama.logging.setup(logging.DEBUG)\n elif args.debug:\n pygama.logging.setup(logging.DEBUG, logging.root)\n else:\n pygama.logging.setup()\n\n if args.version:\n print(pygama.__version__) # noqa: T201\n sys.exit()\n\n args.func(args)\n\n\ndef add_lh5ls_parser(subparsers):\n \"\"\"Configure :func:`.lgdo.lh5_store.show` command line interface.\"\"\"\n\n parser_lh5ls = subparsers.add_parser(\n \"lh5ls\", description=\"\"\"Inspect LEGEND HDF5 (LH5) file contents\"\"\"\n )\n parser_lh5ls.add_argument(\n \"lh5_file\",\n help=\"\"\"Input LH5 file.\"\"\",\n )\n parser_lh5ls.add_argument(\n \"lh5_group\", nargs=\"?\", help=\"\"\"LH5 group.\"\"\", default=\"/\"\n )\n parser_lh5ls.set_defaults(func=lh5_show_cli)\n\n\ndef lh5_show_cli(args):\n \"\"\"Passes command line arguments to :func:`.lgdo.lh5_store.show`.\"\"\"\n\n show(args.lh5_file, args.lh5_group)\n\n\ndef add_build_raw_parser(subparsers):\n \"\"\"Configure :func:`.raw.build_raw.build_raw` command line interface\"\"\"\n\n parser_d2r = subparsers.add_parser(\n \"build-raw\", description=\"\"\"Convert data into LEGEND HDF5 (LH5) raw format\"\"\"\n )\n parser_d2r.add_argument(\n \"in_stream\",\n nargs=\"+\",\n help=\"\"\"Input stream. Can be a single file, a list of files or any\n other input type supported by the selected streamer\"\"\",\n )\n parser_d2r.add_argument(\n \"--stream-type\",\n \"-t\",\n help=\"\"\"Input stream type name. Use this if the stream type cannot be\n automatically deduced by pygama\"\"\",\n )\n parser_d2r.add_argument(\n \"--out-spec\",\n \"-o\",\n help=\"\"\"Specification for the output stream. HDF5 or JSON file name\"\"\",\n )\n parser_d2r.add_argument(\n \"--buffer_size\", \"-b\", type=int, default=8192, help=\"\"\"Set buffer size\"\"\"\n )\n parser_d2r.add_argument(\n \"--max-rows\",\n \"-n\",\n type=int,\n default=np.inf,\n help=\"\"\"Maximum number of rows of data to process from the input\n file\"\"\",\n )\n parser_d2r.add_argument(\n \"--overwrite\", \"-w\", action=\"store_true\", help=\"\"\"Overwrite output files\"\"\"\n )\n\n parser_d2r.set_defaults(func=build_raw_cli)\n\n\ndef build_raw_cli(args):\n \"\"\"Passes command line arguments to :func:`.raw.build_raw.build_raw`.\"\"\"\n\n for stream in args.in_stream:\n basename = os.path.splitext(os.path.basename(stream))[0]\n build_raw(\n stream,\n in_stream_type=args.stream_type,\n out_spec=args.out_spec,\n buffer_size=args.buffer_size,\n n_max=args.max_rows,\n overwrite=args.overwrite,\n orig_basename=basename,\n )\n\n\ndef add_build_dsp_parser(subparsers):\n \"\"\"Configure :func:`.dsp.build_dsp.build_dsp` command line interface\"\"\"\n\n parser_r2d = subparsers.add_parser(\n \"build-dsp\",\n description=\"\"\"Process LH5 raw files and produce a\n dsp file using a JSON configuration\"\"\",\n )\n parser_r2d.add_argument(\n \"raw_lh5_file\",\n nargs=\"+\",\n help=\"\"\"Input raw LH5 file. Can be a single file or a list of them\"\"\",\n )\n parser_r2d.add_argument(\n \"--config\",\n \"-c\",\n required=True,\n help=\"\"\"\"JSON file holding configuration of signal processing\n routines\"\"\",\n )\n parser_r2d.add_argument(\n \"--hdf5-groups\",\n \"-g\",\n nargs=\"*\",\n default=None,\n help=\"\"\"Name of group in the LH5 file. By default process all base\n groups. Supports wildcards\"\"\",\n )\n parser_r2d.add_argument(\n \"--output\",\n \"-o\",\n default=None,\n help=\"\"\"Name of output file, if only one is supplied. By default,\n output to _dsp.lh5\"\"\",\n )\n parser_r2d.add_argument(\n \"--database\",\n \"-d\",\n default=None,\n help=\"\"\"JSON file to read database parameters from. Should be nested\n dict with channel at the top level, and parameters below that\"\"\",\n )\n parser_r2d.add_argument(\n \"--output-pars\",\n \"-p\",\n nargs=\"*\",\n default=None,\n help=\"\"\"List of additional output DSP parameters written to file. By\n default use the \"outputs\" list defined in in the JSON\n configuration file\"\"\",\n )\n parser_r2d.add_argument(\n \"--max-rows\",\n \"-n\",\n default=None,\n type=int,\n help=\"\"\"Number of rows to process. By default do the whole file\"\"\",\n )\n parser_r2d.add_argument(\n \"--block\",\n \"-b\",\n default=16,\n type=int,\n help=\"\"\"Number of waveforms to process simultaneously. Default is\n 16\"\"\",\n )\n parser_r2d.add_argument(\n \"--chunk\",\n \"-k\",\n default=3200,\n type=int,\n help=\"\"\"Number of waveforms to read from disk at a time. Default is\n 3200\"\"\",\n )\n\n group = parser_r2d.add_mutually_exclusive_group()\n group.add_argument(\n \"--overwrite\",\n \"-w\",\n action=\"store_const\",\n const=\"r\",\n dest=\"writemode\",\n default=\"r\",\n help=\"\"\"Overwrite file if it already exists. Default option\"\"\",\n )\n group.add_argument(\n \"--update\",\n \"-u\",\n action=\"store_const\",\n const=\"u\",\n dest=\"writemode\",\n help=\"\"\"Update existing file with new values. Useful with the --output-pars\n option\"\"\",\n )\n group.add_argument(\n \"--append\",\n \"-a\",\n action=\"store_const\",\n const=\"a\",\n dest=\"writemode\",\n help=\"\"\"Append values to existing file\"\"\",\n )\n\n parser_r2d.set_defaults(func=build_dsp_cli)\n\n\ndef build_dsp_cli(args):\n \"\"\"Passes command line arguments to :func:`.dsp.build_dsp.build_dsp`.\"\"\"\n\n if len(args.raw_lh5_file) > 1 and args.output is not None:\n raise NotImplementedError(\"not possible to set multiple output file names yet\")\n\n out_files = []\n if len(args.raw_lh5_file) == 1:\n if args.output is None:\n basename = os.path.splitext(os.path.basename(args.raw_lh5_file[0]))[0]\n basename = basename.removesuffix(\"_raw\")\n out_files.append(f\"{basename}_dsp.lh5\")\n else:\n out_files.append(args.output)\n else:\n for file in args.raw_lh5_file:\n basename = os.path.splitext(os.path.basename(file))[0]\n basename = basename.removesuffix(\"_raw\")\n out_files.append(f\"{basename}_dsp.lh5\")\n\n for i in range(len(args.raw_lh5_file)):\n build_dsp(\n args.raw_lh5_file[i],\n out_files[i],\n args.config,\n lh5_tables=args.hdf5_groups,\n database=args.database,\n outputs=args.output_pars,\n n_max=args.max_rows,\n write_mode=args.writemode,\n buffer_len=args.chunk,\n block_width=args.block,\n )\n\n\ndef add_build_hit_parser(subparsers):\n \"\"\"Configure :func:`.hit.build_hit.build_hit` command line interface\"\"\"\n\n parser_r2d = subparsers.add_parser(\n \"build-hit\",\n description=\"\"\"Process LH5 dsp files and produce a hit file using a\n JSON configuration\"\"\",\n )\n parser_r2d.add_argument(\n \"dsp_lh5_file\",\n nargs=\"+\",\n help=\"\"\"Input dsp LH5 file. Can be a single file or a list of them\"\"\",\n )\n parser_r2d.add_argument(\n \"--config\",\n \"-c\",\n required=True,\n help=\"\"\"\"JSON file holding configuration of column operations on DSP output\"\"\",\n )\n parser_r2d.add_argument(\n \"--hdf5-groups\",\n \"-g\",\n nargs=\"*\",\n default=None,\n help=\"\"\"Name of group in the LH5 file. By default process all base\n groups. Supports wildcards\"\"\",\n )\n parser_r2d.add_argument(\n \"--output\",\n \"-o\",\n default=None,\n help=\"\"\"Name of output file, if only one is supplied. By default,\n output to _hit.lh5\"\"\",\n )\n parser_r2d.add_argument(\n \"--max-rows\",\n \"-n\",\n default=None,\n type=int,\n help=\"\"\"Number of rows to process. By default do the whole file\"\"\",\n )\n parser_r2d.add_argument(\n \"--chunk\",\n \"-k\",\n default=3200,\n type=int,\n help=\"\"\"Number of waveforms to read from disk at a time. Default is\n 3200\"\"\",\n )\n\n group = parser_r2d.add_mutually_exclusive_group()\n group.add_argument(\n \"--overwrite\",\n \"-w\",\n action=\"store_const\",\n const=\"of\",\n dest=\"writemode\",\n default=\"w\",\n help=\"\"\"Overwrite file if it already exists. Default option\"\"\",\n )\n group.add_argument(\n \"--update\",\n \"-u\",\n action=\"store_const\",\n const=\"u\",\n dest=\"writemode\",\n help=\"\"\"Update existing file with new values\"\"\",\n )\n group.add_argument(\n \"--append\",\n \"-a\",\n action=\"store_const\",\n const=\"a\",\n dest=\"writemode\",\n help=\"\"\"Append values to existing file\"\"\",\n )\n\n parser_r2d.set_defaults(func=build_hit_cli)\n\n\ndef build_hit_cli(args):\n \"\"\"Passes command line arguments to :func:`.hit.build_hit.build_hit`.\"\"\"\n\n if len(args.dsp_lh5_file) > 1 and args.output is not None:\n raise NotImplementedError(\"not possible to set multiple output file names yet\")\n\n out_files = []\n if len(args.dsp_lh5_file) == 1:\n if args.output is None:\n basename = os.path.splitext(os.path.basename(args.dsp_lh5_file[0]))[0]\n basename = basename.removesuffix(\"_dsp\")\n out_files.append(f\"{basename}_hit.lh5\")\n else:\n out_files.append(args.output)\n else:\n for file in args.dsp_lh5_file:\n basename = os.path.splitext(os.path.basename(file))[0]\n basename = basename.removesuffix(\"_dsp\")\n out_files.append(f\"{basename}_hit.lh5\")\n\n for i in range(len(args.dsp_lh5_file)):\n build_hit(\n args.dsp_lh5_file[i],\n args.config,\n outfile=out_files[i],\n lh5_tables=args.hdf5_groups,\n n_max=args.max_rows,\n wo_mode=args.writemode,\n buffer_len=args.chunk,\n )\n","sub_path":"src/pygama/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":12003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"398508036","text":"#import libraries\nimport pandas as pd\nfrom link import lnk\nimport IPython.core.display as d\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nfrom pandas import datetime\nfrom datetime import date, timedelta\nimport numpy as np\nimport sys\nsys.path.append('/home/gfield/notebooks')\nimport utility_bg as utility_custom\nfrom csv import DictReader\nfrom sys import argv,exit\n\n# \n\nlookback = 1\nday = datetime.today() - timedelta(days=lookback)\nstart_date = str(day.strftime('%Y-%m-%d'))\nyesterday_str = str(start_date) + ' 00:00:00'\ntoday = datetime.today()\ntoday_str = str(datetime.today().strftime('%Y-%m-%d'))\ntoday_str = \"'\"+today_str+\"'\"\nyear_start_str = \"\"\"'2016-01-01'\"\"\"\n# \n\napiMYSQL = lnk.dbs.mprod_api\nVQ = lnk.dbs.vertica\n\nfilename = sys.argv[1]\nf = open(filename, 'r')\nmember_ids = f.read()\n\n# \n\nmonthly_query = \"\"\"SELECT year(ymdh),month(ymdh),\nbuyer_member_id as xaxis_seat_id,\ncount(distinct advertiser_id) as count_advertisers,\ncount(distinct insertion_order_id) as count_insertion_orders,\ncount(distinct campaign_group_id) as count_line_items,\ncount(distinct campaign_id) as count_campaigns,\nsum(imps) as imps,sum(clicks) as clicks,sum(media_cost_dollars) as media_cost_dollars \nfrom agg_dw_advertiser_publisher_analytics_adjusted where \nbuyer_member_id in (\"\"\"+member_ids+\"\"\") and\nimp_type in (5,7) and ymd>=\"\"\"+year_start_str+\"\"\" and ymd<\"\"\"+today_str+\"\"\" group by 1,2,3 order by 1,2,3;\"\"\"\nvolumes = VQ.select_dataframe(monthly_query)\n\nmember_name_query = \"\"\"SELECT id,billing_name as seat_name from api.member WHERE id IN (\"\"\"+member_ids+\"\"\");\"\"\"\nmember_names = apiMYSQL.select_dataframe(member_name_query)\n\nmerged = volumes.merge(member_names, left_on='xaxis_seat_id', right_on='id')\nmerged = merged[['year', 'month', 'xaxis_seat_id', 'seat_name', 'count_advertisers','count_insertion_orders','count_line_items','count_campaigns', 'imps', 'clicks', 'media_cost_dollars']]\n\n\nfrom datetime import datetime\nusername= 'gfield'\nsave_loc = \"/home/%s/public\" % username\nday = datetime.today()\ndate = str(day.strftime('%Y_%m_%d'))\nfile_name = \"Xaxis_Global_Monthly_Volume%s.csv\"%(date)\nsave_file_location = \"%s/Xaxis_Global_Monthly_Volume_%s.csv\"%(save_loc,date)\nmerged.to_csv(save_file_location,index=False)\n\n# \n\ncss = \"\"\"\n\"\"\"\n\n# \n\nimport os\nimport sys\nsys.path.append('/home/gfield/public/')\n\n# \n\nhtml_doc = css + \"

See attached for Xaxis Global Monthly Volume

\"\nhtml_doc = html_doc.encode(\"utf-8\", 'replace')\nutility_custom.send_email(['gfield@appnexus.com','asanders@appnexus.com','mhealey@appnexus.com','nvages@appnexus.com'],'Xaxis Global Monthly Volume',html_doc,'Xaxis Global Monthly Volume ',smtpserver=\"mail.adnxs.net\",cc_addr_list=None,attachments=[save_file_location])","sub_path":"monthly_volumes.py","file_name":"monthly_volumes.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"617174900","text":"import sys\nimport math\n\n\ndef from_geo_to_radians(lat, lon):\n lat_deg = float(lat[1:3]) + float(lat[3:5])/60 + float(lat[5:])/3600\n lat_r = lat_deg * math.pi/180\n if lat[0] == 'S': lat_r *= -1\n lon_deg = float(lon[1:4]) + float(lon[4:6])/60 + float(lon[6:])/3600\n lon_r = lon_deg * math.pi/180\n if lon[0] == 'W': lon_r *= -1\n return [lat_r, lon_r]\n\n\ndef distance(loc1, loc2):\n dphi = (loc1[0] - loc2[0])/2\n dlambda = (loc1[1] - loc2[1])/2\n a = math.sin(dphi)**2\n a += math.cos(loc1[0]) * math.cos(loc2[0]) * math.sin(dlambda)**2\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n dist = int(math.floor(6371 * c + 0.5))\n return dist\n\n\nn = int(input()) # number of capitals\nm = int(input()) # number of geolocations for which to find the closest capital\n\npositionOf, capitalOf, messageOf = {}, [], {}\nfor i in range(n):\n cd = input().split()\n capitalOf.append(cd[0])\n positionOf[cd[0]] = from_geo_to_radians(cd[1], cd[2])\nfor i in range(n):\n messageOf[capitalOf[i]] = input()\nfor i in range(m):\n geoloc = input().split()\n location = from_geo_to_radians(geoloc[0], geoloc[1])\n near_capitals, min_dist = [], 45000\n for j in range(n):\n d = distance(location, positionOf[capitalOf[j]])\n if d == min_dist:\n near_capitals.append(capitalOf[j])\n elif d < min_dist:\n near_capitals = [capitalOf[j]]\n min_dist = d\n\n nclose, ans = len(near_capitals), \"\"\n for i in range(nclose-1):\n ans += messageOf[near_capitals[i]] + \" \"\n ans += messageOf[near_capitals[nclose-1]]\n print(ans)\n","sub_path":"practice/puzzles/easy/Hello, World!.py","file_name":"Hello, World!.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"592964332","text":"# -*- coding: UTF-8 -*-\n# Copyright 2015 Luc Saffre\n# License: BSD (see file COPYING for details)\n\"\"\"Database models for :mod:`lino_noi.modlib.contacts`.\n\n\"\"\"\n\nfrom lino.api import dd, _\n\nfrom lino_xl.lib.contacts.models import *\n\n\nclass CompanyDetail(CompanyDetail):\n main = \"general tickets\"\n\n general = dd.Panel(\"\"\"\n address_box:60 contact_box:30\n bottom_box\n \"\"\", label=_(\"General\"))\n\n tickets = dd.Panel(\"\"\"\n tickets.ProjectsByCompany topics.InterestsByPartner\n \"\"\", label=_(\"Tickets\"))\n\n\n# @dd.receiver(dd.post_analyze)\n# def my_details(sender, **kw):\n# contacts = sender.models.contacts\n# contacts.Companies.set_detail_layout(contacts.CompanyDetail())\n\nCompanies.set_detail_layout(CompanyDetail())\n","sub_path":"lino_noi/lib/contacts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"36511207","text":"from studentDb.admin import Admin\nfrom studentDb.createDb import create_table_students\nfrom studentDb.user import User\n\nif __name__ == '__main__':\n db_name = 'students_db'\n # create_table_students(db_name)\n\n admin = Admin(db_name)\n # admin.add_student('faculty1', 'group1', 1)\n # admin.change_student_by_ticket_number('marks', 5, 1)\n # admin.add_student('faculty2', 'group2', 2)\n # admin.change_student_by_ticket_number('marks', 2, 2)\n user = User(db_name)\n print(f'Excellent students list {user.get_excellent_students_list()}')\n print(f'All students list {user.get_all_students_list()}')\n print(f'Student by number {user.get_student_by_ticket_number(2)}')\n\n","sub_path":"studentDb/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"164761610","text":"# File: Deal.py\n\n# Description:\n\n# Student Name: Logan Hashmi\n\n# Student UT EID:Sah4334\n\n# Course Name: CS 303E\n\n# Unique Number: 51850\n\n# Date Created:2-24-17\n\n# Date Last Modified: 2-24-27\n\ndef deal():\n import random\n round = int(input(\"Enter the number of rounds you want to play: \"))\n switch= 0\n print()\n print(\" Prize Guess View New Guess\")\n for i in range(1,round+1):\n prize_door= random.randint(1,3)\n guess= random.randint(1,3)\n view=0\n\n if (prize_door==1 and guess==2) or (prize_door==2 and guess==1):\n view=3\n elif (prize_door==3 and guess==1) or (prize_door==1 and guess==3):\n view=2\n elif (prize_door==2 and guess==3) or (prize_door==3 and guess==2):\n view=1\n elif (prize_door==1 and guess==1):\n view=3\n elif (prize_door==2 and guess==2):\n view=1\n elif (prize_door==3 and guess==3):\n view=2\n\n newGuess=0\n\n for i in range(1,4):\n if i!=guess and i!=view:\n newGuess=i\n\n if newGuess==prize_door:\n switch+=1\n\n print(\" \",prize_door,\" \",guess,\" \",view,\" \", newGuess)\n\n print()\n probability_of_switch = switch / round\n probability_of_not_switch = 1 - probability_of_switch\n\n print(\"Probability of winning if you switch = \",\"%.2f\"%probability_of_switch)\n print(\"Probability of winning if you do not switch = \",\"%.2f\"%probability_of_not_switch)\n\ndeal()\n","sub_path":"Deal.py","file_name":"Deal.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"459299048","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\nimport re\n\nfrom nambatest.items import legalEntity\nfrom scrapy.selector import Selector\nfrom scrapy.http import HtmlResponse \n\nrow = 0\n\nclass TestSpider(scrapy.Spider):\n\n name = \"test\"\n\n firstResult = 0\n number = 0\n domain = 'http://register.minjust.gov.kg/register/SearchAction.seam?firstResult=%s&number=%s&tin=&fullnameRu=&logic=and&okpo=&cid=1616977'\n mainDomain = 'http://register.minjust.gov.kg/register/SearchAction.seam?firstResult=%s&number=%s&tin=&fullnameRu=&logic=and&okpo=&cid=1616977' % (str(firstResult), str(number))\n\n allowed_domains = [\"register.minjust.gov.kg\"]\n start_urls = (\n mainDomain, \n )\n\n def parse(self, response):\n global row\n for x in range(1):\n url = 'http://register.minjust.gov.kg' + first(Selector(response = response).xpath(\"///a[@id='searchActionForm:searchAction:%s:j_id109']/@href\" % str(row)).extract())\n \n if len(url) == 0:\n break\n else:\n row += 1\n req = scrapy.Request(url, callback = self.parse_doc)\n yield req\n\n def parse_doc(self, response):\n item = legalEntity()\n item['linkTo'] = response.url\n item['fullNameKg'] = first(response.xpath('//div[@id=\\'j_id22_header\\']/text()').extract())\n item['fullNameRu'] = first(response.xpath('//*[@id=\"j_id22_body\"]/table').extract())\n item['shortNameKg'] = first(response.xpath('//*[@id=\"j_id22_body\"]/table/tbody').extract())\n yield item\n\ndef first(input):\n if len(input) > 0:\n return input[0]\n else:\n return 'nothing'\n","sub_path":"nambaspider.py","file_name":"nambaspider.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"373829887","text":"import requests\r\nimport json\r\nfrom time import sleep\r\nimport sqlite3\r\n\r\n\r\n\r\nTOKEN = \"\"\r\nURL = \"https://api.telegram.org/bot{}/\".format(TOKEN)\r\nPROVIDER_TOKEN = \"\"\r\n\r\npizza = []\r\n\r\ndrink = []\r\n\r\ndessert = []\r\n\r\npizza_base = []\r\n\r\npizza_extra_cheese = []\r\n\r\nTime = 0\r\n\r\ntotal = 0 \r\n\r\nName = ''\r\n \r\nclass FoodProducts:\r\n \r\n def __init__(self, price, time, name):\r\n \r\n self.time = time\r\n self.price = price\r\n self.name = name\r\n\r\n# Pizzas\r\np1 = FoodProducts(10,5,\"Pizza A\")\r\np2 = FoodProducts(20,10,\"Pizza B\")\r\np3 = FoodProducts(30,15,\"Pizza C\")\r\n\r\n#Drinks\r\nd1 = FoodProducts(5,5,\"Drink A\")\r\nd2 = FoodProducts(10,10,\"Drink B\")\r\nd3 = FoodProducts(15,15,\"Drink C\")\r\n\r\n#Dessert\r\nde1 = FoodProducts(20,5,\"Dessert A\")\r\nde2 = FoodProducts(20,5,\"Dessert B\")\r\nde3 = FoodProducts(20,5,\"Dessert C\")\r\n\r\n \r\n\r\ndef get_url(url):\r\n response = requests.get(url)\r\n content = response.content.decode(\"utf8\")\r\n return content\r\n\r\ndef get_json_from_url(url):\r\n content = get_url(url)\r\n js = json.loads(content)\r\n return js\r\n\r\ndef get_updates(offset=None):\r\n url = URL+\"getUpdates?timeout=100\"\r\n if(offset):\r\n url += \"&offset={}\".format(offset)\r\n js = get_json_from_url(url)\r\n return js\r\n\r\ndef get_last_update_id(updates):\r\n update_ids = []\r\n for update in updates[\"result\"]:\r\n update_ids.append(int(update[\"update_id\"]))\r\n return max(update_ids)\r\n\r\ndef get_last_chat_id_and_text(updates):\r\n num_updates = len(updates[\"result\"])\r\n if(len(updates)>0):\r\n last_update = num_updates - 1\r\n text = updates[\"result\"][last_update][\"message\"][\"text\"]\r\n name= updates[\"result\"][last_update][\"message\"][\"from\"][\"first_name\"]\r\n chat_id = updates[\"result\"][last_update][\"message\"][\"chat\"][\"id\"]\r\n print(text)\r\n return (text,name, chat_id)\r\n\r\ndef send_message(chat_id,text,reply_markup=None):\r\n url = URL+ \"sendMessage?text={}&chat_id={}&parse_mode=Markdown\".format(text,chat_id)\r\n if reply_markup:\r\n url += '&reply_markup={}'.format(reply_markup)\r\n res = requests.get(url)\r\n while res.status_code !=200:\r\n res = requests.get(url)\r\n\r\ndef reply_markup_maker(data):\r\n keyboard = []\r\n for i in range(0,len(data),2):\r\n key =[]\r\n key.append(data[i].title())\r\n try:\r\n key.append(data[i+1].title())\r\n except:\r\n pass\r\n keyboard.append(key)\r\n\r\n reply_markup = {\"keyboard\":keyboard, \"one_time_keyboard\": True}\r\n return json.dumps(reply_markup)\r\n\r\ndef start():\r\n Total = 0\r\n time = 0\r\n last_update_id = get_last_update_id(get_updates())\r\n text, name, chat = get_last_chat_id_and_text(get_updates(last_update_id))\r\n if(text==\"/start\" or text==\"/start foo\"):\r\n send_message(chat,\"Welcome to Happy Pizza 🍕, {}\".format(name))\r\n send_message(chat,\"Thank you for making the choice to interact with Happy Pizza 🍕\")\r\n options = [\"Place an Order\", \"Leave a Comment\", \"Lodge a Complaint\", \"Display Special Offers\", \"Check Out/ Exit\"]\r\n send_message(chat,\"What would you like to do?\",reply_markup_maker(options))\r\n text, name, chat = get_last_chat_id_and_text(get_updates(last_update_id))\r\n while(text == \"/start\"):\r\n text, name, chat = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n\t\t\r\n if(text == \"Place An Order\"):\r\n place_order(chat,Total,time, last_update_id)\r\n\r\n if(text ==\"Leave A Comment\"):\r\n leave_comment(chat, text, last_update_id)\r\n\r\n if(text == \"Lodge A Complaint\"):\r\n lodge_complaint(chat, text, last_update_id)\r\n\r\n if(text == \"Check Out/ Exit\"):\r\n check_out_or_exit(chat, Total, time)\r\n\r\n if(text == \"Display Special Offers\"):\r\n display_promotions(chat)\r\n\r\ndef place_order(chat_id, Total, time, last_update_id):\r\n text = \"Yes\"\r\n t=\"Place An Order\"\r\n while(text==\"Yes\"):\r\n options = [\"Pizzas\", \"Drinks\", \"Desserts\"]\r\n send_message(chat_id,\"What would you like to have?\",reply_markup_maker(options))\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n global Name\r\n Name = name\r\n while(text == \"Place An Order\" or t==\"Place An Order\" or text==\"Yes\"):\r\n t=\"randomdata\"\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n \r\n \r\n if(text==\"Pizzas\"):\r\n send_message(chat_id, \"Your total bill amount till now is: SAR {}\".format(Total))\r\n pizzas = [p1, p2, p3]\r\n options = [p1.name, p2.name, p3.name]\r\n send_message(chat_id,\"Which pizza would you like to have?\",reply_markup_maker(options))\r\n while(text == \"Pizzas\"):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n for p in pizzas:\r\n if(text == p.name):\r\n Total += p.price\r\n time += p.time \r\n pizza.append(p.name)\r\n options=[\"Thin base\", \"Thick base\"] \r\n send_message(chat_id,\"Which pizza base would you like to have?\",reply_markup_maker(options))\r\n while(text == p.name):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n base = text\r\n pizza_base.append(base)\r\n options = [\"Extra Cheese\",\"No Extra Cheese\"]\r\n send_message(chat_id,\"Would you like Extra Cheese?\",reply_markup_maker(options))\r\n while(text == base):\r\n text, name, chat = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n extra_cheese = text\r\n pizza_extra_cheese.append(extra_cheese)\r\n send_message(chat_id, \"Your total bill amount till now is: ${}\".format(Total))\r\n options = [\"YES\", \"NO\"]\r\n send_message(chat_id,\"Do you want to continue ordering items? \",reply_markup_maker(options))\r\n while(text == extra_cheese):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n if(text==\"No\"):\r\n check_out_or_exit(chat_id, Total, time)\r\n\r\n if(text==\"Drinks\"):\r\n send_message(chat_id, \"Your total bill amount till now is: ${}\".format(Total))\r\n drinks = [d1, d2, d3]\r\n options = [d1.name, d2.name, d3.name]\r\n send_message(chat_id,\"Which drink would you like to have?\",reply_markup_maker(options))\r\n while(text == \"Drinks\"):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n for d in drinks:\r\n if(text == d.name):\r\n drink_name = text\r\n Total += d.price\r\n time += d.time \r\n drink.append(drink_name)\r\n send_message(chat_id, \"Your total bill amount till now is: ${}\".format(Total))\r\n options = [\"YES\", \"NO\"]\r\n send_message(chat_id,\"Do you want to continue ordering items? \",reply_markup_maker(options))\r\n while(text == drink_name):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n if(text==\"No\"):\r\n check_out_or_exit(chat_id, Total, time)\r\n\r\n if(text == \"Desserts\"):\r\n send_message(chat_id, \"Your total bill amount till now is: SAR {}\".format(Total))\r\n desserts = [de1, de2, de3]\r\n options = [de1.name, de2.name, de3.name]\r\n send_message(chat_id,\"Which dessert would you like to have?\",reply_markup_maker(options))\r\n while(text == \"Desserts\"):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n for de in desserts:\r\n if(text == de.name):\r\n dessert_name = de.name\r\n Total += de.price\r\n time += de.time \r\n dessert.append(dessert_name)\r\n send_message(chat_id, \"Your total bill amount till now is: SAR {}\".format(Total))\r\n options = [\"Yes\", \"No\"]\r\n send_message(chat_id,\"Do you want to continue ordering items? \",reply_markup_maker(options))\r\n while(text == dessert_name):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n if(text==\"No\"):\r\n check_out_or_exit(chat_id, Total, time)\r\n global Time\r\n Time = time\r\n global total \r\n total = Total\r\n print(\"Total is: {} ,{} and time is {}, {}\".format(Time,time,total,Total))\r\n if(text==\"Yes\"):\r\n t = \"Place An Order\" \r\n\r\nprint (pizza,pizza_base,pizza_extra_cheese,drink,dessert,total,Time,Name) \r\n\r\ndef leave_comment(chat_id, text, last_update_id):\r\n send_message(chat_id,\"Please enter your comments below.\")\r\n while(text == \"Leave A Comment\"):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n\t\t\r\n send_message(chat_id,\"Thank you for your valid input\")\r\n sleep(0.5)\r\n \r\n \r\ndef lodge_complaint(chat_id, text, last_update_id):\r\n send_message(chat_id,\"Please lodge your complaint below.\")\r\n while(text == \"Lodge A Complaint\"):\r\n text, name, chat_id = get_last_chat_id_and_text(get_updates(last_update_id))\r\n sleep(0.5)\r\n send_message(chat_id,\"Thank you for your valued input. Your complaint will be escalated to management as soon as possible.\")\r\n\r\ndef check_out_or_exit(chat_id, Total, time):\r\n print(Total)\r\n if(Total>0):\r\n check_out(chat_id, Total, time)\r\n else:\r\n exit_from_bot(chat_id, Total, time)\r\n \r\n\r\ndef write_to_database(total, time):\r\n \r\n pizza_str = \",\".join(pizza)\r\n pizza_base_str = \",\".join(pizza_base)\r\n pizza_extra_cheese_str = \",\".join(pizza_extra_cheese)\r\n drink_str = \",\".join(drink)\r\n dessert_str = \",\".join(dessert)\r\n \r\n global Name\r\n\r\n conn = sqlite3.connect('database.db')\r\n print(\"Opened database successfully\")\r\n\r\n format_str = \"\"\"INSERT INTO DATABASE (NAME,PIZZA,BASE,EXTRA_CHEESE,DRINKS,DESSERTS,BILL_AMOUNT,TIME) \r\n VALUES (\"{Name}\", \"{pizza_str}\", \"{pizza_base_str}\", \"{pizza_extra_cheese_str}\", \"{drink_str}\",\"{dessert_str}\",\"{total}\",\"{time}\");\"\"\"\r\n sql_command = format_str.format(Name=Name,pizza_str=pizza_str,pizza_base_str=pizza_base_str,pizza_extra_cheese_str=pizza_extra_cheese_str,drink_str=drink_str,dessert_str=dessert_str,total=total,time=time)\r\n conn.execute(sql_command)\r\n\r\n conn.commit()\r\n conn.close()\r\n\r\n\r\ndef check_out(chat_id, Total, time):\r\n \r\n url = URL + 'sendInvoice?chat_id='+str(chat_id)+'&title=Your Order&description=Invoice&payload={}&provider_token='+PROVIDER_TOKEN+'&start_parameter=foo¤cy=SAR&prices=[{\"label\":\"Invoice\",\"amount\":'+str(Total*100)+'}]&photo_url=https://bit.ly/2CzDhaC'\r\n\r\n response = requests.get(url)\r\n\r\n print(response)\r\n\r\n send_message(chat_id,\"Estimated time for preparation: {} minutes\".format(time))\r\n \r\n exit_from_bot(chat_id, Total, time)\r\n \r\n\r\ndef exit_from_bot(chat_id, Total, time):\r\n \r\n if(Total>0):\r\n send_message(chat_id,\"Thank you for your order, hope you had a good experience :).\")\r\n write_to_database(Total, time)\r\n else:\r\n send_message(chat_id,\"Thank you for your visit, hope you had a good experience :).\")\r\n\r\ndef display_promotions(chat_id):\r\n \r\n send_message(chat_id,\"Sorry, no special offers as of now. Do visit back later for more offers.\")\r\n\r\n\r\nwhile(True):\r\n \r\n start()\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"telegram_bot.py","file_name":"telegram_bot.py","file_ext":"py","file_size_in_byte":12114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"164106758","text":"from socket import gethostbyname_ex\n\n# Validates a ip and returns true if is valid\ndef validateip(s):\n a = s.split('.')\n if len(a) != 4:\n return False\n for x in a:\n if not x.isdigit():\n return False\n i = int(x)\n if i < 0 or i > 255:\n return False\n return True\n\n# Will resolve a domain and check if its ip is valid\ndef resolveip(ip, *, returnlist=False):\n\n if not ip[0].isdigit():\n try:\n ip = gethostbyname_ex(ip)[2][0]\n except:\n print('\\'{}\\' is not a valid domain'.format(ip))\n return\n\n if not validateip(ip):\n print('\\'{}\\' is not a valid ip'.format(ip))\n return\n\n if returnresult:\n if returnlist:\n return(ip.split('.'))\n else:\n return(ip)\n\n return","sub_path":"resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"274513108","text":"from flask import Flask, render_template, request, jsonify\r\nimport crypto\r\nimport realtime\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/showprice', methods=['GET', 'POST'])\r\ndef realtimeprice():\r\n user_input = (request.form.get('coincode'))\r\n if user_input:\r\n print(user_input)\r\n else:\r\n print(\"error\")\r\n response = jsonify({\r\n 'rtprice': crypto.real_time_predict(user_input)\r\n })\r\n response.headers.add('Access-Control-Allow-Origin', '*')\r\n return response\r\n\r\n\r\n@app.route('/realtimers', methods=['GET', 'POST'])\r\ndef home2():\r\n user_input = (request.form.get('coincode'))\r\n if user_input:\r\n print(user_input)\r\n else:\r\n print(\"error\")\r\n response = jsonify({\r\n 'rtprice': realtime.price(user_input+'-USD')\r\n })\r\n response.headers.add('Access-Control-Allow-Origin', '*')\r\n return response\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","sub_path":"project/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"307334036","text":"import pdb\nimport json\nimport re\nusers=[]\nfile = open('data.txt')\nif(file.readline()!=\"\"):\n with open('data.txt') as json_file:\n data = json.load(json_file)\n for p in data:\n for key in p:\n users.append({\n key: p[key], \n })\n \n\ndef userInput(): \n print(\"Введите email\")\n email=input()\n regex = '^[a-z0-9]+[\\._]?[a-z0-9]+[@][\\w\\.]+[.]\\w{2,3}$'\n while not re.search(regex,email):\n print(\"Некорректный email\")\n email=input()\n print(\"Введите ФИО\")\n question=input()\n if question==\"\":\n print(\"Вы не ввели имя \")\n question=input()\n users.append({\n email: question,\n })\n\nprint(\"Ввод пользователей\")\nuserInput()\nwith open('data.txt', 'w') as outfile:\n json.dump(users, outfile)\n\n\nwith open('data.txt') as json_file:\n data = json.load(json_file)\n for p in data:\n for key in p:\n print(key+\" : \"+p[key]) \n\n","sub_path":"source/repos/PythonApplication2/PythonApplication2/PythonApplication2.py","file_name":"PythonApplication2.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"332893960","text":"from datetime import datetime\nfrom flask import redirect, render_template\nfrom models.MenuItem import MenuItem\nfrom models.Restaurant import Restaurant\n\ndef index(date_string=None):\n\n DATE_FORMAT = '%Y-%m-%d'\n\n if date_string == None:\n return redirect(\"/\" + datetime.today().strftime(DATE_FORMAT))\n\n date = datetime.strptime(date_string, DATE_FORMAT)\n query = (MenuItem.query\n .filter_by(date=date)\n .join(Restaurant, MenuItem.restaurant)\n .order_by(Restaurant.name)\n )\n return render_template('index.html', items = query.all(), date = date)\n","sub_path":"views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"42754881","text":"import numpy as np\n\n\nclass SarsaAgent(object):\n def __init__(self,\n obs_n,\n act_n,\n learning_rate=0.01,\n gamma=0.9,\n e_greed=0.1):\n self.act_n = act_n # 动作维度\n self.lr = learning_rate # 学习率\n self.gamma = gamma # reward 的衰减率\n self.epsilon = e_greed # 按一定的概率随机选动作\n self.Q = np.zeros((obs_n, act_n))\n\n # 根据输入观察值,采样输出的动作值,带探索\n def sample(self, obs):\n if np.random.uniform(0, 1) < (1.0 - self.epsilon): # 根据table的Q值选动作\n action = self.predict(obs)\n else:\n action = np.random.choice(self.act_n) # 有一定概率随机探索选取一个动作\n return action\n\n # 根据输入观察值,预测输出的动作\n def predict(self, obs):\n Q_list = self.Q[obs, :]\n maxQ = np.max(Q_list)\n action_list = np.where(Q_list == maxQ)[0] # maxQ 可能对应多个action\n action = np.random.choice(action_list)\n return action\n\n def learn(self, obs, action, reward, next_obs, next_action, done):\n '''\n on-policy\n obs: 交互前的obs,s_t\n action: 本次交互选择的action,a_t\n reward: 本次动作获得的奖励\n next_obs: 本次交互后的obs,s_t+1\n next_action: 根据当前Q表格,针对next_obs 会选择的动作a_t+1\n done: episode 是否结束\n '''\n predict_Q = self.Q[obs, action]\n if done:\n target_Q = reward # 没有下一个状态了\n else:\n target_Q = reward + self.gamma * self.Q[next_obs, next_action] # Sarsa\n self.Q[obs, action] += self.lr * (target_Q - predict_Q) # 修正Q\n\n def save(self):\n npy_file = './Q_tabel.npy'\n np.save(npy_file, self.Q)\n print(npy_file + ' saved')\n\n def restore(self, npy_file='./q_table.npy'):\n self.Q = np.load(npy_file)\n print(npy_file + ' loaded')\n","sub_path":"baiduAI/ReinforceLearning/lesson2/sarsa/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"378073806","text":"# -*- coding: utf-8 -*-\n#############################################################################\n### COMPUTES RAY PATHS AND TRAVEL TIMES FOR DIFFERENT BODY PHASES ##########\n#############################################################################\n\n\n### Importing various python libraries\n# numpy is a useful toolkit for scientific computations\nimport numpy as np\n# matplotlib is a plotting toolkit\nimport matplotlib.pyplot as plt\n# from matplotlib.gridspec import GridSpec\n\n# Obspy is a seismic toolkit\n# import obspy\n# from obspy.taup import TauPyModel\n# from obspy.taup import plot_travel_times\n# from obspy.taup import plot_ray_paths\n\nimport matplotlib\nfrom matplotlib import transforms as tf\nfrom IPython.display import HTML, Image\nmatplotlib.rc('animation', html='html5')\n\n# velocity model as a function of depth.\n# model = TauPyModel(model='ak135')\n\n########################## SET PARAMETERS HERE #############################\n\n# Set epicentral distance from Earthquake to Station - use station longitude to increase this 0-180 allowed\nepi_dist = 60\n\n# Angular anticlockwise rotation of earthquake and rest of plot from North\ntheta_earthquake = -30\n\n# depth of earthquake in km\ndepth_earthquake = 0\n\nradius = 6371 # radius of Earth in km\n\nfig = plt.figure(figsize =(16,10))\nst = fig.suptitle(\"Inside the Deep Earth\", fontsize=20)\n\n################ First plot the model in the background. #################\n\n# #create axes in the background to show cartesian image\nax0 = fig.add_subplot(121, label=\"Background Figure\")\nim='../../wavefront_movie_home_screen/Model_graphics_vector_final_V2.png'\nbackground_figure = plt.imread(im)\n# ax0 = plt.subplot2grid((10, 16), (1, 1), colspan=6, rowspan=7)\n# ax0.set_facecolor('none')\nax0.imshow(background_figure, alpha=0.5)\nax0.axis(\"off\")\n\n##########################################################################\n\n# define polar subplot\n# ax1 = plt.subplot2grid((10, 16), (1, 1), colspan=6, rowspan=7, polar=True)\nax1 = fig.add_subplot(121, polar=True, label=\"Polar axes\", alpha=0.5)\nax1.set_theta_zero_location('N', offset=theta_earthquake)\nax1.set_facecolor('none')\nax1.set_theta_direction(-1)\nax1.set_xticks([])\nax1.set_yticks([])\n\n\n# add discontinuities\ndiscons = np.array([ 0. , 35. , 210. , 2891.5, 5153.5, 6371. ])\n# ax.set_yticks(radius - discons)\n# ax.xaxis.set_major_formatter(plt.NullFormatter())\n# ax.yaxis.set_major_formatter(plt.NullFormatter())\n\n#\n# # Fill in Earth colors:\n# theta = np.arange(0, 2, (1./6000))*np.pi\n#\n# discons_plot=np.full((len(theta),len(discons)),radius-discons)\n#\n# # Lith:\n# plt.fill_between(theta, discons_plot[:,0],discons_plot[:,2], color=matplotlib.colors.to_hex((.4, .35, .34)), alpha=0.4, lw=0)\n# # Mantle\n# plt.fill_between(theta, discons_plot[:,2],discons_plot[:,3], color=matplotlib.colors.to_hex((.64, .11, .12)), alpha=0.4, lw=0)\n# # Outer core:\n# plt.fill_between(theta, discons_plot[:,3],discons_plot[:,4], color=matplotlib.colors.to_hex((.91, .49, .27)), alpha=0.4, lw=0)\n# # Inner core:\n# plt.fill_between(theta, discons_plot[:,4],discons_plot[:,5], color=matplotlib.colors.to_hex((.96, .91, .56)), alpha=0.4, lw=0)\n#\n\n# Pretty earthquake marker.\neq_symbol, = ax1.plot([0], [radius - depth_earthquake],\n marker=\"*\", color=\"#FEF215\", markersize=20, zorder=10,\n markeredgewidth=1.5, markeredgecolor=\"0.3\",\n clip_on=False)\n\n# Label Earthquake\nplt.annotate(\"Earthquake!\", # this is the text\n (0, radius - depth_earthquake), # this is the point to label\n textcoords=\"offset points\", # how to position the text\n xytext=(-10,10), # distance from text to points (x,y)\n ha='right',\n fontsize=12) # horizontal alignment can be left, right or center\n\n\n# Add seismometer location\nseismom_symbol, = ax1.plot([epi_dist*np.pi/180], [radius+400],\n marker=(3, 0, (60-epi_dist+theta_earthquake)), color='r', markersize=15, zorder=10,\n markeredgewidth=1.5, markeredgecolor=\"0.3\",\n clip_on=False)\n\n# Label Seismometer\nplt.annotate(\"Seismometer\", # this is the text\n (epi_dist*np.pi/180, radius), # this is the point to label\n textcoords=\"offset points\", # how to position the text\n xytext=(10,-10), # distance from text to points (x,y)\n ha='left',\n # rotation=(-epi_dist),\n fontsize=12) # horizontal alignment can be left, right or center\n\n\nax1.set_rmax(radius)\nax1.set_rmin(0.0)\n\nTW_duration=300 # Sesimogram window length (s)\ntick_pointer_width=20 # drawing tick length (s)\n\nax2 = fig.add_subplot(122, label=\"Seismograph\")\n# ax2 = plt.subplot2grid((10, 16), (1, 9), colspan=8, rowspan=7)\nax2.title.set_size(16)\nax2.title.set_text('Seismograph')\ntime = np.arange(0, TW_duration, 1);\n\nt_after_eq=time[0]\n\namplitude = np.exp(-time/100) * np.sin(time/TW_duration/np.pi*180)\nax2.plot(time, amplitude,'r-', linewidth=1)\n\nmax_amp = np.ceil(np.max(amplitude))\nmin_amp = np.floor(np.min(amplitude))\n\nplt.gca().set_xlim([-tick_pointer_width,TW_duration])\nplt.gca().set_ylim([min_amp,max_amp])\n\n# \"Drawing tick\" goes from left side of page up until 1s before start.\ntick_x=[-tick_pointer_width, -1]\ntick_y=[amplitude[0],amplitude[0]]\n\nplt.yticks([]) # Hides y-axis labels\n# plt.xticks([]) # Hides x-axis labels\n\n# plt.xticks(time[0::60], [int(i) for i in time[0::60]/60 ] )\n# plt.xlabel('Time before present (min)', fontsize=10)\n\n\nax2.plot(tick_x ,tick_y,'b-', linewidth=2) \n\n# Puts triangle at end of drawing tick\nax2.plot(-5, amplitude[0], marker=(3, 0, (-90)), color='b', markersize=10, zorder=10,\n markeredgewidth=0.5, markeredgecolor=\"0.3\", clip_on=False)\n \nax2.text(TW_duration-(TW_duration/40), max_amp-0.05, 'Time after Earthquake: '+str(t_after_eq)+'s', ha=\"right\", va=\"top\",\n fontsize=12, color='black', bbox=dict(facecolor='white', edgecolor='grey', pad=5.0))\n\nwait_rem=3\nwait_point='.'\nwaiting=wait_rem*wait_point\n\n# # Adds label for waiting arriving earthquakes waves....\nax2.text(0, min_amp+0.05, 'Earthquake waves arriving '+str(waiting), ha=\"left\", va=\"bottom\",\n fontsize=12, color='black')\n \n \n# # Place white space padding around the plots\n# # Axes to add labels below plot #2\n# ax2b = plt.subplot2grid((10, 16), (8, 9), colspan=8, rowspan=2)\n# ax2b.set_facecolor('red')\n# ax2b.set_xticks([])\n# ax2b.set_yticks([])\n# # ax2b.axis(\"off\")\n\n# plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.3, hspace=1)\n# plt.tight_layout()\n\nplt.show()\n\n\n\n\n","sub_path":"wavefront_movie/Testing_Scripts/OLD/test_plotting_rountine.py","file_name":"test_plotting_rountine.py","file_ext":"py","file_size_in_byte":6835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"600275975","text":"\"\"\"\nImport IPEDS Custom Reports.\n\nUsage:\n ./import_customreport ...\n\"\"\"\nfrom collections import namedtuple\nimport logging\nimport os\nimport sys\n\nfrom tx_highered.ipeds_csv_reader import IpedsCSVReader\nfrom tx_highered.models import (\n Institution, Admissions, PriceTrends, TestScores, Enrollment,\n GraduationRates,\n)\n\n\n# This tells the importer how to interpret IPEDS short variables for import\n# into a Django model and field\nReportDatum = namedtuple('ReportDatum', ['model', 'field', 'year_type'])\nFIELD_MAPPINGS = {\n 'ADMSSN': ReportDatum(Admissions, 'number_admitted', 'fall'),\n 'APPLCN': ReportDatum(Admissions, 'number_of_applicants', 'fall'),\n 'ENRLT': ReportDatum(Admissions, 'number_admitted_who_enrolled', 'fall'),\n # Price Trends\n 'chg2ay3': ReportDatum(PriceTrends, 'tuition_fees_in_state', 'fall'),\n 'chg3ay3': ReportDatum(PriceTrends, 'tuition_fees_outof_state', 'fall'),\n 'chg4ay3': ReportDatum(PriceTrends, 'books_and_supplies', 'fall'),\n 'chg5ay3': ReportDatum(PriceTrends, 'room_and_board_on_campus', 'fall'),\n\n # Test Scores\n 'SATNUM': ReportDatum(TestScores, 'sat_submitted_number', 'fall'),\n 'SATPCT': ReportDatum(TestScores, 'sat_submitted_percent', 'fall'),\n 'ACTNUM': ReportDatum(TestScores, 'act_submitted_number', 'fall'),\n 'ACTPCT': ReportDatum(TestScores, 'act_submitted_percent', 'fall'),\n 'SATVR25': ReportDatum(TestScores, 'sat_verbal_25th_percentile', 'fall'),\n 'SATVR75': ReportDatum(TestScores, 'sat_verbal_75th_percentile', 'fall'),\n 'SATMT25': ReportDatum(TestScores, 'sat_math_25th_percentile', 'fall'),\n 'SATMT75': ReportDatum(TestScores, 'sat_math_75th_percentile', 'fall'),\n 'SATWR25': ReportDatum(TestScores, 'sat_writing_25th_percentile', 'fall'),\n 'SATWR75': ReportDatum(TestScores, 'sat_writing_75th_percentile', 'fall'),\n 'ACTCM25': ReportDatum(TestScores, 'act_composite_25th_percentile', 'fall'),\n 'ACTCM75': ReportDatum(TestScores, 'act_composite_75th_percentile', 'fall'),\n 'ACTEN25': ReportDatum(TestScores, 'act_english_25th_percentile', 'fall'),\n 'ACTEN75': ReportDatum(TestScores, 'act_english_75th_percentile', 'fall'),\n 'ACTMT25': ReportDatum(TestScores, 'act_math_25th_percentile', 'fall'),\n 'ACTMT75': ReportDatum(TestScores, 'act_math_75th_percentile', 'fall'),\n 'ACTWR25': ReportDatum(TestScores, 'act_writing_25th_percentile', 'fall'),\n 'ACTWR75': ReportDatum(TestScores, 'act_writing_75th_percentile', 'fall'),\n\n # Enrollment\n 'PctEnrWh': ReportDatum(Enrollment, 'total_percent_white', 'fall'),\n 'PctEnrBK': ReportDatum(Enrollment, 'total_percent_black', 'fall'),\n 'PctEnrHS': ReportDatum(Enrollment, 'total_percent_hispanic', 'fall'),\n 'PctEnrAP': ReportDatum(Enrollment, 'total_percent_asian', 'fall'),\n 'PctEnrAN': ReportDatum(Enrollment, 'total_percent_native', 'fall'),\n 'PctEnrUn': ReportDatum(Enrollment, 'total_percent_unknown', 'fall'),\n 'ENRTOT': ReportDatum(Enrollment, 'total', 'fall'),\n 'FTE': ReportDatum(Enrollment, 'fulltime_equivalent', 'fall'),\n 'EnrFt': ReportDatum(Enrollment, 'fulltime', 'fall'),\n 'EnrPt': ReportDatum(Enrollment, 'parttime', 'fall'),\n\n # GraduationRates\n 'GBA4RTT': ReportDatum(GraduationRates, 'bachelor_4yr', 'aug'),\n 'GBA5RTT': ReportDatum(GraduationRates, 'bachelor_5yr', 'aug'),\n 'GBA6RTT': ReportDatum(GraduationRates, 'bachelor_6yr', 'aug'),\n}\n\n\ndef generic(path):\n \"\"\"Read the CSV and import into the appropriate model.\"\"\"\n logger = logging.getLogger(__name__)\n reader = IpedsCSVReader(open(path, 'rb'))\n for row in reader:\n unit_id, ipeds_id = row[0]\n assert unit_id == 'UnitID'\n try:\n institution = Institution.objects.get(ipeds_id=ipeds_id)\n except Institution.MultipleObjectsReturned:\n logger.critical('DUPLICATE IPEDS: {}'.format(ipeds_id))\n sys.exit()\n except Institution.DoesNotExist:\n # TODO echo the name too\n logger.error('MISSING Institution: {}'.format(ipeds_id))\n continue\n for key, value in row[2:]:\n logger.debug(u'{} {}'.format(key, value))\n if key is None or value is '':\n # skip cells with no data, CSVs will give empty strings for\n # missing values\n continue\n try:\n finder = FIELD_MAPPINGS[key.short_name]\n except KeyError:\n logger.error('MISSING: cannot interpret {}'\n .format(key.short_name))\n continue\n defaults = {\n finder.field: value,\n 'year_type': finder.year_type,\n }\n logging_state = 'CREATED'\n instance, created = finder.model.objects.get_or_create(\n institution=institution, year=key.year,\n defaults=defaults)\n if not created:\n if unicode(getattr(instance, finder.field)) != value:\n logging_state = 'UPDATED'\n instance.__dict__.update(defaults)\n instance.save()\n else:\n logging_state = 'SKIP'\n logger.info(u'{} {} {}'\n .format(instance, key.short_name, logging_state))\n\n\nif __name__ == '__main__':\n for path in sys.argv[1:]:\n if os.path.isfile(path):\n generic(path)\n","sub_path":"tx_highered/scripts/import_customreport.py","file_name":"import_customreport.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"307326095","text":"import cv2\n\ncap = cv2.VideoCapture('../inputs/ebu7240_hand.mp4')\n\nimg_array = []\n\nif (cap.isOpened() == False):\n print(\"Error opening video stream or file\")\n\n#--------------------------------- WRITE YOUR CODE HERE ---------------------------------#\n\nframe_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nfor a in range(0, frame_num):\n ret, frame = cap.read()\n img_array.append(frame)\nfor b in range(len(img_array)):\n if b < 30:\n continue\n elif b >= 30 and b < 50:\n for m in range(0, width):\n for n in range(0, height):\n img_array[b].itemset((n, m, 0), 0)\n img_array[b].itemset((n, m, 1), 0)\n elif b >= 50 and b < 70:\n for m in range(0, width):\n for n in range(0, height):\n img_array[b].itemset((n, m, 0), 0)\n img_array[b].itemset((n, m, 2), 0)\n else:\n for m in range(0, width):\n for n in range(0, height):\n img_array[b].itemset((n, m, 1), 0)\n img_array[b].itemset((n, m, 2), 0)\n# video_capture = cv2.VideoCapture('../inputs/name_QMnumber.mp4')\n# if (video_capture.isOpened() == False):\n# print(\"Error opening video stream or file\")\n# width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))\n# height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\n# fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n# out = cv2.VideoWriter('../inputs/ebu7240_hand.mp4', fourcc, 30, (360, 640))\n# for i in range(0, 90):\n# ret, frame = video_capture.read()\n# frame1 = cv2.resize(frame, (360, 640), interpolation=cv2.INTER_LINEAR)\n# out.write(frame1)\n# out.release()\n\n# cap = cv2.VideoCapture('../inputs/ebu7240_hand.mp4')\n# width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n# height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n# fps = int(cap.get(cv2.CAP_PROP_FPS))\n# frame_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n# print(width, height, fps, frame_num)\n\n##########################################################################################\n\nout = cv2.VideoWriter('../results/ex1_a_hand_rgbtest.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 30, (360, 640))\nfor i in range(len(img_array)):\n out.write(img_array[i])\nout.release()\n\n# cv2.imshow('frame', img_array[89])\n# cv2.waitKey(0)\n\n\n\n","sub_path":"ex1a.py","file_name":"ex1a.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"428906695","text":"import os\n\nimport tuneuptechnology\n\nAPI_EMAIL = os.getenv('API_EMAIL')\nAPI_KEY = os.getenv('API_KEY')\n\ncustomer = tuneuptechnology.Customer.retrieve(\n data={\n 'auth': API_EMAIL,\n 'api_key': API_KEY,\n 'id': 23 # the ID of the customer you are retrieving\n }\n)\n\ntuneuptechnology.Util.pretty_print(customer)\n","sub_path":"examples/retrieve_customer.py","file_name":"retrieve_customer.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"462462055","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom os import system\n\ncmd = system\n\nmax = int(raw_input(':'))\nx = 1\nwhile True:\n if x < 10:\n cmd('mv 0%d.jpg 0%d.png' % (x, x))\n else:\n cmd('mv %d.jpg %d.png' % (x, x))\n x += 1\n if x == max:\n break\n","sub_path":"chname.py","file_name":"chname.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"254794966","text":"from GenericRequest import GenericRequest\r\nfrom kol.manager import PatternManager\r\n\r\nclass ClanRosterRequest(GenericRequest):\r\n \r\n def __init__(self, session):\r\n super(ClanRosterRequest, self).__init__(session)\r\n self.url = session.serverURL + 'clan_whitelist.php'\r\n \r\n def parseResponse(self):\r\n members = []\r\n whitelistMemberPattern = PatternManager.getOrCompilePattern('whitelistMember')\r\n reponse = self.responseText \r\n snippedResponse = reponse[0:reponse.find(\"People Not In Your Clan\")]\r\n for match in whitelistMemberPattern.finditer(snippedResponse):\r\n member = {}\r\n member[\"id\"] = match.group(1)\r\n member[\"name\"] = match.group(2)\r\n member[\"rank\"] = match.group(3)\r\n members.append(member)\r\n if len(members) > 0:\r\n self.responseData[\"members\"] = members","sub_path":"src/kol/request/ClanRosterRequest.py","file_name":"ClanRosterRequest.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268456271","text":"import os\nfrom subprocess import PIPE, Popen\n\n\ndef popen_wrapper(args):\n \"\"\"\n Friendly wrapper around Popen.\n\n Returns stdout output, stderr output and OS status code.\n \"\"\"\n p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE,\n close_fds=os.name != 'nt', universal_newlines=True)\n output, errors = p.communicate()\n return output, errors, p.returncode\n\ndef handle_extensions(extensions=('html',), ignored=('py',)):\n \"\"\"\n Organizes multiple extensions that are separated with commas or passed by\n using --extension/-e multiple times. Note that the .py extension is ignored\n here because of the way non-*.py files are handled in make_messages() (they\n are copied to file.ext.py files to trick xgettext to parse them as Python\n files).\n\n For example: running 'django-admin makemessages -e js,txt -e xhtml -a'\n would result in an extension list: ['.js', '.txt', '.xhtml']\n\n >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py'])\n set(['.html', '.js'])\n >>> handle_extensions(['.html, txt,.tpl'])\n set(['.html', '.tpl', '.txt'])\n \"\"\"\n ext_list = []\n for ext in extensions:\n ext_list.extend(ext.replace(' ', '').split(','))\n for i, ext in enumerate(ext_list):\n if not ext.startswith('.'):\n ext_list[i] = '.%s' % ext_list[i]\n return set([x for x in ext_list if x.strip('.') not in ignored])\n","sub_path":"django/core/management/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193655934","text":"#!/bin/python3\n\nimport collections\nfrom collections import deque\nimport copy\n\ndef word_ladder(start_word, end_word, dictionary_file='words5.dict'):\n\n if start_word == end_word:\n wordsout = [start_word]\n return wordsout \n dict1 = open(dictionary_file,'r')\n wordList = [line[0:5] for line in dict1.readlines()]\n \n wordsout = [] \n wordsout.append(start_word) \n que = deque() \n que.append(wordsout) \n while len(que) > 0: \n theobject = que.popleft() \n for i in set(wordList): \n if _adjacent(theobject[len(theobject)-1], i): \n if i == end_word:\n anotherobject = theobject \n anotherobject.append(i)\n return(anotherobject)\n break \n someobject = copy.deepcopy(theobject) \n someobject.append(i) \n que.append(someobject) \n wordList.remove(i) \n \n \n \n '''\n Returns a list satisfying the following properties:\n\n 1. the first element is `start_word`\n 2. the last element is `end_word`\n 3. elements at index i and i+1 are `_adjacent`\n 4. all elements are entries in the `dictionary_file` file\n\n For example, running the command\n ```\n word_ladder('stone','money')\n ```\n may give the output\n ```\n ['stone', 'shone', 'phone', 'phony', 'peony', 'penny', 'benny', 'bonny', 'boney', 'money']\n ```\n but the possible outputs are not unique,\n so you may also get the output\n ```\n ['stone', 'shone', 'shote', 'shots', 'soots', 'hoots', 'hooty', 'hooey', 'honey', 'money']\n ```\n (We cannot use doctests here because the outputs are not unique.)\n\n Whenever it is impossible to generate a word ladder between the two words,\n the function returns `None`.\n '''\n \n\n\ndef verify_word_ladder(ladder): #worked with friends on this function\n \n if len(ladder) == 0:\n return False \n '''\n Returns True if each entry of the input list is adjacent to its neighbors;\n otherwise returns False.\n '''\n i = 0\n while i < len(ladder)-1:\n if _adjacent(ladder[i], ladder[i+1]) == True:\n i+=1 \n else:\n \n return False\n \n return True\n \n\n\ndef _adjacent(word1, word2):\n count = 0\n length1 = len(word1)\n length2 = len(word2)\n\n if word1 == word2:\n return False\n\n if length1 == length2:\n for x,y in zip(word1, word2):\n if x != y:\n count += 1\n if (count ==1):\n return True\n\n else:\n return False\n\n","sub_path":"tests/word_ladder.py","file_name":"word_ladder.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"91409000","text":"import collections\n\nFile = collections.namedtuple('File', ['name', 'directory_id', 'block', 'size'])\n\ndef _File_get_directory_id(path):\n directory = path[:path.rfind('/')]\n try:\n directory_id = File.directory_ids[directory]\n except:\n directory_id = len(File.directories)\n File.directory_ids[directory] = directory_id\n File.directories.append(directory)\n\n return directory_id\n\ndef _File_get_basename(path):\n return path[path.rfind('/') + 1:]\n\ndef _File_create(path, block, size):\n return File(File.get_basename(path), File.get_directory_id(path), block, size)\n\ndef _File_fullpath(self):\n return File.directories[self.directory_id] + '/' + self.name\n\ndef _File_clone(self, **kwd):\n if 'path' in kwd:\n path = kwd['path']\n name = File.get_basename(path)\n directory_id = File.get_directory_id(path)\n else:\n name = self.name\n directory_id = self.directory_id\n\n return File(\n name,\n directory_id,\n self.block if 'block' not in kwd else kwd['block'],\n self.size if 'size' not in kwd else kwd['size']\n )\n\nFile.directories = []\nFile.directory_ids = {}\nFile.get_directory_id = staticmethod(_File_get_directory_id)\nFile.get_basename = staticmethod(_File_get_basename)\nFile.create = staticmethod(_File_create)\nFile.fullpath = _File_fullpath\nFile.clone = _File_clone\n\n","sub_path":"lib/common/dataformat/lfile.py","file_name":"lfile.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"296384243","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 15 14:55:55 2018\r\n\r\n@author: manoj\r\n\"\"\"\r\n\r\nfrom matplotlib import pyplot as plt\r\nimport argparse\r\nimport cv2\r\n\r\nap =argparse.ArgumentParser(\"Description:\")\r\nap.add_argument(\"-i\",\"--image\", required = True, help =\"Path to the image\")\r\nb = vars(ap.parse_args())\r\n\r\nimage = cv2.imread(b[\"image\"])\r\ncv2.imshow(\"original\", image)\r\ncv2.waitKey(0)\r\n\r\nnew = cv2.calcHist([image],[0],None,[256],[0,256])\r\nplt.figure()\r\nplt.title(\"Grascale_Histogram\")\r\nplt.xlabel(\"Bins\")\r\nplt.ylabel(\"Number of Pixels\")\r\nplt.plot(new)\r\nplt.xlim([0,255])\r\nplt.show()\r\ncv2.waitKey(0)","sub_path":"Gray_histogram.py","file_name":"Gray_histogram.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"653921495","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# github: https://github.com/houm01\n\nfrom make_db_file import LoadDbase, storeDbase\n\n\ndb = LoadDbase()\nfor key in db:\n print(key, '=>\\n ', db[key])\nprint(db['sue']['name'])\n","sub_path":"Programming Python/chapter 1 /dump_db_file.py","file_name":"dump_db_file.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107575030","text":"\"\"\"Extracts features for different models.\"\"\"\nimport functools\nimport tensorflow as tf\n\nimport xception\nslim = tf.contrib.slim\n\n\n# A map from network name to network function.\nnetworks_map = {\n 'xception_65': xception.xception_65,\n}\n\n# A map from network name to network arg scope.\narg_scopes_map = {\n 'xception_65': xception.xception_arg_scope,\n}\n\n# Names for end point features.\nDECODER_END_POINTS = 'decoder_end_points'\n\n# A dictionary from network name to a map of end point features.\nnetworks_to_feature_maps = {\n 'xception_65': {\n DECODER_END_POINTS: [\n 'entry_flow/block2/unit_1/xception_module/'\n 'separable_conv2_pointwise',\n ],\n }\n}\n\n# A map from feature extractor name to the network name scope used in the\n# ImageNet pretrained versions of these models.\nname_scope = {\n 'xception_65': 'xception_65',\n}\n\ndef extract_features(images,\n output_stride=8,\n multi_grid=None,\n depth_multiplier=1.0,\n final_endpoint=None,\n model_variant=None,\n weight_decay=0.0001,\n reuse=None,\n is_training=False,\n fine_tune_batch_norm=False,\n regularize_depthwise=False,\n num_classes=None,\n global_pool=False):\n \"\"\"Extracts features by the particular model_variant.\n\n Args:\n images: A tensor of size [batch, height, width, channels].\n output_stride: The ratio of input to output spatial resolution.\n multi_grid: Employ a hierarchy of different atrous rates within network.\n depth_multiplier: Float multiplier for the depth (number of channels)\n for all convolution ops used in MobileNet.\n final_endpoint: The MobileNet endpoint to construct the network up to.\n model_variant: Model variant for feature extraction.\n weight_decay: The weight decay for model variables.\n reuse: Reuse the model variables or not.\n is_training: Is training or not.\n fine_tune_batch_norm: Fine-tune the batch norm parameters or not.\n regularize_depthwise: Whether or not apply L2-norm regularization on the\n depthwise convolution weights.\n num_classes: Number of classes for image classification task. Defaults\n to None for dense prediction tasks.\n global_pool: Global pooling for image classification task. Defaults to\n False, since dense prediction tasks do not use this.\n\n Returns:\n features: A tensor of size [batch, feature_height, feature_width,\n feature_channels], where feature_height/feature_width are determined\n by the images height/width and output_stride.\n end_points: A dictionary from components of the network to the corresponding\n activation.\n\n Raises:\n ValueError: Unrecognized model variant.\n \"\"\"\n if 'xception' in model_variant:\n arg_scope = arg_scopes_map[model_variant](\n weight_decay=weight_decay,\n batch_norm_decay=0.9997,\n batch_norm_epsilon=1e-3,\n batch_norm_scale=True,\n regularize_depthwise=regularize_depthwise)\n features, end_points = get_network(\n model_variant, arg_scope)(\n inputs=images,\n num_classes=num_classes,\n is_training=(is_training and fine_tune_batch_norm),\n global_pool=global_pool,\n output_stride=output_stride,\n regularize_depthwise=regularize_depthwise,\n multi_grid=multi_grid,\n reuse=reuse,\n scope=name_scope[model_variant])\n else:\n raise ValueError('Unknown model variant %s.' % model_variant)\n\n return features, end_points\n\n\ndef get_network(network_name, arg_scope=None):\n \"\"\"Gets the network.\n\n Args:\n network_name: Network name.\n arg_scope: Optional, arg_scope to build the network. If not provided the\n default arg_scope of the network would be used.\n\n Returns:\n A network function that is used to extract features.\n\n Raises:\n ValueError: network is not supported.\n \"\"\"\n if network_name not in networks_map:\n raise ValueError('Unsupported network %s.' % network_name)\n arg_scope = arg_scope or arg_scopes_map[network_name]()\n func = networks_map[network_name]\n @functools.wraps(func)\n def network_fn(inputs, *args, **kwargs):\n with slim.arg_scope(arg_scope):\n return func(inputs, *args, **kwargs)\n return network_fn\n","sub_path":"core/feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"317368267","text":"\"\"\"\r\nDaily Coding Problem: Problem #400 [Hard] \r\nGood morning! Here's your coding interview problem for today.\r\nThis problem was asked by Goldman Sachs.\r\nGiven a list of numbers L, implement a method sum(i, j) which returns the sum from the sublist L[i:j] (including i, excluding j).\r\nFor example, given L = [1, 2, 3, 4, 5], sum(1, 3) should return sum([2, 3]), which is 5.\r\nYou can assume that you can do some pre-processing. sum() should be optimized over the pre-processing step.\r\n\"\"\"\r\n\r\ndef sum1(array,i,j):\r\n sum = 0\r\n for x in range(i,j):\r\n sum+=array[x]\r\n return sum\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print( sum1([1, 2, 3, 4, 5],1,3))","sub_path":"codesPython/coding400.py","file_name":"coding400.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213203898","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass InquiryInfo(Model):\n \"\"\"Details about inquired protectable items under a given container.\n\n :param status: Inquiry Status for this container such as\n InProgress | Failed | Succeeded\n :type status: str\n :param error_detail: Error Details if the Status is non-success.\n :type error_detail: ~azure.mgmt.recoveryservicesbackup.models.ErrorDetail\n :param inquiry_details: Inquiry Details which will have workload specific\n details.\n For e.g. - For SQL and oracle this will contain different details.\n :type inquiry_details:\n list[~azure.mgmt.recoveryservicesbackup.models.WorkloadInquiryDetails]\n \"\"\"\n\n _attribute_map = {\n 'status': {'key': 'status', 'type': 'str'},\n 'error_detail': {'key': 'errorDetail', 'type': 'ErrorDetail'},\n 'inquiry_details': {'key': 'inquiryDetails', 'type': '[WorkloadInquiryDetails]'},\n }\n\n def __init__(self, *, status: str=None, error_detail=None, inquiry_details=None, **kwargs) -> None:\n super(InquiryInfo, self).__init__(**kwargs)\n self.status = status\n self.error_detail = error_detail\n self.inquiry_details = inquiry_details\n","sub_path":"sdk/recoveryservices/azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/inquiry_info_py3.py","file_name":"inquiry_info_py3.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"264726302","text":"'''\nCreated on 2012-9-12\n\n@author: damon\n'''\nfrom client import Client\nimport md5\nimport urllib\n\nclass RRClient(Client):\n '''\n classdocs\n '''\n\n def __init__(self, client_id, client_secret, **opts):\n '''\n Constructor\n '''\n Client.__init__(self, client_id, client_secret, **opts)\n self.params = {'format':'JSON', 'v':'1.0'}\n\n def user_getInfo(self):\n self.params['method']='users.getInfo'\n self.params['fields']='uid,name,sex,email_hash,star,zidou,vip,birthday,tinyurl,headurl,mainurl,hometown_location,work_history,university_history'\n return self.__send_request().body\n \n def __send_request(self):\n return self.request('POST', self.__build_url())\n \n def set_access_token(self, token):\n self.params['access_token'] = token\n\n def __build_url(self):\n self.site = 'http://api.renren.com/restserver.do'\n keys = self.params.keys()\n keys.sort()\n sig = ''\n for key in keys:\n sig += key + '=' + self.params[key]\n sig += self.secret\n self.params['sig'] = md5.new(sig).hexdigest()\n print(self.params['sig'])\n url = urllib.urlencode(self.params)\n print(url)\n return '?%s'%url\n ","sub_path":"oauth2/rrclient.py","file_name":"rrclient.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"254488630","text":"import unittest\nfrom flaskblog import app, db\nfrom flaskblog.models import User, Sportsmen\nimport requests\n\n\nclass TestsDatabase(unittest.TestCase):\n def setUp(self):\n self.client = app.test_client()\n app.config['TESTING'] = True\n app.config['WTF_CSRF_ENABLED'] = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site14.db'\n\n def tearDown(self):\n db.session.close()\n\n def test_existence_of_admin(self):\n person = User.query.get(1)\n self.assertEqual(person.username, \"admin\")\n self.assertEqual(person.email, \"admin@example.com\")\n\n def test_existence_of_users(self):\n person = User.query.get(2)\n self.assertNotEqual(person.username, \"admin\")\n self.assertNotEqual(person.email, \"admin@example.com\")\n\n def test_avatar(self):\n person = User.query.filter_by(username=\"admin\").first()\n expected = 'https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?d=identicon&s=36'\n self.assertEqual(person.avatar(36), expected)\n\n def test_follow(self):\n person = User.query.filter_by(username=\"admin\").first()\n # person2 = Sportsmen.query.filter_by(name=\"имя\").first()\n person3 = Sportsmen.query.filter_by(name=\"susan\").first()\n\n person.follow(person3)\n db.session.commit()\n\n self.assertTrue(person.is_following(person3))\n self.assertEqual(person.followed.count(), 3)\n self.assertEqual(person.followed.filter_by(name=\"susan\").first().name, 'susan')\n self.assertEqual(person3.followers.count(), 1)\n self.assertEqual(person3.followers.first().username, 'admin')\n\n def test_unfollow(self):\n person = User.query.filter_by(username=\"admin\").first()\n # person2 = Sportsmen.query.filter_by(name=\"имя\").first()\n person3 = Sportsmen.query.filter_by(name=\"susan\").first()\n\n self.assertTrue(person.is_following(person3))\n person.unfollow(person3)\n db.session.commit()\n\n self.assertFalse(person.is_following(person3))\n self.assertEqual(person.followed.count(), 2)\n self.assertEqual(person3.followers.count(), 0)\n\n def test_following(self):\n person = User.query.filter_by(username=\"admin\").first()\n person2 = Sportsmen.query.filter_by(name=\"имя\").first()\n\n self.assertIsNotNone(person.followed.all())\n self.assertIsNotNone(person2.followers.all())\n\n\nclass PageLoadTest(unittest.TestCase):\n def test_home(self):\n response1 = requests.get('http://127.0.0.1:5000/home')\n # print(response1.status_code, \"test_home\")\n self.assertEqual(response1.status_code, 200)\n\n def test_account(self):\n response2 = requests.get('http://127.0.0.1:5000/account', allow_redirects=False)\n # print(response2.status_code, \"test_account\")\n self.assertEqual(response2.status_code, 302)\n\n def test_adminpage(self):\n response3 = requests.get('http://127.0.0.1:5000/admin', allow_redirects=False)\n self.assertEqual(response3.status_code, 404)\n # print(response3.status_code, \"test_adminpage\")\n","sub_path":"flaskblog/integration/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"409538133","text":"from app.app import create_app\n\n\n# dir = config directory.\n# py = config script name.\n# cls = config class.\napp = create_app('{dir}.{py}.{cls}'.format(dir='app.config',\n py='config',\n cls='Default'))\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=10000, threaded=False, debug=False)\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"394714686","text":"#!/usr/bin/env python\n\n#This uses the algorithms listed on Wikipedia to rasterize a line and a circle.\n#http://en.wikipedia.org/wiki/Bresenham's_line_algorithm\n#http://en.wikipedia.org/wiki/Midpoint_circle_algorithm\n\n#Circle assumes a non-zero radius\n#FillCircle receives a list of points creating a circle (like from Circle) and\n#returns a list of all points inside the circle. It includes the points making\n#the boundary of the circle.\n\nimport operator\n\ndef Line(x0, y0, x1, y1):\n line = []\n \n dx = abs(x1 - x0)\n dy = abs(y1 - y0)\n \n if x0 < x1: sx = 1\n else: sx = -1\n if y0 < y1: sy = 1\n else: sy = -1\n \n err = dx - dy\n \n while 1:\n line.append([x0, y0])\n if x0 == x1 and y0 == y1:\n break\n e2 = err + err\n if e2 > -dy:\n err -= dy\n x0 += sx\n if e2 < dx:\n err += dx\n y0 += sy\n \n return line\n\ndef draw8(x0, y0, x, y):\n points = []\n points.extend(draw4(x0, y0, x, y))\n if x != y: points.extend(draw4(x0, y0, y, x))\n return points\n\ndef draw4(x0, y0, x, y):\n points = []\n points.append([x0 + x, y0 + y])\n points.append([x0 - x, y0 - y])\n if x != 0: points.append([x0 - x, y0 + y])\n if y != 0: points.append([x0 + x, y0 - y])\n return points\n\ndef Circle(x0, y0, r):\n err = -r\n x = r\n y = 0\n \n circle = []\n \n while x >= y:\n circle.extend(draw8(x0, y0, x, y))\n \n err += y\n y += 1\n err += y\n \n if err >= 0:\n x -= 1\n err -= x\n err -= x\n \n return circle\n\ndef FullCircle(aCircle):\n copyCircle = list(aCircle)\n copyCircle.sort(key=operator.itemgetter(0))\n \n filledCircle = []\n \n for point in copyCircle:\n for point2 in copyCircle:\n #if point2[0] > point[0]: break\n if point != point2:\n if point[0] == point2[0]:\n if point not in filledCircle:\n filledCircle.append(point)\n if point2 not in filledCircle:\n filledCircle.append(point2)\n x = point[0]\n for y in xrange(point[1] + 1, point2[1]):\n if [x, y] not in filledCircle:\n filledCircle.append([x, y])\n \n \n return filledCircle","sub_path":"Lines.py","file_name":"Lines.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"438235090","text":"class Component:\n def __init__(self, id, name, cpus, gpu, memory, storageSize, storageType, storageValue, netIn, netOut, netConnections,\n keywords, operatingSystem):\n self.id = id\n self.name = name\n # hardware description\n self.HC = cpus\n self.HCType = gpu\n self.HM = memory\n self.HS = storageSize\n self.HSType = storageType\n self.HSValue =storageValue\n # network description\n self.NIn = netIn\n self.NOut = netOut\n self.NConnections = netConnections\n # other information\n self.keywords = keywords\n self.operatingSystem = operatingSystem\n\n # minimum number of instances\n self.minimumNumberOfInstances = 0\n self.numberOfConflictComponents = 0\n self.orComponentsList = []\n self.dependenceComponentsList = set()\n self.conflictComponentsList = set()\n self.fullDeployedComponent = False\n self.numberOfInstancesDependences = set()\n\n\n\n def getMinimumPossibleNumberOfInstances(self, comps_set):\n \"\"\"\n Get minimum nr of instances for fix components\n If the number of instances of a set of components depends on a value, then the minimum number of instances of\n the component in the set is the minimum of the number of instances of all components\n :return:\n \"\"\"\n if len(self.numberOfInstancesDependences) == 0:\n return self.minimumNumberOfInstances\n else:\n minimum = self.minimumNumberOfInstances\n for comp_id in self.numberOfInstancesDependences:\n if minimum > comps_set[comp_id].minimumNumberOfInstances:\n minimum = comps_set[comp_id].minimumNumberOfInstances\n return minimum\n\n def __repr__(self):\n return \"ID: {} Name: {} Hardware [CPUs: {} GPU: {} Memory: {} StorageSize: {} StorageType: {} StorageValue: {}]\"\\\n \" Network[ In: {} Out: {} Connections: {} ] Keywords: {} OperatingSystem: {}\"\\\n .format(self.id, self.name, self.HC, self.HCType, self.HM, self.HS, self.HSType, self.HSValue, self.NIn,\n self.NOut, self.NConnections, self.keywords, self.operatingSystem)\n\n def getComponentHardWareResources(self):\n \"\"\"\n Used for CP Solver in order to add restrictions regarding hardware requirements\n :return: a list with component hardware restrictions\n \"\"\"\n return [self.HC, self.HM, self.HS]\n\n def getResorces(self):\n \"\"\"\n Function used by EA in order to obtain a aggregation of component hardware resources\n :return:\n \"\"\"\n return self.HC * self.HM * self.HS","sub_path":"maneuverRecomadEngine/problem/Component.py","file_name":"Component.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"397531337","text":"# Time Complexity : O(V+E) [V = number of vertices, E = number of edges]\n# Space Complexity : O(V+E) [V = number of vertices, E = number of edges]\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\nfrom collections import defaultdict\nclass Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n \n def dfs(u,v):\n nonlocal time, discovery, lower, result\n \n ## base\n if discovery[v] != -1:\n return\n \n ## body\n discovery[v] = time\n lower[v] = time\n \n time+=1\n \n neighbours = graph[v]\n for node in neighbours:\n if u == node:\n continue\n dfs(v, node)\n \n # check if the edge is critical\n if discovery[v] < lower[node]:\n result.append([node, v])\n \n lower[v] = min(lower[v], lower[node])\n \n ## build graph\n graph = defaultdict(list)\n \n for v1, v2 in connections:\n graph[v1].append(v2)\n graph[v2].append(v1)\n \n time = 0\n \n result = []\n \n discovery = [-1 for _ in range(n)]\n \n lower = [0 for _ in range(n)]\n \n dfs(0,0)\n \n return result","sub_path":"1192_Critical_Connections_in_a_Network.py","file_name":"1192_Critical_Connections_in_a_Network.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"88087514","text":"class HTTPAwareException(Exception):\n\n def __init__(self,\n status_code: int = 500,\n error_message: str = None,\n root_cause: Exception = None):\n self.root_cause = root_cause\n self.status_code = status_code\n self.error_message = error_message\n\n def get_body(self):\n if self.error_message:\n return {'error': self.error_message}\n elif self.root_cause:\n return {'error': 'exception during request processing',\n 'exception': self.root_cause}\n else:\n return {}\n","sub_path":"life-efficiency/lambda_splitter/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"163152512","text":"# -*- coding: utf-8 -*-\n\nfrom types import MethodType\n\n\"\"\"\n可以动态添加属性和方法\n\"\"\"\nclass Person(object):\n name = \"peter\"\n\n#类动态添加属性\nPerson.addr = \"深圳\"\n\nobj1 = Person()\nobj1.age = 10\n\nprint(obj1.name)\nprint(obj1.age)\nprint(obj1.addr)\n\ndef run(self):\n print(self)\n\nobj1.run = MethodType(run, obj1)\nobj1.run()\n\nobj2 = Person()\nprint(obj2.addr)\n","sub_path":"oo_basic/attr1.py","file_name":"attr1.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"524890508","text":"class Shape:\n\n n = 0\n k = 0\n\n def __init__(self, loop ,polygon = None, c_o_m = None, name = None, radius = None):\n\n self.vertices = loop\n\n if not name:\n Shape.n += 1\n self.tag = 'p{}'.format(Shape.n)\n else:\n self.tag = name\n\n self.kind = polygon\n self.only_loop = not polygon\n self.r = radius\n self.unions = ''\n self.crel = []\n self.hrel = []\n self.vrel = []\n self.center = c_o_m\n\n def reset_n():\n \n Shape.n = 0\n \n def get_shape(self):\n \n return self.kind\n\n def get_center(self):\n \n return self.center\n \n\n def get_radius(self):\n\n if self.r:\n return self.r\n\n def get_loop(self):\n \n return self.vertices\n\n def get_name(self):\n \n return self.tag\n\n def find_unions(self, input):\n \n if self.kind == 'dot' or self.kind == 'circle':\n return\n\n for i in range(1, len(self.vertices)):\n for k, v in input.items():\n \n if k[1] != 'line':\n continue\n \n if set([self.vertices[i], self.vertices[i - 1]]) == set(v):\n self.unions += k[0] + ' U '\n \n self.unions = self.unions[:-3]\n\n\n def find_location(self):\n\n x = int(self.center[0])\n y = int(self.center[1])\n\n if x == 50:\n self.hloc = 'center'\n elif x < 50:\n self.hloc = 'left'\n else:\n self.hloc = 'right'\n \n if y == 50:\n self.vloc = 'middle'\n elif y < 50:\n self.vloc = 'bottom'\n else:\n self.vloc = 'top'\n\n\n def store_crel(self, name, case):\n\n if case == 'i':\n self.crel.append('inside({},{})'.format(self.tag, name))\n elif case == 'o':\n self.crel.append('overlap({},{})'.format(self.tag, name))\n\n\n def store_hrel(self, name, case):\n\n if case == 'l':\n self.crel.append('left_of({},{})'.format(self.tag, name))\n elif case == 'r':\n self.crel.append('right_of({},{})'.format(self.tag, name))\n\n\n def store_vrel(self, name, case):\n\n if case == 'a':\n self.crel.append('above({},{})'.format(self.tag, name))\n elif case == 'b':\n self.crel.append('below({},{})'.format(self.tag, name))\n\n\n def print_relatives(self):\n \n for line in self.hrel:\n print(line)\n \n for line in self.vrel:\n print(line)\n \n for line in self.crel:\n print(line)\n\n\n def print_p(self):\n\n if self.unions != '':\n\n self.p_mid = '('\n\n for value in self.vertices:\n self.p_mid += '({}, {}),{}, '.format(value[0], value[1], Shape.k)\n\n self.p_mid = self.p_mid[:-4]\n self.p_mid += ')'\n\n self.p_line = self.tag + ' = scc' + self.p_mid + ' = ' + self.unions\n print(self.p_line)\n\n\n def print_shape(self):\n\n if not self.only_loop:\n self.s_line = self.kind + '(' + self.tag + ')'\n print(self.s_line)\n\n\n def print_pos(self):\n\n print('hloc(' + self.tag + ',' + self.hloc + ')')\n print('vloc(' + self.tag + ',' + self.vloc + ')')\n\n\n def get_p_line(self):\n\n if self.unions != '':\n\n self.p_mid = '('\n\n for value in self.vertices:\n self.p_mid += '({}, {}),{}, '.format(value[0], value[1], Shape.k)\n\n self.p_mid = self.p_mid[:-4]\n self.p_mid += ')'\n\n self.p_line = self.tag + ' = scc' + self.p_mid + ' = ' + self.unions\n return self.p_line\n\n\n def get_shape_line(self):\n\n if not self.only_loop:\n self.s_line = self.kind + '(' + self.tag + ')'\n return self.s_line\n\n\n def get_pos_lines(self):\n\n return 'hloc(' + self.tag + ',' + self.hloc + ')\\nvloc(' + self.tag + ',' + self.vloc + ')'\n","sub_path":"code/shapes.py","file_name":"shapes.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"207413093","text":"import numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom torchvision import datasets\nimport os\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\n\nclass DiabetesDataset(Dataset):\n def __init__(self):\n self.x_data = np.loadtxt('dataset/diabetes_data.csv.gz', delimiter=' ', dtype=np.float32)\n self.y_data = np.loadtxt('dataset/diabetes_target.csv.gz',ndmin=2 , dtype=np.float32)\n self.len = self.x_data.shape[0]\n def __getitem__(self, index):\n return self.x_data[index], self.y_data[index]\n \n def __len__(self):\n return self.len\n\ndataset = DiabetesDataset()\ntrain_loader = DataLoader(dataset=dataset, batch_size=32, shuffle=True, num_workers=2)\n\n\nclass Model(torch.nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.linear1 = torch.nn.Linear(10, 9)\n self.linear11 = torch.nn.Linear(9, 8)\n self.linear2 = torch.nn.Linear(8, 7)\n self.linear22 = torch.nn.Linear(7, 6)\n self.linear3 = torch.nn.Linear(6, 5)\n self.linear33 = torch.nn.Linear(5, 4)\n self.linear4 = torch.nn.Linear(4, 3)\n self.linear44 = torch.nn.Linear(3, 2)\n self.linear5 = torch.nn.Linear(2,1)\n self.activation = torch.nn.Sigmoid()\n\n def forward(self, x):\n x = self.activation(self.linear1(x))\n x = self.activation(self.linear11(x))\n x = self.activation(self.linear2(x))\n x = self.activation(self.linear22(x))\n x = self.activation(self.linear3(x))\n x = self.activation(self.linear33(x))\n x = self.activation(self.linear4(x))\n x = self.activation(self.linear44(x))\n x = self.activation(self.linear5(x))\n # x = self.sigmoid(x)\n return x\n \nmodel = Model()\n\ncriterion = torch.nn.MSELoss(size_average=True)\noptimizer = torch.optim.SGD(model.parameters(), lr=0.00001)\nepoch_list = []\nloss_list = []\nfor epoch in range(1000):\n for i,data in enumerate(train_loader, 0):\n inputs, labels = data\n \n y_pred = model(inputs)\n # print(labels,y_pred)\n loss = criterion(y_pred,labels)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n epoch_list.append(epoch)\n loss_list.append(loss.item()) \n # print(epoch,loss.item()) \n\nnow = datetime.now()\nos.environ['KMP_DUPLICATE_LIB_OK']='True' # to slove 'Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.'\nplt.plot(epoch_list, loss_list)\nplt.savefig(\"output_figures/liuhongpu/MultipleFeatureLinearRegre_\"+now.strftime(\"%H_%M_%S\")+\"_shuffle_true.pdf\")\nprint('done')\n# plt.show()\n","sub_path":"liuhongpu/MultipleFeatureLinearRegre.py","file_name":"MultipleFeatureLinearRegre.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"358125654","text":"# coding:utf-8\nfrom Agent import actionid2str\nfrom State import State\nfrom State import DRAW_TURN\nfrom Human import Human\nfrom LinearAI import LinearAI\nfrom CNNAI import CNNAI\nfrom BasicAI import state_copy\nimport time\nimport sys\nimport numpy as np\nimport gc\nimport h5py\nimport os\n\n# 学習設定\nMAX_DATA = 2000000\nSTEP = 250000\nSEARCH_NODE = 300\nMAX_EPOCH = 100\nTAU_MIN = 0.25\n\n\n# agentsは初期化されてるとする\ndef normal_play(agents):\n state = State()\n while True:\n state.display_cui()\n start = time.time()\n s = agents[0].act(state, showNQ=True)\n end = time.time()\n print(end - start)\n if isinstance(s, int):\n a = actionid2str(state, s)\n else:\n a = s\n while not state.accept_action_str(a):\n print(a)\n print(\"this action is impossible\")\n s = agents[0].act(state, showNQ=True)\n if isinstance(s, int):\n a = actionid2str(state, s)\n else:\n a = s\n agents[1].prev_action = s\n\n if state.terminate:\n break\n #time.sleep(0.1)\n\n state.display_cui()\n s = agents[1].act(state, showNQ=True)\n if isinstance(s, int):\n a = actionid2str(state, s)\n else:\n a = s\n while not state.accept_action_str(a):\n print(a)\n print(\"this action is impossible\")\n s = agents[1].act(state, showNQ=True)\n if isinstance(s, int):\n a = actionid2str(state, s)\n else:\n a = s\n agents[0].prev_action = s\n\n #time.sleep(0.1)\n if state.terminate:\n break\n\n state.display_cui()\n print(\"The game finished. reward=({}, {})\".format(state.reward, -state.reward))\n\n\ndef generate_data(AIs, play_num, noise=0.1, display=False, equal_draw=True):\n data = []\n for i in range(play_num):\n state = State()\n AIs[0].init_prev()\n AIs[1].init_prev()\n featuress = [[], [], [], []]\n for i, b1, b2 in [(0, False, False), (1, True, False), (2, False, True), (3, True, True)]:\n featuress[i].append(state.feature_CNN(b1, b2))\n\n pis = []\n states = [state_copy(state)]\n while True:\n AIs[0].tau = np.random.rand() * (1. - TAU_MIN) + TAU_MIN\n AIs[1].tau = np.random.rand() * (1. - TAU_MIN) + TAU_MIN\n if state.turn >= 20:\n AIs[0].tau = TAU_MIN\n AIs[1].tau = TAU_MIN\n s, pi = AIs[0].act_and_get_pi(state, noise=noise)\n a = actionid2str(state, s)\n while not state.accept_action_str(a):\n print(\"this action is impossible\")\n s, pi = AIs[0].act_and_get_pi(state)\n a = actionid2str(state, s)\n AIs[1].prev_action = s\n pis.append(pi)\n if display:\n state.display_cui()\n end = False\n for state2 in states:\n if equal_draw and state == state2:\n end = True\n break\n if end:\n break\n states.append(state_copy(state))\n if state.terminate:\n break\n for i, b1, b2 in [(0, False, False), (1, True, False), (2, False, True), (3, True, True)]:\n featuress[i].append(state.feature_CNN(b1, b2))\n s, pi = AIs[1].act_and_get_pi(state, noise=noise)\n a = actionid2str(state, s)\n while not state.accept_action_str(a):\n print(\"this action is impossible\")\n s, pi = AIs[1].act_and_get_pi(state)\n a = actionid2str(state, s)\n AIs[0].prev_action = s\n pis.append(pi)\n if display:\n state.display_cui()\n end = False\n for state2 in states:\n if equal_draw and state == state2:\n end = True\n break\n if end:\n break\n states.append(state_copy(state))\n if state.terminate:\n break\n for i, b1, b2 in [(0, False, False), (1, True, False), (2, False, True), (3, True, True)]:\n featuress[i].append(state.feature_CNN(b1, b2))\n del states\n if state.reward == 0:\n continue\n for feature1, feature2, feature3, feature4, pi in zip(featuress[0], featuress[1], featuress[2], featuress[3], pis):\n data.append((feature1, pi, state.reward))\n a = np.flip(pi[:64].reshape((8, 8)), 0).flatten()\n b = np.flip(pi[64:128].reshape((8, 8)), 0).flatten()\n mvarray1 = pi[128:].reshape((3, 3))\n mvarray2 = np.zeros((3, 3))\n for y in [-1, 0, 1]:\n for x in [-1, 0, 1]:\n mvarray2[x, y] = mvarray1[-x, y]\n c = mvarray2.flatten()\n data.append((feature2, np.concatenate([a, b, c]), state.reward))\n a = np.flip(pi[:64].reshape((8, 8)), 1).flatten()\n b = np.flip(pi[64:128].reshape((8, 8)), 1).flatten()\n mvarray1 = pi[128:].reshape((3, 3))\n mvarray2 = np.zeros((3, 3))\n for y in [-1, 0, 1]:\n for x in [-1, 0, 1]:\n mvarray2[x, y] = mvarray1[x, -y]\n c = mvarray2.flatten()\n data.append((feature3, np.concatenate([a, b, c]), -state.reward))\n a = np.flip(np.flip(pi[:64].reshape((8, 8)), 1), 0).flatten()\n b = np.flip(np.flip(pi[64:128].reshape((8, 8)), 1), 0).flatten()\n mvarray1 = pi[128:].reshape((3, 3))\n mvarray2 = np.zeros((3, 3))\n for y in [-1, 0, 1]:\n for x in [-1, 0, 1]:\n mvarray2[x, y] = mvarray1[-x, -y]\n c = mvarray2.flatten()\n data.append((feature4, np.concatenate([a, b, c]), -state.reward))\n\n return data\n\n\n# 中で先手後手を順番に入れ替えている\ndef evaluate(AIs, play_num, return_draw=False):\n wins = 0.\n draw_num = 0\n for i in range(play_num):\n state = State()\n AIs[0].init_prev()\n AIs[1].init_prev()\n AIs[i % 2].color = 0\n AIs[1 - i % 2].color = 1\n while True:\n s, pi = AIs[i % 2].act_and_get_pi(state)\n a = actionid2str(state, s)\n while not state.accept_action_str(a):\n print(\"this action is impossible\")\n s, pi = AIs[i % 2].act_and_get_pi(state)\n a = actionid2str(state, s)\n AIs[1 - i % 2].prev_action = s\n\n if state.terminate:\n break\n\n s, pi = AIs[1 - i % 2].act_and_get_pi(state)\n a = actionid2str(state, s)\n while not state.accept_action_str(a):\n print(\"this action is impossible\")\n s, pi = AIs[1 - i % 2].act_and_get_pi(state)\n a = actionid2str(state, s)\n AIs[i % 2].prev_action = s\n\n if state.terminate:\n break\n\n if i % 2 == 0 and state.reward == 1:\n wins += 1.\n elif i % 2 == 1 and state.reward == -1:\n wins += 1.\n elif state.reward == 0:\n wins += 0.5\n draw_num += 1\n sys.stderr.write('\\r\\033[K {}win/{}'.format(i + 1 - wins, i + 1))\n sys.stderr.flush()\n print(\"\")\n AIs[0].color = 0\n AIs[1].color = 1\n\n if return_draw:\n return wins, draw_num\n else:\n return wins\n\n\ndef learn(AIs, restart=False, initial_rate=0., initial_epoch=0, skip_first_selfplay=False):\n features = np.zeros((STEP, 8, 8, 7))\n pis = np.zeros((STEP, 137))\n rewards = np.zeros((STEP,))\n\n search_nodes = AIs[0].search_nodes\n if restart:\n if os.path.exists(\"./parameter/post.ckpt\"):\n AIs[0].load(\"./parameter/post.ckpt\")\n AIs[1].load(\"./parameter/post.ckpt\")\n else:\n for filename in os.listdir(\"data\"):\n os.remove(\"data/\" + filename)\n # 初回のみ探索ノード1(引き分け多いから)\n\n AIs[0].search_nodes = 1\n AIs[1].search_nodes = 1\n\n rating = initial_rate\n h5_num = MAX_DATA // STEP\n for i in range(initial_epoch, MAX_EPOCH):\n if not skip_first_selfplay:\n # -------data generation-------\n b_win = 0\n w_win = 0\n draw = 0\n start = time.time()\n index = 0\n while index < STEP:\n if i < h5_num and not restart:\n #State.draw_turn = 200\n temp_data = generate_data(AIs, 1, noise=1., equal_draw=False)\n #State.draw_turn = DRAW_TURN\n else:\n temp_data = generate_data(AIs, 1, noise=0.1)\n if len(temp_data) == 0:\n draw += 1\n else:\n reward = -temp_data[-1][2] # augmentationの影響で報酬がひっくり返っている\n if reward == 1:\n b_win += 1\n elif reward == -1:\n w_win += 1\n for feature, pi, reward in temp_data:\n features[index] = feature\n pis[index] = pi\n rewards[index] = reward\n index += 1\n if index >= STEP:\n break\n del temp_data\n sys.stderr.write('\\r\\033[Kepoch{}:data={}/{} B{}win W{}win {}draw'.format(i + 1, index, STEP, b_win, w_win, draw))\n sys.stderr.flush()\n h5file = h5py.File(\"data/{}.h5\".format(i), \"w\")\n h5file.create_dataset(\"feature\", data=features, compression=\"gzip\", compression_opts=1)\n h5file.create_dataset(\"pi\", data=pis, compression=\"gzip\", compression_opts=1)\n h5file.create_dataset(\"reward\", data=rewards, compression=\"gzip\", compression_opts=1)\n h5file.flush()\n h5file.close()\n\n print(\"\")\n print(\"elapsed time(self-play)={}\".format(time.time() - start))\n skip_first_selfplay = False\n start = time.time()\n\n if i < h5_num - 1:\n continue\n elif i >= h5_num:\n pass\n #os.remove(\"data/{}.h5\".format(i - h5_num))\n\n # --------training---------\n AIs[1].save(\"./parameter/pre.ckpt\")\n if i >= h5_num:\n AIs[1].load(\"./parameter/post.ckpt\")\n AIs[1].learn(i, h5_num, h5_num, STEP)\n AIs[1].save(\"./parameter/post.ckpt\")\n\n print(\"elapsed time(training)={}\".format(time.time() - start))\n start = time.time()\n\n # ----------evaluation--------\n AIs[0].tau = TAU_MIN\n AIs[1].tau = TAU_MIN\n AIs[0].search_nodes = search_nodes\n AIs[1].search_nodes = search_nodes\n play_num = 100\n white_win_num = evaluate(AIs, play_num)\n win_rate = (play_num - white_win_num) / play_num\n print(\"new AI win rate={}\".format(win_rate))\n if win_rate > 0.5:\n win_rate2 = (play_num + 2 - (white_win_num + 1)) / (play_num + 2)\n rating += -np.log(1. / win_rate2 - 1)\n print(\"new AI accepted. rate={}\".format(rating))\n AIs[1].save(\"./parameter/epoch{}.ckpt\".format(i + 1))\n AIs[0].load(\"./parameter/post.ckpt\")\n else:\n print(\"new AI rejected\")\n AIs[1].load(\"./parameter/pre.ckpt\")\n\n gc.collect()\n print(\"elapsed time(evaluation)={}\".format(time.time() - start))\n print(\"\")\n\n # 元に戻す\n AIs[0].tau = 1.\n AIs[1].tau = 1.\n AIs[0].search_nodes = search_nodes\n AIs[1].search_nodes = search_nodes\n\nsearch_nodes = 300\nif len(sys.argv) >= 3:\n search_nodes = int(sys.argv[2])\n\nif sys.argv[1] == \"train\":\n # 1つ目はパラメータ0にすることでランダムAIにする.2つ目は学習のことがあるから0にしてはだめ\n learn([CNNAI(0, search_nodes=SEARCH_NODE, all_parameter_zero=True),\n CNNAI(1, search_nodes=SEARCH_NODE)])\n #restart=True, initial_rate=7, initial_epoch=17, skip_first_selfplay=False)\nelif sys.argv[1] == \"view\":\n AIs = [CNNAI(0, search_nodes=search_nodes, tau=0.25), CNNAI(1, search_nodes=search_nodes, tau=0.25)]\n AIs[0].load(\"./parameter/post.ckpt\")\n AIs[1].load(\"./parameter/post.ckpt\")\n normal_play(AIs)\nelif sys.argv[1] == \"measure\":\n np.random.seed(0)\n game_num = 20\n AIs = [CNNAI(0, search_nodes=search_nodes, tau=1), CNNAI(1, search_nodes=search_nodes, tau=1)]\n AIs[0].load(\"./parameter/epoch22.ckpt\")\n AIs[1].load(\"./parameter/epoch22.ckpt\")\n temp_data = generate_data(AIs, game_num, noise=0.1, display=True)\n\n\"\"\"\nprint(\"---------\")\nfor node_num in [1, 10, 25, 50, 100]:\n AIs[0].search_nodes = node_num\n AIs[1].search_nodes = node_num\n win_num, draw = evaluate(AIs, game_num, True)\n print(\"{}win {}draw / {}games\".format(win_num, draw, game_num))\n\nprint(\"---------\")\nAIs[1].search_nodes = 1\nfor node_num in [1, 10, 25, 50, 100]:\n AIs[0].search_nodes = node_num\n win_num, draw = evaluate(AIs, game_num, True)\n print(\"{}win {}draw / {} games\".format(win_num, draw, game_num))\n\nAIs = [CNNAI(0, search_nodes=50, tau=0.5), CNNAI(1, search_nodes=50, tau=0.5)]\nAIs[0].load(\"./parameter/post.ckpt\")\nAIs[1].load(\"./parameter/post.ckpt\")\n\nprint(\"---------\")\nfor C_puct in [3, 4, 5]:\n AIs[0].C_puct = C_puct\n win_num, draw = evaluate(AIs, game_num, True)\n print(\"{}win {}draw / {} games\".format(win_num, draw, game_num))\n\nprint(\"---------\")\nAIs[0].C_puct = 2\nfor tau in [0.25, 0]:\n AIs[0].tau = tau\n win_num, draw = evaluate(AIs, game_num, True)\n print(\"{}win {}draw / {} games\".format(win_num, draw, game_num))\n\nprint(\"---------\")\nAIs[0].tau = 0.5\nAIs[0].n_parallel = 4\nfor node_num in [1, 10, 25, 50, 100]:\n AIs[0].search_nodes = node_num\n AIs[1].search_nodes = node_num\n win_num, draw = evaluate(AIs, game_num, True)\n print(\"{}win {}draw / {}games\".format(win_num, draw, game_num))\n\"\"\"\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"241945479","text":"#-*- coding: utf-8 -*-\n# Maintainer: Cambus\n# Version: 0.0.1\n#\n#\n\nimport os\nimport numpy as np\nimport threading\nimport cv2\nimport Pessoa\nimport time\nfrom random import randint\nfrom time import gmtime, strftime\nimport math\nimport decimal\n\n\nclass Contador:\n\n def __init__(self, logger, video):\n self.id = os.getpid()\n self.frame = None\n self._countFlag = os.getenv('COUNT')\n self.LOG = logger\n self._videoPath = video\n self.LOG.info(self._videoPath)\n self.LOG.info('countFlag= ' + str(self._countFlag))\n\n self._countUp = 0\n self._countDown = 0\n self._model = 'Basic OpenCV'\n self.LOG.info('Contador[%s] successfully loaded', self._model)\n\n def getVersion(self):\n return 'ContadorFake 1.0'\n\n def stop(self):\n self._mustRun = False\n\n def run(self):\n self._mustRun = True\n\n # Roda dentro de uma thread\n if (self._countFlag):\n self._model = 'Basic OpenCV'\n T1 = threading.Thread(target=self.detectPeople)\n T1.daemon = True # Permite CTR+C parar o progama!\n T1.start()\n else:\n self._model = 'dummy'\n T2 = threading.Thread(target=self.detectPeopleSimulator)\n T2.daemon = True\n T2.start()\n\n def getJson(self):\n Data = {\n 'count_up': self._countUp,\n 'count_down': self._countDown,\n 'model': self._model\n }\n\n return Data\n\n def detectPeopleSimulator(self):\n self.LOG.info('CounterThread= ' + str(threading.current_thread()))\n while (self._mustRun):\n time.sleep(2)\n self._countUp = randint(0, 9)\n self._countDown = randint(0, 9)\n\n def detectPeople(self):\n\n # Contadore de entrada e saida\n self._countUp = 0\n self._countDown = 0\n\n # Fonte de video\n # cap = cv2.VideoCapture(0) # Descomente para usar a camera.\n cap = cv2.VideoCapture(self._videoPath) # Captura um video\n\n #Descomente para imprimir as propriedades do video\n \"\"\"for i in range(19):\n print (i, cap.get(i))\"\"\"\n\n #Metodo GET para pegar width e height do frame\n w = cap.get(3)\n h = cap.get(4)\n print(\"Resolução do video: \", w, \"x\", h)\n\n x_meio = int(w/2)\n y_meio = int(h/2)\n\n frameArea = h*w\n print(\"Area do Frame:\", frameArea)\n areaTH = frameArea/100\n print ('Area Threshold', areaTH) # Area de contorno usada para detectar uma pessoa\n\n #Linhas de Entrada/Saida\n\n #line_up = int(2*(h/6))\n #line_down = int(3*(h/6))\n line_up = int(4.7*(h/10)) #deve-se adaptar de acordo com as caracteristicas da camera\n line_down = int(5.3*(h/10)) #deve-se adaptar de acordo com as caracteristicas da camera\n print (\"Line UP:\", line_up)\n print (\"Line DOW:\", line_down)\n\n #up_limit = int(1*(h/6))\n #down_limit = int(5*(h/6))\n up_limit = int(0.1*(h/10))\n down_limit = int(9.9*(h/10))\n\n l1UP = int(4.8*(h/10))\n l1DOWN = int(5.2*(h/10))\n l2UP = int(4.9*(h/10))\n l2DOWN = int(5.1*(h/10))\n\n print (\"Limite superior:\", up_limit)\n print (\"Limite inferior:\", down_limit)\n\n #Propriedades das linhas\n\n print (\"Red line y:\",str(line_down))\n print (\"Blue line y:\", str(line_up))\n line_down_color = (0,0,255)\n line_up_color = (255,0,0)\n pt1 = [0, line_down];\n pt2 = [w, line_down];\n pts_L1 = np.array([pt1,pt2], np.int32)\n pts_L1 = pts_L1.reshape((-1,1,2))\n pt3 = [0, line_up];\n pt4 = [w, line_up];\n pts_L2 = np.array([pt3,pt4], np.int32)\n pts_L2 = pts_L2.reshape((-1,1,2))\n\n pt5 = [0, up_limit];\n pt6 = [w, up_limit];\n pts_L3 = np.array([pt5,pt6], np.int32)\n pts_L3 = pts_L3.reshape((-1,1,2))\n pt7 = [0, down_limit];\n pt8 = [w, down_limit];\n pts_L4 = np.array([pt7,pt8], np.int32)\n pts_L4 = pts_L4.reshape((-1,1,2))\n\n pt9 = [0, l1UP];\n pt10 = [w, l1UP];\n pts_L5 = np.array([pt9,pt10], np.int32)\n pts_L5 = pts_L5.reshape((-1,1,2))\n\n pt11 = [0, l1DOWN];\n pt12 = [w, l1DOWN];\n pts_L6 = np.array([pt11,pt12], np.int32)\n pts_L6 = pts_L6.reshape((-1,1,2))\n\n pt13 = [0, l2UP];\n pt14 = [w, l2UP];\n pts_L7 = np.array([pt13,pt14], np.int32)\n pts_L7 = pts_L7.reshape((-1,1,2))\n\n\n pt15 = [0, l2DOWN];\n pt16 = [w, l2DOWN];\n pts_L8 = np.array([pt15,pt16], np.int32)\n pts_L8 = pts_L8.reshape((-1,1,2))\n\n #Substrator de fundo\n #fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows = False)\n #fgbg = cv2.createBackgroundSubtractorMOG2(500,detectShadows = True)\n #fgbg = cv2.createBackgroundSubtractorMOG2()\n fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()\n\n #kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n #fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()\n\n #Elementos estruturantes para filtros morfoogicos\n kernelOp = np.ones((3,3),np.uint8)\n kernelOp2 = np.ones((5,5),np.uint8)\n kernelOp3 = np.ones((8, 8), np.uint8)\n kernelCl = np.ones((11,11),np.uint8)\n kernelCl2 = np.ones((8, 8), np.uint8)\n\n #Inicializacao de variaveis Globais\n font = cv2.FONT_HERSHEY_SIMPLEX\n pessoas = []\n max_p_age = 5\n pid = 1\n\n while(cap.isOpened()):\n ##for image in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n #Le uma imagem de uma fonte de video\n\n ret, frame = cap.read()\n ## frame = image.array\n\n for pessoa in pessoas:\n pessoa.age_one() #age every person one frame\n #########################\n # PRE-PROCESSAMENTO #\n #########################\n\n #Aplica subtracao de fundo\n fgmask = fgbg.apply(frame)\n #fgmask2 = fgbg.apply(frame)\n\n #Binarizacao para eliminar sombras (color gris)\n try:\n\n fgmask = cv2.GaussianBlur(fgmask, (3, 3), 0)\n #fgmask2 = cv2.GaussianBlur(fgmask2, (3, 3), 0)\n\n ret,imBin= cv2.threshold(fgmask,128,255,cv2.THRESH_BINARY)\n #ret,imBin2 = cv2.threshold(fgmask2,128,255,cv2.THRESH_BINARY)\n\n #Opening (erode->dilate) para remover o ruido.\n mask = cv2.morphologyEx(imBin, cv2.MORPH_OPEN, kernelOp)\n #mask2 = cv2.morphologyEx(imBin2, cv2.MORPH_OPEN, kernelOp)\n\n #Closing (dilate -> erode) para juntar regioes brancas.\n mask = cv2.morphologyEx(mask , cv2.MORPH_CLOSE, kernelCl)\n #mask2 = cv2.morphologyEx(mask2, cv2.MORPH_CLOSE, kernelCl)\n except:\n print('EOF')\n print ('Entrou:', self._countUp)\n print ('Saiu:', self._countDown)\n return (self._countUp - self._countDown)\n #break\n #################\n # CONTORNOS #\n #################\n\n # RETR_EXTERNAL returns only extreme outer flags. All child contours are left behind.\n contours0, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for cnt in contours0:\n area = cv2.contourArea(cnt)\n peri = cv2.arcLength(cnt, True)\n M = cv2.moments(cnt)\n\n if area > areaTH:\n\n #####################\n # RASTREAMENTO #\n #####################\n\n #Falta agregar condicoes para multiplas pessoas, saidas e entradas da tela\n\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n\n x, y, w, h = cv2.boundingRect(cnt)\n\n new = True\n if cy in range(up_limit, down_limit):\n for pessoa in pessoas:\n if abs(cx - pessoa.getX()) <= w and abs(cy - pessoa.getY()) <= h:\n # O objeto esta perto de um que ja foi detectado anteriormente\n new = False\n pessoa.updateCoords(cx,cy) #atualizar coordenadas no objeto e reseta a idade\n if pessoa.deslocaCima(line_down,line_up) == True: # and shape[0] < 0.30:# and dist < 170 and dist > 70 : #and (pessoa.getOffset() - time.time() < -0.95):\n self._countUp += 1;\n elif pessoa.deslocaBaixo(line_down,line_up) == True : # and dist < 170 and dist > 70: # and (pessoa.getOffset() - time.time() < -0.95):\n self._countDown += 1;\n break\n if pessoa.getState() == '1':\n if pessoa.getDir() == 'Saiu' and pessoa.getY() > down_limit:\n pessoa.setDone()\n elif pessoa.getDir() == 'Entrou' and pessoa.getY() < up_limit:\n pessoa.setDone()\n if pessoa.timedOut():\n #remover pessoas da lista\n index = pessoas.index(pessoa)\n pessoas.pop(index)\n del pessoa #libera a memoria de variavel i.\n if new == True:\n p = Pessoa.Pessoa(pid, cx, cy, max_p_age, time.time())\n pessoas.append(p)\n pid += 1\n #################\n # DESENHOS #\n #################\n cv2.circle(frame,(cx,cy), 5, (0,0,255), -1)\n img = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)\n #cv2.drawContours(frame, cnt, -1, (0,255,0), 3)\n\n #END for cnt in contours0\n\n #########################\n # DESENHAR TRAJETORIAS #\n #########################\n for pessoa in pessoas:\n if len(pessoa.getTracks()) >= 2:\n pts = np.array(pessoa.getTracks(), np.int32)\n pts = pts.reshape((-1,1,2))\n frame = cv2.polylines(frame,[pts],False,pessoa.getRGB())\n #if pessoa.getId() == 9:\n #print (str(pessoa.getX()), ',', str(pessoa.getY()))\n cv2.putText(frame, str(pessoa.getId()),(pessoa.getX(),pessoa.getY()),font,0.3,pessoa.getRGB(),1,cv2.LINE_AA)\n\n #################\n # IMAGEM #\n #################\n str_up = 'Entraram '+ str(self._countUp)\n str_down = 'Sairam '+ str(self._countDown)\n tituloup = \"Entrada \"\n titulodown = \"Saida \"\n #dataehora = strftime(\"%c\")\n dataehora = strftime(\"%A, %d %b %Y %H:%M:%S\", gmtime())\n frame = cv2.polylines(frame,[pts_L1],False,line_down_color,thickness=1)\n frame = cv2.polylines(frame,[pts_L2],False,line_up_color,thickness=1)\n frame = cv2.polylines(frame,[pts_L3],False,(255,255,0),thickness=1)\n frame = cv2.polylines(frame,[pts_L4],False,(255,255,0),thickness=1)\n\n frame = cv2.polylines(frame,[pts_L5],False,(line_up_color),thickness=1)\n frame = cv2.polylines(frame,[pts_L6],False,(line_down_color),thickness=1)\n frame = cv2.polylines(frame,[pts_L7],False,(line_up_color),thickness=1)\n frame = cv2.polylines(frame,[pts_L8],False,(line_down_color),thickness=1)\n\n self.escreveCabecalho(frame, str_up, str_down, titulodown,tituloup,dataehora,font, x_meio)\n\n cv2.imshow('Frame',frame)\n #cv2.imshow('Debug',mask)\n #cv2.imshow('Binarizacao', imBin)\n\n #preisonar ESC para sair\n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n #END while(cap.isOpened())\n\n #################\n # LIMPEZA #\n #################\n cap.release()\n cv2.destroyAllWindows()\n\n def escreveCabecalho(self,frame,str_up, str_down, titulodown, tituloup, dataehora, font, x_meio):\n cv2.putText(frame, str_up, (10, 40), font, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n cv2.putText(frame, str_up, (10, 40), font, 0.5, (255, 0, 0), 1, cv2.LINE_AA)\n cv2.putText(frame, str_down, (10, 60), font, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n cv2.putText(frame, str_down, (10, 60), font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)\n #cv2.putText(frame, tituloup, (x_meio, 40), font, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n #cv2.putText(frame, titulodown, (x_meio, 200), font, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n #cv2.putText(frame, dataehora, (180, 40), font, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n\nif __name__ == '__main__':\n LOG = logging.getLogger(__name__)\n c = Contador(LOG)\n c.detectPeople()","sub_path":"Contador37.py","file_name":"Contador37.py","file_ext":"py","file_size_in_byte":13249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"387733600","text":"# https://judge.softuni.bg/Contests/Practice/Index/368#5\n\nbegin = input()\nend = input()\nskip = input()\n\ncounter = 0\n\nwhile not (len(begin) == 1 and len(end) == 1 and len(skip) == 1):\n begin = input()\n end = input()\n skip = input()\n\nfor first_letter in range(ord(begin[0]), ord(end[0]) + 1):\n if not first_letter == ord(skip):\n for second_letter in range(ord(begin[0]), ord(end[0]) + 1):\n if not second_letter == ord(skip):\n for third_letter in range(ord(begin[0]), ord(end[0]) + 1):\n if not third_letter == ord(skip):\n print(chr(first_letter) + chr(second_letter) + chr(third_letter), end=' ')\n counter += 1\nprint(counter)\n","sub_path":"Programing_Basics/Others/Problem 06. Letters Combinations.py","file_name":"Problem 06. Letters Combinations.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"187137185","text":"from musicscore.dtd.dtd import Sequence, Choice, Element, GroupReference\nfrom musicscore.musicxml.attributes.attribute_abstract import TypeSyllabic\nfrom musicscore.musicxml.attributes.color import Color\nfrom musicscore.musicxml.attributes.justify import Justify\nfrom musicscore.musicxml.attributes.optional_unique_id import OptionalUniqueId\nfrom musicscore.musicxml.attributes.placement import Placement\nfrom musicscore.musicxml.attributes.position import Position\nfrom musicscore.musicxml.attributes.printobject import PrintObject\nfrom musicscore.musicxml.attributes.timeonly import TimeOnly\nfrom musicscore.musicxml.elements.xml_element import XMLElement\nfrom musicscore.musicxml.groups.common import Editorial\nfrom musicscore.musicxml.types.complextypes.complextype import ComplexType, Empty\nfrom musicscore.musicxml.types.complextypes.elision import ComplexTypeElision\nfrom musicscore.musicxml.types.complextypes.extend import ComplexTypeExtend\nfrom musicscore.musicxml.types.complextypes.textelementdata import ComplexTypeTextElementData\nfrom musicscore.musicxml.types.simple_type import Token\n\n\nclass Syllabic(XMLElement, TypeSyllabic):\n \"\"\"\"\"\"\n _TAG = 'syllabic'\n\n def __init__(self, value, *args, **kwargs):\n super().__init__(tag=self._TAG, value=value, *args, **kwargs)\n\n\nclass Text(ComplexTypeTextElementData):\n \"\"\"\"\"\"\n _TAG = 'text'\n\n def __init__(self, value=None, *args, **kwargs):\n super().__init__(tag=self._TAG, value=value, *args, **kwargs)\n\n\nclass Elision(ComplexTypeElision):\n \"\"\"\"\"\"\n _TAG = 'elision'\n\n def __init__(self, value, *args, **kwargs):\n super().__init__(tag=self._TAG, value=value, *args, **kwargs)\n\n\nclass Extend(ComplexTypeExtend):\n \"\"\"\"\"\"\n _TAG = 'extend'\n\n def __init__(self, value, *args, **kwargs):\n super().__init__(tag=self._TAG, value=value, *args, **kwargs)\n\n\nclass Laughing(Empty):\n \"\"\"\"\"\"\n _TAG = 'laughing'\n\n def __init__(self, *args, **kwargs):\n super().__init__(tag=self._TAG, *args, **kwargs)\n\n\nclass Humming(Empty):\n \"\"\"\"\"\"\n _TAG = 'humming'\n\n def __init__(self, *args, **kwargs):\n super().__init__(tag=self._TAG, *args, **kwargs)\n\n\nclass EndParagraph(Empty):\n \"\"\"\"\"\"\n _TAG = 'end-paragraph'\n\n def __init__(self, *args, **kwargs):\n super().__init__(tag=self._TAG, *args, **kwargs)\n\n\nclass EndLine(Empty):\n \"\"\"\"\"\"\n _TAG = 'end-line'\n\n def __init__(self, *args, **kwargs):\n super().__init__(tag=self._TAG, *args, **kwargs)\n\n\nclass ComplexTypeLyric(ComplexType, Justify, Position, Placement, Color, PrintObject, TimeOnly,\n OptionalUniqueId):\n \"\"\"The lyric type represents text underlays for lyrics, based on Humdrum with support for other formats. Two text\n elements that are not separated by an elision element are part of the same syllable, but may have different text\n formatting. The MusicXML XSD is more strict than the DTD in enforcing this by disallowing a second syllabic element\n unless preceded by an elision element. The lyric number indicates multiple lines, though a name can be used as well\n (as in Finale's verse / chorus / section specification).\n\n Justification is center by default; placement is below by default. The print-object attribute can override a note's\n print-lyric attribute in cases where only some lyrics on a note are printed, as when lyrics for later verses are\n printed in a block of text rather than with each note. The time-only attribute precisely specifies which lyrics are\n to be sung which time through a repeated section.\n \"\"\"\n\n # todo: sorting mixed Sequence with min_occurrence = 0 and max_occurrence = None and check_occurrence.\n # Syllabic doubled by sort\n _DTD = Sequence(\n Choice(\n Sequence(\n Element(Syllabic, min_occurrence=0),\n Element(Text),\n # Sequence(\n # Sequence(\n # Element(Elision),\n # Element(Syllabic, min_occurrence=0),\n # min_occurrence=0\n # ),\n # Element(Text)\n # # ,\n # # min_occurrence=0,\n # # max_occurrence=None\n # ),\n Element(Extend, min_occurrence=0)\n ),\n Element(Extend),\n Element(Laughing),\n Element(Humming)\n ),\n Element(EndLine, min_occurrence=0),\n Element(EndParagraph, min_occurrence=0),\n GroupReference(Editorial)\n )\n\n def __init__(self, tag, number='1', *args, **kwargs):\n super().__init__(tag=tag, *args, **kwargs)\n self.number = number\n\n @property\n def number(self):\n return self.get_attribute('number')\n\n @number.setter\n def number(self, value):\n if value is None:\n self.remove_attribute('number')\n else:\n Token(value)\n self._ATTRIBUTES.insert(0, 'number')\n self.set_attribute('number', value)\n\n @property\n def name(self):\n return self.get_attribute('name')\n\n @name.setter\n def name(self, value):\n if value is None:\n self.remove_attribute('name')\n else:\n Token(value)\n self._ATTRIBUTES.insert(0, 'name')\n self.set_attribute('name', value)\n","sub_path":"musicscore/musicxml/types/complextypes/lyric.py","file_name":"lyric.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"215604028","text":"from config_db import *\nfrom module_db_words import *\nfrom module_db_default_words import *\n\n\ndef insert_words_test(id, list_words):\n index = 0\n try:\n for word in list_words:\n with connection.cursor() as cursor:\n query = \"INSERT INTO db_test (id, word, _index) VALUES (%s, %s, %s)\"\n val = (id, word, index)\n cursor.execute(query, val)\n connection.commit()\n index += 1\n except:\n raise Exception(\"db_test Error insert_words_test\")\n\n\ndef get_words_from_test(id):\n try:\n with connection.cursor() as cursor:\n query = \"SELECT word FROM db_test WHERE id=%s ORDER BY _index\"\n val = (id)\n cursor.execute(query, val)\n result = cursor.fetchall()\n return result\n except:\n raise Exception(\"db_test Error get_words_from_test\")\n\n\ndef delete_words_from_test(id):\n try:\n with connection.cursor() as cursor:\n query = \"DELETE FROM db_test WHERE id=%s\"\n val = (id)\n cursor.execute(query, val)\n connection.commit()\n except:\n raise Exception(\"db_test Error delete_words_from_test\")\n\n\ndef find_words_for_test(id, amout_of_words_translate):\n try:\n new_word_list = []\n list_words = get_words_sorted_descending_order(id)\n for word in list_words:\n new_word_list.append(word[\"word\"])\n\n if len(new_word_list) < amout_of_words_translate:\n left_to_add = amout_of_words_translate - len(new_word_list)\n left_to_add_list = find_words_unused(left_to_add)\n left_to_add_list = [word[\"word\"] for word in left_to_add_list]\n new_word_list = new_word_list + left_to_add_list\n\n elif len(new_word_list) > amout_of_words_translate:\n new_word_list = new_word_list[:amout_of_words_translate]\n return new_word_list\n except Exception as e:\n return e\n","sub_path":"module_db_test.py","file_name":"module_db_test.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"389245207","text":"import random\n\n\ndef random_heuristic(variables):\n random.shuffle(variables)\n flip = 1\n for varb in variables:\n if flip == 1:\n variables[variables.index(varb)] = -varb\n flip = -flip\n random.shuffle(variables)\n\n return variables\n\n\ndef f(clauses, literal):\n smallest_clauses_size = len(min(clauses, key=len))\n number_of_occurances = 0\n for clause in clauses:\n if len(clause) == smallest_clauses_size:\n if literal in clause: # or -literal in clause:\n number_of_occurances += 1\n return number_of_occurances\n\n\ndef moms_heuristic(atoms, k, clauses): # atoms = argments?, k=2\n max_val = 0\n chosen_literal = None\n for atom in atoms:\n function_res = (f(clauses, atom) + f(clauses, -atom))*(2**k) + (f(clauses, atom) * f(clauses, -atom))\n if function_res > max_val:\n max_val = function_res\n chosen_literal = atom\n return chosen_literal\n\n\ndef jw1_heuristic(literals, clauses):\n j_value = {}\n for literal in literals:\n j_value[literal] = 0\n for clause in clauses:\n if literal in clause:\n j_value[literal] += 2 ** (-len(clause))\n\n chosen_literal = max(j_value, key=j_value.get)\n\n return chosen_literal\n","sub_path":"final_working_version/heur.py","file_name":"heur.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"440375658","text":"import torch\nimport torch.nn as nn\n\n# torchsummary is optional, but really helpful for scalable model !! (see example below)\nfrom torchsummary import summary\ntry:\n # relative import\n from .base_models import BaseModelSRL\n from .base_trainer import BaseTrainer\nexcept:\n from models.base_trainer import BaseTrainer\n\n\nclass NewModelName(BaseModelSRL):\n \"\"\"\n BaseModelSRL: a subclass of nn.Module of Pytorch with \n - getStates (equi to self.forward(x))\n\n NewModelName should act like an encoder in the sense that 'forward' method should take \n an observation (image) as input and return encoded state representation.\n\n \"\"\"\n\n def __init__(self, state_dim, img_shape, *args, **kwargs):\n super().__init__()\n self.state_dim = state_dim # state dimension\n self.img_shape = img_shape # input image shape, assert img_shape is \"channel first\" !!!\n # some example\n self.dummy_model = nn.Sequential(\n nn.Linear(np.prod(self.img_shape), self.state_dim)\n )\n # Note: for Conv2D: the \"same\" padding has the following formula:\n # if dilation=1, default:\n # padding = (kernel_size - stride) / 2\n\n self.dummy_model_cnn = nn.Sequential(\n nn.Conv2d(self.img_shape[0], 32, kernel_size=7, stride=3, padding=2, bias=True),\n nn.MaxPool2d(kernel_size=3, stride=2)\n )\n # Using summary, we can get the output shape of format [-1, channels, high, width] !\n out_shape = summary(self.dummy_model_cnn, img_shape, show=False) # [-1, channels, high, width]\n # Do what you want ....\n\n #######################\n\n def forward(self, x):\n # Define new model here\n return x\n\n\nclass NewModelTrainer(BaseTrainer):\n \"\"\"\n Define the training mechanism of custom model. Build the model by the method \"build_model\".\n Define the training dynamic at batch level by the method \"train_on_batch\"\n\n BaseTrainer is a subclass of nn.Module of Pytorch ! This allows us to call trainer params \n by self.model.parameters() (where 'model' is an instance of NewModelTrainer). \n\n \"\"\"\n\n def __init__(self, state_dim=2, img_shape=(3, 224, 224)):\n super().__init__()\n self.state_dim = state_dim\n self.img_shape = img_shape\n\n def build_model(self, model_type=None):\n self.model = NewModelName(self.state_dim, self.img_shape)\n ## model_type is optional\n # if model_type == \"a\":\n # self.model =\n # elif model_type == \"b\":\n # self.model =\n # else:\n # raise NotImplementedError\n\n def train_on_batch(self, obs, next_obs, optimizer, loss_manager, valid_mode=False, device=torch.device('cpu')):\n \"\"\"\n :param obs: observation (torch.tensor)\n :param next_obs: next observation (torch.tensor)\n :param optimizer: pytorch optimizer\n :param loss_manager: collect loss tensors and loss history\n :param valid_model (bool) validation mode (or training mode)\n return loss: (scalar)\n \"\"\"\n # Define the training mechanism (the additional losses)\n # --------- Here -----------\n # e.g. for autoencoder, self.reconstruct call self.model.decode(self.model.encode(x))\n # decoded_obs = self.reconstruct(obs)\n # decoded_next_obs = self.reconstruct(next_obs)\n # autoEncoderLoss(obs, decoded_obs, next_obs, decoded_next_obs, weight=1.0, loss_manager=loss_manager)\n # # ------------- It's mandatory to update loss/model weights by calling -----------\n loss = self.update_nn_weights(optimizer, loss_manager, valid_mode=valid_mode)\n return loss\n\n def forward(self, x):\n return self.model(x)\n\n\nif __name__ == \"__main__\":\n print(\"Start\")\n","sub_path":"models/new_model_template.py","file_name":"new_model_template.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"324927461","text":"#!/usr/bin/python3.6\n# -*- coding:UTF-8 -*-\nimport math\nimport datetime\nfrom datetime import timedelta\nimport re\nfrom copy import deepcopy\nimport time\nimport pandas as pd\nimport numpy as np\n\n'''\n约定坐标顺序为: member, time,ddtime, level, lat,lon\n添加一个grid类来存储网格的范围包括(起始经纬度、格距、起止时间,时间间隔,起止时效,时效间隔,层次列表,数据成员)\n'''\n\n\nclass grid:\n def __init__(self,glon, glat, gtime=None, gdtime=None,levels=None,members = None):\n\n #提取成员维度信息\n if(members == None):\n self.members =['data0']\n else:\n self.members = members\n ############################################################################\n #提取层次维度信息\n if(levels == None):\n self.levels =[0]\n else:\n self.levels = levels\n ############################################################################\n #提取时间维度信息\n self.stime = np.datetime64('2099-01-01T00:00:00.000000')\n self.etime = np.datetime64('2099-01-01T00:00:00.000000')\n self.dtime_int = 1\n self.dtime_type = \"hour\"\n self.dtimedelta = np.timedelta64(1,'h')\n if(gtime == None):gtime = []\n if len(gtime) == 1:\n if type(gtime[0]) == str:\n num = ''.join([x for x in gtime[0] if x.isdigit()])\n # 用户输入2019041910十位字符,后面补全加0000,为14位统一处理\n if len(num) == 4:\n num += \"0101000000\"\n elif len(num) == 6:\n num +=\"01000000\"\n elif len(num) == 8:\n num +=\"000000\"\n elif len(num) == 10:\n num +=\"0000\"\n elif len(num) == 12:\n num +=\"00\"\n else:\n print(\"输入日期有误,请检查!\")\n # 统一将日期变为datetime类型\n self.stime = datetime.strptime(num, '%Y%m%d%H%M%S')\n self.etime = datetime.strptime(num, '%Y%m%d%H%M%S')\n self.stime = np.datetime64(self.stime)\n self.etime = np.datetime64(self.etime)\n else:\n self.stime = gtime[0]\n self.etime = gtime[0]\n self.dtime_int = 1\n self.dtime_type = \"hour\"\n self.dtimedelta = np.timedelta64(0,'h')\n elif len(gtime) ==3:\n num1 =[]\n if type(gtime[0]) == str:\n for i in range (0,2):\n num = ''.join([x for x in gtime[i] if x.isdigit()])\n #用户输入2019041910十位字符,后面补全加0000,为14位统一处理\n if len(num) == 4:\n num1.append(num + \"0101000000\")\n elif len(num) == 6:\n num1.append(num + \"01000000\")\n elif len(num) == 8:\n num1.append(num + \"000000\")\n elif len(num) == 10:\n num1.append(num + \"0000\")\n elif len(num) == 12:\n num1.append(num + \"00\")\n elif len(num) == 14:\n num1.append(num)\n else:\n print(\"输入日期有误,请检查!\")\n #统一将日期变为datetime类型\n self.stime = datetime.strptime(num1[0], '%Y%m%d%H%M%S')\n self.etime = datetime.strptime(num1[1], '%Y%m%d%H%M%S')\n self.stime = np.datetime64(self.stime)\n self.etime = np.datetime64(self.etime)\n else:\n self.stime = gtime[0]\n self.etime = gtime[1]\n\n if type(gtime[2]) == str:\n self.dtime_int = re.findall(r\"\\d+\", gtime[2])[0]\n dtime_type = re.findall(r\"\\D+\", gtime[2])[0]\n if dtime_type == 'h':\n self.dtime_type =\"hour\"\n self.dtimedelta = np.timedelta64(self.dtime_int,'h')\n elif dtime_type == 'd':\n self.dtime_type =\"Day\"\n self.dtimedelta = np.timedelta64(self.dtime_int, 'D')\n elif dtime_type == 'm':\n self.dtime_type =\"minute\"\n self.dtimedelta = np.timedelta64(self.dtime_int, 'm')\n else:\n self.dtimedelta = gtime[2]\n seconds = gtime[2].total_seconds()\n if seconds % 3600 == 0:\n self.dtime_type = \"hour\"\n self.dtime_int = int(seconds/3600)\n else:\n self.dtime_type = \"minute\"\n self.dtime_int = int(seconds / 60)\n self.gtime = [self.stime,self.etime,str(self.dtime_int) + self.dtime_type]\n self.stime_str = str(self.stime).replace(\"-\",\"\").replace(\" \",\"\").replace(\":\",\"\").replace(\"T\",\"\")[0:14]\n self.etime_str = str(self.etime).replace(\"-\", \"\").replace(\" \", \"\").replace(\":\", \"\").replace(\"T\", \"\")[0:14]\n self.dtime_str = str(self.dtime_int) + self.dtime_type\n\n ############################################################################\n #提取预报时效维度信息\n\n self.sdt_int = 0\n self.edt_int = 0\n self.ddt_int = 1\n self.sdtimedelta = np.timedelta64(0, 'h')\n self.edtimedelta = np.timedelta64(0, 'h')\n self.ddtimedelta = np.timedelta64(1, 'h')\n self.gdtime_type = \"hour\"\n if (gdtime == None): gdtime = []\n if len(gdtime)==1:\n num2 = []\n if type(gdtime[0]) == str:\n for i in range(1):\n gdt_num = ''.join([x for x in gdtime[i] if x.isdigit()])\n num2.append(gdt_num)\n self.sdt_int = int(num2[0])\n self.edt_int = int(num2[0])\n self.ddt_int = 1\n # 提取出dtime_type类型\n TIME_type = re.findall(r\"\\D+\", gdtime[2])[0]\n if TIME_type == 'h':\n self.gdtime_type = \"hour\"\n self.sdtimedelta = np.timedelta64(self.sdt_int, 'h')\n self.edtimedelta = np.timedelta64(self.edt_int, 'h')\n self.ddtimedelta = np.timedelta64(self.ddt_int, 'h')\n elif TIME_type == 'd':\n self.gdtime_type = \"Day\"\n self.sdtimedelta = np.timedelta64(self.sdt_int, 'D')\n self.edtimedelta = np.timedelta64(self.edt_int, 'D')\n self.ddtimedelta = np.timedelta64(self.edt_int, 'D')\n elif TIME_type == 'm':\n self.gdtime_type = \"minute\"\n self.sdtimedelta = np.timedelta64(self.sdt_int, 'm')\n self.edtimedelta = np.timedelta64(self.edt_int, 'm')\n self.ddtimedelta = np.timedelta64(self.edt_int, 'm')\n else:\n if isinstance(gdtime[0],datetime.timedelta):\n seconds = gdtime[0].total_seconds()\n else:\n seconds = gdtime[0].astype('timedelta64[s]')/np.timedelta64(1, 's')\n\n if seconds % 3600 == 0:\n self.sdt_int = int(seconds / 3600)\n self.edt_int = int(seconds / 3600)\n self.ddt_int = 1\n self.gdtime_type = \"hour\"\n self.sdtimedelta = gdtime[0]\n self.edtimedelta = gdtime[0]\n\n else:\n self.dtime_type = \"minute\"\n self.sdt_int = int(seconds / 60)\n self.edt_int = int(seconds / 60)\n self.ddt_int = 1\n self.sdtimedelta = gdtime[0]\n self.edtimedelta = gdtime[0]\n self.ddtimedelta = np.timedelta64(1, 'h')\n elif len(gdtime) == 3:\n num2 = []\n if type(gdtime[0]) == str:\n for i in range(0, 3):\n gdt_num = ''.join([x for x in gdtime[i] if x.isdigit()])\n num2.append(gdt_num)\n self.sdt_int = int(num2[0])\n self.edt_int = int(num2[1])\n self.ddt_int = int(num2[2])\n #提取出dtime_type类型\n TIME_type = re.findall(r\"\\D+\", gdtime[2])[0]\n if TIME_type == 'h':\n self.gdtime_type = \"hour\"\n self.sdtimedelta = np.timedelta64(self.sdt_int, 'h')\n self.edtimedelta = np.timedelta64(self.edt_int, 'h')\n self.ddtimedelta = np.timedelta64(self.ddt_int, 'h')\n elif TIME_type == 'd':\n self.gdtime_type = \"Day\"\n self.sdtimedelta = np.timedelta64(self.sdt_int, 'D')\n self.edtimedelta = np.timedelta64(self.edt_int, 'D')\n self.ddtimedelta = np.timedelta64(self.ddt_int, 'D')\n elif TIME_type == 'm':\n self.gdtime_type = \"minute\"\n self.sdtimedelta = np.timedelta64(self.sdt_int, 'm')\n self.edtimedelta = np.timedelta64(self.edt_int, 'm')\n self.ddtimedelta = np.timedelta64(self.ddt_int, 'm')\n else:\n seconds = gdtime[2].total_seconds()\n if seconds % 3600 == 0:\n seconds1 = gdtime[0].total_seconds()\n seconds2 = gdtime[1].total_seconds()\n self.sdt_int = int(seconds1 / 3600)\n self.edt_int = int(seconds2 / 3600)\n self.ddt_int = int(seconds / 3600)\n self.gdtime_type = \"hour\"\n self.sdtimedelta = gdtime[0]\n self.edtimedelta = gdtime[0]\n\n else:\n self.dtime_type = \"minute\"\n seconds1 = gdtime[0].total_seconds()\n seconds2 = gdtime[1].total_seconds()\n self.sdt_int = int(seconds1 / 60)\n self.edt_int = int(seconds2 / 60)\n self.ddt_int = int(seconds / 60)\n self.sdtimedelta = gdtime[0]\n self.edtimedelta = gdtime[1]\n self.ddtimedelta = gdtime[2]\n\n self.gdtime = [str(self.sdt_int),str(self.edt_int), str(self.ddt_int)+ self.gdtime_type[0]]\n\n ############################################################################\n #提取经度信息\n\n self.slon = glon[0]\n self.elon = glon[1]\n self.dlon = glon[2]\n nlon = 1 + (self.elon - self.slon) / self.dlon\n error = abs(round(nlon) - nlon)\n if (error > 0.01):\n self.nlon = math.ceil(nlon)\n else:\n self.nlon = int(round(nlon))\n self.elon = self.slon + (nlon - 1) * self.dlon\n self.glon = [self.slon,self.elon,self.dlon]\n\n ############################################################################\n #提取经度信息\n self.slat = glat[0]\n self.elat = glat[1]\n self.dlat = glat[2]\n nlat = 1 + (self.elat - self.slat) / self.dlat\n error = abs(round(nlat) - nlat)\n if (error > 0.01):\n self.nlat = math.ceil(nlat)\n else:\n self.nlat = int(round(nlat))\n self.elat = self.slat + (nlat - 1) * self.dlat\n self.glat = [self.slat,self.elat,self.dlat]\n\n\n\n\n def copy(self):\n return deepcopy(self)\n\n #reset的作用是把网格的坐标间隔统一为正数。\n def reset(self):\n if (self.dlon > 0 and self.dlat > 0):\n pass\n if (self.dlat < 0):\n tran = self.slat\n self.slat = self.elat\n self.elat = tran\n self.dlat = abs(self.dlat)\n if (self.dlon < 0):\n tran = self.slon\n self.slon = self.elon\n self.elon = tran\n self.dlon = abs(self.dlon)\n return\n\n # tostring 的作用是重置系统自动的函数,在print(grid) 的时候可以很整齐的看到所有信息\n def tostring(self):\n grid_str = \"\"\n grid_str += \"members:\" + str(self.members) +\"\\n\"\n grid_str += \"levels:\" + str(self.levels) + \"\\n\"\n grid_str += \"gtime:\" + str([self.stime_str,self.etime_str,self.dtime_str]) + \"\\n\"\n grid_str += \"gdtime:\" + str(self.gdtime) +\"\\n\"\n grid_str += \"glon:\" + str(self.glon) + \"\\n\"\n grid_str += \"glat:\" + str(self.glat) + \"\\n\"\n return grid_str\ndef get_grid_of_data(grid_data0):\n #print(grid_data0)\n members = grid_data0['member'].values\n levels = grid_data0['level'].values\n times = grid_data0['time'].values\n print(times)\n if(len(times)>1):\n gtime = [times[0],times[-1],times[1]-times[0]]\n elif len(times) == 1:\n gtime = times\n else:\n gtime = None\n\n dtimes = grid_data0['dtime'].values\n if(len(dtimes)>1):\n gdt = [dtimes[0],dtimes[-1],dtimes[1]-dtimes[0]]\n elif len(dtimes) ==1:\n gdt = dtimes\n else:\n gdt = None\n #print(grid_data0)\n lons = grid_data0['lon'].values\n glon = [lons[0],lons[-1],lons[1]-lons[0]]\n lats = grid_data0['lat'].values\n glat = [lats[0],lats[-1],lats[1]-lats[0]]\n grid01 = grid(glon, glat, gtime, gdt, levels, members)\n return grid01\n\n","sub_path":"build/lib/nmc_verification/nmc_vf_base/basicdata/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":13407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"100674444","text":"import os\nimport configparser\nfrom . import const, exception\n\n\nclass Config:\n \"\"\"\n Manager of cmdnote config\n \"\"\"\n\n def __init__(self, config_file=const.CONFIG_FILE):\n if not os.path.isfile(config_file):\n raise exception.ConfigFileNotFoundError('Config file not found', config_file)\n self.config_file = config_file\n self.config = configparser.ConfigParser()\n\n def get_configs(self):\n \"\"\"Get configs from config file.\"\"\"\n self.config.read(self.config_file)\n default = self.config[self.config.default_section]\n return dict(default)\n\n def get_config(self, key, default=None):\n \"\"\"Get a config by key from config file.\"\"\"\n configs = self.get_configs()\n return configs.get(key, default)\n\n def set_configs(self, configs):\n \"\"\"Set configs in config file.\"\"\"\n default = self.config[self.config.default_section]\n for key, value in configs.items():\n default[key] = str(value)\n with open(self.config_file, 'w') as f:\n self.config.write(f)\n\n def set_config(self, key, value):\n \"\"\"Set a config by key in config file.\"\"\"\n configs = self.get_configs()\n configs[key] = value\n self.set_configs(configs)\n","sub_path":"cmdnote/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"539987570","text":"import autograd.numpy as np\nimport autograd.numpy.random as npr\n\nimport torch\n\nfrom sds import rARHMM\nfrom sds.utils import sample_env\n\n\nif __name__ == \"__main__\":\n\n np.random.seed(1337)\n torch.manual_seed(1337)\n\n import matplotlib.pyplot as plt\n\n from hips.plotting.colormaps import gradient_cmap\n import seaborn as sns\n\n sns.set_style(\"white\")\n sns.set_context(\"talk\")\n\n color_names = [\"windows blue\", \"red\", \"amber\",\n \"faded green\", \"dusty purple\", \"orange\"]\n\n colors = sns.xkcd_palette(color_names)\n cmap = gradient_cmap(colors)\n\n import pickle\n import gym\n import rl\n\n env = gym.make('Pendulum-RL-v0')\n env._max_episode_steps = 5000\n env.seed(1337)\n\n nb_rollouts, nb_steps = 25, 200\n dm_obs = env.observation_space.shape[0]\n dm_act = env.action_space.shape[0]\n\n obs, act = sample_env(env, nb_rollouts, nb_steps)\n\n nb_states = 5\n obs_prior = {'mu0': 0., 'sigma0': 1.e12, 'nu0': dm_obs + 2, 'psi0': 1.e-4}\n # trans_kwargs = {'hidden_layer_sizes': (10,)}\n trans_kwargs = {'degree': 3}\n rarhmm = rARHMM(nb_states, dm_obs, dm_act, trans_type='poly',\n obs_prior=obs_prior, trans_kwargs=trans_kwargs)\n rarhmm.initialize(obs, act)\n\n lls = rarhmm.em(obs, act, nb_iter=50, prec=0., verbose=True)\n\n plt.figure(figsize=(5, 5))\n plt.plot(lls)\n plt.show()\n\n plt.figure(figsize=(8, 8))\n idx = npr.choice(nb_rollouts)\n _, sample_obs = rarhmm.sample([act[idx]], horizon=[nb_steps])\n plt.plot(sample_obs[0])\n plt.show()\n","sub_path":"examples/pendulum/rarhmm.py","file_name":"rarhmm.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"77737173","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License (MIT)\nCopyright (c) 2017 Rapptz\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n---\n\nThis whole cog is basically copied from:\nhttps://github.com/Rapptz/RoboDanny/\n\"\"\"\n\nfrom lxml import etree\nimport discord\nfrom discord.ext import commands\nimport re\n\n\ndef finder(text, collection, *, key=None, lazy=True):\n \"\"\"\n\n \"\"\"\n suggestions = []\n text = str(text)\n pat = '.*?'.join(map(re.escape, text))\n regex = re.compile(pat, flags=re.IGNORECASE)\n for item in collection:\n to_search = key(item) if key else item\n r = regex.search(to_search)\n if r:\n suggestions.append((len(r.group()), r.start(), item))\n\n def sort_key(tup):\n if key:\n return tup[0], tup[1], key(tup[2])\n return tup\n\n if lazy:\n return (z for _, _, z in sorted(suggestions, key=sort_key))\n else:\n return [z for _, _, z in sorted(suggestions, key=sort_key)]\n\n\nclass RtfmCog(commands.Cog):\n \"\"\"\n Cog to have fancy discordpy doc embeds\n thanks danny :)\n \"\"\"\n def __init__(self, bot):\n self.bot = bot\n self._cache = {}\n\n async def build_rtfm_lookup_table(self):\n cache = {}\n page_types = ('https://discordpy.readthedocs.io/en/latest/api.html',\n 'https://discordpy.readthedocs.io/en/latest/ext/commands/api.html')\n for page in page_types:\n async with self.bot.aiohttp_session.get(page) as resp:\n if resp.status != 200:\n return -1\n text = await resp.text(encoding=\"UTF-8\")\n root = etree.fromstring(text, etree.HTMLParser())\n nodes = root.findall(\".//dt/a[@class='headerlink']\")\n for node in nodes:\n href = node.get('href', '')\n as_key = href.replace('#discord.', '').replace('ext.commands.', '')\n cache[as_key] = page + href\n self._cache = cache\n return 1\n\n async def do_rtfm(self, ctx, obj):\n base_url = 'https://discordpy.readthedocs.org/en/rewrite/'\n\n if obj is None:\n await ctx.send(base_url)\n return\n\n if len(self._cache) == 0:\n await ctx.trigger_typing()\n await self.build_rtfm_lookup_table()\n\n # identifiers don't have spaces\n obj = obj.replace(' ', '_')\n\n pit_of_success_helpers = {\n 'vc': 'VoiceClient',\n 'msg': 'Message',\n 'color': 'Colour',\n 'perm': 'Permissions',\n 'channel': 'TextChannel',\n 'chan': 'TextChannel',\n }\n\n # point the abc.Messageable types properly:\n q = obj.lower()\n for name in dir(discord.abc.Messageable):\n if name[0] == '_':\n continue\n if q == name:\n obj = f'abc.Messageable.{name}'\n break\n\n def replace(o):\n return pit_of_success_helpers.get(o.group(0), '')\n\n pattern = re.compile('|'.join(fr'\\b{k}\\b' for k in pit_of_success_helpers.keys()))\n obj = pattern.sub(replace, obj)\n\n cache = list(self._cache.items())\n\n matches = finder(obj, cache, key=lambda t: t[0], lazy=False)[:5]\n\n e = discord.Embed(colour=discord.Colour.blurple())\n if len(matches) == 0:\n return await ctx.send('Could not find anything. Sorry.')\n\n e.description = '\\n'.join(f'[{key}]({url})' for key, url in matches)\n e.set_footer(text=\"Based on https://github.com/Rapptz/RoboDanny/\")\n await ctx.send(embed=e)\n\n @commands.command()\n async def rtfm(self, ctx, *, obj: str = None):\n await self.do_rtfm(ctx, obj)\n\n @commands.command(aliases=[\"pydocs\"])\n async def pydoc(self, ctx, *, obj: str = None):\n if obj is None:\n return await ctx.send(\"https://docs.python.org/3/\")\n obj = obj.replace(\" \", \"+\")\n return await ctx.send(f\"https://docs.python.org/3/search.html?q={obj}\")\n\n\ndef setup(bot):\n bot.add_cog(RtfmCog(bot))\n","sub_path":"cogs/rtfm.py","file_name":"rtfm.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"460862298","text":"from flask import Flask,jsonify,request,url_for,make_response,g,render_template,Response,abort,redirect,flash\nfrom flask.ext.httpauth import HTTPBasicAuth\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom oauth import OAuthSignIn\nfrom flask.ext.login import LoginManager, UserMixin, login_user, logout_user,\\\n current_user\n\n\napp = Flask(__name__)\n\napp.config.from_object('config')\n\napp.config['SECRET_KEY'] = 'top secret!'\napp.config['OAUTH_CREDENTIALS'] = {\n 'facebook': {\n 'id': '1499036657056554',\n 'secret': '3e5ab24b3a181b79fabe61262b27994e'\n },\n 'twitter': {\n 'id': '3RzWQclolxWZIMq5LJqzRZPTl',\n 'secret': 'm9TEd58DSEtRrZHpz2EjrV9AhsBRxKMo8m3kuIZj3zLwzwIimt'\n }\n}\n\ndb = SQLAlchemy(app)\n\nauth = HTTPBasicAuth()\n\n\nfrom models import *\n\n\n@auth.error_handler\ndef unauthorizedaccess():\n return make_response(jsonify({'error':'Unauthorized access'}),401)\n\n\n@app.errorhandler(400)\ndef not_found(error):\n return make_response(jsonify( { 'error': 'Bad request' } ), 400)\n\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify( { 'error': 'Not found' } ), 404)\n\n\n\ntasks1 = [\n {\n 'nickname' : u'daksh',\n 'email':u'daksh@gmail.com',\n 'id' : 1,\n\n },\n {\n\n 'nickname' : u'nikhil',\n 'email':u'nikhil@gmail.com',\n 'id' : 2,\n\n }\n]\n\n'''\n@app.route('/api/register',methods = ['POST'])\ndef registration():\n username = request.json.get('username')\n password = request.json.get('password')\n email = request.json.get('email')\n\n if username in None or password is None or email is None:\n return jsonify({'error' : 'content missing'})\n if User.query.filter_by(nickname = username).first is not None:\n return jsonify({'error' : 'username taken'})\n\n user = User(nickname = username,password = password,email = email)\n db.session.add(user)\n db.session.commit()\n return jsonify({'nickname':user.nickname,'email':user.email})\n'''\n\n#register funciton\n\n@app.route('/api/checkregister',methods=['POST'])\ndef checkregister():\n username = request.json.get('username')\n password = request.json.get('password')\n email = request.json.get('email')\n tempStr = \"http://localhost:5000/static/img/slate.jpg\"\n if username is None or password is None or email is None:\n abort(403)\n if User.query.filter_by(nickname=username).first() is not None:\n abort(403)\n user = User(nickname=username,password=password,email=email,imageurl = tempStr)\n db.session.add(user)\n p = user.follow(user)\n db.session.add(p)\n db.session.commit()\n return jsonify({'done':'hello'})\n\n\n\n\n# login function\n@auth.verify_password\ndef verify_password(username, password):\n user = User.query.filter_by(nickname = username).first()\n if not user or not user.verify_password(password):\n abort(403)\n g.user = user\n return True\n\n#check api source\n@app.route('/api/resource')\n@auth.login_required\ndef get_resource():\n return jsonify({ 'data': 'Hello, %s!' % g.user.nickname})\n\n\n#for testing tasks\n@app.route('/api/tasks')\ndef displayTasks():\n return jsonify({'tasks': tasks1,'success':1})\n\ndef checkfollowstatus(temp):\n if g.user.is_following(temp):\n return True\n return False\n\n\n#list all the users\n@app.route('/api/search')\n@auth.login_required\ndef hello_world():\n result = User.query.all()\n obj = {}\n post_list = []\n post_listnew = []\n #x = 0\n for i in range(0,len(result)):\n obj[\"nickname\"] = result[i].nickname\n obj[\"email\"] = result[i].email\n obj[\"id\"] = result[i].id\n obj[\"done\"] = checkfollowstatus(result[i])\n post_list.append(obj)\n obj = {}\n\n for key in post_list:\n if key[\"id\"] == g.user.id:\n post_list.remove(key)\n\n for key in User.query.all():\n post_listnew.append(key.__dict__)\n\n cols = ['nickname', 'email','id']\n data = User.query.all()\n result1 = [{col: getattr(d, col) for col in cols} for d in data]\n result2 = []\n obj = {}\n for d in data:\n for col in cols:\n obj[col] = getattr(d,col)\n result2.append(obj)\n obj = {}\n\n if len(result1) == 0:\n abort(403)\n return jsonify({'tasks': post_list})\n\n\n#add post to the database\n@app.route('/api/addposts',methods=['POST'])\n@auth.login_required\ndef addPost():\n tempStr = request.json.get('body')\n tempTime = datetime.utcnow()\n p = Post(body = tempStr,author = g.user,timestamp=tempTime)\n db.session.add(p)\n db.session.commit()\n c = Post.query.filter_by(user_id = g.user.id).all()\n tempNo = len(c)\n return jsonify({'success':1})\n\n\n\n\n\n\n\n\n\n\n\n#displaying of posts\n@app.route('/api/getposts',methods=['GET'])\n@auth.login_required\ndef displayPost():\n tempobj = {}\n userlist = []\n u = User.query.all()\n tempcols = ['id','nickname']\n for key in u:\n for t in tempcols:\n tempobj[t] = getattr(key,t)\n userlist.append(tempobj)\n tempobj = {}\n print(userlist)\n obj = {}\n tempList = []\n query = g.user.followed_posts().all()\n cols = ['id','body','timestamp','editedtimestamp','user_id']\n for key in query:\n for col in cols:\n obj[col] = getattr(key,col)\n obj[\"author\"] = getnickname(obj[\"user_id\"],userlist)\n tempList.append(obj)\n obj = {}\n print(tempList)\n return jsonify({'templist':tempList,'success':1})\n\n\n#follow button\n@app.route('/api/follow',methods=['POST'])\n@auth.login_required\ndef follow():\n tempStr = request.json.get('username')\n findUser = User.query.filter_by(nickname = tempStr).first()\n if findUser is None:\n return jsonify({'error':'No user found','success':0})\n if findUser == g.user:\n return jsonify({'error':'apne aap ko follow','success':0})\n temp = g.user.follow(findUser)\n if temp is None:\n abort(403)\n db.session.add(temp)\n db.session.commit()\n return jsonify({'success':'ho gya kaam','success':1})\n\n\n\n#unfollow button\n@app.route('/api/unfollow',methods=['POST'])\n@auth.login_required\ndef unfollow():\n tempStr = request.json.get('username')\n findUser = User.query.filter_by(nickname = tempStr).first()\n if findUser is None:\n return jsonify({'error':'No user found','success':0})\n if findUser == g.user:\n return jsonify({'error':'apne aap ko unfollow','success':0})\n temp = g.user.unfollow(findUser)\n if temp is None:\n return jsonify({'error':'ho gya bhai unfollow','success':0})\n db.session.add(temp)\n db.session.commit()\n return jsonify({'success':1})\n\n\n#edit the posts\n@app.route('/api/editpost',methods=['POST'])\n@auth.login_required\ndef editpost():\n tempNo = request.json.get('id')\n query = Post.query.filter_by(id = tempNo).first()\n if query is None or query.user_id != g.user.id:\n abort(403)\n query.body = request.json.get('body')\n tempTime = datetime.utcnow()\n query.editedtimestamp = tempTime\n db.session.commit()\n return jsonify({'success':1})\n\n\n\n#get user only post\n@app.route('/api/getuseronlypost',methods=['GET'])\n@auth.login_required\ndef getuseronlypost():\n query = Post.query.filter(\n Post.user_id == g.user.id).order_by(\n Post.timestamp.desc())\n\n query1 = Post.query.filter_by(user_id = g.user.id).order_by(Post.timestamp.desc()).all()\n if query is None:\n abort(403)\n\n tempList = []\n obj = {}\n cols = ['id','body','timestamp','editedtimestamp']\n for key in query:\n for col in cols:\n obj[col] = getattr(key,col)\n tempList.append(obj)\n obj = {}\n print(tempList)\n return jsonify({'templist':tempList,'success':1})\n\n\n\ndef getnickname(tempid,list):\n for key in list:\n if key[\"id\"] == tempid:\n return key[\"nickname\"]\n return \"\"\n\n\n#get posts of followed user .\n@app.route('/api/followeduserposts',methods=['POST'])\n@auth.login_required\ndef getfolloweduserposts():\n tempid = request.json.get('id')\n findUser = User.query.filter_by(id = tempid).first()\n if findUser is None:\n abort(403)\n if g.user.is_following(findUser) == False:\n abort(403)\n posts = Post.query.filter_by(user_id = tempid).order_by(Post.timestamp.desc()).all()\n obj = {}\n list = []\n cols = ['id','body','timestamp','editedtimestamp']\n for key in posts:\n for col in cols:\n obj[col] = getattr(key,col)\n list.append(obj)\n obj = {}\n return jsonify({'templist':list})\n\n\n\n#delete the posts\n@app.route('/api/deleteposts',methods=['POST'])\n@auth.login_required\ndef deletepost():\n tempid = request.json.get('id')\n query = Post.query.filter_by(id = tempid).first();\n if query is None:\n abort(403)\n db.session.delete(query)\n db.session.commit()\n return jsonify({'success':1})\n\n\n\n\n\n\n\n\n#new function added here .\n#showing of pofile of other users\n@app.route('/api/showuserprofile',methods=['POST'])\n@auth.login_required\ndef showuserprofile():\n tempid = request.json.get('id')\n #find user profile data\n findUser = User.query.filter_by(id = tempid).all()\n obj = {}\n list = []\n cols = ['name','nickname','email']\n for key in findUser:\n for col in cols:\n obj[col] = getattr(key,col)\n list.append(obj)\n obj = {}\n\n list1 = []\n obj = {}\n cols = ['id','body','timestamp','editedtimestamp']\n findUser = Post.query.filter_by(user_id = tempid).order_by(Post.timestamp.desc()).all()\n for key in findUser:\n for col in cols:\n obj[col] = getattr(key,col)\n list1.append(obj)\n obj = {}\n\n # Add intrest function .\n list2 = []\n obj = {}\n cols = ['body','id']\n findUser = Intrest.query.filter_by(user_id1 = tempid).all()\n for key in findUser:\n for col in cols:\n obj[col] = getattr(key,col)\n list2.append(obj)\n obj = {}\n return jsonify({'templist':list,'templist1':list1,'templist2':list2})\n\n\n\n\n#for recommendation algorithm .\n@app.route('/api/recommendation')\n@auth.login_required\ndef recommendationalgo():\n findUser = g.user.followed_posts().all()\n findInterst = Intrest.query.all()\n tempIntrest = []\n obj = {}\n for key in findUser:\n tempNo = getattr(key,\"id\")\n for key1 in findInterst:\n if getattr(key1,\"user_id1\") == tempNo:\n obj[\"id\"] = getattr(key1,\"id\")\n obj[\"body\"] = getattr(key1,\"body\")\n obj[\"user_id1\"] = getattr(key1,\"user_id1\")\n tempIntrest.append(obj)\n obj = {}\n return jsonify({'tempInterst':tempIntrest})\n\n\n##################################\n#get my profile\n@app.route('/api/getmyprofile')\n@auth.login_required\ndef getmyprofilefunction():\n findUser = User.query.filter_by(id = g.user.id).all()\n cols = ['name','nickname','about_me','imageurl']\n list = []\n obj = {}\n for key in findUser:\n for col in cols:\n obj[col] = getattr(key,col)\n list.append(obj)\n obj = {}\n findIntrest = Intrest.query.filter_by(user_id1 = g.user.id).all()\n obj = {}\n list1 = []\n for key in findIntrest:\n obj[\"body\"] = getattr(key,\"body\")\n list1.append(obj)\n obj = {}\n return jsonify({\"tlist\":list,\"tlist1\":list1,\"imageurl\":\"http://localhost:5000/static/img/slate.jpg\"})\n\n\n\n#########################\n@app.route('/api/getphoto')\n@auth.login_required\ndef getphotouser():\n return jsonify({\"photo\":g.user.imageurl})\n\n\n\n###############################\n###message functions\n@app.route('/api/entermessage',methods=['POST'])\n@auth.login_required\ndef enterMessage():\n findId = request.json.get('id')\n tempBody = request.json.get('body')\n if id is None or tempBody is None:\n abort(403)\n tempTime = datetime.utcnow()\n x = Message(body = tempBody,timestamp = tempTime,sender = g.user.id,recevier = findId)\n db.session.add(x)\n db.session.commit()\n return jsonify({'success':1})\n\n\n\n##############################\n@app.route('/api/getmessages')\n@auth.login_required\ndef getMessageFunction():\n findUser = Message.query.filter_by(sender = g.user.id).all()\n q = User.query.all()\n obj = {}\n for key in q:\n obj[getattr(key,\"id\")] = getattr(key,\"nickname\")\n\n list = []\n object1 = {}\n for key1 in findUser:\n object1[\"recevier\"] = obj.get(getattr(key1,\"recevier\"))\n object1[\"body\"] = getattr(key1,\"body\")\n list.append(object1)\n object1 = {}\n\n return jsonify({'list':list})\n\n\n\n\n\n#add interst to the database\n@app.route('/api/addintrest',methods=['POST'])\n@auth.login_required\ndef addIntrest():\n tempStr = request.json.get('body')\n p = Intrest(body = tempStr,author = g.user)\n db.session.add(p)\n db.session.commit()\n c = Post.query.filter_by(user_id = g.user.id).all()\n tempNo = len(c)\n return jsonify({'success':1})\n\n\n\n\n@app.route('/api/changeaboutme',methods=['POST'])\n@auth.login_required\ndef changeaboutfunction():\n tempStr = request.json.get('body')\n if tempStr is None or tempStr == \"\":\n abort(403)\n findUser = User.query.filter_by(id = g.user.id).first()\n findUser.about_me = tempStr\n db.session.commit()\n return jsonify({'success':'1'})\n\n\n###########################\n###edit name in the database .\n@app.route('/api/changename',methods=['POST'])\n@auth.login_required\ndef changenamefunction():\n tempStr = request.json.get('body')\n if tempStr is None or tempStr == \"\":\n abort(403)\n findUser = User.query.filter_by(id = g.user.id).first()\n findUser.name = tempStr\n db.session.commit()\n return jsonify({'success':'1'})\n\n\n\n\n\n\nlm = LoginManager(app)\nlm.login_view = 'index'\n\n\n\n####### Facebook login #############\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\n@app.route('/authorize/')\ndef oauth_authorize(provider):\n if not current_user.is_anonymous:\n return redirect(url_for('index'))\n oauth = OAuthSignIn.get_provider(provider)\n return oauth.authorize()\n\n\n\n@app.route('/callback/')\ndef oauth_callback(provider):\n if not current_user.is_anonymous:\n print(\"hello world\")\n return redirect(url_for('index'))\n oauth = OAuthSignIn.get_provider(provider)\n\n return redirect(url_for('index'))\n\n\nif __name__ == '__main__':\n app.run(debug = True)\n","sub_path":"minorproject.py","file_name":"minorproject.py","file_ext":"py","file_size_in_byte":14482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"561736574","text":"# 目标邮箱是随机生成一个9位数QQ号邮箱\n\nimport string\nimport random\n\ndef qq_email():\n digits = string.digits\n num = \"\"\n for i in range(1, 9):\n i += 1\n num += random.choice(digits)\n # print(num)\n qqEmail = num + \"@qq.com\"\n return qqEmail\n\n # qqlist = [qqEmail, '527539087@qq.com', '406556942@qq.com']\n # return qqlist\n\ndef random_char():\n letters = string.ascii_letters\n randsub = ''\n for i in range(1, 16):\n randsub += random.choice(letters)\n return randsub\n","sub_path":"Sendmail/RandomQQEmail.py","file_name":"RandomQQEmail.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"408740392","text":"import numpy as np\nimport matplotlib as plt\n\n#input\nmass = float(input(\"insert the value of the mass of the cannon ball in kg: \"))\n\n#parameters\nradius=0.08\nvel = 100\ntheta=np.pi/6\nrho=1.22\nC=0.47\ng=9.81\nconst=(np.pi/2)*(radius**2)*rho*C/(mass)\n\n#initial condition\nr=np.array([0,100*np.cos(theta),0,100*np.sin(theta)], float)\n\n#ODE\ndef f(r,t):\n x=r[0]\n vx=r[1]\n y=r[2]\n vy=r[3]\n fx=vx\n fy=vy\n ax=-const*vx*np.sqrt(vx**2+vy**2)\n ay=-g-const*vy*np.sqrt(vx**2+vy**2)\n return np.array([fx,ax,fy,ay])\n\n\n#time steps\na=0.0\nb=10\nN=1000\nstep = (b-a)/N\ntpoints = np.linspace(a,b,N)\n\nxpoints = []\nvxpoints=[]\nypoints=[]\nvypoints=[]\n\n#solve ODE\nfor t in tpoints:\n xpoints.append(r[0])\n vxpoints.append(r[1])\n ypoints.append(r[2])\n vypoints.append(r[3])\n k1 = step*f(r,t)\n k2 = step*f(r+0.5*k1,t+0.5*step)\n k3 = step*f(r+.5*k2,t+.5*step)\n k4 = step*f(r+k3,t+step)\n r += (k1+2*k2+2*k3+k4)/6\n\n#plot \nplt.pyplot.plot(xpoints,ypoints)\nplt.pyplot.xlabel(\"distance\")\nplt.pyplot.ylabel(\"height\")\nplt.pyplot.show()","sub_path":"Homework5_8_7_ODE.py","file_name":"Homework5_8_7_ODE.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"539461145","text":"\"\"\"Module for handling errors caught by discord.ext.commands.CommandError.\"\"\"\n\nimport sys\nimport traceback\n\nimport discord\nfrom discord.ext import commands\nimport auth\n\nfrom vars import bot, get_prefix\n\n\nclass CommandErrorHandler(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n \"\"\"The event triggered when an error is raised while invoking a command.\"\"\"\n error = getattr(error, 'original', error)\n\n # skip if command is invalid\n if isinstance(error, commands.CommandNotFound):\n return\n\n elif isinstance(error, auth.RegistrationError):\n return await ctx.send(error)\n\n elif isinstance(ctx.channel, discord.channel.DMChannel):\n return await ctx.send(f\"**{ctx.command}** must be used in a server channel\")\n\n elif isinstance(error, commands.MissingRequiredArgument):\n return await ctx.send(f\"Your command is missing a required argument\")\n\n elif isinstance(error, commands.UserInputError):\n return await ctx.send(error)\n\n # If error is not caught then show the ugly error code\n error_embed = discord.Embed(title=f'Your command: {ctx.message.content}',\n description=str(error),\n color=discord.Colour.red())\n\n await ctx.send(embed=error_embed)\n\n # send to devs too\n # error_channel = bot.get_channel(692427334803914813)\n # await error_channel.send(embed=error_embed)\n\n print(f'Ignoring exception in command {ctx.command}:', file=sys.stderr)\n traceback.print_exception(\n type(error), error, error.__traceback__, file=sys.stderr)\n\n\ndef setup(bot):\n bot.add_cog(CommandErrorHandler(bot))\n","sub_path":"cogs/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"6083135","text":"from microbit import *\nimport radio\nimport music\n\nradio.config(channel=86)\nradio.on()\n\n\ndef send_board(board):\n \"\"\"send board to display and to other micro:bit\"\"\"\n radio.send(board)\n display.show(Image(board))\n\n\ndef get_board_pixel(x, y, board):\n pos = get_pos(x, y)\n value = board[pos]\n return value\n\n\ndef set_board_pixel(x, y, board, colour):\n pos = get_pos(x, y)\n board = board[:pos] + str(colour) + board[pos+1:]\n return board\n\n\ndef get_pos(x, y):\n pos = (6*y) + x\n return pos\n\n\ndef fall(x, y, board, colour):\n set_board_pixel(x, y, board, colour)\n send_board(board)\n falling = True\n while falling:\n if y >= 4 or get_board_pixel(x, y+1, board) != \"0\": # if above another 'couner' or at bottom of LED matrix\n falling = False\n else:\n y += 1\n board = set_board_pixel(x, y, board, colour) # moves counter down by one\n board = set_board_pixel(x, y-1, board, 0) # removes counter from above\n send_board(board)\n sleep(500) # waits for 0.5 seconds so animation can be seen\n return board\n\n\ndef congradulate():\n radio.send(\"IW\")\n display.show(Image.HAPPY)\n music.play(music.BA_DING)\n\ndef defeat():\n display.show(Image.SAD)\n music.play(music.DADADADUM)\n\ndef detect_win(board):\n rows = board.split(\":\")\n won = False\n for row in rows:\n for i in range(3):\n colour = row[i]\n if colour != \"0\":\n if row[i] == row[i+1] == row[i+2]:\n print(row)\n return colour\n for col in range(3):\n for row in range(5):\n colour = rows[col][row]\n if colour != \"0\":\n if rows[col][row] == rows[col+1][row] == rows[col+2][row]:\n print(colour)\n return colour\n for col in range(3):\n for row in range(3):\n colour = rows[col][row]\n if colour != \"0\":\n if rows[col][row] == rows[col+1][row+1] == rows[col+2][row+2]:\n return colour\n for col in range(4, 1, -1):\n for row in range(3):\n colour = rows[col][row]\n if colour != \"0\":\n print(col ,row)\n if rows[col][row] == rows[col - 1][row + 1] == rows[col - 2][row + 2]:\n return colour\n return None\n\n\nmy_colour = \"4\"\nmy_turn = False\nboard = \"00000:00000:00000:00000:00000\"\nx = 0\ny = 0\nwhile True:\n if my_turn:\n if button_a.is_pressed():\n x += 1\n while get_board_pixel(x, 1, board) != \"0\":\n x += 1\n if x > 5:\n x = 0\n row = [\"0\", \"0\", \"0\", \"0\", \"0\"]\n row[x] = my_colour\n for c, pixel_colour in enumerate(row):\n board = set_board_pixel(c, 0, board, pixel_colour)\n send_board(board)\n sleep(250)\n if button_b.is_pressed():\n board = fall(x, y, board, my_colour)\n if detect_win(board):\n radio.send(\"IW\")\n congradulate()\n break\n else:\n my_turn = False\n radio.send(\"YT\")\n else:\n data = radio.receive()\n if data:\n if data == \"YT\":\n my_turn = True\n elif data == \"IW\":\n defeat()\n break\n else:\n board = data\n display.show(Image(data))\n","sub_path":"player2.py","file_name":"player2.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"440117094","text":"\n\"\"\"\nBeating the Benchmark \nSearch Results Relevance @ Kaggle\n__author__ : Abhishek\n\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.preprocessing import StandardScaler\n\ntrain = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\n\n# we dont need ID columns\nidx = test.id.values.astype(int)\ntrain = train.drop('id', axis=1)\ntest = test.drop('id', axis=1)\n\n# create labels. drop useless columns\ny = train.median_relevance.values\ntrain = train.drop(['median_relevance', 'relevance_variance'], axis=1)\n\n# do some lambda magic on text columns\ntraindata = list(train.apply(lambda x:'%s %s %s' % (x['query'],x['product_title'], x['product_description']),axis=1))\ntestdata = list(test.apply(lambda x:'%s %s %s' % (x['query'],x['product_title'], x['product_description']),axis=1))\n\n# the infamous tfidf vectorizer (Do you remember this one?)\ntfv = TfidfVectorizer(min_df=3, max_features=None, \n strip_accents='unicode', analyzer='word',token_pattern=r'\\w{1,}',\n ngram_range=(1, 2), use_idf=1,smooth_idf=1,sublinear_tf=1,\n stop_words = 'english')\n\n# Fit TFIDF\ntfv.fit(traindata)\nX = tfv.transform(traindata) \nX_test = tfv.transform(testdata)\n\n# LSA / SVD\nsvd = TruncatedSVD(n_components = 140)\nX = svd.fit_transform(X)\nX_test = svd.transform(X_test)\n\n# Scaling the data is important prior to SVM\nscl = StandardScaler()\nX = scl.fit_transform(X)\nX_test = scl.transform(X_test)\n\nmodel = SVC(C=10.0)\n\n\n# Fit SVM Model\nmodel.fit(X, y)\npreds = model.predict(X_test)\n\n# Create your first submission file\nsubmission = pd.DataFrame({\"id\": idx, \"prediction\": preds})\nsubmission.to_csv(\"beating_the_benchmark_yet_again.csv\", index=False)","sub_path":"iris_training/benchmark_code_for_crowdflower.py","file_name":"benchmark_code_for_crowdflower.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620224734","text":"import lib.rconprotocol\nimport logging\nimport time\n\n\"\"\"\nRconExecute class module.\nUsed to setup a shutdown timer with restart messages.\n\nPlease note that this module will only exit the server.\nYou may need an additional script (or watchdog) to get the server back online.\n\"\"\"\nclass RconExecute(object):\n def __init__(self, rcon, config):\n # chat messages\n self.command = config \n self.rcon = rcon\n\n logging.debug('%s() initialized' % type(self).__name__)\n\n \"\"\"\n Event: Called from Rcon.OnConnected()\n When connection is established start the \"restart\"\n \"\"\"\n def OnConnected(self):\n if self.command == 'shutdown': \n logging.debug('Begin the server shutdown')\n self.rcon.sendCommand('#lock')\n self._countdown(10);\n self.rcon.sendCommand('#shutdown');\n else:\n self.rcon.sendCommand(self.command)\n\n self.rcon.Abort()\n\n \"\"\"\n private: the actual shutdown call (with some delay to make sure players are disconnected)\n \"\"\"\n def _shutdownTask(self): \n self.rcon.sendCommand('#shutdown');\n\n \"\"\"\n private: Timer function\n \"\"\"\n def _countdown(self, n):\n while n > 0:\n self.rcon.sendCommand('SAY -1 The server will shutdown in %s seconds' % n)\n time.sleep(1)\n n -= 1\n \n","sub_path":"lib/rconexecute.py","file_name":"rconexecute.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609546783","text":"import sys\n\n\nclass Logger(object):\n def __init__(self, *args):\n self.outputs = args\n\n def write(self, message):\n for o in self.outputs:\n o.write(f\"{message}\")\n o.flush()\n\n def flush(self):\n for o in self.outputs:\n o.flush()\n\n\ndef start(OUTPUT_FILE='logfile.log', ERROR_FILE='errorfile.log'):\n sys.stdout = Logger(\n sys.stdout,\n open(OUTPUT_FILE, \"a\")\n )\n\n sys.stderr = Logger(\n sys.stderr,\n open(OUTPUT_FILE, \"a\"),\n open(ERROR_FILE, \"a\")\n )\n\n print(f\"[!] Now logging to {OUTPUT_FILE}, errors \")\n","sub_path":"TerminalLogger.py","file_name":"TerminalLogger.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"66279485","text":"from security_monkey.cloudaux_watcher import CloudAuxWatcher\nfrom security_monkey.cloudaux_watcher import CloudAuxChangeItem\nfrom security_monkey.decorators import record_exception\nfrom cloudaux.decorators import iter_account_region\n\n\nclass CloudAuxBatchedWatcher(CloudAuxWatcher):\n\n def __init__(self, **kwargs):\n super(CloudAuxBatchedWatcher, self).__init__(**kwargs)\n self.batched_size = 100\n self.done_slurping = False\n\n def slurp_list(self):\n self.prep_for_batch_slurp()\n\n @record_exception(source='{index}-watcher'.format(index=self.index), pop_exception_fields=True)\n def invoke_list_method(**kwargs):\n return self.list_method(**kwargs['conn_dict'])\n\n @iter_account_region(self.service_name, accounts=self.account_identifiers,\n regions=self._get_regions(), conn_type='dict')\n def get_item_list(**kwargs):\n kwargs, exception_map = self._add_exception_fields_to_kwargs(**kwargs)\n items = invoke_list_method(**kwargs)\n\n if not items:\n self.done_slurping = True\n items = list()\n\n return items, exception_map\n\n items, exception_map = self._flatten_iter_response(get_item_list())\n self.total_list.extend(items)\n\n return items, exception_map\n\n def slurp(self):\n @record_exception(source='{index}-watcher'.format(index=self.index), pop_exception_fields=True)\n def invoke_get_method(item, **kwargs):\n return self.get_method(item, **kwargs['conn_dict'])\n\n @iter_account_region(self.service_name, accounts=self.account_identifiers,\n regions=self._get_regions(), conn_type='dict')\n def slurp_items(**kwargs):\n item_list = list()\n kwargs, exception_map = self._add_exception_fields_to_kwargs(**kwargs)\n item_counter = self.batch_counter * self.batched_size\n while self.batched_size - len(item_list) > 0 and not self.done_slurping:\n cursor = self.total_list[item_counter]\n item_name = self.get_name_from_list_output(cursor)\n if item_name and self.check_ignore_list(item_name):\n item_counter += 1\n if item_counter == len(self.total_list):\n self.done_slurping = True\n continue\n\n item_details = invoke_get_method(cursor, name=item_name, **kwargs)\n if item_details:\n # Determine which region to record the item into.\n # Some tech, like IAM, is global and so we record it as 'universal' by setting an override_region\n # Some tech, like S3, requires an initial connection to us-east-1, though a buckets actual region may be different. Extract the actual region from item_details.\n # Otherwise, just use the region where the boto connection was made.\n record_region = self.override_region or \\\n item_details.get('Region') or kwargs['conn_dict']['region']\n item = CloudAuxChangeItem.from_item(\n name=item_name,\n item=item_details,\n record_region=record_region, **kwargs)\n item_list.append(item)\n item_counter += 1\n if item_counter == len(self.total_list):\n self.done_slurping = True\n self.batch_counter += 1\n return item_list, exception_map\n\n return self._flatten_iter_response(slurp_items())\n","sub_path":"security_monkey/cloudaux_batched_watcher.py","file_name":"cloudaux_batched_watcher.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"230051074","text":"import numpy as np\nimport pandas as pd\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.models import ColumnDataSource, LabelSet\n\n\noutput_file(\"../html/windrichting.html\")\ndata = pd.read_csv(\"../week1/KNMI_normalized.csv\")\n\ndef calc(wind):\n counts = []\n for i in range(1,9):\n counts.append(wind.count(i)/len(wind))\n f = counts\n f_1 = f[1:8]\n f_first = [f[0]]\n f_rev = f_1 + f_first\n return(f_rev[::-1])\n\nyear = 1951\nwind = []\nwinds = []\ncounter_year = 1\nfor i in range(len(data[\"TX\"])):\n wind.append(data[\"DDVEC\"][i])\n if data[\"YYYYMMDD\"][i]//10000 > year:\n year = data[\"YYYYMMDD\"][i]//10000\n counter_year +=1\n if counter_year == 20:\n counter_year = 0\n f = calc(wind)\n winds.append(f)\n wind = []\nf = calc(wind)\nwinds.append(f)\n\nnum_vars = 8\n\ncentre = 0.5\n\ntheta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)\n# rotate theta such that the first axis is at the top\ntheta += np.pi/2\n\ndef unit_poly_verts(theta, centre ):\n \"\"\"Return vertices of polygon for subplot axes.\n This polygon is circumscribed by a unit circle centered at (0.5, 0.5)\n \"\"\"\n x0, y0, r = [centre ] * 3\n verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]\n return verts\n\ndef radar_patch(r, theta, centre ):\n \"\"\" Returns the x and y coordinates corresponding to the magnitudes of\n each variable displayed in the radar plot\n \"\"\"\n # offset from centre of circle\n offset = 0.01\n yt = (r*centre + offset) * np.sin(theta) + centre\n xt = (r*centre + offset) * np.cos(theta) + centre\n return xt, yt\n\nverts = unit_poly_verts(theta, centre)\nx = [v[0] for v in verts]\ny = [v[1] for v in verts]\n\np1 = figure(title=\"Baseline - Radar plot\")\ntext = ['Noord', 'Noord-west', 'West', 'Zuid-west', 'Zuid', 'Zuid-oost', 'Oost', 'Noord-oost','']\nsource = ColumnDataSource({'x':x + [centre ],'y':y + [1],'text':text})\n\np1.line(x=\"x\", y=\"y\", source=source)\n\nlabels = LabelSet(x=\"x\",y=\"y\",text=\"text\",source=source)\n\np1.add_layout(labels)\np1.axis.visible = False\n\nflist = [np.array(winds[0])*3.5, np.array(winds[1])*3.5, np.array(winds[2])*3.5, np.array(winds[3])*3.5]\ncolors = ['blue','green','red', 'purple']\nfor i in range(len(flist)):\n xt, yt = radar_patch(flist[i], theta, centre)\n p1.patch(x=xt, y=yt, fill_alpha=0.15, fill_color=colors[i])\n","sub_path":"code/week2/windrichting.py","file_name":"windrichting.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"309547421","text":"import numpy as np\nimport pandas as pd\n#import matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import Sequential, load_model\nfrom keras.layers import LSTM, Dense, Dropout\nimport os\nimport tensorflow as tf\n\n# import yfinance, get MFST ticker\nimport yfinance as yf\n\ntickerStr = \"MFST\"\nticker = yf.Ticker(tickerStr)\ndf = ticker.history(period='5y')['Close'].values\ndf = df.reshape(-1, 1)\n\n# split 80% into training, remaining 20% + 50 values into testing data\ndataset_train = np.array(df[:int(df.shape[0]*0.8)])\ndataset_test = np.array(df[int(df.shape[0]*0.8)-50:])\n\n# scale datasets\nscaler = MinMaxScaler(feature_range=(0, 1))\ndataset_train = scaler.fit_transform(dataset_train)\ndataset_test = scaler.transform(dataset_test)\n\n# helper function, creates batches of 50 days of stock prices\ndef create_my_dataset(df):\n x = []\n y = []\n for i in range(50, df.shape[0]):\n x.append(df[i-50:i, 0])\n y.append(df[i, 0])\n x = np.array(x)\n y = np.array(y)\n return x, y\n\n\nx_train, y_train = create_my_dataset(dataset_train)\nx_test, y_test = create_my_dataset(dataset_test)\n\n# reshaping for LSTM\nx_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\nx_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))\n\n# creating model\ntf.logging.set_verbosity(tf.logging.ERROR)\nmodel = Sequential()\nmodel.add(LSTM(units=96, return_sequences=True, input_shape=(x_train.shape[1],1)))\nmodel.add(LSTM(units=96, return_sequences=True))\nmodel.add(LSTM(units=96))\nmodel.add(Dense(units=1))\n\nmodel.compile(loss='mean_squared_error', optimizer='adam')\nmodel.fit(x_train, y_train, epochs=50, batch_size=32)\nmodel.save(os.join(\"..\",\"models\",f\"{tickerStr}.h5\"))","sub_path":"static/py/create_model.py","file_name":"create_model.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485022616","text":"# 3. opencv contour : 이미지의 특성을 추출하여 더 명확하게 이미지를 인식하기 위함.\r\n\r\nimport cv2\r\n\r\ndef contour(image_path, person, spell, num):\r\n image = cv2.imread(\"%s%d_%d.jpg\" %(image_path, person, num))\r\n imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n ret, thr = cv2.threshold(imgray, 70, 255, cv2.THRESH_BINARY)\r\n\r\n _, countors, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n contour_img = cv2.drawContours(image, countors, -1, (0, 255, 0), 1)\r\n cv2.imwrite(\"final/%d/%d_%d.jpg\" % (spell, person, num), contour_img)\r\n\r\nimage_path = \"second_cropped\"\r\n\r\nfor spell in range(1,7):\r\n for person in range(1, 11):\r\n for num in range(1,64):\r\n image_path = \"second_cropped/%d/\" %(spell)\r\n countoured = contour(image_path, person, spell, num)\r\n image_path2 = \"final/%d\" % (spell)\r\n\r\n","sub_path":"3_third_preprocessing(contour).py","file_name":"3_third_preprocessing(contour).py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"84078857","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport urllib\nimport sys\nimport socket\n\nfrom YTBase import YTBase\n\n\nclass YTHttp(YTBase):\n '''\n 获取url内容\n '''\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) '\n 'AppleWebKit/537.36 (KHTML, like Gecko)'\n ' Chrome/46.0.2490.80 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;'\n + 'q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.6',\n 'Connection': 'keep-alive'\n }\n\n def __init__(self, isjson=False):\n \"\"\"\n 初始化属性\n :param is_json: 返回结果是否为json\n \"\"\"\n\n super(YTHttp, self).__init__()\n\n self.timeout = 120.0\n self._isJson = isjson\n\n def request(self, url, method='get', values=False):\n \"\"\"\n 获取url内容\n :param url:网络地址\n :param method 方法 'get' 'post'\n :param values: 数据 dict\n :rtype : string\n \"\"\"\n self.log(\"get url: {0} content start\\n\".format(url))\n\n # post请求数据整理\n if method == 'get':\n req = urllib.request.Request(url, headers=YTHttp.headers)\n\n elif method == 'post':\n pdata = urllib.urlencode(values) if values else ''\n req = urllib.request.Request(url, data=pdata, headers=self.headers)\n\n else:\n self.log('unknown http protocol')\n raise ValueError('unknown http protocol')\n\n try:\n response = urllib.request.urlopen(req, timeout=self.timeout)\n data = response.read()\n except urllib.request.URLError as e:\n self.log(\"get url: {0} error\".format(url))\n\n if hasattr(e, 'code'):\n msg = \"urlopen error code:\" + str(e.code)\n else:\n msg = \"\"\n msg += \"reason:\" + e.read() if hasattr(e, 'reason') else ''\n self.log(msg)\n\n return ''\n except socket.timeout as e:\n self.log(\"get url: {0} error time out\\n\".format(url))\n return ''\n\n else:\n\n self.log(\"get url: {0} content done\\n\".format(url))\n\n # 解压\n if 'content-encoding' in response.headers:\n import StringIO\n import gzip\n\n fileobj = StringIO.StringIO\n fileobj.write(data)\n fileobj.seek(0)\n gzip_file = gzip.GzipFile(fileobj=fileobj)\n data = gzip_file.read()\n\n return self._decode(data)\n\n def _decode(self, raw_data):\n \"\"\"\n 将获取的内容解码为本地数据\n :param raw_data: 获取的原始数据\n :rtype string\n \"\"\"\n raw_data = raw_data.decode('utf-8')\n if self._isJson:\n import json\n raw_data = json.loads(raw_data)\n\n return raw_data\n\nif __name__ == '__main__':\n sys.getfilesystemencoding()\n","sub_path":"tieba/YTHttp.py","file_name":"YTHttp.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306884050","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\n\"\"\"\nConvert an image to an array of bytes in a .c file \nsource: https://github.com/kendryte/nncase/blob/master/examples/20classes_yolo/k210/kpu_20classes_example/img2c.py\n\"\"\"\n\ntarget_shape = (224, 224)\nif __name__ == '__main__':\n img = plt.imread(sys.argv[1])\n # img = cv2.imread(sys.argv[1])\n img = cv2.resize(img, target_shape)\n cv2.imwrite(\"c_img.png\", img)\n print(img.shape)\n # img = np.transpose(img, [2, 0, 1])\n with open('image.c', 'w') as f:\n print('const unsigned char gImage_image[] __attribute__((aligned(128))) ={', file=f)\n print(', '.join([str(i) for i in img.flatten()]), file=f)\n print('};', file=f)\n","sub_path":"img2c.py","file_name":"img2c.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"311848778","text":"import math\n\ndef checkVrijstand(huis1, huis2):\n\t# init variablen voor vrijstand en om in op te slaan waar huis2 zich\n\t# ten opzichte van huis1 bevindt\n\tvrijstand = 0\n\tisLeft = False\n\tisRight = False\n\tisAbove = False\n\tisBelow = False\n\n\t# bereken hoekpunten van huis 1\n\thuis1xmin = huis1.hoekpunt.x\n\thuis1xmax = huis1.hoekpunt.x + huis1.width\n\thuis1ymin = huis1.hoekpunt.y\n\thuis1ymax = huis1.hoekpunt.y + huis1.length\n\n\t# bereken hoekpunten van huis 2\n\thuis2xmin = huis2.hoekpunt.x\n\thuis2xmax = huis2.hoekpunt.x + huis2.width\n\thuis2ymin = huis2.hoekpunt.y\n\thuis2ymax = huis2.hoekpunt.y + huis2.length\n\n\t# controleer of hoekpunten huis 2 binnen bereik huis 1 vallen\n\t# zo ja: error, huizen mogen niet overlappen.\n\tif (huis2xmin > huis1xmin and huis2xmin < huis1xmax) or (huis2xmax > huis1xmin and huis2xmax < huis1xmax):\n\t\tif (huis2ymin > huis1ymin and huis2ymin < huis1ymax) or (huis2ymax > huis1ymin and huis2ymax < huis1ymax):\n\t\t\t# error\n\t\t\treturn 0\n\n\t# vergelijk x waarden van beide huizen\n\tif huis1xmin > huis2xmin:\n\t\t# huis 2 staat links\n\t\tisLeft = True\n\tif huis1xmax < huis2xmin:\n\t\t# huis 2 staat rechts\n\t\tisRight = True\n\n\t# vergelijk y waarden van beide huizen\n\tif huis1ymin > huis2ymin:\n\t\t# huis 2 staat boven\n\t\tisAbove = True\n\tif huis1ymax < huis2ymin:\n\t\t# huis 2 staat onder\n\t\tisBelow = True\n\n\t# bereken vrijstand\n\t# wanneer huis2 boven huis1 staat:\n\tif isAbove == True:\n\t\t# wanneer huis2 ook links van huis1 staat (i.e. linksboven)\n\t\tif isLeft == True:\n\t\t\tx = huis1xmin - huis2xmax\n\t\t\ty = huis1ymin - huis2ymax\n\t\t\tvrijstand = (x**2 + y**2)**0.5\n\t\t# wanneer huis2 ook rechts van huis1 staat (i.e. rechtsboven)\n\t\telif isRight == True:\n\t\t\tx = huis2xmin - huis1xmax\n\t\t\ty = huis1ymin - huis2ymax\n\t\t\tvrijstand = (x**2 + y**2)**0.5\n\t\t# anders staat huis2 direct boven huis1\n\t\telse:\n\t\t\tvrijstand = huis1ymin - huis2ymax\n\n\t# wanneer huis2 onder huis1 staat\n\telif isBelow == True:\n\t\tif isLeft == True:\n\t\t\t# wanneer huis2 ook links van huis1 staat (i.e. linksonder)\n\t\t\tx = huis1xmin - huis2xmax\n\t\t\ty = huis2ymin - huis1ymax\n\t\t\tvrijstand = (x**2 + y**2)**0.5\n\t\t# wanneer huis2 ook rechts van huis1 staat (i.e. rechtsonder)\n\t\telif isRight == True:\n\t\t\tx = huis2xmin - huis1xmax\n\t\t\ty = huis2ymin - huis1ymax\n\t\t\tvrijstand = (x**2 + y**2)**0.5\n\t\t# anders staat huis2 direct onder huis1\n\t\telse:\n\t\t\tvrijstand = huis2ymin - huis1ymax\n\t# anders staat huis 2 direct links of rechts van huis 1\n\telse:\n\t\tif isLeft == True:\n\t\t\t# wanneer huis2 links van huis1 staat\n\t\t\tvrijstand = huis1xmin - huis2xmax\n\t\telif isRight == True:\n\t\t\t# wanneer huis2 rechts van huis1 staat\n\t\t\tvrijstand = huis2xmin - huis1xmax\n\t\telse:\n\t\t\tpass\n\t# floor ivm pythagoras-stelling die floats teruggeeft\n\treturn math.floor(vrijstand)\n","sub_path":"vrijstand.py","file_name":"vrijstand.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"538493972","text":"#! /usr/bin/env python3\n\n\nimport sys\n\nimport simple_classes\n\n\n\ndef dump(color, msg):\n print(msg)\n print(\" __str__() returns: \"+str(color))\n print(\" html_hex_color() returns: \"+color.html_hex_color())\n print(\" get_rgb() returns: {}\".format(color.get_rgb()))\n print()\n\n\n\nr,g,b = (127,127,127)\n\nprint(\"Creating a new Color object. r,g,b: {},{},{}\".format(r,g,b))\nsome_color = simple_classes.Color(r,g,b)\ndump(some_color, \"Initial Color:\")\n\n\n\ncolor2 = \"BLACK\"\nprint(f\"--- Setting the color: '{color2}'\")\nsome_color.set_standard_color(color2)\ndump(some_color, \"Color, after setting the color\")\n\n\n\ncolor3 = \"white\"\nprint(f\"--- Setting the color: '{color3}'\")\nsome_color.set_standard_color(color3)\ndump(some_color, \"Color, after setting the color\")\n\n\n\nprint(\"--- Clearing the red component ---\")\nsome_color.remove_red()\ndump(some_color, \"Color, after removing the red\")\n\n\n\ncolor4 = \"black\"\nprint(f\"--- Setting the color: '{color4}'\")\nsome_color.set_standard_color(color4)\ndump(some_color, \"Color, after setting the color\")\n\n\n\ncolor5 = \"WHITE\"\nprint(f\"--- Setting the color: '{color5}'\")\nsome_color.set_standard_color(color5)\ndump(some_color, \"Color, after setting the color\")\n\n\n\nprint(\"--- Clearing the red component ---\")\nsome_color.remove_red()\ndump(some_color, \"Color, after removing the red\")\n\n\n\ncolor6 = \"yellow\"\nprint(f\"--- Setting the color: '{color6}'\")\nsome_color.set_standard_color(color6)\ndump(some_color, \"Color, after setting the color\")\n\n\n\nprint(\"TESTCASE COMPLETED\")\n\n","sub_path":"python02/proj04-short/test-cases/test-color-02.py","file_name":"test-color-02.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"303122101","text":"def procedure_perevod(money, currency):\n usd = 57\n euro = 60\n jpy = 0.5\n cny = 8.9\n gbr = 78.3\n\n\n if currency == 1:\n money = round(money / usd, 2)\n print(\"Валюта: доллары США\")\n elif currency == 2:\n money = round(money / euro, 2)\n print(\"Валюта: евро\")\n elif currency == 3:\n money = round(money / jpy, 2)\n print(\"Валюта: йена\")\n elif currency == 4:\n money = round(money / cny, 2)\n print(\"Валюта: юань\")\n elif currency == 5:\n money = round(money / gbr, 2)\n print(\"Валюта: фунт стерлингов\")\n return money\n\ndef main():\n money = int(input(\"Введите сумму, которую вы хотите обменять: \"))\n currency = int(input(\"Укажите код валюты: доллары - 1, евро - 2, йена - 3, юань - 4, фунт стерлингов - 5: \"))\n result = procedure_perevod(money, currency)\n print(\"К получению:\", result)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Evro.py","file_name":"Evro.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"509330067","text":"from django.contrib import admin\nfrom django.urls import include, path\n\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n)\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n path(\"photos/\", include(\"photos.urls\")),\n path(\"user/\", include(\"users.urls\")),\n path(\"posts/\", include(\"posts.urls\")),\n path(\"token/\", TokenObtainPairView.as_view(), name=\"token_obtain_pair\"),\n path(\"token/refresh/\", TokenRefreshView.as_view(), name=\"token_refresh\"),\n]\n","sub_path":"backend/backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"436719293","text":"from sklearn.decomposition import PCA\nfrom sklearn.neighbors import NearestNeighbors\nimport numpy as np\n\ntotalX = []\n\nfor i in range(100): #loads Mode A data\n f = open(\"base/ModeA/File\"+str(i)+\".txt\", \"r\")\n data = f.read().split(\"\\t\")\n data[20000] = 0\n totalX.append(data[:-1])\n\nfor i in range(100): #loads Mode B data\n f = open(\"base/ModeB/File\"+str(i)+\".txt\", \"r\")\n data = f.read().split(\"\\t\")\n data[20000] = 0\n totalX.append(data[:-1])\n\nfor i in range(100): #loads Mode C data\n f = open(\"base/ModeC/File\"+str(i)+\".txt\", \"r\")\n data = f.read().split(\"\\t\")\n data[20000] = 0\n totalX.append(data[:-1])\n\nfor i in range(100): #loads Mode D data\n f = open(\"base/ModeD/File\"+str(i)+\".txt\", \"r\")\n data = f.read().split(\"\\t\")\n if(len(data) <= 20000):\n continue\n data[20000] = 0\n totalX.append(data[:-1])\n\n#applying FFT and PCA on loaded data\nfftX = np.fft.fft(totalX)\npca = PCA(svd_solver='full')\nnewX = pca.fit_transform(fftX)\n\nclf = NearestNeighbors(n_neighbors=4) #taking 4 neighbours since the each point will also consider itself as nearest neighbor\ndistances, indices = clf.fit(newX).kneighbors(newX)\nalpha = [0]*len(distances)\n\n#Calculating KNN scores from KNN distances\nfor i in range(len(distances)):\n alpha[i] = sum(distances[i])\n\nalpha.sort(reverse=True)\n\ntestX = []\nfor i in range(499): #loads Mode M data as test data\n f = open(\"Test/TestWT/Data\"+str(i+1)+\".txt\", \"r\")\n data = f.read().split(\"\\t\")\n testX.append(data[:-1])\n\n#applying FFT and PCA on loaded data\nfftTestX = np.fft.fft(testX)\npca = PCA(n_components=399, svd_solver='full')\nnewTestX = pca.fit_transform(fftTestX)\n\n\nf = open(\"results.txt\", \"w\") #writing results to text file\n\n#Applying KNN on new data set\nclf = NearestNeighbors(n_neighbors=3)\ndistances, indices = clf.fit(newX).kneighbors(newTestX)\n\n#StrOUD Algorithm with KNN as strangeness function\nfor i in range(len(newTestX)):\n b = 0.0\n strangeness_i = sum(distances[i])\n print (strangeness_i)\n for j in range(len(alpha)):\n if strangeness_i > alpha[j]:\n break\n b += 1.0\n pvalue = (b+1.0)/(float(len(newTestX))+1.0)\n f.write(str(pvalue)+\"\\n\")\n","sub_path":"src/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"171393314","text":"import time\nimport datetime\n\nfrom ubxlib.frame import UbxFrame, UbxCID\nfrom ubxlib.types import Padding, U1, U2, U4, X1, I1\n\n\nclass UbxMgaIniTimeUtc_(UbxFrame):\n CID = UbxCID(0x13, 0x40)\n NAME = 'UBX-MGA-INI-TIME_UTC'\n\n\nclass UbxMgaIniTimeUtc(UbxMgaIniTimeUtc_):\n def __init__(self):\n super().__init__()\n\n self.f.add(U1('type'))\n self.f.add(U1('version'))\n self.f.add(X1('ref'))\n\n self.f.add(I1('leapSecs'))\n self.f.add(U2('year'))\n self.f.add(U1('month'))\n self.f.add(U1('day'))\n self.f.add(U1('hour'))\n self.f.add(U1('minute'))\n self.f.add(U1('second'))\n self.f.add(Padding(1, 'res1'))\n self.f.add(U4('ns'))\n\n self.f.add(U2('tAccS'))\n self.f.add(Padding(2, 'res2'))\n self.f.add(U4('tAccNs'))\n\n def set_current_dt(self):\n dt = datetime.datetime.utcnow()\n print(dt)\n\n self.f.type = 0x10\n self.f.version = 0x00\n self.f.ref = 0x00 # none, i.e. on receipt of message (will be inaccurate!)\n\n self.f.year = dt.year\n self.f.month = dt.month\n self.f.day = dt.day\n self.f.hour = dt.hour\n self.f.minute = dt.minute\n self.f.second = dt.second\n self.f.ns = 0 # dt.microsecond * 1000.0\n\n self.f.tAccS = 2\n self.f.tAccNs = 0\n","sub_path":"ubxlib/ubx_mga_ini_time_utc.py","file_name":"ubx_mga_ini_time_utc.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"557383829","text":"class Car(object):\n def __init__(self, ID, begin_id, end_id,maxspeed,planTime):\n self.ID = ID\n self.begin_id=begin_id\n self.end_id=end_id\n self.maxspeed = maxspeed\n self.planTime=planTime\n self.realtime=self.planTime\n self.routelen=0\n self.state=0\n #state: \n # 0:未出车\n # 1:等待状态(没有到达终点)\n # 2:终止状态(没有到达终点)\n # 3:已到达\n self.route=[]\n self.position=0\n self.roadID=0\n self.path=0\n self.pathdir='no'\n #pathdir: \n # no:未出车或已到达\n # go\n # back\n\n\n\nclass Cross(object):\n def __init__(self,ID,roadId1,roadId2,roadId3,roadId4):\n self.ID=ID\n self.roadId1 = roadId1\n self.roadId2 = roadId2\n self.roadId3 = roadId3\n self.roadId4 = roadId4\n self.roadlist=sorted([self.roadId1,self.roadId2,self.roadId3,self.roadId4])\n\nclass road(object):\n def __init__(self, ID, length, maxspeed,path_number,begin_id,end_id,isDuplex):\n self.ID = ID\n self.length = length\n self.maxspeed = maxspeed\n self.path_number=path_number\n self.begin_id=begin_id\n self.end_id=end_id\n self.isDuplex=isDuplex\n self.situation=[] #此道路里面的车辆的情况","sub_path":"Huawei-CodeCraft-2019/3.0/classini.py","file_name":"classini.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"103471179","text":"import pandas as pd \nimport flask\nimport pickle\nimport numpy as np\n\n\n\n# Use pickle to load in the pre-trained model.\nwith open('model/SVM.pkl', 'rb') as f:\n svm_model = pickle.load(f)\n \nwith open('model/Mapping.pkl', 'rb') as output:\n mapping = pickle.load(output)\n\napp = flask.Flask(__name__, template_folder='templates')\n@app.route('/', methods=['GET', 'POST'])\ndef main():\n if flask.request.method == 'GET':\n return(flask.render_template('main.html'))\n if flask.request.method == 'POST':\n \n # Extract the input\n asin = flask.request.form['asin']\n initial_identifier = flask.request.form['initial_identifier']\n title = flask.request.form['title']\n brand = flask.request.form['brand']\n manufacturer = flask.request.form['manufacturer']\n publisher = flask.request.form['publisher']\n studio = flask.request.form['studio']\n label = flask.request.form['label']\n features = flask.request.form['features']\n all_categories = flask.request.form['all_categories']\n nodeid_tree = flask.request.form['nodeid_tree']\n subcategory = flask.request.form['subcategory']\n part_num = flask.request.form['part_num']\n mpn = flask.request.form['mpn']\n product_type_name = flask.request.form['product_type_name']\n category = flask.request.form['category']\n model = flask.request.form['model']\n sku = flask.request.form['sku']\n product_group = flask.request.form['product_group']\n parent_asin = flask.request.form['parent_asin']\n color = flask.request.form['color']\n binding = flask.request.form['binding']\n size = flask.request.form['size']\n package_dimensions_width = flask.request.form['package_dimensions_width']\n package_dimensions_length = flask.request.form['package_dimensions_length']\n \n # Make DataFrame for model\n input_variables = pd.DataFrame([[initial_identifier, asin, title, \n brand, manufacturer, publisher, \n studio, label, features,\n all_categories, nodeid_tree, \n subcategory, part_num, mpn, \n product_type_name, category, \n model, sku, product_group, \n parent_asin, color, binding, size, \n package_dimensions_width, package_dimensions_length]],\n columns=['initial_identifier', 'asin', \n 'title', 'brand', 'manufacturer', \n 'publisher','studio', 'label', \n 'features', 'all_categories', \n 'nodeid_tree', 'subcategory','part_num', \n 'mpn', 'product_type_name','category', \n 'model', 'sku', 'product_group', \n 'parent_asin', 'color','binding', 'size',\n 'package_dimensions_width','package_dimensions_length'],\n dtype=object,\n index=['input']) \n \n classifier_variables=['initial_identifier', 'asin', \n 'title', 'brand', 'manufacturer', \n 'publisher','studio', 'label', \n 'features', 'all_categories', \n 'nodeid_tree', 'subcategory','part_num', \n 'mpn', 'product_type_name','category', \n 'model', 'sku', 'product_group', \n 'parent_asin', 'color','binding', 'size']\n quantative_variables=['package_dimensions_width', 'package_dimensions_length' ]\n\n for j in classifier_variables: \n input_variables[j].replace('', value=\"UNKNOWN\", inplace=True)\n\n for k in quantative_variables:\n input_variables[k].replace('', value=0, inplace=True)\n \n \n \n\n # print(input_variables) \n #encoding and assigning mapping \n classifier_encoded_variables=[]\n for val in classifier_variables:\n classifier_encoded_variables.append(val+'_En')\n uval=input_variables[val].unique()\n for i in uval:\n if i in mapping[val]:\n input_variables.loc[input_variables[val]==i,val+'_En'] = mapping[val][i]\n else:\n input_variables.loc[input_variables[val]==i,val+'_En'] = 0.5\n \n general_features=classifier_encoded_variables+quantative_variables\n \n input_data=input_variables[general_features]\n # Get the model's prediction \n prediction = svm_model.predict(input_data)[0]\n \n # Render the form again, but add in the prediction and remind user\n # of the values they input before\n return flask.render_template('main.html',original_input={},result=prediction,)\nif __name__ == '__main__':\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"215909902","text":"# Authors: Lucas Foulon \n# License: BSD 3 clause\n\nfrom numpy import array as np_array\nfrom numpy import ndarray as np_ndarray\nfrom numpy import zeros as np_zeros\n\nfrom pyCFOFiSAX._tree_iSAX import TreeISAX\nfrom tslearn.piecewise import PiecewiseAggregateApproximation\n\n\nclass ForestISAX:\n \"\"\"\n ForestISAX class containing one or more trees and pretreatment functions on the data contained\n in these trees\n\n :param int size_word: The size of the SAX words\n :param int threshold: The maximum threshold of nodes\n :param numpy.ndarray data_ts: The sequences to be inserted to extract the stats\n :param int base_cardinality: The smallest cardinality for encoding *i*\\ SAX\n :param int number_tree: The number of TreeISAX trees in the forest\n :param list indices_partition: a list of index list where, for each tree, specifies the indices of\n sequences to be inserted\n :param int max_card_alphabet: if ``boolean_card_max == True``, the maximum cardinality of encoding *i*\\ SAX in\n each of the trees\n :param boolean boolean_card_max: if ``== True``, Defines a maximum cardinality for encoding *i*\\ SAX\n Sequences in each of the trees\n :param float mu: mean value used to define the isax transformation\n :param float sig: standard deviation used to define the isax transformation\n\n :ivar list length_partition: The length of the SAX words in each tree (``== [size_word]`` if ``number_tree\n == 1``)\n \"\"\"\n\n def __init__(self, size_word: int, threshold: int, data_ts: np_ndarray, base_cardinality: int = 2,\n number_tree: int = 1,\n indices_partition: list = None,\n max_card_alphabet: int = 128, boolean_card_max: bool = True,\n mu=None, sig=None):\n \"\"\"\n Initialization function of the TreeISAX class\n\n :returns: a forest pointing to one or more iSAX trees\n :rtype: ForestISAX\n \"\"\"\n\n # Number of cover contained in the SAX word\n self.size_word = size_word\n # threshold of split node\n self.threshold = threshold\n # Cardinality of each letter at level 1 of the tree\n self.base_cardinality = base_cardinality\n # Max cardinality\n self.max_cardinality = base_cardinality\n\n self._paa = PiecewiseAggregateApproximation(self.size_word)\n\n self.forest = {}\n self.number_tree = number_tree\n\n self.indices_partition = indices_partition\n\n self._init_trees(data_ts, max_card_alphabet, boolean_card_max, mu=mu, sig=sig)\n\n def _init_trees(self, data_ts: np_ndarray, max_card_alphabet: int, boolean_card_max: bool, mu=None, sig=None):\n \"\"\"\n Function that initializes the tree (s) when creating a ForestISAX object\n\n :param numpy.ndarray data_ts: The sequences to be inserted to extract the stats\n :param int max_card_alphabet: if ``boolean_card_max == True``, The maximum cardinality of encoding *i*\\ SAX\n dans chacun des arbres\n :param boolean boolean_card_max: if ``boolean_card_max == True``, defines maximum cardinality for encoding *i*\\ SAX\n sequences in each tree\n \"\"\"\n\n if self.number_tree == 1:\n \"\"\" if there is only one tree\"\"\"\n\n self.forest[0] = TreeISAX(\n size_word=self.size_word,\n threshold=self.threshold, data_ts=data_ts,\n base_cardinality=self.base_cardinality,\n max_card_alphabet=max_card_alphabet,\n boolean_card_max=boolean_card_max,\n mu=mu,\n sig=sig\n )\n self.length_partition = [self.size_word]\n self.indices_partition = [list(range(self.size_word))]\n\n elif self.indices_partition is None:\n \"\"\" If there is no tree and the indices are not defined \"\"\"\n\n self.length_partition = [int(self.size_word / self.number_tree)] * self.number_tree\n for reste in range(self.size_word - sum(self.length_partition)):\n self.length_partition[reste] += 1\n\n self.indices_partition = []\n\n for i in range(self.number_tree):\n self.forest[i] = TreeISAX(\n size_word=self.length_partition[i],\n threshold=self.threshold,\n data_ts=data_ts[:, i:self.size_word:self.number_tree],\n base_cardinality=2,\n max_card_alphabet=max_card_alphabet,\n boolean_card_max=boolean_card_max\n )\n self.indices_partition.append(list(range(i, self.size_word, self.number_tree)))\n\n else:\n # List of letter number in each tree\n self.length_partition = []\n for part_tmp in self.indices_partition:\n self.length_partition.append(len(part_tmp))\n\n for i in range(self.number_tree):\n self.forest[i] = TreeISAX(\n size_word=self.length_partition[i],\n threshold=self.threshold,\n data_ts=data_ts[:, self.indices_partition[i]],\n base_cardinality=2,\n max_card_alphabet=max_card_alphabet,\n boolean_card_max=boolean_card_max\n )\n\n def index_data(self, new_sequences: np_ndarray, annotation=None, parallel=False):\n \"\"\"\n The Index_Data function allows you to insert a large number of sequences\n\n :param numpy.ndarray new_sequences: The sequences to be inserted\n :param dictionary annotation: Dictionary of lists with annotations to be added to each item in a leaf\n :param boolean parallel: if True, it runs the indexing of the tree at minimum cardinality and waits for the parallel escalation\n \n :returns: The number of sequences (sub sequences) insert into the tree (in the trees)\n :rtype: numpy.array\n \"\"\"\n\n # Ts Conversion to PAA\n if new_sequences.shape[-1] > 1:\n # add dim to avoid tslearn warning\n new_sequences = new_sequences.reshape(new_sequences.shape + (1,))\n npaa = self._paa.fit_transform(new_sequences)\n\n # To count the number of objects in each tree\n cmpt_insert = np_zeros(shape=self.number_tree)\n\n for i, tree in self.forest.items():\n # Retrieves the indices of the tree, in the multi-tree case\n npaa_tmp = npaa[:, self.indices_partition[i]]\n npaa_tmp = npaa_tmp.reshape(npaa_tmp.shape[:-1])\n\n for j,npa_tp in enumerate(npaa_tmp):\n entry = {}\n if annotation is not None:\n for key, value in annotation.items():\n entry[key] = value[j]\n\n tree.insert_paa(npa_tp, annotation=entry, parallel=parallel)\n cmpt_insert[i] += 1\n\n # Returns array[tree_index] with the number of inserted objects for each tree\n return cmpt_insert\n\n def _count_nodes(self, id_tree: int):\n \"\"\"\n The _count_nodes function returns the number of nodes and leaf nodes for a given tree.\n Uses :func:`~pyCFOFiSAX.tree_iSAX.TreeISAX.count_nodes_by_tree`.\n\n :param int id_tree: The tree ID to be analyzed\n\n :returns: the number of internal nodes, the number of leaf nodes\n :rtype: int, int\n \"\"\"\n\n tree = self.forest[id_tree]\n return tree.count_nodes_by_tree()\n\n def list_nodes(self, id_tree: int, bool_print: bool = False):\n \"\"\"\n Returns lists of nodes and barycenters of the tree id_tree.Displays statistics on standard output\n if ``bool_print == True``\n Uses :func:`~pyCFOFiSAX.tree_iSAX.TreeISAX.get_list_nodes_and_barycentre`.\n\n :param int id_tree: The tree ID to be analyzed\n :param boolean bool_print: Displays the nodes stats on the standard output\n\n :returns: The list of nodes, the list of internal nodes, the list of barycenters\n :rtype: list, list, list\n \"\"\"\n\n tree = self.forest[id_tree]\n node_list, node_list_leaf, node_leaf_ndarray_mean = tree.get_list_nodes_and_barycentre()\n if bool_print:\n print(f\"{len(node_list)} nodes whose {len(node_list_leaf)} leafs in tree {id_tree}\")\n\n return node_list, node_list_leaf, node_leaf_ndarray_mean\n\n def preprocessing_forest_for_icfof(self, ntss: np_ndarray, bool_print: bool = False, count_num_node: bool = False):\n \"\"\"\n Allows us to call, for the ``id_tree`` to the pre-treatment for the calculation *i*\\ CFOF\n\n :param ntss: Reference sequences\n :param boolean bool_print: if True, displays the times of each pre-treatment step\n :param boolean count_num_node: if True, count the number of nodes\n\n :returns: if count_num_node, returns the number of nodes contained in each tree\n :rtype: numpy.array\n \"\"\"\n\n total_num_node = np_zeros(self.number_tree)\n for id_tree, tmp_tree in self.forest.items():\n ntss_tmp = ntss[:, self.indices_partition[id_tree]]\n total_num_node[id_tree] = tmp_tree.preprocessing_for_icfof(ntss_tmp,\n bool_print=bool_print,\n count_num_node=count_num_node)\n\n if count_num_node:\n return total_num_node\n\n def number_nodes_visited(self, query: np_array, ntss: np_ndarray):\n \"\"\"\n Count the number of average visited nodes in each tree for calculating the approximation.\n\n :param numpy.array query: The sequence to be evaluated\n :param numpy.ndarray ntss: Reference sequences\n\n :returns: Returns the number of nodes visited in each tree for the approximation *i*\\ CFOF\n :rtype: numpy.array\n \"\"\"\n\n total_num_node = np_zeros(self.number_tree*2)\n\n for id_tree, tmp_tree in self.forest.items():\n\n sub_query = query[self.indices_partition[id_tree]]\n ntss_tmp = np_array(ntss)[:, self.indices_partition[id_tree]]\n\n total_num_node[id_tree], total_num_node[self.number_tree + id_tree] = \\\n tmp_tree.number_nodes_visited(sub_query, ntss_tmp)\n\n return total_num_node\n","sub_path":"pyCFOFiSAX/_forest_iSAX.py","file_name":"_forest_iSAX.py","file_ext":"py","file_size_in_byte":10302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"166043987","text":"from pprint import pprint\nfrom lxml import html\nimport requests\nfrom datetime import datetime\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client['news']\nnews = db.news\n\ndef convers(month):\n if month == '01':\n month_c = 'января'\n elif month == '02':\n month_c = 'февраля'\n elif month == '03':\n month_c = 'марта'\n elif month == '04':\n month_c = 'апреля'\n elif month == '05':\n month_c = 'мая'\n elif month == '06':\n month_c = 'июня'\n elif month == '07':\n month_c = 'июля'\n elif month == '08':\n month_c = 'августа'\n elif month == '09':\n month_c = 'сентября'\n elif month == '10':\n month_c = 'октября'\n elif month == '11':\n month_c = 'ноября'\n elif month == '12':\n month_c = 'декабря'\n return month_c\n\nheader = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}\n\nlinks = []\n\nlenta = 'https://lenta.ru'\nresponse_l = requests.get(lenta + '/', headers=header)\ndom_l = html.fromstring(response_l.text)\nblocks_l = dom_l.xpath(\"//div[@class='item news b-tabloid__topic_news']\")\n\nfor block in blocks_l:\n item_l = {}\n item_l['source'] = lenta[8:]\n name = block.xpath(\".//div[@class='titles']//a/span/text()\")\n item_l['name'] = name[0].replace(\"\\xa0\", ' ')\n a = block.xpath(\".//div[@class='titles']//a/@href\")\n if 'https' in a[0]:\n item_l['link'] = a[0]\n else:\n item_l['link'] = lenta + a[0]\n date = block.xpath(\".//span[@class='g-date item__date']/text()\")\n if date[0] == 'Сегодня':\n date_r = datetime.now().strftime('%d') + ' ' + convers(datetime.now().strftime('%m'))\n else:\n date_r = date[0]\n time = block.xpath(\".//span[@class='g-date item__date']//text()\")\n item_l['date'] = date_r\n item_l['time'] = time[0]\n links.append(item_l)\n\nyandex = 'https://yandex.ru'\nresponse_y = requests.get(yandex + '/news/', headers=header)\ndom_y = html.fromstring(response_y.text)\nblocks_y = dom_y.xpath(\"//div[@class='story__topic']\")\n\nfor block in blocks_y:\n item_y = {}\n\n name = block.xpath(\".//h2[@class ='story__title']//a[1]/text()\")\n item_y['name'] = name[0]\n\n a = block.xpath(\".//h2[@class ='story__title']//a[1]/@href\")\n link = a[0][:a[0].index('?')]\n item_y['link'] = yandex + link\n\n info = block.xpath(\"./../div[@class = 'story__info']//div[1]/text()\")\n\n date = info[0].rsplit(' ', 1)[1]\n if len(date) == 5:\n item_y['date'] = datetime.now().strftime('%d') + ' ' + convers(datetime.now().strftime('%m'))\n item_y['time'] = date\n else:\n item_y['date'] = date.replace(\"\\xa0\", ' ')[:-8]\n item_y['time'] = date[-5:]\n\n source = info[0].rsplit(' ', 1)[0]\n item_y['source'] = source\n\n links.append(item_y)\n\nmail = 'https://news.mail.ru'\nresponse_m = requests.get(mail + '/', headers=header)\ndom_m = html.fromstring(response_m.text)\nblocks_m = dom_m.xpath(\"//li[@class='list__item'] | //li[@class='list__item hidden_small']\")\n\nfor block in blocks_m:\n item_m = {}\n\n name = block.xpath(\"./a[@class ='list__text']/text() | .//span[@class ='link__text']/text()\")[0]\n item_m['name'] = name.replace(\"\\xa0\", ' ')\n\n link = block.xpath(\".//a[@class ='list__text']/@href | .//a[@class ='link link_flex']/@href\")[0]\n item_m['link'] = mail + link\n\n response_m2 = requests.get(mail + link, headers=header)\n dom_m2 = html.fromstring(response_m2.text)\n blocks_m2 = dom_m2.xpath(\"//div[@class='breadcrumbs breadcrumbs_article js-ago-wrapper']\")\n\n for block2 in blocks_m2:\n\n source = block2.xpath(\".//span[@class='link__text']/text()\")\n item_m['source'] = source[0]\n\n date = block2.xpath(\".//span[@class='note__text breadcrumbs__text js-ago']/@datetime\")\n item_m['date'] = date[0][8:10] + ' ' + convers(date[0][5:7])\n item_m['time'] = date[0][11:16]\n\n links.append(item_m)\n\nfor link in links:\n news.insert_one(link)\n","sub_path":"4_dz. XPath.py","file_name":"4_dz. XPath.py","file_ext":"py","file_size_in_byte":4095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418126018","text":"import csv\nfrom typing import Any, Dict, List, Optional\n\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\nfrom langchain.document_loaders.unstructured import (\n UnstructuredFileLoader,\n validate_unstructured_version,\n)\n\n\nclass CSVLoader(BaseLoader):\n \"\"\"Loads a CSV file into a list of documents.\n\n Each document represents one row of the CSV file. Every row is converted into a\n key/value pair and outputted to a new line in the document's page_content.\n\n The source for each document loaded from csv is set to the value of the\n `file_path` argument for all documents by default.\n You can override this by setting the `source_column` argument to the\n name of a column in the CSV file.\n The source of each document will then be set to the value of the column\n with the name specified in `source_column`.\n\n Output Example:\n .. code-block:: txt\n\n column1: value1\n column2: value2\n column3: value3\n \"\"\"\n\n def __init__(\n self,\n file_path: str,\n source_column: Optional[str] = None,\n csv_args: Optional[Dict] = None,\n encoding: Optional[str] = None,\n ):\n \"\"\"\n\n Args:\n file_path: The path to the CSV file.\n source_column: The name of the column in the CSV file to use as the source.\n Optional. Defaults to None.\n csv_args: A dictionary of arguments to pass to the csv.DictReader.\n Optional. Defaults to None.\n encoding: The encoding of the CSV file. Optional. Defaults to None.\n \"\"\"\n self.file_path = file_path\n self.source_column = source_column\n self.encoding = encoding\n self.csv_args = csv_args or {}\n\n def load(self) -> List[Document]:\n \"\"\"Load data into document objects.\"\"\"\n\n docs = []\n with open(self.file_path, newline=\"\", encoding=self.encoding) as csvfile:\n csv_reader = csv.DictReader(csvfile, **self.csv_args) # type: ignore\n for i, row in enumerate(csv_reader):\n content = \"\\n\".join(f\"{k.strip()}: {v.strip()}\" for k, v in row.items())\n try:\n source = (\n row[self.source_column]\n if self.source_column is not None\n else self.file_path\n )\n except KeyError:\n raise ValueError(\n f\"Source column '{self.source_column}' not found in CSV file.\"\n )\n metadata = {\"source\": source, \"row\": i}\n doc = Document(page_content=content, metadata=metadata)\n docs.append(doc)\n\n return docs\n\n\nclass UnstructuredCSVLoader(UnstructuredFileLoader):\n \"\"\"Loader that uses unstructured to load CSV files. Like other\n Unstructured loaders, UnstructuredCSVLoader can be used in both\n \"single\" and \"elements\" mode. If you use the loader in \"elements\"\n mode, the CSV file will be a single Unstructured Table element.\n If you use the loader in \"elements\" mode, an HTML representation\n of the table will be available in the \"text_as_html\" key in the\n document metadata.\n\n Examples\n --------\n from langchain.document_loaders.csv_loader import UnstructuredCSVLoader\n\n loader = UnstructuredCSVLoader(\"stanley-cups.csv\", mode=\"elements\")\n docs = loader.load()\n \"\"\"\n\n def __init__(\n self, file_path: str, mode: str = \"single\", **unstructured_kwargs: Any\n ):\n \"\"\"\n\n Args:\n file_path: The path to the CSV file.\n mode: The mode to use when loading the CSV file.\n Optional. Defaults to \"single\".\n **unstructured_kwargs: Keyword arguments to pass to unstructured.\n \"\"\"\n validate_unstructured_version(min_unstructured_version=\"0.6.8\")\n super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)\n\n def _get_elements(self) -> List:\n from unstructured.partition.csv import partition_csv\n\n return partition_csv(filename=self.file_path, **self.unstructured_kwargs)\n","sub_path":"langchain/document_loaders/csv_loader.py","file_name":"csv_loader.py","file_ext":"py","file_size_in_byte":4195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"317283325","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport os.path\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\ntransform = transforms.Compose(\n [\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\nroot = os.path.join(BASE_DIR, '../data/hymenoptera_data')\ntrainset = torchvision.datasets.ImageFolder(root=os.path.join(root, 'train'), transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset,\n shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.ImageFolder(root=os.path.join(root, 'val'), transform=transform)\ntestloader = torch.utils.data.DataLoader(testset,\n shuffle=False, num_workers=2)\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nclass Net1(nn.Module):\n def __init__(self):\n super(Net1, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 53 * 53, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 2)\n\n def forward(self, x):\n # print('input', x.shape)\n x = self.conv1(x)\n # print('conv', x.shape)\n x = F.relu(x)\n # print('relu', x.shape)\n x = self.pool(x)\n # print('pool', x.shape)\n\n x = self.conv2(x)\n # print('conv', x.shape)\n x = F.relu(x)\n # print('relu', x.shape)\n x = self.pool(x)\n # print('pool', x.shape)\n\n x = x.view(-1, 16 * 53 * 53)\n # print('view', x.shape)\n\n x = self.fc1(x)\n # print('Linear', x.shape)\n x = F.relu(x)\n # print('relu', x.shape)\n\n x = self.fc2(x)\n # print('Linear', x.shape)\n x = F.relu(x)\n # print('relu', x.shape)\n\n x = self.fc3(x)\n # print('Linear', x.shape)\n return x\n\n# input torch.Size([1, 1, 28, 28])\n# conv torch.Size([1, 6, 24, 24])\n# relu torch.Size([1, 6, 24, 24])\n# pool torch.Size([1, 6, 12, 12])\n# conv torch.Size([1, 16, 8, 8])\n# relu torch.Size([1, 16, 8, 8])\n# pool torch.Size([1, 16, 4, 4])\n# view torch.Size([1, 256])\n# Linear torch.Size([1, 120])\n# relu torch.Size([1, 120])\n# Linear torch.Size([1, 84])\n# relu torch.Size([1, 84])\n# Linear torch.Size([1, 100])\n\nclass Net2(nn.Module):\n def __init__(self):\n super(Net2, self).__init__()\n self.conv1 = nn.Conv2d(1, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 53 * 53, 2)\n\n def forward(self, x):\n # print('input', x.shape)\n x = self.conv1(x)\n # print('conv', x.shape)\n x = F.relu(x)\n # print('relu', x.shape)\n x = self.pool(x)\n # print('pool', x.shape)\n\n x = self.conv2(x)\n # print('conv', x.shape)\n x = F.relu(x)\n # print('relu', x.shape)\n x = self.pool(x)\n # print('pool', x.shape)\n\n x = x.view(-1, 16 * 53 * 53)\n # print('view', x.shape)\n\n x = self.fc1(x)\n return x\n\n\nclass Train:\n def __init__(self, nets):\n self.nets = nets\n self.optimizers = [optim.SGD(net.parameters(), lr=0.001, momentum=0.9) for net in nets]\n self.running_losss = [.0]*len(nets)\n def start_train(self):\n self.reset_loss()\n for net in self.nets:\n net.train()\n\n def reset_loss(self):\n self.running_losss = [.0] * len(self.nets)\n\n def train(self, inputs, labels):\n for i in range(len(self.nets)):\n net, optimizer = self.nets[i], self.optimizers[i],\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n self.running_losss[i] += loss.item()\n\n def start_test(self):\n self.corrects = [0] * len(self.nets)\n self.totals = [0] * len(self.nets)\n for net in self.nets:\n net.eval()\n\n def test(self, inputs, labels):\n for i in range(len(self.nets)):\n net = self.nets[i]\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n self.totals[i] += labels.size(0)\n self.corrects[i] += (predicted == labels).sum().item()\n\n\ncriterion = nn.CrossEntropyLoss()\n\ntrain = Train([Net1()])\n\nfor epoch in range(10): # loop over the dataset multiple times\n train.start_train()\n print('start epoch', epoch+1)\n i = 0\n for inputs, labels in trainloader:\n # zero the parameter gradients\n train.train(inputs, labels)\n\n if i % 5000 == 4999: # print every 2000 mini-batches\n print(i + 1, [i/5000 for i in train.running_losss])\n train.reset_loss()\n i += 1\n\n train.start_test()\n with torch.no_grad():\n for data in testloader:\n images, labels = data\n train.test(images, labels)\n\n for correct, total in zip(train.corrects, train.totals):\n print(f'{correct} / {total}, {100 * correct / total}%')\n\n print()\n\n\n\n#\n# [1, 5000] loss: 0.531\n# [1, 10000] loss: 0.151\n# [1, 15000] loss: 0.103\n# [1, 20000] loss: 0.088\n# [1, 25000] loss: 0.085\n# [1, 30000] loss: 0.078\n# [1, 35000] loss: 0.061\n# [1, 40000] loss: 0.060\n# [1, 45000] loss: 0.063\n# [1, 50000] loss: 0.067\n# [1, 55000] loss: 0.058\n# [1, 60000] loss: 0.061\n# 9829 / 10000, 98.29%\n# [2, 5000] loss: 0.038\n# [2, 10000] loss: 0.034\n# [2, 15000] loss: 0.041\n# [2, 20000] loss: 0.044\n# [2, 25000] loss: 0.040\n# [2, 30000] loss: 0.046\n# [2, 35000] loss: 0.039\n# [2, 40000] loss: 0.042\n# [2, 45000] loss: 0.042\n# [2, 50000] loss: 0.035\n# [2, 55000] loss: 0.039\n# [2, 60000] loss: 0.043\n# 9871 / 10000, 98.71%\n# [3, 5000] loss: 0.019\n# [3, 10000] loss: 0.023\n# [3, 15000] loss: 0.024\n# [3, 20000] loss: 0.028\n# [3, 25000] loss: 0.026\n# [3, 30000] loss: 0.028\n# [3, 35000] loss: 0.025\n# [3, 40000] loss: 0.030\n# [3, 45000] loss: 0.032\n# [3, 50000] loss: 0.029\n# [3, 55000] loss: 0.033\n# [3, 60000] loss: 0.025\n# 9913 / 10000, 99.13%\n# [4, 5000] loss: 0.012\n# [4, 10000] loss: 0.018\n# [4, 15000] loss: 0.015\n# [4, 20000] loss: 0.014\n# [4, 25000] loss: 0.008\n# [4, 30000] loss: 0.020\n# [4, 35000] loss: 0.017\n# [4, 40000] loss: 0.020\n# [4, 45000] loss: 0.014\n# [4, 50000] loss: 0.021\n# [4, 55000] loss: 0.027\n# [4, 60000] loss: 0.025\n# 9922 / 10000, 99.22%\n# [5, 5000] loss: 0.008\n# [5, 10000] loss: 0.018\n# [5, 15000] loss: 0.012\n# [5, 20000] loss: 0.007","sub_path":"python/py3study/pytorch-lab/demo-hymenoptera.py","file_name":"demo-hymenoptera.py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"503531016","text":"# Кто самый умный супергерой?\n# Есть API по информации о супергероях.\n# Нужно определить кто самый умный(intelligence) из трех супергероев- Hulk, Captain America, Thanos.\n# Для определения id нужно использовать метод /search/name\n#\n# Токен, который нужно использовать для доступа к API: 2619421814940190.\n# Таким образом, все адреса для доступа к API должны начинаться с https://superheroapi.com/api/2619421814940190/\n\n\nimport requests\nimport operator\n\nhero_list_data = ['Hulk', 'Captain', 'America', 'Thanos']\n\n\ndef get_data(hero_list):\n result_data = {}\n for hero in hero_list:\n result = requests.get(f'https://www.superheroapi.com/api.php/2619421814940190/search/{hero}')\n result_data[result.json()['results'][0]['name']] = result.json()['results'][0]['powerstats']['intelligence']\n return result_data\n\n\ndef compare_intelligence(dict1):\n sorted_hero_list = sorted(dict1.items(), key=operator.itemgetter(1))\n winner = sorted_hero_list[0][0]\n return winner\n\n\nresult = get_data(hero_list_data)\nprint(compare_intelligence(result))\n","sub_path":"superhero_API.py","file_name":"superhero_API.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"387077698","text":"#!/usr/bin/env python\n\nimport logging\n\nfrom googleapiclient import errors\n\nfrom brkt_cli.util import append_suffix\nfrom brkt_cli.gcp.gcp_service import GCP_NAME_MAX_LENGTH\n\nlog = logging.getLogger(__name__)\n\n\ndef wrap_guest_image(gcp_svc, image_id, encryptor_image, zone,\n metadata, instance_name=None, image_project=None,\n image_file=None, image_bucket=None,\n instance_type='n1-standard-4', network=None,\n subnet=None, cleanup=True, ssd_disks=0, gcp_tags=None):\n try:\n keep_encryptor = True\n if not encryptor_image:\n log.info('Retrieving encryptor image from GCP bucket')\n try:\n encryptor_image = gcp_svc.get_latest_encryptor_image(zone,\n image_bucket, image_file=image_file)\n keep_encryptor = False\n except errors.HttpError as e:\n encryptor_image = None\n log.exception('GCP API call to retrieve image failed')\n return\n\n if not instance_name:\n instance_name = 'brkt-guest-' + gcp_svc.get_session_id()\n guest_disk_name = append_suffix(instance_name, '-unencrypted',\n GCP_NAME_MAX_LENGTH)\n else:\n guest_disk_name = append_suffix(instance_name,\n gcp_svc.get_session_id(),\n GCP_NAME_MAX_LENGTH)\n \n gcp_svc.disk_from_image(zone, image_id, guest_disk_name, image_project)\n log.info('Waiting for guest root disk to become ready')\n gcp_svc.wait_for_detach(zone, guest_disk_name)\n\n guest_disk = gcp_svc.get_disk(zone, guest_disk_name)\n guest_disk['autoDelete'] = True\n disks = [guest_disk]\n for x in range(ssd_disks):\n ssd_disk = gcp_svc.create_ssd_disk(zone)\n disks.append(ssd_disk)\n\n log.info('Launching wrapped guest image')\n gcp_svc.run_instance(zone=zone,\n name=instance_name,\n image=encryptor_image,\n instance_type=instance_type,\n network=network,\n subnet=subnet,\n disks=disks,\n delete_boot=True,\n metadata=metadata,\n tags=gcp_tags)\n gcp_svc.wait_instance(instance_name, zone)\n log.info(\"Instance %s (%s) launched successfully\" % (instance_name,\n gcp_svc.get_instance_ip(instance_name, zone)))\n except errors.HttpError as e:\n log.exception('GCP API request failed: {}'.format(e.message))\n finally:\n if not cleanup:\n log.info(\"Not cleaning up\")\n else:\n if not keep_encryptor and encryptor_image:\n log.info('Deleting encryptor image %s' % encryptor_image)\n gcp_svc.delete_image(encryptor_image)\n\n return instance_name\n\n\n","sub_path":"brkt_cli/gcp/wrap_gcp_image.py","file_name":"wrap_gcp_image.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125128526","text":"HEIGHT = 0.3\nEPS = 0.05\n\n\nclass Environment(object):\n def __init__(self, idx):\n self.idx = idx\n self.l = HEIGHT\n self.w = HEIGHT\n self.h = HEIGHT\n if self.idx == 0:\n self.x = 30 * HEIGHT\n self.y = 0\n self.z = HEIGHT / 2.0\n if self.idx == 1:\n self.x = 0\n self.y = 30 * HEIGHT\n self.z = HEIGHT / 2.0\n if self.idx == 2:\n self.x = -30 * HEIGHT\n self.y = 0\n self.z = HEIGHT / 2.0\n if self.idx == 3:\n self.x = 0\n self.y = -30 * HEIGHT\n self.z = HEIGHT / 2.0\n\n def send_to(self, sim):\n light_source = sim.send_box(x=self.x, y=self.y, z=self.z,\n length=self.l, width=self.w, height=self.h,\n r=0.5, g=0.5, b=0.5)\n sim.send_light_source(light_source)\n","sub_path":"Morphology 2 Env/Baseline/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"558729278","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef plotData(X, y):\n y1 = np.where(y == 1)\n y2 = np.where(y == 0)\n pos = plt.plot(X[y1,0], X[y1,1], marker='+', color='k', linestyle='None')[0]\n neg = plt.plot(X[y2,0], X[y2,1], marker='.', color='y', linestyle='None')[0]\n \n return plt\n","sub_path":"ex6-python/plotData.py","file_name":"plotData.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"88819066","text":"\"\"\"This file contains code inspired from https://msdn.microsoft.com/en-us/library/bb259689.aspx\"\"\"\n\nfrom math import pi, radians, log, sin\nimport urllib\nimport urllib2\nimport xml.etree.ElementTree as et\n\n\n#returns the Tile coordinates of a given point and a level of detail\ndef getTile(long, lat, lvl):\n X = ((long + 180)/360)*256*(2**lvl)\n Y = (0.5 - log((1 + sin(radians(lat)))/(1 - sin(radians(lat))))/(4*pi))*256*2**(lvl)\n\n return int(X/256), int(Y/256)\n\n#returns the quadkey of a tile given it's coordinates and a level of detail\ndef getQuadkey(X, Y, lvl):\n f = '0%db' % lvl\n x = format(X, f)\n y = format(Y, f)\n\n quadkey2 = \"\"\n quadkey4 = \"\"\n\n for bit1, bit2 in zip(x, y):\n quadkey2 += bit2 + bit1\n\n for bit1, bit2 in zip(quadkey2[0::2], quadkey2[1::2]):\n b2 = bit1 + bit2\n integer = int(b2, 2)\n quadkey4 += str(integer)\n\n return quadkey4\n\n#returns the most zoomed in quadkey common of two points, \"\" if none could be found\ndef common_quadkey(long1, lat1, long2, lat2):\n #print long1, lat1, long2, lat2\n if long1 < -180 or long1 > 180\\\n or long2 < -180 or long2 > 180\\\n or lat1 < -85.05112878 or lat1 > 85.05112878\\\n or lat2 < -85.05112878 or lat2 > 85.05112878:\n\n exit(\"Please enter longitudes values between -180 and 180 \"\n \"and latitude values between -85.05112878 and 85.05112878\")\n\n\n lvls = range(1, 24)[::-1]\n\n for lvl in lvls:\n tile = getTile(long1, lat1, lvl)\n if tile == getTile(long2, lat2, lvl):\n return getQuadkey(tile[0], tile[1], lvl)\n\n return \"\"\n\ndef requestbingserverforimageurl(quadkey):\n imageURL = ''\n bing_map_key = 'Aq66dFa81v2YuGNYpgi3SlpJwzpUgVA4SgdWuu2mEd_QELC8mGZ8wCilOF3V-J6A'\n source_info = str(urllib2.urlopen('http://dev.virtualearth.net/REST/v1/Imagery/Metadata/AerialWithLabels?key='+bing_map_key+'&o=xml').read())\n # print source_info\n with open(\"source_xml_file.xml\", \"w\") as source_xml_file:\n source_xml_file.write(source_info)\n with open(\"source_xml_file.xml\", \"rt\") as source_xml_file:\n tree = et.parse(source_xml_file)\n root = tree.getroot()\n # print [item.text for item in root.findall('ImageUrl')]\n imageURL = str([element.text for element in root.iter() if element.tag.split('}')[1] == 'ImageUrl'][0])\n # print imageURL\n imageURL = imageURL.replace('{subdomain}', 't1')\n imageURL = imageURL.replace('{quadkey}', str(quadkey))\n imageURL = imageURL.replace('{culture}', 'en-US')\n\n #print 'after:', imageURL\n urllib.urlretrieve(imageURL, str(quadkey)+'.jpeg')\n return imageURL\n\n # print str(urllib2.urlopen('http://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?key='+bing_map_key+'&o=xml').read())\n # ImageUrl\n\n\ndef main_fnc():\n\n while True:\n latlng1 = raw_input(\"Enter Latitude and Longitude of the First Location (separated by Commas )\")\n lat1 = latlng1.split(',')[0]\n long1 = latlng1.split(',')[1]\n latlng2 = raw_input(\"Enter Latitude and Longitude of the Second Location (separated by Commas )\")\n lat2 = latlng2.split(',')[0]\n long2 = latlng2.split(',')[1]\n quad_key = common_quadkey(float(long1), float(lat1), float(long2), float(lat2))\n # print quad_key\n image_url = requestbingserverforimageurl(quad_key)\n continue_flag = raw_input(\"Do you want to Continue (y/n)\")\n if continue_flag == 'n':\n break\n\nmain_fnc()\n","sub_path":"src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"310784556","text":"import re\r\nimport copy\r\nimport logging\r\nimport argparse\r\nfrom beautifultable import BeautifulTable\r\nfrom datetime import datetime\r\nimport time\r\n\r\nLOG_FILENAME = \"logfile.log\"\r\nSTARTED_TIME = time.time()\r\n\r\n# Command line inputs (argv)\r\nparser = argparse.ArgumentParser(description='Necessary information to run the program.')\r\nparser.add_argument('filename',\r\n type=str,\r\n help='A required filename to investigate, i.e: .txt')\r\nparser.add_argument('--columns',\r\n type=str,\r\n nargs='?',\r\n help='Columns to filter, i.e: --columns datetime,ip')\r\nparser.add_argument('--filter',\r\n type=str,\r\n help='A condition for filter, i.e --filter errorlevel>20')\r\nparser.add_argument('--format',\r\n type=str,\r\n help='Format to display, i.e: --format value')\r\nparser.add_argument('--seperator',\r\n type=str,\r\n help='Choose the seperator you want to display, i.e: --seperator `;`')\r\nargs = parser.parse_args()\r\n\r\n# LL's Nodes\r\nclass Node:\r\n def __init__(self, dataval = None):\r\n self.dataval = dataval,\r\n self.nextval = None\r\n\r\n# Linked List's class\r\nclass LinkedList:\r\n def __init__(self):\r\n self.headval = None\r\n\r\n def AtEnd(self, newdata):\r\n NewNode = Node(newdata)\r\n if self.headval is None:\r\n self.headval = NewNode\r\n return\r\n lastElement = self.headval\r\n while(lastElement.nextval):\r\n lastElement = lastElement.nextval\r\n lastElement.nextval = NewNode\r\n\r\n def printList(self):\r\n printVal = self.headval\r\n while printVal is not None:\r\n print(printVal.dataval)\r\n printVal = printVal.nextval\r\n\r\nclass Analyzer:\r\n def __init__(self, columns, filter, format, filename):\r\n self.filename = filename\r\n self.columns = columns\r\n self.filter = re.split(',', filter)\r\n self.format = format\r\n self.masterCols = ['TYPE', 'N', 'DATETIME', 'ERRORLEVEL', 'DEVICEID', 'USERNAME', 'MESSAGE', 'MOBILEID']\r\n self.slaveCols = ['TYPE', 'N', 'DATETIME', 'ERRORLEVEL', 'DEVICEID', 'ACTION', 'MESSAGE', 'IP']\r\n self.masterLL = None\r\n self.slaveLL = None\r\n self.file = None\r\n self.fileLines = None\r\n self.upperCols()\r\n self.writeLog()\r\n\r\n def writeLog(self):\r\n for handler in logging.root.handlers[:]:\r\n logging.root.removeHandler(handler)\r\n logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)\r\n logging.info(str(datetime.now()) + ' - New lunch with the following arguments: --columns - ' + args.columns.upper() + ' --filter - ' + self.filter[0].upper() + ' --format - ' + self.format.upper())\r\n logging.debug(str(datetime.now()) + ' - Analyzer method started..')\r\n\r\n def writeFinishLog(self):\r\n finishedTime = round(time.time() - STARTED_TIME,5)\r\n logging.info(str(datetime.now()) + ' - Finished, running time was : ' + str(finishedTime) + ' seconds')\r\n\r\n def upperCols(self):\r\n upperCols = []\r\n cols = ''.join(self.columns)\r\n cols = cols.split(\",\")\r\n for col in cols:\r\n upperCols.append(col.upper())\r\n self.columns = upperCols\r\n\r\n\r\n def getFile(self):\r\n try:\r\n self.file = open(self.filename, 'r')\r\n print(self.filename + ' has successfully loaded')\r\n print(\"-\" * len(self.filename) + \"-\" * 24)\r\n except Exception:\r\n print('Couldn\\'t open ' + self.filename + ', Please try again.')\r\n\r\n def getMasterLines(self):\r\n self.masterLL = LinkedList()\r\n if self.fileLines == None:\r\n self.fileLines = self.file.readlines()\r\n\r\n for line in self.fileLines:\r\n if line[0] == 'M':\r\n # Splitting each master line with commas\r\n values = [value.strip() for value in line.split(',', len(self.masterCols) - 1)]\r\n finalLine = []\r\n # Checks line with each of the filters inserted by user\r\n if self.filter is not None or len(self.filter) > 0:\r\n for eaFilter in self.filter:\r\n finalLine = self.convertFilterToCondition(eaFilter, values, self.masterCols)\r\n if finalLine is None:\r\n break\r\n if finalLine is not None:\r\n # Filtering by columns inserted by user\r\n finalLine = self.saveNesscaryParts(values, self.masterCols);\r\n # Adding to master's linked list.\r\n self.masterLL.AtEnd(finalLine)\r\n # Prints the linked list by inserted format\r\n if self.masterLL.headval == None:\r\n print('\\nThere\\'re no master lines using your filter.')\r\n elif ''.join(self.format).upper() == \"TABLE\":\r\n self.convertToTable(self.masterCols, self.masterLL)\r\n elif ''.join(self.format).upper() == \"LIST\":\r\n print('Printing master list:')\r\n self.convertToList(self.masterCols, self.masterLL)\r\n else:\r\n print(\"Nothing to print, format is not correct, please choose one of 'LIST' / 'TABLE' formats\")\r\n\r\n def getSlaveLines(self):\r\n self.slaveLL = LinkedList()\r\n if self.fileLines == None:\r\n self.fileLines = self.file.readlines()\r\n\r\n for line in self.fileLines:\r\n if line[0] == 'S':\r\n # Splitting each master line with commas\r\n values = [value.strip() for value in line.split(',', len(self.slaveCols) - 1)]\r\n finalLine = []\r\n # Checks line with each of the filters inserted by user\r\n if self.filter is not None or len(self.filter) > 0:\r\n for eaFilter in self.filter:\r\n finalLine = self.convertFilterToCondition(eaFilter, values, self.slaveCols)\r\n if finalLine is None:\r\n break\r\n if finalLine is not None:\r\n # Filtering by columns inserted by user\r\n finalLine = self.saveNesscaryParts(values, self.slaveCols)\r\n self.slaveLL.AtEnd(finalLine)\r\n # Prints the linked list by inserted format\r\n if self.slaveLL.headval == None:\r\n print('\\nThere\\'re no slave lines using your filter.')\r\n elif ''.join(self.format).upper() == 'TABLE':\r\n self.convertToTable(self.slaveCols, self.slaveLL)\r\n elif ''.join(self.format).upper() == 'LIST':\r\n print('Printing slave list:')\r\n self.convertToList(self.slaveCols, self.slaveLL)\r\n else:\r\n print(\"Nothing to print, format is not correct, please choose one of 'LIST' / 'TABLE' formats\")\r\n\r\n def saveNesscaryParts(self, line, cols):\r\n colIndexes = []\r\n # Getting cols indexes\r\n for idx,col in enumerate(cols):\r\n for column in self.columns:\r\n if col == column:\r\n colIndexes.append(idx)\r\n\r\n # Getting columns to delete\r\n colsToDelete = []\r\n for idx, col in enumerate(cols):\r\n if idx not in colIndexes:\r\n colsToDelete.append(idx)\r\n\r\n # Deleting unnecessary parts from inserted line\r\n for index in reversed(colsToDelete):\r\n if len(line) > index:\r\n del line[index]\r\n\r\n return line\r\n\r\n def convertFilterToCondition(self, filter, line, mainCols):\r\n operator = \"\"\r\n if \">=\" in filter:\r\n operator = \">=\"\r\n elif \">\" in filter:\r\n operator = \">\"\r\n elif \"<=\" in filter:\r\n operator = \"<=\"\r\n elif \"<\" in filter:\r\n operator = \"<\"\r\n elif \"==\" in filter:\r\n operator = \"==\"\r\n elif \"!=\" in filter:\r\n operator = \"!=\"\r\n if operator == \">\" or operator == \">=\" or operator == \"<\" or operator == \"<=\":\r\n newFilter = re.split(operator, filter)\r\n upperCol = newFilter[0].upper()\r\n for idx,col in enumerate(mainCols):\r\n if upperCol == col:\r\n if(eval(line[idx] + operator + newFilter[1])):\r\n return line\r\n else:\r\n return None\r\n elif operator == \"!=\":\r\n newFilter = re.split(operator, filter)\r\n upperCol = newFilter[0].upper()\r\n for idx, col in enumerate(mainCols):\r\n if upperCol == col:\r\n if (line[idx] != newFilter[1]):\r\n return line\r\n else:\r\n return None\r\n else:\r\n newFilter = re.split(operator, filter)\r\n upperCol = newFilter[0].upper()\r\n for idx, col in enumerate(mainCols):\r\n if upperCol == col:\r\n if(len(line) - 1 < idx):\r\n return None\r\n elif (line[idx] == newFilter[1]):\r\n return line\r\n else:\r\n return None\r\n\r\n def convertToTable(self, cols, list):\r\n relatedCols=[]\r\n # Ordering cols by masterCols / slaveCols\r\n for idx, col in enumerate(cols):\r\n for column in self.columns:\r\n if col == column:\r\n relatedCols.append(col)\r\n\r\n table = BeautifulTable()\r\n table.column_headers = relatedCols\r\n listElem = list.headval\r\n # Looping through the related linked list and adding it to table\r\n while(listElem is not None):\r\n row = listElem.dataval[0]\r\n while(len(row) < len(relatedCols)):\r\n row.append('N/A')\r\n table.append_row(row)\r\n listElem = listElem.nextval\r\n print(table)\r\n\r\n def convertToList(self, cols, list):\r\n columns = copy.deepcopy(cols);\r\n # Getting only the necessary cols by order of slaveCols / masterCols\r\n for col in columns:\r\n if col not in self.columns:\r\n columns.remove(col)\r\n loopingList = list.headval;\r\n\r\n # Looping through the related linked list and printing it\r\n i = 1\r\n while(loopingList is not None):\r\n print(str(i), end=\". \")\r\n for idx,col in enumerate(columns):\r\n if idx == len(loopingList.dataval[0]) - 1:\r\n print(col + \"= \" + loopingList.dataval[0][idx])\r\n elif idx < len(loopingList.dataval[0]) - 1:\r\n print(col + \"= \" + loopingList.dataval[0][idx] + \", \", end=\"\")\r\n i = i + 1\r\n loopingList = loopingList.nextval\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n analyzer = Analyzer(args.columns, args.filter, args.format, args.filename)\r\n analyzer.getFile()\r\n analyzer.getMasterLines()\r\n analyzer.getSlaveLines()\r\n analyzer.writeFinishLog()\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"145593680","text":"import json\nd = {}\nd1 = {}\ncm = 0\ndef genera_sottoalbero(fnome,x,fout):\n global d1,cm,d\n if cm == 0:\n x = [x]\n cm = 1\n d2 = {}\n a = (open(fnome,'r').read())\n d = json.loads(a)\n t = len(x)\n r = []\n for i in range(t):\n d2[x[i]] = d[x[i]]\n r+= d[x[i]]\n d2.update(d1)\n d1 = d2\n if r == []:\n with open(fout, \"w\") as f:\n json.dump(d1, f)\n d1 = {}\n cm = 0\n return \n x = r\n return genera_sottoalbero(fnome,x,fout)\ncm = 0\ndef cancella_sottoalbero(fnome,x,fout):\n global d\n global cm\n if cm == 0:\n d = list(d.items())\n u = len(d)\n for i in range (u):\n if x in d[i][1]:\n b8 = d[i][1]\n del b8[d[i][1].index(x)]\n d = dict(d)\n cm+=1\n x = [x]\n break \n t = len(x)\n r = []\n for i in range(t):\n r+= d[x[i]]\n del d[x[i]] \n if r == []:\n with open(fout, \"w\") as f:\n json.dump(d, f)\n cm = 0\n return\n x = r\n return cancella_sottoalbero(fnome,x,fout)\nmc = 0\ndm = {}\ncr = 0\n\ndef dizionario_livelli(fnome,fout):\n global mc,dm,cr,dga\n if len(fout) > 2:\n fout = [fout]\n a = (open(fnome,'r').read())\n dga = json.loads(a)\n d = ricerca_chiave(dga)\n m = list(d.items())\n fout+= [m[0][1]]\n dm[str(mc)] = [m[0][0]]\n return dizionario_livelli(fnome,fout)\n cr+=1\n a = (open(fnome,'r').read())\n d = json.loads(a)\n x = fout[1]\n r = []\n if type(x) == str:\n x = [x]\n dm[str(cr)] = sorted(x)\n for i in range(len(x)):\n mc+=1\n x1 = x[i]\n r += d[x1]\n if r == []:\n fout = fout[0]\n with open(fout, \"w\") as f:\n json.dump(dm, f)\n mc = 0\n dm = {}\n cr = 0\n return \n del fout[1]\n fout+=[r]\n return dizionario_livelli(fnome,fout)\ndiz1 = {} \ndga = ''\ncga = 0\ndef dizionario_gradi_antenati(fnome,y,fout):\n global diz1,cga,dga\n import collections\n if cga == 0:\n a = (open(fnome,'r').read())\n dga = json.loads(a)\n cga+=1\n dga = ricerca_chiave(dga)\n m = list(dga.items())\n diz1[m[0][0]] = 0\n return(dizionario_gradi_antenati(fnome,y,fout))\n d = dga\n m = list(d.items())\n for i in range(0,len(d)):\n u = m[i][1]\n u1 = m[i][0]\n lu = len(u)\n for i1 in range(lu):\n u2 = u[i1]\n if lu == y:\n r = diz1[u1] + 1\n diz1[u2] = r\n else:\n r = diz1[u1]\n diz1[u2] = r\n diz1 = dict(collections.OrderedDict(sorted(diz1.items())))\n with open(fout, \"w\") as f:\n json.dump(diz1, f) \n diz1 = {} \n dga = ''\n cga = 0\n return ()\n \n \n \ndef ricerca_chiave(dga):\n m = list(dga.values())\n m = [item for sublist in m for item in sublist] \n m1 = list(dga.keys())\n for i in range(len(m1)):\n if m1[i] not in m:\n if i > 0:\n dga = list(dga.items())\n m3 = dga[i]\n del dga[i]\n dga = [m3] + dga\n dga = dict(dga)\n return(dga)\n","sub_path":"students/1808728/homework04/program01.py","file_name":"program01.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"100304861","text":"#**********************************************************************\n# Copyright 2020 Advanced Micro Devices, Inc\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#********************************************************************\nimport sys\nimport subprocess\nfrom pathlib import Path\n\n\ndef main(*args):\n if not args:\n print(\"\"\"\nUsage\n\n build_usd.py [...]\n \nSpecify path to USD repository and arguments for build_scripts/build_usd.py script\nin USD repository.\n\"\"\")\n return\n\n usd_path = Path(args[0])\n usd_imaging_lite_path = Path(__file__).parent.parent / \"src/extras/usdImagingLite\"\n\n usd_imaging_cmake = usd_path / \"pxr/usdImaging/CMakeLists.txt\"\n print(\"Modifying:\", usd_imaging_cmake)\n cmake_txt = usd_imaging_cmake.read_text()\n usd_imaging_cmake.write_text(cmake_txt + f\"\"\"\nadd_subdirectory(\"{usd_imaging_lite_path.absolute().as_posix()}\" usdImagingLite)\n\"\"\")\n\n call_args = (sys.executable, str(usd_path / \"build_scripts/build_usd.py\"), *args[1:])\n print(\"Running:\", call_args)\n subprocess.run(call_args)\n\n print(\"Reverting:\", usd_imaging_cmake)\n usd_imaging_cmake.write_text(cmake_txt)\n\n\nif __name__ == \"__main__\":\n main(*sys.argv[1:])\n","sub_path":"tools/build_usd.py","file_name":"build_usd.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"100286062","text":"\"\"\"django_skeleton URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n \n Deal antiguo: url(r'^deal/(?P[-\\w]+)/?$', views.deal, name='deal')\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nfrom Gopeb.views import search, checkout, get_ideas, send_sms, deal, review, home, \\\n terms_conditions, billing, categories, frequently_asked_questions, payment_view, newsletter\nfrom people.views import login_view, register_view, logout_view\n\nif settings.DEBUG:\n urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\nelse:\n urlpatterns = []\n\nurlpatterns += [\n url(r'^admin/', admin.site.urls), # NO\n url(r'^paypal/', include('paypal.standard.ipn.urls')), # NO\n url(r'^tinymce/', include('tinymce.urls')), # NO\n url(r'^payment/', include('payment.urls', namespace='payment')),\n url(r'^pagar/$', payment_view, name=\"payment_view\"),\n\n url(r'^buscar/', search, name='search'),\n url(r'^checkout/', checkout, name='checkout'),\n url(r'^get_ideas/$', get_ideas, name='get_ideas'),\n url(r'^register/$', register_view, name='register'),\n url(r'^login/$', login_view, name='login'),\n url(r'^logout/$', logout_view, name='logout'),\n url(r'^billing/', billing, name='billing'),\n url(r'^categorias/', categories, name='categories'),\n url(r'^sms/', send_sms, name='send-sms'),\n url(r'^oferta/(?P[-\\w]+)/?$', deal, name='deal'),\n url(r'^recomendaciones/(?P[-\\w]+)/?$', review, name='review'),\n url(r'^newsletter/?$', newsletter, name='newsletter'),\n url(r'^condiciones/', terms_conditions, name='terms_conditions'),\n url(r'^preguntas_frecuentes/', frequently_asked_questions, name='frequently_asked_questions'),\n url(r'^$', home, name='home'),\n]\n","sub_path":"django_skeleton/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"385519492","text":"import sublime\nimport os\nfrom .javatar_actions import *\n\n\nSTATUS = \"Javatar\"\nSETTINGSBASE = None\nSETTINGS = None\n\n\ndef reset():\n\tgetAction().addAction(\"javatar.util.util.reset\", \"Reset all settings\")\n\tglobal SETTINGS, SETTINGSBASE\n\tSETTINGS = None\n\tSETTINGSBASE = None\n\tfrom .javatar_collections import resetSnippetsAndPackages\n\tresetSnippetsAndPackages()\n\n\ndef isReady():\n\treturn SETTINGS is not None\n\n\ndef readSettings(config):\n\tgetAction().addAction(\"javatar.util.util.read_settings\", \"Read settings\")\n\tglobal SETTINGS, SETTINGSBASE\n\tSETTINGSBASE = config\n\tSETTINGS = sublime.load_settings(config)\n\tfrom .javatar_collections import loadSnippetsAndPackages\n\tloadSnippetsAndPackages()\n\n\ndef getSettings(key):\n\tproject_data = sublime.active_window().project_data()\n\tif key in project_data:\n\t\treturn project_data[key]\n\treturn SETTINGS.get(key)\n\n\ndef setSettings(key, val, project=False):\n\tif project:\n\t\tproject_data = sublime.active_window().project_data()\n\t\tproject_data[key] = val\n\t\tsublime.active_window().set_project_data(project_data)\n\telse:\n\t\tSETTINGS.set(key, val)\n\t\tsublime.save_settings(SETTINGSBASE)\n\n\ndef isDebug():\n\treturn getSettings(\"debug_mode\")\n\n\ndef isStable():\n\treturn str.lower(getSettings(\"package_channel\")) == \"stable\"\n\n\ndef normalizePath(path):\n\tname = getPath(\"name\", path)\n\tparent = getPath(\"parent\", path)\n\tif parent != getPath(\"parent\", parent):\n\t\tparent = normalizePath(parent)\n\tfor dir in os.listdir(parent):\n\t\tif dir.lower() == name:\n\t\t\treturn getPath(\"join\", parent, dir)\n\treturn path\n\n\ndef splitPath(path):\n\trest, tail = os.path.split(path)\n\tif len(rest) <= 1:\n\t\treturn tail,\n\treturn splitPath(rest) + (tail,)\n\n\ndef mergePath(pathlist):\n\toutpath = \"\"\n\tfor path in pathlist:\n\t\toutpath = getPath(\"join\", outpath, path)\n\treturn outpath\n\n\ndef showStatus(text, delay=None, require_java=True):\n\tif delay is None:\n\t\tdelay = getSettings(\"status_delay\")\n\tfrom .javatar_validator import isJava\n\tif not isJava() and require_java:\n\t\treturn\n\tview = sublime.active_window().active_view()\n\tview.set_status(STATUS, text)\n\tif delay >= 0:\n\t\tsublime.set_timeout(hideStatus, delay)\n\n\ndef hideStatus():\n\tview = sublime.active_window().active_view()\n\tif view is not None:\n\t\tfrom .javatar_validator import isJava\n\t\tif isJava() and getSettings(\"show_package_path\"):\n\t\t\tview.set_status(STATUS, \"Package: \" + toReadablePackage(getCurrentPackage(), True))\n\t\telse:\n\t\t\tview.erase_status(STATUS)\n\n\ndef toReadableSize(filepath):\n\tif filepath[0:8] == \"Packages\":\n\t\tfilepath = sublime.packages_path()+filepath[8:]\n\tscales = [\n\t\t[1000**5, \"PB\"],\n\t\t[1000**4, \"TB\"],\n\t\t[1000**3, \"GB\"],\n\t\t[1000**2, \"MB\"],\n\t\t[1000**1, \"KB\"],\n\t\t[1000**0, \"B\"]\n\t]\n\tfilesize = os.path.getsize(filepath)\n\tfor scale in scales:\n\t\tif filesize >= scale[0]:\n\t\t\tbreak\n\treturn str(int(filesize/scale[0]*100)/100)+scale[1]\n\n\ndef getCurrentPackage(relative=False):\n\tfrom .javatar_validator import isProject, isFile\n\tif not relative and isFile() and getPath(\"current_dir\") is not None:\n\t\treturn toPackage(getPath(\"current_dir\"))\n\telif not relative and isProject() and getPath(\"project_dir\") is not None:\n\t\treturn toPackage(getPath(\"project_dir\"))\n\telse:\n\t\treturn \"\"\n\n\ndef toReadablePackage(package, asPackage=False):\n\tif not asPackage:\n\t\tpackage = toPackage(package)\n\tif package == \"\":\n\t\tfrom .javatar_validator import isProject\n\t\tif isProject():\n\t\t\tpackage = \"(Default Package)\"\n\t\telse:\n\t\t\tpackage = \"(Unknown Package)\"\n\treturn package\n\n\ndef toPackage(path, relative=True):\n\tif relative:\n\t\tpath = getPath(\"relative\", path, getPackageRootDir())\n\tpackage = \".\".join(splitPath(path))\n\tfrom .javatar_java import normalizePackage\n\treturn normalizePackage(package)\n\n\ndef getPackageRootDir(isSub=False):\n\tfrom .javatar_validator import isProject, isFile\n\tif isFile() and isSub:\n\t\treturn getPath(\"current_dir\")\n\telif isProject():\n\t\treturn getPath(\"project_dir\")\n\telif getPath(\"current_dir\") is not None:\n\t\treturn getPath(\"current_dir\")\n\telse:\n\t\treturn \"\"\n\n\ndef containsFile(directory, file):\n\treturn os.path.normcase(os.path.normpath(file)).startswith(os.path.normcase(os.path.normpath(directory)))\n\n\ndef getPath(type=\"\", dir=\"\", dir2=\"\"):\n\twindow = sublime.active_window()\n\tif type == \"project_dir\":\n\t\tfrom .javatar_validator import isFile\n\t\tpath = getSettings(\"source_folder\")\n\t\tif path != \"\":\n\t\t\treturn path\n\t\tif path is None:\n\t\t\tpath = \"\"\n\t\tfolders = window.folders()\n\t\tif len(folders) == 1:\n\t\t\treturn folders[0]\n\t\tfor folder in folders:\n\t\t\tif isFile() and containsFile(folder, getPath(\"current_file\")):\n\t\t\t\tpath = folder\n\t\t\t\tbreak\n\t\treturn path\n\telif type == \"current_dir\":\n\t\tif getPath(\"current_file\") is not None:\n\t\t\treturn getPath(\"parent\", getPath(\"current_file\"))\n\t\telse:\n\t\t\treturn None\n\telif type == \"current_file\":\n\t\treturn window.active_view().file_name()\n\telif type == \"parent\":\n\t\treturn os.path.dirname(dir)\n\telif type == \"relative\":\n\t\tif dir != \"\" and dir2 != \"\":\n\t\t\treturn os.path.relpath(dir, dir2)\n\t\telse:\n\t\t\treturn \"\"\n\telif type == \"name\":\n\t\treturn os.path.basename(dir)\n\telif type == \"join\":\n\t\treturn os.path.join(dir, dir2)\n\telif type == \"exist\":\n\t\treturn os.path.exists(dir)\n\telif type == \"javatar_parent\":\n\t\tname = __name__.split('.')\n\t\treturn name[0]\n\telse:\n\t\treturn \"\"\n","sub_path":"utils/javatar_utils.py","file_name":"javatar_utils.py","file_ext":"py","file_size_in_byte":5151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"284009323","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom appraisal.models import Appraisal, Comment\nfrom commune.models import Commune\nfrom region.models import Region\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.core.exceptions import ObjectDoesNotExist\nimport datetime\nfrom django.core.mail import send_mail\nfrom django.template import loader\n\nclass Notification(models.Model):\n ntype = models.CharField(max_length=100, default='')\n appraisal_id = models.IntegerField(null=True)\n comment_id = models.IntegerField(null=True)\n time_created = models.DateTimeField(\"Time created\",blank=True,null=True)\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', primary_key=True)\n first_name = models.CharField(max_length=100, default='')\n last_name = models.CharField(max_length=100, default='')\n email = models.EmailField(blank=False, default='')\n address = models.CharField(max_length=100, default='')\n phone = models.IntegerField(default=0)\n rut = models.CharField('RUT', max_length=14, null=True)\n addressStreet = models.CharField(\"Calle\",max_length=300,default=\"\")\n addressNumber = models.CharField(\"Numero\",max_length=10)\n addressCommune = models.ForeignKey(Commune,\n on_delete=models.CASCADE,\n verbose_name=\"Comuna\",\n blank=True,\n null=True,\n to_field='code')\n addressRegion = models.ForeignKey(Region,\n on_delete=models.CASCADE,\n verbose_name=\"Region\",\n blank=True,\n null=True,\n to_field='code')\n notifications = models.ManyToManyField(Notification)\n\n @property\n def has_address(self):\n if self.addressStreet == None or self.addressCommune == None or self.addressRegion == None:\n return False\n else:\n return True\n\n @property\n def address(self):\n if not self.has_address:\n return ''\n else:\n return self.addressStreet+' '+str(self.addressNumber)+', '+self.addressCommune.name+', '+self.addressRegion.shortName\n\n @property\n def full_name(self):\n return self.first_name + \" \" + self.last_name\n \n @property\n def full_name_short(self):\n return self.first_name + \" \" + self.last_name.split(' ')[0]\n\n @property\n def rut_verbose(self):\n return \"16.017.511-7\"\n\n @property\n def badge(self):\n if self.user.is_superuser:\n return '
Superuser
'\n groups = self.user.groups.values_list('name',flat=True)\n if 'tasador' in groups:\n return '
Tasador
'\n elif 'visador' in groups:\n return '
Visador
'\n elif 'asignador' in groups:\n return '
Asignador
'\n else:\n return ''\n \n def removeNotification(self,ntype=\"\",appraisal_id=\"\",comment_id=\"\"):\n if ntype == \"comment\":\n notifications = self.notifications.all().filter(appraisal_id=appraisal_id)\n for notification in notifications:\n self.notifications.remove(notification)\n\n def addNotification(self,ntype=\"\",appraisal_id=\"\",comment_id=\"\"):\n notification = Notification(\n ntype=ntype,\n appraisal_id=appraisal_id,\n comment_id=comment_id,\n time_created=datetime.datetime.now(datetime.timezone.utc))\n notification.save()\n self.notifications.add(notification)\n\n comment = Comment.objects.get(id=comment_id)\n # Send email\n if comment.event == Comment.EVENT_TASADOR_SOLICITADO:\n appraisal = Appraisal.objects.get(id=appraisal_id)\n html_message = loader.render_to_string('user/email_solicitud.html',{'user':self.user,'appraisal':appraisal})\n send_mail(\n subject='Asignación de tasación',\n message='',\n from_email='soporte@dataurbana.io',\n recipient_list=[self.user.email],\n fail_silently=False,\n html_message=html_message)\n \n if comment.event == Comment.EVENT_RETURNED:\n appraisal = Appraisal.objects.get(id=appraisal_id)\n html_message = loader.render_to_string('user/email_reconsideracion.html',{'user':self.user,'appraisal':appraisal})\n send_mail(\n subject='Tasación a ser reconsiderada',\n message='',\n from_email='soporte@dataurbana.io',\n recipient_list=[self.user.email],\n fail_silently=False,\n html_message=html_message)\n\n def hasNotificationAppraisal(self,id):\n '''\n Check if there is a notification for this user\n related to the appraisal given by the id\n '''\n for notification in self.notifications.all():\n if notification.ntype == \"comment\":\n if notification.appraisal_id == id:\n return True\n return False\n\n def hasNotificationComment(self,id):\n '''\n Check if there is a notification for this user\n related to the comment given by the id\n '''\n for notification in self.notifications.all():\n if notification.ntype == \"comment\":\n if notification.comment_id == id:\n return True\n return False\n\n def __str__(self):\n return self.user.username\n\n class Meta:\n \"\"\"\n \"\"\"\n permissions = (\n (\"view_accounting\", \"Can view accounting\"),\n (\"evaluate_tasador\", \"Can evaluate appraisers\"),)\n\n\n@receiver(post_save, sender=User)\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n userprofile = UserProfile.objects.create(user=instance, first_name=instance.first_name,\n last_name=instance.first_name, email=instance.email)\n userprofile.save()\n\n@receiver(post_save, sender=User)\ndef save_user_profile(sender, instance, **kwargs):\n try:\n instance.profile.save()\n except ObjectDoesNotExist:\n userprofile = UserProfile.objects.create(user=instance, first_name=instance.first_name,\n last_name=instance.first_name, email=instance.email)\n userprofile.save()\n instance.profile.save()\n","sub_path":"web/user/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"524390539","text":"import fresh_tomatoes\nimport media\n\n\n# Create six Movie objects for each of six movies.\nhateful_eight = media.Movie('The Hateful Eight',\n 'A story of intrigue, betrayal, and justice.',\n 'https://upload.wikimedia.org/wikipedia/en/d/d4/The_Hateful_Eight.jpg',\n 'https://www.youtube.com/watch?v=6_UI1GzaWv0')\n\n\nstar_wars = media.Movie('Star Wars',\n 'A young man learns The Force and discovers his destiny.',\n 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Star_Wars_Logo.svg/694px-Star_Wars_Logo.svg.png',\n 'https://www.youtube.com/watch?v=nywPf1p-BBY')\n\nshakespeare_in_love = media.Movie('Shakespeare in Love',\n 'William Shakespeare struggles with love and writer\\'s block.',\n 'https://upload.wikimedia.org/wikipedia/en/e/e8/Shakespeare_in_Love_1998_Poster.jpg',\n 'https://www.youtube.com/watch?v=v5R5La5f3eo')\n\nbig_lebowski = media.Movie('The Big Lebowski',\n 'The Dude gets more than he bargained for when seeking the men who defiled his rug.',\n 'https://upload.wikimedia.org/wikipedia/en/3/35/Biglebowskiposter.jpg',\n 'https://www.youtube.com/watch?v=cd-go0oBF4Y')\n\nin_bruges = media.Movie('In Bruges',\n 'Two Irish hitmen hide out in \"shithole\" Bruges.',\n 'https://upload.wikimedia.org/wikipedia/en/6/63/In_Bruges_Poster.jpg',\n 'https://youtu.be/p-gG2qo_l_A')\n\nmad_max = media.Movie('Mad Max: Fury Road',\n 'In postapocalyptic Australia the road is ruled by warriors.',\n 'https://upload.wikimedia.org/wikipedia/en/6/6e/Mad_Max_Fury_Road.jpg',\n 'https://www.youtube.com/watch?v=hEJnMQG9ev8')\n\n# Compile all six Movie objects into a list. \nmovies = [hateful_eight, star_wars, shakespeare_in_love, big_lebowski, in_bruges, mad_max]\n\n\n# Feed the list of Movie objects into a function call.\n# This function will dynamically generate a movie trailers web page \n# from a list of movies and their attributes. Opens browser window.\nfresh_tomatoes.open_movies_page(movies)\n\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"253308902","text":"#Escriba el codigo necesario para que al ejecutar\n#python ejercicio1.py se impriman los enteros del 10 al 1 en cuenta regresiva.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nlista=[]\nfor i in range (11):\n lista.append(i)\n \nnum=0 \nfor i in lista:\n num+=1\n print (lista[-num])\n \n\n ","sub_path":"ejercicio1.py","file_name":"ejercicio1.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"167306354","text":"import discord\nfrom discord.ext import commands\n\nfrom config import config\nfrom database_connector import Database\nfrom discord_bot.checks import is_in_admin_channel\nfrom discord_bot.colours import green, red\n\nstartup_extensions = [\n \"discord_bot.reporting\"\n]\n\n\nclass Admin():\n\n def __init__(self, bot):\n self.bot = bot\n self.database = Database()\n self.cnx, self.cursor = self.database.get_connection()\n for extension in startup_extensions:\n try:\n print(\"Loading {}\".format(extension))\n bot.load_extension(extension)\n print(\"Loaded!\")\n except Exception as e:\n exc = '{}: {}'.format(type(e).__name__, e)\n print('Failed to load extension {}\\n{}'.format(extension, exc))\n\n @is_in_admin_channel()\n @commands.command()\n async def unload(self, ctx, extension_name: str):\n \"\"\"Unloads an extension.\"\"\"\n self.bot.unload_extension(extension_name)\n await ctx.send(\"{} unloaded.\".format(extension_name))\n\n @is_in_admin_channel()\n @commands.command()\n async def load(self, ctx, extension_name: str):\n \"\"\"Loads an extension. \"\"\"\n self.bot.load_extension(extension_name)\n await ctx.send(\"{} loaded.\".format(extension_name))\n\n @is_in_admin_channel()\n @commands.command()\n async def reload(self, ctx):\n print(\"==RELOAD==\")\n \"\"\"Reload all existing cogs\"\"\"\n reload_text = \"Reloading {}\"\n startup_extensions_temp = startup_extensions\n startup_extensions_temp.insert(0, \"discord_bot.admin\")\n\n em = discord.Embed(title=\"Reloading - please wait\", color=red)\n output = await ctx.channel.send(embed=em)\n\n for cog in startup_extensions_temp:\n self.bot.unload_extension(cog)\n self.bot.load_extension(cog)\n\n em = discord.Embed(title=\"Finished!\", colour=green)\n await output.edit(embed=em)\n\n @is_in_admin_channel()\n @commands.command(pass_context=True)\n async def tickets(self, ctx, urgency: int = 5, only_open = 1):\n \"\"\" Gets all tickets that have been stored.\n Usage: ticket;list [urgency_level] [only_open].\n If no params are specified, urgency_level defaults to 4 and only_open defaults to 1\n Example: ticket;list 1 0 to show all tickets with urgency level 1, regardless of whether or not they are open.\"\"\"\n async with ctx.channel.typing():\n print(str(only_open) + \" | \" + str(type(only_open)))\n print(str(urgency) + \" | \" + str(type(urgency)))\n only_open = bool(only_open)\n urgency = int(urgency) + 1\n raw_tickets = self.database.get_tickets(only_open=only_open, urgency=urgency)\n ticket_list = self.database.create_ticket_classes(raw_tickets[0])\n print(len(ticket_list))\n\n if len(ticket_list) == 0:\n await ctx.channel.send(\"No tickets returned\")\n for ticket in ticket_list:\n em = discord.Embed(title=\"Ticket by \" + ticket.author, description=\"For more info, click the URL\")\n\n em.add_field(name=\"ID\", value=ticket.id)\n\n em.add_field(name=\"Author\", value=ticket.author)\n\n em.add_field(name=\"Category\", value=ticket.category_name)\n\n em.add_field(name=\"Message\", value=ticket.message, inline=False)\n\n em.add_field(name=\"Is open?\", value=ticket.is_open, inline=False)\n\n if ticket.is_open == 1:\n colour = 0xEF1300\n else:\n colour = 0x00CC66\n if ticket.is_open != 1:\n em.add_field(name=\"Closed by\", value=ticket.closed_by)\n em.add_field(name=\"Close reason\", value=ticket.close_reason)\n #em.add_field(name=\"Close date\", value=ticket.date_closed)\n em.colour = colour\n\n em.add_field(name=\"Date created\", value=ticket.date_added)\n\n em.add_field(name=\"Date last modified\", value=ticket.date_last_modified)\n\n em.add_field(name=\"URL\", value=\"https://{}/tickets/single?id={}\".format(config.domain, ticket.id), inline=False)\n\n await ctx.channel.send(embed=em)\n\n @is_in_admin_channel()\n @commands.command(pass_context=True)\n async def close(self, ctx, ticket: str, reason: str):\n \"\"\"Close a ticket. If you just pass the ID, reason will default to \"Ticket Resolved\"\n Usage: ticket;close [ticketid]\"\"\"\n try:\n author_id = str(ctx.message.author.display_name)\n ticket_id = int(ticket)\n success = self.database.close_ticket(ticket_id, author_id, reason)\n if success:\n await ctx.channel.send(\"Closed ticket {}\".format(ticket_id))\n else:\n await ctx.channel.send(\"Ticket does not exist!\")\n except ValueError:\n await ctx.channel.send(\"Please enter a valid number.\")\n\n @is_in_admin_channel()\n @commands.command()\n async def addnote(self, ctx, ticket: int, note: str):\n \"\"\"Add a note to a ticket - note, running this on a ticket that does not exist, doesn't output an error.\n Usage: ticket;addnote [ticket id] [note text]\n Example: ticket;addnote 5 \"ugh this ticket sux\" \"\"\"\n\n self.database.add_note(ticket, note)\n await ctx.channel.send(\"Done!\")\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n","sub_path":"discord_bot/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"55941901","text":"import torch.utils.data\nimport torch.autograd as autograd\n\nfrom utils.parser import get_parser_with_args\nfrom utils.helpers import (get_test_loaders, get_criterion,\n initialize_metrics, get_mean_metrics,\n set_test_metrics)\nfrom sklearn.metrics import precision_recall_fscore_support as prfs\nfrom tqdm import tqdm\n\n\nparser, metadata = get_parser_with_args()\nopt = parser.parse_args()\n\ndev = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\ntest_loader = get_test_loaders(opt)\n\npath = 'tmp/checkpoint_epoch_64.pt'\nmodel = torch.load(path)\ncriterion = get_criterion(opt)\n\nmodel.eval()\n\nval_metrics = initialize_metrics()\nwith torch.no_grad():\n tbar = tqdm(test_loader)\n for batch_img1, batch_img2, labels in tbar:\n # Set variables for training\n batch_img1 = autograd.Variable(batch_img1).float().to(dev)\n batch_img2 = autograd.Variable(batch_img2).float().to(dev)\n labels = autograd.Variable(labels).long().to(dev)\n\n # Get predictions and calculate loss\n cd_preds = model(batch_img1, batch_img2)\n\n cd_preds = cd_preds[-1]\n _, cd_preds = torch.max(cd_preds, 1)\n\n # Calculate and log other batch metrics\n cd_corrects = (100 *\n (cd_preds.squeeze().byte() == labels.squeeze().byte()).sum() /\n (labels.size()[0] * (opt.patch_size**2)))\n\n cd_val_report = prfs(labels.data.cpu().numpy().flatten(),\n cd_preds.data.cpu().numpy().flatten(),\n average='binary',\n pos_label=1)\n\n test_metrics = set_test_metrics(val_metrics,\n cd_corrects,\n cd_val_report)\n\n # log the batch mean metrics\n mean_test_metrics = get_mean_metrics(test_metrics)\n\n # clear batch variables from memory\n del batch_img1, batch_img2, labels\n\n print(\"EPOCH VALIDATION METRICS\", mean_test_metrics)","sub_path":"eval_metrics.py","file_name":"eval_metrics.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"26226902","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport os\nfrom scipy import interpolate\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\ndef count(temp):\n countx=0\n while 1:\n if (temp[0]==temp[countx]):\n countx+=1\n else:\n break\n return countx\ndef wtf_sort(tx,ty,n,x,y,tol):\n ww=np.full([ty,tx ,n],np.nan)\n tt=np.split(np.argsort(x),tx)\n for i in range (tx):\n temp=tol[tt[i],:]\n tty=np.argsort(temp[:,1])\n temp=temp[tty,:]\n ww[:,i,:]=temp\n return ww\nt='c'\ntype_=1\nfor i in range(35):\n n=1\n a=np.loadtxt('%s\\\\iteration\\\\Iteration%d.inp'%(t,i+1),delimiter=',')\n s=np.loadtxt('%s\\\\s\\\\S_DATA%d.inp'%(t,i+1),delimiter=',')\n e=np.loadtxt('%s\\\\E_P_PERM\\\\ID_E_P%d.inp'%(t,i+1),delimiter=',')\n d=np.loadtxt('%s\\\\DIFFUSION\\\\diffusion_iteration%d.inp'%(t,i+1),delimiter=',')\n sss=np.concatenate((a[:,1:],d[:,1][:,np.newaxis],e[:,[1,2,3]],s[:,1][:,np.newaxis]),axis=1)\n x=a[:,1]\n y=a[:,2]\n loc=a[:,[1,2,13]]\n plt.scatter(x*100,y*100 ,c=s[:,1])\n plt.title('origin DAY %d'%(i), fontsize=20)\n plt.axis('equal')\n plt.savefig('orgia%d.png'%(i))\n plt.clf()\n temp_x=np.int64(np.sort(x)*(10**5))\n temp_y=np.int64(np.sort(y)*(10**5))\n ty=count(temp_x)\n tx=count(temp_y)\n if (tx*ty!=len(x)):\n print ('len error')\n final=wtf_sort(tx,ty,19,x,y,sss)\n plt.imshow(final[:,:,18][::-1])\n plt.title('reshape DAY %d'%(i), fontsize=20)\n plt.savefig('reshape%d.png'%(i))\n plt.clf()\n final=np.insert(final,19, values=i, axis=2)\n final=np.insert(final,20, values=type_, axis=2)\n cyka=np.reshape(final,[int(final.shape[0]*final.shape[1]),21])\n np.savetxt('%s'%(i),cyka)\nnp.savetxt('shape',[final.shape[0],final.shape[1]]) \n","sub_path":"box_type/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"392101525","text":"import argparse\n\nfrom .infocheck import InfoCheck\nfrom .imgcopier import ImageCopier\n\n\nclass Base:\n def __init__(self):\n p = argparse.ArgumentParser(\n description='Extract paintings from WikiArt dataset')\n\n p.add_argument('--style',\n type=str,\n default='',\n help='Painting style (e.g. realism, baroque)')\n\n p.add_argument('--genre',\n type=str,\n default='',\n help='Painting genre (e.g. portrait, landscape)')\n\n p.add_argument('--date',\n type=str,\n default='',\n help='Year that painting was created (e.g. 1960) or range (e.g. 1900,1999)')\n\n p.add_argument('--in_csv',\n type=str,\n default='train_info.csv',\n help='Location of CSV file')\n\n p.add_argument('--in_dir',\n type=str,\n default='input',\n help='Directory in which to store paintings')\n\n p.add_argument('--out_dir',\n type=str,\n default='output',\n help='Directory in which to store paintings')\n\n p.add_argument('--remove_original',\n type=bool,\n default=False,\n help='Remove image from original directory '\n 'when extracting')\n\n self.args = p.parse_args()\n\n def start(self):\n ImageCopier(\n self.args,\n InfoCheck(self.args).list_paintings)\n\n\ndef main():\n Base().start()\n print(\"Done.\")\n","sub_path":"art_extract/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"258717728","text":"def countdown(path, seq):\n\tfin = open(path)\n\tans = []\n\tfor line in fin:\n\t\tadd = True\n\t\tstr = seq\n\t\tfor letter in line[:-1]:\n\t\t\tif letter not in str:\n\t\t\t\tadd = False\n\t\t\telse:\n\t\t\t\tstr = str.replace(letter, \"\", 1)\n\n\n\t\tif add == True and len(line[:-1]) > 3:\n\t\t\tans.append(line[:-1])\n\n\treturn ans","sub_path":"önn3/Python/countdown.py","file_name":"countdown.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"13275017","text":"\"\"\"\nContains the main class that is used to add the functionality for the main\nline edit in the VCS window to create scenes and to add commit notes to new\ncommits and saves.\n\"\"\"\nimport os\nimport re\nimport sys\n\nfrom Qt import QtWidgets, QtGui, QtCore\nimport pymel.core as pmc\n\nfrom listWidgetClass import UpdateVCSSceneList\nfrom ..checkinCheckout import Checkin, Checkout\nfrom .. import utilities as util\nfrom OrcaMaya.filePaths import get_icon_path\nfrom OrcaMaya.utilities import mPrint\n\n\nclass LineEditWidget(QtWidgets.QLineEdit):\n \"\"\"Custom LineEditWidget class that is used to define the functionality \n of the QLineEdit in the VCS main window. Defines the functionality to\n create a new scene as well as defining the default naming conventions.\n Focus In and Out for this widget is defined here.\n \n Methods: (Overloaded)\n [__init__]\n \"\"\"\n \n def __init__(self, parent):\n \"\"\"\n **Position Argument**\n\n :param parent: Main window instance\n :type parent: `CheckoutUI`\n \"\"\"\n QtWidgets.QLineEdit.__init__(self)\n self.parent = parent\n self.setFocusPolicy(QtCore.Qt.ClickFocus)\n \n rx = QtCore.QRegExp('[a-zA-Z0-9_]{1,}')\n self.setValidator(QtGui.QRegExpValidator(rx, self.parent))\n \n def keyPressEvent(self, event):\n \"\"\"Key Press Event for main window. Toggle between Check-Out,\n Check-In, and Reference windows by pressing the left and right\n arrow buttons.\n \n **Positional Arguments**\n\n :param event: Event provided by main window event loop\n :type event: keyPressEvent\n \"\"\"\n QtWidgets.QLineEdit.keyPressEvent(self, event)\n util.key_press_event(self.parent, event)\n \n\nclass CreateSceneLineEdit(LineEditWidget):\n \"\"\"Subclass of LineEditWidget for the purpose of creating a new scene\n upon pressing enter.\n \n Methods: (Overloaded)\n [__init__, mousePressEvent]\n \n Methods:\n [_set_text, line_edit_change_base, line_edit, create_scene]\n \"\"\"\n \n def __init__(self, parent):\n \"\"\"Initialize class and take parent window.\n \n **Position Arguments**\n\n :param parent: Main window instance\n :type parent: `CheckoutUI`\n \n Instance Attributes:\n [self.win, self.vcs_info, self.user_text]\n \"\"\"\n LineEditWidget.__init__(self, parent)\n self.setPlaceholderText('Click here to create a scene:')\n self.win = parent\n self.user_text = ''\n \n def mousePressEvent(self, event):\n \"\"\"Move cursor to the end of the user text.\n \n **Positonal Arguments**\n\n :param event: Event provided by main window event loop\n :type event: mousePressEvent\n \"\"\"\n self._set_cursor_position()\n \n def keyPressEvent(self, event):\n \"\"\"Override the left and right keys in order to prevent a bug. If \n the user tries to add text in the middle of the self.user_text, \n then the set_cursor_position forces the cursor to the end of the \n user text string.\n\n **Positional Arguments**\n\n :param event: Event provided by main window event loop\n :type event: keyPressEvent\n \"\"\"\n LineEditWidget.keyPressEvent(self, event)\n if event.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Right]:\n pass\n \n def _set_cursor_position(self):\n \"\"\"Helper function to set the cursor position to the location after\n the user-defined text.\n \"\"\"\n self.setCursorPosition(len(self.user_text))\n \n def _update_text(self):\n \"\"\"When the Stage of Production combo box changes selection, update \n the base of the existing string the new base text based on production \n (ie. model, rigging, lighting)\n \"\"\"\n self.setText(self.user_text + '_' + self.get_base_text())\n \n def get_base_text(self):\n \"\"\"return the base text that trails after the user-defined text.\n\n :returns: Base text suffix\n :rtype: string\n \"\"\"\n stage = self.win.stage_combo_box.currentText().lower()\n base_text = stage\n if stage == 'rigging':\n base_text = 'rig'\n elif stage == 'modeling':\n base_text = 'model'\n\n return '{stage}_final'.format(stage = base_text)\n \n def _edit_line_when_pressing_keys(self):\n \"\"\"Append '_{stage of production}_final' to a file name being \n typed into the line. This is allow the user to create new scenes \n to be added to the project field below.\n \"\"\"\n self.user_text = self.text().split('_' + self.get_base_text())[0]\n if len(self.user_text) == 0:\n self.setText('')\n return\n self._update_text()\n self._set_cursor_position()\n \n def _validate_text(self, text):\n \"\"\"Validate the new scene name text to conform to Orca Health \n standards.\n\n **Positional Arguments**\n\n :param text: Text entered into the line edit\n :type text: string\n \"\"\"\n pattern = util.return_scene_pattern()\n try:\n pattern.match(text).group(0)\n except Exception as e:\n raise RuntimeError('{0} does not follow the pattern: \\n'\n 'sceneName_stage_final.mb\\n or\\n'\n 'tool_sceneName_stage_final.mb'.format(text))\n \n def create_scene(self):\n \"\"\"Create a new scene from the current scene being worked on. \n This will save the scene by a new name to the appropriate file \n path, update the list widget with the new name, and check the \n scene out. \n (Checking out will also save an initial version of the file and \n create the appropriate directories.\n \"\"\"\n new_name = u'{0}.mb'.format(self.text())\n # Validate line edit text\n self._validate_text(new_name)\n fullpath = self.win._type().joinpath(new_name)\n message_string = 'Would you like to create and save a new scene ' \\\n 'by the name'\n # Warning dialog to confirm saving\n message = QtWidgets.QMessageBox()\n message.setWindowTitle('Confirm Save?')\n message.setText('{0}:\\n {1}?'.format(message_string, new_name))\n message.setInformativeText('This will also check the scene out.')\n message.setStandardButtons(QtWidgets.QMessageBox.Save | \n QtWidgets.QMessageBox.Cancel)\n message.setDefaultButton(QtWidgets.QMessageBox.Cancel)\n message.setIcon(QtWidgets.QMessageBox.Question)\n message.setWindowIcon(QtGui.QIcon('{path}/{name}.png'.format(\n path = get_icon_path(), \n name = 'logo_bluewhale')))\n mPrint('{0}:\\n {1}?'.format(message_string, new_name))\n\n result = message.exec_()\n if result == QtWidgets.QMessageBox.Save:\n # Save the current scene as a new scene\n # If the scene doesn't exist save it\n # Else print a warning\n checkin = Checkin(self.win.user, self.win.checked_out_item)\n\n if fullpath.isfile():\n overwrite_btn = QtWidgets.QPushButton('Overwrite')\n warn_message_string = '{0} already exists on disk!'.format(\n new_name)\n warn_message = QtWidgets.QMessageBox()\n warn_message.setWindowTitle('Already Exists!')\n warn_message.setText(warn_message_string)\n warn_message.setStandardButtons(QtWidgets.QMessageBox.Ok)\n warn_message.addButton(overwrite_btn, QtWidgets.QMessageBox.AcceptRole)\n warn_message.setIcon(QtWidgets.QMessageBox.Information)\n warn_message.setWindowIcon(QtGui.QIcon('{path}/{name}.'\n 'png'.format(\n path = get_icon_path(), \n name = 'logo_bluewhale')))\n # Print another QMessageBox as a warning\n sys.stderr.write(warn_message_string + '\\n')\n result = warn_message.exec_()\n\n if result == QtWidgets.QMessageBox.Ok:\n return\n # Continues on to save if 'overwrite' is clicked\n\n # Checkin first\n checkin.run()\n\n pmc.renameFile(fullpath)\n pmc.saveFile(force = True, type = 'mayaBinary')\n # Update the list widget\n scene_list = UpdateVCSSceneList(self.win)\n scene_list.update()\n # Check the scene out\n for i in xrange(self.win.list_widg.count()):\n if self.win.list_widg.item(i).text() == new_name:\n # Select the new name within the list widget\n self.win.list_widg.setCurrentItem(\n self.win.list_widg.item(i)) \n # Run the checking out method\n # Check the scene out and create the necessary \n # directories, etc.\n checkout = Checkout(self.win.list_widg.currentItem(), \n self.win.user)\n Checkin(self.win.user).commit()\n\n self.win.checked_out_item = self.win.list_widg.currentItem()\n self.win.checked_out_label.setText('Checked-Out: {0}'.format(\n self.win.checked_out_item.scene))\n self.win.checked_out_label.setStyleSheet('font-size: 15pt; color: green')\n\n return_value = checkout.run()\n if return_value == 'Success':\n # Open the check-in window\n self.win.chk_in_action.trigger()\n else:\n # If cancel is pressed\n mPrint('Operation cancelled.')\n\n\nclass CommitSceneLineEdit(LineEditWidget):\n \"\"\"Subclass of LineEditWidget for the purpose of commiting changes of the\n current scene.\n \n Methods: (Overloaded)\n [__init__]\n \n Methods:\n [add_buttons, typing_notes]\n \"\"\"\n \n def __init__(self, parent):\n \"\"\"Initialize instance.\n \n **Positional Arguments**\n\n :param parent: Main window instance\n :type parent: `CheckoutUI`\n \n Instance Attributes:\n [self.win, self.buttons] \n \"\"\"\n LineEditWidget.__init__(self, parent)\n self.win = parent\n self.setPlaceholderText('Append notes to the version number:')\n self.buttons = None\n \n def add_buttons(self, buttons):\n \"\"\"Capture buttons that are then used in the add_notes method.\n\n **Positional Arguments**\n\n :param buttons: Add list of buttons to adjust enabled method when \n the QLineEdit is empty\n :type buttons: List of `QPushButton`\n \"\"\"\n self.buttons = buttons\n \n def typing_notes(self):\n \"\"\"Toggles the enabled function of the Pushbutton widgets when \n nothing is typed into the add notes line edit. Forces the \n addition of notes for each version when the scene is checked in.\n \"\"\"\n for button in self.buttons:\n if self.text():\n button.setEnabled(True)\n else:\n button.setEnabled(False)\n \n def keyPressEvent(self, event):\n \"\"\"Set key press to default.\n\n **Positional Arguments**\n\n :param event: Event provided by main window event loop\n :type event: keyPressEvent\n \"\"\"\n QtWidgets.QLineEdit.keyPressEvent(self, event)","sub_path":"OrcaMaya/plugins/orca3dTeamVCS/modules/UI/lineEditClass.py","file_name":"lineEditClass.py","file_ext":"py","file_size_in_byte":11816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"256338596","text":"class No():\n def __init__(self,valor, prox=None):\n self.valor = valor\n self.prox = prox\n\n def __str__(self):\n return \"%s - %s\"%(self.valor, self.prox)\n\n def insere_inicio(self):\n self.__primeiro = No(self.valor, self.__primeiro)\n if self.__ultimo == None:\n self.__ultimo = self.__primeiro\n\na = No(23, None)\na = No(5, a)\na = No(10, a)\na.insere_inicio()\nprint(a)","sub_path":"Estrutura de dados/10-09-2019.py","file_name":"10-09-2019.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"356004728","text":"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\"\"\"Contains the SageMaker Experiments Tracker class.\"\"\"\nimport datetime\nimport os\nimport mimetypes\nimport urllib.parse\nimport urllib.request\nimport logging\n\nimport dateutil\n\nfrom smexperiments import api_types, metrics, trial_component, _utils, _environment\n\n\nclass Tracker(object):\n \"\"\"A SageMaker Experiments Tracker.\n\n Use a tracker object to record experiment information to a SageMaker trial component.\n\n A new tracker can be created in two ways:\n\n - By loading an existing trial component with :meth:`~smexperiments.tracker.Tracker.load`\n - By creating a tracker for a new trial component with :meth:`~smexperiments.tracker.Tracker.create`.\n\n When creating a tracker within a SageMaker training or processing job, use the ``load`` method with\n no arguments to track artifacts to the trial component automatically created for your job. When tracking\n within a Jupyternotebook running in SageMaker, use the ``create`` method to automatically create a new\n trial component.\n\n Trackers are Python context managers and you can use them using the Python ``with`` keyword. Exceptions\n thrown within the with block will cause the tracker's trial component to be marked as failed. Start and\n end times are automatically set when using the with statement and the trial component is saved to\n SageMaker at the end of the block.\n\n Note that only parameters, input artifacts, and output artifacts are saved to SageMaker. Metrics are saved to file.\n\n Attributes:\n trial_component (TrialComponent): The trial component tracked.\n \"\"\"\n\n trial_component = None\n _metrics_writer = None\n _in_sagemaker_job = False\n _artifact_uploader = None\n\n def __init__(self, trial_component, metrics_writer, artifact_uploader):\n self.trial_component = trial_component\n self.trial_component.parameters = self.trial_component.parameters or {}\n self.trial_component.input_artifacts = self.trial_component.input_artifacts or {}\n self.trial_component.output_artifacts = self.trial_component.output_artifacts or {}\n self._artifact_uploader = artifact_uploader\n self._metrics_writer = metrics_writer\n self._warned_on_metrics = False\n\n @classmethod\n def load(\n cls,\n trial_component_name=None,\n artifact_bucket=None,\n artifact_prefix=None,\n boto3_session=None,\n sagemaker_boto_client=None,\n ):\n \"\"\"Create a new ``Tracker`` by loading an existing trial component.\n\n Examples:\n .. code-block:: python\n\n from smexperiments import tracker\n\n my_tracker = tracker.Tracker.load(trial_component_name='xgboost')\n\n Args:\n trial_component_name: (str, optional). The name of the trial component to track. If specified, this\n trial component must exist in SageMaker. If you invoke this method in a running SageMaker training\n or processing job, then trial_component_name can be left empty. In this case, the Tracker will\n resolve the trial component automatically created for your SageMaker Job.\n artifact_bucket: (str, optional) The name of the S3 bucket to store artifacts to.\n artifact_prefix: (str, optional) The prefix to write artifacts to within ``artifact_bucket``\n boto3_session: (boto3.Session, optional) The boto3.Session to use to interact with AWS services.\n If not specified a new default boto3 session will be created.\n sagemaker_boto_client: (boto3.Client, optional) The SageMaker AWS service client to use. If not\n specified a new client will be created from the specified ``boto3_session`` or default\n boto3.Session.\n\n Returns:\n Tracker: The tracker for the given trial component.\n\n Raises:\n ValueError: If the trial component failed to load.\n \"\"\"\n boto3_session = boto3_session or _utils.boto_session()\n sagemaker_boto_client = sagemaker_boto_client or _utils.sagemaker_client()\n\n tce = _environment.TrialComponentEnvironment.load()\n\n # Resolve the trial component for this tracker to track: If a trial component name was passed in, then load\n # and track that trial component. Otherwise, try to find a trial component given the current environment,\n # failing if we're unable to load one.\n if trial_component_name:\n tc = trial_component.TrialComponent.load(\n trial_component_name=trial_component_name, sagemaker_boto_client=sagemaker_boto_client\n )\n elif tce:\n tc = tce.get_trial_component(sagemaker_boto_client)\n else:\n raise ValueError('Could not load TrialComponent. Specify a trial_component_name or invoke \"create\"')\n\n # if running in a SageMaker context write metrics to file\n if not trial_component_name and tce.environment_type == _environment.EnvironmentType.SageMakerTrainingJob:\n metrics_writer = metrics.SageMakerFileMetricsWriter()\n else:\n metrics_writer = None\n\n tracker = cls(\n tc,\n metrics_writer,\n _ArtifactUploader(tc.trial_component_name, artifact_bucket, artifact_prefix, boto3_session),\n )\n tracker._in_sagemaker_job = True if tce else False\n return tracker\n\n @classmethod\n def create(\n cls,\n display_name=None,\n artifact_bucket=None,\n artifact_prefix=None,\n boto3_session=None,\n sagemaker_boto_client=None,\n ):\n \"\"\"Create a new ``Tracker`` by creating a new trial component.\n\n Examples\n .. code-block:: python\n\n from smexperiments import tracker\n\n my_tracker = tracker.Tracker.create()\n\n Args:\n display_name: (str, optional). The display name of the trial component to track.\n artifact_bucket: (str, optional) The name of the S3 bucket to store artifacts to.\n artifact_prefix: (str, optional) The prefix to write artifacts to within ``artifact_bucket``\n boto3_session: (boto3.Session, optional) The boto3.Session to use to interact with AWS services.\n If not specified a new default boto3 session will be created.\n sagemaker_boto_client: (boto3.Client, optional) The SageMaker AWS service client to use. If not\n specified a new client will be created from the specified ``boto3_session`` or default\n boto3.Session.\n\n Returns:\n Tracker: The tracker for the new trial component.\n \"\"\"\n boto3_session = boto3_session or _utils.boto_session()\n sagemaker_boto_client = sagemaker_boto_client or _utils.sagemaker_client()\n\n tc = trial_component.TrialComponent.create(\n trial_component_name=_utils.name(\"TrialComponent\"),\n display_name=display_name,\n sagemaker_boto_client=sagemaker_boto_client,\n )\n\n metrics_writer = metrics.SageMakerFileMetricsWriter()\n\n return cls(\n tc,\n metrics_writer,\n _ArtifactUploader(tc.trial_component_name, artifact_bucket, artifact_prefix, boto3_session),\n )\n\n def log_parameter(self, name, value):\n \"\"\"Record a single parameter value for this trial component.\n\n Overwrites any previous value recorded for the specified parameter name.\n\n Examples\n .. code-block:: python\n\n # log hyper parameter of learning rate\n my_tracker.log_parameter('learning_rate', 0.01)\n\n Args:\n name (str): The name of the parameter\n value (str or numbers.Number): The value of the parameter\n \"\"\"\n self.trial_component.parameters[name] = value\n\n def log_parameters(self, parameters):\n \"\"\"Record a collection of parameter values for this trial component.\n\n Examples\n .. code-block:: python\n\n # log multiple hyper parameters used in training\n my_tracker.log_parameters({\"learning_rate\": 1.0, \"gamma\": 0.9, \"dropout\": 0.5})\n\n Args:\n parameters (dict[str, str or numbers.Number]): The parameters to record.\n \"\"\"\n self.trial_component.parameters.update(parameters)\n\n def log_input(self, name, value, media_type=None):\n \"\"\"Record a single input artifact for this trial component.\n\n Overwrites any previous value recorded for the specified input name.\n\n Examples\n .. code-block:: python\n\n # log input dataset s3 location\n my_tracker.log_input(name='input', value='s3://inputs/path')\n\n Args:\n name (str): The name of the input value.\n value (str): The value.\n media_type (str, optional): The MediaType (MIME type) of the value\n \"\"\"\n self.trial_component.input_artifacts[name] = api_types.TrialComponentArtifact(value, media_type=media_type)\n\n def log_output(self, name, value, media_type=None):\n \"\"\"Record a single output artifact for this trial component.\n\n Overwrites any previous value recorded for the specified output name.\n\n Examples\n .. code-block:: python\n\n # log input dataset s3 location\n my_tracker.log_output(name='prediction', value='s3://outputs/path')\n\n Args:\n name (str): The name of the output value.\n value (str): The value.\n media_type (str, optional): The MediaType (MIME type) of the value.\n \"\"\"\n self.trial_component.output_artifacts[name] = api_types.TrialComponentArtifact(value, media_type=media_type)\n\n def log_artifact(self, file_path, name=None, media_type=None):\n \"\"\"Upload a local file to s3 and store it as an artifact in this trial component.\n\n Examples\n .. code-block:: python\n\n # log local artifact\n my_tracker.log_artifact(file_path='/local/path/artifact.tar.gz')\n\n Args:\n file_path (str): The path of the local file to upload.\n name (str, optional): The name of the artifact.\n media_type (str, optional): The MediaType (MIME type) of the file. If not specified, this library\n will attempt to infer the media type from the file extension of ``file_path``.\n \"\"\"\n media_type = media_type or _guess_media_type(file_path)\n name = name or _resolve_artifact_name(file_path)\n s3_uri = self._artifact_uploader.upload_artifact(file_path)\n self.trial_component.output_artifacts[name] = api_types.TrialComponentArtifact(\n value=s3_uri, media_type=media_type\n )\n\n def log_metric(self, metric_name, value, timestamp=None, iteration_number=None):\n \"\"\"Record a scalar metric value for this TrialComponent to file, not SageMaker.\n\n Examples\n .. code-block:: python\n\n for epoch in range(epochs):\n # your training logic and calculate accuracy and loss\n my_tracker.log_metric(metric_name='accuracy', value=0.9, iteration_number=epoch)\n my_tracker.log_metric(metric_name='loss', value=0.03, iteration_number=epoch)\n\n Args:\n metric_name (str): The name of the metric.\n value (number): The value of the metric.\n timestamp (datetime.datetime|number, optional): The timestamp of the metric. If specified, should\n either be a datetime.datetime object or a number representing the seconds since\n the epoch. If not specified, the current local time will be used.\n iteration_number (number, optional): The integer iteration number of the metric value.\n \"\"\"\n try:\n self._metrics_writer.log_metric(metric_name, value, timestamp, iteration_number)\n except AttributeError:\n if not self._metrics_writer:\n if not self._warned_on_metrics:\n logging.warning(\"Cannot write metrics in this environment.\")\n self._warned_on_metrics = True\n else:\n raise\n\n def __enter__(self):\n self._start_time = datetime.datetime.now(dateutil.tz.tzlocal())\n if not self._in_sagemaker_job:\n self.trial_component.start_time = self._start_time\n self.trial_component.status = api_types.TrialComponentStatus(primary_status=\"InProgress\")\n return self\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n self._end_time = datetime.datetime.now(dateutil.tz.tzlocal())\n if not self._in_sagemaker_job:\n self.trial_component.end_time = self._end_time\n if exc_value:\n self.trial_component.status = api_types.TrialComponentStatus(\n primary_status=\"Failed\", message=str(exc_value)\n )\n else:\n self.trial_component.status = api_types.TrialComponentStatus(primary_status=\"Completed\")\n self.close()\n\n def close(self):\n \"\"\"Close this tracker and save state to SageMaker.\"\"\"\n try:\n self.trial_component.save()\n finally:\n if self._metrics_writer:\n self._metrics_writer.close()\n\n\ndef _resolve_artifact_name(file_path):\n _, filename = os.path.split(file_path)\n if filename:\n return filename\n else:\n return _utils.name(\"artifact\")\n\n\nclass _ArtifactUploader(object):\n def __init__(self, trial_component_name, artifact_bucket, artifact_prefix, boto_session):\n self.s3_client = boto_session.client(\"s3\")\n self.boto_session = boto_session\n self.trial_component_name = trial_component_name\n self.artifact_bucket = artifact_bucket\n self.artifact_prefix = artifact_prefix or \"trial-component-artifacts\"\n\n def upload_artifact(self, file_path):\n \"\"\"Upload an artifact file to S3 and record the artifact S3 key with this trial run.\"\"\"\n file_path = os.path.expanduser(file_path)\n if not os.path.isfile(file_path):\n raise ValueError(\"{} does not exist or is not a file. Please supply a file path.\".format(file_path))\n if not self.artifact_bucket:\n self.artifact_bucket = _utils.get_or_create_default_bucket(self.boto_session)\n artifact_name = os.path.basename(file_path)\n artifact_s3_key = \"{}/{}/{}\".format(self.artifact_prefix, self.trial_component_name, artifact_name)\n self.s3_client.upload_file(file_path, self.artifact_bucket, artifact_s3_key)\n return \"s3://{}/{}\".format(self.artifact_bucket, artifact_s3_key)\n\n\ndef _guess_media_type(file_path):\n file_url = urllib.parse.urljoin(\"file:\", urllib.request.pathname2url(file_path))\n guessed_media_type, _ = mimetypes.guess_type(file_url, strict=False)\n return guessed_media_type\n","sub_path":"src/smexperiments/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":15510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"300645065","text":"\"\"\"Game management code.\"\"\"\nimport sys\n\n\nclass GameException(Exception):\n \"\"\"Game events exception.\"\"\"\n\n\nclass Game(object):\n \"\"\"Game management object used to make moves and manage board.\"\"\"\n\n CHOICES = {\n 'w': 'ccwise',\n 's': 'cwise',\n 'a': 'left',\n 'd': 'right',\n }\n\n def __init__(self, board, piece_maker):\n \"\"\"Set board and piece maker to be used in the game.\n\n :param board: game board class\n :type board: Board\n :param piece_maker: Factory producing piece objects\n :type piece_maker: piece_maker\n \"\"\"\n self._board = board\n self._piece_maker = piece_maker\n self._piece = None\n\n @property\n def board(self):\n \"\"\"Return ready to print board content.\n\n :returns: Board as ascii art string\n :rtype: str\n \"\"\"\n return self._board.stringify(self._piece)\n\n def add_piece(self):\n \"\"\"Add new piece in a random position in first row of game board.\"\"\"\n self._piece = self._piece_maker.get_random()\n self._piece.position = self._board.get_random_position(self._piece), 0\n\n def move(self, choice):\n \"\"\"Make move picked by user.\n\n :param choice: key pressed by user\n :type choice: str\n :returns: output to be printed after move\n :rtype: str\n \"\"\"\n if choice not in Game.CHOICES:\n raise GameException(\"Error: Wrong choice!\")\n new_piece = self._piece_maker.transform(\n self._piece,\n Game.CHOICES[choice],\n )\n return self._get_new_frame(new_piece)\n\n def _get_new_frame(self, new_piece):\n \"\"\"Render new game frame based on the new_piece.\n\n :param new_piece: New piece position\n :type new_piece: piece\n :returns: Rendered board\n :rtype: str\n \"\"\"\n board_str = self._board.stringify(new_piece)\n if board_str is None:\n del new_piece\n raise GameException(\"Error: New position is invalid!\")\n else:\n self._piece = new_piece\n if self._board.is_locked(new_piece):\n self._board.melt(new_piece)\n self.add_piece()\n board_str = self._board.stringify(self._piece)\n if board_str is None:\n sys.exit()\n return board_str\n","sub_path":"slowtris/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"100681192","text":"import csv\r\nimport plotly.express as px\r\nimport numpy as np\r\n\r\ndef getDataSource(data_path):\r\n sizeOfTv=[] \r\n averageTimeSpent=[]\r\n with open(data_path)as csv_files:\r\n csv_reader=csv.DictReader(csv_files)\r\n for row in csv_reader:\r\n sizeOfTv.append(float(row[\"Size of Tv\"]))\r\n averageTimeSpent.append(float(row[\"\\tAverage time spent watching TV in a week (hours)\"]))\r\n\r\n return{\"x\":sizeOfTv,\"y\":averageTimeSpent}\r\n\r\ndef findCorrelation(dataSource):\r\n correlation=np.corrcoef(dataSource[\"x\"],dataSource[\"y\"])\r\n print(\"correlation between size of TV and average time spent watching TV in a week- \\n--->\",correlation[0,1])\r\n\r\ndef setup():\r\n data_path=\"/Size of TV,_Average time spent watching TV in a week (hours).csv\"\r\n dataSource=getDataSource(data_path)\r\n findCorrelation(dataSource)\r\n\r\nsetup()\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"188118301","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom poly_dataset import get_input\nfrom poly_model import get_model, get_train_op, get_loss_op\nfrom time import time\nimport argparse\nimport os\n\n_base_dir = os.path.join(\".\", \"outputs\")\nPARSER = argparse.ArgumentParser()\nPARSER.add_argument(\"--base_dir\", type=str, default=_base_dir, help=\"Where to output stuff\")\nPARSER.add_argument(\"--model_dir\", type=str, default=os.path.join(_base_dir, \"model\"), help=\"Where to save models\")\nPARSER.add_argument(\"--plots_dir\", type=str, default=os.path.join(_base_dir, \"plots\"), help=\"Where to save plots\")\nPARSER.add_argument(\"--log_frequency\", type=int, default=25, help=\"How often to print to the console\")\nPARSER.add_argument(\"--num_epochs\", type=int, default=15000, help=\"How many epochs to train the model\")\nPARSER.add_argument(\"--batch_size\", type=int, default=1, required=False, help=\"Size of each batch\")\nPARSER.add_argument(\"--log_device_placement\", type=bool, default=False, help=\"Whether or not to print Tensorflow's \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"device placement\")\nARGS = PARSER.parse_args()\n# tf.logging.set_verbosity('0' if ARGS.log_device_placement else '3')\n# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0' if ARGS.log_device_placement else '3' # To suppress Tensorflow's messages\n\n\ndef export_polynomial_plot(model_number, Xs, Ys, Predictions):\n\tX_MIN, X_MAX = Xs.min() - 1, Xs.max() + 1\n\tY_MIN, Y_MAX = np.minimum(Ys.min(), Predictions.min()) - 1, np.maximum(Ys.max(), Predictions.max()) + 1\n\tplt.xlim([X_MIN, X_MAX])\n\tplt.ylim([Y_MIN, Y_MAX])\n\tplt.scatter(Xs, Ys, s=5, color=\"blue\", marker=\".\")\n\tplt.plot(Xs, Predictions, c=\"red\", ls=\"solid\", lw=1.0)\n\tplt.legend([\"p(x)\", \"Validation data\"])\n\tplt.axhline(0, color='black')\n\tplt.axvline(0, color='black')\n\tplt.title(\"Degree %d\" % model_number)\n\tplt.xlabel('x')\n\tplt.ylabel('y')\n\tOUTPUT_SAVE_PATH = os.path.join(ARGS.plots_dir, \"deg_%s_fit_plot.svg\" % model_number)\n\tplt.savefig(OUTPUT_SAVE_PATH)\n\tplt.close()\n\n\ndef train_model(degree):\n\tif degree <= 0:\n\t\traise ValueError(\"Invalid argument. degree <= 0\")\n\ttf.reset_default_graph()\n\tCURRENT_MODEL_SAVE_PATH = os.path.join(ARGS.model_dir, str(degree))\n\n\tbIsTraining = tf.placeholder(tf.bool)\n\n\tX_train, Y_train = get_input(\"train\", ARGS.batch_size, None)\n\tX_validation, Y_validation = get_input(\"validation\", ARGS.batch_size, None)\n\tX = tf.cond(bIsTraining, true_fn=lambda: X_train, false_fn=lambda: X_validation)\n\tY = tf.cond(bIsTraining, true_fn=lambda: Y_train, false_fn=lambda: Y_validation)\n\n\tglobal_step = tf.train.get_or_create_global_step()\n\tpredictions = get_model(X, degree)\n\tloss_op = get_loss_op(Y, predictions)\n\ttrain_op = get_train_op(loss_op, global_step)\n\t# total_correct_preds, accuracy_op = tf.metrics.accuracy(Y, predictions) Loss ~= Accuracy here\n\tscaffold = tf.train.Scaffold(init_op=tf.global_variables_initializer(), local_init_op=tf.local_variables_initializer())\n\n\tclass _LoggerHook(tf.train.SessionRunHook):\n\t\t\"\"\"Logs loss and runtime.\"\"\"\n\n\t\tdef __init__(self, *args, **kwargs):\n\t\t\tsuper(*args, **kwargs)\n\t\t\tself._start_time = time()\n\t\t\tself._train_losses = np.array([], dtype=np.float64)\n\n\t\tdef begin(self):\n\t\t\tprint(\"%8s | %10s | %11s | %16s | %16s\" % (\n\t\t\t\"Duration\", \"Epoch\", 'Samples', 'Train Loss', 'Validation Loss'))\n\n\t\tdef before_run(self, run_context):\n\t\t\t# return tf.train.SessionRunArgs([loss_op, accuracy_op])\n\t\t\treturn tf.train.SessionRunArgs(loss_op)\n\n\t\tdef after_run(self, run_context, run_values):\n\t\t\t# loss_value, accuracy_value = run_values.results\n\t\t\tloss_value = run_values.results\n\t\t\tself._train_losses = np.append(self._train_losses, loss_value)\n\t\t\tsess = run_context.session\n\t\t\tstep = global_step.eval(session=sess)\n\t\t\tif step % ARGS.log_frequency == 0:\n\t\t\t\tcurrent_time = time()\n\t\t\t\tduration = current_time - self._start_time\n\t\t\t\tself._start_time = current_time\n\t\t\t\tavg_train_loss = np.mean(self._train_losses, dtype=np.float64)\n\t\t\t\tavg_validation_loss = loss_op.eval(session=sess, feed_dict={bIsTraining: False})\n\t\t\t\tprint(\"%3.2f sec | %10d | %11d | %10.6f | %10.6f\" % (duration, step, step * ARGS.batch_size,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tavg_train_loss, avg_validation_loss))\n\t\t\t\tself._train_losses = np.array([])\n\n\n\twith tf.train.MonitoredTrainingSession(checkpoint_dir=CURRENT_MODEL_SAVE_PATH, scaffold=scaffold,\n\t\t\t\t\t\t\t\t\t\t hooks=[tf.train.StopAtStepHook(last_step=ARGS.num_epochs),\n\t\t\t\t\t\t\t\t\t\t\t\t tf.train.NanTensorHook(loss_op),\n\t\t\t\t\t\t\t\t\t\t\t\t _LoggerHook()]) as mon_sess:\n\t\twhile not mon_sess.should_stop():\n\t\t\tmon_sess.run(train_op, feed_dict={bIsTraining: True})\n\n\ndef test_model(degree):\n\ttf.reset_default_graph()\n\tCURRENT_MODEL_SAVE_PATH = os.path.join(ARGS.model_dir, str(degree))\n\tX_data, Y_data = get_input(\"test\", batch_size=1, num_epochs=1)\n\tpredict_op = get_model(X_data, degree)\n\n\tXs_coordinates, Ys_coordinates = np.array([]), np.array([])\n\tPreds_coordinates = np.array([])\n\n\tsaver = tf.train.Saver()\n\twith tf.Session() as sess:\n\t\tsaver.restore(sess, tf.train.latest_checkpoint(CURRENT_MODEL_SAVE_PATH))\n\t\tprint(\"Predicting for model %d\" % degree)\n\t\ttry:\n\t\t\twhile True:\n\t\t\t\tx, y = sess.run([X_data, Y_data])\n\t\t\t\tpreds = sess.run(predict_op, feed_dict={X_data: x, Y_data: y})\n\t\t\t\tXs_coordinates = np.concatenate((Xs_coordinates, x))\n\t\t\t\tYs_coordinates = np.concatenate((Ys_coordinates, y.flatten()))\n\t\t\t\tPreds_coordinates = np.concatenate((Preds_coordinates, preds.flatten()))\n\t\texcept tf.errors.OutOfRangeError: # Obtaining data until there is none left.\n\t\t\tpass\n\tprint(\"Preparing data for plotting.\")\n\tindices = np.argsort(Xs_coordinates)\n\tXs_coordinates = Xs_coordinates[indices]\n\tYs_coordinates = Ys_coordinates[indices]\n\tPreds_coordinates = Preds_coordinates[indices]\n\tprint(\"Exporting plot for model %d\" % degree)\n\texport_polynomial_plot(degree, Xs_coordinates, Ys_coordinates, Preds_coordinates)\n\n\ndef _validate_folders():\n\tif not os.path.exists(ARGS.base_dir):\n\t\tos.mkdir(ARGS.base_dir)\n\tif not os.path.exists(ARGS.model_dir):\n\t\tos.mkdir(ARGS.model_dir)\n\tif not os.path.exists(ARGS.plots_dir):\n\t\tos.mkdir(ARGS.plots_dir)\n\n\ndef main():\n\t_validate_folders()\n\tmodel_degrees = range(1, 10)\n\tfor d in model_degrees:\n\t\ttrain_model(degree=d)\n\t\ttest_model(degree=d)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"polynomial_regression/poly.py","file_name":"poly.py","file_ext":"py","file_size_in_byte":6182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"425039294","text":"import os, time\n\nimport random, requests\n\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import *\nfrom selenium.webdriver.support import expected_conditions as EC\n\nUSER_AGENTS = [\n \"Mozilla/5.0 (Linux; ; ) AppleWebKit/ (KHTML, like Gecko) Chrome/ Mobile Safari/\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0\",\n ]\n\nemail='hello@surekoala.com.au'; password='7xAuQpnhTkdh'\n\nPOST_LOGIN_URL = 'https://www.dropshipzone.com.au/customer/account/loginPost/referer/aHR0cHM6Ly93d3cuZHJvcHNoaXB6b25lLmNvbS5hdS8_X19fU0lEPVU,/'\nREQUEST_URL = 'https://www.dropshipzone.com.au/rsdropship/download/downloadSkuList/'\nua = random.choice(USER_AGENTS)\npayload = {\n\t'login[username]': email,\n\t'login[password]': password,\n}\n\n# cookies=dict(cookies_are='working')\nprint(\"[DropShipZone Bot] Attempting to login to Account\")\nsession = requests.Session()\nsession.get('https://www.google.com', headers={'User-agent': ua})\n# try:\npost = session.post(POST_LOGIN_URL, headers={'User-agent': ua}, cookies=dict(session.cookies), data=payload, timeout=(30, 60))\npost = session.post('https://www.dropshipzone.com.au/rsds/download/skus/', headers={'User-agent': ua}, cookies=session.cookies, data=payload, timeout=(30, 60))\n\nif post.ok:\n\tprint(\"[DropShipZone Bot] Login Successful\")\n\tprint(\"[DropShipZone Bot] File Download Initiated\")\n\tr = session.get(REQUEST_URL, headers={'User-agent': ua}, stream=True, cookies=dict(session.cookies), timeout=(30, 60))\n\t# r = session.get(REQUEST_URL, headers={'User-agent': random.choice(USER_AGENTS)}, cookies=dict(session.cookies), timeout=(30, 120))\n\tfilename = r.headers['Content-Disposition'].split('=')[-1].strip()\n\twith open(filename, 'wb') as file:\n\t\tprint(f\"[DropShipZone Bot] Downloading {filename} .. This file is quite large and might take a little while to finish downloading.\")\n\t\tfor chunk in r.iter_content(10000):\n\t\t\tif chunk:\n\t\t\t\tfile.write(chunk)\n\tprint(f\"[DropShipZone Bot] Done Downloading {filename} ...\")\nelse:\n\tprint(\"[DropShipZone Bot] Login Failure\")\n\n\n\n\n\n# # STORE CREDENTIALS\n# USERNAME = 'gilsanarisse'\n# PASSWORD = 'koaunqFKhG2E3qkoala'\n\n# IGNORED_EXCEPTIONS = (NoSuchElementException, StaleElementReferenceException, ElementNotVisibleException, TimeoutException)\n\n# def make_driver_settings(driver_path=r\"..\\CDN\\chromedriver.exe\"):\n# \topts = webdriver.ChromeOptions()\n# \t# chrome_prefs = {}\n# \t# opts.experimental_options[\"prefs\"] = chrome_prefs\n# \t# chrome_prefs[\"profile.default_content_settings\"] = {\"images\" : 2}\n# \t# chrome_prefs[\"profile.managed_default_content_settings\"] = {\"images\" : 2}\n# \t# opts.add_argument('--headless')\n# \tdriver = webdriver.Chrome(driver_path, options = opts)\n# \tdriver.implicitly_wait(30)\n# \treturn driver\n\n# def logout(driver):\n# \t# logout procedure\n# \tbutton = driver.find_element_by_id('netoToolbar').find_element_by_css_selector('a[class=sign-out-link]')\n# \tdriver.get(button.get_attribute('href'))\n# \ttime.sleep(2)\n# \tdriver.close()\n\n# def initial_steps(driver, USERNAME=USERNAME, PASSWORD=PASSWORD):\n# \t# login prodedures\n# \tdriver.get(\"https://www.surekoala.com.au/_cpanel\")\n# \tdriver.find_element_by_id('username').send_keys(USERNAME)\n# \tdriver.find_element_by_id('password').send_keys(PASSWORD)\n# \tdriver.find_element_by_css_selector('button[type=\"submit\"]').click()\n# \t# if driver.current_url != \"https://www.surekoala.com.au/_cpanel\":\n# \tdriver.get('https://www.surekoala.com.au/_cpanel/dsimport?limitmod=DS_inventory&limittmp=n')\n\n# def wait_until(secs=300):\n# \tfor i in range(secs):\n# \t\tstat = driver.execute_script('return document.readyState;')\n# \t\tif stat == 'complete':\n# \t\t\treturn\n\n\n\n# # def main_actions(driver):\n# driver = make_driver_settings()\n# initial_steps(driver)\n# tags = driver.find_elements_by_tag_name('tbody tr')\n# tags[4].find_element_by_id('chkbox2').click()\n# #####\n# # upload neto csv\n# tags[5].find_element_by_css_selector('[type=\"file\"]').send_keys(os.path.abspath('neto.csv'))\n# time.sleep(1)\n# driver.execute_script('javascript:doAction(\"run\");')\n# driver.switch_to.alert.accept()\n\n# # wait for some seconds till you see the link\n# link = WebDriverWait(driver, 180, ignored_exceptions=IGNORED_EXCEPTIONS).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div[class=\"netoPage--content--page currentTkn--dsimport\"] a')))\n# next_link = link.get_attribute('href')\n\n# # next_link = driver.find_element_by_css_selector('div[class=\"netoPage--content--page currentTkn--dsimport\"] a').get_attribute('href')\n# driver.get(next_link)\n# driver.find_element_by_css_selector('input[type=\"checkbox\"]').click()\n# driver.execute_script(\"javascript:doActionSingle('run','0');\")\n\n# @classmethod\n# def nucleus(cls):\n# cls.main_actions(driver)\n# cls.logout(driver)\n\n\n\n\n\n\n\n\n\n\n\n\n\n# import pickle\n# import os.path\n# from googleapiclient import errors\n# from googleapiclient.discovery import build\n# from google_auth_oauthlib.flow import InstalledAppFlow\n# from google.auth.transport.requests import Request\n\n# class FilterSheet:\n# \t@classmethod\n# \tdef get_scripts_service(cls):\n# \t\tSCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets']\n# \t\tcreds = None\n# \t\tif os.path.exists('token.pickle'):\n# \t\t\twith open('token.pickle', 'rb') as token:\n# \t\t\t\tcreds = pickle.load(token)\n# \t\tif not creds or not creds.valid:\n# \t\t\tif creds and creds.expired and creds.refresh_token:\n# \t\t\t\tcreds.refresh(Request())\n# \t\t\telse:\n# \t\t\t\tflow = InstalledAppFlow.from_client_secrets_file(\n# \t\t\t\t\t'client_secrets.json', SCOPES) \n# \t\t\t\tcreds = flow.run_local_server(port=0)\n# \t\t\twith open('token.pickle', 'wb') as token:\n# \t\t\t\tpickle.dump(creds, token)\n\n# \t\treturn build('script', 'v1', credentials=creds)\n\n# \t@classmethod\n# \tdef action(cls):\n# \t\tservice = cls.get_scripts_service()\n# \t\tAPI_ID = \"MgWJvW4FegI-NDpFLP44x-vLSJHYMIpDM\" \n# \t\trequest = {\"function\": \"filterSheet\"} \n# \t\ttry:\n# \t\t\tresponse = service.scripts().run(body=request, scriptId=API_ID).execute()\n# \t\t\tprint(response)\n# \t\texcept errors.HttpError as error:\n# \t\t\t# The API encountered a problem.\n# \t\t\tprint(error.content)","sub_path":"gdrive.py","file_name":"gdrive.py","file_ext":"py","file_size_in_byte":6628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"648078956","text":"# coding=utf-8\n# Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"TIMIT automatic speech recognition dataset.\"\"\"\n\n\nimport os\nfrom pathlib import Path\n\nimport datasets\nfrom datasets.tasks import AutomaticSpeechRecognition\n\n\n_CITATION = \"\"\"\\\n@inproceedings{\n title={TIMIT Acoustic-Phonetic Continuous Speech Corpus},\n author={Garofolo, John S., et al},\n ldc_catalog_no={LDC93S1},\n DOI={https://doi.org/10.35111/17gk-bn40},\n journal={Linguistic Data Consortium, Philadelphia},\n year={1983}\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\\\nThe TIMIT corpus of reading speech has been developed to provide speech data for acoustic-phonetic research studies\nand for the evaluation of automatic speech recognition systems.\n\nTIMIT contains high quality recordings of 630 individuals/speakers with 8 different American English dialects,\nwith each individual reading upto 10 phonetically rich sentences.\n\nMore info on TIMIT dataset can be understood from the \"README\" which can be found here:\nhttps://catalog.ldc.upenn.edu/docs/LDC93S1/readme.txt\n\"\"\"\n\n_HOMEPAGE = \"https://catalog.ldc.upenn.edu/LDC93S1\"\n\n\nclass TimitASRConfig(datasets.BuilderConfig):\n \"\"\"BuilderConfig for TimitASR.\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Args:\n data_dir: `string`, the path to the folder containing the files in the\n downloaded .tar\n citation: `string`, citation for the data set\n url: `string`, url for information about the data set\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n super(TimitASRConfig, self).__init__(version=datasets.Version(\"2.0.1\", \"\"), **kwargs)\n\n\nclass TimitASR(datasets.GeneratorBasedBuilder):\n \"\"\"TimitASR dataset.\"\"\"\n\n BUILDER_CONFIGS = [TimitASRConfig(name=\"clean\", description=\"'Clean' speech.\")]\n\n @property\n def manual_download_instructions(self):\n return (\n \"To use TIMIT you have to download it manually. \"\n \"Please create an account and download the dataset from https://catalog.ldc.upenn.edu/LDC93S1 \\n\"\n \"Then extract all files in one folder and load the dataset with: \"\n \"`datasets.load_dataset('timit_asr', data_dir='path/to/folder/folder_name')`\"\n )\n\n def _info(self):\n return datasets.DatasetInfo(\n description=_DESCRIPTION,\n features=datasets.Features(\n {\n \"file\": datasets.Value(\"string\"),\n \"audio\": datasets.Audio(sampling_rate=16_000),\n \"text\": datasets.Value(\"string\"),\n \"phonetic_detail\": datasets.Sequence(\n {\n \"start\": datasets.Value(\"int64\"),\n \"stop\": datasets.Value(\"int64\"),\n \"utterance\": datasets.Value(\"string\"),\n }\n ),\n \"word_detail\": datasets.Sequence(\n {\n \"start\": datasets.Value(\"int64\"),\n \"stop\": datasets.Value(\"int64\"),\n \"utterance\": datasets.Value(\"string\"),\n }\n ),\n \"dialect_region\": datasets.Value(\"string\"),\n \"sentence_type\": datasets.Value(\"string\"),\n \"speaker_id\": datasets.Value(\"string\"),\n \"id\": datasets.Value(\"string\"),\n }\n ),\n supervised_keys=(\"file\", \"text\"),\n homepage=_HOMEPAGE,\n citation=_CITATION,\n task_templates=[AutomaticSpeechRecognition(audio_column=\"audio\", transcription_column=\"text\")],\n )\n\n def _split_generators(self, dl_manager):\n\n data_dir = os.path.abspath(os.path.expanduser(dl_manager.manual_dir))\n\n if not os.path.exists(data_dir):\n raise FileNotFoundError(\n f\"{data_dir} does not exist. Make sure you insert a manual dir via `datasets.load_dataset('timit_asr', data_dir=...)` that includes files unzipped from the TIMIT zip. Manual download instructions: {self.manual_download_instructions}\"\n )\n\n return [\n datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={\"split\": \"train\", \"data_dir\": data_dir}),\n datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={\"split\": \"test\", \"data_dir\": data_dir}),\n ]\n\n def _generate_examples(self, split, data_dir):\n \"\"\"Generate examples from TIMIT archive_path based on the test/train csv information.\"\"\"\n # Iterating the contents of the data to extract the relevant information\n wav_paths = sorted(Path(data_dir).glob(f\"**/{split}/**/*.wav\"))\n wav_paths = wav_paths if wav_paths else sorted(Path(data_dir).glob(f\"**/{split.upper()}/**/*.WAV\"))\n for key, wav_path in enumerate(wav_paths):\n\n # extract transcript\n txt_path = with_case_insensitive_suffix(wav_path, \".txt\")\n with txt_path.open(encoding=\"utf-8\") as op:\n transcript = \" \".join(op.readlines()[0].split()[2:]) # first two items are sample number\n\n # extract phonemes\n phn_path = with_case_insensitive_suffix(wav_path, \".phn\")\n with phn_path.open(encoding=\"utf-8\") as op:\n phonemes = [\n {\n \"start\": i.split(\" \")[0],\n \"stop\": i.split(\" \")[1],\n \"utterance\": \" \".join(i.split(\" \")[2:]).strip(),\n }\n for i in op.readlines()\n ]\n\n # extract words\n wrd_path = with_case_insensitive_suffix(wav_path, \".wrd\")\n with wrd_path.open(encoding=\"utf-8\") as op:\n words = [\n {\n \"start\": i.split(\" \")[0],\n \"stop\": i.split(\" \")[1],\n \"utterance\": \" \".join(i.split(\" \")[2:]).strip(),\n }\n for i in op.readlines()\n ]\n\n dialect_region = wav_path.parents[1].name\n sentence_type = wav_path.name[0:2]\n speaker_id = wav_path.parents[0].name[1:]\n id_ = wav_path.stem\n\n example = {\n \"file\": str(wav_path),\n \"audio\": str(wav_path),\n \"text\": transcript,\n \"phonetic_detail\": phonemes,\n \"word_detail\": words,\n \"dialect_region\": dialect_region,\n \"sentence_type\": sentence_type,\n \"speaker_id\": speaker_id,\n \"id\": id_,\n }\n\n yield key, example\n\n\ndef with_case_insensitive_suffix(path: Path, suffix: str):\n path = path.with_suffix(suffix.lower())\n path = path if path.exists() else path.with_suffix(suffix.upper())\n return path\n","sub_path":"datasets/timit_asr/timit_asr.py","file_name":"timit_asr.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"523509619","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('webgroup', '0002_auto_20170411_2245'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Groupings',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=255, verbose_name='Kursnamn')),\n ('courses', models.ManyToManyField(to='webgroup.Course')),\n ],\n ),\n ]\n","sub_path":"wsgi/iportalen_django/webgroup/migrations/0003_groupings.py","file_name":"0003_groupings.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"28665860","text":"import datetime\nfrom accounting import models \nfrom django.db.models import Q\nfrom calendar import monthrange\nfrom common_data.utilities import AutomatedServiceMixin\n\n\nclass AccountingTaskService(AutomatedServiceMixin):\n service_name = 'accounting'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.today = datetime.date.today()\n\n def _run(self):\n print('running accounting services')\n self.run_recurring_expenses()\n self.run_interest_on_accounts()\n self.depreciate_assets()\n \n\n def run_recurring_expenses(self):\n expenses = models.RecurringExpense.objects.filter(\n Q(expiration_date__gt=self.today) |\n Q(expiration_date__isnull=True)\n )\n\n for expense in expenses:\n\n if expense.last_created_date is None:\n # expenses whose start date + cycle exceeds today\n if expense.start_date + datetime.timedelta(\n days=expense.cycle) >= self.today:\n expense.create_standalone_expense()\n #expenses\n else:\n if expense.last_created_date + datetime.timedelta(\n days=expense.cycle) <= self.today:\n expense.create_standalone_expense()\n\n def run_interest_on_accounts(self):\n print('accruing interest')\n accounts = models.InterestBearingAccount.objects.all()\n for acc in accounts:\n if acc.should_receive_interest(self.today):\n acc.add_interest()\n acc.last_interest_earned_date = self.today\n acc.save()\n\n\n def depreciate_assets(self):\n print('depreciating assets')\n end_of_month = monthrange(self.today.year, self.today.month)[1]\n if self.today.day == end_of_month:\n #fix # how to make sure each month is depreciated\n for asset in models.Asset.objects.filter(\n Q(category=1) | \n Q(category=2) | \n Q(category=4) | \n Q(category=5)):\n \n amount = asset.depreciation_for_month(self.today.month, \n self.today.year)\n settings = models.AccountingSettings.objects.first()\n bkkpr = models.Bookkeeper.objects.first()\n if settings.default_bookkeeper:\n created_by= settings.default_bookkeeper\n else:\n created_by=bkkpr\n \n j = models.JournalEntry.objects.create(\n date=self.today,\n draft=False,\n memo=\"Asset depreciation\",\n journal=models.Journal.objects.get(pk=5),\n created_by=created_by.employee.user\n )\n j.simple_entry(amount, asset.account, \n asset.depreciation_account)","sub_path":"accounting/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"369275310","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 29 23:24:41 2020\n\n@author: pranjal27bhardwaj\n\"\"\"\n# This script will scrape the best performerming stocks of that day and save it as CSV file.\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef daily_gainers():\n dfs = pd.read_html('https://money.rediff.com/gainers/bse/daily',header=0)\n for df in dfs[:-1]:\n df=df\n\n df['% Change'] = df['% Change'].str.replace(' ', \"\")\n df1 = df[['Company', '% Change', 'Current Price (Rs)']][:10]\n data = {}\n col = list(df1)\n for i in range(10):\n current = 'Company {}'.format(i+1)\n data[current] = {}\n c=0\n for j in col:\n if c==0:\n data[current]['Company Name'] = df[j][i]\n elif c==1:\n data[current]['% Change'] = df[j][i]\n else:\n data[current]['Current Price (Rs)'] = df[j][i]\n c+=1\n return data\n \n df1.to_csv('daily_top_gainers.csv',index=False)\n \n \n#daily_gainers()\n\n\n\ndef plot_daily_gainers():\n plt.style.use('fivethirtyeight')\n data_daily_gainers = pd.read_csv('daily_top_gainers.csv')\n data_daily_gainers_final = data_daily_gainers[:16]\n x1 = data_daily_gainers_final.plot.bar(x = 'Company', y = '% Change', title = 'Daily Top Gainers', color='Black')\n plt.savefig('daily_top_gainers.png', bbox_inches='tight')\n plt.show(x1)\n \nplot_daily_gainers() \n","sub_path":"ML/scraping/gainers/daily_top_gainers.py","file_name":"daily_top_gainers.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"200666364","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom requests_oauthlib import OAuth1Session\nimport json\nimport secret\n\n# URL for keyword search\nurl = 'https://api.twitter.com/1.1/search/tweets.json'\n\nkeyword = 'Python'\nparams = {'q': keyword, 'count': 10}\n\n# GET by OAuth\ntwitter = OAuth1Session(secret.CK, secret.CS, secret.AT, secret.AS)\nreq = twitter.get(url, params = params)\n\nif req.status_code == 200:\n timeline = json.loads(req.text)\n for each in timeline['statuses']:\n print('-----')\n print(each['text'])\nelse:\n print (\"Error: %d\" % req.status_code)\n","sub_path":"twitter/timeline.py","file_name":"timeline.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"652086884","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('lessons', '0013_auto_20150505_2212'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='review',\n old_name='user',\n new_name='student',\n ),\n migrations.AlterField(\n model_name='post',\n name='publish_date',\n field=models.DateTimeField(default=datetime.datetime(2015, 5, 5, 22, 18, 12, 901602), null=True),\n ),\n ]\n","sub_path":"lessons/migrations/0014_auto_20150505_2218.py","file_name":"0014_auto_20150505_2218.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"378439259","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 31 16:52:22 2019\r\n\r\n@author: Julia\r\n\"\"\"\r\nimport tensorflow.compat.v1 as tf\r\nimport pandas as pd\r\nimport numpy as np\r\nimport FirstWindow\r\n#第一步:------------------------收集和清洗資料\r\ndf = pd.read_csv('早餐早午餐中式.txt', sep='\\t', names=['user_na','rest_id','score'])\r\ndf['user_id'] = df.index\r\n\r\ndf['movieRow'] = df.index\r\nmovies_df = df[['movieRow', 'rest_id']]\r\nmovies_df.to_csv('rest1.csv', index=False, header=True, encoding='utf-8')\r\n\r\nratings_df = pd.merge(df, movies_df, on='rest_id')\r\nprint(ratings_df)\r\nratings_df = ratings_df[['user_id', 'movieRow_x', 'score']]\r\nratings_df.to_csv('score1.csv', index=False, header=True, encoding='utf-8')\r\n#第二步:-----------------------建立評分矩陣rating和評分紀錄矩陣record\r\nuserNo=ratings_df['user_id'].count()\r\nmovieNo=ratings_df['movieRow_x'].count()\r\n#userNo = tf.cast(userNo,dtype=tf.int32)\r\n#movieNo = tf.cast(movieNo,dtype=tf.int32)\r\nrating = np.zeros((movieNo, userNo))\r\nflag = 0\r\nratings_df_length = np.shape(ratings_df)[0]\r\nfor index, row in ratings_df.iterrows():\r\n rating[int(row['movieRow_x'])][int(row['user_id'])] = row['score']\r\n flag += 1\r\nrecord = rating > 0\r\nrecord = np.array(record, dtype=int)\r\n#第三步:----------------------------構建模型\r\ndef normalizeRatings(rating, record):\r\n m, n = rating.shape\r\n rating_mean = np.zeros((m, 1))\r\n rating_norm = np.zeros((m, n))\r\n for i in range(m):\r\n idx = (record[i, :] != 0)\r\n rating_mean[i] = np.mean(rating[i, idx])\r\n rating_norm[i, idx] = rating[i, idx] - rating_mean[i]\r\n return rating_norm, rating_mean\r\n\r\nrating_norm, rating_mean = normalizeRatings(rating, record)\r\nrating_norm = np.nan_to_num(rating_norm)\r\nrating_mean = np.nan_to_num(rating_mean)\r\n# 構建模型\r\nnum_features = 12\r\nX_parameters = tf.Variable(tf.random_normal([movieNo, num_features], stddev = 0.35))\r\nTheta_parameters = tf.Variable(tf.random_normal([userNo, num_features], stddev = 0.35))\r\nloss = 1/2 * tf.reduce_sum(((tf.matmul(X_parameters, Theta_parameters, transpose_b=True) - rating_norm) * record) ** 2) + 0.5*(1/2 * (tf.reduce_sum(X_parameters ** 2) + tf.reduce_sum(Theta_parameters ** 2)))\r\n# 基於內容的推薦演算法模型\r\ntrain = tf.train.AdamOptimizer(1e-3).minimize(loss)\r\n# 第四步:------------------------------------訓練模型\r\ntf.summary.scalar('train_loss', loss)\r\nsummaryMerged = tf.summary.merge_all()\r\nfilename = 'movie_tensorborad.csv'\r\nwriter = tf.summary.FileWriter(filename)\r\nsess = tf.Session()\r\ninit = tf.global_variables_initializer()\r\nsess.run(init)\r\nfor i in range(2000):\r\n _, movie_summary = sess.run([train, summaryMerged])\r\n writer.add_summary(movie_summary, i)\r\n# 第五步:-------------------------------------評估模型\r\nCurrent_X_parameters, Current_Theta_parameters = sess.run([X_parameters, Theta_parameters])\r\npredicts = np.dot(Current_X_parameters, Current_Theta_parameters.T) + rating_mean\r\nerrors = np.sqrt(np.sum(((predicts - rating) * record)**2))\r\n# 第六步:--------------------------------------構建完整的推薦系統\r\nFirstWindow.na=\"1\"\r\nuser_na = FirstWindow.na\r\nuser_id=df[df['user_na'].isin(['A'])].index.values[0]\r\nprint(user_id)\r\nsortedResult = predicts[:, int(user_id)].argsort()[::-1]\r\nidx = 0\r\nfor i in sortedResult:\r\n a=movies_df.iloc[i]['rest_id']\r\n print(a)\r\n #print(u'評分: %.1f, 店名: %s' % (predicts[i, int(user_id)]-2, movies_df.iloc[i]['rest_id']))\r\n idx += 1\r\n if idx == 1:\r\n break\r\n \r\n \r\n'''FirstWindow.nam=\"1\"\r\nuser_id = FirstWindow.nam\r\nsortedResult = predicts[:, int(user_id)].argsort()[::-1]\r\nidx = 0\r\nglobal a\r\nfor i in sortedResult:\r\n global a\r\n a=df.iloc[i]['user_na']\r\n idx += 1\r\n if idx == 1:\r\n break'''","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"248448828","text":"import sys\nx = sys.maxsize\ny = sys.maxsize\nMAX_GCD = sys.maxsize\n\nn = int(input())\nnum = [int(i) for i in input().split()]\nrem = [int(i) for i in input().split()]\nn = len(num)\nprod = 1\nfor i in num:\n prod*=i\n\npp = [ 0 for i in range(n)]\nfor i in range(n):\n pp[i] = prod//num[i]\n\ninv = [ 0 for i in range(n)] \n\n\ndef GCD(a,b):\n return a if b==0 else GCD(b,a%b)\n\ndef ExtendedEuclid(a,b):\n global x, y, MAX_GCD\n\n if b==0:\n x=1\n y=0\n MAX_GCD = a\n return\n\n ExtendedEuclid(b,a%b)\n cX = y\n cY = x - (a//b)*y\n\n x = cX\n y = cY\n\ndef invModulo(a,m):\n if GCD(a,m) != 1:\n raise Exception('No inverse modulo exist for given a and m')\n else:\n ExtendedEuclid(a,m)\n return (x+m)%m\n\n\nfor i in range(n):\n inv[i] = invModulo(pp[i],num[i])\n\nres = 0\n\nfor i in range(n):\n res+=(rem[i] * pp[i] * inv[i])%prod\n\nprint(res%prod)\n","sub_path":"15. Number Theory Challenges/13. Linear Congerence.py","file_name":"13. Linear Congerence.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"53372419","text":"#!/usr/bin/env python3\n\"\"\"\nBuild an image in the pangeo stack.\n\"\"\"\nimport subprocess\nfrom dateutil.parser import parse\nfrom datetime import datetime\nimport pytz\nimport docker\nimport os\nfrom functools import lru_cache\nfrom repo2docker.app import Repo2Docker\nimport argparse\n\ndef modified_date(n, *paths, **kwargs):\n \"\"\"\n Return the commit date for nth commit that modified *paths\n \"\"\"\n iso_date = subprocess.check_output([\n 'git',\n 'log',\n '-n', f'{n}',\n '--pretty=format:%cd',\n '--date=iso',\n '--',\n *paths\n ], **kwargs).decode('utf-8').strip().split('\\n')[-1]\n return parse(iso_date)\n\n\n@lru_cache(128)\ndef image_exists_in_registry(client, image_spec):\n \"\"\"\n Return true if image exists in docker registry\n \"\"\"\n try:\n image_manifest = client.images.get_registry_data(image_spec)\n return image_manifest is not None\n except docker.errors.ImageNotFound:\n return False\n except docker.errors.APIError as e:\n # This message seems to vary across registries?\n if e.explanation.startswith('manifest unknown: '):\n return False\n else:\n raise\n\ndef docker_build(image_spec, path, build_args):\n print(f'Building {image_spec}')\n if os.path.exists(os.path.join(path, 'Dockerfile')):\n df_path = os.path.join(path, 'Dockerfile')\n else:\n df_path = os.path.join(path, 'binder', 'Dockerfile')\n command = [\n 'docker', 'build',\n '-t', image_spec,\n '-f', df_path\n ]\n for k, v in build_args.items():\n command += ['--build-arg', f'{k}={v}']\n command.append(path)\n subprocess.check_call(command)\n\n\ndef r2d_build(image, image_spec, cache_from):\n r2d = Repo2Docker()\n\n r2d.subdir = image\n r2d.output_image_spec = image_spec\n r2d.user_id = 1000\n r2d.user_name = 'jovyan'\n r2d.cache_from = cache_from\n\n r2d.initialize()\n r2d.build()\n\n if os.path.exists(os.path.join(r2d.subdir, 'binder/verify')):\n print(f'Validating {image_spec}')\n # Validate the built image\n subprocess.check_call([\n 'docker',\n 'run',\n '-i', '-t',\n f'{r2d.output_image_spec}',\n 'binder/verify'\n ])\n else:\n print(f'No verify script found for {image_spec}')\n\ndef main():\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\n 'image',\n help='Image to build. Subdirectory with this name must exist'\n )\n argparser.add_argument(\n '--image-prefix',\n help='Prefix for image to be built. Usually contains registry url and name',\n default='pangeo/'\n )\n argparser.add_argument(\n '--push',\n help='Push the built image to the docker registry',\n action='store_true',\n default=False\n )\n\n args = argparser.parse_args()\n\n image_name = f'{args.image_prefix}{args.image}'\n print(f'Building {image_name}')\n client = docker.from_env()\n cache_from = []\n\n # Pull the most recent built image available for this docker image\n # We can re-use the cache from that, significantly speeding up\n # our image builds\n for i in range(1, 100):\n date = modified_date(i, '.')\n # Stick to UTC for calver\n existing_calver = date.astimezone(pytz.utc).strftime('%Y.%m.%d')\n existing_image_spec = f'{image_name}:{existing_calver}'\n if image_exists_in_registry(client, existing_image_spec):\n print(f'Re-using cache from {existing_image_spec}')\n cache_from = [existing_image_spec]\n subprocess.check_call([\n 'docker',\n 'pull', existing_image_spec\n ])\n break\n\n\n calver = datetime.utcnow().strftime('%Y.%m.%d')\n dockerfile_paths = [\n os.path.join(args.image, 'binder', 'Dockerfile'),\n os.path.join(args.image, 'Dockerfile')\n ]\n if any((os.path.exists(df) for df in dockerfile_paths)):\n # Use docker if we have a Dockerfile\n # Can be just r2d once we can pass arbitrary BUILD ARGs to it\n # https://github.com/jupyter/repo2docker/issues/645\n docker_build(\n f'{image_name}:{calver}',\n args.image,\n {\n 'CALVER': calver\n }\n )\n else:\n # Build regular image\n r2d_build(\n args.image,\n f'{image_name}:{calver}',\n cache_from\n )\n\n # Build onbuild image\n docker_build(\n f'{image_name}-onbuild:{calver}',\n 'onbuild',\n {'BASE_IMAGE_SPEC': f'{image_name}:{calver}'}\n )\n\n\nif __name__ == '__main__':\n main()","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"565520855","text":"\"\"\"Helper macro to compile and test code samples.\"\"\"\n\nload(\"@rules_python//python:defs.bzl\", \"py_binary\")\nload(\"@ortools_deps//:requirements.bzl\", \"requirement\")\n\ndef code_sample_cc(name):\n native.cc_binary(\n name = name + \"_cc\",\n srcs = [name + \".cc\"],\n deps = [\n \"//ortools/base\",\n \"//ortools/graph:assignment\",\n \"//ortools/graph:ebert_graph\",\n \"//ortools/graph:linear_assignment\",\n \"//ortools/graph:max_flow\",\n \"//ortools/graph:min_cost_flow\",\n \"//ortools/graph:shortestpaths\",\n ],\n )\n\n native.sh_test(\n name = name + \"_cc_test\",\n size = \"small\",\n srcs = [\"code_samples_cc_test.sh\"],\n args = [name],\n data = [\n \":\" + name + \"_cc\",\n ],\n )\n\ndef code_sample_py(name):\n py_binary(\n name = name + \"_py3\",\n srcs = [name + \".py\"],\n main = name + \".py\",\n data = [\n \"//ortools/graph/python:linear_sum_assignment.so\",\n \"//ortools/graph/python:min_cost_flow.so\",\n \"//ortools/graph/python:max_flow.so\",\n ],\n deps = [\n requirement(\"absl-py\"),\n requirement(\"numpy\"),\n ],\n python_version = \"PY3\",\n srcs_version = \"PY3\",\n )\n\n native.sh_test(\n name = name + \"_py_test\",\n size = \"small\",\n srcs = [\"code_samples_py_test.sh\"],\n args = [name],\n data = [\n \":\" + name + \"_py3\",\n ],\n )\n\ndef code_sample_cc_py(name):\n code_sample_cc(name = name)\n code_sample_py(name = name)\n","sub_path":"ortools/graph/samples/code_samples.bzl","file_name":"code_samples.bzl","file_ext":"bzl","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"51338025","text":"import pickle\nfrom os.path import join\nfrom envs.ScrapyEnviroment.Lib import os\n\nimport PreProcessing_valid\n\n\ndef Classification():\n # s = \"Đồ ăn tại quán ăn rất là đầy đặn,đậm đà,ngon, không gian quán đẹp\"\n # s= \"Mình thấy suất XL ở đây to hơn, ngon hơn và rất đẹp\"\n s=\"Đường vào quán vẫn khó tìm , lòng_vòng lắm .\"\n s = PreProcessing_valid.PreProcessing(s)\n print(s)\n pre = []\n pre.append(s)\n list_file = os.listdir(\"models_new\")\n print(list_file)\n for i in list_file:\n load_file = open(join(\"models_new\",i),'rb')\n clf = pickle.load(load_file)\n t = clf.predict(pre)\n print(t)\n\n\n\n # datas_valid = []\n # labels_valid = []\n # vectorizer = CountVectorizer()\n # transformed_x_valid = vectorizer.fit_transform(s).toarray()\n # load_file = open(join(\"models\",\"STYLEOPTIONS_new.pkl\"),'rb')\n # clf = pickle.load(load_file)\n # print(\"Loading file : \",clf)\n #\n # with open(join(\"data_valid\", \"datas_STYLEOPTIONS_valid_new.txt\"), 'r', encoding='utf-8')as file:\n # for i in file:\n # datas_valid.append(i)\n # with open(join(\"data_valid\", \"labels_STYLEOPTIONS_valid_new.txt\"), 'r', encoding='utf-8')as file:\n # for i in file:\n # labels_valid.append(i)\n #\n # X_valid = datas_valid\n # a = clf.predict(X_valid)\n # with open(\"predict.txt\",'w',encoding='utf-8') as f:\n # for i in a:\n # f.write(i)\n # t = clf.predict(pre)\n # print(t)\n # print(a)\n # print(confusion_matrix(labels_valid, a))\n\n # X_train, y_train = LoadData(\"../data_train/.txt\", \"labels_new1.txt\")\n\nif __name__ == \"__main__\":\n Classification()\n\n","sub_path":"test_all_models.py","file_name":"test_all_models.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"310689994","text":"#\r\n# set of functions that are used by two or more of the knapsack solution\r\n# methods: enum, branch-and-bound, dynamic programming and greedy\r\n#\r\n\r\nclass knapsack:\r\n \r\n def __init__(self, filename):\r\n self.QUIET = False\r\n # Note: knapsack intems in the input files are numbered from 1 to N\r\n # We shall use arrays of size N+1 to store the indexes, weights and values\r\n # of the items. So w[1] and v[1] stored the weight and value of the first item.\r\n \r\n try:\r\n f = open (filename)\r\n self.Nitems = int(f.readline())\r\n self.item_weights = [None]*(self.Nitems + 1)\r\n self.item_values = [None]*(self.Nitems + 1)\r\n self.temp_indexes = [0]*(self.Nitems + 1)\r\n\r\n for i in range(1, self.Nitems + 1):\r\n (index_string, value_string, weight_string) = f.readline().split()\r\n self.temp_indexes[i] = int(index_string)\r\n self.item_values[i] = int(value_string)\r\n self.item_weights[i] = int(weight_string)\r\n \r\n self.Capacity = int(f.readline())\r\n return\r\n except:\r\n print(\"Problem reading from file and/or allocating arrays\")\r\n exit(1)\r\n \r\n def print_instance(self):\r\n print(\"item\\tW\\tV\")\r\n for i in range(1, self.Nitems + 1):\r\n print(\"%d\\t%d\\t%d\" % (self.temp_indexes[i], self.item_weights[i], self.item_values[i]))\r\n print(\"%d\" % self.Capacity)\r\n \r\n def sort_by_ratio(self):\r\n # sort the item indexes\r\n self.temp_indexes.sort(key=self.mycomp, reverse=True)\r\n \r\n # Sadly the above puts the None first item at the end of the list move the end to the start\r\n # I'm sure there's a better way to do this\r\n start = self.temp_indexes.pop()\r\n self.temp_indexes.insert(0, start)\r\n \r\n \r\n for i in range(1, self.Nitems + 1):\r\n print(\"%d\\t%d\\t\" % (self.item_weights[self.temp_indexes[i]], self.item_values[self.temp_indexes[i]]), end=\"\")\r\n print(\"%f\" % (self.item_weights[self.temp_indexes[i]] / self.item_values[self.temp_indexes[i]]))\r\n \r\n def mycomp(self, ia):\r\n if (self.item_values[ia] == None):\r\n return 0\r\n return self.item_values[ia]/self.item_weights[ia]\r\n \r\n def check_evaluate_and_print_sol(self, sol):\r\n # This function prints out the items packed in a solution, in ascending order.\r\n # Since items may have been sorted in a different order (using temp_indexes), it first reverses this mapping\r\n\r\n\r\n # The vector sol is a \"binary\" vector of length Nitems, describing the items to be put in the knapsack.\r\n # The (global) temp_indexes array maps item i to temp_indexes[i].\r\n # So sol[i]=True really means item temp_indexes[i] should be taken.\r\n # In order to print out the item numbers referred to by sol in ascending order, we\r\n # copy them accross to an auxiliary array \"pack\" and then print the\r\n # items in pack in ascending order.\r\n \r\n self.total_value = 0 # total value packed\r\n self.total_weight = 0 # total weight packed\r\n pack = [None]*(self.Nitems + 1) # auxilliary array to do reverse-mapping\r\n \r\n # First pass: unamp the mapping using pack\r\n for i in range(1, self.Nitems + 1):\r\n if (sol[i]):\r\n pack[self.temp_indexes[i]] = True\r\n else:\r\n pack[self.temp_indexes[i]] = False\r\n \r\n # Second pass: now print out item numbers of items to be packed in ascending order\r\n if (not self.QUIET):\r\n print(\"Pack items: \", end=\"\")\r\n \r\n for i in range(1, self.Nitems + 1):\r\n if (pack[i]):\r\n if (not self.QUIET):\r\n print(\"%d \" % i, end=\"\")\r\n self.total_value += self.item_values[i]\r\n self.total_weight += self.item_weights[i]\r\n \r\n # Finally, print out the value, weight and Capacity, and feasibility\r\n if (not self.QUIET):\r\n if (self.total_weight > self.Capacity):\r\n print(\"\\nvalue=%d weight=%d > Capacity=%d: Infeasible\" % (self.total_value, self.total_weight, self.Capacity))\r\n else:\r\n print(\"\\nvalue=%d weight=%d <= Capacity=%d: Feasible\" % (self.total_value, self.total_weight, self.Capacity))\r\n if (self.total_weight > self.Capacity):\r\n return True # return True for infeasible solutions\r\n else:\r\n return False # return True for feasible solutions\r\n\r\n","sub_path":"COMP26120_n34851zc-lab7/python/knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"368735892","text":"import numpy as np\nimport pandas as pd\n\nimport pickle as pkl\n\n# from rf_data_prep import CATEGORICAL_DTYPES\n\nfrom rf_data_prep.read_observation import is_valid_category, obs_check, dict_to_dataframe\n\n\nCATEGORICAL_DTYPES = pkl.load(open( \"CATEGORICAL_DTYPES.pkl\", \"rb\" ))\n\nEDITED_OBS = {'channelGrouping': 'Organic Search',\n 'visitNumber': 1,\n 'device.browser': 'BAD DATA',\n 'device.operatingSystem': 'BAD DATA',\n 'device.isMobile': False,\n 'device.deviceCategory': 'desktop',\n 'geoNetwork.continent': 'Oceania',\n 'geoNetwork.subContinent': 'Australasia',\n 'geoNetwork.country': 'Australia',\n 'geoNetwork.region': 'not available in demo dataset',\n 'geoNetwork.metro': 'not available in demo dataset',\n 'geoNetwork.city': 'not available in demo dataset',\n 'totals.transactionRevenue': False,\n 'trafficSource.campaign': '(not set)',\n 'trafficSource.source': 'google',\n 'trafficSource.medium': 'organic',\n 'trafficSource.adwordsClickInfo.page': np.nan,\n 'trafficSource.adwordsClickInfo.slot': np.nan,\n 'trafficSource.adwordsClickInfo.adNetworkType': np.nan,\n 'trafficSource.adContent': np.nan}\n\nTRUE_OBS = {'channelGrouping': 'Organic Search',\n 'visitNumber': 1,\n 'device.browser': 'Other',\n 'device.operatingSystem': 'Other',\n 'device.isMobile': False,\n 'device.deviceCategory': 'desktop',\n 'geoNetwork.continent': 'Oceania',\n 'geoNetwork.subContinent': 'Australasia',\n 'geoNetwork.country': 'Australia',\n 'geoNetwork.region': 'not available in demo dataset',\n 'geoNetwork.metro': 'not available in demo dataset',\n 'geoNetwork.city': 'not available in demo dataset',\n 'totals.transactionRevenue': False,\n 'trafficSource.campaign': '(not set)',\n 'trafficSource.source': 'google',\n 'trafficSource.medium': 'organic',\n 'trafficSource.adwordsClickInfo.page': np.nan,\n 'trafficSource.adwordsClickInfo.slot': np.nan,\n 'trafficSource.adwordsClickInfo.adNetworkType': np.nan,\n 'trafficSource.adContent': np.nan}\n\n# unit test 1:\ndef test_is_valid_category():\n # testing with key:value parameters ('channelGrouping','Organic Search'):\n assert is_valid_category('channelGrouping','Organic Search',CATEGORICAL_DTYPES) == True\n\n# unit test 2:\ndef test_obs_check():\n # testing whether function can successfully convert EDITED_OBS to match TRUE_OBS:\n assert obs_check(EDITED_OBS, CATEGORICAL_DTYPES) == TRUE_OBS\n\n# unit test 3:\ndef test_dict_to_dataframe():\n # testing whether function can convert dictionary data input to Pandas.DataFrame object\n # with correct dtypes\n assert dict_to_dataframe(EDITED_OBS,CATEGORICAL_DTYPES).dtypes.to_dict() == CATEGORICAL_DTYPES\n\n","sub_path":"tests/test_unit.py","file_name":"test_unit.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"122641067","text":"# constants\n\nconstants = {\n 'departure_D': float(100),\n 'departure_S': float(100),\n 'initial_W': float(21000000-69864.73),\n 'initial_B': float(69864.73),\n 'decay_rate': float(0.996673),\n 'mean_C': float(0.5),\n 'sigma_C': float(0.1),\n 'alpha_C': float(0.8),\n 'epsilon_B': float(0.01),\n 'momentum_U': float(0.7),\n 'gamma_K': float(0.5),\n 'initial_K': float(1),\n 'initial_lambda_D': float(1000),\n 'initial_lambda_S': float(1000),\n}\n","sub_path":"validation/tokeneconomy/baseline/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256210798","text":"from django.http import HttpResponse,JsonResponse\nfrom user import models\nimport json\nimport pymysql\n\ndef userLogin(request):\n login_msg = request.GET\n user = getUser(login_msg['username'])\n if user:\n if user.password == login_msg['password']:\n login_msg = {'code': 0, 'status':0, 'msg':'OK', 'data': login_msg}\n response = HttpResponse(json.dumps(login_msg), content_type='application/json')\n print(json.dumps(login_msg))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n return response\n else:\n return HttpResponse('密码不正确')\n return HttpResponse('用户不存在')\n\n\ndef getUser(login_username):\n try:\n user = models.User.objects.get(userName=login_username)\n except:\n return \"\"\n return user\n","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414762020","text":"import numpy as np\n\ndef computeNumericalGradient(N, X, y):\n paramsInitial = N.getParams()\n numgrad = np.zeros(paramsInitial.shape)\n perturb = np.zeros(paramsInitial.shape)\n e = 1e-4\n\n for p in range(len(paramsInitial)):\n #Set perturbation vector\n perturb[p] = e\n N.setParams(paramsInitial + perturb)\n loss2 = N.costFunction(X, y)\n \n N.setParams(paramsInitial - perturb)\n loss1 = N.costFunction(X, y)\n\n #Compute Numerical Gradient\n numgrad[p] = (loss2 - loss1) / (2*e)\n\n #Return the value we changed to zero:\n perturb[p] = 0\n \n #Return Params to original value:\n N.setParams(paramsInitial)\n\n return numgrad","sub_path":"NN/Neural_Network/computeNumericalGradient.py","file_name":"computeNumericalGradient.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242836313","text":"#!/usr/bin/env python\n################################################################################\n# Software License Agreement (BSD License)\n#\n# Copyright (c) 2013, Johns Hopkins University\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of the Johns Hopkins University nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n################################################################################\n__author__ = \"Kelleher Guerin\"\n__email__ = \"futureneer@gmail.com\"\n__copyright__ = \"2013, The Johns Hopkins University\"\n__license__ = \"BSD\"\n################################################################################\n\nimport roslib; roslib.load_manifest('wallframe_core')\nimport rospy,sys\n### PySide ###\nimport PySide\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\nfrom PySide import QtCore\n\nfrom geometry_msgs.msg import Transform\nfrom geometry_msgs.msg import Vector3\nfrom std_msgs.msg import Bool\nfrom std_msgs.msg import String\n\nfrom wallframe_msgs.msg import WallframeUser\nfrom wallframe_msgs.msg import WallframeUserArray\nfrom wallframe_msgs.msg import WallframeUserEvent\nfrom wallframe_msgs.msg import TrackerUser\nfrom wallframe_msgs.msg import TrackerUserArray as tracker_msg\n\nimport wallframe_core\nfrom wallframe_core.srv import *\nimport signal\n\n################################################################################\nclass WallframeTooltip(QWidget):\n SIGNAL_HIDE = QtCore.Signal()\n SIGNAL_SHOW = QtCore.Signal(str)\n def __init__(self, node_name):\n QWidget.__init__(self)\n self.node_name = node_name\n self.wall_height = rospy.get_param(\"/wallframe/core/params/height\", 3197)\n self.wall_width = rospy.get_param(\"/wallframe/core/params/width\", 5760)\n\n self.x = rospy.get_param(\"/wallframe/core/params/x\", 1680)\n self.y = rospy.get_param(\"/wallframe/core/params/y\", 24)\n\n self.height = int(rospy.get_param(\"/wallframe/\" + self.node_name + \"/params/height_percentage\", 0.08) * self.wall_height)\n self.width = int(rospy.get_param(\"/wallframe/\" + self.node_name + \"/params/width_percentage\", 0.2) * self.wall_width)\n\n self.x_position = int(rospy.get_param(\"/wallframe/\"+ self.node_name + \"/params/x_percentage\", 0.4) * self.wall_width + self.x)\n self.y_position = int(rospy.get_param(\"/wallframe/\" + self.node_name + \"/params/y_percentage\", 0.05) * self.wall_height + self.y)\n self.name = rospy.get_param(\"/wallframe/\" + self.node_name + \"/params/name\")\n self.assets_path = rospy.get_param(\"/wallframe/core/tooltip/assets\")\n #self.setStyleSheet(\"background-color:#ffffff;color:#222222\")\n self.setWindowFlags(QtCore.Qt.FramelessWindowHint )\n # the tool tip always stays on top\n self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)\n self.move(self.x_position, self.y_position)\n self.show()\n #self.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform)\n self.setAutoFillBackground(True)\n self.setWindowOpacity(.5)\n #self.setAttribute(Qt.WA_TranslucentBackground, True)\n self.resize(self.width, self.height)\n #print \"Tool tip height\" , self.height , \"width \" , self.width\n #print \"xpos \" , self.x_position , \" ypos\" , self.y_position\n\n\n self.text_label = QLabel('Welcome')\n self.text_label.setFixedSize(self.width, self.height)\n #self.text_label.setAttribute(Qt.WA_TranslucentBackground, True)\n layout = QHBoxLayout()\n layout.addWidget(self.text_label)\n #self.text_label.setStyleSheet(\"QLabel { color : blue; font-size: 30px; }\")\n self.setLayout(layout)\n # ROS Services\n\n self.update_tooltip_srv = rospy.Service(self.name + '/update_tooltip', wallframe_core.srv.update_tooltip, self.update_tooltip_service)\n rospy.logwarn(\"WallframeTooltip: Service Ready [\" + self.name + \"/update_tooltip ]\")\n self.hide_tooltip_srv = rospy.Service(self.name + '/hide_tooltip', wallframe_core.srv.hide_tooltip, self.hide_tooltip_service)\n rospy.logwarn(\"WallframeTooltip: Service Ready [\" + self.name + \"/hide_tooltip ]\")\n\n self.SIGNAL_HIDE.connect(self.hide_tooltip)\n self.SIGNAL_SHOW.connect(self.update_tooltip)\n # Running\n rospy.logwarn(\"WallframeTooltip: Started\")\n\n def hide_tooltip(self):\n self.hide()\n\n\n def update_tooltip(self, image_path):\n #pixmap = QPixmap(image_path)\n #self.setStyleSheet(\"border-image: url(\" + image_path + \");\")\n #self.text_label.setPixmap(pixmap)\n\n movie = QMovie(image_path)\n movie.setScaledSize(QtCore.QSize(self.width, self.height))\n self.text_label.setMovie(movie)\n movie.start()\n self.update()\n self.show()\n\n\n def update_tooltip_service(self, request):\n rospy.logdebug(\"WallframeTooltip: Service Call to update the text [\"+request.app_id+\"]\")\n\n self.text_label.setText(request.text)\n image_path = self.assets_path + \"/\" + request.background_path\n self.SIGNAL_SHOW.emit(image_path)\n return True\n\n def hide_tooltip_service(self, request):\n rospy.logdebug(\"WallframeTooltip: Service Call to hide [\"+request.app_id+\"]\")\n\n self.SIGNAL_HIDE.emit()\n return True\n# MAIN\nif __name__ == '__main__':\n try:\n node_name = sys.argv[1]\n except:\n node_name = \"wallframe_tooltip\"\n rospy.init_node(node_name, anonymous=True)\n app = QApplication(sys.argv)\n tooltip = WallframeTooltip(node_name)\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n # Running\n app.exec_()\n # Done\n rospy.logwarn('WallframeInfobar: Finished')\n","sub_path":"wallframe_core/scripts/wallframe_tooltip.py","file_name":"wallframe_tooltip.py","file_ext":"py","file_size_in_byte":7046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"602000582","text":"import pandas as pd\nimport numpy as np\n\nfrom corna import constants as const\nfrom corna import helpers as hlp\nfrom isotopomer import Infopacket\n\ndef calculate_pool_total(df):\n \"\"\"\n This function calculates pool total\n for all the metabolites in the input data file\n\n Args:\n df: dataframe for which pool total has to be calculated.\n Returns:\n final_df: dataframe which consists of the calculated values.\n \"\"\"\n df[const.POOL_TOTAL_COL] = df[const.NA_CORRECTED_WITH_ZERO]\n df1 = df.groupby([const.SAMPLE_COL, const.NAME_COL])[const.POOL_TOTAL_COL].sum().reset_index()\n df.drop(const.POOL_TOTAL_COL, axis=1, inplace=True)\n df = df.merge(df1, on=[const.SAMPLE_COL, const.NAME_COL])\n return df\n\n\ndef pool_total(na_corr_df, colname):\n \"\"\"\n This function calculates the pool total for each metabolite in a sample\n Args:\n na_corr_df: data frame with corrected intensities\n colname: Name of the column that contains corrected intensities\n \n Returns: grouped data frame with pool total\n \n \"\"\"\n pool_total_df = na_corr_df.groupby(([NAME, SAMPLE]))\n pool_total_df = pool_total_df.apply(lambda x: x[x[colname] >= 0][colname].sum())\n return pool_total_df\n\n\ndef pool_total_MSMS(na_corr_df, colname):\n \"\"\"\n This function calculates the pool total for each metabolite in a sample\n Args:\n na_corr_df: data frame with corrected intensities\n colname: Name of the column that contains corrected intensities\n\n Returns: grouped data frame with pool total\n \"\"\"\n na_corr_df[METABOLITE_NAME] = na_corr_df[NAME].apply(get_metabolite)\n pool_total_df = na_corr_df.groupby(([METABOLITE_NAME, SAMPLE]))\n pool_total_df = pool_total_df.apply(lambda x: x[x[colname] >= 0][colname].sum())\n return pool_total_df\n\ndef fractional_enrichment(df):\n \"\"\"\n This function calculates fractional enrichment\n for all the metabolites in the input data file\n Args:\n df: dataframe for which fractional enrichment has to be calculated.\n Returns:\n final_df: dataframe which consists of the calculated values.\n \"\"\"\n final_df = pd.DataFrame()\n df = df.filter([const.SAMPLE_COL, const.NAME_COL, const.LABEL_COL, const.FORMULA_COL, const.NA_CORRECTED_COL])\n df = hlp.replace_negatives_in_column(df,const.NA_CORRECTED_WITH_ZERO, const.NA_CORRECTED_COL)\n\n df = calculate_pool_total(df)\n df[const.FRACTIONAL_ENRICH] = df[const.NA_CORRECTED_WITH_ZERO]/df[const.POOL_TOTAL_COL]\n final_df = df.fillna(0)\n if const.NA_CORRECTED_COL in final_df.columns:\n final_df.drop([const.NA_CORRECTED_COL], axis=1, inplace=True)\n if const.NA_CORRECTED_WITH_ZERO in final_df.columns:\n final_df.drop([const.NA_CORRECTED_WITH_ZERO], axis=1, inplace=True)\n return final_df\n\n\ndef zero_if_negative(num):\n \"\"\"\n This function replaces negative numbers by zero_if_negative\n\n Args:\n num : any int value\n\n Return:\n 1. zero if num is negative\n 2. number itself if num is non negative\n \"\"\"\n return 0 if num < 0 else num\n\ndef sum_intensities(fragments_dict):\n \"\"\"\n This function calculates the sum of corrected intensities for a given sample\n\n Args:\n fragments_dict : dictionary of the form, example : {'Aceticacid_C13_1': [C2H4O2,\n {'sample_1': array([ 0.0164])}, False, 'Aceticacid']\n Returns:\n sum_dict : dictionary of sum of all corrected intensities for each sample\n \"\"\"\n all_frag_info = fragments_dict.values()\n\n sample_names = []\n for frag in all_frag_info:\n sample_names.extend(frag.data.keys())\n sample_names = list(set(sample_names))\n\n sum_dict = {}\n\n for sample_name in sample_names:\n sum_dict[sample_name] = sum(value.data.get(sample_name,0) for value in all_frag_info)\n\n return sum_dict\n\ndef enrichment(fragments_dict, decimals):\n \"\"\"\n This function calculates the fractional enrichment for each label\n Fractional enrichment[sample1] = Corrected Intensity/ Sum of corrected intensities of all labels\n \n Args:\n fragments_dict : dictionary of the form, example : {'Aceticacid_C13_1': [C2H4O2,\n {'sample_1': array([ 0.0164])}, False, 'Aceticacid']\n \n decimals : number of significant digits to keep\n\n Returns:\n fragments_fractional : fragment dictionary model of fractional enrichment values\n \"\"\"\n fragments_fractional = {}\n sum_dict = sum_intensities(fragments_dict)\n \n for key, value in fragments_dict.iteritems():\n fractional_data = {}\n for sample_name, intensity in value.data.iteritems():\n if not sum_dict[sample_name] == 0:\n fractional_data[sample_name] = np.around(\n intensity / sum_dict[sample_name], decimals)\n else:\n fractional_data[sample_name] = 0\n warnings.warn(\"{} {} {} {}\".format('sum of labels is zero for sample ', sample_name.encode('utf-8'),\n ' of ', (value.name).encode('utf-8')))\n fragments_fractional[key] = Infopacket(\n value.frag, fractional_data, value.unlabeled, value.name)\n \n return fragments_fractional\n\ndef replace_vals(sample_int_dict):\n \"\"\"\n This function replace negatives by zero in sample intensity dictionary\n Args:\n sample_int_dict : dictionary with keys as samples and values as corrected intensities\n \n Returns:\n dict_replaced_vals : sample_int_dict with negative intensities replaced by zeroes\n \"\"\"\n dict_replaced_vals = {}\n \n for sample, intensity in sample_int_dict.iteritems():\n dict_replaced_vals[sample] = zero_if_negative(intensity)\n \n return dict_replaced_vals\n\n\ndef replace_negative_to_zero(corrected_dict):\n \"\"\"\n This function replaces negative intensity values by zero from list of intensity\n in the standardised model dictionary\n \n Args:\n corrected_dict : nested dictionary (std model) with NA corrected intensity values\n \n Returns:\n post_proc_dict : returns nested dictionary with negative values replaced\n \n \"\"\"\n \n post_proc_dict = {}\n \n for frag_key, frag_info in corrected_dict.iteritems():\n sample_int_dict = frag_info.data\n dict_replaced_vals = replace_vals(sample_int_dict)\n post_proc_dict[frag_key] = Infopacket(\n frag_info.frag, dict_replaced_vals, frag_info.unlabeled, frag_info.name)\n \n return post_proc_dict\n\ndef replace_negatives(na_corr_dict):\n \"\"\"\n This function is a wrapper around replace_negatives_to_zero, it performs this\n function for all metabolites in the input data file\n \n Args:\n corrected_dict : nested dictionary (std model) with NA corrected intensity values\n \n Returns:\n post_proc_dict : returns nested dictionary with negative values replaced for\n all the metabolites in the input data file\n \n \"\"\"\n post_processed_dict = {}\n for metabolite, fragment_dict in na_corr_dict.iteritems():\n post_processed_dict[\n metabolite] = replace_negative_to_zero(fragment_dict)\n \n return post_processed_dict\n","sub_path":"corna/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":7222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"519842450","text":"from collections import deque\nfrom array import array\nfrom sys import getsizeof\n\n\n# Lists\n\nletters = [\"a\", \"b\", \"c\", \"d\"]\nmatrix = [[0, 1], [2, 3]]\nzeros = [0] * 5\ncombined = zeros + letters\nnumbers = list(range(21))\nchar = list(\"Hello World\")\nprint(len(char))\n\n\n# Accesing Items\nletters[0] = \"A\"\nprint(letters[0:3])\nprint(letters[0:])\n\nprint(numbers[::2])\nprint(numbers[::-1]) # reverse list order\n\n\n# List Unpacking\nnumbers = [1, 2, 3, 4, 4, 4, 4, 9]\nfirst, *other, last = numbers\n\nprint(first, last)\nprint(other)\n\n\n# Looping over Lists\nfor index, letter in enumerate(letters):\n print(index, letter)\n\n\n# Adding Items\nletters.append(\"e\") # at end of the list\nletters.insert(0, \"-\") # beginning of list\nprint(letters)\n\n# Removing Items\nletters.pop(0)\nletters.remove(\"d\")\ndel letters[0:3]\nletters.clear()\nprint(letters)\n\n\n# Finding Items\nletters = [\"a\", \"b\", \"c\"]\nprint(letters.count(\"d\"))\n\nif \"b\" in letters:\n print(letters.index(\"b\"))\n\n\n# Sorting Lists\nnumbers = [3, 51, 2, 8, 6]\n# numbers.sort(reverse=True)\nprint(sorted(numbers, reverse=True))\nprint(numbers)\n\nitems = [\n (\"Product1\", 10),\n (\"Product1\", 9),\n (\"Product1\", 12),\n]\n\n\n# def sort_item(item):\n# return item[1]\n\n\n# items.sort(key=sort_item)\n\n# Lambda Functions\nitems.sort(key=lambda item: item[1])\nprint(items)\n\n\n# Map Function\n\n# prices = []\n# for item in items:\n# prices.append(item[1])\n\nprices = map(lambda item: item[1], items)\n\nfor item in prices:\n print(item)\n\n\n# Filter Function\nfiltered = list(filter(lambda item: item[1] >= 10, items))\nprint(filtered)\n\n\n# List Comprehensions\nprices = [item[1] for item in items] # instead of map fun\n\nfiltered = [item for item in items if item[1] >= 10] # instead of filter fun\n\n\n# Zip Function\nlist1 = [1, 2, 3]\nlist2 = [10, 20, 30]\n\nprint(list(zip(\"abc\", list1, list2)))\n\n\n# Stacks\nbrowsing_session = []\n\nbrowsing_session.append(11)\nbrowsing_session.append(12)\nbrowsing_session.append(13)\n\nprint(browsing_session)\nlast = browsing_session.pop()\nprint(last)\nprint(browsing_session)\nprint(\"redirect:\", browsing_session[-1])\n\nif not browsing_session:\n browsing_session[-1]\n\n\n# Queues\n\nqueue = deque([])\nqueue.append(1)\nqueue.append(2)\nqueue.append(3)\nqueue.popleft()\n\nprint(queue)\n\nif not queue:\n print(\"empty\")\n\n\n# Tuples\npoint = (1, 2)\npoint = 1, 2\npoint = 1,\npoint = () # empty tuple\npoint = (1, 2) + (3, 4)\npoint = (1, 2) * 3\npoint = tuple([1, 2])\npoint = tuple(\"Hello World\")\npoint = (1, 2, 3)\n\nprint(type(point))\nprint(point)\nprint(point[0:2])\nx, y, z = point\nif 1 in point:\n print(\"exists\")\n\n\n# Swapping Variables\nx = 10\ny = 20\n\nx, y = y, x # swapp :)\n\nprint(\"x\", x)\nprint(\"y\", y)\n\n\n# Arrays\n\n# python 3 typecode\nnumbers = array(\"i\", [1, 2, 3]) # 'i' singed short\nprint(numbers)\n\n\n# Sets\nnumbers = [1, 1, 2, 3, 4]\nuniques = set(numbers)\nsecond = {1, 6}\nsecond.add(5)\nsecond.remove(5)\n\nprint(len(second))\nprint(uniques)\n\nfirst = set(numbers)\n\nprint(first | second) # union\nprint(first & second)\nprint(first - second)\nprint(first ^ second)\n\nif 1 in first:\n print(\"yes\")\n\n\n# Dictionaries\npoint = {\"x\": 1, \"y\": 2}\npoint = dict(x=1, y=2) # better\npoint[\"x\"] = 10\npoint[\"z\"] = 20\ndel point[\"y\"]\n\nprint(point)\n\nif \"a\" in point:\n print(point[\"a\"])\n\nprint(point.get(\"a\", 0))\n\nfor key in point:\n print(key, point[key])\n\n\n# Dictionary Comprehensions\nvalues = []\nfor x in range(5):\n values.append(x * 2)\n\n# short version\nvalues = [x * 2 for x in range(5)] # list\nvalues = {x * 2 for x in range(5)} # set\nvalues = {x: x * 2 for x in range(5)} # dict\n\nprint(values)\n\n\n# Generator Expressions\nvalues = (x * 2 for x in range(1000000))\nprint(\"gen:\", getsizeof(values))\nvalues = [x * 2 for x in range(1000000)]\nprint(\"list:\", getsizeof(values))\n\n# for x in values:\n# print(x)\n\n\n# Unpacking Operator\nnumbers = [1, 2, 3]\nprint(*numbers)\n\nvalues = [*range(5), *\"Hello\"]\nprint(values)\n\nfirst = {\"x\": 1}\nsecond = {\"x\": 10, \"y\": 2}\ncombined = {**first, **second, \"z\": 1}\nprint(combined)\n","sub_path":"DataStructures/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"493177068","text":"import sqlite3\n\nfrom django.urls import reverse\nfrom django.shortcuts import redirect, render\nfrom ..connection import Connection\nfrom breadapp.models import Bread, Ingredient, BreadIngredient, model_factory\n\ndef bread_details(request, bread_id):\n if request.method == \"GET\":\n with sqlite3.connect(Connection.db_path) as conn:\n conn.row_factory = create_bread\n db_cursor = conn.cursor()\n db_cursor.execute(\"\"\"\n select b.id,\n b.name,\n b.region,\n i.id ing_id,\n i.name ing_name,\n i.local_source,\n bi.amount,\n bi.id relationship_id\n from breadapp_bread b \n left join breadapp_breadingredient bi on bi.bread_id = b.id\n left join breadapp_ingredient i on bi.ingredient_id = i.id\n where b.id = ?\n \n \"\"\", (bread_id,))\n\n breads = db_cursor.fetchall()\n bread_dict = {}\n for (bread, ingredient) in breads :\n if bread.id not in bread_dict:\n bread_dict[bread.id] = bread\n bread_dict[bread.id].all_ingredients.append(ingredient)\n else:\n bread_dict[bread_id].all_ingredients.append(ingredient)\n \n\n template = \"bread/bread_details.html\"\n bread_list = list(bread_dict.values())\n context = {\n 'bread': bread_list[0]\n }\n return render(request, template, context)\n if request.method == \"POST\":\n form_data = request.POST\n if(\n \"actual_method\" in form_data and form_data['actual_method'] == \"DELETE\"\n ):\n with sqlite3.connect(Connection.db_path) as conn:\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n DELETE FROM breadapp_breadingredient\n where id = ?\n \"\"\", (bread_id,))\n\n\n return(redirect(reverse('breadapp:breads')))\n if request.method == \"POST\":\n form_data = request.POST\n if(\n \"actual_method\" in form_data and form_data['actual_method'] == \"PUT\"\n ):\n with sqlite3.connect(Connection.db_path) as conn:\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n UPDATE breadapp_bread \n set region = ?\n where id = ?\n \"\"\", (form_data[\"region\"], bread_id))\n\n\n return(redirect(reverse('breadapp:breads')))\n\n\n\n\n\ndef create_bread(cursor, row):\n row = sqlite3.Row(cursor, row)\n\n bread = Bread()\n bread.name = row[\"name\"]\n bread.id = row[\"id\"]\n bread.region = row['region']\n\n bread.all_ingredients = list()\n\n ingredient = Ingredient()\n ingredient.id = row['ing_id']\n ingredient.name = row['ing_name']\n ingredient.local_source = row['local_source']\n ingredient.amount = row[\"amount\"]\n ingredient.relationship_id = row[\"relationship_id\"]\n\n \n\n \n \n return (bread,ingredient,)\n\n","sub_path":"breadapp/views/bread/bread_details.py","file_name":"bread_details.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"75233864","text":"# region Setup\nfrom re import sub\nfrom bilisession import BiliSession, Submission\nfrom providers import DownloadResult\nfrom providers import youtube\nfrom utils import prepare_temp, report_progress, save_cookies, load_cookies, sanitize_string, \\\n truncate_string, local_args as largs\nfrom utils import global_args\nimport sys, time, urllib.parse\nfrom loguru import logger\n\nsess = BiliSession()\nlogger.add(\"err.log\", encoding=\"utf-8\", enqueue=True)\n\n\n\ndef download_sources(arg) -> DownloadResult:\n resource = arg['resource'] \n opts = arg['opts'] \n if arg['desc_fmt'] != '':\n desc = arg['desc_fmt']\n try:\n opts = urllib.parse.parse_qs(opts)\n youtube.update_config({k: v[-1] for k, v in opts.items()}) # k: 'format' v: ['best']\n except:\n opts = 'INVALID OPTIONS'\n\n '''Passing options'''\n # logger.info('Fectching source video')\n # logger.info(' - Type: %s - %s' % (provider.__name__,provider.__desc__))\n # logger.info(' - URI : %s' % resource)\n for k, v in largs.items(): logger.info(' - %s : %s' % (v[0], arg[k]))\n '''Downloading source'''\n try:\n \n return youtube.download_video(resource, desc)\n except Exception as e:\n logger.error('Cannot download specified resource - %s' % e)\n return\n\n\n\ndef upload_sources(sources: DownloadResult, arg, report=report_progress):\n '''To perform a indivudial task\n\n If multiple videos are given by the provider,the submission will be in multi-parts (P)\n Otherwise,only the given video is uploaded as a single part subject\n\n Args:\n\n provider - one of the modules of `providers`\n arg - task arguments dictionary \n * resource - resoucre URI (must have)\n - opts - options for uploader in query string e.g. format=best \n - See `utils.local_args` for more arguments,along with thier details\n report : A function takes (current,max) to show progress of the upload\n '''\n submission = Submission()\n if not sources: return None, True\n logger.info('Processing total of %s sources' % len(sources.results))\n\n def sanitize(title, desc, **kw):\n blocks = {'title': title, 'desc': desc, **kw}\n return sanitize_string(truncate_string(arg['title_fmt'] % blocks, 80)), sanitize_string(\n truncate_string(arg['desc_fmt'] % blocks, 2000))\n\n for source in sources.results:\n '''If one or multipule sources'''\n title, description = sanitize(source.title, source.description)\n logger.info('Uploading: %s' % title)\n '''Summary trimming'''\n basename, size, endpoint, config, state, pic = [None] * 6\n while True:\n try:\n basename, size, endpoint, config, state = sess.UploadVideo(source.video_path, report=report)\n pic = sess.UploadCover(source.cover_path)['data']['url'] if source.cover_path else ''\n break\n except Exception as e:\n logger.warning('Failed to upload (%s) - skipping' % e)\n break\n if not endpoint:\n continue\n logger.info('Upload complete')\n with Submission() as video:\n '''Creatating a video per submission'''\n video.cover_url = pic\n video.video_endpoint = endpoint\n video.biz_id = config['biz_id']\n '''Sources identifiers'''\n video.copyright = Submission.COPYRIGHT_REUPLOAD if not source.original else Submission.COPYRIGHT_SELF_MADE\n video.source = sources.soruce\n video.thread = arg['thread_id']\n video.tags = arg['tags'].split(',')\n video.description = source.description\n video.title = title\n '''Use the last given thread,tags,cover & description per multiple uploads'''\n submission.copyright = video.copyright or submission.copyright\n submission.thread = video.thread or submission.thread\n submission.tags.extend(video.tags)\n submission.videos.append(video) # to the main submission\n '''Filling submission info'''\n title, description = sanitize(sources.title, sources.description)\n submission.source = sources.soruce\n submission.title = title\n submission.description = description\n '''Upload cover images for all our submissions as well'''\n pic = sess.UploadCover(sources.cover_path)['data']['url'] if sources.cover_path else ''\n submission.cover_url = pic\n '''Finally submitting the video'''\n submit_result = sess.SubmitVideo(submission, seperate_parts=arg['seperate_parts'])\n dirty = False\n for result in submit_result['results']:\n if result['code'] == 0:\n logger.success('Upload success - BVid: %s' % result['data']['bvid'])\n else:\n logger.warning('Upload Failed: %s' % result['message'])\n dirty = True\n return submit_result, dirty\n\n\ndef setup_session(cookies: str):\n '''Setup session with cookies in query strings & setup temp root'''\n return prepare_temp() and sess.load_cookies(cookies)\n\n\n\n\ndef __tasks__(local_args):\n logger.info('Total tasks: %s' % len(local_args))\n success, failure = [], []\n for arg in local_args:\n sources = download_sources(arg) \n if arg['no_upload']:\n logger.warning('Not uploading - no_upload sepceified on this resource')\n else:\n \n result, dirty = upload_sources(sources, arg,\n report_progress if global_args['show_progress'] else lambda current,\n max: None)\n if not dirty:\n success.append((arg, result))\n else:\n failure.append((arg, None))\n if not failure: return result['results'][0]['data']['bvid']\n logger.warning('Dirty flag set,not all tasks are done properly')\n return 'upload failed'\n\n\ndef start(a):\n '''Parsing args'''\n save_cookies(global_args['cookies'])\n '''Saving / Loading cookies'''\n if not setup_session(load_cookies()):\n logger.error('Unable to set working directory,quitting')\n sys.exit(2)\n else:\n self_info = sess.Self\n if not 'uname' in self_info['data']:\n logger.error('Invalid cookies: %s' % self_info['message'])\n sys.exit(2)\n logger.warning('Bilibili-toolman - operating as %s' % self_info['data']['uname'])\n s = __tasks__(a)\n return s\n\n\n\n","sub_path":"app/bili.py","file_name":"bili.py","file_ext":"py","file_size_in_byte":6520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490978833","text":"from imgurpython import ImgurClient\r\nimport imgurpython\r\nfrom creds import *\r\nimport urllib.request\r\nimport re\r\nimport os\r\nimport time\r\n\r\ndef saveImage(link, author, sub, name, ext, direct):\r\n folder = direct + '/' + sub + '/' + author + '/'\r\n if not os.path.exists(folder):\r\n os.makedirs(folder)\r\n try:\r\n urllib.request.urlretrieve(link, folder + name + ext)\r\n except urllib.error.URLError:\r\n time.sleep(20)\r\n try:\r\n urllib.request.urlretrieve(link, folder + name + ext)\r\n except:\r\n pass\r\ndef saveAlbum(album, author, sub, sub_title, direct):\r\n counter = 0\r\n client = ImgurClient(Im_client_id, Im_client_secret) #Imgur client\r\n try:\r\n album_data = client.get_album(album) #Whole album\r\n folderName = album_data.title #album title\r\n\r\n if not folderName:\r\n folderName = sub_title + \" - \" + str(album)\r\n folderName = formatName(folderName)\r\n else:\r\n folderName = folderName.replace(' ', '_')\r\n folderName = formatName(folderName)\r\n print(album)\r\n images = client.get_album_images(album)\r\n print(album)\r\n\r\n for image in images:\r\n #print(str(image.link))\r\n #print(str(image.description))\r\n print(image.type)\r\n folder = direct + '/' + sub + '/' + author + '/' + str(folderName) + '/'\r\n #folder = re.sub('[?/|\\:<>*\"]', '', folder)\r\n\r\n if not os.path.exists(folder):\r\n os.makedirs(folder)\r\n\r\n writeDescription(image.description, image.id, folder, counter)\r\n\r\n urllib.request.urlretrieve(image.link, folder + \"(\" + str(counter) + \") \" + str(image.id) + str(image.type).replace('image/','.'))\r\n\r\n counter = counter + 1\r\n except imgurpython.helpers.error.ImgurClientError:\r\n with open(direct + '/error.txt', 'a') as logFile:\r\n logFile.write('ImgurClientError: ' + album + '\\n')\r\n logFile.close()\r\n\r\ndef writeDescription(description, imageId, folder, counter):\r\n name = folder + \"(\" + str(counter) + \") \" + imageId + '.txt'\r\n #print(name)\r\n file = open(name, 'w+')\r\n file.write('%s\\n' % description)\r\n\r\ndef formatName(title):\r\n title = re.sub('[?/|\\\\\\:<>*\"]', '', title)\r\n if len(title) > 211:\r\n title = title[:210]\r\n return title\r\n","sub_path":"ImgurDownloader2.py","file_name":"ImgurDownloader2.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"148120024","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2014, imageio contributors\n#\n# imageio is distributed under the terms of the (new) BSD License.\n# The full license can be found in 'license.txt'.\n\n# styletest: skip\n\n\"\"\"\n\nBefore release:\n\n * Run test suite on pypy (with numpy)\n * Run test suite on Windows 32\n * Run test suite on Windows 64\n * Run test suite on OS X\n * Write release notes\n * Check if docs are still good\n * Maybe test pypi page via \"python setup.py register -r test\"\n\nRelease:\n\n * Increase __version__\n * git tag the release\n * Upload to Pypi:\n * python setup.py register\n * python setup.py sdist upload\n * Update, build and upload conda package\n\nAfter release:\n\n * Set __version__ to dev\n * Announce\n\n\"\"\"\n\nimport os\nimport sys\ntry:\n from setuptools import setup # Supports wheels\nexcept ImportError:\n from distutils.core import setup # Supports anything else\n\nname = 'imageio'\ndescription = 'Library for reading and writing a wide range of image formats.'\n\n\n# Get version and docstring\n__version__ = None\n__doc__ = ''\ndocStatus = 0 # Not started, in progress, done\ninitFile = os.path.join(os.path.dirname(__file__), 'imageio', '__init__.py')\nfor line in open(initFile).readlines():\n if (line.startswith('__version__')):\n exec(line.strip())\n elif line.startswith('\"\"\"'):\n if docStatus == 0:\n docStatus = 1\n line = line.lstrip('\"')\n elif docStatus == 1:\n docStatus = 2\n if docStatus == 1:\n __doc__ += line\n\n# Template for long description. __doc__ gets inserted here\nlong_description = \"\"\"\n.. image:: https://travis-ci.org/imageio/imageio.svg?branch=master\n :target: https://travis-ci.org/imageio/imageio'\n\n.. image:: https://coveralls.io/repos/imageio/imageio/badge.png?branch=master\n :target: https://coveralls.io/r/imageio/imageio?branch=master\n\n__doc__\n\nRelease notes: http://imageio.readthedocs.org/en/latest/releasenotes.html\n\nExample:\n\n.. code-block:: python:\n \n >>> import imageio\n >>> im = imageio.imread('astronaut.png')\n >>> im.shape # im is a numpy array\n (512, 512, 3)\n >>> imageio.imsave('astronaut-gray.jpg', im[:, :, 0])\n\nSee the `user API `_\nor `examples `_\nfor more information.\n\"\"\"\n\nsetup(\n name = name,\n version = __version__,\n author = 'imageio contributors',\n author_email = 'almar.klein@gmail.com',\n license = '(new) BSD',\n \n url = 'http://imageio.github.io/',\n download_url = 'http://pypi.python.org/pypi/imageio', \n keywords = \"image imread imsave io animation volume FreeImage ffmpeg\",\n description = description,\n long_description = long_description.replace('__doc__', __doc__),\n \n platforms = 'any',\n provides = ['imageio'],\n requires = ['numpy'],\n \n packages = ['imageio', 'imageio.core', 'imageio.plugins'],\n package_dir = {'imageio': 'imageio'}, \n \n classifiers = [\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Education',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n ],\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"46708469","text":"\"\"\"\n\"\"\"\nimport numpy as np\nimport os\nimport warnings\n\nTASSO = \"/Users/aphearin/work/DATA/diffmah_data\"\nBEBOP = \"/lcrc/project/halotools/diffmah_data/PUBLISHED_DATA\"\n\n\ndef load_tng_data(data_drn=BEBOP):\n tng_t = np.load(os.path.join(data_drn, \"tng_cosmic_time.npy\"))\n fn = os.path.join(data_drn, \"tng_diffmah.npy\")\n _halos = np.load(fn)\n halo_ids = np.arange(len(_halos[\"mpeak\"])).astype(\"i8\")\n log_mahs = np.maximum.accumulate(_halos[\"mpeakh\"], axis=1)\n log_mah_fit_min = 10.0\n return halo_ids, log_mahs, tng_t, log_mah_fit_min\n\n\ndef load_bolshoi_data(gal_type, data_drn=BEBOP):\n basename = \"bpl_diffmah_{}.npy\".format(gal_type)\n fn = os.path.join(data_drn, basename)\n _halos = np.load(fn)\n halo_ids = _halos[\"halo_id\"]\n\n _mah = np.maximum.accumulate(_halos[\"mpeak_history_main_prog\"], axis=1)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_mahs = np.where(_mah == 0, 0, np.log10(_mah))\n\n bpl_t = np.load(os.path.join(data_drn, \"bpl_cosmic_time.npy\"))\n log_mah_fit_min = 10.0\n return halo_ids, log_mahs, bpl_t, log_mah_fit_min\n\n\ndef load_mdpl2_data(gal_type, data_drn=BEBOP):\n basename = \"mdpl2_diffmah_{}.npy\".format(gal_type)\n fn = os.path.join(data_drn, basename)\n _halos = np.load(fn)\n halo_ids = _halos[\"halo_id\"]\n\n _mah = np.maximum.accumulate(_halos[\"mpeak_history_main_prog\"], axis=1)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n log_mahs = np.where(_mah == 0, 0, np.log10(_mah))\n\n mdpl2_t = np.loadtxt(os.path.join(data_drn, \"mdpl2_cosmic_time.txt\"))\n log_mah_fit_min = 11.25\n return halo_ids, log_mahs, mdpl2_t, log_mah_fit_min\n","sub_path":"scripts/load_mah_data.py","file_name":"load_mah_data.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"538443171","text":"# -*- coding: utf-8 -*-\nimport os\n\nfrom flask import Flask, render_template, request, Markup, url_for, send_from_directory\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\n\nfrom flask_ckeditor import CKEditor, CKEditorField\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\napp = Flask(__name__)\napp.config['CKEDITOR_SERVE_LOCAL'] = True\napp.config['CKEDITOR_HEIGHT'] = 400\napp.config['CKEDITOR_FILE_UPLOADER'] = 'upload'\napp.config['UPLOADED_PATH'] = basedir + '/uploads'\n\napp.secret_key = 'secret string'\n\nckeditor = CKEditor(app)\n\nclass PostForm(FlaskForm):\n\ttitle = StringField('Title')\n\tbody = CKEditorField('Body', validators=[DataRequired()])\n\tsubmit = SubmitField()\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n\tform = PostForm()\n\tif form.validate_on_submit():\n\t\ttitle = form.title.data\n\t\tbody = form.body.data\n\t\t# You may need to store the data in database here\n\t\treturn render_template('post.html', title=title, body=body)\n\treturn render_template('index.html', form=form)\n\n\n@app.route('/files/')\ndef files(filename):\n\tpath = app.config['UPLOADED_PATH']\n\treturn send_from_directory(path, filename)\n\n\n@app.route('/upload', methods=['POST'])\n@ckeditor.uploader\ndef upload():\n\tf = request.files.get('upload')\n\tf.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))\n\turl = url_for('files', filename=f.filename)\n\treturn url\n\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n","sub_path":"examples/image-upload/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"196368366","text":"# https://www.codechef.com/problems/CHN15A\n\n\nclass Input:\n @classmethod\n def integer_array(cls):\n return list(map(int, input().split()))\n\n\ndef solve():\n for _ in range(int(input())):\n n, k = Input.integer_array()\n count = 0\n for item in Input.integer_array():\n if (item + k) % 7 == 0:\n count += 1\n print(count)\n\n\nsolve()\n","sub_path":"src/arrays/mutated-minions.py","file_name":"mutated-minions.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"335397669","text":"\n#%% \nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \n# %%\n\ndata = [[2,4],[6,1],[1,8],[6,3],[3,6],[7,5],[6,6],[7,9],[8,9]]\nX = np.array(data)\n\n#%%\nfrom sklearn.cluster import AgglomerativeClustering\n\nfor i, linkage in enumerate(('single','complete')):\n clustering = AgglomerativeClustering(linkage = linkage, n_clusters=3)\n\n y_pred = clustering.fit_predict(X)\n plt.figure(i+1,figsize=(5,5))\n plt.title(linkage + \" cluster : 4\")\n plt.scatter(X[:,0],X[:,1],s=30,c=y_pred,cmap='tab20')\nplt.show()\n\n# %%\n#for i, linkage in enumerate(('single','complete','average','ward')):\nfor i, linkage in enumerate(('single','complete')):\n\n for j in range(2,5):\n clustering = AgglomerativeClustering(linkage = linkage, n_clusters=j)\n\n y_pred = clustering.fit_predict(X)\n plt.figure(i*3+(j-1),figsize=(5,5))\n plt.title(linkage + \"distance cluster number: \" + str(j))\n plt.scatter(X[:,0],X[:,1],s=30,c=y_pred,cmap='tab20')\nplt.show()\n\n\n# %%\n\n# %%\nfrom sklearn.cluster import Birch\nbrc = Birch(threshold=3, n_clusters=None , branching_factor=3)\ny_pred = brc.fit_predict(X)\nplt.figure(figsize=(5,5))\nplt.title(\"birch threshold=3 \")\nplt.scatter(X[:,0],X[:,1],s=60,c=y_pred,cmap='tab20')\nplt.show()\n\n\n# %%\nfrom scipy.spatial import distance\ndata = [[2,4],[6,1],[1,8],[6,3],[3,6],[7,5],[6,6],[7,9],[8,9]]\nX = np.array(data)\ndistList =[]\nfor i in range(len(X)):\n for j in range(i):\n dst = distance.euclidean(X[i],X[j])\n print(\"value {}:{} - X {}, X1{} - dst {}\".format(i,j,X[i],X[j],dst))\n distList.append( [X[i],X[j],dst] )\n\nprint(distList) \ndistList.sort()\n# %%\nsorted = sorted(distList, key=lambda x: x[2])\nfor item in sorted:\n print(item)\n\n# %%\n\nfrom sklearn.cluster import DBSCAN\nmodel = DBSCAN(min_samples=2,eps=np.sqrt(5))\n\ny_pred = model.fit_predict(X)\n\nplt.figure(1,figsize=(5,5))\nplt.scatter(X[:,0],X[:,1],s=30,c=y_pred,cmap='tab20')\n\n# %%\n","sub_path":"data mining/python/homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"227485293","text":"#!/usr/bin/python3\n# -*- coding: ascii -*-\nfrom matplotlib import pyplot as plt\nimport argparse\nimport cv2\nimport numpy as np\n\nimage = cv2.imread(\"soru2-fingerprint.tif\")\n\nkernel = np.ones((5,5),np.float32)/35\ndst = cv2.filter2D(image,-1,kernel,borderType=cv2.BORDER_CONSTANT)\n\ncv2.imshow(\"linearfilter\", dst)\nblurred1 = cv2.medianBlur(image, 3)\nblurred2 = cv2.medianBlur(image, 5)\nblurred3 = cv2.medianBlur(image, 7)\ncv2.imwrite(\"soru2-linearfiler.png\",dst)\ncv2.imwrite(\"soru2-blurredWith3.png\",blurred1)\ncv2.imwrite(\"soru2-blurredWith5.png\",blurred2)\ncv2.imwrite(\"soru2-blurredWith7.png\",blurred3)\n\n","sub_path":"question2.py","file_name":"question2.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"3922372","text":"\"\"\"\nCreated on Thu Oct 06 11:00:00 2016\n\n@author: Fernando Suarez\n\n\"\"\"\n\nimport sys\nsys.path.insert(0, '../../libreria/')\nimport libreria_fdo as fs\nimport pandas as pd\nimport numpy as np\nimport math as math\n\n\ndef get_inflation(start_date, end_date):\n '''\n Retorna el retorno entre dos fechas para una moneda, dado el id del fx.\n '''\n path = \"..\\\\risk_library\\\\querys_risk\\\\clf.sql\"\n query_start = fs.read_file(path=path).replace(\"autodate\", start_date)\n clf_start = fs.get_val_sql_user(server=\"Puyehue\",\n database=\"MesaInversiones\",\n username=\"usrConsultaComercial\",\n password=\"Comercial1w\",\n query=query_start)\n query_end = fs.read_file(path=path).replace(\"autodate\", end_date)\n clf_end = fs.get_val_sql_user(server=\"Puyehue\",\n database=\"MesaInversiones\",\n username=\"usrConsultaComercial\",\n password=\"Comercial1w\",\n query=query_end)\n if fs.convert_string_to_date(end_date).weekday() != 0:\n inflation = ((clf_end/clf_start)-1) * 365\n else:\n inflation = (((clf_end/clf_start)-1) * 365) / 3\n return inflation\n\n\ndef get_historical_dataset(data_start_date, data_end_date):\n '''\n Entrega un dataframe con toda la informacion historica de los indicesc, cada columna es un indice.\n '''\n # obtenemos las querys para indices_estatica e indices_dinamica\n indices_serie_query_path = \"..\\\\risk_library\\\\querys_risk\\\\indices_dinamica.sql\"\n indices_query_path = \"..\\\\risk_library\\\\querys_risk\\\\indices_estatica.sql\"\n indices_serie_query = fs.read_file(path=indices_serie_query_path)\n indices_serie_query = indices_serie_query.replace(\"AUTODATE1\", data_start_date).replace(\"AUTODATE2\", data_end_date)\n indices_query = fs.read_file(path=indices_query_path)\n # Descargamos ambas tablas, la dinamica para las fechas parametrizadas\n indices_serie = fs.get_frame_sql_user(server=\"Puyehue\",\n database=\"MesaInversiones\",\n username=\"usrConsultaComercial\",\n password=\"Comercial1w\",\n query=indices_serie_query)\n indices_serie.set_index([\"fecha\", \"index_id\"], inplace=True)\n indices = fs.get_frame_sql_user(server=\"Puyehue\",\n database=\"MesaInversiones\",\n username=\"usrConsultaComercial\",\n password=\"Comercial1w\",\n query=indices_query)\n vectores = []\n\n # Por cada indice indice obtenemos su serie y calculamos su vector de retornos\n for index_id in indices[\"index_id\"]:\n serie = indices_serie.iloc[indices_serie.index.get_level_values(\"index_id\") == index_id]\n serie.columns = [index_id]\n serie = serie.reset_index().set_index([\"fecha\"]).drop(\"index_id\", 1).pct_change().fillna(0).replace([np.inf, -np.inf], 0.0)[1:][::-1]\n vectores.append(serie)\n # Agregamos un indice con retorno 0 constante (CLPCLP)\n vectores.insert(0, pd.DataFrame(0.0, index = vectores[0].index, columns=[0]))\n dataset = pd.concat(vectores, axis=1)\n return dataset\n\n\ndef get_ewma_cov_matrix(data, landa=1):\n '''\n Funcion para calcular la matriz de varianza-covarianza con proceso EWMA. Recibe un dataframe\n en que cada columna es una serie de retornos. Es importante que las series no tengan NaN.\n '''\n # Sacamos el promedio de cada serie y normalizamos los datos\n #print(data)\n avg = data.mean(axis=0)\n data_mwb = data - avg\n #print(data_mwb)\n # Sacamos el vector de landas dandole mas peso a los primeros elementos(datos mas nuevos)\n powers = np.arange(len(data_mwb))\n landavect = np.empty(len(data_mwb))\n landavect.fill(landa)\n landavect = np.power(landavect, powers)\n\n # Multiplicamos el vector por la matriz de datos normalizada, el vector landa tambien se normaliza con la raiz\n landavectSQRT = np.sqrt(landavect)\n \n data_tilde = data_mwb.T\n data_tilde = data_tilde * landavectSQRT\n data_tilde = data_tilde.T\n # Multiplicamos la suma de todos los landas con la multiplicacion de la matriz compuesta con ella misma\n sumlanda = np.sum(landavect)\n cov_ewma = (1/(sumlanda-1)) * (data_tilde.T.dot(data_tilde))\n\n\n # Para obtener la covarianza/varianza de dos/un indices\n # print(cov_ewma[73].loc[168])\n # para obtener la matriz descorrelacionada\n # cov_ewma = pd.DataFrame(np.diag(np.diag(cov_ewma)),index = cov_ewma.index, columns = cov_ewma.columns)\n \n return cov_ewma\n\n\ndef get_portfolio(fund_date, fund_id, inflation):\n '''\n Retorna la cartera de un fondo junto con sus posiciones al dia de ayer en un dataframe.\n '''\n path = \"..\\\\risk_library\\\\querys_risk\\\\map_master.sql\"\n query_portfolio = fs.read_file(path=path).replace(\"AUTODATE\", fund_date).replace(\"AUTOFUND\", fund_id)\n full_portfolio = fs.get_frame_sql_user(server=\"Puyehue\",\n database=\"MesaInversiones\",\n username=\"usrConsultaComercial\",\n password=\"Comercial1w\",\n query=query_portfolio)\n # Agregamos la inflacion a las tasa de los bonos reajustables\n for i, instrument in full_portfolio.iterrows():\n if instrument[\"moneda\"] == \"UF\":\n instrument[\"tasa\"] = instrument[\"tasa\"] + inflation\n full_portfolio.loc[i] = instrument\n \n #if fund_id == \"MACRO 1.5\":\n # full_portfolio.loc[19, \"monto\"] = 1500000000 \n \n return full_portfolio\n\n\ndef get_portfolio_bmk(benchmark_date, benchmark_id):\n '''\n Retorna la cartera de todos los benchmarks junto con sus posiciones al dia de ayer en un dataframe.\n '''\n path = \"..\\\\risk_library\\\\querys_risk\\\\map_bmk_master.sql\"\n query_portfolio = fs.read_file(path=path).replace(\"AUTODATE\", benchmark_date).replace(\"AUTOBMK\", str(benchmark_id))\n full_portfolio_bmk = fs.get_frame_sql_user(server=\"Puyehue\",\n database=\"MesaInversiones\",\n username=\"usrConsultaComercial\",\n password=\"Comercial1w\",\n query=query_portfolio)\n return full_portfolio_bmk\n\n\ndef get_funds():\n '''\n Retorna los fondos con su informacion basica en un dataframe.\n '''\n path = \"..\\\\risk_library\\\\querys_risk\\\\fondos.sql\"\n query_funds = fs.read_file(path=path)\n funds = fs.get_frame_sql_user(server=\"Puyehue\",\n database=\"MesaInversiones\",\n username=\"usrConsultaComercial\",\n password=\"Comercial1w\",\n query=query_funds)\n return funds\n\n\ndef get_full_portfolio_metrics(matrix, funds, fund_date, benchmark_date, inflation):\n '''\n En base a la cartera de los fondos y la matriz de varianza-covarianza, obtiene un dataframe con todos los portfolios\n con sus metricas de reisgo calculadas.\n '''\n portfolios = []\n # Para cada fondo obtenemos su portafolio activo con sus respectivas metricas de riesgo\n for i, fund in funds.iterrows():\n # Sacamos la informacion basica del fondo\n fund_id = fund[\"codigo_fdo\"]\n benchmark_id = fund[\"benchmark_id\"]\n alpha_seeker = fund[\"alpha_seeker\"]\n # Portfolio del fondo sin metricas de riesgo\n fund_portfolio = get_portfolio(fund_date=fund_date,\n fund_id=fund_id,\n inflation=inflation)\n # Portfolio del benchmark sin metricas de riesgo\n benchmark_portfolio = get_portfolio_bmk(benchmark_date=benchmark_date,\n benchmark_id=benchmark_id)\n # Portfolio activo con metricas de riesgo\n portfolio = get_portfolio_metrics(fund_portfolio=fund_portfolio,\n benchmark_portfolio=benchmark_portfolio,\n fund_id=fund_id,\n matrix=matrix,\n benchmark_id=benchmark_id,\n alpha_seeker=alpha_seeker)\n portfolios.append(portfolio)\n portfolios = pd.concat(portfolios, ignore_index=True)\n return portfolios\n\n\ndef get_portfolio_metrics(fund_portfolio, benchmark_portfolio, fund_id, matrix, benchmark_id, alpha_seeker):\n '''\n En base a la cartera de cada fondo, su benchmark y la matriz de varianza-covarianza, \n obtiene un dataframe con el portfolio activo junto sus metricas de riesgo calculadas.\n '''\n # Obtenemos el vector con los montos del portfolio agrupados por indice\n\n stock_pindex = fund_portfolio.groupby(by=\"Index_Id\")[\"monto\"].sum().reset_index().set_index([\"Index_Id\"]).reindex(index=matrix.index).fillna(0)\n \n # Transformamos el vector a uno de weights agrupado por indices\n w_pindex = stock_pindex/np.sum(stock_pindex)\n w_pindex.columns = [\"weight_index\"]\n\n # if fund_id=='MACRO 1.5':\n\n # fs.print_full(fund_id)\n # fs.print_full(fund_portfolio)\n # fs.print_full(w_pindex)\n # exit()\n\n # En caso de que tenga benchmark, obtenemos el vector w_b con la posicion del benchmark, tambien agrupado por indices\n if alpha_seeker == 1:\n w_bindex = benchmark_portfolio.groupby(by=\"Index_Id\")[\"weight\"].sum().reset_index().set_index([\"Index_Id\"]).reindex(index=matrix.index).fillna(0)\n # En caso contrario el vector de weights es un vector de ceros\n else:\n w_bindex = pd.DataFrame(index=w_pindex.index, columns=[\"weight\"]).fillna(0)\n w_bindex.columns = [\"weight_index\"]\n # Obtenemos el vector de weight activos\n w_aindex = w_pindex - w_bindex\n \n # Mutiplicamos los weights por la matriz de varianza covarianza para obtener los mcr no normalizados\n w_marginal = matrix.dot(w_aindex)\n\n # Multiplicamos de nuevo por los weights para obtener la volatilidad o tracking error\n sigma = np.sqrt(w_aindex.T.dot(w_marginal))[\"weight_index\"][0]\n\n # Ahora recomputamos el portfolio desagrupado para calcular las risk metrics\n portfolio = fund_portfolio.reset_index().set_index([\"Index_Id\"]).drop(\"index\", 1)\n\n # Calculamos la contribucion marginal al riesgo normalizando por la volatilidad y concatenamos al portfolio\n mcr = ((w_marginal)*math.sqrt(360))/sigma\n mcr.columns = [\"mcr\"]\n \n\n portfolio = pd.merge(portfolio, mcr, how=\"left\", left_index=True, right_index=True)\n portfolio = portfolio.reset_index().set_index([\"codigo_ins\"])\n \n # Concatenamos weight a cada instrumento y renombramos la columna del indice\n portfolio[\"weight\"] = portfolio[\"monto\"]/np.sum(portfolio[\"monto\"])\n portfolio = portfolio.rename(columns = {\"index\": \"Index_Id\"})\n \n # Hacemos el mismo proceso para desagregar el portfolio del benchmark\n benchmark = benchmark_portfolio.reset_index().set_index([\"Index_Id\"]).drop(\"index\", 1)\n benchmark = pd.merge(benchmark, mcr, how=\"left\", left_index=True, right_index=True)\n benchmark = benchmark.reset_index().set_index([\"codigo_ins\"])\n if benchmark.index.name != \"Index_Id\":\n benchmark = benchmark.rename(columns = {\"index\": \"Index_Id\"})\n\n \n\n \n active_portfolio = pd.merge(portfolio, benchmark, how=\"outer\", left_index=True, right_index=True)\n active_portfolio[\"weight_x\"].fillna(0.0, inplace=True)\n active_portfolio[\"weight_y\"].fillna(0.0, inplace=True)\n\n # Concatenamos el active weight al portfolio\n active_portfolio[\"weight_active\"] = active_portfolio[\"weight_x\"] - active_portfolio[\"weight_y\"]\n \n # Definimos las metricas a agregar a cada instrumento\n active_portfolio[\"ctr\"] = None\n active_portfolio[\"ctd\"] = None\n active_portfolio[\"cty\"] = None\n #active_portfolio[\"index_id\"] = None\n active_portfolio = active_portfolio.reset_index()\n \n \n # Por cada instrumento vamos completando los campos que no hicieron match en el join, por convencion trabajamos en el lado del fondo\n for i, instrument in active_portfolio.iterrows():\n #Vemos si el instrumento esta en el bmk\n if np.isnan(instrument[\"mcr_x\"]):\n active_portfolio.set_value(i, \"ctr\", instrument[\"mcr_y\"]*instrument[\"weight_active\"])\n active_portfolio.set_value(i, \"tipo_instrumento_x\", instrument[\"tipo_instrumento_y\"])\n active_portfolio.set_value(i, \"moneda_x\", instrument[\"moneda_y\"])\n active_portfolio.set_value(i, \"mcr_x\", instrument[\"mcr_y\"])\n active_portfolio.set_value(i, \"duration_x\", instrument[\"duration_y\"])\n active_portfolio.set_value(i, \"riesgo_x\", instrument[\"riesgo_y\"])\n active_portfolio.set_value(i, \"sector_x\", instrument[\"sector_y\"])\n active_portfolio.set_value(i, \"tasa_x\", instrument[\"tasa_y\"])\n active_portfolio.set_value(i, \"riesgo_internacional_x\", instrument[\"riesgo_internacional_y\"])\n active_portfolio.set_value(i, \"pais_emisor_x\", instrument[\"pais_emisor_y\"])\n active_portfolio.set_value(i, \"nombre_emisor_x\", instrument[\"nombre_emisor_y\"])\n active_portfolio.set_value(i, \"Index_Id_x\", instrument[\"Index_Id_y\"])\n else:\n active_portfolio.set_value(i, \"ctr\", instrument[\"mcr_x\"]*instrument[\"weight_active\"])\n active_portfolio.set_value(i, \"ctd\", instrument[\"duration_x\"]*instrument[\"weight_x\"])\n active_portfolio.set_value(i, \"cty\", instrument[\"tasa_x\"]*instrument[\"weight_x\"])\n\n # Finalmente recalculamos sigma agregado por si hubieron inconsistencias entre los mapeos, esto puede psar por cupones de bonos\n sigma_ag = np.sum(active_portfolio[\"ctr\"])\n\n # Con el sigma nuevo podemos calcular el pcr exacto\n active_portfolio[\"pcr\"] = active_portfolio[\"ctr\"]/sigma_ag\n active_portfolio[\"codigo_fdo\"] = fund_id\n active_portfolio[\"benchmark_id\"] = benchmark_id\n\n # Ordenamos las columnas para el display\n active_portfolio = active_portfolio.rename(columns = {\"Index_Id_x\": \"Index_Id\"})\n active_portfolio = active_portfolio.reindex(columns = [\"Index_Id\", \"benchmark_id\",\"cantidad\",\n \"codigo_emi\",\"codigo_fdo\",\"codigo_ins\",\"ctd\",\"ctr\",\"duration_x\",\"duration_y\",\n \"fec_vtco\",\"fecha_x\",\"fecha_y\", \"index\", \"index_x\",\"index_y\",\"mcr_x\",\"mcr_y\",\n \"moneda_x\",\"moneda_y\",\"monto\",\"nombre_emisor_x\",\"nombre_instrumento\",\"nominal\",\n \"pais_emisor_x\",\"pcr\",\"precio\",\"riesgo_x\",\"riesgo_y\",\"sector_x\",\"tasa_x\",\"tasa_y\",\n \"tipo_instrumento_x\",\"tipo_instrumento_y\",\"weight_active\",\"weight_x\",\"weight_y\",\n \"sector_y\", \"riesgo_internacional_x\", \"riesgo_internacional_y\", \"pais_emisor_y\", \"cty\", \"tipo_ra\"])\n\n\n return active_portfolio\n\n\ndef get_historical_metrics(funds, dataset, fund_date, benchmark_date, inflation, days):\n '''\n Obtiene las metricas de riesgo agregadas en una serie de tiempo dado.\n Se deja fija la inflacion diaria porque no es una metrica dinamica\n en el analisis.\n '''\n # Definimos un dataframe para guardar los datos de las metricas historicamente\n serie = pd.DataFrame(columns=[\"Fecha\", \"Codigo_Fdo\", \"Slice\", \"Metric\"])\n k = 0\n fund_date_iter = fund_date\n benchmark_date_iter = benchmark_date\n # Para cada fecha computamos una matriz de varianza covarianza\n for j in range(days):\n print(\"days left -> \" + str(days - j))\n matrix = get_ewma_cov_matrix(data=dataset[j:], landa=0.94)\n # Para cada fondo computamos sus metricas\n for i, fund in funds.iterrows():\n fund_id = fund[\"codigo_fdo\"]\n benchmark_id = fund[\"benchmark_id\"]\n alpha_seeker = fund[\"alpha_seeker\"]\n # Portfolio del fondo sin metricas de riesgo\n print(fund_date_iter)\n fund_portfolio_iter = get_portfolio(fund_date=fund_date_iter,\n fund_id=fund_id, \n inflation=inflation)\n # Portfolio del benchmark sin metricas de riesgo\n benchmark_portfolio_iter = get_portfolio_bmk(benchmark_date=benchmark_date_iter,\n benchmark_id=benchmark_id)\n try:\n # Portfolio activo con metricas de riesgo\n portfolio_iter = get_portfolio_metrics(fund_portfolio=fund_portfolio_iter,\n benchmark_portfolio=benchmark_portfolio_iter,\n fund_id=fund_id, matrix=matrix,\n benchmark_id=benchmark_id,\n alpha_seeker=alpha_seeker)\n te_clp = np.sum(portfolio_iter[portfolio_iter[\"moneda_x\"] == \"$\"][\"ctr\"])\n te_clf = np.sum(portfolio_iter[portfolio_iter[\"moneda_x\"] == \"UF\"][\"ctr\"])\n te_usd = np.sum(portfolio_iter[portfolio_iter[\"moneda_x\"] == \"US$\"][\"ctr\"])\n te_eur = np.sum(portfolio_iter[portfolio_iter[\"moneda_x\"] == \"EU\"][\"ctr\"])\n te_mxn = np.sum(portfolio_iter[portfolio_iter[\"moneda_x\"] == \"MX\"][\"ctr\"])\n te_sol = np.sum(portfolio_iter[portfolio_iter[\"moneda_x\"] == \"SOL\"][\"ctr\"])\n te_rea = np.sum(portfolio_iter[portfolio_iter[\"moneda_x\"] == \"REA\"][\"ctr\"])\n te_chile = np.sum(portfolio_iter[portfolio_iter[\"pais_emisor_x\"] == \"CL\"][\"ctr\"])\n te_mexico = np.sum(portfolio_iter[portfolio_iter[\"pais_emisor_x\"] == \"MX\"][\"ctr\"])\n te_colombia = np.sum(portfolio_iter[portfolio_iter[\"pais_emisor_x\"] == \"CO\"][\"ctr\"])\n te_peru = np.sum(portfolio_iter[portfolio_iter[\"pais_emisor_x\"] == \"PE\"][\"ctr\"])\n te_brazil = np.sum(portfolio_iter[portfolio_iter[\"pais_emisor_x\"] == \"BR\"][\"ctr\"])\n te_other = np.sum(portfolio_iter[(portfolio_iter[\"pais_emisor_x\"] != \"CL\") & (portfolio_iter[\"pais_emisor_x\"] != \"MX\") & (portfolio_iter[\"pais_emisor_x\"] != \"CO\") & (portfolio_iter[\"pais_emisor_x\"] != \"PE\") & (portfolio_iter[\"pais_emisor_x\"] != \"BR\") ][\"ctr\"])\n dur = np.sum(portfolio_iter[\"ctd\"])\n serie.loc[k] = [fund_date_iter, fund_id, \"$\", te_clp]\n serie.loc[k + 1] = [fund_date_iter, fund_id, \"UF\", te_clf]\n serie.loc[k + 2] = [fund_date_iter, fund_id, \"US$\", te_usd]\n serie.loc[k + 3] = [fund_date_iter, fund_id, \"EU\", te_eur]\n serie.loc[k + 4] = [fund_date_iter, fund_id, \"MX\", te_mxn]\n serie.loc[k + 5] = [fund_date_iter, fund_id, \"SOL\", te_sol]\n serie.loc[k + 6] = [fund_date_iter, fund_id, \"REA\", te_rea]\n serie.loc[k + 7] = [fund_date_iter, fund_id, \"duration\", dur]\n serie.loc[k + 8] = [fund_date_iter, fund_id, \"chile\", te_chile]\n serie.loc[k + 9] = [fund_date_iter, fund_id, \"mexico\", te_mexico]\n serie.loc[k + 10] = [fund_date_iter, fund_id, \"colombia\", te_colombia]\n serie.loc[k + 11] = [fund_date_iter, fund_id, \"peru\", te_peru]\n serie.loc[k + 12] = [fund_date_iter, fund_id, \"brazil\", te_brazil]\n serie.loc[k + 13] = [fund_date_iter, fund_id, \"other\", te_other]\n k += 14\n except:\n print(\"Error para \" + fund_id + \" en \" + fund_date_iter)\n fund_date_iter = fs.get_prev_weekday(fund_date_iter)\n benchmark_date_iter = fs.get_prev_weekday(benchmark_date_iter)\n return serie","sub_path":"Proyectos/portfolio_analytics/risk_library/risk.py","file_name":"risk.py","file_ext":"py","file_size_in_byte":19898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"138747683","text":"from django import forms\nfrom django.db.models import fields\nfrom .models import McqQuestions, Topics, Tutorial\n\nclass TutorialForm(forms.ModelForm):\n class Meta:\n model = Tutorial\n fields = ['topics','title','About','Image','description','tutorials'] \n\n def __init__(self, *args, **kwargs):\n super(TutorialForm, self).__init__(*args, **kwargs)\n # self.fields['title'].widget.attrs['class'] = 'form-control'\n\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'\n\n\nclass TopicForm(forms.ModelForm):\n class Meta:\n model = Topics\n fields = ['tutorial_name','tut_image']\n \n def __init__(self, *args, **kwargs):\n super(TopicForm, self).__init__(*args, **kwargs)\n\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'\n \n\n\n\nclass McQForm(forms.ModelForm):\n class Meta:\n model = McqQuestions\n fields = ['topic','question','option1','option2','option3','correct_answer']\n\n def __init__(self, *args, **kwargs):\n super(McQForm, self).__init__(*args, **kwargs)\n\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'\n\n\n\n","sub_path":"tutorials/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"449985290","text":"import nltk\nimport random\nimport string\n#initializes all word/phrase arrays\nprepArr = [ \"Forsooth, \",\n\t\t\"I say, \",\n\t\t\"I sayeth, \",\n\t\t\"Forsooth, I say, \",\n\t\t\"Forsooth, say I, \",\n\t\t\"Forsooth, sayeth I, \",\n\t\t\"Hark, \",\n\t\t\"Harketh, \",\n\t\t\"Avast, \",\n\t\t\"Zounds, \",\n\t\t\"Perchance, \",\n\t\t\"Pray tell, \",\n\t\t\"Prithee, \",\n\t\t\"What hey, \",\n\t\t\"What ho, \",\n\t\t\"Pray, \",\n\t\t\"Surely \",\n\t\t\"Pray pardon, \",\n\t\t\"Alas, \",\n\t\t\"In short, \",\n\t\t\"My Lord, \",\n\t\t\"My Lady, \",\n\t\t\"By my faith, \",\n\t\t\"If it pleases you, \",\n\t\t\"I pray you, \",\n\t\t\"In truth, \",\n\t\t\"By my trowth, \",\n\t\t\"In sooth, \",\n\t\t\"By my word, \",\n\t\t\"S'wounds, \",\n\t\t\"Z'wounds, \",\n\t\t\"Heigh-ho, \",\n\t\t\"Ah, \",\n\t\t\"Quoth I, \",\n\t\t\"Listen, \",\n\t\t\"Listen thee, \",\n\t\t\"Hear me, \",\n\t\t\"Now hear me, \",\n\t\t\"I warrant \",\n\t\t\"Come, \",\n\t\t\"Kind sire, \",\n\t\t\"Sire, \",]\n\nprepGod = [ \"god's wounds, \",\n\t\t\"god's bodypart, \",\n \"By god, \",\n\t\t\"By the Will of godadj god, \",\n\t\t\"By the bodyadj bodypart of the godadj god, \",\n\t\t\"By godadj god's bodyadj bodypart, \",]\n\npostArr = [ \" Anon!\",\n\t\t\" Hum.\",\n\t\t\" Good sir!\",\n\t\t\" Good sire!\",\n\t\t\" Milady!\",\n\t\t\" My Liege!\",\n\t\t\" Guvnor!\"]\n\nexclamArr = [ \", verily!\",\n \", verily I say!\",\n\t\t\", verily I sayeth!\",\n\t\t\", I say!\",\n\t\t\", I sayeth!\",\n\t\t\"! Huzzah!\",\n\t\t\"! Hear Hear!\",\n\t\t\"! What-ho!\",\n\t\t\"! Ho!\",\n\t\t\"! Fie!\",\n\t\t\", indeed!\",\n \"!\"]\n\nquestArr = [\t\", I say?\",\n\t\t\", I wonder?\",\n\t\t\", wonder I?\",\n\t\t\", what say thee?\",\n\t\t\", what sayeth thee?\",\n\t\t\", what say thou?\",\n\t\t\", what sayeth thou?\",\n\t\t\", I ponder?\",\n\t\t\", I pondereth?\",\n\t\t\", pray tell?\",\n\t\t\", ho?\",\n\t\t\", do tell?\"]\n\nthankYouArr = [ \"many good thanks to you\",\n\t\t\"thankee\",\n\t\t\"kindly thanks to you\",\n\t\t\"grammercy to you\"]\n\nyouArr = [ \"thou\",\n \"thee\",\n \"ye\"]\n\nlolArr = [ \"lolleth\",\n \"lollery\"]\n\nkillPastArr = [ \"slain\",\n\t\t\"vanquished\",\n\t\t\"brung low\",\n\t\t\"conquered\",\n\t\t\"fleeced\",\n\t\t\"humbled\",\n\t\t\"subjugated\",\n\t\t\"bested\",\n\t\t\"foiled\"]\n\nkillArr = [ \"slay\",\n\t\t\"vanquish\",\n\t\t\"bring low\",\n\t\t\"conquer\",\n\t\t\"fleece\",\n\t\t\"humble\",\n\t\t\"subjugate\",\n\t\t\"best\",\n\t\t\"foil\"]\n\ngodArr = [\t \"Odin\",\n \"Bob\",\n \"Zeus\",\n \"Hera\",\n \"Thor\",\n \"Crom\",\n \"Mad-poet Navarth\",\n \"Cugel\",\n \"Wotsit\",\n \"Baron Boddisey\",\n \"Poseidon\",\n \"Saint Mary\",\n \"Pallus Athena\",\n \"Loki\",\n \"Erlik\",\n \"Shoggoth\",\n \"Omm\",\n \"Vishnu\",\n \"Azazoth\",\n \"Father Odin\",\n \"Allfather Odin\",\n \"Cthulhu\",\n \"Buddha\",\n \"Aphrodite\",\n \"Isis\",\n \"Kali\",\n \"Dionysus\",\n \"Zarathustra\",\n \"Croesus\",\n \"Hermes\",\n \"Venus\",\n \"Montezuma\",\n \"Popacatapetl\",\n \"Hephaestus\",\n \"Bubastes\",\n \"Bacchus\",\n \"Nebuchadnezzar\",\n \"Assurbanipal\",\n \"Sargon\",\n \"Xerxes\",\n \"Mulwatallish\",\n \"Labarna\",\n \"Hammurabi\",\n \"Rameses\",\n \"Minos\",\n \"Tilgath-Pileser\",\n \"Vercingetorix\",\n \"Mithradites\",\n \"Pericles\",\n \"Belasarius\",\n \"Archaemides\",\n \"Heraclius\",\n \"Imhotep\",\n \"Artemis\",\n \"Orthia\",\n \"Phoebe\",\n \"Hestia\",\n \"Eros\",\n \"Persephone\",\n \"Minerva\",\n \"Mercury\",\n \"Aesculapius\",\n \"Discordia\",\n \"Hecate\",\n \"Hespera\"]\n\ngodAdjArr = [\t \"Almighty\",\n \"Unthinkable\",\n \"Unknowable\",\n \"All-knowing\",\n \"All-seeing\",\n \"Lecherous\",\n \"Scandalous\",\n \"Merciful\",\n \"Ravaging\",\n \"Thunderous\",\n \"Wrathful\",\n \"Distant\",\n \"Vengeful\",\n \"Supreme\",\n \"Wise\",\n \"Warlike\",\n \"Jealous\",\n \"Vindictive\",\n \"Powerful\",\n \"Adulterous\",\n \"Licentious\",\n \"Crafty\",\n \"Benefical\",\n \"Virtuous\",\n \"Protective\",\n \"Prophetic\",\n \"Bloodthirsty\",\n \"Murderous\",\n \"Ruinous\",\n \"Militant\",\n \"Invisible\",\n \"Omnipotent\",\n \"Forgotten\",\n \"Enlightened\",\n \"Tempestuous\",\n \"Destructive\",\n \"Grim\"]\n\nbodyArr = [\t \"Beard\",\n \"Third Leg\",\n \"Scalp\",\n \"Eye\",\n \"Thigh\",\n \"Arm\",\n \"Sword\",\n \"Heel\",\n \"Gaze\",\n \"Tongue\",\n \"Hammer\",\n \"Toenail\",\n \"Nether Regions\",\n \"Liver\",\n \"Lights\",\n \"Spleen\",\n \"Gall\",\n \"Liver and Lights\"]\n\nbodyAdjArr = [\t \"Unknowable\",\n \"Unescapable\",\n \"Unfathomable\",\n \"Unthinkable\",\n \"Righteous\",\n \"Hairy\",\n \"Hairless\",\n \"Wandering\",\n \"Blistered\",\n \"Awe-inspiring\",\n \"Toothy\",\n \"Ravaged\",\n \"Aged\",\n \"Endless\",\n \"Wondrous\",\n \"Unavoidable\",\n \"Pestilent\",\n \"Forgotten\",\n \"Beautiful\",\n \"Fertile\",\n \"Prophetic\",\n \"Musical\",\n \"Helpful\",\n \"Virginal\",\n \"Curative\",\n \"Bleak\",\n \"Incessant\",\n \"Sagely\",\n \"Unfashionable\",\n \"Unfaltering\",\n \"Unfamiliar\",\n \"Abysmal\",\n \"Boundless\",\n \"Eternal\",\n \"Immeasurable\",\n \"Infinite\",\n \"Unending\",\n \"Soundless\",\n \"Incomprehensible\",\n \"Inexplicable\",\n \"Profound\",\n \"unintelligible\",\n \"Unbelievable\",\n \"Impenetrable\",\n \"Indecipherable\",\n \"Esoteric\",\n \"Enigmatic\",\n \"Ancient\",\n \"Venerable\",\n \"Baneful\",\n \"Contagious\",\n \"Corrupting\",\n \"Deadly\",\n \"Deleterious\",\n \"Evil\",\n \"Noxious\",\n \"Diseased\",\n \"Pernicious\",\n \"Pestiferous\",\n \"Pestilential\",\n \"Tainted\",\n \"Contaminated\",\n \"Pulchritudinous\",\n \"Odoriferous\",\n \"Misbegotten\",\n \"Sacriligious\"]\n\npersonal = [ 'town',\n 'village',\n 'home',\n\n 'lol',\n\n 'afk',\n\n 'rofl'\n\n 'water',\n\n 'balls',\n 'groin',\n\n 'gold',\n 'money',\n\n 'joke',\n\n 'idiot',\n 'fool',\n 'bastard',\n 'moron',\n 'idiots',\n 'fools',\n 'bastards',\n 'bitch',\n 'bitches',\n 'jackass',\n 'jackasses',\n 'dumbass',\n 'dumbasses',\n 'morons',\n 'fucker',\n 'fuckers',\n 'shit',\n\n 'map',\n 'maps',\n\n 'debuff',\n 'debuffed',\n\n 'food',\n\n 'man',\n 'guy',\n 'guys',\n 'men',\n 'boys',\n\n 'party',\n 'group',\n\n 'noob',\n 'newb',\n 'newbie',\n 'nub',\n 'lowbie',\n 'beginner',\n 'noobs',\n 'newbs',\n 'newbies',\n 'nubs',\n 'lowbies',\n 'beginners',\n\n 'level',\n\n 'hehe',\n 'haha',\n 'heh',\n 'hah',\n\n 'shop',\n 'store',\n 'vendor',\n 'seller',\n\n 'friend',\n 'buddy',\n 'pal',\n 'mate',\n 'friends',\n 'buddies',\n 'pals',\n 'mates',\n\n 'girl',\n 'woman',\n 'girls',\n 'women',\n\n 'child',\n 'flag',\n\n 'sick',\n 'i',\n 'hello',\n 'hey',\n 'hi',\n\n 'god',\n 'does',\n 'Does']\n\nidiotPreArr = [\t\"artless\",\n\t\t\"droning\",\n\t\t\"fawning\",\n\t\t\"warped\",\n\t\t\"paunchy\",\n\t\t\"puny\",\n\t\t\"spongy\",\n\t\t\"ruttish\",\n\t\t\"vain\",\n\t\t\"lumpish\",\n\t\t\"craven\",\n\t\t\"witless\",\n\t\t\"pustulent\",\n\t\t\"infested\",\n\t\t\"ill-bred\",\n\t\t\"blind\",\n\t\t\"scurvy\",\n \t\t\"puny\",\n\t \t\"fetid\",\n \"vile\",\n \t\t\"gibbering\",\n\t\t\"mewling\",\n\t\t\"rank\",\n \"fawning\",\n \"moonish\",\n \"brutish\",\n \"malapert\",\n \"curst\",\n \"lack-linen\",\n \"bottle-ailed\",\n \"lyingest\",\n \"embossed\",\n \"cheating\",\n \"crook-pated\",\n \"base-court\",\n \"hasty-witted\",\n \"two-faced\",\n \"pox-marked\",\n \"toad-brained\",\n \"errant\",\n \"idle-headed\",\n \"quailing\",\n \"flap-mouthed\",\n \"puking\",\n \"fly-bitten\",\n \"surly\",\n \"tottering\",\n \"villainous\",\n \"rump-fed\",\n \"bootless\",\n \"churlish\",\n \"tickle-brained\",\n \"froward\"]\n\n\nidiotArr = [ \"mongrel\",\n \"codpiece\",\n \"jackanape\",\n \"ape\",\n \"coxcomb\",\n \"harlot\",\n \"hussy\",\n \"strumpet\",\n \"cur\",\n \"clot\",\n \"fool\",\n \"barnacle\",\n \"harpy\",\n \"wench\",\n \"churl\",\n \"pleb\",\n \"taffer\",\n \"scoundrel\",\n \"scalliwag\",\n \"mooncalf\",\n \"rapscallion\",\n \"doxy\",\n \"bawd\",\n \"tosspot\",\n \"cupshot\",\n \"recreant\",\n \"fustalarion\",\n \"scullion\",\n \"rampallion\",\n \"knave\",\n \"barbermonger\",\n \"boil\",\n \"plague-sore\",\n \"carbuncle\",\n \"whoreson\",\n \"clotpole\",\n \"lout\",\n \"gudgeon\",\n \"puttock\",\n \"skainsmate\",\n \"varlet\",\n \"bladder\"]\nidiotPlur = [\t\"mongrels\",\n \"codpieces\",\n \"jackanapes\",\n \"apes\",\n \"coxcombes\",\n \"harlots\",\n \"hussies\",\n \"strumpets\",\n \"clots\",\n \"fools\",\n \"barnacles\",\n \"harpies\",\n \"wenches\",\n \"churls\",\n \"plebians\",\n \"taffers\",\n \"scoundrels\",\n \"scalliwags\",\n \"mooncalves\",\n \"rapscallions\",\n \"doxies\",\n \"bawds\",\n \"tosspots\",\n \"cupshots\",\n \"recreants\",\n \"fustalarions\",\n \"scullions\",\n \"rampallions\",\n \"knaves\",\n \"barbermongerers\",\n \"boils\",\n \"plague-sores\",\n \"carbuncles\",\n \"whoresons\",\n \"louts\"]\n\ndef medieval(s): #main function\n s = checkTags(s)\n s = nounReplacements(s)\n s = wordReplacements(s)\n x = checkPunct(s)\n return(prepend() + x)\n\ndef godAppend():\n x = random.randrange(len(prepGod)-1)\n y = prepGod[x]\n y = nltk.word_tokenize(y)\n for i in range(len(y)):\n if y[i] == 'god':\n x = random.randrange(len(godArr)-1)\n y[i] = godArr[x]\n if y[i] == 'godadj':\n x = random.randrange(len(godAdjArr)-1)\n y[i] = godAdjArr[x]\n if y[i] == 'bodypart':\n x = random.randrange(len(bodyArr)-1)\n y[i] = bodyArr[x]\n if y[i] == 'bodyadj':\n x = random.randrange(len(bodyAdjArr)-1)\n y[i] = bodyAdjArr[x]\n\n y = \"\".join([\" \"+i if not i.startswith(\"'\") and i not in string.punctuation else i for i in y]).strip() + ' '\n return y\n \ndef prepend(): #prepends the message with a phrase\n x = random.randrange(0,3)\n if x == 0:\n x = random.randrange(len(prepArr)-1)\n return prepArr[x]\n if x == 1:\n return godAppend()\n if x == 2:\n return ''\n\ndef idiotPre():\n x = random.randrange(len(idiotPreArr)-1)\n return idiotPreArr[x]\n\ndef idiot(x):\n if x == 0:\n y = random.randrange(len(idiotArr)-1)\n return idiotArr[y]\n if x == 1:\n y = random.randrange(len(idiotPlur)-1)\n return idiotPlur[y]\n\ndef nounReplacements(s): #replaces improper nouns (school, tree, plant) with a rate of .33\n pos = nltk.pos_tag(s)\n for i in range(len(s)):\n rand = rando()\n if pos[i][1] == 'NN' and personalized(s[i]) != True: #Checks if word is a noun and is not changed by particular replacement\n x = s[i]\n if(x[0].isupper()): continue #will ignore intentional capitalizations of nouns (for usernames, etc)\n if rand > 34: continue #randomizer\n if x.endswith('e'):\n s[i] = x+\"'th\"\n else:\n s[i] = x+\"eth\"\n return s\n\ndef personalized(s): #Checks if noun in question is in the personal list\n if s in personal:\n return True\n else:\n return False\n\ndef wordReplacements(tag): #Replaces phrases and single words\n #for preceeding \"it\"\n try:\n for word in range(len(tag)):\n tagged = tag[word].lower()\n if(tagged == 'it'):\n if(tag[word+1] == 'was'):\n tag[word] = \"'twas\"\n tag[word+1] = ''\n if(tag[word+1] == 'is' or tag[word+1] == \"'s\"):\n tag[word] = \"'tis\"\n tag[word+1] = ''\n if(tag[word+1] == 'would'):\n tag[word] = \"'twould\"\n tag[word+1] = ''\n if(tag[word+1] == 'will' or tag[word+1] == \"'ll\"):\n tag[word] = \"'twill\"\n tag[word+1] = ''\n if(tag[word+1] == 'were'):\n tag[word] = \"'twere\"\n tag[word+1] = ''\n if(tagged == 'teh'):\n tag[word] = 'the'\n if(tagged == 'the'):\n rand = rando()\n if(rand > 50):\n tag[word] = 'ye'\n if((tagged == 'shall' or tagged == 'will') and tag[word+1] == 'not'): #shant\n tag[word] = \"shan't\"\n tag[word+1] = ''\n if(tagged == 'over' and tag[word+1] == 'there'): #over there\n tag[word] = 'yonder'\n tag[word+1] = ''\n if(tagged == 'in' and tag[word+1] == 'the'): #in the\n tag[word] = \"i' the\"\n tag[word+1] = ''\n if((tagged == 'thank' and tag[word+1] == 'you') or (tagged == 'ty')): #thank you & ty\n x = random.randrange(len(thankYouArr)-1)\n tag[word] = thankYouArr[x]\n tag[word+1] = ''\n except IndexError: pass\n for word in range(len(tag)):\n tagged = tag[word].lower()\n if(tagged == 'god' or tagged == 'God'):\n if rando() < 80:\n y = random.randrange(len(godArr)-1)\n y = godArr[y]\n x = random.randrange(len(godAdjArr)-1)\n x = godAdjArr[x]\n tag[word] = x + ' ' + y\n else: tag[word] = 'God'\n if(tagged == 'is'): #is\n rand = rando()\n if(rand > 50):\n tag[word] = 'be'\n if(tagged == 'map'): #map\n tag[word] = 'chart'\n if(tagged == 'between'): #between\n tag[word] = 'betwixt'\n if(tagged == 'aggro'): #aggro\n tag[word] = 'wrath'\n if(tagged == 'buy'): #buy\n rand = rando()\n if(rand > 50):\n tag[word] = 'purchase'\n else: tag[word] = 'obtain'\n if(tagged == 'bought'): #bought\n rand = rando()\n if(rand > 50):\n tag[word] = 'purchased'\n else: tag[word] = 'obtained'\n if(tagged == 'debuff'): #debuff\n rand = rando()\n if(rand > 1 and rand <= 33):\n tag[word] = 'ailment'\n elif(rand > 34 and rand <= 66):\n tag[word] = 'sickness'\n else: tag[word] = 'pox'\n if(tagged == 'debuffed' or tagged == 'sick'): #debuffed / sick\n rand = rando()\n if(rand > 1 and rand <= 33):\n tag[word] = 'ailed'\n elif(rand > 34 and rand <= 66):\n tag[word] = 'sicknened'\n else: tag[word] = \"pox't\"\n if(tagged == 'sell'): #sell\n rand = rando()\n if(rand > 1 and rand <= 25):\n tag[word] = 'hawk'\n elif(rand > 25 and rand <= 50):\n tag[word] = 'pawn'\n elif(rand > 50 and rand <= 75):\n tag[word] = \"tender\"\n else: tag[word] ='purvey'\n if(tagged == 'sold'): #sold\n rand = rando()\n if(rand > 1 and rand <= 25):\n tag[word] = \"hawk'd\"\n elif(rand > 25 and rand <= 50):\n tag[word] = 'pawned'\n elif(rand > 50 and rand <= 75):\n tag[word] = \"tendered\"\n else: tag[word] = 'purveyed'\n if(tagged == 'food'): #food\n rand = rando()\n if(rand > 1 and rand < 20):\n print(True)\n tag[word] = \"vittles\"\n elif(rand > 20 and rand < 40):\n tag[word] = 'rations'\n elif(rand > 40 and rand < 60):\n tag[word] = \"sustenance\"\n elif(rand > 60 and rand < 80):\n tag[word] = \"sustenance\"\n else: tag[word] = 'viands'\n if(tagged == 'bet'):\n tag[word] = 'warrant'\n if(tagged == 'hunting' or tagged == 'huntin'):\n tag[word] = \"a-huntin'\"\n if(tagged == 'coming' or tagged == 'comin'):\n tag[word] = \"a-comin'\"\n if(tagged == 'walking' or tagged == 'walkin'):\n tag[word] = \"a-walkin'\"\n if(tagged == 'making' or tagged == 'makin'):\n tag[word] = \"a-makin'\"\n if(tagged == 'of'):\n rand = rando()\n if rand >= 50:\n tag[word] = \"o'\"\n if(tagged == 'away'):\n rand = rando()\n if rand > 74:\n tag[word] = 'aroint'\n if(tagged == 'being'):\n rand = rando()\n if rand > 25:\n tag[word] = \"bein'\"\n if(tagged == 'why'):\n rand = rando()\n if rand > 50:\n tag[word] = 'wherefore'\n if(tagged == 'fucker'):\n tag[word] = 'swiver'\n if(tagged == 'fuckers'):\n tag[word] = 'swivers'\n if(tagged == 'shit'):\n tag[word] = 'nightsoil'\n if(tagged == 'child'):\n rand = rando()\n if rand > 50:\n tag[word] = 'poppet'\n if(tagged == 'those'):\n rand = rando()\n if rand > 50:\n tag[word] = 'yon'\n if(tagged == 'really'):\n rand = rando()\n if rand > 50:\n tag[word] = 'indeed'\n else: tag[word] = 'in truth'\n if(tagged == 'often'):\n rand = rando()\n if rand > 33:\n tag[word] = 'oft'\n if(tagged == 'maybe'):\n rand = rando()\n if rand > 33:\n tag[word] = 'mayhaps'\n if rand > 66:\n tag[word] = 'perchance'\n if(tagged == 'sure'):\n rand = rando()\n if rand > 66:\n tag[word] = 'shore'\n if(tagged == 'assist'): #food\n rand = rando()\n if(rand > 1 and rand <= 20):\n tag[word] = \"aid\"\n elif(rand > 20 and rand <= 40):\n tag[word] = 'aideth'\n elif(rand > 40 and rand <= 60):\n tag[word] = \"saveth\"\n elif(rand > 60 and rand <= 80):\n tag[word] = \"assistance\"\n else: tag[word] = 'succor'\n if(tagged == 'could'):\n rand = rando()\n if rand > 50:\n tag[word] = 'couldst'\n if(tagged == 'would'):\n rand = rando()\n if rand > 50:\n tag[word] = 'wouldst'\n if(tagged == 'later'):\n rand = rando()\n if rand > 50:\n tag[word] = 'anon'\n if(tagged == 'here'):\n rand = rando()\n if rand > 25:\n tag[word] = 'hither'\n if(tagged == 'enough'):\n rand = rando()\n if rand > 66:\n tag[word] = 'enow'\n if(tagged == 'though'):\n rand = rando()\n if rand > 66:\n tag[word] = \"tho'\"\n if(tagged == 'underneath' or tagged == 'beneath' or tagged == 'under'):\n rand = rando()\n if rand > 50:\n tag[word] = \" 'neath\"\n if(tagged == 'until'):\n rand = rando()\n if rand > 33:\n tag[word] = \"' till\"\n if(tagged == 'joke'):\n rand = rando()\n if rand > 33:\n tag[word] = \"jest\"\n else: tag[word] = 'jape'\n if(tagged == 'your'):\n rand = rando()\n if rand < 33:\n tag[word] = \"thy\"\n elif rand > 32 and rand < 66:\n tag[word] = 'thine'\n else: tag[word] = 'thyne'\n if(tagged == 'my'):\n rand = rando()\n if rand > 50:\n tag[word] = 'mine'\n if(tagged == 'in'):\n rand = rando()\n if rand > 50:\n tag[word] = 'within'\n if(tagged == 'gold' or tagged == 'money'):\n rand = rando()\n if(rand >= 1 and rand <= 12):\n tag[word] = 'bullion'\n elif(rand > 12 and rand <= 25):\n tag[word] = 'florins'\n elif(rand > 25 and rand <= 37):\n tag[word] = \"pounds\"\n elif(rand > 37 and rand <= 50):\n tag[word] = \"pieces o'silver\"\n elif(rand > 50 and rand <= 63):\n tag[word] = \"groats\"\n elif(rand > 63 and rand <= 75):\n tag[word] = \"crowns\"\n elif(rand > 75 and rand <= 88):\n tag[word] = \"ingots\"\n else: tag[word] ='ducats'\n if(tagged == 'balls' or tagged == 'groin'):\n rand = rando()\n if(rand >= 1 and rand <= 12):\n tag[word] = 'leathers'\n elif(rand > 12 and rand <= 25):\n tag[word] = 'beans'\n elif(rand > 25 and rand <= 37):\n tag[word] = \"poundables\"\n elif(rand > 37 and rand <= 50):\n tag[word] = \"nethers\"\n elif(rand > 50 and rand <= 63):\n tag[word] = \"nadchackles\"\n elif(rand > 63 and rand <= 75):\n tag[word] = \"buis\"\n elif(rand > 75 and rand <= 88):\n tag[word] = \"fellahs\"\n else: tag[word] ='coin purse'\n if(tagged == 'go'):\n rand = rando()\n if rand > 50:\n tag[word] = 'be off'\n else: tag[word] = ''\n if(tagged == 'will'):\n rand = rando()\n if rand > 50:\n tag[word] = 'wilt'\n else: tag[word] = 'wouldst'\n if(tagged == 'does' or tagged == 'Does'):\n rand = rando()\n if rand < 33:\n tag[word] = 'doeseth'\n elif rand > 32 and rand < 66:\n tag[word] = 'dost'\n else: tag[word] = 'doth'\n if(tagged == 'hello' or tagged == 'hi' or tagged == 'hey'):\n rand = rando()\n if(rand >= 20):\n tag[word] = \"good day\"\n elif(rand > 20 and rand <= 40):\n tag[word] = \"well met\"\n elif(rand > 40 and rand <= 60):\n tag[word] = \"tally ho\"\n elif(rand > 60 and rand <= 80):\n tag[word] = \"well meteth\"\n else: tag[word] ='ave'\n if(tagged == 'yes'):\n rand = rando()\n if rand < 33:\n tag[word] = 'aye'\n elif rand < 66:\n tag[word] = 'yea'\n else: tag[word] = 'yeah verily'\n if(tagged == 'no'):\n rand = rando()\n if rand > 50:\n tag[word] = 'nay'\n else: tag[word] = 'nayeth'\n if(tagged == 'goodbye' or tagged == 'bye' or tagged == 'seeya' or tagged == 'goodnight'):\n rand = rando()\n if(rand >= 1 and rand <= 12):\n tag[word] = 'good morrow'\n elif(rand > 12 and rand <= 25):\n tag[word] = 'godspeed'\n elif(rand > 25 and rand <= 37):\n tag[word] = \"begone\"\n elif(rand > 37 and rand <= 50):\n tag[word] = \"adieu\"\n elif(rand > 50 and rand <= 63):\n tag[word] = \"cheerio\"\n elif(rand > 63 and rand <= 75):\n tag[word] = \"I bid thee good day\"\n elif(rand > 75 and rand <= 88):\n tag[word] = \"by your leave\"\n else: tag[word] ='pleasant journey'\n if(tagged == 'idiot' or tagged == 'fool' or tagged == 'bastard' or tagged == 'moron'\n or tagged == 'jackass' or tagged == 'dumbass' or tagged == \"bitch\"):\n one = idiotPre()\n two = idiotPre()\n three = idiot(0)\n tag[word] = one + ' ' + two + ' ' + three\n if(tagged == 'idiots' or tagged == 'fools' or tagged == 'bastards' or tagged == 'morons'\n or tagged == 'jackasss' or tagged == 'dumbass' or tagged == \"bitches\"):\n one = idiotPre()\n two = idiotPre()\n three = idiot(1)\n tag[word] = one + ' ' + two + ' ' + three\n\n\n #contractions\n #for word in range(len(tag)):\n #misc\n for word in range(len(tag)):\n tagged = tag[word].lower()\n if(tagged == 'you' or tagged == 'u'): #you\n x = random.randrange(len(youArr)-1)\n tag[word] = youArr[x]\n if(tagged == 'are'): # are\n tag[word] = 'art'\n if(tagged == 'lol'): #lol\n x = random.randrange(len(lolArr)-1)\n tag[word] = lolArr[x]\n if(tagged == 'killed' or tagged == 'beaten' or tagged == 'fucked'): #killed\n x = random.randrange(len(killPastArr)-1)\n tag[word] = killPastArr[x]\n if(tagged == 'kill' or tagged == 'gank'): #killed\n x = random.randrange(len(killArr)-1)\n tag[word] = killArr[x]\n\n\n\n tag = \"\".join([\" \"+i if not i.startswith(\"'\") and i not in string.punctuation else i for i in tag]).strip()\n return tag\n\ndef checkTags(x): #Checks if a mention occurs within the message, then concats the mention to maintain its integrity\n #else it will remain in the form of ['<','@','userid','>']\n #it is also the ugliest code in existence\n cnt = 0 #and is only for discord mentions in the form of '<@userid>'\n tag = nltk.word_tokenize(x)\n if('@' not in tag):\n return tag\n else:\n for i in range(len(tag)):\n if(tag[i] == '<'):\n for j in range(len(tag)):\n j += 1+i\n tag[i] += tag[j]\n tag[i+1] = tag[j]\n cnt = j\n if('>' in tag[i+1]):\n for z in range(cnt):\n try:\n del tag[i+1]\n if(tag[i+1] == '>'):\n del tag[i+1]\n return(tag)\n except IndexError:\n return(tag)\n return(tag)\n\ndef checkPunct(s): #Checks the end of message, if there is no punctuation, assume period\n l = list(s)\n tag = nltk.pos_tag(nltk.word_tokenize(s))[-1] #tag = last character of message\n if(tag[0] == '!'):\n return(exclam(s))\n if(tag[0] == '?'):\n return(questi(s))\n if(tag[0] == '.' or tag[0] != '!' or tag[0] != '?'):\n if rando() > 50:\n return(postpend(s))\n else: return s\n\ndef exclam(s): # for '!'\n l = list(s)\n tag = nltk.pos_tag(nltk.word_tokenize(s))[-1]\n if(tag[0] == '!'):\n l[-1] = ''\n s = ''.join(l)\n\n x = random.randrange(len(exclamArr)-1)\n return(s + exclamArr[x])\n\ndef questi(s): # for '?'\n l = list(s)\n tag = nltk.pos_tag(nltk.word_tokenize(s))[-1]\n if(tag[0] == '?'):\n l[-1] = ''\n s = ''.join(l)\n\n x = random.randrange(len(questArr)-1)\n return(s + questArr[x])\n\ndef postpend(s): # for '.' end punct\n if(len(s) >= 1):\n l = list(s)\n tag = nltk.pos_tag(nltk.word_tokenize(s))[-1]\n if(tag[0] == '.'):\n l[-1] = ','\n s = ''.join(l)\n else: #if message does not end with '.', assume period\n l.append(',')\n s = ''.join(l)\n\n x = random.randrange(len(postArr)-1)\n return (s + postArr[x])\n\ndef rando():\n rand = random.randint(1,101)\n return rand\n\n\n#TESTING--------------------------------TESTING\n#while True:\n# s = input(\"Enter a string \")\n# print(s)\n# print(medieval(s))\n# s = input(\"Again?\")\n# if(s == 'n'):\n# break\n#TESTING--------------------------------TESTING\n","sub_path":"nltktest.py","file_name":"nltktest.py","file_ext":"py","file_size_in_byte":31331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"345781193","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CTask',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('create_timestamp', models.DateTimeField(auto_now_add=True)),\n ('modify_timestamp', models.DateTimeField(auto_now=True)),\n ('task_type', models.CharField(default=b'tag', max_length=10, choices=[(b'tag', 'Tag'), (b'global', 'Global'), (b'week', 'Week'), (b'day', 'Day'), (b'routine', 'Routine'), (b'silly', 'Silly')])),\n ('title', models.CharField(max_length=250)),\n ('description', models.TextField(blank=True)),\n ('start_time', models.DateTimeField(blank=True)),\n ('end_time', models.DateTimeField(blank=True)),\n ('completed', models.BooleanField(default=False)),\n ('owners', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),\n ('parents', models.ManyToManyField(to='core.CTask', blank=True)),\n ],\n ),\n ]\n","sub_path":"core/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"27237240","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests\nimport argparse \nimport sys \nimport json\nimport zipfile\n\nimport pandas as pd \nimport io \nimport urllib \n\ndef dataJsonMaker(data):\n dataJson = []\n for element in data['features']: \n Name = element['properties']['name']\n Marque = element['properties']['marque']\n if element['properties']['capacity']:\n Capacity = element['properties']['capacity']\n else:\n Capacity = element['properties']['capacity'] = 0 \n Zip_code = element['properties']['com_insee'] \n City = element['properties']['com_nom'] \n dataDict = {\n 'Name' : Name,\n 'Marque' : Marque,\n 'City' : City,\n 'Zip_code' : Zip_code,\n 'Capacity' : int(Capacity),\n }\n dataJson.append(dataDict) \n return dataJson\n\n\ndef main(args):\n if args.network == \"vue\":\n access_url = urllib.request.urlopen('https://geodatamine.fr/dump/cinema_geojson.zip')\n z = zipfile.ZipFile(io.BytesIO(access_url.read()))\n data = json.loads(z.read(z.infolist()[0]).decode())\n \n dataJson = dataJsonMaker(data)\n\n df = pd.DataFrame.from_dict(dataJson, orient='columns')\n cleanDf = df[df.Capacity != 0]\n\n TenSmallestTheatre = cleanDf.nsmallest(10, 'Capacity')\n Biggest_networks = df['Marque'].value_counts()[:3].index.tolist()\n cityAndTheatre = df.groupby(['Zip_code', 'City'])['Name'].count().reset_index(name='theaters')\n\n print(\n \"10 smallest theaters :\\n\\n\", TenSmallestTheatre,\"\\n\",\n \"\\nBiggest networks :\\n\\n\", Biggest_networks,\"\\n\",\n \"\\nThe city with the most theaters :\\n\\n\", cityAndTheatre.nlargest(1, 'theaters'), \"\\n\"\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--network', dest='network', default='vue', \n type=str, choices=['vue'], \n help=\"Display some statistics about french theaters\", required=True) \n args = parser.parse_args()\n main(args)\n \n","sub_path":"cinemaFacts.py","file_name":"cinemaFacts.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"474191139","text":"import json\nfrom django.http import HttpResponse, Http404\nfrom mpr import models\n\ndosage_form = {\n \"Liq\" : \"liquid\",\n \"Tab\" : \"tablet\",\n \"Cap\" : \"capsule\",\n \"Oin\" : \"ointment\",\n \"Lit\" : \"lotion\",\n \"Inj\" : \"injection\",\n \"Syr\" : \"syrup\",\n \"Eft\" : \"Effervescent\",\n \"Drp\" : \"Drops\",\n \"Sus\" : \"Suspension\",\n \"Cal\" : \"Calasthetic\",\n \"Sol\" : \"Solution\",\n \"Neb\" : \"Nebuliser\",\n \"Inh\" : \"Inhaler\",\n \"Inf\" : \"Infusion\",\n}\n\ndef calc_max_fee(x):\n try:\n if x < 81:\n return x * 1.46 + 6.3\n elif x < 216:\n return x * 1.33 + 16\n elif x < 756:\n return x * 1.15 + 52\n else:\n return x * 1.05 + 123\n except (ValueError, TypeError):\n return \"-\"\n\ndef as_currency(x):\n try:\n x = float(x)\n return \"R %.2f\" % x\n except (ValueError, TypeError):\n return \"-\"\n\ndef int_or_float(x):\n try:\n x = float(x)\n if int(x) == float(x):\n return int(x)\n return x\n except (ValueError, TypeError):\n return \"-\"\n\ndef serialize_ingredient(ingredient, strength):\n return {\n \"name\" : ingredient.name,\n \"unit\" : ingredient.unit,\n \"strength\" : int_or_float(strength),\n }\n\ndef serialize_product(product):\n return {\n \"regno\" : product.regno,\n \"schedule\" : product.schedule,\n \"name\" : product.name,\n \"dosage_form\" : dosage_form.get(product.dosage_form, product.dosage_form),\n \"pack_size\" : product.pack_size,\n \"num_packs\" : product.num_packs,\n \"sep\" : as_currency(calc_max_fee(product.sep)),\n \"is_generic\" : \"Generic\" if product.is_generic else \"Innovator\",\n \"ingredients\" : [\n serialize_ingredient(pi.ingredient, pi.strength)\n for pi in product.product_ingredients.all()\n ]\n }\n \n\ndef api(request):\n ingredsearch = request.GET.get(\"ingredient\", \"\").strip()\n\n if len(ingredsearch) < 3:\n products = []\n else:\n ingredients = models.Ingredient.objects.filter(name__icontains=ingredsearch)\n\n products = set()\n for i in ingredients:\n products |= set(i.product_set.all())\n\n products = sorted(products, key=lambda x: x.sep)\n products = [serialize_product(p) for p in products]\n\n return HttpResponse(\n json.dumps(products, indent=4), mimetype=\"application/json\"\n )\n\n","sub_path":"server/mpr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"654136731","text":"\"\"\"oil URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom django.contrib import admin\nfrom django.urls import path\nfrom rest_framework import routers\nfrom django.conf.urls import include, url\nfrom oilapi.views import ( JobView,\n JobTypeView,\n UserPairView,\n JobInviteView,\n UserView,\n login_user,\n register_user,\n email_check\n ) \n\nrouter = routers.DefaultRouter(trailing_slash=False)\nrouter.register(r'jobs', JobView, 'job')\nrouter.register(r'jobtypes', JobTypeView, 'job_type')\nrouter.register(r'friends', UserPairView, 'user_pair')\nrouter.register(r'shared', JobInviteView, 'job_invite')\nrouter.register(r'users', UserView, 'user')\n\nurlpatterns = [\n path('', include(router.urls)),\n path('admin/', admin.site.urls),\n url(r'^login$', login_user),\n url(r'^register$', register_user),\n url(r'^email$', email_check),\n url(r'^api-token-auth$', obtain_auth_token),\n url(r'^api-auth', include('rest_framework.urls', namespace='rest_framework')),\n]\n","sub_path":"oil/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"263080113","text":"# coding:utf-8\n\"\"\"Mxonline URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\n# from django.urls import path\nfrom django.conf.urls import url, include\nfrom django.views.generic import TemplateView\nimport xadmin\nfrom django.views.static import serve\n\nfrom users.views import LoginView, RegisterView, ActiveUserView, ForgetPwdView, ResetView, ModifyPwdView,LogoutView,IndexView\nfrom organization.views import OrgView,TeacherView,TeacherDetailView\nfrom djangoceshi.settings import MEDIA_ROOT\n\nurlpatterns = [\n url(r'xadmin/', xadmin.site.urls),\n url('^$', IndexView.as_view(), name='index'),\n url(r'^login/$', LoginView.as_view(), name='login'),\n url(r'^logout/$', LogoutView.as_view(), name='logout'),\n url(r'^register/$', RegisterView.as_view(), name='register'),\n url(r'^captcha/', include('captcha.urls')),\n url(r'^active/(?P.*)/$', ActiveUserView.as_view(), name='user_active'),\n url(r'^forgetpwd/$', ForgetPwdView.as_view(), name='forget_pwd'),\n url(r'^reset/(?P.*)/$', ResetView.as_view(), name='reset_pwd'),\n url(r'^modifypwd/$', ModifyPwdView.as_view(), name='modify_pwd'),\n\n #课程机构url配置\n url(r'^org/', include('organization.urls',namespace='org')),\n\n #课程相关url配置\n url(r'^course/', include('courses.urls',namespace='course')),\n\n #讲师相关url配置\n url(r'^teacher_list/$', TeacherView.as_view(), name='teacher_list'),\n url(r'^teacher_detail/(?P.*)/$', TeacherDetailView.as_view(), name='teacher_detail'),\n\n #配置上次文件的访问处理函数\n url(r'^media/(?P.*)$', serve, {\"document_root\":MEDIA_ROOT}),\n\n # url(r'^static/(?P.*)$', serve, {\"document_root\":STATIC_ROOT}),\n\n #个人中心url配置\n url(r'^users/', include('users.urls', namespace='user')),\n\n # xadmin 集成富文本相关url\n url(r'^ueditor/', include('DjangoUeditor.urls')),\n\n]\n\n#全局404页面配置\nhandler404 = \"users.views.page_not_found\"\nhandler500 = \"users.views.page_error\"\n","sub_path":"djangoceshi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"130451583","text":"#python -m flask run --reload --debugger\nfrom flask import Flask, redirect, url_for, render_template, request\nfrom graphviz import dot\nfrom Analyzer.Grammar import parse\nimport graphviz\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\nheadingsSimbolos = (\"Environment\", \"Name\", \"Type\", \"Role\", \"Lower\", \"Upper\", \"Absolute\", \"Relative\", \"Size\", \n \"Reference\", \"Row\", \"Column\", \"Return\")\nheadingsErrores = (\"Type\", \"Error\", \"Line\", \"Column\")\n\n@app.route(\"/analyze\", methods=[\"POST\",\"GET\"])\ndef analyze():\n if request.method == \"POST\":\n inpt = request.form[\"inpt\"]\n global tmp_val\n tmp_val=inpt\n tmp_val = str(tmp_val).replace('||', '!!!')\n tmp_val = str(tmp_val).replace('global ', '')\n tmp_val = str(tmp_val).replace('local ', '')\n return redirect(url_for(\"output\"))\n else:\n return render_template('analyze.html', initial=\"\")\n\n@app.route('/output', methods=[\"POST\", \"GET\"])\ndef output():\n global tmp_val\n result = parse(tmp_val)\n app.c = result[1]\n if request.method == \"POST\":\n return redirect(url_for(\"grafo\"))\n else:\n if result[3] == '':\n return render_template('output.html', input=result[0], headings=headingsErrores, data=result[2], codigo=result[3])\n return render_template('output.html', input=result[0], headings=headingsSimbolos, data=result[2], codigo=result[3])\n\n@app.route('/grafo')\ndef grafo():\n dot = app.c\n return dot.pipe().decode('utf-8')\n\nif __name__ == '__main__':\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"110994101","text":"from scipy.stats import kendalltau\n\nfrom .base import IndependenceTest\nfrom ._utils import _CheckInputs\n\n\nclass Kendall(IndependenceTest):\n r\"\"\"\n Class for calculating the Kendall's :math:`\\tau` test statistic and\n p-value.\n\n Kendall's :math:`\\tau` coefficient is a statistic to meassure ordinal\n associations between two quantities. The Kendall's :math:`\\tau`\n correlation between high when variables similar rank relative to other\n observations [#1Kend]_. Both this and the closely related Spearman's\n :math:`\\rho` coefficient are special cases of a general correlation\n coefficient.\n\n See Also\n --------\n Pearson : Pearson product-moment correlation test statistic and p-value.\n Spearman : Spearman's rho test statistic and p-value.\n\n Notes\n -----\n This class is a wrapper of `scipy.stats.kendalltau\n `_. The statistic can be derived\n as follows [#1Kend]_:\n\n Let :math:`x` and :math:`y` be :math:`(n, 1)` samples of random variables\n :math:`X` and :math:`Y`. Define :math:`(x_i, y_i)` and :math:`(x_j, y_j)`\n as concordant if the ranks agree: :math:`x_i > x_j` and :math:`y_i > y_j`\n or :math:`x_i > x_j` and :math:`y_i < y_j`. They are discordant if the ranks\n disagree: :math:`x_i > x_j` and :math:`y_i < y_j` or :math:`x_i < x_j` and\n :math:`y_i > y_j`. If :math:`x_i > x_j` and :math:`y_i < y_j`, the pair is\n said to be tied. Let :math:`n_c` and :math:`n_d` be the number of\n concordant and discordant pairs respectively and :math:`n_0 = n(n-1) / 2`.\n In the case of no ties, the test statistic is defined as\n\n .. math::\n\n \\mathrm{Kendall}_n (x, y) = \\frac{n_c - n_d}{n_0}\n\n Further, define :math:`n_1 = \\sum_i \\frac{t_i (t_i - 1)}{2}`,\n :math:`n_2 = \\sum_j \\frac{u_j (u_j - 1)}{2}`, :math:`t_i` be the number of\n tied values in the :math:`i`-th group and :math:`u_j` be the number of tied\n values in the :math:`j`-th group. Then, the statistic is [#2Kend]_,\n\n .. math::\n\n \\mathrm{Kendall}_n (x, y) = \\frac{n_c - n_d}\n {\\sqrt{(n_0 - n_1) (n_0 - n_2)}}\n\n References\n ----------\n .. [#1Kend] Kendall, M. G. (1938). A new measure of rank correlation.\n *Biometrika*, 30(1/2), 81-93.\n .. [#2Kend] Agresti, A. (2010). *Analysis of ordinal categorical data*\n (Vol. 656). John Wiley & Sons.\n \"\"\"\n\n def __init__(self):\n IndependenceTest.__init__(self)\n\n def _statistic(self, x, y):\n r\"\"\"\n Helper function that calculates the Kendall's :math:`\\tau` test\n statistic.\n\n Parameters\n ----------\n x, y : ndarray\n Input data matrices. `x` and `y` must have the same number of\n samples and dimensions. That is, the shapes must be `(n, 1)` where\n `n` is the number of samples.\n\n Returns\n -------\n stat : float\n The computed Kendall's tau statistic.\n \"\"\"\n x.shape = (-1,)\n y.shape = (-1,)\n stat, _ = kendalltau(x, y)\n self.stat = stat\n\n return stat\n\n def test(self, x, y):\n r\"\"\"\n Calculates the Kendall's :math:`\\tau` test statistic and p-value.\n\n Parameters\n ----------\n x, y : ndarray\n Input data matrices. `x` and `y` must have the same number of\n samples and dimensions. That is, the shapes must be `(n, 1)` where\n `n` is the number of samples.\n\n Returns\n -------\n stat : float\n The computed Kendall's tau statistic.\n pvalue : float\n The computed Kendall's tau p-value.\n\n Examples\n --------\n >>> import numpy as np\n >>> from hyppo.independence import Kendall\n >>> x = np.arange(7)\n >>> y = x\n >>> stat, pvalue = Kendall().test(x, y)\n >>> '%.1f, %.2f' % (stat, pvalue)\n '1.0, 0.00'\n \"\"\"\n check_input = _CheckInputs(x, y, dim=1)\n x, y = check_input()\n stat, pvalue = kendalltau(x, y)\n self.stat = stat\n self.pvalue = pvalue\n\n return stat, pvalue\n","sub_path":"hyppo/independence/kendall.py","file_name":"kendall.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"336343625","text":"\"\"\"Closed caption processing\"\"\"\n\nfrom youtube_transcript_api import YouTubeTranscriptApi as yttapi\n# https://github.com/jdepoix/youtube-transcript-api\nimport spacy\n# https://spacy.io/usage/linguistic-features\n# https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.3.1/en_core_web_sm-2.3.1.tar.gz\nfrom collections import Counter\nfrom random import choice\n\nIGNORETAGS = [\"ADP\", \"AUX\", \"CONJ\", \"PART\", \"PUNCT\", \"SCONJ\", \"SYM\", \"X\", \"SPACE\"]\n\nclass contextStruct:\n interjections = []\n adjectives = []\n nouns = []\n adverbs = []\n verbs = []\n determiners = []\n def __init__(self, validTokens):\n interjections = mostFrequentWords(validTokens, \"INTJ\")\n adjectives = mostFrequentWords(validTokens, \"ADJ\")\n nouns = mostFrequentWords(validTokens, \"NOUN\")\n nouns += mostFrequentWords(validTokens, \"PROPN\")\n adverbs = mostFrequentWords(validTokens, \"ADV\")\n verbs = mostFrequentWords(validTokens, \"VERB\")\n determiners = mostFrequentWords(validTokens, \"DET\")\n # take care of default values\n self.interjections = interjections if len(interjections) > 0 else [\"wow\", \"haha\"]\n self.adjectives = adjectives if len(adjectives) > 0 else [\"interesting\", \"funny\", \"ordinary\", \"controversial\", \"painstaking\"]\n self.nouns = nouns if len(nouns) > 0 else [\"person\", \"thing\"]\n self.adverbs = adverbs if len(adverbs) > 0 else [\"quickly\", \"slowly\"]\n self.verbs = verbs if len(verbs) > 0 else [\"did\", \"threw\", \"took\", \"said\"]\n self.determiners = determiners if len(determiners) > 0 else [\"the\", \"that\", \"this\", \"these\"]\n\n\nsentenceStructures = [\n \"DET ADJ NOUN VERB.\",\n \"DET NOUN ADV VERB.\",\n \"DET NOUN VERB...\",\n \"INTJ! INTJ!!\",\n \"INTJ! NOUN VERB DET ADJ NOUN, ADV.\",\n \"INTJ, DET NOUN VERB NOUN.\",\n \"NOUN ADV VERB NOUN ADV.\",\n \"NOUN ADV VERB NOUN!\",\n \"NOUN VERB DET ADJ NOUN ADV.\",\n \"DET ADJ NOUN VERB.\",\n \"DET NOUN VERB DET ADJ NOUN ADV, INTJ!\",\n \"INTJ. DET NOUN VERB.\",\n \"NOUN VERB!\",\n \"INTJ, INTJ, INTJ. NOUN ADV VERB NOUN.\"\n]\n\ndef fetchTranscript(videoID):\n return yttapi.get_transcript(videoID)\n\ndef fetchTranscriptRaw(transcript):\n return \" \".join([i[\"text\"] for i in transcript]).lower()\n\ndef fetchIntervalRaw(transcript, a, b):\n return fetchTranscriptRaw(fetchInterval(transcript, a, b))\n\ndef fetchInterval(transcript, a, b):\n thisTranscript = []\n for t in transcript:\n if (t[\"start\"] + 5 >= a) and (t[\"start\"] + t[\"duration\"] - 5 <= b):\n thisTranscript.append(t)\n return thisTranscript\n\ndef determineContext(transcriptRaw):\n global IGNORETAGS\n sentence = \"\"\n nlp = spacy.load(\"./comtube/en_core_web_sm-3.0.0/en_core_web_sm/en_core_web_sm-3.0.0\")\n tokenized = nlp(transcriptRaw)\n validTokens = [token for token in tokenized if token.pos_ not in IGNORETAGS]\n context = contextStruct(validTokens)\n return constructSentence(context)\n\ndef constructSentence(context):\n if type(context) != contextStruct: raise TypeError(\"contextStruct expected\")\n w = lambda words: choice(words)\n j = int(len(context.nouns) * .5)\n if j == 0:\n return \"\"\n sentences = []\n while j > 0:\n sentence = choice(sentenceStructures)\n while any(tag in sentence for tag in [\"INTJ\", \"ADJ\", \"NOUN\", \"ADV\", \"VERB\", \"DET\"]):\n sentence = sentence.replace(\"INTJ\", w(context.interjections), 1)\n sentence = sentence.replace(\"ADJ\", w(context.adjectives), 1)\n sentence = sentence.replace(\"NOUN\", w(context.nouns), 1)\n sentence = sentence.replace(\"ADV\", w(context.adverbs), 1)\n sentence = sentence.replace(\"VERB\", w(context.verbs), 1)\n sentence = sentence.replace(\"DET\", w(context.determiners), 1)\n sentences.append(sentence.capitalize())\n j -= 1\n return choice(sentences)\n\ndef mostFrequentWords(validTokens, pos):\n counter = Counter([ token.text for token in validTokens if token.pos_ == pos ])\n count = int(len(counter) * .5) + 1\n freqWords = [i[0] for i in counter.most_common(count)]\n return freqWords\n\ndef getNouns(sentence):\n nlp = spacy.load(\"./comtube/en_core_web_sm-3.0.0/en_core_web_sm/en_core_web_sm-3.0.0\")\n tokenized = nlp(sentence)\n return [token.text for token in tokenized if token.pos_ == \"NOUN\"]\n\n# [\n# {\n# 'text': 'Hey there',\n# 'start': 7.58,\n# 'duration': 6.13\n# },\n# {\n# 'text': 'how are you',\n# 'start': 14.08,\n# 'duration': 7.58\n# },\n# # ...\n# ]\n","sub_path":"src/comtube/cc.py","file_name":"cc.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"505625465","text":"'''\nThis module implements API to communicate with database backend.\n'''\nimport logging\nimport os.path\nimport sys\nsys.path.append('../')\nfrom connection import connectionPool\n\n\n'''\n (0,'None');\n (1,'amusement');\n (2,'awe');\n (3,'contentment');\n (4,'anger');\n (5,'disgust');\n (6,'excitement');\n (7,'fear');\n (8,'sadness');\n'''\n\nclass databaseAPI:\n \"\"\"\n This is the API portal to grab connections\n \"\"\"\n\n def __init__(self, dbPath=None, filePath=None):\n '''\n Initialization, either use SQL or NoSQL\n All image data and model data are stored under data folder (possibly under image and model, separately)\n The database backend should manage metadata only (i.e., store PATH to data, instead of storing data itself) to\n achieve efficiency.\n '''\n self.logger = logging.getLogger()\n self.logger.setLevel(logging.INFO)\n dbType = \"sqlite\"\n # self.logger.addHandler(ch)\n self.__connectSQL(dbType, dbPath, filePath)\n\n if not os.path.isdir(filePath):\n logging.info(filePath + \" doesn't exist, will create a new one \\n\")\n os.makedirs(filePath)\n\n def close(self):\n self.__pool.clear()\n\n def __connectSQL(self, dbType, name, filePath):\n self.__pool = connectionPool(dbType, name, filePath)\n # self.sql=myConnection(dbType,name)\n\n def popConnection(self):\n return self.__pool.pop()\n\n def appendConnection(self, connection):\n return self.__pool.append(connection)\n\n # ----------------------------------\n # those are just wrapper methods\n #-----------------------------------\n def execute(self, command):\n sql = self.__pool.pop()\n out = sql.execute(command)\n self.__pool.append(sql)\n return out\n\n def query_meta(self, command):\n sql = self.__pool.pop()\n out = sql.query_meta(command)\n self.__pool.append(sql)\n return out\n\n def printSchemas(self):\n sql = self.__pool.pop()\n out = sql.printSchemas()\n self.__pool.append(sql)\n return out\n\n def insertModelLabel(self, model, image_id, label, confidence):\n sql = self.__pool.pop()\n out = sql.insertModelLabel(model, image_id, label, confidence)\n self.__pool.append(sql)\n return out\n\n def removeModelLabel(self, model=None, image_id=None):\n sql = self.__pool.pop()\n out = sql.removeModelLabel(model, image_id)\n self.__pool.append(sql)\n return out\n\n def getRandomImageWithWeakLabel(self):\n sql = self.__pool.pop()\n out = sql.getRandomImageWithWeakLabel()\n self.__pool.append(sql)\n return out\n\n def insertImage(self, path, source='other', label=0, confidence=5, comment=\"NULL\", hashid=None):\n sql = self.__pool.pop()\n out = sql.insertImage(path, source, label, confidence, comment, hashid)\n self.__pool.append(sql)\n return out\n\n def insertMultipleImages(self, folderPath, source='other', label=0, confidence=5, comment='NULL'):\n sql = self.__pool.pop()\n out = sql.insertMultipleImages(folderPath, source, label, confidence, comment)\n self.__pool.append(sql)\n return out\n\n def removeImage(self, image_id):\n sql = self.__pool.pop()\n out = sql.removeImage(image_id)\n self.__pool.append(sql)\n return out\n\n def insertModel(self, path, name='', accuracy=0):\n sql = self.__pool.pop()\n out = sql.insertModel(path, name, accuracy)\n self.__pool.append(sql)\n return out\n\n def removeModel(self, name):\n sql = self.__pool.pop()\n out = sql.removeModel(name)\n self.__pool.append(sql)\n return out\n\n def synchronize(self):\n sql = self.__pool.pop()\n out = sql.synchronize()\n self.__pool.append(sql)\n return out\n\n def insertMultipleImagesParallel(self, folderPath, hashThreadNum=2, source='other', label=0, confidence=5,\n comment='NULL'):\n sql = self.__pool.pop()\n out = sql.insertMultipleImagesParallel(folderPath, hashThreadNum, source, label, confidence, comment)\n self.__pool.append(sql)\n return out\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"server/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"618465602","text":"\"\"\"\r\n@author: kid\r\n@file: gunicorn.config.py\r\n@time: 2020/1/12 14:34\r\n\"\"\"\r\nimport sys\r\nimport os\r\nimport multiprocessing\r\n\r\npath_of_current_file = os.path.abspath(__file__)\r\npath_of_current_dir = os.path.split(path_of_current_file)[0]\r\n_file_name = os.path.basename(__file__)\r\n\r\nsys.path.insert(0, path_of_current_dir)\r\n\r\n# 监听端口\r\nbind = '0.0.0.0:85'\r\n\r\n# 并行工作进程数\r\nworkers = multiprocessing.cpu_count() * 2 + 1\r\n\r\n# 指定每个工作者的线程数\r\nthreads = 1\r\n\r\n# 工作模式协程\r\nworker_class = 'sync'\r\n\r\n# 设置最大并发量\r\nworker_connections = 2000\r\n\r\n# 设置访问日志和错误信息日志路径\r\naccesslog = '{}/logs/access.log'.format(path_of_current_dir)\r\nerrorlog = '{}/logs/error.log'.format(path_of_current_dir)\r\n\r\n# 设置日志记录水平\r\nloglevel = 'debug'\r\n","sub_path":"gunicorn.config.py","file_name":"gunicorn.config.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"332297554","text":"from flask import Flask, render_template, request, request, redirect\nfrom mysqlconnection import connectToMySQL # import the function that will return an instance of a connection\napp = Flask(__name__)\n@app.route(\"/users\")\ndef index():\n print('*'*80)\n print ('entered index route')\n mysql = connectToMySQL('users_db') # call the function, passing in the name of our db\n users = mysql.query_db('SELECT * FROM users_db.users;') # call the query_db function, pass in the query as a string\n print (\"ALL USERS =\",users)\n return render_template(\"index.html\", users=users)\n\n@app.route(\"/users/\")\ndef show_user_details(id):\n print('*'*80)\n print ('entered show_user_details route')\n mysql = connectToMySQL('users_db') \n user = mysql.query_db(f'SELECT * FROM users_db.users WHERE id={id};') \n print (user)\n return render_template(\"show.html\", user=user)\n\n@app.route(\"/users/new\")\ndef new():\n print('*'*80)\n print ('entered create new user route')\n return render_template(\"create.html\")\n\n@app.route(\"/users/create\", methods=[\"POST\"])\ndef create():\n print('*'*80)\n print ('Received add_new_user form with the following data:')\n print ('FORM DATA RECEIVED:\\n',request.form)\n mysql = connectToMySQL('users_db')\n query = 'INSERT INTO users (first_name, last_name, email) VALUES (%(first_name)s, %(last_name)s, %(email)s)'\n data = {\n 'first_name': request.form['first_name'],\n 'last_name': request.form['last_name'],\n 'email': request.form['email']\n }\n new_user_id = mysql.query_db(query,data)\n return redirect(\"/users\")\n\n@app.route(\"/users//edit\")\ndef edit(id):\n print('*'*80)\n print ('entered edit user route')\n mysql = connectToMySQL('users_db') \n user = mysql.query_db(f'SELECT * FROM users_db.users WHERE id={id};')\n return render_template(\"edit.html\",user=user)\n\n@app.route(\"/users//update\", methods=[\"POST\"])\ndef update(id):\n print('*'*80)\n print ('Received update user form with the following data:')\n print ('FORM DATA RECEIVED:\\n',request.form)\n print ('ID resolves to',id)\n mysql = connectToMySQL('users_db')\n query = 'UPDATE users SET first_name=%(first_name)s, last_name=%(last_name)s, email=%(email)s WHERE id=%(id)s'\n data = {\n 'id': {id},\n 'first_name': request.form['first_name'],\n 'last_name': request.form['last_name'],\n 'email': request.form['email']\n }\n new_user_id = mysql.query_db(query,data)\n return redirect(f\"/users/{id}\")\n\n@app.route(\"/users//destroy\")\ndef destroy(id):\n print('*'*80)\n print ('entered delete user route')\n mysql = connectToMySQL('users_db') \n user = mysql.query_db(f'DELETE FROM users_db.users WHERE id={id};')\n return redirect(\"/users\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"python/flask_mysql/users/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"233222907","text":"#!/usr/bin/env python3\n#from mpl_toolkits.basemap import Basemap\nimport cartopy as cpy\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nimport json\nimport matplotlib.colors as mc\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nimport numpy as np\nimport os\nimport pandas as pd\nimport xarray as xr\nimport xarray.ufuncs as xu\nimport seaborn as sns\n\n#very useful tutorial ! http://earthpy.org/cartopy_backgroung.html\nland_50m = cfeature.NaturalEarthFeature('physical', 'land', '50m',\n edgecolor='face',\n facecolor=cfeature.COLORS['land'])\n\n\ntilesize = 768\ndpi = 288\n\nremapdir='/mnt/raid/wrf-chem/wrfchem_v39/data_back/output-wrf-remapped'\n\nfplot=os.path.join(remapdir, 'd01reg_2019011800')\n#print(fplot)\n\nds=xr.open_dataset(fplot)\n#print(ds.lon)\nlon0=ds.lon.min()\nlon1=ds.lon[1]\nloninc=(lon1-lon0)\ntagon=0\n#loninc.values/2\nex_dom=([ds.lon.min()-tagon, ds.lon.max()+tagon,ds.lat.min()-tagon, (ds.lat.max() +tagon-1.5)])\n#ex_dom= \nprint(ex_dom, ds.lat.max())\n\npng_out_path='/mnt/raid/wrf-chem/wrfchem_v39/imgs/outline_merc_fine.svg'\nlons = ds.variables['lon'][:]\nlats = ds.variables['lat'][:]\nterr=ds.variables['t2']\nprint(ds.variables['terrain'].shape)\n\n\n\n#plotting\nlevels=(-5, -4, -2, 0,1, 2 , 5, 7, 10, 12, 13, 14, 15, 20)\nfig=plt.figure(figsize=(tilesize/dpi, tilesize/dpi), dpi=dpi)\nax=fig.add_subplot(111, projection=ccrs.PlateCarree())\n# NB: in order to contourf onto a particular projection: must define using \"transform\" the projection relevant to the dataset. Eg: if the dataset is in equirectangular grid (latlon): then the contourf trasnform must be defined as ccrs.PlateCarree()\n#cs=ax.contourf(lons, lats, terr[0,:,:], transform=ccrs.PlateCarree())\nax.set_extent(ex_dom)\nplt.box(on=None)\nplt.subplots_adjust(bottom=0, left=0, right=1, top=1, hspace = 0, wspace = 0)\n\n\n#cs.background_patch=None\n\n\n\n#ax.set_extent(ex_dom)\nax.coastlines('10m', linewidth=0.05)\nplt.axis('off')\nax.figsize=(tilesize/dpi, tilesize/dpi)\nax.dpi=dpi\nax.outline_patch.set_visible(False)\nax.background_patch.set_visible(False)\nax.background_patch.set_alpha(0)\n#ax.add_feature(cfeature.BORDERS,linewidth=0.25)\nax.axes.get_xaxis().set_visible(False)\nax.axes.get_yaxis().set_visible(False)\n#ax.add_feature(cfeature.LAND)\n#ax.set_axis_off()\n#\n\nplt.savefig(png_out_path, format='svg', bbox_inches='tight', pad_inches=0, dpi=288, tilesize=768, transparent=True)\nplt.close()\n\n\n","sub_path":"wrfchem_v415_ext/scripts/components/old2/outline_merc.py","file_name":"outline_merc.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"442193567","text":"from django import forms\n\nfrom govuk_forms.fields import SplitDateField\nfrom govuk_forms.forms import GOVUKForm\nfrom govuk_forms.widgets import InlineCheckboxSelectMultiple, InlineRadioSelect, \\\n SeparatedCheckboxSelectMultiple, SeparatedRadioSelect\n\noptions = (('a', 'Alpha'), ('b', 'Beta'))\nseparated_options = (('a', 'Alpha'), ('b', 'Beta'), ('c', 'Gamma'), ('d', 'Delta'), ('e', 'Epsilon'))\ngrouped_options = (\n ('First', options),\n ('Second', (('c', 'Gamma'), ('d', 'Delta'))),\n)\n\nclass IncidentDateForm(GOVUKForm):\n # customisations:\n auto_replace_widgets = True\n field_label_classes = 'heading-medium'\n\n reveal_conditionally = {\n 'occur_today': {\n False: 'exact_date'\n },\n 'exact_date': {\n True: 'full_date',\n False: 'hidden_at_first'\n }\n }\n\n occur_today = forms.ChoiceField(label='Did the incident occur today?', choices=((True, 'Yes'), (False, 'No')),\n widget=InlineRadioSelect)\n\n exact_date = forms.ChoiceField(label='Did the incident occur today?', choices=((True, 'I know the exact date'), (False, 'Im not sure')),\n widget=InlineRadioSelect)\n\n full_date = SplitDateField(label='', help_text='For example, 20 11 2017', required=False)\n\n hidden_at_first = forms.CharField(label='Hidden at first')","sub_path":"application/forms/incident.py","file_name":"incident.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"153950501","text":"\nsource_file = \"JavaSources/FeatureTest.java\"\n\nimport sys\nsys.path.insert(0, \"Source\")\n\nfrom Source.CXXCompiler import CXXCompiler\nfrom Source.PLYJ.parser import Parser\n\nparser = Parser()\n\n# Concat java lib with source file\njava_code = \"\"\n\nwith open(\"JavaSources/JavaLib.inc.java\", \"r\") as handle:\n java_code += handle.read()+ \"\\n\\n\"\n\nwith open(source_file, \"r\") as handle:\n java_code += handle.read()+ \"\\n\\n\"\n\ntree = parser.parse_string(java_code)\ngen = CXXCompiler()\ngen.compile(tree)\n\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"175050639","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nimport matplotlib.pylab as pylab\n\nparams = {'legend.fontsize': 'x-large',\n 'figure.figsize': (10, 10),\n 'axes.labelsize': 'x-large',\n 'axes.titlesize': 'x-large',\n 'xtick.labelsize': 'x-large',\n 'ytick.labelsize': 'x-large'}\npylab.rcParams.update(params)\n\n\nclass Node():\n def __init__(self):\n self.weights = np.random.uniform(0, 1, 31)\n\n\nclass SOM():\n\n def __init__(self, eta=0.2):\n self.nodes = np.array([[None]*10]*10)\n self.index = None\n self.eta = eta\n\n def __str__(self):\n return str(self.nodes.shape)\n\n def initWeights(self):\n for i in range(10):\n for j in range(10):\n self.nodes[i][j] = Node()\n\n def euclidianDist(self, pattern):\n dBest = 100000000\n for i in range(10):\n for j in range(10):\n d = np.linalg.norm(pattern-self.nodes[i][j].weights)\n if d < dBest:\n dBest = d\n iBest = i\n jBest = j\n return iBest, jBest\n\n def neighbourhood(self, iBest, jBest, epoch, epochs):\n if epoch/epochs <= 0.2:\n dist = 2\n elif epoch/epochs <= 0.5:\n dist = 1\n else:\n dist = 0\n\n hood = []\n iHood = np.linspace(iBest-dist, iBest+dist, 2*dist+1)\n jHood = np.linspace(jBest-dist, jBest+dist, 2*dist+1)\n\n for i in iHood:\n for j in jHood:\n if abs(i-iBest) + abs(j-jBest) > dist or 0 > i or i > 9 or 0 > j or j > 9:\n continue\n else:\n hood.append([i, j])\n hood = np.array(hood)\n return hood\n\n def weightsUpdate(self, pattern, hood):\n for indexes in hood:\n i = int(indexes[0])\n j = int(indexes[1])\n self.nodes[i][j].weights = self.nodes[i][j].weights + self.eta * \\\n np.subtract(pattern, self.nodes[i][j].weights)\n\n\ndef main():\n\n ####### Import vote data ##############\n data = []\n with open('/home/andrej/school/ann-course/lab2/votes.dat', 'r') as f:\n d = f.readlines()\n for i in d:\n k = i.rstrip().split(\",\")\n data.append([float(i) for i in k])\n data = np.array(data, dtype='O')\n voteData = np.reshape(data, (349, 31))\n ######################################\n\n # Coding: 0=no party, 1='m', 2='fp', 3='s', 4='v', 5='mp', 6='kd', 7='c'\n # Use some color scheme for these different groups\n\n data = []\n with open('/home/andrej/school/ann-course/lab2/mpparty.dat', 'r') as f:\n d = f.readlines()\n for i in d:\n k = i.rstrip().split(\",\")\n data.append([int(i) for i in k])\n partyData = np.array(data, dtype='O')\n\n ####### init som and weights #########\n som = SOM()\n som.initWeights()\n epochs = 20\n ######################################\n\n ######## Training ###################\n for epoch in range(epochs):\n shuffler = np.random.permutation(349)\n for i in shuffler:\n iBest, jBest = som.euclidianDist(voteData[i][:])\n hood = som.neighbourhood(iBest, jBest, epoch, epochs)\n weights = som.weightsUpdate(voteData[i][:], hood)\n som.eta *= 0.95\n # ######################################\n\n # ########## Testing ##################\n winnerIndexes = []\n for i in range(349):\n iBest, jBest = som.euclidianDist(voteData[i][:])\n winnerIndexes.append((iBest, jBest))\n # ######################################\n\n plt.figure('Party member comparison')\n plt.title('Party Member comparison')\n # plt.grid()\n nr_attributes = 8\n grid = np.array([[[0]*10]*10]*nr_attributes)\n\n index = 0\n for winner in winnerIndexes:\n partyBelonging = partyData[index]\n grid[partyBelonging[0]][winner[0]][winner[1]] += 1\n index += 1\n\n color = ['k', '#0000ff', '#3399ff', '#ff0000',\n '#990000', '#339933', '#6600cc', '#49ff33']\n party = ['-', 'M', 'FP', 'S', 'V', 'MP', 'KD', 'C']\n for i in range(10):\n for j in range(10):\n bestNr = 0\n bestAtt = None\n for attribute in range(nr_attributes):\n nr = grid[attribute][i][j]\n if nr > bestNr:\n bestNr = nr\n bestAtt = attribute\n if bestAtt == None:\n continue\n else:\n plt.scatter(i, j, color=color[bestAtt], s=2500)\n plt.text(\n i, j, party[bestAtt], horizontalalignment='center', verticalalignment='center', fontsize=14)\n plt.axes([0, 10, 0, 10])\n\n # GENDER\n data = []\n with open('/home/andrej/school/ann-course/lab2/mpsex.dat', 'r') as f:\n d = f.readlines()\n for i in d:\n k = i.rstrip().split(\",\")\n data.append([int(i) for i in k])\n partyData = np.array(data, dtype='O')\n\n plt.figure('Gender Comparision')\n plt.title('Gender Comparision')\n nr_attributes = 2\n grid = np.array([[[0]*10]*10]*nr_attributes)\n\n index = 0\n for winner in winnerIndexes:\n partyBelonging = partyData[index]\n grid[partyBelonging[0]][winner[0]][winner[1]] += 1\n index += 1\n\n color = ['blue', 'pink']\n # % Coding: Male 0, Female 1\n\n party = ['M', 'F']\n for i in range(10):\n for j in range(10):\n bestNr = 0\n bestAtt = None\n for attribute in range(nr_attributes):\n nr = grid[attribute][i][j]\n if nr > bestNr:\n bestNr = nr\n bestAtt = attribute\n if bestAtt == None:\n continue\n else:\n plt.scatter(i, j, color=color[bestAtt], s=2500)\n plt.text(\n i, j, party[bestAtt], horizontalalignment='center', verticalalignment='center', fontsize=14)\n plt.axes([0, 10, 0, 10])\n plt.grid()\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"RBF, CL, SOM/som_parlament.py","file_name":"som_parlament.py","file_ext":"py","file_size_in_byte":6090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"555557775","text":"\"\"\"\nTCP套接字客户端流程(重点代码)\n\"\"\"\nfrom socket import *\n\n# 1,创建流式套接字(socket)\nsockfd = socket()\n\n# 4,客户端请求连接服务端的网络地址(connect)\nsockfd.connect((\"127.0.0.1\",8888))\n\n# 循环<收发消息>\nwhile True:\n # 5,收发消息(recv/send)\n data = input(\"Msg>>\")\n \"\"\"\n 循环终止条件\n \"\"\"\n if not data: # 判空\n break\n n = sockfd.send(data.encode())\n print(\"客户端发送了%d字节\" % n)\n # data = sockfd.recv(1024)\n # print(\"客户端接收:\",data.decode())\n\n# 4,关闭流式套接字(close)\nsockfd.close()\n","sub_path":"2_4_CONCURRENT/day04_net_concurrent_IO/multiplexing/select_tcp_server_stdin/tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"148282770","text":"\"\"\"\nThis is an app.\n\"\"\"\nfrom flask import Flask\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\nfrom utils.database import Deal, DealProducts\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/hello')\ndef hello():\n return 'Hello, World'\n\n\n@app.route('/weee')\ndef weee():\n return \"\"\"\n {}\n \"\"\".format(\"\\n\".join(get_open_deal_products()))\n\n\ndef get_open_deal_products():\n deals = Deal.get_deals_by_status_and_type(status='open', deal_type='weee')\n lines = []\n for deal in deals:\n deal_products = deal.deal_products\n if deal_products is not None:\n deal_products.deal_products\n lines.append(deal_products.deal_products if deal_products is not None else \"\")\n\n return lines\n\nif __name__ == '__main__':\n handler = RotatingFileHandler(\n 'foo.log', maxBytes=1024 * 1024, backupCount=1)\n handler.setLevel(logging.INFO)\n app.logger.setLevel(logging.INFO)\n app.logger.addHandler(handler)\n app.run()\n","sub_path":"mifen/mifen.py","file_name":"mifen.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"532173508","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Anuj\n\"\"\"\n\n## Import packages\nfrom textblob import TextBlob\nimport pandas as pd\nimport numpy as np\n\n## Import data\ncsv_file = 'C:/Users/Anuj/Desktop/Evolent Assessment/BeerData.csv'\nbeer_data = pd.read_csv(csv_file, encoding = \"ISO-8859-1\")\n\n## Drop NA values\nbeer_data = beer_data.dropna(subset=['review_text'])\n\n## Narrow down relevent columns\ndf = beer_data[['review_text','beer_style','review_overall']]\n\n## Drop reviews below an overall rating of 4\nlow_rating = df[df['review_overall'] < 5 ].index\ndf.drop(low_rating , inplace=True)\n\nreindexed_data = df['review_text']\nreindexed_data.index = df['beer_style']\n\n## Use TextBlob for sentiment analysis\nblobs = [TextBlob(reindexed_data[i]) for i in range(reindexed_data.shape[0])]\npolarity = [blob.polarity for blob in blobs]\ndf['polarity'] = polarity\n\n## Make data frame for review text and sentiment\nsentiment_analysed = pd.DataFrame({'review_text':reindexed_data,\n 'polarity':polarity}, index=reindexed_data.index)\n\n## Group list by beer name and obtain overall average polarity\ng = df.groupby([\"beer_style\"])\npolarity_averages = g.aggregate({\"polarity\":np.mean})\n\n## Sort by overall average polarity from highest to lowest\ntop_beerstyle = polarity_averages.sort_values(by='polarity', ascending=False)\n\n## Print beers with highest average polarity\nprint(top_beerstyle.head())","sub_path":"BeerAssessment_5.py","file_name":"BeerAssessment_5.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"199768364","text":"# Copyright 2017 Google Inc.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom gapit_test_framework import gapit_test, require, require_equal, require_true\nfrom gapit_test_framework import require_not_equal, little_endian_bytes_to_int\nfrom gapit_test_framework import GapitTest, get_read_offset_function\nimport gapit_test_framework\nfrom struct_offsets import VulkanStruct, UINT32_T, FLOAT, ARRAY\nfrom vulkan_constants import *\n\nfrom array import array\n\nCOLOR_VALUE = [\n (\"float32\", ARRAY, 4, FLOAT)\n]\n\nSUBRESOURCE_RANGE = [\n (\"aspectMask\", UINT32_T),\n (\"baseMipLevel\", UINT32_T),\n (\"levelCount\", UINT32_T),\n (\"baseArrayLayer\", UINT32_T),\n (\"layerCount\", UINT32_T),\n]\n\n\n@gapit_test(\"vkCmdClearColorImage_test\")\nclass Clear2DColorImageSingleLayerSingleLevel(GapitTest):\n def expect(self):\n \"\"\"1. Expects vkCmdClearColorImage() is called and traced successfully.\"\"\"\n architecture = self.architecture\n clear_color_image = require(self.nth_call_of(\"vkCmdClearColorImage\", 1))\n require_not_equal(0, clear_color_image.int_commandBuffer)\n require_not_equal(0, clear_color_image.int_image)\n require_equal(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, clear_color_image.int_imageLayout)\n require_not_equal(0, clear_color_image.hex_pColor)\n require_equal(1, clear_color_image.int_rangeCount)\n require_not_equal(0, clear_color_image.hex_pRanges)\n\n color = VulkanStruct(\n architecture, COLOR_VALUE, get_read_offset_function(\n clear_color_image, clear_color_image.hex_pColor))\n require_true(\n array('f', [0.2 for i in range(4)]) ==\n array('f', color.float32))\n\n subresource_range = VulkanStruct(\n architecture, SUBRESOURCE_RANGE, get_read_offset_function(\n clear_color_image, clear_color_image.hex_pRanges))\n require_equal(VK_IMAGE_ASPECT_COLOR_BIT, subresource_range.aspectMask)\n require_equal(0, subresource_range.baseMipLevel)\n require_equal(1, subresource_range.levelCount)\n require_equal(0, subresource_range.baseArrayLayer)\n require_equal(1, subresource_range.layerCount)\n","sub_path":"gapid_tests/command_buffer_tests/vkCmdClearColorImage_test/vkCmdClearColorImage_test.py","file_name":"vkCmdClearColorImage_test.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"151338765","text":"\"\"\"\nThis module implements the repulsing supermartingale proof rule\n\"\"\"\n\nfrom diofant import symbols, sympify, simplify\n\nfrom . import bound_store\nfrom .asymptotics import is_dominating_or_same, Answer, dominating\nfrom .expression import get_cases_for_expression, split_expressions_on_rvs\nfrom .invariance import is_invariant\nfrom .rule import Rule, Result, Witness\nfrom .utils import amber_limit\n\n\nclass RepulsingSMRule(Rule):\n\n def is_applicable(self):\n n = symbols(\"n\", integer=True, positive=True)\n lim = amber_limit(self.loop_guard_change, n)\n return lim >= 0\n\n def run(self, result: Result):\n if result.PAST.is_known() and result.AST.is_known():\n return result\n\n # Martingale expression has to be <= 0 eventually\n if not is_invariant(self.martingale_expression, self.program):\n return result\n\n branches = get_cases_for_expression(sympify(self.program.loop_guard), self.program)\n if self.program.contains_rvs:\n branches = split_expressions_on_rvs(branches, self.program)\n branches = [simplify(branch - sympify(self.program.loop_guard)) for branch, _ in branches]\n bounds = [bound_store.get_bounds_of_expr(case) for case in branches]\n\n # Make sure that there is always a positive probability of having a next iteration\n if all([cb.maybe_negative for cb in bounds]):\n return result\n\n n = symbols(\"n\", integer=True, positive=True)\n cs = dominating([cb.absolute_upper for cb in bounds], n)\n epsilons = simplify(bound_store.get_bounds_of_expr(self.martingale_expression).upper * -1)\n\n # Epsilons and cs have to be bound by a constant\n if not is_dominating_or_same(sympify(1), epsilons, n):\n return result\n if not is_dominating_or_same(sympify(1), cs, n):\n return result\n\n # The epsilons have to grow more or equal to the cs\n if not is_dominating_or_same(sympify(0), epsilons, n) and is_dominating_or_same(epsilons, cs, n):\n result.PAST = Answer.FALSE\n result.AST = Answer.FALSE\n result.add_witness(NONASTWitness(\n sympify(self.program.loop_guard) * -1,\n self.martingale_expression,\n epsilons,\n cs\n ))\n elif is_dominating_or_same(sympify(0), epsilons, n) and is_dominating_or_same(sympify(1), cs, n):\n result.PAST = Answer.FALSE\n result.add_witness(NONPASTWitness(\n sympify(self.program.loop_guard) * -1,\n self.martingale_expression\n ))\n\n return result\n\n\nclass NONASTWitness(Witness):\n\n def __init__(self, repulsing_martingale, martingale_expression, epsilons, cs):\n super(NONASTWitness, self).__init__(\"Not AST\")\n repulsing_martingale = sympify(repulsing_martingale).as_expr()\n martingale_expression = sympify(martingale_expression).as_expr()\n epsilons = sympify(epsilons).as_expr()\n cs = sympify(cs).as_expr()\n self.data = {\n \"Repulsing SM\": repulsing_martingale,\n \"SM expression\": martingale_expression,\n \"Epsilons\": epsilons,\n \"Cs\": cs\n }\n self.explanation = f\"There is always a positive probability of having a next iteration.\\n\" \\\n f\"Moreover, '{repulsing_martingale}' eventually is a repulsing supermartingale\\n\" \\\n f\"decreasing with epsilons '{epsilons}'. Also, the repulsing SM has differences bound\\n\" \\\n f\"by '{cs}' which is O(epsilons).\"\n\n\nclass NONPASTWitness(Witness):\n\n def __init__(self, repulsing_martingale, martingale_expression):\n super(NONPASTWitness, self).__init__(\"Not PAST\")\n repulsing_martingale = sympify(repulsing_martingale).as_expr()\n martingale_expression = sympify(martingale_expression).as_expr()\n self.data = {\n \"Repulsing SM\": repulsing_martingale,\n \"SM expression\": martingale_expression,\n }\n self.explanation = f\"There is always a positive probability of having a next iteration.\\n\" \\\n f\"Moreover, '{repulsing_martingale}' eventually is a repulsing supermartingale\\n\" \\\n f\"decreasing with epsilons '0'. Also, the repulsing SM has differences bounded\\n\" \\\n f\"by a constant.\"\n","sub_path":"src/repulsing_sm_rule.py","file_name":"repulsing_sm_rule.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489725157","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 20 11:41:44 2021\n\n@author: user9\n\"\"\"\n\n# 온도 Data를 받아 DB에 저장하는 Client (0820_1 + 0810_4)\n\nimport socket\nimport datetime\nimport pymysql\n\n# DB 연결\nconn = pymysql.connect(host='127.0.0.1', user='python', password='12345678', db='test', charset='utf8')\ncursor = conn.cursor()\n\n# server 연결 및 소켓 생성\nHOST = '192.168.0.9'\nPORT = 9999 \n\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 객체 생성\n\nclient_socket.connect((HOST,PORT)) # 서버에 접속\n\nwhile True:\n \n data = client_socket.recv(1024)\n now = datetime.datetime.today()\n nowstr = now.strftime('%Y-%m-%d %H:%M:%S') \n # formating하여 str로 저장 (%Y:4자리year, %m:2자리month, %H:2자리hour,... )\n print(nowstr)\n rs = data.decode().split(sep=':') # ':'으로 문자열 split. List로 반환\n \n i=1\n for i in range(10):\n rs[i] = int(rs[i])\n print(rs)\n \n sql = \"INSERT INTO tblsensor VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n cursor.execute(sql, (nowstr, rs[0],rs[1],rs[2],rs[3],rs[4],rs[5],rs[6],rs[7],rs[8],rs[9]))\n conn.commit()\n \nclient_socket.close() \ncursor.close()\nconn.close()","sub_path":"spyder_python/06TCPIP/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361739640","text":"import wmi\nimport time\nimport json\n# import win32com\n\n\nclass PCHardwork(object):\n global s\n s = wmi.WMI()\n\n def get_CPU_info(self):\n cpu = []\n cp = s.Win32_Processor()\n for u in cp:\n cpu.append(\n {\n \"Name\": u.Name,\n \"Serial Number\": u.ProcessorId,\n \"CoreNum\": u.NumberOfCores,\n \"numOfLogicalProcessors\": u.NumberOfLogicalProcessors,\n \"timestamp\": time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime()),\n \"cpuPercent\": u.loadPercentage\n }\n )\n print(\":::CPU info:\", json.dumps(cpu, True, indent=4))\n return cpu\n\n def get_disk_info(self):\n disk = []\n for pd in s.Win32_DiskDrive():\n disk.append(\n {\n # 获取硬盘序列号,调用另外一个win32 API\n \"Serial\": s.Win32_PhysicalMedia()[0].SerialNumber.lstrip().rstrip(),\n \"ID\": 123456,\n \"Caption\": pd.Caption,\n \"size\": str(int(float(pd.Size) / 1024 / 1024 / 1024)) + \"G\"\n }\n )\n print(\":::Disk info:\", json.dumps(disk, True, indent=4))\n return disk\n\n def get_network_info(self):\n network = []\n for nw in s.Win32_NetworkAdapterConfiguration(IPEnabled=1):\n network.append(\n {\n \"MAC\": nw.MACAddress,\n \"ip\": nw.IPAddress\n }\n )\n print(\":::Network info:\", json.dumps(network, True, indent=4))\n return network\n\n def get_running_process(self):\n process = []\n for p in s.Win32_Process():\n process.append(\n {\n p.Name: p.ProcessId\n }\n )\n print(\":::Running process:\", json.dumps(process, True, indent=4))\n return process\n\n\n# 运行测试:\nPCinfo = PCHardwork()\nPCinfo.get_CPU_info()\nPCinfo.get_disk_info()\nPCinfo.get_network_info()\nPCinfo.get_running_process()\n","sub_path":"hard.py","file_name":"hard.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"460139666","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\n\nurl = ['https://knewone.com/?page={}'.format(str(i)) for i in range(1,11,1)]\n\ndef get_web_info(url,data=None):\n wb_data = requests.get(url)\n soup = BeautifulSoup(wb_data.text,'lxml')\n time.sleep(2)\n\n titles = soup.select('section.content > h4 > a')\n images = soup.select('a.cover-inner > img')\n links = soup.select('section.content > h4 > a')\n\n for title,image,link in zip(titles,images,links):\n data = {\n 'title':title.get('title'),\n 'image':image.get('src'),\n 'link':'https://knewone.com/'+link.get('href')\n }\n print(data)\n\nfor single_url in url:\n get_web_info(single_url)","sub_path":"exercise_bak/7_PythonSpider/week1/1.4_real_web_knewone/parse_knewone.py","file_name":"parse_knewone.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"53138583","text":"import requests\nfrom PIL import Image\nfrom io import BytesIO\nimport pandas as pd\nfrom pathlib import Path\n\n\nAPI_KEY = 'your api key here'\n\ndLat, dLong = 0.010122000000002629, 0.013259999999988281\n\ndf = pd.read_excel('Cities500.xlsx')\n\nno_of_cities = df.count()[0]\n\n# check if the file exists before creating new one\nmy_file = Path('ImageDetails.csv')\nif not(my_file.is_file()):\n \n image_name_list = []\n image_city = []\n image_state = []\n image_latitude = []\n image_longitude = []\n\n df3 = pd.DataFrame()\n\n df3['Image Name'] = image_name_list\n df3['City'] = image_city\n df3['State'] = image_state\n df3['Latitude'] = image_latitude\n df3['Longitude'] = image_longitude\n \n df3.to_csv('ImageDetails.csv', header=True, mode='a', index=False)\n\n\nfor city_no in range(no_of_cities):\n \n print(\"-------------------------- started city = \",city_no)\n\n image_count = 0\n \n \n image_name_list = []\n image_city = []\n image_state = []\n image_latitude = []\n image_longitude = []\n\n scale = df.Scale[city_no]\n Lat0 = df.Latitude[city_no]\n Long0 = df.Longitude[city_no]\n LatLong0 = str(Lat0) + ','+str(Long0)\n\n Lat1 = Lat0 + scale*dLat\n Long1 = Long0 - scale*dLong\n LatLong1 = str(Lat1) + ','+str(Long1)\n\n for i in range(int(scale+1)):\n for j in range(int(scale+1)):\n\n Lati = Lat1 - i*dLat\n Longi = Long1 + j*dLong\n LatLongi = str(Lati) + ','+str(Longi)\n\n image_name_list.append('city_no_'+ str(city_no) +'_image_number_'+str(image_count))\n image_count = image_count + 1\n image_city.append(df.City[city_no])\n image_state.append(df.State[city_no])\n image_latitude.append(Lati)\n image_longitude.append(Longi)\n\n ##############################################################################################\n\n roadmap_url = 'https://maps.googleapis.com/maps/api/staticmap?zoom=16&size=620x640&scale=2&maptype=roadmap¢er='+LatLongi+'&key='+API_KEY\n\n response = requests.get(roadmap_url) \n im = Image.open(BytesIO(response.content))\n image_name = 'city_no_'+ str(city_no) +'_roadmap_image_'+str(image_count)\n im.save('roadmap-images/'+image_name+'.png')\n\n ##############################################################################################\n\n satellite_url = 'https://maps.googleapis.com/maps/api/staticmap?zoom=16&size=620x640&scale=2&maptype=satellite¢er='+LatLongi+'&key='+API_KEY\n\n response = requests.get(satellite_url)\n im = Image.open(BytesIO(response.content))\n image_name = 'city_no_'+ str(city_no) +'_satellite_image_'+str(image_count)\n im.save('satellite-images/'+image_name+'.png')\n \n print(\"city_no = \", city_no,\" image_no = \", image_count)\n \n print(\"-------------------------- finished city = \",city_no)\n\n\n df3 = pd.DataFrame()\n\n df3['Image Name'] = image_name_list\n df3['City'] = image_city\n df3['State'] = image_state\n df3['Latitude'] = image_latitude\n df3['Longitude'] = image_longitude\n df3.to_csv('ImageDetails.csv', header=True, mode='a', index=False)\n\n","sub_path":"get_images.py","file_name":"get_images.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256865413","text":"# class Agent:\n# def __init__(self, group_id, x, y, ingroup_frac):\n# self.x, self.y = x, y\n# self.group_id = group_id\n\n# def is_satisfied(self, model):\n# pass\n\n\nfrom random import randint, choice, shuffle, uniform\nfrom math import floor, sqrt, ceil\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\nfrom itertools import product\n# class Model:\n\n# def __init__(self, n: int, a_prop: float, b_prop: float, ingroup_frac: float):\n# \"\"\"Init\n\n# Args:\n# n (int): grid size\n# a_prop (float): what percentage of pop is an A\n# b_prop (float): what percentage of pop is a B\n# ingroup_frac (float): [description]\n# \"\"\"\n# assert a_prop + b_prop <= 1\n# self.n, self.a_prop, self.b_prop, self.ingroup_frac = n, a_prop, b_prop, ingroup_frac\n# self.grid = [[None for _ in range(n)] for _ in range(n)]\n# a_count, b_count = 0, 0\n# while a_count < floor(self.n**2*self.a_prop):\n# shuffle(self.grid)\n# for sublist in self.grid:\n# shuffle(sublist)\n# if self.grid[0][0] is None:\n# self.grid[0][0] = 'A'\n# a_count += 1\n# while b_count < floor(self.n**2*self.b_prop):\n# shuffle(self.grid)\n# for sublist in self.grid:\n# shuffle(sublist)\n# if self.grid[0][0] is None:\n# self.grid[0][0] = 'B'\n# b_count += 1\n# print(self.all_satisfied())\n# # a_list, b_list = [], []\n# # for i in range(self.n):\n# # for j in range(self.n):\n# # new_id = choice(('A', 'B'))\n# # self.grid[i][j] = new_id\n# # if new_id == 'A':\n# # a_count += 1\n# # a_list.append((j, i))\n# # else:\n# # b_count += 1\n# # b_list.append((j, i))\n\n# # while a_count > floor(self.n*self.a_prop):\n# # shuffle(a_list)\n# # dead_x, dead_y = a_list.pop()\n# # self.grid[dead_y][dead_x] = None\n# # while b_count > floor(self.n*self.b_prop):\n# # shuffle(b_list)\n# # dead_x, dead_y = b_list.pop()\n# # self.grid[dead_y][dead_x] = None\n# # while a_count < self.n*self.a_prop:\n# # new_x, new_y = randint(0, self.n-1), randint(0, self.n-1)\n# # if self.grid[new_y][new_x] is None:\n# # self.grid[new_y][new_x] = 'A'\n# # while b_count < self.n*self.b_prop:\n# # new_x, new_y = randint(0, self.n-1), randint(0, self.n-1)\n# # if self.grid[new_y][new_x] is None:\n# # self.grid[new_y][new_x] = 'B'\n\n# def agent_satisfied(self, x, y):\n# agent_id = self.grid[y][x]\n# # print(agent_id, x, y)\n# neighbor_count = 0\n# sat_count = 0\n# for n_y in range(y-1, y+1):\n# for n_x in range(x-1, x+1):\n# in_bounds = 0 <= n_x <= self.n-1 and 0 <= n_y <= self.n-1\n# is_agent = x == n_x and y == n_y\n# # print(in_bounds, is_agent)\n# if in_bounds and not is_agent and self.grid[n_y][n_x] is not None:\n# sat_count = sat_count + \\\n# 1 if self.grid[n_y][n_x] == agent_id else sat_count\n# neighbor_count += 1\n# # print(neighbor_count, floor(self.ingroup_frac * neighbor_count))\n# return sat_count >= floor(self.ingroup_frac * neighbor_count)\n\n# def all_satisfied(self):\n# for i in range(self.n):\n# for j in range(self.n):\n# if self.grid[i][j] is not None and not self.agent_satisfied(j, i):\n# return False\n# return True\n\n# def plot(self):\n# plt.figure()\n# for i in range(self.n):\n# for j in range(self.n):\n# if self.grid[i][j] == 'A':\n# plt.plot(j, i, 'bo')\n# elif self.grid[i][j] == 'B':\n# plt.plot(j, i, 'go')\n# plt.show()\n\n\nclass Agent:\n\n def __init__(self, agent_id, agents, n, num_neighbors=10, prop_same=.3):\n self.agent_id = agent_id\n self.num_neighbors = num_neighbors\n self.draw_location(agents, n)\n self.num_same_req = floor(num_neighbors*prop_same)\n\n def draw_location(self, agents, n):\n # print(agents)\n # used_points = [a.location for a in agents]\n # # print(ceil(sqrt(n)))\n # all_points = list(product(range(ceil(sqrt(n))), repeat=2))\n # # print(len(all_points))\n # valid_points = list(\n # filter(lambda point: point not in used_points, all_points))\n # shuffle(valid_points)\n # print(valid_points)\n self.location = uniform(0, 1), uniform(0, 1)\n\n def get_distance(self, other):\n \"Computes the euclidean distance between self and other agent.\"\n a = (self.location[0] - other.location[0])**2\n b = (self.location[1] - other.location[1])**2\n return sqrt(a + b)\n\n def happy(self, agents):\n \"True if sufficient number of nearest neighbors are of the same agent_id.\"\n distances = []\n # distances is a list of pairs (d, agent), where d is distance from\n # agent to self\n for agent in agents:\n if self != agent:\n distance = self.get_distance(agent)\n distances.append((distance, agent))\n # == Sort from smallest to largest, according to distance == #\n # print(distances)\n distances.sort(key=lambda tup: tup[0])\n # == Extract the neighboring agents == #\n neighbors = [agent for d, agent in distances[:self.num_neighbors]]\n # == Count how many neighbors have the same agent_id as self == #\n num_same_type = sum(\n self.agent_id == agent.agent_id for agent in neighbors)\n return num_same_type >= self.num_same_req\n\n def update(self, agents, n):\n \"If not happy, then randomly choose new locations until happy.\"\n while not self.happy(agents):\n self.draw_location(agents, n)\n\n\nclass World:\n def __init__(self, n, zero_prop, one_prop, same_prop=.3):\n num_of_type_0 = floor(n*zero_prop)\n num_of_type_1 = floor(n*one_prop)\n self.n = n\n num_neighbors = 10 # Number of agents regarded as neighbors\n # require_same_type = 5 # Want at least this many neighbors to be same type\n # == Create a list of agents == #\n self.agents = []\n for _ in range(num_of_type_0):\n self.agents.append(\n Agent(0, self.agents, self.n, num_neighbors, same_prop))\n for _ in range(num_of_type_1):\n self.agents.append(\n Agent(1, self.agents, self.n, num_neighbors, same_prop))\n\n def plot_distribution(self, cycle_num):\n \"Plot the distribution of agents after cycle_num rounds of the loop.\"\n x_values_0, y_values_0 = [], []\n x_values_1, y_values_1 = [], []\n # == Obtain locations of each type == #\n for agent in self.agents:\n x, y = agent.location\n if agent.agent_id == 0:\n x_values_0.append(x)\n y_values_0.append(y)\n else:\n x_values_1.append(x)\n y_values_1.append(y)\n fig, ax = plt.subplots(figsize=(8, 8))\n plot_args = {'markersize': 8, 'alpha': 0.6}\n ax.set_facecolor('azure')\n ax.plot(x_values_0, y_values_0, 'o',\n markerfacecolor='orange', **plot_args)\n ax.plot(x_values_1, y_values_1, 'o',\n markerfacecolor='green', **plot_args)\n ax.set_title(f'Cycle {cycle_num}')\n plt.show()\n\n def loop(self):\n count = 1\n # == Loop until none wishes to move == #\n self.plot_distribution(count)\n\n while True:\n print('Entering loop ', count)\n count += 1\n no_one_moved = True\n for agent in self.agents:\n old_location = agent.location\n agent.update(self.agents, self.n)\n if agent.location != old_location:\n no_one_moved = False\n if no_one_moved:\n break\n self.plot_distribution(count)\n print('Converged, terminating.')\n\n\ndef empty_idxs(lst):\n return [i for i in range(len(lst)) if lst[i] == '_']\n\n\ndef total_neighbors(idx, lst):\n n_count = 0\n if idx > 0 and lst[idx-1] != '_':\n n_count += 1\n if idx < len(lst)-1 and lst[idx+1] != '_':\n n_count += 1\n return n_count\n\n\ndef group_count(idx: int, group_type: str, lst) -> int:\n g_count = 0\n if idx > 0 and lst[idx-1] == group_type:\n g_count += 1\n if idx < len(lst)-1 and lst[idx+1] == group_type:\n g_count += 1\n return g_count\n\n\ndef dist_to_group(idx: int, group_type: str, lst):\n \"\"\"\n A version of group_count that allows for sorting with solo agents\n Sometimes entities don't have immediately adjacent neighbors. \n In that case, the value represents the distance to any neighbor, e.g\n -1 means that an entity one to the left or right has a neighbor of that type.\n\n Args:\n idx (int):index in the list\n group_type (str):group type we care about matching\n lst ([type]): [description]\n \"\"\"\n my_count = group_count(idx, group_count, lst)\n if my_count > 0:\n return my_count\n adjacent_counts = []\n l_neighbor_count = dist_to_group(idx-1, group_type, lst) if idx > 0 else None\n r_neighbor_count = dist_to_group(idx+1, group_type, lst) if idx < len(lst)-1 else None\n for neighbor_count in (l_neighbor_count, r_neighbor_count):\n if neighbor_count != 0:\n if neighbor_count < 0 and neighbor_count is not None: #The neighbor doesn't have any next directly to it either \n adjacent_counts.append(neighbor_count - 1)\n else: #The neighbor does have one next to it!\n adjacent_counts.append(neighbor_count) \n return max(adjacent_counts)\n\n\ndef swap(idx: int, idy: int, lst: list):\n \"\"\"Swap in place the values at idx and idy\n\n Args:\n idx (int): first index\n idy (int): second index\n lst (list): the list\n \"\"\"\n temp = lst[idx]\n lst[idx] = lst[idy]\n lst[idy] = temp\n\n\n# def move(idx, members_lst):\n# if members_lst[idx] == 'A':\n# current_b = other_neighbor_count(idx, members_lst)\n# # print(current_b)\n# for e_idx in empty_idxs(members_lst):\n# # print(e_idx)\n# empty_b_count = other_neighbor_count(e_idx, members_lst)\n# # print(empty_b_count)\n# if empty_b_count < current_b:\n# swap(e_idx, idx, members_lst)\n# current_b = empty_b_count\n# if members_lst[idx] == 'B':\n# current_n = total_neighbors(idx, members_lst)\n# for e_idx in empty_idxs(members_lst):\n# empty_n_count = total_neighbors(e_idx, members_lst)\n# if empty_n_count > current_n:\n# swap(e_idx, idx, members_lst)\n# current_n = empty_n_count\n# def stable_alignment(members_lst: [str]) -> bool:\n# for member in members_lst:\n\n\ndef avoid_others(idx, members_lst):\n other_type = 'B' if members_lst[idx] == 'A' else 'A'\n current_others = group_count(idx, other_type, members_lst)\n # print(current_b)\n # for e_idx in empty_idxs(members_lst):\n # # print(e_idx)\n # empty_others_count = other_neighbor_count(\n # e_idx, other_type, members_lst)\n # # print(empty_b_count)\n # if empty_others_count < current_others:\n # swap(e_idx, idx, members_lst)\n # current_others = empty_others_count\n empty_others_counts = [(e_idx, dist_to_group(\n e_idx, other_type, members_lst)) for e_idx in empty_idxs(members_lst)]\n empty_others_counts = sorted(\n empty_others_counts, key=lambda tup: tup[1])\n print(members_lst[idx], empty_others_counts)\n if empty_others_counts[0][1] < current_others:\n swap(idx, empty_others_counts[0][0], members_lst)\n\n\ndef increase_ingroup(idx, members_lst):\n current_ingroup_count = group_count(idx, members_lst[idx], members_lst)\n empty_ingroup_counts = [(e_idx, dist_to_group(\n e_idx, members_lst[idx], members_lst)) for e_idx, val in enumerate(empty_idxs(members_lst))]\n empty_ingroup_counts = sorted(\n empty_ingroup_counts, key=lambda tup: tup[1], reverse=True)\n if empty_ingroup_counts[0][1] < current_ingroup_count:\n swap(idx, empty_ingroup_counts[0][0], members_lst)\n\n\ndef move_all(members_lst):\n print(members_lst)\n past_lst = deepcopy(members_lst)\n for member_idx in range(len(members_lst)):\n if past_lst[member_idx] != '_':\n avoid_others(member_idx, members_lst)\n print(members_lst)\n past_lst = deepcopy(members_lst)\n\n\ndef schelling(members_str):\n runtime = 0\n members = list(members_str)\n old_lst = []\n while old_lst != members:\n old_lst = deepcopy(members)\n move_all(members)\n runtime += 1\n if runtime > 100:\n print(\"There may not be a stable arrangement\")\n break\n\n\nif __name__ == \"__main__\":\n schelling(['A', 'B', 'A', 'B', 'A', 'B', '_', '_', '_'])\n # num_of_type_0 = 250\n # num_of_type_1 = 250\n # num_neighbors = 10 # Number of agents regarded as neighbors\n # require_same_type = 5 # Want at least this many neighbors to be same type\n\n # # == Create a list of agents == #\n # agents = [Agent(0) for i in range(num_of_type_0)]\n # agents.extend(Agent(1) for i in range(num_of_type_1))\n\n # count = 1\n # # == Loop until none wishes to move == #\n # while True:\n # print('Entering loop ', count)\n # plot_distribution(agents, count)\n # count += 1\n # no_one_moved = True\n # for agent in agents:\n # old_location = agent.location\n # agent.update(agents)\n # if agent.location != old_location:\n # no_one_moved = False\n # if no_one_moved:\n # break\n\n # print('Converged, terminating.')\n","sub_path":"PS1/schelling.py","file_name":"schelling.py","file_ext":"py","file_size_in_byte":14314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"305713457","text":"from configparser import ConfigParser\nimport sqlalchemy as db\nimport pandas as pd\nfrom datetime import datetime as dt\nimport numpy as np\n\n\nclass time_to_close(object):\n def __init__(self, config=None, requestTypes=None, tableName=\"ingest_staging_table\"):\n \"\"\"\n Choose table from database by setting the value of tableName. Default table is the staging table.\n \"\"\"\n self.config = config\n self.dbString = None if not self.config else self.config['Database']['DB_CONNECTION_STRING']\n self.table = tableName\n self.data = None\n pass\n\n def ttc_view_columns(self):\n \"\"\"\n Returns all the columns' names\n \"\"\"\n engine = db.create_engine(self.dbString)\n\n df = pd.read_sql_query(\"SELECT * FROM %s\" % self.table, con=engine)\n\n self.data = df\n\n return df\n\n def ttc_view_table(self, onlyClosed=False):\n \"\"\"\n Returns all entries\n Returns only those with Status as 'Closed' if onlyClosed is set to True\n \"\"\"\n engine = db.create_engine(self.dbString)\n\n # The following directly converts SQL data to json objects; for consistency, this function first converts the SQL data to pandas dataframe\n # connection = engine.connect()\n # query = \"SELECT row_to_json(ingest_staging_table) \\\n # FROM ingest_staging_table\"\n # result = connection.execute(query)\n # connection.close()\n\n if onlyClosed:\n df = pd.read_sql_query(\n \"SELECT * FROM %s WHERE Status = 'Closed'\" % self.table, con=engine)\n else:\n df = pd.read_sql_query(\"SELECT * FROM %s\" % self.table, con=engine)\n\n return df.to_json(orient='index')\n\n def ttc_view_dates(self, serviced=False):\n \"\"\"\n Returns all rows under the CreatedDate and ClosedDate columns in human-readable format\n Returns all rows with a service date under CreatedDate, ClosedDate, and ServicedDate columns if serviced is True\n \"\"\"\n engine = db.create_engine(self.dbString)\n\n if serviced:\n df = pd.read_sql_query(\n \"SELECT createddate, closeddate, servicedate FROM %s\" % self.table, con=engine)\n df = df[df['servicedate'].notnull()]\n else:\n df = pd.read_sql_query(\n \"SELECT createddate, closeddate FROM %s\" % self.table, con=engine)\n\n df['createddate'] = df['createddate'].apply(\n lambda x: x.strftime('%m/%d/%Y %I:%M:%S %p'))\n\n return df.to_json(orient='index')\n\n def ttc_time_diff(self, serviced=False, all=False):\n \"\"\"\n Returns the average time in days or hours for a specific request type to be completed\n \"\"\"\n engine = db.create_engine(self.dbString)\n\n if serviced:\n df = pd.read_sql_query(\n \"SELECT createddate, closeddate, servicedate FROM %s\" % self.table, con=engine)\n df = df[df['servicedate'].notnull()]\n df['servicedate'] = pd.to_datetime(df['servicedate'])\n diff_df = pd.DataFrame(\n df['servicedate'] - df['createddate'], columns=['time_to_service'])\n else:\n df = pd.read_sql_query(\n \"SELECT createddate, closeddate FROM %s\" % self.table, con=engine)\n diff_df = pd.DataFrame({'time_to_close': []})\n\n df['createddate'] = pd.to_datetime(df['createddate'])\n df['closeddate'] = pd.to_datetime(df['closeddate'])\n diff_df['time_to_close'] = df['closeddate'] - df['createddate']\n\n def dt_to_days(dt):\n num_days = pd.Timedelta.total_seconds(dt)/(24.*3600)\n if num_days <= .000001:\n return 0\n return pd.Timedelta.total_seconds(dt)/(24.*3600)\n\n diff_df['time_to_close'] = diff_df.time_to_close.apply(dt_to_days) \n diff_df['time_to_service'] = diff_df.time_to_service.apply(dt_to_days) \n \n ### Todo: Convert unix time to strings displaying days\n ### Todo: Return averages and min/max\n ### Todo: Implement function for considering request type\n\n return diff_df.to_json(orient='index')\n\nif __name__ == \"__main__\":\n ttc = time_to_close()\n config = ConfigParser()\n config.read(\"../setting.cfg\")\n ttc.config = config\n ttc.dbString = config['Database']['DB_CONNECTION_STRING']\n ttc.ttc_view_table()\n","sub_path":"server/src/services/time_to_close.py","file_name":"time_to_close.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633730430","text":"#LSTM두개 구현\n#삼성전자\n#hite는 lstm은 시계열 모델 아니다. 왜냐면 거래량 이런것이 있기 때문\n#samsung은 lstm가능\n#pca로 hite축소(n*1로 줄이기)\n#삼성(n*1)=하이트(n*1)\nimport numpy as np\nfrom keras.models import Model,Input\nfrom keras.layers import Dense, LSTM, Dropout\nfrom keras.layers.merge import Concatenate, concatenate\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\nfrom sklearn.decomposition import PCA\n\n\ndef split_x(seq,size):\n aaa=[]\n for i in range(len(seq)-size+1):\n subset=seq[i:(i+size)] #행 구성\n aaa.append([item for item in subset]) #subset에 있는 아이템을 반환\n print(type(aaa))\n return np.array(aaa)\n\nsize=6\n\n# 1.데이터\n# npy불러오기\nsamsung=np.load('./data/samsung.npy',allow_pickle=True)\nhite=np.load('./data/hite.npy',allow_pickle=True)\n\n\nprint(\"samsung.shape:\",samsung.shape) #shape=(509,1)\nprint(\"hite.shape:\",hite.shape)\n\nsamsung=samsung.reshape(samsung.shape[0],) #shape=(509,) \nsamsung=(split_x(samsung,size))\nprint(\"samsung.shape:\",samsung.shape)\n#samsung만 x, y분리해주면 된다\n#hite는 x만 필요\n\n#데이터 자르기\nx_sam=samsung[:,0:5]\nprint(x_sam.shape) #(504,5)\ny_sam=samsung[:,5]\nprint(y_sam.shape)#(504,)\n\nx_sam=x_sam.reshape(504,5,1)\n\nx_hite=hite\nx_hite=StandardScaler().fit_transform(x_hite)\n\npca=PCA(n_components=1) #주성분 개수\ntrans_x_hite=pca.fit_transform(x_hite)\n\nprint(\"trans.shpe:\",trans_x_hite.shape)\n\ntrans_x_hite=(split_x(trans_x_hite,size))\n\nprint(trans_x_hite.shape)\n\ntrans_x_hite=trans_x_hite[:,0:5]\n\nprint(trans_x_hite.shape) #(504,5,1)\n\nx_sam_train,x_sam_test,y_sam_train,y_sam_test, trans_x_hite_train,trans_x_hite_test=train_test_split(x_sam,y_sam,trans_x_hite,test_size=0.2,random_state=60)\n\n#2. 모델 구성\ninput1=Input(shape=(5,1)) # 변수명은 소문자(암묵적약속)\ndense1_1=LSTM(30,activation='relu',name='A1')(input1) #input명시해주어야 함\ndense1_2=Dense(40,activation='relu',name='A2')(dense1_1)\ndense1_2=Dense(40,activation='relu',name='A2')(dense1_1)\ndense1_2=Dense(40,activation='relu',name='A2')(dense1_1)\ndense1_2=Dense(50,activation='relu',name='A2')(dense1_1)\ndense1_3=Dense(40,activation='relu',name='A3')(dense1_2)\ndense1_4=Dense(30,activation='relu',name='A4')(dense1_3)\n\n#두번쨰 모델(2)\ninput2=Input(shape=(5,1)) \ndense2_1=LSTM(30,activation='relu',name='B1')(input2) \ndense1_2=Dense(40,activation='relu',name='A2')(dense1_1)\ndense1_2=Dense(40,activation='relu',name='A2')(dense1_1)\ndense1_2=Dense(40,activation='relu',name='A2')(dense1_1)\ndense2_2=Dense(40,activation='relu',name='B2')(dense2_1)\ndense2_2=Dense(40,activation='relu',name='B2')(dense2_1)\ndense2_2=Dense(40,activation='relu',name='B2')(dense2_1)\ndense2_2=Dense(40,activation='relu',name='B2')(dense2_1)\ndense2_2=Dense(40,activation='relu',name='B2')(dense2_1)\ndense2_3=Dense(30,activation='relu',name='B3')(dense2_2)\ndense2_4=Dense(20,activation='relu',name='B4')(dense2_3)\n\n# 엮어주는 기능(첫번째 모���과 두번째 모델)(3) #concatenate-사슬 같이 잇다, 단순병합\nfrom keras.layers.merge import concatenate\nmerge1=concatenate([dense1_4,dense2_4],name='merge1') #두 개 이상은 항상 리스트('[]')\n\n# 또 레이어 연결(3)\nmiddle1=Dense(10)(merge1)\nmiddle1=Dense(15)(middle1)\nmiddle1=Dense(15)(middle1)\nmiddle1=Dense(10)(middle1)\n\n# 엮은 거 다시 풀어준다(output도 2개 나와야하니까) ---분리(4)\n# input=middle1(상단 레이어의 이름)\noutput1=Dense(10,name='o1')(middle1)\noutput1_2=Dense(70,name='o1_2')(output1)\noutput1_3=Dense(30,name='o1_3')(output1_2) \noutput1_4=Dense(30,name='o1_4')(output1_3) \noutput1_5=Dense(1,name='o1_5')(output1_4) \n\n\n#함수형 지정(제일 하단에 명시함)\nmodel=Model(inputs=[input1,input2], outputs=output1_5) # 범위 명시 #함수형은 마지막에 선언 #두 개 이상은 리스트\n\nmodel.summary()\n\n#3. 컴파일, 훈련\n# 앙상블은 행이 맞아야 한다. \nmodel.compile(optimizer='adam',loss='mse',metrics=['mse'])\nfrom keras.callbacks import EarlyStopping\nearly_stopping=EarlyStopping(monitor='loss',patience=10, mode='aut')\nmodel.fit([x_sam_train,trans_x_hite_train],y_sam_train,epochs=10,batch_size=1,callbacks=[early_stopping])\n\nloss,acc=model.evaluate([x_sam_test,trans_x_hite_test],y_sam_test,batch_size=1)\ny_predict=model.predict([x_sam_test,trans_x_hite_test])\nprint(\"y_predict:\",y_predict)\n\nfor i in range(5):\n print(\"종가:\",x_sam_test[i],'/예측가:',y_predict[i])\n","sub_path":"test_samsung/test0602_model4.py","file_name":"test0602_model4.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"345785225","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 14 19:03:24 2021\r\n\r\n@author: DELL\r\n\"\"\"\r\n\r\nimport sys\r\nimport pygame as py\r\nfrom settings import Settings\r\nimport floor\r\n\r\nclass Gameover:\r\n def __init__(self):\r\n py.init()\r\n self.settings = Settings()\r\n self.clock = py.time.Clock()\r\n self.screen = py.display.set_mode(\r\n (self.settings.screen_width, self.settings.screen_height))\r\n py.display.set_caption('Flappy Bird')\r\n \r\n self.background = py.image.load('images/background2.png')\r\n self.gameover_image = py.image.load('images/gameover.png')\r\n \r\n self.gameover_x = (self.settings.screen_width-self.gameover_image.get_width())/2\r\n self.gameover_y = (self.settings.floor_pos-self.gameover_image.get_height())/2\r\n #self.frame = 0\r\n \r\n def execute(self):\r\n while True:\r\n for event in py.event.get():\r\n if event.type ==py.QUIT:\r\n py.quit()\r\n sys.exit()\r\n if event.type == py.KEYDOWN and event.key == py.K_SPACE:\r\n return\r\n if event.type == py.MOUSEBUTTONDOWN:\r\n if py.mouse.get_pressed(3) == (1,0,0):\r\n return\r\n \r\n self.screen.blit(self.background, (0,0))\r\n floor.load_floor(self)\r\n self.screen.blit(self.gameover_image,(self.gameover_x,self.gameover_y))\r\n #self.screen.blit(self.bird_image, (self.settings.screen_width*0.2,self.settings.screen_height/2))\r\n py.display.flip()\r\n self.clock.tick(self.settings.fps)\r\n ","sub_path":"gameover.py","file_name":"gameover.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"614518367","text":"import tweepy\nfrom tweepy import OAuthHandler\nfrom tweepy.streaming import StreamListener\nimport configparser\n\n\ndef loadtwitterinfo():\n cfg = configparser.ConfigParser()\n cfg.read('twitterinfo.ini')\n\n info = {}\n options = cfg.options('Twitter Info')\n for option in options:\n try:\n info[option] = cfg.get('Twitter Info', option)\n except KeyError:\n info[option] = None\n return info\n\ntwitterInfo = loadtwitterinfo()\n\n\nclass Listener(StreamListener):\n\n def on_data(self, data):\n print(data)\n return True\n\n def on_error(self, status):\n print(status)\n\nauth = OAuthHandler(twitterInfo['consumer_key'], twitterInfo['consumer_secret'])\nauth.set_access_token(twitterInfo['access_token'], twitterInfo['access_secret'])\n\napi = tweepy.API(auth)\nprint(api.user_timeline('NBAcom')[0].text)\n# twitterStream = Stream(auth, Listener())\n# twitterStream.filter(track=[\"nba\"])\n\n","sub_path":"TwitterNews.py","file_name":"TwitterNews.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"373468835","text":"import unittest\nimport tarfile\nimport os\nfrom PyExpUtils.utils.archive import getArchiveName, inArchive\n\nclass TestArchive(unittest.TestCase):\n def test_getArchiveName(self):\n path = 'test/path/thing'\n\n got = getArchiveName(path)\n expected = 'test.tar'\n\n self.assertEqual(got, expected)\n\n def test_inArchive(self):\n with open('inArchive.txt', 'w') as f:\n f.write('hey there')\n\n with tarfile.open('inArchive.tar', 'w') as tar:\n tar.add('inArchive.txt')\n\n got = inArchive('inArchive.tar', 'inArchive.txt')\n self.assertTrue(got)\n\n got = inArchive('inArchive.tar', 'notInArchive.txt')\n self.assertFalse(got)\n\n got = inArchive('notAnArchive.tar', 'inArchive.txt')\n self.assertFalse(got)\n\n os.remove('inArchive.tar')\n os.remove('inArchive.txt')\n","sub_path":"tests/utils/test_archive.py","file_name":"test_archive.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"600542844","text":"from optimizer import Interface_optimizer\nimport numpy as np\nfrom functools import partial\n\nclass MCMC(Interface_optimizer):\n def __init__(self, sigma, PI=None, lambd=1e-3, iter_mcmc=1):\n Interface_optimizer.__init__(self)\n self.lambd=lambd\n self.fx=None\n\n if PI is None:\n def PI(x,sigma):\n return np.random.normal(x,sigma)\n self.init_sigma=sigma\n self.sigma=sigma\n self.PI=PI\n\n self.last_it_accept=0\n self.iter_mcmc=iter_mcmc\n\n\n def run_one_step(self,x,function_to_min):\n #if self.fx is None: # first time\n self.fx=function_to_min.f(x)\n\n\n self.last_it_accept=0\n\n for i in range(self.iter_mcmc):\n xp = self.PI(x,sigma=self.sigma)\n fx_prop = function_to_min.f(xp)\n\n # accept or reject ?\n #accept_rate = -self.lambd * (fx_prop - self.fx)\n #accept = np.log(np.random.uniform(0., 1.)) < accept_rate\n accept = fx_prop < self.fx\n\n # update x\n if accept:\n x = xp\n self.fx=fx_prop\n self.last_it_accept+=1\n\n accept_rate=self.last_it_accept / self.iter_mcmc\n if accept_rate <= 0.001:\n self.sigma*=0.1\n print(\"sigma=\" + str(self.sigma))\n\n return x\n\n def next_batch(self):\n \"\"\"\n When we change batch we must reset self.fx to not compare loss between two different batch\n :return:\n \"\"\"\n self.fx=None\n def reset_sigma(self):\n self.sigma=self.init_sigma\n print(\"sigma=\" + str(self.sigma))","sub_path":"optimizer/MCMC.py","file_name":"MCMC.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"417230359","text":"from domain.ValidatorException import ValidatorException\n\nclass Car:\n def __init__(self, objectId, licenseNumber, make, model):\n self._id = objectId\n self._license = licenseNumber\n self._make = make\n self._model = model\n\n @property\n def id(self):\n return self._id\n\n @property\n def license(self):\n return self._license\n\n @property\n def make(self):\n return self._make\n\n @property\n def model(self):\n return self._model\n \n def __eq__(self, z):\n if isinstance(z, Car) == False:\n return False\n return self.id == z.id\n\n def __str__(self):\n return \"Id: \" + str(self.id) + \", License: \" + self.license + \", Car type: \" + self.make + \", \" + self.model\n\n def __repr__(self):\n return str(self)\n\nclass CarValidator:\n \n def __init__(self):\n # and so on...\n self.__counties = [\"AB\", \"B\", \"CJ\"]\n self._errors = \"\"\n\n def _licensePlateValid(self, plate):\n token = str(plate).split(' ')\n if len(token) != 3:\n return False\n if token[0] not in self.__counties:\n return False\n try:\n n = int(token[1])\n if len(token[1]) < 2 or len(token[1]) > 3:\n return False\n if n < 1 or n > 999:\n return False\n if n > 99 and token[0] != \"B\":\n return False\n except TypeError:\n return False\n if len(token[2]) != 3:\n return False\n tu = str(token[2]).upper()\n if tu[0] in ['I', 'O']:\n return False\n for x in tu:\n if x < 'A' or x > 'Z':\n return False\n if x == 'Q':\n return False\n return True\n\n def validate(self, car):\n \"\"\"\n Validate if provided Car instance is valid\n car - Instance of Car type\n Return List of validation errors. An empty list if instance is valid.\n \"\"\"\n if isinstance(car, Car) == False:\n raise TypeError(\"Can only validate Car objects!\")\n _errors = []\n if len(car.make) == 0:\n _errors.append(\"Car must have x make\")\n if len(car.model) == 0:\n _errors.append(\"Car must have x model;\")\n if self._licensePlateValid(car.license) == False:\n _errors.append(\"Bad license plate number;\")\n if len(_errors) > 0:\n raise ValidatorException(_errors)\n return True","sub_path":"An1_sem1/Python/Seminar/Seminar 9/Prj2/seminar/domain/Car.py","file_name":"Car.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62206801","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^about/$', views.about, name='about'),\n url(r'^contact/$', views.contact, name='contact'),\n url(r'^articles/(?P[0-9]+)/$', views.show_article, name='show_article'),\n url(r'^json/(?P[0-9]+)/$', views.home_json, name='home_json'),\n\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"185988021","text":"#coding=utf-8\nu'''\n#文件名:\n#被测软件版本号:V2.8.1\n#作成人:张利娟\n#生成日期:2018/1/31\n#模块描述:密码信封\n#历史修改记录\n#修改人:\n#修改日期:\n#修改内容:\n'''\nimport sys,time\nreload(sys)\nsys.setdefaultencoding('utf-8')\n#导入通用模块\nsys.path.append(\"/testIsomp/common/\")\nfrom _initDriver import *\nfrom _icommon import getElement,selectElement,commonFun,frameElement\nfrom _cnEncode import cnEncode\n\nclass EnvelopePage(object):\n #浏览按钮\n LOGOIMAGE = \"logoImage\"\n #上传按钮\n SAVE_IMAGES_BUTTON = \"save_images_button\"\n #同步按钮\n IMAGESELECT = \"imagesSelect\"\n #信封抬头\n COMPANY = \"company\"\n #打印服务器IP\n SERVERIP = \"serverIp\"\n #打印服务器监听端口\n SERLISPORT = \"serverListenerPort\"\n #打印服务器文件监听端口\n FILELISPORT = \"fileListenerPort\"\n #保存按钮\n SAVE_METHOD = \"save_method\"\n #同步图片ID\n IMAGEONESPAN = \"imageOneSpan\"\n\n def __init__(self, driver):\n self.driver = driver\n self.getElem = getElement(driver)\n self.selectElem = selectElement(driver)\n self.frameElem = frameElement(driver)\n self.cmf = commonFun(driver)\n self.cnEn = cnEncode()\n\n u'''点击保存按钮'''\n def envelope_save(self):\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_click_EC(\"id\", self.SAVE_METHOD)\n except Exception:\n print(\"Click the save button is error\")\n\n u'''上传操作\n\t\tparameters:\n\t\t\t- fileurl :上传图片路径\n\t'''\n def envelope_upload(self,fileurl):\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_sendkeys(\"id\", self.LOGOIMAGE, fileurl)\n time.sleep(2)\n self.getElem.find_element_wait_and_click_EC(\"id\", self.SAVE_IMAGES_BUTTON)\n self.frameElem.switch_to_content()\n self.cmf.click_msg_button(1)\n except Exception:\n print(\"upload passwd envelope image is error\")\n\n\n u'''同步操作'''\n def envelope_sync(self):\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_click_EC(\"id\", self.IMAGESELECT)\n time.sleep(3)\n self.getElem.find_element_wait_and_click_EC(\"id\", self.IMAGEONESPAN)\n except Exception:\n print(\"passwd envelope images sync is error\")\n\n u'''发送公司(信封抬头)\n \tParameters:\n\t -sendcompany 公司(信封抬头)\n '''\n def envelope_company(self, sendcompany):\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_clear_EC(\"id\", self.COMPANY)\n self.getElem.find_element_wait_and_sendkeys(\"id\", self.COMPANY, sendcompany)\n except Exception:\n print(\"passwd envelope company is error\")\n\n u'''发送打印服务器IP\n\t Parameters:\n\t -sendserverip 打印服务器IP\n '''\n def envelope_server_ip(self, sendserverip):\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_clear_EC(\"id\", self.SERVERIP)\n self.getElem.find_element_wait_and_sendkeys(\"id\", self.SERVERIP, sendserverip)\n except Exception:\n print(\"server ip is error\")\n\n u'''发送打印服务器监听端口\n\t Parameters:\n\t -sendserverport 打印服务器端口\n '''\n def envelope_server_port(self, sendserverport):\n sendserverport = self.cnEn.is_float(sendserverport)\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_clear_EC(\"id\", self.SERLISPORT)\n self.getElem.find_element_wait_and_sendkeys(\"id\", self.SERLISPORT, sendserverport)\n except Exception:\n print(\"server port is error\")\n\n u'''发送打印服务器文件监听端口\n\t Parameters:\n\t -sendfileport 打印服务器文件监听端口\n '''\n def envelope_file_port(self, sendfileport):\n sendfileport = self.cnEn.is_float(sendfileport)\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_clear_EC(\"id\", self.FILELISPORT)\n self.getElem.find_element_wait_and_sendkeys(\"id\", self.FILELISPORT, sendfileport)\n except Exception:\n print(\"file port is error\")\n\n u'''清空数据-->进行校验测试'''\n def envelope_empty(self):\n try:\n self.frameElem.from_frame_to_otherFrame(\"rigthFrame\")\n self.getElem.find_element_wait_and_clear_EC(\"id\",self.COMPANY)\n self.getElem.find_element_wait_and_clear_EC(\"id\",self.SERVERIP)\n self.getElem.find_element_wait_and_clear_EC(\"id\",self.SERLISPORT)\n self.getElem.find_element_wait_and_clear_EC(\"id\",self.FILELISPORT)\n except Exception:\n print(\"envelope empty is error\")\n\n u'''左边框点击密码信封'''\n def click_left_moudle_envelope(self):\n self.frameElem.from_frame_to_otherFrame(\"leftFrame\")\n time.sleep(2)\n self.getElem.find_element_wait_and_click_EC(\"id\", \"url3\")\n time.sleep(2)","sub_path":"webElement/passwd_envelope/test_passwd_envelope_ment.py","file_name":"test_passwd_envelope_ment.py","file_ext":"py","file_size_in_byte":5357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"112550863","text":"# -*- coding: utf-8 -*-\n##########################################################################\n#\n# Copyright (c) 2015-Present Webkul Software Pvt. Ltd. ()\n# See LICENSE file for full copyright and licensing details.\n# License URL : \n#\n##########################################################################\n\nfrom odoo import api, models\n\n\nclass MagentoSynchronization(models.TransientModel):\n _inherit = \"magento.synchronization\"\n\n #############################################\n ## Export Attributes and values ##\n #############################################\n\n @api.multi\n def export_attributes_and_their_values(self):\n displayMessage = ''\n attributeCount = 0\n attributeModel = self.env['product.attribute']\n attributeMappingModel = self.env['magento.product.attribute']\n valueMappingModel = self.env['magento.product.attribute.value']\n connection = self.env['magento.configure']._create_connection()\n if connection:\n url = connection[0]\n token = connection[1]\n ctx = dict(self._context or {})\n ctx['instance_id'] = instanceId = connection[2]\n attributeMapObjs = attributeMappingModel.with_context(\n ctx).search([('instance_id', '=', instanceId)])\n mapDict = dict(attributeMapObjs.mapped(lambda mapObj: \\\n (mapObj.erp_id,[mapObj.mage_id,mapObj.mage_attribute_code])))\n mapArray = mapDict.keys()\n attributeObjs = attributeModel.search([])\n if attributeObjs:\n for attributeObj in attributeObjs:\n odooId = attributeObj.id\n if odooId not in mapArray:\n name = attributeObj.name\n attributeCode = name.lower().replace(\" \", \"_\").replace(\"-\", \"_\")[:29]\n attributeCode = attributeCode.strip()\n label = attributeObj.name\n attributeResponse = self.with_context(ctx).create_product_attribute(\n url, token, odooId, attributeCode, label)\n else:\n mapData = mapDict.get(odooId)\n mageId = mapData[0]\n attributeCode = mapData[1]\n attributeResponse = [1, int(mageId), attributeCode]\n if attributeResponse[0] == 0:\n displayMessage = displayMessage + attributeResponse[1]\n if attributeResponse[0] > 0:\n mageId = attributeResponse[1]\n attributeCode = attributeResponse[2]\n attributeValueData = {}\n for valueObj in attributeObj.value_ids:\n valueName = valueObj.name\n valueId = valueObj.id\n attributeValueData[valueName] = valueId\n if not valueMappingModel.with_context(ctx).search([('erp_id', '=', valueId), ('instance_id', '=', instanceId)], limit=1):\n position = valueObj.sequence\n valueResponse = self.with_context(ctx).create_attribute_value(\n url, token, attributeCode, valueId, valueName, position)\n self.with_context(ctx).map_attribute_values(\n url, token, attributeCode, attributeValueData)\n attributeCount += 1\n else:\n displayMessage = \"No Attribute(s) Found To Be Export At Magento!!!\"\n if attributeCount:\n displayMessage += \"\\n %s Attribute(s) and their value(s) successfully Synchronized To Magento.\" % (\n attributeCount)\n return self.display_message(displayMessage)\n\n @api.model\n def create_product_attribute(self, url, token, odooId, attributeCode, label):\n if token:\n attrributeData = {\"attribute\": {\n 'scope': 'global',\n 'frontendInput': 'select',\n 'isRequired': 0,\n 'frontendLabels': [{'storeId': 0, 'label': label}]\n }\n }\n attributeResponse = self.callMagentoApi(\n baseUrl=url,\n url='/V1/products/attributes',\n method='post',\n token=token,\n data=attrributeData\n )\n mageAttributeId = 0\n if attributeResponse and attributeResponse.get('attribute_id', 0) > 0:\n mageAttributeId = attributeResponse['attribute_id']\n attributeCode = attributeResponse['attribute_code']\n returnData = [1, mageAttributeId, attributeCode]\n else:\n attributeResponse = self.callMagentoApi(\n baseUrl=url,\n url='/V1/products/attributes/' + attributeCode,\n method='get',\n token=token,\n )\n if attributeResponse and attributeResponse.get('attribute_id') > 0:\n mageAttributeId = attributeResponse['attribute_id']\n attributeCode = attributeResponse['attribute_code']\n returnData = [1, mageAttributeId, attributeCode]\n else:\n returnData = [0, 'Attribute {} failed to create at magento.'.format(label), attributeCode]\n if mageAttributeId :\n erpMapData = {\n 'name': odooId,\n 'erp_id': odooId,\n 'mage_id': mageAttributeId,\n 'mage_attribute_code':attributeCode, \n 'instance_id': self._context.get('instance_id'),\n }\n self.env['magento.product.attribute'].create(erpMapData)\n mapData = {'attribute': {\n 'name':attributeCode,\n 'magento_id': mageAttributeId, \n 'odoo_id': odooId, \n 'created_by': 'Odoo'\n }}\n self.callMagentoApi(\n baseUrl=url,\n url='/V1/odoomagentoconnect/attribute',\n method='post',\n token=token,\n data=mapData\n )\n return returnData\n\n @api.model\n def create_attribute_value(self, url, token, attributeCode, erpAttrId, name, position='0'):\n if token:\n name = name.strip()\n optionsData = {\"option\": {\n \"label\": name,\n \"sortOrder\": position,\n \"isDefault\": 0,\n 'storeLabels': [{'storeId': 0, 'label': name}]\n }}\n optionResponse = self.callMagentoApi(\n baseUrl=url,\n url='/V1/products/attributes/' + attributeCode + '/options',\n method='post',\n token=token,\n data=optionsData\n )\n return optionResponse\n\n @api.model\n def map_attribute_values(self, url, token, attributeCode, attributeValueData):\n mapValueModel = self.env['magento.product.attribute.value']\n optionResponse = self.callMagentoApi(\n baseUrl=url,\n url='/V1/products/attributes/' + attributeCode + '/options',\n method='get',\n token=token\n )\n mageIds = optionResponse\n if type(optionResponse) is list:\n for mageOption in optionResponse:\n mageId = mageOption.get('value', '0')\n if mageId and mageId.isdigit():\n mageLabel = mageOption['label']\n mapValueObj = mapValueModel.search([\n ('mage_id', '=', int(mageId)), \n ('instance_id', '=', self._context.get('instance_id'))\n ], limit=1)\n if not mapValueObj and attributeValueData.get(mageLabel):\n odooId = attributeValueData[mageLabel]\n erpMapData = {\n 'name': odooId,\n 'erp_id': odooId,\n 'mage_id': int(mageId),\n 'instance_id': self._context.get('instance_id')\n }\n mapValueModel.create(erpMapData)\n mapData = {'option': {\n 'name': mageLabel, \n 'magento_id': mageId, \n 'odoo_id': odooId, \n 'created_by': 'Odoo'\n }}\n self.callMagentoApi(\n url='/V1/odoomagentoconnect/option',\n method='post',\n token=token,\n data=mapData\n )\n return True\n","sub_path":"odoo_magento_connect/models/attribute_sync.py","file_name":"attribute_sync.py","file_ext":"py","file_size_in_byte":9071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"53429852","text":"# Name: Renacin Matadeen\n# Date: 11/29/2020\n# Title Toronto Police Auctions - Website Parsing - Additional Fuunctions\n#\n# ----------------------------------------------------------------------------------------------------------------------\nimport time\nimport re\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n# Function To Grab Data From Website Either With HTML Or Xpath Scrape\ndef collect_item_info(raw_html, cdriver_object):\n\n\n # Find Name, SKU_ID, Current Price, Upbid Increase | Use Regular Expression, Quicker?\n try:\n re_name = r'title\">(.*)(.{1,10})'\n re_cur_price_data = re.findall(re_cur_price, raw_html)\n parsed_prices = re_cur_price_data\n\n cur_price = re_cur_price_data[0]\n min_upbid = re_cur_price_data[1]\n upbid_increase = round(float(min_upbid) - float(cur_price), 2)\n\n\n except ValueError:\n item_name = \"N/A\"\n item_TPA_ID = \"N/A\"\n\n cur_price = \"N/A\"\n min_upbid = \"N/A\"\n upbid_increase = \"N/A\"\n\n\n\n # Find Minutes Left Remaining | Use Selenium Select By Xpath\n try:\n time_remaining_raw = cdriver_object.find_element_by_xpath('/html/body/main/div/div[2]/div/div[3]/div[3]/div[1]/span/span')\n rem_time_raw = time_remaining_raw.get_attribute('innerHTML')\n\n for rep_chr in [\"Days\", \"Day\"]:\n rem_time_raw = rem_time_raw.replace(rep_chr, \"\")\n rem_time_data = rem_time_raw.split(\" \")\n\n days_ = rem_time_data[0 ].replace(\"\\n\", \"\")\n days_in_minutes_left = int(days_) * 1440\n\n time_split = rem_time_data[1].split(\":\")\n total_minutes_left = days_in_minutes_left + (int(time_split[0]) * 60) + int(time_split[1])\n\n except ValueError:\n total_minutes_left = \"N/A\"\n\n\n\n # Find Bidding End & Start Date | Use Selenium Select By Xpath\n try:\n months = {\"December\": 12, \"January\": 1, \"February\": 2, \"March\": 3, \"April\": 4, \"May\": 5, \"June\": 6, \"July\": 7, \"August\": 8, \"September\": 9, \"October\": 10, \"November\": 11}\n\n start_date_raw = cdriver_object.find_element_by_xpath('/html/body/main/div/div[2]/div/div[4]/div[4]/table/tbody/tr[7]/td[2]')\n start_date_str = start_date_raw.get_attribute('innerHTML')\n start_date_str_split = start_date_str.split(\" \")\n date_ = start_date_str_split[2].replace(\" \", \"\")\n date_ = start_date_str_split[2].replace(\",\", \"\")\n start_date = \"{}/{}/{}\".format(months[start_date_str_split[1]], date_, start_date_str_split[3])\n\n end_date_raw = cdriver_object.find_element_by_xpath('/html/body/main/div/div[2]/div/div[4]/div[4]/table/tbody/tr[4]/td[2]/span[1]')\n end_date_raw_str = end_date_raw.get_attribute('innerHTML')\n end_date_raw_str_split = end_date_raw_str.split(\" \")\n date_ = end_date_raw_str_split[2].replace(\" \", \"\")\n date_ = end_date_raw_str_split[2].replace(\",\", \"\")\n end_date = \"{}/{}/{}\".format(months[end_date_raw_str_split[1]], date_, end_date_raw_str_split[3])\n\n except ValueError:\n start_date = \"00/00/00\"\n end_date = \"00/00/00\"\n\n\n # Find Number Of Bids | Use Selenium Select By Xpath\n try:\n # Find Total Number Of Bids\n num_bids_raw = cdriver_object.find_element_by_xpath('/html/body/main/div/div[2]/div/div[4]/div[4]/table/tbody/tr[5]')\n num_bids_str = num_bids_raw.get_attribute('innerHTML')\n num_bids_re = r'=\"([0-9]{1,3})\">'\n num_bids_list = re.findall(num_bids_re, num_bids_str)\n\n try:\n num_bids = int(num_bids_list[0])\n\n except IndexError:\n num_bids = 0\n\n except ValueError:\n num_bids = 0\n\n\n # Find Highest Bidder | Use Selenium Select By Xpath\n try:\n # Find Highest Bidder Info\n high_bidder_raw = cdriver_object.find_element_by_xpath('/html/body/main/div/div[2]/div/div[4]/div[4]/table/tbody/tr[6]/td[2]/span')\n highest_bidder = high_bidder_raw.get_attribute('innerHTML')\n\n except ValueError:\n highest_bidder = \"N/A\"\n\n\n return [item_name, item_TPA_ID, cur_price, min_upbid, upbid_increase, total_minutes_left, start_date, end_date, num_bids, highest_bidder]\n","sub_path":"WebCrawler/funcs/wc_funcs.py","file_name":"wc_funcs.py","file_ext":"py","file_size_in_byte":5526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"522890653","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom tetris_model import BOARD_DATA, Shape\r\nimport math\r\nfrom datetime import datetime\r\nimport numpy as np\r\ndef takeSecond(elem):\r\n return elem[1]\r\nclass TetrisExpMaxAI(object):\r\n def getPossibleDirections(self, shape):\r\n if shape in (Shape.shapeI, Shape.shapeZ, Shape.shapeS):\r\n directions = (0, 1)\r\n elif shape == Shape.shapeO:\r\n directions = (0,)\r\n else:\r\n directions = (0, 1, 2, 3)\r\n return directions\r\n\r\n def enumerationPossibleResult(self):\r\n from copy import copy\r\n import itertools\r\n Shapes = [BOARD_DATA.currentShape] + [Shape for Shape in BOARD_DATA.nextShape]\r\n allDirections = [self.getPossibleDirections(Shape.shape) for Shape in Shapes]\r\n allPossibleActions = []\r\n for index in range(len(Shapes)):\r\n allPossibleActions.append([])\r\n for direction in allDirections[index]:\r\n minX, maxX, _, _ = Shapes[index].getBoundingOffsets(direction)\r\n for x in range(-minX, BOARD_DATA.width - maxX):\r\n allPossibleActions[index].append((x, direction))\r\n result = list(itertools.product(*allPossibleActions))\r\n return Shapes, result\r\n\r\n def generateBoardBySingleAction(self, Shape, action, board):\r\n (x0, direction) = action\r\n dy = BOARD_DATA.height - 1\r\n for x, y in Shape.getCoords(direction, x0, 0):\r\n yy = 0\r\n print(board)\r\n print(board[(y + yy), x])\r\n while yy + y < BOARD_DATA.height and (yy + y < 0 or board[(y + yy), x] == Shape.shapeNone):\r\n yy += 1\r\n yy -= 1\r\n if yy < dy:\r\n dy = yy\r\n self.dropDownByDist(board, Shape, direction, x0, dy)\r\n return board\r\n\r\n def generateBoardByActions(self, Shapes, actionSequence):\r\n board = np.array(BOARD_DATA.getData()).reshape((BOARD_DATA.height, BOARD_DATA.width))\r\n for index in range(len(Shapes)):\r\n (x0, direction) = actionSequence[index]\r\n dy = BOARD_DATA.height - 1\r\n for x, y in Shapes[index].getCoords(direction, x0, 0):\r\n yy = 0\r\n while yy + y < BOARD_DATA.height and (yy + y < 0 or board[(y + yy), x] == Shape.shapeNone):\r\n yy += 1\r\n yy -= 1\r\n if yy < dy:\r\n dy = yy\r\n self.dropDownByDist(board, Shapes[index], direction, x0, dy)\r\n return board\r\n\r\n def dropDownByDist(self, data, shape, direction, x0, dist):\r\n for x, y in shape.getCoords(direction, x0, 0):\r\n data[y + dist, x] = shape.shape\r\n\r\n def evaluationScore(self, board):\r\n width = BOARD_DATA.width\r\n height = BOARD_DATA.height\r\n # print(datetime.now() - t1)\r\n\r\n fullLines, nearFullLines = 0, 0\r\n roofY = [0] * width\r\n holeCandidates = [0] * width\r\n holeConfirm = [0] * width\r\n vHoles, vBlocks = 0, 0\r\n for y in range(height - 1, -1, -1):\r\n hasHole = False\r\n hasBlock = False\r\n for x in range(width):\r\n if board[y, x] == Shape.shapeNone:\r\n hasHole = True\r\n holeCandidates[x] += 1\r\n else:\r\n hasBlock = True\r\n roofY[x] = height - y\r\n if holeCandidates[x] > 0:\r\n holeConfirm[x] += holeCandidates[x]\r\n holeCandidates[x] = 0\r\n if holeConfirm[x] > 0:\r\n vBlocks += 1\r\n if not hasBlock:\r\n break\r\n if not hasHole and hasBlock:\r\n fullLines += 1\r\n vHoles = sum([x ** .7 for x in holeConfirm])\r\n maxHeight = max(roofY) - fullLines\r\n # print(datetime.now() - t1)\r\n\r\n roofDy = [roofY[i] - roofY[i+1] for i in range(len(roofY) - 1)]\r\n\r\n if len(roofY) <= 0:\r\n stdY = 0\r\n else:\r\n stdY = math.sqrt(sum([y ** 2 for y in roofY]) / len(roofY) - (sum(roofY) / len(roofY)) ** 2)\r\n if len(roofDy) <= 0:\r\n stdDY = 0\r\n else:\r\n stdDY = math.sqrt(sum([y ** 2 for y in roofDy]) / len(roofDy) - (sum(roofDy) / len(roofDy)) ** 2)\r\n\r\n absDy = sum([abs(x) for x in roofDy])\r\n maxDy = max(roofY) - min(roofY)\r\n \r\n score = fullLines * 1.8 - vHoles * 1.0 - vBlocks * 0.5 - maxHeight ** 2 * 0.02 \\\r\n - stdY * 0.0 - stdDY * 0.01 - absDy * 0.2 - maxDy * 0.3\r\n return score\r\n\r\n \r\n\r\n def nextMoveByEnumeration(self):\r\n # t1 = datetime.now()\r\n # print(\"**\")\r\n if BOARD_DATA.currentShape == Shape.shapeNone:\r\n return None\r\n # print(\"=======\")\r\n Shapes, allPossibleActionSequence = self.enumerationPossibleResult()\r\n # print(len(allPossibleActionSequence))\r\n (maxScore, bestActionSequence) = (-float('inf'), None)\r\n for actionSequence in allPossibleActionSequence:\r\n tempBoard = self.generateBoardByActions(Shapes, actionSequence)\r\n tempScore = self.evaluationScore(tempBoard)\r\n if tempScore > maxScore:\r\n (maxScore, bestActionSequence) = (tempScore, actionSequence)\r\n return (bestActionSequence[0][1], bestActionSequence[0][0], maxScore)\r\n # def nextMoveByEnumerationWithPurning(self):\r\n # Shapes = list([BOARD_DATA.currentShape] + [Shape for Shape in BOARD_DATA.nextShape])\r\n # allDirections = [self.getPossibleDirections(Shape.shape) for Shape in Shapes]\r\n # lamda = 1\r\n # boards = [(np.array(BOARD_DATA.getData()).reshape((BOARD_DATA.height, BOARD_DATA.width)), 0)]\r\n # for index in range(len(Shapes)):\r\n # # print(boards)\r\n # newBoards = []\r\n # for board in boards:\r\n # for direction in allDirections[index]:\r\n # minX, maxX, _, _ = Shapes[index].getBoundingOffsets(direction)\r\n # for x in range(-minX, BOARD_DATA.width - maxX):\r\n # newBoard = self.generateBoardBySingleAction(Shapes[index], (x, direction), board)\r\n # newScore = self.evaluationScore(newBoard)\r\n # newBoards.append((newBoards, newScore))\r\n # boards = newBoards\r\n # boards.sort(key = takeSecond)\r\n\r\n def nextMove(self):\r\n return self.nextMoveByEnumeration()\r\n# TETRIS_AI = TetrisAI()\r\nTETRIS_AI = TetrisExpMaxAI()\r\n\r\n","sub_path":"tetris_game_new/tetris_ai_expmax.py","file_name":"tetris_ai_expmax.py","file_ext":"py","file_size_in_byte":6583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"580555577","text":"import sys\nimport random\nfrom dolfin import *\nfrom dolfin_adjoint import *\nfrom math import sqrt\n\n# Model parameters\neps = 0.1\nlmbda = eps**2 # surface parameter\ndt = 5.0e-03 # time step\ntheta = 0.5 # time stepping family, e.g. theta=1 -> backward Euler, theta=0.5 -> Crank-Nicolson\n\n# Form compiler options\nparameters[\"form_compiler\"][\"optimize\"] = True\nparameters[\"form_compiler\"][\"cpp_optimize\"] = True\nparameters[\"form_compiler\"][\"representation\"] = \"quadrature\"\nparameters[\"std_out_all_processes\"] = False;\n\n# Create mesh and define function spaces\nmesh = IntervalMesh(100, 0, 2)\nV = FunctionSpace(mesh, \"Lagrange\", 1)\nME = V*V\n\nsteps = 100\ndef main(ic, annotate=False):\n\n # Define trial and test functions\n du = TrialFunction(ME)\n q, v = TestFunctions(ME)\n\n # Define functions\n u = Function(ME, name=\"NextSolution\") # current solution\n u0 = Function(ME, name=\"Solution\") # solution from previous converged step\n\n # Split mixed functions\n dc, dmu = split(du)\n c, mu = split(u)\n c0, mu0 = split(u0)\n\n # Create intial conditions and interpolate\n u.assign(ic)\n u0.assign(ic)\n\n # Compute the chemical potential df/dc\n c = variable(c)\n f = (c**2/4.0)*(c**2 - 2.0)\n dfdc = diff(f, c)\n\n # mu_(n+theta)\n mu_mid = (1.0-theta)*mu0 + theta*mu\n\n # Weak statement of the equations\n L0 = c*q*dx - c0*q*dx + dt*dot(grad(mu_mid), grad(q))*dx\n L1 = mu*v*dx - dfdc*v*dx - lmbda*dot(grad(c), grad(v))*dx\n L = L0 + L1\n\n # Compute directional derivative about u in the direction of du (Jacobian)\n a = derivative(L, u, du)\n\n # Boundary conditions\n bcs = [DirichletBC(ME.sub(0), 1.0, \"near(x[0], 0.0) && on_boundary\"), \n DirichletBC(ME.sub(0),-1.0, \"near(x[0], 2.0) && on_boundary\")]\n\n # Create nonlinear problem and Newton solver\n parameters = {}\n parameters[\"linear_solver\"] = \"lu\"\n parameters[\"newton_solver\"] = {}\n parameters[\"newton_solver\"][\"convergence_criterion\"] = \"incremental\"\n\n file = File(\"output_1d/output_1d.pvd\", \"compressed\")\n\n # Step in time\n t = 0.0\n T = steps*dt\n\n if annotate:\n adjointer.time.start(t)\n while t < T:\n t += dt\n solve(L == 0, u, J=a, bcs=bcs, solver_parameters=parameters)\n\n u0.assign(u)\n\n file << (u.split()[0], t)\n if annotate:\n adj_inc_timestep(time=t, finished=t>=T)\n\n return u0\n\nif __name__ == \"__main__\":\n ic = Function(ME)\n ic.interpolate(Expression((\"1 - x[0]\", \"0.0\")))\n\n u = main(ic, annotate=True)\n","sub_path":"cahn_hilliard/1d.py","file_name":"1d.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"24065644","text":"#unix command \"cut -f 1 < hightemp.txt\"\n#unix command \"cut -f 2 < hightemp.txt\"\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ncol1=\"\"\ncol2=\"\"\n\nfor i in open(\"hightemp.txt\"):\n col1=col1+i.strip().split(\"\\t\")[0]+\"\\n\"\n col2=col2+i.strip().split(\"\\t\")[1]+\"\\n\"\nf1=open(\"col1.txt\",\"w\")\nf2=open(\"col2.txt\",\"w\")\nf1.write(col1)\nf2.write(col2)\nf1.close()\nf2.close()\n","sub_path":"osaki/chapter02/knock12.py","file_name":"knock12.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"359886753","text":"import os\nimport shutil\n\n# 1\n# Write a function list_files_walk that returns a list of the paths of all the \n# parts.txt files, using the os module's walk generator. The function takes no \n# input parameters. Part of the output would look like this:\n# CarItems/Chevrolet/Chevelle/2011/parts.txt\n# CarItems/Chevrolet/Chevelle/1982/parts.txt\n# CarItems/Chevrolet/Volt/1994/parts.txt\n# CarItems/Chevrolet/Volt/1999/parts.txt\n# if I printed each element of the output list on one line at a time. In the \n# above example, the current working directory from which I called the function \n# was the parent directory of CarItems.\ndef list_files_walk():\n \"\"\"Returns a list of the paths of all the parts.txt files.\n \n This function returns a list of the paths of all the parts.txt files. Uses\n the os module's walk generator. Only includes parts files, not accessories\n files.\n \n Postitional Input Parameters:\n none\n \n Returns:\n paths | list:\n The paths of all the parts.txt files.\n \"\"\"\n #for dirpath in os.walk(\"CarItems\"):\n # #if os.path.isfile(dirpath.split(\"/\")[-1]):\n # print(str(dirpath))\n paths = []\n for dirpath, dirnames, filenames in os.walk(\"CarItems\"):\n for ifile in filenames:\n if \"parts\" in ifile: # only add parts files\n paths.append(os.path.join(dirpath, ifile))\n return paths\n\n# Output the items in the list\nprint(\"\\nList files using os.walk() function:\")\nparts_list = list_files_walk()\nfor i in range(len(parts_list)):\n print(parts_list[i])\n \n# 2\n# Write a function list_files_recursive that returns a list of the paths of all \n# the parts.txt files without using the os module's walk generator. Instead, the \n# function should use recursion. The input will be a directory name and the \n# output should be the same as the output in Task #1 above.\ndef list_files_recursive(top_dir):\n \"\"\"Returns a list of the paths of all the parts.txt files.\n \n This function returns a list of the paths of all the parts.txt files, using\n recursion. Only includes parts files, not accessories files.\n \n Postitional Input Parameters:\n none\n \n Returns:\n paths | list:\n The paths of all the parts.txt files.\n \"\"\"\n dir_contents = os.listdir(top_dir)\n paths = []\n for item in dir_contents:\n item_path = os.path.join(top_dir, item)\n if os.path.isdir(item_path):\n paths += list_files_recursive(item_path)\n else:\n if \"parts\" in item: # only add parts files\n if os.path.splitext(item)[-1] == '.txt':\n paths += [item_path]\n return paths\n \n# Output the items in the list\nprint(\"\\nList files using recursive function:\")\nparts_list_recursive = list_files_recursive(\"CarItems\")\nfor i in range(len(parts_list_recursive)):\n print(parts_list_recursive[i])\n\n# 3\n# Make calls to list_files_walk and list_files_recursive and compare whether the \n# output is the same. Print to screen the result as to whether or not both calls \n# return the same list. (The result should be True.)\nprint(\"\\nCalls to list_files_walk() and list_files_recursive() return the same\" \n \" list: \" + str(list_files_walk() == list_files_recursive(\"CarItems\")))\n\n# 4\n# Create a copy of the CarItems tree called CarItemsCopy where all files, \n# instead of being in directories named after years, rather have the year as \n# part of the filename, and the year directories are entirely absent. That is, \n# when you're done, the CarItems directory tree will look like: (image omitted)\n# Do this using Python (you can't create the copy by manually rearranging \n# things). You may use the os module's walk generator. Hint: You might find the \n# os.path module's split function to be helpful. You don't have to use it though.\ndef copy_car_items():\n if not os.path.isdir(\"CarItemsCopy\"): # Make sure dir doesn't exist already\n shutil.copytree(\"CarItems\", \"CarItemsCopy\")\n for dirpath, dirnames, filenames in os.walk(\"CarItemsCopy\"):\n for ifile in filenames:\n # Full filepath\n fullpath = os.path.join(dirpath, ifile)\n pieces = os.path.split(fullpath)\n \n # Add the year to the filename\n filename_with_year = os.path.splitext(pieces[1])[0] + \"-\" + \\\n os.path.split(pieces[0])[1] + \\\n os.path.splitext(pieces[1])[1]\n \n # New destination of the parts/accessories files (inside the model\n # folder)\n model_path = os.path.split(dirpath)[0]\n \n # Move the file to the model directory\n shutil.move(os.path.join(dirpath, ifile), \n os.path.join(model_path, filename_with_year))\n \n # Delete the empty year directory inside the model directory \n if 'parts.txt' not in os.listdir(dirpath) and \\\n 'accessories.txt' not in os.listdir(dirpath):\n shutil.rmtree(dirpath)\n \n# Create the CarItemsCopy directory tree\ncopy_car_items()\n","sub_path":"hw7.py","file_name":"hw7.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619659098","text":"from pymongo import MongoClient\nimport time\n\nimport get_html as gh\nimport parse_html as ph\n\nuser = 'crawl'\npwd = 'crawl123'\nserver = '10.138.61.39'\nport = \"27017\"\ndb_name = 'crawl'\n\nuri = 'mongodb://' + user + ':' + pwd + '@' + server + ':' + port + '/' + db_name\nclient = MongoClient(uri)\ndb = client[\"crawl\"]\ncol = db.ctxhtml\n\nurls = gh.get_url(5)\ntotal = 0\n\nfor url in urls[7579:]:\n html = gh.get_info(url)\n state = ph.judge(html)\n col.insert_one({'url': url, 'state': state, 'html': html})\n\n total += 1\n print(\"已插入%d条数据\" % total)\n\n time.sleep(20)\n\n\n\n\n\n\n\n\n","sub_path":"mongo_text.py","file_name":"mongo_text.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"35424809","text":"from random import randint\n\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nfrom nonebot import get_driver, on_command, logger, require\nfrom nonebot.adapters.cqhttp import Bot, Event, MessageSegment\n\nfrom .config import Config\nfrom src.common.rules import not_to_me\n\nglobal_config = get_driver().config\nconfig = Config(**global_config.dict())\n\nNOT_ANONYMOUS_GROUP = require(\"permission\").NOT_ANONYMOUS_GROUP\nfetch_user_sign_status = require(\"dao\").fetch_user_sign_status\ninsert_user = require(\"dao\").insert_user\nupdate_user = require(\"dao\").update_user\nreset_user_signed = require(\"dao\").reset_user_signed\nscheduler: AsyncIOScheduler = require(\"nonebot_plugin_apscheduler\").scheduler\n\ncheck_in = on_command(\"签到\", rule=not_to_me(), permission=NOT_ANONYMOUS_GROUP, priority=3)\n\n\n@check_in.handle()\nasync def handle_first_receive(bot: Bot, event: Event, state: dict):\n if str(event.message).strip():\n await check_in.finish(\"11\")\n\n user_status = await fetch_user_sign_status(event.user_id, event.group_id)\n sign_money = randint(config.sign_in_money_down, config.sign_in_money_up)\n\n logger.debug(user_status)\n\n if user_status is None:\n succ = await insert_user(event.user_id, event.group_id, sign_money, int(True))\n else:\n if user_status[\"has_signed\"] == True:\n await check_in.finish(MessageSegment.at(event.user_id) + \"您今日已签过到,请勿重复签到!\")\n succ = await update_user(event.user_id, event.group_id, sign_money, int(True))\n\n logger.debug(succ)\n if succ:\n await check_in.finish(MessageSegment.at(event.user_id) + f\"您已签到成功!获得金钱:{sign_money}{config.money_unit}\")\n else:\n await check_in.finish(MessageSegment.at(event.user_id) + \"对不起,签到失败,请重新签到或者联系管理!\")\n\n\n@scheduler.scheduled_job(\"cron\", day=\"*\", hour=\"0\", minute=\"0\", id=\"reset_signed_task\", kwargs={})\nasync def run_every_day_reset_signed(**kwargs):\n await reset_user_signed(int(False))\n","sub_path":"src/plugins/plugins/sign/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"69357790","text":"# -*- coding: utf-8 -*-\n\n# 問題: MxNの行列について、要素が0であれば、その行と列のすべてを0にするアルゴリズムを書いてください。\n\n# (本来)確認すべき前提\n# 新しい行列を返すのか? それとも入力を弄るのか?\n\n# 基本方針:基本は行ごとに総スキャンするが、一度0になった行は次にスキップすると計算量減りそう。\n\nimport numpy\nimport copy\n\n\ndef zerofill_row(matrix, m, N):\n for n in range(N):\n matrix[m, n] = 0\n\n\ndef zerofill_column(matrix, M, n):\n for m in range(M):\n matrix[m, n] = 0\n\n\ndef main(matrix, M, N):\n new_matrix = copy.deepcopy(matrix)\n for m in range(M):\n for n in range(N):\n if matrix[m, n] == 0:\n zerofill_row(new_matrix, m, N)\n zerofill_column(new_matrix, M, n)\n break\n print(new_matrix)\n\nif __name__ == '__main__':\n matrix = numpy.matrix([[1, 2, 3], [4, 0, 6], [7, 8, 9]])\n print(matrix)\n main(matrix, matrix.shape[0], matrix.shape[1])\n\n# ハマった点\n# 最初、元の行列をその場で書き換えてしまった。すると、0に書き換えられた値を次のループで参照し、\n# 本来0埋めしなくてよい場所も0で埋めてしまった。\n# 元の行列の完全なコピーを作成し、0埋めはそちらにするようにした。\n\n# コードの出来\n# 計算量; M x N の2重ループを回しているので、オーダー(MxN)\n# メモリ: M x N x 2 x 32bitは最低必要。 オーダー(MxN)\n#     もう少し詰めるとしたら、コピーをしない。0がある行、列番号を格納する配列を作り、\n# 1回スキャンして上記配列に値を入れ、その値をもとに元の行列でzerofillする。\n#     (ただし、ループを2回回すので、計算量は倍になる。)\n\n\n\n\n","sub_path":"CrackingTheCodingInterview_v5/Chapter1_Array/1_7.py","file_name":"1_7.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571933488","text":"from setuptools import setup, find_packages\nfrom os.path import join\nimport sys\nimport os\n\nNAME = 'Products.ZSPARQLMethod'\nPATH = NAME.split('.') + ['version.txt']\nVERSION = open(join(*PATH)).read().strip()\n\ninstall_requires = ['sparql-client']\nif sys.version_info < (2, 6):\n install_requires += ['simplejson']\n\ndocs = open('README.rst').read() + \"\\n\" + \\\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read()\n\nsetup(\n name=NAME,\n version=VERSION,\n keywords='sparql rdf linkeddata semanticweb zope python',\n author='European Environment Agency',\n author_email=\"webadmin@eea.europa.eu\",\n url='https://svn.eionet.europa.eu/repositories/Zope/trunk/Products.ZSPARQLMethod',\n license=\"Mozilla Public License 1.1\",\n classifiers = [\n 'Environment :: Web Environment',\n 'Framework :: Zope2',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Mozilla Public License 1.1 (MPL 1.1)',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Topic :: Software Development',\n 'Topic :: Software Development :: Libraries',\n ],\n description=\"Zope product for making SPARQL queries, simiar to ZSQLMethod\",\n long_description=docs,\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=install_requires,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633853640","text":"####################################\n# flasky.py under RPI_FPVcar #\n# -------------------------------- #\n# Program written by Minsu Kim #\n# Last Update 17/07/17 #\n# Author email: 521minsu@gmail.com #\n####################################\n\nfrom flask import Flask\nimport motor_control\nimport servo_control\n\nservo = servo_control\nmotor = motor_control\napp = Flask(__name__)\n\n\n@app.route('/motor/')\ndef motor_control_call(joystick_angle):\n motor.control(joystick_angle)\n print('Received Motor dir: {}'.format(joystick_angle))\n return 'Received Motor dir: {}'.format(joystick_angle)\n\n\n@app.route('/servo/')\ndef servo_control_call(servo_angle):\n servo.control(servo_angle)\n print('Received Servo ang: {}'.format(servo_angle))\n return 'Received Servo ang: {}'.format(servo_angle)\n\n\n@app.route('/flasky')\ndef flasky():\n return \"Hello I'm Flasky ㅇㅅㅇ\"","sub_path":"flasky.py","file_name":"flasky.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"51899106","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 1 19:35:23 2017\n\n@author: dlicht\n\"\"\"\n\n#load data\n#Values = int(input())\n#mu = int(input())\n#sig = int(input())\n#mp = float(input()) \n#z = float(input())\n\nvalues = 100\nmu = 500\nsig = 80\nmp = 0.95\nz = 1.96\n\n#mu_all = mu * values\n#sig_all = sig * values**0.5\n\nA = mu - z*sig/(values**0.5)\nB = mu + z*sig/(values**0.5)\n\nprint(\"%.2f\" % A)\nprint(\"%.2f\" % B)","sub_path":"statistics/10daysofcoding\\day6Q22.py","file_name":"10daysofcoding\\day6Q22.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"59590665","text":"#!/usr/bin/python3\nimport paramiko\n\n\nclass SSH_Client():\n _host = None\n _port = None\n _user = None\n _keyfile = None\n _trans = None\n _ssh = None\n _scp = None\n\n def __init__(self, host, port, user, keyfile):\n self._host = host\n self._port = port\n self._user = user\n self._keyfile = keyfile\n self._trans = self.login(host, port, user, keyfile)\n\n def login(self, host, port, user, keyfile):\n # 建立一个socket\n trans = paramiko.Transport((host, port))\n # 启动一个客户端\n trans.start_client()\n\n # 如果使用rsa密钥登录的话\n key = paramiko.RSAKey.from_private_key_file(keyfile)\n trans.auth_publickey(username=user, key=key)\n\n return trans\n\n def run(self, command):\n # 将sshclient的对象的transport指定为以上的trans\n if self._ssh == None:\n self._ssh = paramiko.SSHClient()\n self._ssh._transport = self._trans\n stdin, stdout, stderr = self._ssh.exec_command(command)\n out = stdout.read()\n err = stderr.read()\n if len(err) > 0:\n print(err.decode())\n return out\n\n def put(self, localfile, remotefile):\n # 实例化一个 sftp对象,指定连接的通道\n if self._scp == None:\n self._scp = paramiko.SFTPClient.from_transport(self._trans)\n self._scp.put(localfile, remotefile)\n\n def get(self, remotefile, localfile):\n # 实例化一个 sftp对象,指定连接的通道\n if self._scp == None:\n self._scp = paramiko.SFTPClient.from_transport(self._trans)\n self._scp.get(remotefile, localfile)\n","sub_path":"cmdb/ssh.py","file_name":"ssh.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"559355037","text":"# import info about system\r\nfrom os import system, name\r\n\r\n\r\n# define a function to clear the screen\r\ndef clearScreen():\r\n # windows\r\n if name == 'nt':\r\n _ = system('cls')\r\n # mac and linux\r\n else:\r\n _ = system('clear')\r\n\r\ndef getHistory(orders, id, carOrUser):\r\n if carOrUser == \"car\":\r\n form = \"User ID\"\r\n else:\r\n form = \"Car ID\"\r\n clearScreen()\r\n print(\"->Print order history for {} with ID: \\\"{}\\\"\".format(carOrUser, id))\r\n print(\"\")\r\n print(\"These are the history items for this {}:\".format(carOrUser))\r\n print(\"{:10}{:10}{:15}{:15}\".format(\"Order ID\", form, \"Pick Up date\", \"Return date\"))\r\n if carOrUser == \"car\":\r\n for order in orders:\r\n if str(order.carId) == str(id):\r\n print(\"{:10}{:10}{:15}{:15}\".format(str(order.id), str(order.userId),\r\n order.pickUpDate, order.returnDate))\r\n else:\r\n for order in orders:\r\n if str(order.userId) == str(id):\r\n print(\"{:10}{:10}{:15}{:15}\".format(str(order.id), str(order.carId),\r\n order.pickUpDate, order.returnDate))\r\n print(\"\")\r\n input(\"Press enter to return \")\r\n","sub_path":"helperfunctions/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"100265920","text":"import re\nimport time\nfrom selenium import webdriver\nfrom pyquery import PyQuery as pq\nimport pymysql.cursors\nimport mysql\n# 连接MySQL数据库\nconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456789', db='test',\n charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)\n# 通过cursor创建游标\ncursor = connection.cursor()\nbrowser = webdriver.Chrome()\ndef music_detail(url,album):\n browser.get(url)\n time.sleep(1)\n musicname=browser.find_element_by_class_name('audioName')\n musci=browser.find_element_by_class_name('songDetail')\n audio = browser.find_element_by_class_name('music')\n image=browser.find_element_by_class_name('albumImg').find_element_by_tag_name('img')\n singer = musci.find_element_by_class_name('singerName')\n #singerurl=singer.get_attribute()//后期完善歌手的url 可以用来获取歌手图片\n #print(type(singer.get_attribute('title')))\n if(album==0):\n return (musicname.get_attribute('title'),audio.get_attribute('src'),'null',singer.get_attribute('title').replace('、',' '),image.get_attribute('src'))\n album = browser.find_element_by_class_name('albumName').find_element_by_tag_name('a')\n return (musicname.get_attribute('title'),audio.get_attribute('src'), album.get_attribute('title'),singer.get_attribute('title').replace('、',' '),image.get_attribute('src'))\ndef zhuaquTop(url):\n browser.get(url)\n page_code = browser.page_source\n patter = '''\"Hash\":\"(\\w+?)\".*?\"album_id\":(\\d+?),'''\n results = re.findall(patter, page_code, re.S)\n #print(results.__len__())\n doc = pq(\"http://www.kugou.com/yy/html/rank.html\")\n li = doc('.pc_temp_songlist.pc_rank_songlist_short ul li a.pc_temp_songname').items()\n\n for url, item in zip(li, results):\n zurl = url.attr.href + \"#hash=\" + item[0] + \"&album_id=\" + item[1]\n print(zurl)\n info = music_detail(zurl, item[1])\n mysql.insertdata(connection,cursor,info,zurl)\n print(info[0] + ' ' + info[2] + ' ' + info[3]+' '+info[1]+''+info[4])\n # print(url.attr.href, url.attr('title'),item[0],item[1])\n\n# browser.get(\"http://www.kugou.com/yy/html/rank.html\")\n# page_code=browser.page_source\n#\n# patter='''\"Hash\":\"(\\w+?)\".*?\"album_id\":(\\d+?),'''\n# results=re.findall(patter,page_code,re.S)\n# print(results.__len__())\n# doc = pq(\"http://www.kugou.com/yy/html/rank.html\")\n# li = doc('.pc_temp_songlist.pc_rank_songlist_short ul li a.pc_temp_songname').items()\n#\n# for url,item in zip(li,results):\n# zurl=url.attr.href+\"#hash=\"+item[0]+\"&album_id=\"+item[1]\n# #print(zurl)\n# info=music_detail(zurl,item[1])\n# print(info[0]+' '+info[1]+' '+info[2])\n# #print(url.attr.href, url.attr('title'),item[0],item[1])","sub_path":"wanzheng_url.py","file_name":"wanzheng_url.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"47858972","text":"import sys\nimport math\n\n'''\n My first python program.\n My first serious attempt at codingame.com.\n I got bronze 300/900 and 1540/2200~ overall result.\n'''\n\n# VARIABLES\nITEM_NONE = -1\nITEM_RADAR = 2\nITEM_TRAP = 3\nITEM_ORE = 4\nTRAP_COOLDOWN = -1\nRADAR_COOLDOWN = -1\nIS_RADAR_REQUESTED = False\nIS_TRAP_REQUESTED = False\nCURRENT_HOT_POINT = ''\nCURRENT_BOILING_POINT = ''\n\n# COLLECTIONS\nhot_points_one = ['5 3', '5 11', '10 7',\n '15 3', '15 11', '20 7', '25 3', '25 11']\nhot_points_two = ['10 0', '20 0', '24 7', '20 14', '10 14']\n\nboiling_points = ['5 5', '5 13', '11 6', '14 4']\n\nTRAPS = set()\n\nACTIONS = dict()\nNEIGHBOURS = set()\nORES = set()\nHOLES = set()\n\n# CLASSES -------------------------------------\n\n\nclass Round:\n available_ores = 0\n busy_fields = set()\n\n def __init__(self, oreMap, holeMap, entities, enemies, radars, traps):\n self.oreMap = oreMap\n self.holeMap = holeMap\n self.entities = entities\n self.enemies = enemies\n self.radars = radars\n self.traps = traps\n\n def defineStrategyForEntities(self, round):\n global IS_RADAR_REQUESTED\n global CURRENT_HOT_POINT\n global CURRENT_BOILING_POINT\n IS_RADAR_REQUESTED = False\n round.count_available_ores()\n\n actions = ACTIONS\n is_need_to_go_home = False\n if self.available_ores == 0:\n is_need_to_go_home = True\n\n for entity in self.entities.values():\n e_id = entity.__dict__['id']\n if e_id > 4:\n entity.__dict__['id'] = e_id - 5\n \n if entity.__dict__['current_X'] == -1 and entity.__dict__['current_Y'] == -1:\n action = Action('', 'WAIT')\n actions[entity.__dict__['id']] = action\n continue\n else:\n radar_coordinates = round.get_radar_coordinates(round.radars)\n trap_coordinates = round.get_trap_coordinates(round.traps)\n\n if CURRENT_HOT_POINT in radar_coordinates:\n CURRENT_HOT_POINT = ''\n\n if CURRENT_BOILING_POINT in trap_coordinates:\n CURRENT_BOILING_POINT = ''\n\n if is_need_to_go_home and entity.__dict__['current_X'] != 0:\n round.go_home(entity, actions)\n is_need_to_go_home = False\n\n if ITEM_ORE == entity.__dict__['item']:\n round.go_home(entity, actions)\n continue\n\n if ITEM_RADAR == entity.__dict__['item']:\n round.start_radar_strategy(entity, actions, round)\n continue\n \n if ITEM_TRAP == entity.__dict__['item']:\n round.start_trap_strategy(entity, actions, round)\n continue\n\n if entity.__dict__['id'] in actions:\n round.continue_action(\n entity, actions[entity.__dict__['id']], actions)\n continue\n\n if entity.__dict__['current_X'] == 0:\n round.start_line_strategy(entity, actions, round)\n if is_need_to_go_home == True:\n is_need_to_go_home == False\n continue\n else:\n round.start_gather_strategy(entity, actions, round)\n continue\n return actions\n\n def start_line_strategy(self, entity, actions, round):\n global hot_points_one\n if round.available_ores == 0:\n if ITEM_NONE == entity.__dict__['item']:\n if RADAR_COOLDOWN == 0 and len(hot_points_one) > 0 and not IS_RADAR_REQUESTED:\n round.request_radar_strategy(entity, actions)\n elif RADAR_COOLDOWN == 0 and len(hot_points_one) == 0 and round.available_ores == 0:\n if IS_RADAR_REQUESTED == False:\n round.request_radar_strategy(entity, actions)\n elif TRAP_COOLDOWN == 0 and not IS_TRAP_REQUESTED:\n round.request_trap_strategy(entity, actions)\n else:\n round.start_gather_strategy(entity, actions, round)\n # TODO: Here may cause some problems\n if ITEM_RADAR == entity.__dict__['item']:\n round.start_radar_strategy(entity, actions, round)\n # TODO: And here too\n if ITEM_TRAP == entity.__dict__['item']:\n round.start_trap_strategy(entity, actions, round)\n else:\n round.start_gather_strategy(entity, actions, round)\n\n def start_gather_strategy(self, entity, actions, round):\n global CURRENT_HOT_POINT\n global NEIGHBOURS\n global hot_points_one\n if round.available_ores == 0:\n if CURRENT_HOT_POINT == '':\n CURRENT_HOT_POINT = hot_points_one[0]\n del hot_points_one[0]\n if len(NEIGHBOURS) == 0:\n coordinates = CURRENT_HOT_POINT.split()\n NEIGHBOURS = round.get_neighbours(coordinates)\n\n point = ''\n while point == '':\n point = next(iter(NEIGHBOURS))\n print(TRAPS, file = sys.stderr)\n if point in HOLES or point in TRAPS:\n print(point, file = sys.stderr)\n point = ''\n NEIGHBOURS.discard(point)\n\n if len(NEIGHBOURS) == 0 and point == '':\n round.go_home(entity, actions)\n break\n\n if point != '':\n action = Action(point, 'MOVE ')\n actions[entity.__dict__['id']] = action\n elif len(ORES) > 0:\n ores_list = list(ORES)\n ores_list.sort()\n point = ores_list[0]\n ORES.discard(point)\n\n action = Action(point, 'MOVE ')\n actions[entity.__dict__['id']] = action\n else:\n round.go_home(entity, actions)\n\n def start_radar_strategy(self, entity, actions, round):\n global hot_points_one\n global hot_points_two\n global CURRENT_HOT_POINT\n if len(hot_points_one) == 0:\n hot_points_one = hot_points_two\n hot_points_two = {'0 24', '24 14'}\n\n if CURRENT_HOT_POINT == '':\n CURRENT_HOT_POINT = hot_points_one[0]\n del hot_points_one[0]\n\n coordinates = CURRENT_HOT_POINT.split()\n\n current_X = entity.__dict__['current_X']\n current_Y = entity.__dict__['current_Y']\n\n if int(coordinates[0]) != current_X and int(coordinates[1]) != current_Y:\n action = Action(CURRENT_HOT_POINT, 'MOVE ')\n actions[entity.__dict__['id']] = action\n else:\n action = Action(CURRENT_HOT_POINT, 'DIG ')\n actions[entity.__dict__['id']] = action\n\n def start_trap_strategy(self, entity, actions, round):\n global ORES\n global CURRENT_BOILING_POINT\n\n if CURRENT_BOILING_POINT == '': \n if len(ORES) > 0:\n ores_list = list(ORES)\n ores_list.sort(reverse=True)\n CURRENT_BOILING_POINT = ores_list[0]\n ORES.discard(CURRENT_BOILING_POINT)\n TRAPS.add(CURRENT_BOILING_POINT)\n elif len(boiling_points) > 0:\n CURRENT_BOILING_POINT = boiling_points[0]\n del boiling_points[0]\n else:\n round.go_home(entity, actions)\n \n if CURRENT_BOILING_POINT != '':\n coordinates = CURRENT_BOILING_POINT.split()\n\n current_X = entity.__dict__['current_X']\n current_Y = entity.__dict__['current_Y']\n\n if int(coordinates[0]) != current_X and int(coordinates[1]) != current_Y:\n action = Action(CURRENT_BOILING_POINT, 'MOVE ')\n actions[entity.__dict__['id']] = action\n else:\n action = Action(CURRENT_BOILING_POINT, 'DIG ')\n actions[entity.__dict__['id']] = action\n\n\n def request_trap_strategy(self, entity, actions):\n global IS_TRAP_REQUESTED\n action = Action(\"\", 'REQUEST TRAP')\n actions[entity.__dict__['id']] = action\n IS_TRAP_REQUESTED = True\n\n def request_radar_strategy(self, entity, actions):\n global IS_RADAR_REQUESTED\n action = Action(\"\", 'REQUEST RADAR')\n actions[entity.__dict__['id']] = action\n IS_RADAR_REQUESTED = True\n\n def go_home(self, entity, actions):\n action = Action('0 ' + str(entity.__dict__['current_Y']), 'MOVE ')\n actions[entity.__dict__['id']] = action\n\n def continue_action(self, entity, action, actions):\n xy = action.__dict__['x_y']\n coordinates = xy.split()\n current_X = entity.__dict__['current_X']\n current_Y = entity.__dict__['current_Y']\n\n if int(coordinates[0]) != current_X and int(coordinates[1]) != current_Y:\n action = Action(xy, 'MOVE ')\n actions[entity.__dict__['id']] = action\n else:\n action = Action(xy, 'DIG ')\n actions[entity.__dict__['id']] = action\n\n def get_neighbours(self, coordinates):\n x = coordinates[0]\n y = coordinates[1]\n\n neighbours = set()\n\n neighbours.add(str(int(x) - 1) + ' ' + str(y))\n neighbours.add(str(int(x) - 1) + ' ' + str(int(y) - 1))\n neighbours.add(str(x) + ' ' + str(int(y) - 1))\n neighbours.add(str(int(x) + 1) + ' ' + str(int(y) - 1))\n neighbours.add(str(int(x) + 1) + ' ' + str(y))\n neighbours.add(str(int(x) + 1) + ' ' + str(int(y) + 1))\n neighbours.add(str(x) + ' ' + str(int(y) + 1))\n neighbours.add(str(int(x) - 1) + ' ' + str(int(y) + 1))\n return neighbours\n\n def get_radar_coordinates(self, radars):\n coordinates = []\n\n for radar in radars.values():\n coordinates.append(\n str(radar.__dict__['current_X']) + ' ' + str(radar.__dict__['current_Y']))\n\n return coordinates\n\n def get_trap_coordinates(self, traps):\n coordinates = []\n\n for trap in traps.values():\n coordinates.append(\n str(trap.__dict__['current_X']) + ' ' + str(trap.__dict__['current_Y']))\n\n return coordinates\n \n def count_available_ores(self):\n for i in range(height):\n for j in range(width):\n if self.oreMap[i][j] != '?' and self.oreMap[i][j] != '0':\n ore_point = str(j) + ' ' + str(i)\n ORES.add(ore_point)\n self.available_ores = self.available_ores + 1\n\n def count_holes(self):\n for i in range(height):\n for j in range(width):\n if self.holeMap[i][j] == 1:\n hole_point = str(j) + ' ' + str(i)\n HOLES.add(hole_point)\n\n\nclass Entity:\n def __init__(self, id, type, current_X, current_Y, item):\n self.id = id\n self.type = type\n self.current_X = current_X\n self.current_Y = current_Y\n self.item = item\n\n\nclass Action:\n def __init__(self, x_y, action):\n self.x_y = x_y\n self.action = action\n# END CLASSES ---------------------------------\n\n\n# height: size of the map\nwidth, height = [int(i) for i in input().split()]\n\n# game loop\nwhile True:\n hole_map = [[None for y in range(30)] for x in range(15)]\n ore_map = [[None for y in range(30)] for x in range(15)]\n # my_score: Amount of ore delivered\n my_score, opponent_score = [int(i) for i in input().split()]\n for i in range(height):\n inputs = input().split()\n for j in range(width):\n # ore: amount of ore or \"?\" if unknown\n # hole: 1 if cell has a hole\n ore = inputs[2*j]\n ore_map[i][j] = ore\n hole = int(inputs[2*j+1])\n hole_map[i][j] = hole\n # entity_count: number of entities visible to you\n # radar_cooldown: turns left until a new radar can be requested\n # trap_cooldown: turns left until a new trap can be requested\n entity_count, radar_cooldown, trap_cooldown = [\n int(i) for i in input().split()\n ]\n\n RADAR_COOLDOWN = radar_cooldown\n TRAP_COOLDOWN = trap_cooldown\n\n robots = dict()\n enemyRobots = dict()\n radars = dict()\n traps = dict()\n\n for i in range(entity_count):\n # entity_id: unique id of the entity\n # entity_type: 0 for your robot, 1 for other robot, 2 for radar, 3 for trap\n # y: position of the entity\n # item: if this entity is a robot, the item it is carrying (-1 for NONE, 2 for RADAR, 3 for TRAP, 4 for ORE)\n entity_id, entity_type, x, y, item = [int(j) for j in input().split()]\n entity = Entity(entity_id, entity_type, x, y, item)\n if entity.__dict__['type'] == 0:\n robots[entity_id] = entity\n elif entity.__dict__['type'] == 1:\n enemyRobots[entity_id] = entity\n elif entity.__dict__['type'] == 2:\n radars[entity_id] = entity\n else:\n traps[entity_id] = entity\n\n round = Round(ore_map, hole_map, robots, enemyRobots, radars, traps)\n ACTIONS = round.defineStrategyForEntities(round)\n\n TRAP_COOLDOWN = -1\n RADAR_COOLDOWN = -1\n\n for i in range(5):\n action = ACTIONS[i]\n xy = action.__dict__['x_y']\n act = action.__dict__['action']\n\n if xy == '':\n print(act)\n elif 'DIG' in act:\n print(act + xy)\n del ACTIONS[i]\n else:\n print(act + xy)\n\n # Write an action using print\n # To debug: print(\"Debug messages...\", file=sys.stderr)\n\n # WAIT|MOVE x y|DIG x y|REQUEST item\n","sub_path":"iteration.py","file_name":"iteration.py","file_ext":"py","file_size_in_byte":13720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"329560500","text":"import socket\n\n'''\nsocket 通信\n服务端\n'''\n# 创建服务端socket\n# AF_INET 设定ipv4\n# SOCK_STREAM 指定以流的方式进行传输\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# 绑定服务端地址和端口,创建一个服务器,参数是一个两个元素的元组,地址和端口\nserver.bind((\"192.169.30.183\", 8081))\n\n# 接受监听,5表示同时接受最多5个客户端的请求,目前形同虚设,待使用线程后体现\nserver.listen(5)\nprint(\"服务器启动成功....\")\n\n# 接受请求,返回两个值,一并接收,一个是客户端socket对象,一个是客户端地址\nclientSocket, clientAddr = server.accept()\nprint(\"接收到来自(%s, %s)客户端的请求\" %(str(clientSocket), clientAddr))\n\n# 定义一个死循环持续接收数据\nwhile True:\n\n # 接收来自客户端的数据,需要解码\n recvinfo = clientSocket.recv(1024).decode(\"utf-8\")\n print(recvinfo)\n\n # 发送给客户端数据,需要编码\n clientSocket.send(\"地瓜地瓜,我是土豆\".encode(\"utf-8\"))","sub_path":"26.网络编程socket/tcp/socket_tcp_server.py","file_name":"socket_tcp_server.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"368529646","text":"import torch\nimport json\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport pytorch_lightning as pl\nimport argparse\nimport os\n\nfrom models import Classifier, MultiTaskClassifier\nfrom data_utils import *\n#from data import MNLIDataset, StanceDataset, ParaphraseDataset\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom torch.utils.data import DataLoader\nfrom transformers import get_cosine_schedule_with_warmup\n\nclass BaselineTrainer(pl.LightningModule):\n \"\"\"Trainer for the baseline experiments which trains BERT + MLP.\"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.save_hyperparameters()\n self.model = Classifier(config)\n self.model.init_phi_normal(config['n_classes'])\n self.config = config\n self.loss_func = self.get_loss_func()\n\n def configure_optimizers(self):\n \"\"\"Configures optimizer for pytorch lightning.\"\"\"\n optimizer_dict = {\n \"sgd\": optim.SGD,\n \"adam\": optim.Adam\n }\n optimizer = optimizer_dict[self.config['optimizer']]\n self.optimizer = optimizer(self.model.parameters(), self.config['lr'])\n self.scheduler = get_cosine_schedule_with_warmup(self.optimizer, \n num_training_steps=config['n_steps'],\n num_warmup_steps=int(0.10*config['n_steps']))\n return [self.optimizer], self.scheduler\n\n def get_loss_func(self):\n \"\"\"Returns loss function specified in config.\"\"\"\n loss_dict = {\n \"ce\": nn.CrossEntropyLoss(),\n \"bce\": nn.BCEWithLogitsLoss()\n }\n return loss_dict[self.config['loss']]\n\n def forward(self, batch):\n \"\"\"Performs a forward pass on the batch.\"\"\"\n logits = self.model(self._to_device(batch['input_ids']), \n token_type_ids=self._to_device(batch['token_type_ids']), \n attention_mask=self._to_device(batch['attention_mask']))\n return logits\n\n def _to_device(self, inp):\n if not torch.is_tensor(inp):\n inp = torch.tensor(inp)\n return inp.to(self.config['device'])\n\n def calc_accuracy(self, logits, labels):\n \"\"\"Utility function to calculate the accuracy given logits and labels. \"\"\"\n if logits.size(-1) > 1:\n predictions = torch.argmax(logits, dim=1)\n else:\n predictions = (nn.functional.sigmoid(logits) > 0.5).float()\n return (predictions == labels).float().mean().item()\n\n def training_step(self, batch, batch_idx):\n \"\"\"Performs a single training step and logs metrics.\"\"\"\n labels = self._to_device(batch['labels'])\n logits = self.forward(batch)\n loss = self.loss_func(logits, labels)\n accuracy = self.calc_accuracy(logits, labels)\n\n sch = self.scheduler\n sch.step()\n\n self.log('train_loss', loss)\n self.log('train_accuracy', accuracy, on_step=False, on_epoch=True)\n return loss\n\n def evaluation_step(self, batch):\n \"\"\"Performs a single evaluation step.\"\"\"\n labels = self._to_device(batch['labels'])\n logits = self.forward(batch)\n loss = self.loss_func(logits, labels)\n accuracy = self.calc_accuracy(logits, labels)\n\n return loss, accuracy\n\n def validation_step(self, batch, batch_idx):\n \"\"\"Performs an evaluation step and logs metrics for validation set. \"\"\"\n loss, accuracy = self.evaluation_step(batch)\n\n self.log('validation_loss', loss)\n self.log('validation_accuracy', accuracy)\n\n def test_step(self, batch, batch_idx):\n \"\"\"Performs an evaluation step and logs metrics for test set.\"\"\"\n loss, accuracy = self.evaluation_step(batch)\n\n self.log('test_loss', loss)\n self.log('test_accuracy', accuracy)\n\n\nclass MultiTaskTrainer(pl.LightningModule):\n\n def __init__(self, config):\n super().__init__()\n self.save_hyperparameters()\n self.model = MultiTaskClassifier(config)\n self.config = config\n self.loss_func = nn.CrossEntropyLoss()\n self.cosines = {\"total\":[]}\n self.automatic_optimization = False\n self.lambda_ = self.config['lambda']\n self.grad_cum = config['grad_cum']\n self.task_grad_cums = {0: [0, None], 1: [0, None]}\n\n def forward(self, batch, src):\n \"\"\"Performs a forward pass on the batch.\"\"\"\n logits = self.model(self._to_device(batch['input_ids']),\n token_type_ids=self._to_device(batch['token_type_ids']),\n attention_mask=self._to_device(batch['attention_mask']),\n src=src)\n return logits\n\n def _to_device(self, inp):\n if not torch.is_tensor(inp):\n inp = torch.tensor(inp)\n return inp.to(self.config['device']) \n\n def calc_accuracy(self, logits, labels):\n \"\"\"Utility function to calculate the accuracy given logits and labels. \"\"\"\n if logits.size(-1) > 1:\n predictions = torch.argmax(logits, dim=1)\n else:\n predictions = (nn.functional.sigmoid(logits) > 0.5).float()\n return (predictions == labels).float().mean().item()\n\n def accumulate_grads(self, task):\n\n packed_grads = []\n for i, (name, param) in enumerate(self.model.named_parameters()):\n if 'src' not in name and 'aux' not in name and not 'encoder.pooler' in name:\n packed_grads.append(param.grad.flatten())\n\n packed_grads = torch.cat(packed_grads)\n if self.task_grad_cums[task][1] is None:\n self.task_grad_cums[task][1] = packed_grads\n self.task_grad_cums[task][0] += 1\n else:\n self.task_grad_cums[task][1] += packed_grads\n self.task_grad_cums[task][0] += 1\n\n def calc_cosine_sim(self, task):\n # check if we should accumulate or skip.\n if self.task_grad_cums[task][0] < self.grad_cum:\n self.accumulate_grads(task)\n \n # check if we can calculate cosine similarity.\n if self.task_grad_cums[0][0] == self.grad_cum and self.task_grad_cums[1][0] == self.grad_cum:\n cosine_sim = F.cosine_similarity(self.task_grad_cums[0][1], \n self.task_grad_cums[1][1],\n dim=0).item()\n self.cosines['total'].append(cosine_sim)\n \n # reset task_grads:\n self.task_grad_cums = self.task_grad_cums = {0: [0, None], 1: [0, None]}\n\n \n\n def training_step(self, batch, batch_idx):\n task, samples = batch \n opt = self.optimizers()\n labels = self._to_device(samples['labels'])\n\n src = bool(1 - task)\n logits = self.forward(samples, src=src)\n loss = self.loss_func(logits, labels)\n acc = self.calc_accuracy(logits, labels)\n \n opt.zero_grad()\n loss.backward()\n self.calc_cosine_sim(task) \n opt.step()\n\n sch = self.scheduler\n sch.step()\n\n if src:\n self.log('src_train_loss', loss)\n self.log('src_train_accuracy', acc)\n else:\n self.log('aux_train_loss', loss)\n self.log('aux_train_accuracy', acc)\n \n return loss\n\n def training_epoch_end(self, training_step_outputs):\n with open(self.config['cosine_file'], 'w') as f:\n json.dump(self.cosines, f)\n\n def evaluation_step(self, samples, task):\n labels = self._to_device(samples['labels'])\n\n src = bool(1 - task)\n logits = self.forward(samples, src=src)\n\n loss = self.loss_func(logits, labels)\n acc = self.calc_accuracy(logits, labels)\n\n return loss, acc\n\n def validation_step(self, batch, batch_idx, dataloader_idx=0):\n loss, acc = self.evaluation_step(batch, dataloader_idx)\n\n if dataloader_idx == 0:\n self.log('src_val_loss', loss)\n self.log('src_val_acc', acc)\n else:\n self.log('aux_val_loss', loss)\n self.log('aux_val_acc', acc)\n\n def test_step(self, batch, batch_idx, dataloader_idx):\n loss, acc = self.evaluation_step(batch, dataloader_idx)\n\n if dataloader_idx == 0:\n self.log('src_test_loss', loss)\n self.log('src_test_acc', acc)\n else:\n self.log('aux_test_loss', loss)\n self.log('aux_test_acc', acc)\n\n\n def configure_optimizers(self):\n self.opt = torch.optim.Adam(self.model.parameters())\n self.scheduler = get_cosine_schedule_with_warmup(self.opt, \n num_training_steps=config['n_steps'],\n num_warmup_steps=int(0.10*config['n_steps']))\n return [self.opt], [self.scheduler]\n\n\ndef train_model(loaders, config):\n \"\"\"Creates a trainer module and fits it on training + evaluation step.\n Performs evaluation on validation and test set after training.\n \"\"\"\n model_save_path = os.path.join(config['model_save_path'], config[\"save_name\"])\n n_gpus = 1 if torch.cuda.is_available() else 0\n early_stop_callback = EarlyStopping(\n monitor='validation_accuracy',\n patience=10,\n verbose=False,\n mode='max'\n )\n\n trainer = pl.Trainer(default_root_dir = model_save_path,\n checkpoint_callback = ModelCheckpoint(save_weights_only=True, mode='max', monitor='validation_accuracy'),\n gpus = n_gpus,\n max_steps = config['max_steps'],\n progress_bar_refresh_rate=1,\n gradient_clip_val=config[\"clip_value\"])\n trainer.logger._log_graph = True\n trainer.logger._default_hp_metric = None\n\n train_loader, dev_loader, test_loader = loaders\n\n if config['pretrained_model_path'] != \"\":\n model = BaselineTrainer.load_from_checkpoint(config['pretrained_model_path'])\n else:\n pl.seed_everything(config['seed'])\n model = BaselineTrainer(config)\n trainer.fit(model, train_loader, dev_loader)\n #model = BaselineTrainer.load_from_checkpoint(trainer.checkpoint_callback.best_model_path)\n\n if dev_loader is not None:\n validation_result = trainer.test(model, test_dataloaders=dev_loader, verbose=False)\n else:\n validation_result = [0]\n test_result = trainer.test(model, test_dataloaders=test_loader, verbose=False)\n\n results = {\n \"validation\": validation_result[0],\n \"test\": test_result[0]\n }\n return results\n\ndef train_multitask(src_loaders, aux_loaders, config):\n\n model_save_path = os.path.join(config[\"model_save_path\"], config[\"save_name\"])\n n_gpus = 1 if torch.cuda.is_available() else 0\n\n early_stop_callback = EarlyStopping(\n monitor='src_val_loss',\n patience=10,\n verbose=False,\n mode='min'\n )\n\n trainer = pl.Trainer(default_root_dir = model_save_path,\n checkpoint_callback = ModelCheckpoint(save_weights_only=True, mode='max', monitor='src_val_acc'),\n gpus = n_gpus,\n callbacks=[early_stop_callback],\n val_check_interval=20,\n max_steps = config['max_steps'],\n progress_bar_refresh_rate=0,\n gradient_clip_val=config['clip_value'])\n trainer.logger._log_graph = True\n trainer.logger._default_hp_metric = None\n\n train_loader = iter(MultiTaskLoader(src_loaders[0], aux_loaders[0], seed=config[\"seed\"]))\n #dev_loader = iter(MultiTaskLoader(src_loaders[1], aux_loaders[1], seed=config[\"seed\"]))\n #test_loader = iter(MultiTaskLoader(src_loaders[2], aux_loaders[2], seed=config[\"seed\"]))\n\n if config[\"pretrained_model_path\"] != \"\":\n model = MultiTaskTrainer.load_from_checkpoint(config['pretrained_model_path'])\n else:\n pl.seed_everything(config[\"seed\"])\n model = MultiTaskTrainer(config)\n trainer.fit(model, train_loader, src_loaders[1])\n\n validation_result = trainer.test(model, test_dataloaders=[src_loaders[1], aux_loaders[1]], verbose=False)\n test_result = trainer.test(model, test_dataloaders=[src_loaders[2], aux_loaders[2]], verbose=False)\n\n results = {\n \"validation\": validation_result[0],\n \"test\": test_result[0]\n }\n \n return results\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n # Model Arguments\n parser.add_argument(\"--n_classes\", type=int, default=3,\n help=\"Number of classes in the dataset.\")\n parser.add_argument(\"--freeze_bert\", action=\"store_true\",\n help=\"Whether to freeze bert parameters.\")\n parser.add_argument(\"--n_src_classes\", type=int, default=2)\n parser.add_argument(\"--n_aux_classes\", type=int, default=2)\n\n # Training Arguments\n parser.add_argument(\"--optimizer\", type=str, default=\"adam\",\n help=\"Which optimizer to use.\")\n parser.add_argument(\"--loss\", type=str, default=\"ce\",\n help=\"Which loss function to use.\")\n parser.add_argument(\"--lr\", type=float, default=0.0001,\n help=\"Learning rate for training.\")\n parser.add_argument(\"--max_epochs\", type=int, default=10,\n help=\"Maximum number of epochs to train for.\")\n parser.add_argument(\"--seed\", type=int, default=42,\n help=\"Random seed.\")\n parser.add_argument(\"--batch_size\", type=int, default=8,\n help=\"Size of training batches.\")\n parser.add_argument(\"--device\", default=torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\"))\n parser.add_argument(\"--dataset_name\", type=str, default=\"mnli\",\n help=\"Name of the dataset to train on.\")\n parser.add_argument(\"--train_split\", type=float, default=0.8,\n help=\"Fraction of training data to use for trainin set, the rest will go to val set.\")\n parser.add_argument(\"--multitask\", action=\"store_true\",\n help=\"whether to perform multitask training.\")\n parser.add_argument(\"--lambda\", type=float, default=0.1,\n help=\"Ratio of aux loss w.r.t. src loss\")\n parser.add_argument(\"--max_steps\", type=int, default=10000,\n help=\"maximum number of training steps.\")\n\n # Directory Arguments\n parser.add_argument(\"--model_save_path\", type=str, default=\"checkpoints\",\n help=\"Directory to store trained models.\")\n parser.add_argument(\"--pretrained_model_path\", type=str, default=\"\",\n help=\"Path to pretrained model.\")\n parser.add_argument(\"--save_name\", type=str, default=\"bert_mlp\")\n parser.add_argument(\"--cosine_file\", type=str, default=\"checkpoints/cosine.txt\")\n parser.add_argument(\"--dataset_file\", type=str, default=\"data/Stance/claim_stance_dataset_v1.csv\")\n parser.add_argument(\"--grad_cum\", type=int, default=4)\n parser.add_argument(\"--clip_value\", type=float, default=1.5)\n\n config = parser.parse_args().__dict__\n\n para_train = ScitailDataset.read(path='data/SciTailV1.1/', split='train')\n para_dev = ScitailDataset.read(path='data/SciTailV1.1/', split='dev')\n para_train_load = DataLoader(para_train, \n batch_size=config['batch_size'], \n shuffle=True,\n collate_fn=collator2)\n para_dev_load = DataLoader(para_dev, \n batch_size=config['batch_size'], \n collate_fn=collator2)\n\n para_test = ScitailDataset.read(path='data/SciTailV1.1/', split='test')\n para_test_load = DataLoader(para_test, \n batch_size=config['batch_size'], \n collate_fn=collator2)\n\n config['n_steps'] = len(para_train) * config['max_epochs']\n\n if config[\"multitask\"]:\n stance_train = ScitailDataset.read(path='data/SciTailV1.1/', split='train')\n stance_dev = ScitailDataset.read(path='data/SciTailV1.1/', split='dev')\n stance_train_load = DataLoader(stance_train,\n batch_size=config['batch_size'],\n shuffle=True,\n collate_fn=collator2)\n stance_dev_load = DataLoader(stance_dev,\n batch_size=config['batch_size'],\n shuffle=True,\n collate_fn=collator2)\n stance_test = ScitailDataset.read(path='data/SciTailV1.1/', split='test')\n stance_test_load = DataLoader(stance_test,\n batch_size=config['batch_size'],\n shuffle=True,\n collate_fn=collator2) \n \n # LETOP!! src & aux omgewisseld.\n train_multitask([stance_train_load, stance_dev_load, stance_test_load],\n [para_train_load, para_dev_load, para_test_load],\n config)\n\n else:\n train_model([para_train_load, para_dev_load, para_test_load], config)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":17551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"255352934","text":"# -*- coding: utf-8 -*-\n\nclass Env(dict):\n\n def __init__(self, parms=(), args=(), outer=None):\n self.update(zip(parms, args))\n self.outer = outer\n\n def find(self, var):\n return self if var in self else self.outer.find(var)\n\n\ndef add_globals(env):\n import math\n import operator as op\n from functools import reduce\n env.update(vars(math))\n # + - * /\n env.update({\n '+': lambda *args: sum(args), \n '-': lambda *args: reduce(op.sub, args),\n '*': lambda *args: reduce(op.mul, args),\n '/': lambda *args: reduce(op.truediv, args),\n })\n # bool operator\n env.update({'>': op.gt, '<': op.lt, '>=': op.ge, '<=': op.le, '=': op.eq,})\n # bool keyword\n env.update({\n 'not': op.not_,\n })\n # cons cell\n env.update(dict(\n cons=lambda x, y: [x, y],\n car=lambda x: x[0],\n cdr=lambda x: x[1],\n list=lambda *args: list(args),\n ))\n # type judge\n env.update({\n 'null?': lambda x: x == [],\n 'symbol?': lambda x: isinstance(x, str),\n 'list?': lambda x: isinstance(x, list),\n })\n return env\nglobal_env = add_globals(Env())\n\n\nclass Execution(object):\n\n def eval_define(self, x, env):\n _, var, exp = x\n if isinstance(var, list):\n func, *parms = var\n env[func] = lambda *args: self.eval(exp, Env(parms, args, env))\n else:\n env[var] = self.eval(exp, env)\n\n def eval(self, x, env=global_env):\n if isinstance(x, str):\n return env.find(x)[x]\n if not isinstance(x, list):\n return x\n if x[0] == 'define':\n return self.eval_define(x, env)\n if x[0] == 'set!':\n _, var, _ = x\n var_env = env.find(var)\n return self.eval_define(x, var_env)\n if x[0] == 'if':\n _, text, conseq, alt = x\n return self.eval(conseq if self.eval(text, env) else alt, env)\n if x[0] == 'lambda':\n _, parms, exp = x\n return lambda *args: self.eval(exp, Env(parms, args, env))\n if x[0] == 'begin':\n for exp in x[1:]:\n val = self.eval(exp, env)\n return val\n if x[0] == 'quote':\n _, exp = x\n return exp\n exps = [self.eval(exp, env) for exp in x]\n proc = exps.pop(0)\n return proc(*exps)\n\n def __call__(self, x, env=global_env):\n return self.eval(x, env)\n","sub_path":"app/execution.py","file_name":"execution.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"248376200","text":"# coding: utf-8\nfrom flask import Flask, jsonify, abort, request\n\nfrom sklearn import cross_validation\nfrom sklearn.linear_model import LogisticRegression\n\nimport MeCab\nfrom datetime import datetime\n\ndef _nest(list):\n \"\"\"return nest\"\"\"\n return [y for x in list for y in x]\n\n\ndef _get_accuracy_score(clf, data, label, test_size=0.2):\n \"\"\"get accuracy score and cross_validation.\"\"\"\n X_train, X_test, y_train, y_test = cross_validation.train_test_split(\n data, label, test_size=test_size)\n clf.fit(X_train, y_train)\n return clf.score(X_test, y_test)\n\nif __name__ == \"__main__\":\n from TF_IDF import get_tf_idf\n import json\n import sys\n\n TAGGER = MeCab.Tagger(\"-Owakati\")\n clf = LogisticRegression()\n prediction_algorithm = \"Logistic regression\"\n\n with open(sys.argv[1], \"r\") as f:\n data = json.load(f)\n targets = [data[\"files\"][\"text_0\"], data[\"files\"][\"text_1\"]]\n label_names = data[\"label_names\"]\n print(\"[INFO]: mode: {}\".format(data[\"mode\"]))\n\n vectorizer, vectorizer_toarray, label, data_count = get_tf_idf(\n targets, \"data/Japanese.txt\")\n\n x = 3\n average_correct_answer_rate = sum([_get_accuracy_score(\n clf, vectorizer_toarray, label, test_size=0.2) for i in range(x)]) / x\n print(\"[INFO]: average_correct_answer_rate: {}\".format(\n average_correct_answer_rate))\n\n vectorizer_toarray, label = 0, 0\n print(\"[INFO]: close [vectorizer_toarray, label]\")\n app = Flask(__name__)\n\n @app.route(\"/api/v1/is_{}/\".format(data[\"mode\"]))\n def API(text):\n \"\"\"Main API CODE\n url: /api/v1/is_XXX/text\n return result.\"\"\"\n try:\n data = vectorizer.transform(\n [TAGGER.parse(text).replace(\"\\n\", \"\")]).toarray()\n result_code = int(clf.predict(data))\n result_text = label_names[result_code]\n Probability = _nest(list(clf.predict_proba(data)))\n with open(\"log.txt\", \"a\") as f:\n f.write(\"{}: {}: {}\\n\".format(datetime.now().strftime(\n \"%Y/%m/%d %H:%M:%S\"), text, request.headers.get(\"User-Agent\")))\n except:\n result = \"error\"\n result = {\n \"status\": result_text,\n \"result_info\": {\n \"average_correct_answer_rate\": average_correct_answer_rate,\n \"result_code\": result_code,\n \"Probability\": {\n \"class_{}\".format(label_names[0]): Probability[0],\n \"class_{}\".format(label_names[1]): Probability[1]\n }\n },\n \"data_info\": {\n \"data_count\": {\n \"text_{}\".format(label_names[0]): data_count[0],\n \"text_{}\".format(label_names[1]): data_count[1]\n }\n }\n }\n return jsonify(result)\n\n app.run(host='0.0.0.0', port=9000)\n","sub_path":"v1_API.py","file_name":"v1_API.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"31628665","text":"\"\"\"\nCS1101S Attendance Bot\n\nCurrent Version Developed by Chaitanya Baranwal and Raivat Shah\nProject founded by Advay Pal, Chaitanya Baranwal and Raivat Shah.\n\nProject supervised by A/P Martin Henz and Visiting Professor Tobias Wrigstad\n\nReleased Under MIT License.\n\"\"\"\n# Imports\nimport os\nimport json\nimport logging\nfrom telegram import ReplyKeyboardMarkup\nfrom telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport redis\nimport time\n\n#######################################\n### SETUP REQUIRED GLOBAL VARIABLES ###\n#######################################\n\n# Function to determine column based on date for Reflection Spreadsheet\ndef get_week_ref():\n cur_time = time.asctime()\n li = cur_time.split()\n month = li[1]\n date = int(li[2]) # convert to integer for comparison later\n with open('acad_calendar.json') as acad_calendar:\n data = json.load(acad_calendar)\n for date_range in data[month].keys():\n start = int(date_range.split('-')[0])\n end = int(date_range.split('-')[1])\n if start <= date <= end:\n return data[month][date_range]\n return 'Z'\n\n# Function to determine column based on date for Studio Spreadsheet\ndef get_week_stu():\n cur_time = time.asctime()\n li = cur_time.split()\n month = li[1]\n date = int(li[2]) # convert to integer for comparison later\n with open('acad_calendar_studio.json') as acad_calendar:\n data = json.load(acad_calendar)\n for date_range in data[month].keys():\n start = int(date_range.split('-')[0])\n end = int(date_range.split('-')[1])\n if start <= date <= end:\n return data[month][date_range]\n return 'Z'\n\n# Enable logging\nlogging.basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n# Constants for conversation handler\nSELECT_STUDENT, ENTER_COMMENT = range(2)\n\n# Redis - stores mapping of Telegram username to Row Number on Google Spreadsheet.\nredis_client = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)\n\n# Dictionaries storing the various mappings for the Telegram bot\nSTUDENT_MAP = \"STUDENT_MAP\" # Maps student's telegram @username to row num and username\nUSERNAME_MAP = \"USERNAME_MAP\" # Maps student's name to their telegram username/ID\nTUTOR_MAP = \"TUTOR_MAP\" # Maps @username of staff to state (\"no\"/token)\nTOKEN_MAP = \"TOKEN_MAP\" # Maps the set of active tokens to a capacity, type, status and current students\nAVENGER_MAP = \"AVENGER_MAP\" # Maps @username of avenger to token number\n\n# for Feedback. Stores current row_num for feedback in the Google Spreadsheet\nif not redis_client.hexists(TOKEN_MAP, \"feedback\"):\n redis_client.hset(TOKEN_MAP, \"feedback\", json.dumps({'capacity': 2, 'active': True, 'type': 'feedback', 'students': []}))\n\n# Google Spreadsheet\nscope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('CS1101S Bot-99365efd2073.json', scope)\ngc = gspread.authorize(credentials)\nwks1 = gc.open(\"CS1101S Reflection Attendance\").sheet1 # For Reflection\nwks2 = gc.open(\"CS1101S Studio Attendance\").sheet1 # For studio\nwk3 = gc.open(\"CS1101S Bot Feedback\").sheet1 # For Bot Feedback\n# wk4 = gc.open(\"CS1101S Avenger Feedback\").sheet1 # For Avenger Feedback, disabled because this is giving error\n\ndef get_user_id_or_username(update):\n \"\"\"\n Function to get username or user ID depending on what is available.\n \"\"\"\n user_id = update.message.from_user.id\n username = update.message.from_user.username\n if username:\n return username\n else:\n return user_id\n\n##### Tutor #######\n\ndef start_session(update, context):\n \"\"\"\n Function to start an attendance taking session.\n \"\"\"\n # Store tutor usernames\n username = get_user_id_or_username(update)\n if not (redis_client.hexists(TUTOR_MAP, username) or redis_client.hexists(AVENGER_MAP, username)):\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Sorry! You're not registered as a staff member and hence cannot use this command\")\n return\n if len(context.args) == 0:\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Insufficient number of arguments. Please enter number of students along with \"\n \"the /start_session command\")\n return\n if int(context.args[0]) <= 0:\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Number of students must be greater than 0.\")\n return\n token = generate_hash()\n if redis_client.hexists(TUTOR_MAP, username):\n if redis_client.hget(TUTOR_MAP, username) != \"No\":\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"A session is already running. Please use /stop_session to stop it\")\n return\n\n redis_client.hdel(TOKEN_MAP, redis_client.hget(TUTOR_MAP, username))\n redis_client.hset(TUTOR_MAP, username, token) # Make tutor active. Store string value of token as value\n token_data = {\n 'capacity': int(context.args[0]),\n 'type': 'r',\n 'active': True,\n 'students': []\n }\n redis_client.hset(TOKEN_MAP, token, json.dumps(token_data)) # Activate Token and store capacity\n context.bot.send_message(chat_id=update.message.chat_id, text=f'You have successfully started a Reflection '\n f'Session. '\n f'Your token is {token}. Please write it on a '\n f'board to share it with students')\n else: # avenger\n avenger_token = redis_client.hget(AVENGER_MAP, username)\n if avenger_token != \"No\" and json.loads(redis_client.hget(TOKEN_MAP, avenger_token))['active']:\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"A session is already running. Please use /stop_session to stop it\")\n return\n\n redis_client.hdel(TOKEN_MAP, redis_client.hget(AVENGER_MAP, username))\n redis_client.hset(AVENGER_MAP, username, token)\n token_data = {\n 'capacity': int(context.args[0]),\n 'type': 's',\n 'active': True,\n 'students': []\n }\n redis_client.hset(TOKEN_MAP, token, json.dumps(token_data))\n context.bot.send_message(chat_id=update.message.chat_id,\n text=f'You have successfully started a Studio Session. '\n f'Your token is {token}. Please write it on a board to share it with students')\n\ndef stop_session(update, context):\n \"\"\"\n Function to stop an attendance session.\n \"\"\"\n username = get_user_id_or_username(update)\n if not (redis_client.hexists(TUTOR_MAP, username) or redis_client.hexists(AVENGER_MAP, username)):\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Sorry! You're not registered as a staff member and hence cannot use this command\")\n return\n # stop the session\n if redis_client.hexists(TUTOR_MAP, username):\n token = redis_client.hget(TUTOR_MAP, username)\n if (token == \"No\") or (not json.loads(redis_client.hget(TOKEN_MAP, token))['active']):\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"You've not started a session yet. Please send /start_session to start a session\")\n return\n redis_client.hset(TUTOR_MAP, username, \"No\") # Tutor is not active anymore\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Your Reflection Session has successfully stopped. Thanks!\")\n else:\n token = redis_client.hget(AVENGER_MAP, username)\n if (token == \"No\") or (not json.loads(redis_client.hget(TOKEN_MAP, token))['active']):\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"You've not started a session yet. Please send /start_session to start a session\")\n return\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Your Studio Session has successfully stopped. Thanks!\")\n token_in_token_map = json.loads(redis_client.hget(TOKEN_MAP, token))\n token_in_token_map['active'] = False\n redis_client.hset(TOKEN_MAP, token, json.dumps(token_in_token_map))\n\ndef generate_hash():\n \"\"\"\n Function to generate the attendance token hash.\n \"\"\"\n token = hash(time.time()) % 100000000\n return token\n\n##### Student ##########\n\ndef start(update, context):\n \"\"\"\n Start function for the bot.\n \"\"\"\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Welcome to CS1101S Cadet! This bot records your attendance for reflection sessions.\"\n \"Please send /setup to get started.\")\n\ndef setup(update, context):\n \"\"\"\n Function to setup the username of student user and\n store it in the key-value database.\n \"\"\"\n # check if no args\n if len(context.args) == 0:\n context.bot.send_message(chat_id=update.message.chat_id, text='Please enter your student number along with the '\n 'command. Eg if your student number is '\n 'A0123456X, enter /setup A0123456X')\n return\n # check if already registered\n username = get_user_id_or_username(update)\n if redis_client.hexists(STUDENT_MAP, username):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"You're already signed up! Please wait for your\"\n \" tutor to give you a token to mark \"\n \"attendance\")\n return\n # check if student can register for this module!\n student_no = context.args[0]\n try:\n refresh_gsp() #refresh api auth\n cell = wks1.find(student_no) # Look in reflection sessions\n row_num = cell.row\n student_details = {\n 'row': row_num,\n 'name': wks2.acell(f'A{row_num}').value\n }\n redis_client.hset(STUDENT_MAP, username, json.dumps(student_details))\n redis_client.hset(USERNAME_MAP, student_details['name'], username)\n context.bot.send_message(chat_id=update.message.chat_id, text=\"You're successfully registered! Please wait \"\n \"for your tutor to give you an attendance token\")\n # store in redis client\n except gspread.exceptions.CellNotFound:\n context.bot.send_message(chat_id=update.message.chat_id, text=\"Sorry! Your student number is not registered \"\n \"for this module. Please contact a staff \"\n \"member.\")\n\ndef attend(update, context):\n \"\"\"\n Function to mark attendance of bot user.\n \"\"\"\n # check if no args\n if len(context.args) == 0:\n context.bot.send_message(chat_id=update.message.chat_id, text='Insufficient number of arguments. Please enter '\n 'the token along with the /attend command')\n return\n # check if registered or not\n username = get_user_id_or_username(update)\n if not redis_client.hexists(STUDENT_MAP, username):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"You've not registered yet. Please send /setup \"\n \" to register\")\n return\n # decide reflection or studio\n token = context.args[0]\n if not redis_client.hexists(TOKEN_MAP, token): # Not active token\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Token doesn't exist or has expired. Please contact your tutor.\")\n return\n token_type = json.loads(redis_client.hget(TOKEN_MAP, token))['type']\n refresh_gsp() #refresh api auth\n if token_type == \"r\": # reflection session\n col_name_reflect = get_week_ref()\n # check if already attended for current week\n row_name = json.loads(redis_client.hget(STUDENT_MAP, username))['row'] # (TODO) make sure the row number are same for each student in both the different sheets\n val = wks1.acell(f'{col_name_reflect}{row_name}').value # check reflection sheet\n if val == \"1\":\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Your attendance for this week has already been \"\n \"marked. Thanks!\")\n else:\n # Token Logic\n curr_capacity = json.loads(redis_client.hget(TOKEN_MAP, token))['capacity']\n if curr_capacity == 0:\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Cannot take attendance. Your class is full. Please contact tutor as \"\n \"someone may be trying to get undue points for attendance\")\n return\n else:\n # set attendance\n wks1.update_acell(f'{col_name_reflect}{row_name}', '1')\n context.bot.send_message(chat_id=update.message.chat_id, text=\"Your attendance for this week has been \"\n \"successfully marked. Thanks!\")\n token_map = json.loads(redis_client.hget(TOKEN_MAP, token))\n token_map['capacity'] -= 1\n redis_client.hset(TOKEN_MAP, token, json.dumps(token_map)) # reduce capacity\n return\n\n elif token_type == \"s\": # studio session\n # check if already attended for current week\n col_name_attend = get_week_stu()\n row_name = json.loads(redis_client.hget(STUDENT_MAP, username))['row'] # (TODO) make sure the row number are same for each student in both\n # the different sheets\n val = wks2.acell(f'{col_name_attend}{row_name}').value\n if val == \"1\":\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Your attendance for this week has already been \"\n \"marked. Thanks!\")\n else:\n if not redis_client.hexists(TOKEN_MAP, token): # Not active token\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Token doesn't exist or has expired. Please contact your avenger.\")\n return\n curr_capacity = json.loads(redis_client.hget(TOKEN_MAP, token))['capacity']\n if curr_capacity == 0:\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Cannot take attendance. Your class is full. Please contact Avenger as \"\n \"someone may be trying to get undue points for attendance\")\n return\n else:\n # set attendance\n wks2.update_acell(f'{col_name_attend}{row_name}', '1')\n context.bot.send_message(chat_id=update.message.chat_id, text=\"Your attendance for this week has been \"\n \"successfully marked. Thanks!\")\n token_map = json.loads(redis_client.hget(TOKEN_MAP, token))\n student_list = token_map['students'].copy()\n student_list.append(json.loads(redis_client.hget(STUDENT_MAP, username))['name'])\n token_map['capacity'] -= 1\n token_map['students'] = student_list\n redis_client.hset(TOKEN_MAP, token, json.dumps(token_map)) # reduce capacity\n return\n\ndef refresh_gsp():\n \"\"\"\n Function to refresh Google Spreadsheet API token when it has expired.\n \"\"\"\n global gc\n global credentials\n if credentials.access_token_expired:\n gc.login()\n\ndef help_func(update, context):\n \"\"\"\n Function to generate help text.\n \"\"\"\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Here are the available functions in the bot:\\n\"\n \"For students: \\n\"\n \"/setup : to register yourself.\\n\"\n \"/attend to mark your attendance. Token will be provided by cluster leader.\\n\"\n \"/attendance_reflection to check your attendance for reflection sessions\\n\"\n \"/attendance_studio to check your attendance for studio sessions\\n\"\n \"For avengers/tutors: \\n\"\n \"/start_session to mark the attendance for your group of \"\n \"avengers.\\n\"\n \"/stop_session to stop your current running session.\\n\"\n \"/comment to trigger a set of commands to give feedback to students\\n\"\n \"For all: \\n\"\n \"/bot_feedback to give feedback or report bugs to the developers.\\n\")\n\ndef change_username(update, context): # (TODO) Review code for avenger vs student vs tutor reflection\n \"\"\"\n Function to change the username of bot user.\n \"\"\"\n if len(context.args) == 0:\n context.bot.send_message(chat_id=update.message.chat_id, text='Please enter your student number along with the '\n 'command. Eg if your student number is '\n '123456789, enter /change_username 123456789')\n else:\n username = get_user_id_or_username(update)\n student_no = context.args[0]\n try:\n refresh_gsp() #refresh api auth\n cell = wks1.find(student_no) # Look in reflection sessions\n row_num = cell.row\n student_details = {\n 'row': row_num,\n 'name': wks2.acell(f'A{row_num}').value\n }\n redis_client.hset(STUDENT_MAP, username, json.dumps(student_details))\n redis_client.hset(USERNAME_MAP, student_details['name'], username)\n context.bot.send_message(chat_id=update.message.chat_id, text=\"You've successfully changed your username.\")\n # store in redis client\n except gspread.exceptions.CellNotFound:\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Sorry! Your student number is not registered \"\n \"for this module. Please contact a staff \"\n \"member.\")\n\ndef bot_feedback(update, context):\n \"\"\"\n Function to give feedback to the developers.\n \"\"\"\n if len(context.args) == 0:\n context.bot.send_message(chat_id=update.message.chat_id, text='Please send your valuable feedback along with '\n 'this /feedback command, all in the same '\n 'message')\n else:\n name = update.message.from_user.first_name\n username = get_user_id_or_username(update)\n refresh_gsp() #refresh api auth\n feedback_token = json.loads(redis_client.hget(TOKEN_MAP, \"feedback\"))\n row = feedback_token['capacity']\n wk3.update_acell(\"A\" + row, name)\n wk3.update_acell(\"B\" + row, username)\n wk3.update_acell(\"C\" + row, print_arr(context.args))\n feedback_token['capacity'] += 1\n redis_client.hset(TOKEN_MAP, \"feedback\", json.dumps(feedback_token)) # update row num for other feedback\n context.bot.send_message(chat_id=update.message.chat_id, text=\"Thank you so much for your valuable feedback!\")\n\ndef attendance_reflection(update, context):\n \"\"\"\n Function to know attendance so far for reflection sessions\n \"\"\"\n # if not registered\n username = get_user_id_or_username(update)\n if not redis_client.hexists(STUDENT_MAP, username):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"You've not registered yet. Please send /setup \"\n \" to register\")\n else: # iterate through columns of the row, checking for instances where the attendance is marked.\n refresh_gsp() #refresh api auth\n row_num = json.loads(redis_client.hget(STUDENT_MAP, username))['row']\n weeks = []\n week_counter = 2\n for i in range(66, 78):\n col = chr(i)\n if wks1.acell(f'{col}{row_num}').value == '1':\n weeks.append(\"Week \" + str(week_counter))\n week_counter += 1\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Our records indicate that you've so far attended reflection sessions for: \"\n + print_arr(weeks) + \". Please contact a staff member if there is a discrepancy\")\n\ndef attendance_studio(update, context):\n \"\"\"\n Function to know attendance so far for studio sessions\n \"\"\"\n # if not registered\n username = get_user_id_or_username(update)\n if not redis_client.hexists(STUDENT_MAP, username):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"You've not registered yet. Please send /setup \"\n \" to register\")\n else: # iterate through columns of the row, checking for instances where the attendance is marked.\n refresh_gsp() #refresh api auth\n row_num = json.loads(redis_client.hget(STUDENT_MAP, username))['row']\n weeks = []\n week_counter = 2\n for i in range(67, 90, 2):\n col = chr(i)\n if wks2.acell(f'{col}{row_num}').value == '1':\n weeks.append(\"Week \" + str(week_counter)) # (TODO) fix counting error\n week_counter += 1\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Our records indicate that you've so far attended studio sessions for: \" +\n print_arr(weeks) + \". Please contact a staff member if there is a discrepancy\")\n\ndef comment(update, context):\n \"\"\"\n Function to comment on students who attended tutorial\n \"\"\"\n username = get_user_id_or_username(update)\n if not redis_client.hexists(AVENGER_MAP, username):\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Sorry! You're not registered as an avenger and hence cannot use this command.\")\n return ConversationHandler.END\n refresh_gsp()\n token = redis_client.hget(AVENGER_MAP, username)\n if token == \"No\":\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Sorry! Seems like no previous session is registered for you to comment on.\")\n return ConversationHandler.END\n\n students = json.loads(redis_client.hget(TOKEN_MAP, token))['students']\n if len(students) == 0:\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"No students have signed up yet!\")\n return ConversationHandler.END \n reply_keyboard = [[i] for i in students]\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Select a student from the list below. Type /cancel to cancel the process.\",\n reply_markup=ReplyKeyboardMarkup(reply_keyboard))\n return SELECT_STUDENT\n\ndef select_student(update, context):\n \"\"\"\n This function is reached after the student name has been entered.\n \"\"\"\n student = update.message.text\n context.user_data['student'] = redis_client.hget(USERNAME_MAP, student)\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Okay, enter the comment for this student.\")\n return ENTER_COMMENT\n\ndef enter_comment(update, context):\n \"\"\"\n This function is reached after the comment has been entered.\n \"\"\"\n comment = update.message.text\n student = context.user_data['student']\n col_name_comment = chr(ord(get_week_stu()) + 1)\n row_name = json.loads(redis_client.hget(STUDENT_MAP, student))['row']\n wks2.update_acell(f'{col_name_comment}{row_name}', comment)\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Okay! Comment has been added.\")\n return ConversationHandler.END\n\ndef cancel(update, context):\n context.bot.send_message(chat_id=update.message.chat_id,\n text=\"Okay! Commenting canceled.\")\n return ConversationHandler.END\n\n\ndef print_arr(arr):\n \"\"\"\n Function to get the string version of an array in one line.\n \"\"\"\n runner = \"\"\n for item in arr:\n runner += item + \" \"\n return runner\n\ndef init_data():\n \"\"\"\n Setup initial data in the Redis database.\n \"\"\"\n # Setup module/admin staff in Redis database\n with open('people.json') as people_json:\n data = json.load(people_json)\n for staff_member in data['staff']:\n if not redis_client.hexists(TUTOR_MAP, staff_member):\n redis_client.hset(TUTOR_MAP, staff_member, \"No\")\n for admin_member in data['admin']:\n if not redis_client.hexists(TUTOR_MAP, admin_member):\n redis_client.hset(TUTOR_MAP, admin_member, \"No\")\n for avenger in data['avenger']:\n if not redis_client.hexists(AVENGER_MAP, avenger):\n redis_client.hset(AVENGER_MAP, avenger, \"No\")\n redis_client.hset(AVENGER_MAP, \"raivatshah\", \"No\") # for testing.\n\ndef main():\n \"\"\"Start the bot\"\"\"\n # Create an event handler, # (TODO) hide key\n updater = Updater(os.environ.get('TELEKEY'), use_context=True)\n \n # Setup data in the Redis database\n init_data()\n\n # Get dispatcher to register handlers\n dp = updater.dispatcher\n\n # Register different commands\n dp.add_handler(CommandHandler('start', start))\n dp.add_handler(CommandHandler('setup', setup))\n dp.add_handler(CommandHandler('attend', attend))\n dp.add_handler(CommandHandler('start_session', start_session))\n dp.add_handler(CommandHandler('stop_session', stop_session))\n dp.add_handler(CommandHandler('change_username', change_username))\n dp.add_handler(CommandHandler('help', help_func))\n dp.add_handler(CommandHandler('attendance_reflection', attendance_reflection))\n dp.add_handler(CommandHandler('attendance_studio', attendance_studio))\n dp.add_handler(CommandHandler('bot_feedback', bot_feedback))\n\n # Create a conversation handler for commenting\n conv_handler = ConversationHandler(\n entry_points=[CommandHandler('comment', comment)],\n states={\n SELECT_STUDENT: [MessageHandler(Filters.text, select_student)],\n ENTER_COMMENT: [MessageHandler(Filters.text, enter_comment)]\n },\n fallbacks=[CommandHandler('cancel', cancel)]\n )\n dp.add_handler(conv_handler)\n\n # Start the bot\n updater.start_polling()\n\n # Run the bot until you press Ctrl-C\n updater.idle()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":28391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"579160623","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDisplay track currently playing in deadbeef.\n\nConfiguration parameters:\n cache_timeout: how often we refresh usage in seconds (default: 1s)\n format: see placeholders below\n delimiter: delimiter character for parsing (default: ¥)\n\nFormat of status string placeholders:\n {artist} artist\n {title} title\n {elapsed} elapsed time\n {length} total length\n {year} year\n {tracknum} track number\n\n\nRequires:\n deadbeef:\n\n@author mrt-prodz\n\"\"\"\nfrom subprocess import check_output, CalledProcessError\nfrom time import time\n\n\nclass Py3status:\n # available configuration parameters\n cache_timeout = 1\n delimiter = '¥'\n format = '{artist} - {title}'\n\n # return error occurs\n def _error_response(self, color):\n response = {\n 'cached_until': time() + self.cache_timeout,\n 'full_text': 'deadbeef: error',\n 'color': color\n }\n return response\n\n # return empty response\n def _empty_response(self):\n response = {\n 'cached_until': time() + self.cache_timeout,\n 'full_text': ''\n }\n return response\n\n # return track currently playing in deadbeef\n def get_status(self, i3s_output_list, i3s_config):\n try:\n # check if we have deadbeef running\n check_output(['pidof', 'deadbeef'])\n except CalledProcessError:\n return self._empty_response()\n\n try:\n # get all properties using ¥ as delimiter\n status = check_output(['deadbeef',\n '--nowplaying',\n self.delimiter.join(['%a',\n '%t',\n '%l',\n '%e',\n '%y',\n '%n'])])\n\n if status == 'nothing':\n return self._empty_response()\n\n # split properties using special delimiter\n parts = status.split(self.delimiter)\n if len(parts) == 6:\n artist, title, length, elapsed, year, tracknum = parts\n else:\n return self._error_response(i3s_config['color_bad'])\n\n response = {\n 'cached_until': time() + self.cache_timeout,\n 'full_text': self.format.format(artist=artist,\n title=title,\n length=length,\n elapsed=elapsed,\n year=year,\n tracknum=tracknum)\n }\n return response\n except:\n return self._error_response(i3s_config['color_bad'])\n\nif __name__ == \"__main__\":\n \"\"\"\n Test this module by calling it directly.\n \"\"\"\n x = Py3status()\n config = {\n 'color_good': '#00FF00',\n 'color_degraded': '#00FFFF',\n 'color_bad': '#FF0000'\n }\n print(x.get_status([], config))\n","sub_path":"py3status/modules/deadbeef.py","file_name":"deadbeef.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"472514894","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: c:\\Users\\asus\\Desktop\\PythonGameEngine\\Walimaker\\screen.py\n# Compiled at: 2019-08-30 07:29:48\n# Size of source mod 2**32: 2348 bytes\nfrom .config import *\nfrom .camera import Camera\nfrom .physics import *\n\ndef setup(*size):\n if not (isinstance(size[0], int) and isinstance(size[1], int)):\n raise TypeError('类型错误:参数必须为整数')\n if len(size) != 2:\n raise TypeError('类型错误:参数数目错误,只允许两个参数')\n global_var.SCREEN = Screen(size)\n global_var.WIDTH, global_var.HEIGHT = size\n global_var.ALL_SPRITES = pygame.sprite.LayeredDirty()\n global_var.CAMERA = Camera(size)\n global_var.SPACE = pymunk.Space()\n global_var.SPACE.collision_bias = 0\n global_var.SPACE.gravity = (0, 0)\n global_var.BODIES = BodiesGroup()\n global_var.TMBG = TiledMapBodiesGroup()\n return global_var.SCREEN\n\n\ndef title(title):\n pygame.display.set_caption(title)\n\n\ndef update():\n global_var.SCREEN.update()\n global_var.JUST_RELEASED = False\n\n\ndef save_screen(name):\n global_var.SCREEN.save_name = name\n\n\ndef done():\n while True:\n global_var.SCREEN.update()\n\n\nclass Screen:\n\n def __init__(self, size):\n self.size = size\n self._screen = pygame.display.set_mode(size)\n self._clock = pygame.time.Clock()\n self.save_name = None\n\n def update(self):\n global_var.EVENTS = pygame.event.get()\n for event in global_var.EVENTS:\n if event.type == pygame.QUIT:\n pygame.quit()\n os._exit(0)\n\n global_var.GROUP.update()\n global_var.BODIES.update()\n global_var.TMBG.update()\n global_var.SPACE.step(0.016666666666666666)\n rects = global_var.CAMERA.update()\n size = vec(global_var.CAMERA.size) * global_var.CAMERA.scl\n self._screen.blit(pygame.transform.scale(global_var.CAMERA.surface, [int(i) for i in size]), global_var.CAMERA.offset + (vec(self.size) - size) // 2)\n self.draw()\n if self.save_name:\n pygame.image.save(self._screen, self.save_name)\n self.save_name = None\n pygame.display.update()\n self._clock.tick(40)\n self._screen.fill(BLACK)\n\n def draw(self):\n for p1, p2, color, width in global_var.LINES:\n pygame.draw.lines(self._screen, color, 0, [p1, p2], width)\n\n global_var.LINES = []","sub_path":"pycfiles/yuanmaxiong1-2.0-py3-none-any/screen.cpython-37.py","file_name":"screen.cpython-37.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"362319227","text":"import networkx as nx\nimport pandas as pd\n\n\nGRAPH = nx.Graph()\n\n\n\"\"\"\nFunção para abrir o arquivo.\n\"\"\"\ndef open_txt():\n return open(\"grafo.txt\", \"r+\")\n\n\n\"\"\"\nFunção para ler o arquivo e adiciona-lo na variavel GRAPH.\n\"\"\"\ndef read_txt_graph(txt_graph):\n for line in txt_graph:\n line = line.split()\n node = line[0][:-1]\n GRAPH.add_node(node)\n\n for val in range(1, len(line)):\n GRAPH.add_edge(node, line[val])\n\n\n\"\"\"\nFunção para verificar se o grafo é euleriano.\n\"\"\"\ndef eulerian():\n if is_eulerian(GRAPH):\n print(\"É um grafo euleriano!\\n\")\n else:\n print(\"Não é um grafo euleriano!\\n\")\n\n\ndef is_eulerian(G):\n \"\"\"\n Return True if G is an Eulerian graph, False otherwise.\n An Eulerian graph is a graph with an Eulerian circuit.\n \"\"\"\n if G.is_directed():\n # Every node must have equal in degree and out degree\n for n in G.nodes_iter():\n if G.in_degree(n) != G.out_degree(n):\n return False\n # Must be strongly connected\n if not nx.is_strongly_connected(G):\n return False\n else:\n # An undirected Eulerian graph has no vertices of odd degrees\n for v,d in G.degree_iter():\n if d % 2 != 0:\n return False\n # Must be connected\n if not nx.is_connected(G):\n return False\n return True\n\n\n\"\"\"\nFunção para verificar se o grafo tem um ciclo euleriano.\n\"\"\"\ndef has_eulerian_cycle():\n try:\n eulerian_cycle = list(nx.find_cycle(GRAPH))\n print(\"Possui ao menos um ciclo euleriano: {}\".format(eulerian_cycle))\n except:\n print(\"Não possui um ciclo euleriano!\")\n\n\n\"\"\"\nInício do código.\n\"\"\"\ntxt_graph = open_txt()\nread_txt_graph(txt_graph)\neulerian()\nhas_eulerian_cycle()\n","sub_path":"Matérias/TEG/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"636669092","text":"###########################################\n# Author: Alfonso Medela #\n# Contact alfonso@legit.health #\n# Copyright: Legit.Health #\n# Website: https://legit.health/ #\n###########################################\n\nfrom fastai.vision import *\nimport glob\nimport numpy as np\nimport configparser\nfrom tqdm import tqdm\nimport cv2\nfrom sklearn.metrics import accuracy_score, roc_auc_score, f1_score, jaccard_score\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module=\"torch.nn.functional\")\n\ndef validate(image_paths, path_label, model_dir, t=0.5):\n\n '''\n Function to obtain the main metric on lesion segmentation\n :param image_paths: list containing image paths\n :param path_label: path to labels\n :param model_dir: main directory of the models where the folds are saved\n :param t: threshold\n :return: AUC, [ACC, IOU, F1]\n '''\n\n # Load learner\n learn = load_learner(model_dir)\n\n metrics = []\n auc_metric = []\n for i_img in tqdm(range(len(image_paths))):\n\n image_path = image_paths[i_img]\n path_to_annotation = path_label + image_path.split('/')[-1].split('.')[0] + '.png'\n\n label = cv2.imread(path_to_annotation, -1)\n y = label.reshape(label.shape[0] * label.shape[1])\n\n img = PIL.Image.open(image_path)\n original_image = np.array(img)\n a = original_image.shape[0]\n b = original_image.shape[1]\n if a > b:\n original_image = cv2.resize(original_image, (b, b))\n else:\n original_image = cv2.resize(original_image, (a, a))\n\n img = PIL.Image.fromarray(original_image).convert('RGB')\n img = pil2tensor(img, np.float32)\n img = img.div_(255)\n img = Image(img)\n\n learn.model.eval()\n _, _, mask = learn.predict(img)\n\n mask = mask.detach().numpy()\n mask = mask[1, :, :, np.newaxis]\n\n mask_show = cv2.resize(mask, (b, a))\n mask_flatten_int = mask_show.reshape((a * b, mask.shape[-1]))\n\n mask_flatten = mask_flatten_int.copy()\n mask_flatten_int = mask_flatten_int[:, 0]\n mask_flatten = mask_flatten[:, 0]\n\n mask_flatten[mask_flatten > t] = 1\n mask_flatten[mask_flatten <= t] = 0\n\n # IoU\n jac = jaccard_score(y, mask_flatten)\n\n # F1 score\n f1 = f1_score(y, mask_flatten)\n\n # Pixel Accuracy\n acc = accuracy_score(y, mask_flatten)\n\n metrics.append([acc, jac, f1])\n\n try:\n # AUC only for images with lesion\n auc = roc_auc_score(y, mask_flatten_int)\n auc_metric.append(auc)\n except:\n continue\n\n\n auc_metric = np.asarray(auc_metric)\n metrics = np.asarray(metrics)\n\n # destroy learner\n learn.destroy()\n return np.mean(auc_metric), np.mean(metrics, axis=0)\n\n\nif __name__ == '__main__':\n\n root = '../../../'\n SERVABLE_CFG_FILE = root + 'config.ini'\n config = configparser.ConfigParser()\n config.read(SERVABLE_CFG_FILE)\n\n # Input params defined in config file\n k_folds = int(config['PARAMS']['K_FOLDS'])\n\n # Get paths from config\n root_path = config['DATA']['DATASET_ROOT_PATH']\n results_path = config['DATA']['RESULTS_ROOT_PATH']\n\n # Set main path and output path\n path = root_path + 'LegitHealth-AD-Test/'\n output_path = results_path + 'lesion-segmentation/'\n\n # Set the path to save the models\n model_dir_path = 'MODEL_PATH'\n\n # Load image paths\n image_paths = glob.glob(path + '*')\n image_paths = np.asarray(image_paths)\n\n # Paths to ground truth labels\n path_labels = path + 'labels/lesion_segmentation/ground_truth_masks/'\n\n total_auc = []\n total_metrics = []\n for n_fold in range(k_folds):\n print('Fold ' + str(n_fold))\n\n # Fold directory\n model_dir = model_dir_path + 'fold-' + str(n_fold) + '/'\n\n auc_split, metrics_split = validate(image_paths, path_labels, model_dir)\n\n total_auc.append(auc_split)\n total_metrics.append(metrics_split)\n\n n_fold += 1\n\n total_auc = np.asarray(total_auc)\n total_metrics = np.asarray(total_metrics)\n\n AUC, AUC_std = np.mean(total_auc)*100., np.std(total_auc)*100.\n metrics, metrics_std = np.mean(total_metrics, axis=0)*100., np.std(total_metrics, axis=0)*100.\n\n df = [AUC, AUC_std,\n metrics[0], metrics_std[0],\n metrics[1], metrics_std[1],\n metrics[2], metrics_std[2]\n ]\n\n df = np.asarray(df)[np.newaxis, :]\n\n # Convert the array to dataframe and set column names\n df = pd.DataFrame(df)\n df.columns = ['AUC',\n 'AUC std',\n 'Px Acc',\n 'Px acc std',\n 'IoU',\n 'IoU std',\n 'F1',\n 'F1 std'\n ]\n\n # Convert values to float and round to 2 decimals\n df = df.astype(float)\n df = df.round(2)\n\n # Save results as csv\n df.to_csv(output_path + 'LegitHealth-AD-Test segmentation metrics.csv', index=False)\n\n","sub_path":"code/A_lesion_segmentation/validation/exp1/validate_on_v2.py","file_name":"validate_on_v2.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"615619052","text":"from __future__ import absolute_import, print_function\nimport re\nfrom collections import OrderedDict\n\nfrom .base import Code, CodeGenerator\nfrom .jsonschema import Schema, SchemaGenerator, build_default\nimport six\n\nSUPPORT_METHODS = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head']\n\n\nclass Router(Code):\n\n template = 'falcon/routers.tpl'\n dest_template = '%(package)s/%(module)s/routes.py'\n override = True\n\n\nclass View(Code):\n\n template = 'falcon/view.tpl'\n dest_template = '%(package)s/%(module)s/api/%(view)s.py'\n override = False\n\n\nclass Specification(Code):\n\n template = 'falcon/specification.tpl'\n dest_template = '%(package)s/static/%(module)s/swagger.json'\n override = True\n\n\nclass Validator(Code):\n\n template = 'falcon/validators.tpl'\n dest_template = '%(package)s/%(module)s/validators.py'\n override = True\n\n\nclass Api(Code):\n\n template = 'falcon/api.tpl'\n dest_template = '%(package)s/%(module)s/api/__init__.py'\n\n\nclass Blueprint(Code):\n\n template = 'falcon/blueprint.tpl'\n dest_template = '%(package)s/%(module)s/__init__.py'\n\n\nclass App(Code):\n\n template = 'falcon/app.tpl'\n dest_template = '%(package)s/__init__.py'\n\n\nclass Requirements(Code):\n\n template = 'falcon/requirements.tpl'\n dest_template = 'requirements.txt'\n\n\nclass UIIndex(Code):\n\n template = 'ui/index.html'\n dest_template = '%(package)s/static/swagger-ui/index.html'\n\n\ndef _swagger_to_falcon_url(url, swagger_path_node):\n types = {\n 'integer': 'int',\n 'long': 'int',\n 'float': 'float',\n 'double': 'float'\n }\n node = swagger_path_node\n params = re.findall(r'\\{([^\\}]+?)\\}', url)\n url = re.sub(r'{(.*?)}', '{\\\\1}', url)\n\n def _type(parameters):\n for p in parameters:\n if p.get('in') != 'path':\n continue\n t = p.get('type', 'string')\n if t in types:\n yield '{%s}' % p['name'], '{%s}' % p['name']\n\n for old, new in _type(node.get('parameters', [])):\n url = url.replace(old, new)\n\n for k in SUPPORT_METHODS:\n if k in node:\n for old, new in _type(node[k].get('parameters', [])):\n url = url.replace(old, new)\n\n return url, params\n\n\nif six.PY3:\n def _remove_characters(text, deletechars):\n return text.translate({ord(x): None for x in deletechars})\nelse:\n def _remove_characters(text, deletechars):\n return text.translate(None, deletechars)\n\n\ndef _path_to_endpoint(swagger_path):\n return _remove_characters(\n swagger_path.strip('/').replace('/', '_').replace('-', '_'),\n '{}')\n\n\ndef _path_to_resource_name(swagger_path):\n return _remove_characters(swagger_path.title(), '{}/_-')\n\n\ndef _location(swagger_location):\n location_map = {\n 'body': 'json',\n 'formData': 'form',\n 'header': 'headers',\n 'query': 'params'\n }\n return location_map.get(swagger_location)\n\n\nclass FalconGenerator(CodeGenerator):\n\n dependencies = [SchemaGenerator]\n\n def __init__(self, swagger):\n super(FalconGenerator, self).__init__(swagger)\n self.with_spec = False\n self.with_ui = False\n\n def _dependence_callback(self, code):\n if not isinstance(code, Schema):\n return code\n schemas = code\n # schemas default key likes `('/some/path/{param}', 'method')`\n # use falcon endpoint to replace default validator's key,\n # example: `('some_path_param', 'method')`\n validators = OrderedDict()\n for k, v in six.iteritems(schemas.data['validators']):\n locations = {_location(loc): val for loc, val in six.iteritems(v)}\n validators[(_path_to_endpoint(k[0]), k[1])] = locations\n\n # filters\n filters = OrderedDict()\n for k, v in six.iteritems(schemas.data['filters']):\n filters[(_path_to_endpoint(k[0]), k[1])] = v\n\n # scopes\n scopes = OrderedDict()\n for k, v in six.iteritems(schemas.data['scopes']):\n scopes[(_path_to_endpoint(k[0]), k[1])] = v\n\n schemas.data['validators'] = validators\n schemas.data['filters'] = filters\n schemas.data['scopes'] = scopes\n self.schemas = schemas\n self.validators = validators\n self.filters = filters\n return schemas\n\n def _process_data(self):\n\n views = [] # [{'endpoint':, 'name':, url: '', params: [], methods: {'get': {'requests': [], 'response'}}}, ..]\n\n for paths, data in self.swagger.search(['paths', '*']):\n swagger_path = paths[-1]\n url, params = _swagger_to_falcon_url(swagger_path, data)\n endpoint = _path_to_endpoint(swagger_path)\n name = _path_to_resource_name(swagger_path)\n\n methods = OrderedDict()\n for method in SUPPORT_METHODS:\n if method not in data:\n continue\n methods[method] = {}\n validator = self.validators.get((endpoint, method.upper()))\n if validator:\n methods[method]['requests'] = list(validator.keys())\n\n for status, res_data in six.iteritems(data[method].get('responses', {})):\n if isinstance(status, int) or status.isdigit():\n example = res_data.get('examples', {}).get('application/json')\n\n if not example:\n example = build_default(res_data.get('schema'))\n response = example, 'falcon.HTTP_%s' % int(status), build_default(res_data.get('headers')) or {}\n methods[method]['response'] = response\n break\n\n views.append(dict(\n url=url,\n params=params,\n methods=methods,\n endpoint=endpoint,\n name=name\n ))\n\n return views\n\n def _get_oauth_scopes(self):\n for path, scopes in self.swagger.search(('securityDefinitions', '*', 'scopes')):\n return scopes\n return None\n\n def _process(self):\n views = self._process_data()\n yield Router(dict(views=views))\n for view in views:\n yield View(view, dist_env=dict(view=view['endpoint']))\n if self.with_spec:\n try:\n import simplejson as json\n except ImportError:\n import json\n swagger = {}\n swagger.update(self.swagger.origin_data)\n swagger.pop('host', None)\n swagger.pop('schemes', None)\n yield Specification(dict(swagger=json.dumps(swagger, indent=2)))\n\n yield Validator()\n\n yield Api()\n\n yield Blueprint(dict(scopes_supported=self.swagger.scopes_supported,\n blueprint=self.swagger.module_name))\n yield App(dict(blueprint=self.swagger.module_name,\n base_path=self.swagger.base_path))\n\n yield Requirements()\n\n if self.with_ui:\n yield UIIndex(dict(spec_path='/static/%s/swagger.json' % self.swagger.module_name))\n","sub_path":"swagger_py_codegen/falcon.py","file_name":"falcon.py","file_ext":"py","file_size_in_byte":7123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"563521852","text":"import gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nclass MultiGoalEnv(gym.Env):\n \n def __init__(self, nr_goal = 4, goal_reward=100.):\n radius = 2.\n self.min_x = -radius*1.1\n self.max_x = radius*1.1\n self.min_y = -radius*1.1\n self.max_y = radius*1.1\n\n self.state_shape = (1,2)\n self.low = np.array([self.min_x, self.min_y])\n self.high = np.array([self.max_x, self.max_y])\n\n self.dynamics = PointDynamics(dim=2, sigma=0.03)\n self.init_mu = np.array((0, 0), dtype=np.float32)\n self.init_sigma = 0.\n self.max_time_step = 20\n \n self.nr_goal = nr_goal\n if nr_goal == 1:\n goal_positions = np.array(\n [\n [radius, 0]\n ],\n dtype=np.float32\n )\n avo_positions = np.array(\n [\n [-radius*2/3,0]\n ],\n dtype=np.float32\n )\n elif nr_goal == 2:\n goal_positions = np.array(\n [\n [radius, 0],\n [-radius, 0]\n ],\n dtype=np.float32\n )\n avo_positions = np.array(\n [\n [0, radius*2/3],\n [0, -radius*2/3]\n ],\n dtype=np.float32\n )\n elif nr_goal == 3:\n goal_positions = np.array(\n [\n [radius, 0],\n [-radius/2, radius*np.sqrt(3)/2],\n [-radius/2, -radius*np.sqrt(3)/2]\n ],\n dtype=np.float32\n )\n avo_positions = np.array(\n [\n [radius*np.sqrt(3)/3,radius/3],\n [radius*np.sqrt(3)/3,-radius/3],\n [0, -radius*2/3]\n ],\n dtype=np.float32\n )\n elif nr_goal == 4:\n goal_positions = np.array(\n [\n [radius, 0],\n [0, radius],\n [-radius, 0],\n [0, -radius]\n ],\n dtype=np.float32\n )\n avo_positions = np.array(\n [\n [radius*2/3/np.sqrt(2), radius*2/3/np.sqrt(2)],\n [-radius*2/3/np.sqrt(2), radius*2/3/np.sqrt(2)],\n [-radius*2/3/np.sqrt(2), -radius*2/3/np.sqrt(2)],\n [radius*2/3/np.sqrt(2), -radius*2/3/np.sqrt(2)]\n ],\n dtype=np.float32\n )\n \n self.avo_positions = avo_positions\n self.goal_positions = goal_positions\n self.cost_scale = .2\n \n self.goal_threshold = .25\n self.goal_reward = goal_reward*0.\n self.action_cost_coeff = 0.\n self.vel_bound = radius/self.max_time_step\n \n self.action_space = spaces.Box(-self.vel_bound,self.vel_bound,shape=(2,))\n self.observation_space = spaces.Box(self.low, self.high)\n\n self._seed()\n self.observation = self.reset()\n \n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _step(self, action):\n action = action.ravel()\n\n a_lb = self.action_space.low\n a_ub = self.action_space.high\n action = np.clip(action, a_lb, a_ub).ravel()\n\n next_obs = self.dynamics.forward(self.observation, action)\n o_lb = self.observation_space.low\n o_ub = self.observation_space.high\n next_obs = np.clip(next_obs, o_lb, o_ub)\n\n reward = self.compute_reward(self.observation, action)\n cur_position = self.observation\n dist_to_goal_list = [\n np.linalg.norm(cur_position - goal_position)\n for goal_position in self.goal_positions\n ]\n dist_to_goal = np.amin(dist_to_goal_list)\n \n self.time_step += 1\n gaol_id = -1\n# done = dist_to_goal < self.goal_threshold\n# if done:\n# gaol_id = np.argmin(dist_to_goal_list)\n# reward += self.goal_reward\n# else:\n done = self.time_step > self.max_time_step\n if dist_to_goal < 0.3:\n gaol_id = np.argmin(dist_to_goal_list)\n \n self.observation = np.copy(next_obs)\n return next_obs, reward, done, {'pos':next_obs,'goal_id': gaol_id}\n\n def _reset(self):\n self.time_step = 0\n unclipped_observation = self.init_mu + self.init_sigma * \\\n np.random.normal(size=self.dynamics.s_dim)\n o_lb = self.observation_space.low\n o_ub = self.observation_space.high\n self.observation = np.clip(unclipped_observation, o_lb, o_ub)\n return self.observation\n\n def render(self):\n\n delta = 0.01\n x_min, y_min = tuple(1.1 * np.array(self.low))\n x_max, y_max = tuple(1.1 * np.array(self.high))\n \n X, Y = np.meshgrid(\n np.arange(x_min, x_max, delta),\n np.arange(y_min, y_max, delta)\n )\n reward = 200*np.exp(-0.5*np.amin([\n (X - goal_x) ** 2 + (Y - goal_y) ** 2\n for goal_x, goal_y in self.goal_positions\n ], axis=0)/2/self.cost_scale) - 100*np.exp(-0.5*np.amin([\n (X - avo_x) ** 2 + (Y - avo_y) ** 2\n for avo_x, avo_y in self.avo_positions\n ], axis=0)/self.cost_scale)\n \n contours = plt.contour(X, Y, reward, 40)\n plt.clabel(contours, inline=1, fontsize=10, fmt='%.0f')\n goal = plt.plot(self.goal_positions[:, 0],\n self.goal_positions[:, 1], 'ko')\n avo = plt.plot(self.avo_positions[:, 0],\n self.avo_positions[:, 1], 'kx')\n plt.xlim([x_min,x_max])\n plt.ylim([y_min,y_max])\n plt.grid(True)\n \n def plot_path(self,env_info_list, style='b'):\n self.render()\n path = np.concatenate([i['pos'][None] for i in env_info_list], axis=0)\n xx = path[:, 0]\n yy = path[:, 1]\n line, = plt.plot(xx, yy, style)\n\n def plot_paths(self,paths):\n self.render()\n line_lst = []\n for path in paths:\n positions = path[\"env_infos\"][\"pos\"]\n xx = positions[:, 0]\n yy = positions[:, 1]\n line_lst += plt.plot(xx, yy, 'b')\n\n def compute_reward(self, observation, action):\n # penalize the L2 norm of acceleration\n # noinspection PyTypeChecker\n action_cost = np.sum(action ** 2) * self.action_cost_coeff\n\n # penalize squared dist to goal\n cur_position = observation\n # noinspection PyTypeChecker\n goal_reward = 200*np.exp(-0.5*np.amin([\n np.sum((cur_position - goal_position) ** 2)\n for goal_position in self.goal_positions\n ])/2/self.cost_scale) - 100*np.exp(-0.5*np.amin([\n np.sum((cur_position - avo_position) ** 2)\n for avo_position in self.avo_positions\n ])/self.cost_scale)\n\n # penalize staying with the log barriers\n reward = np.sum([-action_cost, goal_reward])\n return reward\n\n def plot_position_cost(self):\n delta = 0.01\n x_min, y_min = tuple(1.1 * np.array(self.low))\n x_max, y_max = tuple(1.1 * np.array(self.high))\n X, Y = np.meshgrid(\n np.arange(x_min, x_max, delta),\n np.arange(y_min, y_max, delta)\n )\n goal_costs = 10*np.min([\n (X - goal_x) ** 2 + (Y - goal_y) ** 2\n for goal_x, goal_y in self.goal_positions\n ],axis=0) - self.reward_bias\n costs = goal_costs\n return [costs, self.goal_positions]\n\nclass PointDynamics(object):\n \"\"\"\n State: position.\n Action: velocity.\n \"\"\"\n def __init__(self, dim, sigma):\n self.dim = dim\n self.sigma = sigma\n self.s_dim = dim\n self.a_dim = dim\n\n def forward(self, state, action):\n mu_next = state + action\n state_next = mu_next + self.sigma * \\\n np.random.normal(size=self.s_dim)\n return state_next","sub_path":"multigoal_experiments/multigoal.py","file_name":"multigoal.py","file_ext":"py","file_size_in_byte":8206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"105983794","text":"# fetch tweet from file\n# send data to kafka\n# configurable kafka broker and kafka topic\n\nfrom kafka import KafkaProducer\n\nimport csv\nimport json\n# shutdown hook\nimport atexit\nimport argparse\nimport logging\nimport schedule\nimport time\n\nimport codecs\nimport sys\nimport io\n\nfrom ttp import ttp\nimport geograpy\n\nlogging.basicConfig()\nlogger = logging.getLogger('data-producer')\n\n# debug, info, warn, error\nlogger.setLevel(logging.DEBUG)\n\ntopic_name = ''\nkafka_broker = ''\nfilename = \"twitter-data.csv\"\nreload(sys)\n# new-line character seen in unquoted field, so open file in universal-newline mode\ndata_file = io.open(filename, \"rU\", encoding='ISO-8859-1')\nsys.setdefaultencoding('utf-8')\nreader = csv.reader(data_file)\nentity_parser = ttp.Parser()\n\ndef normalize_location(loc):\n if loc is None or not loc:\n return ''\n location = geograpy.get_place_context(text=loc)\n\n country = ''\n if location.countries is not None and len(location.countries) is not 0:\n country = location.countries[0]\n return country\n\ndef extract_hashtags(tweet):\n parsed_entities = entity_parser.parse(tweet)\n hashtags = parsed_entities.tags\n return hashtags\n\ndef fetch_tweet(producer):\n try:\n fields = next(reader)\n # logger.debug('read line: %s\\n' % fields)\n tweet_location = fields[24]\n normalized_location = normalize_location(tweet_location)\n\n tweet_text = fields[19]\n hashtags = []\n try:\n hashtags = extract_hashtags(tweet_text)\n except UnicodeDecodeError:\n logger.info(\"tweet text: %s\" % tweet_text)\n except Exception as e:\n logger.warn(\"Exception: %s\" % e)\n\n data = {\n '_unit_id': fields[0],\n 'gender': fields[5],\n 'text': fields[19],\n 'hashtags': hashtags,\n 'tweet_count': fields[21],\n 'tweet_location': tweet_location,\n 'normalized_location': normalized_location,\n 'user_timezone': fields[25]\n }\n data = json.dumps(data)\n producer.send(topic=topic_name, value=data)\n logger.debug('sent data to kafka %s\\n' % data)\n except EOFError as e:\n logger.warn('Reach EOF')\n except Exception as e:\n logger.warn('Failed to fetch tweet %s\\n' % e)\n\ndef shutdown_hook(producer):\n logger.info('closing data file')\n data_file.close()\n logger.info('closing kafka producer')\n producer.flush(10)\n producer.close(10)\n logger.info('kafka producer closed')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('topic_name', help='the kafka topic to send to')\n parser.add_argument('kafka_broker', help='the kafka broker ip')\n\n # parse the argument\n args = parser.parse_args()\n topic_name = args.topic_name\n kafka_broker = args.kafka_broker\n\n producer = KafkaProducer(\n bootstrap_servers=kafka_broker\n )\n\n # skip the first line, headers\n next(reader)\n schedule.every(2).seconds.do(fetch_tweet, producer)\n\n atexit.register(shutdown_hook, producer)\n\n while True:\n schedule.run_pending()\n time.sleep(1)\n","sub_path":"data-producer.py","file_name":"data-producer.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"5081404","text":"from Crypto.Cipher import AES\n\nkey = b'xxxx cccc vvvv b'\niv = b'gggg hhhh jjjj k'\n\ndef get_cipher():\n global key, iv\n return AES.new(key, AES.MODE_CFB, iv)\n\nif __name__ == '__main__':\n c1 = get_cipher()\n c2 = get_cipher()\n c3 = get_cipher()\n\n a = c1.encrypt('abc')\n b = c1.encrypt('abc')\n c = c2.decrypt(a)\n d = c2.decrypt(a)\n e = c3.decrypt(a)\n f = c3.decrypt(b)\n\n print(a) # b'\\xb2\\x9f\\xa4'\n print(b) # b'\\xa7;:'\n print(c) # b'abc'\n print(d) # b't85'\n print(e) # b'abc'\n print(f) # b'abc'\n","sub_path":"shell/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"39420135","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Imports\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.contrib import learn\nfrom tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n# Our application logic will be added here\n\ndef cnn_model_fn(features, labels, mode):\n \"\"\"Build a CNN model trained on MNIST data.\"\"\"\n\n # Input Layer, 28 x 28 pixel intensities\n input_layer = tf.reshape(features, [-1, 28, 28, 1])\n\n # Convolutional Layer 1: Applies 32 5x5 filters (extracting 5x5-pixel subregions), with ReLU activation function\n conv1 = tf.layers.conv2d(\n input_layer, filters=32, kernel_size=[5, 5], padding='same', activation=tf.nn.relu\n )\n\n # Pooling Layer 1: Performs max pooling with a 2x2 filter and stride of 2 (which specifies that pooled regions do not overlap)\n pool1 = tf.layers.max_pooling2d(conv1, pool_size=[2, 2], strides=[2, 2])\n\n # Convolutional Layer 2: Applies 64 5x5 filters, with ReLU activation function\n conv2 = tf.layers.conv2d(\n pool1, filters=64, kernel_size=[5, 5], padding='same', activation=tf.nn.relu\n )\n\n # Pooling Layer 2: Again, performs max pooling with a 2x2 filter and stride of 2\n pool2 = tf.layers.max_pooling2d(conv2, pool_size=[2, 2], strides=[2, 2])\n\n # Dense Layer 1: 1,024 neurons, with dropout regularization rate of 0.4 (probability of 0.4 that any given element\n # will be dropped during training)\n pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])\n dense = tf.layers.dense(pool2_flat, units=1024, activation=tf.nn.relu)\n dropout = tf.layers.dropout(dense, rate=0.4, training=(mode == learn.ModeKeys.TRAIN))\n\n # Dense Layer 2 (Softmax Layer): 10 neurons, one for each digit target class (0-9).\n output = tf.layers.dense(dropout, units=10)\n\n loss, train_op = None, None\n\n # Calculating loss for train and eval modes.\n if mode != learn.ModeKeys.INFER:\n onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)\n loss = tf.losses.softmax_cross_entropy(onehot_labels, output)\n\n # Configure the training Op, for train mode.\n if mode == learn.ModeKeys.TRAIN:\n train_op = tf.contrib.layers.optimize_loss(\n loss, global_step=tf.contrib.framework.get_global_step(), learning_rate=0.001, optimizer='SGD'\n )\n\n predictions = {\n 'classes': tf.argmax(input=output, axis=1),\n 'probabilities': tf.nn.softmax(output, name='softmax_tensor')\n }\n\n # Return the model.\n return model_fn_lib.ModelFnOps(mode=mode, predictions=predictions, loss=loss, train_op=train_op)\n\n\ndef main(unused_argv):\n\n # Load training and eval data\n mnist = learn.datasets.load_dataset(\"mnist\")\n train_data = mnist.train.images # Returns np.array\n train_labels = np.asarray(mnist.train.labels, dtype=np.int32)\n eval_data = mnist.test.images # Returns np.array\n eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)\n\n mnist_classifier = learn.Estimator(model_fn=cnn_model_fn, model_dir=\"/tmp/mnist_convnet_model\")\n\n # Set up logging for predictions\n tensors_to_log = {\"probabilities\": \"softmax_tensor\"}\n logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=50)\n\n # Train the model.\n mnist_classifier.fit(x=train_data, y=train_labels, batch_size=100, steps=20000, monitors=[logging_hook])\n\n # Configure the accuracy metric for evaluation\n metrics = {\n \"accuracy\": learn.MetricSpec(metric_fn=tf.metrics.accuracy, prediction_key=\"classes\")\n }\n\n # Evaluate the model and print results\n eval_results = mnist_classifier.evaluate(x=eval_data, y=eval_labels, metrics=metrics)\n print(eval_results)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n\n","sub_path":"MNIST/mnist_CNNs_2.py","file_name":"mnist_CNNs_2.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"443596808","text":"# helper script - preprocesses data\n# and creates a file \"dataset_fast.cache\"\n# for fast data loading\n\nimport pickle\nimport numpy as np\nimport os\nimport gzip\nfrom utils import *\n\ndef load(file_pattern, frm, to, frac = 0.1):\n \"\"\"Customized load method for my data - the data is split up into multiple numbered recordings, this\n method joins them together, splits them into train and validation and returns them\"\"\"\n states = []\n actions = []\n\n print(\"loading...\")\n\n for i in range(frm,to+1):\n # insert number into file name template\n data_file = file_pattern.replace(\"$i$\", str(i))\n print(\" loading data from\", data_file)\n\n f = gzip.open(data_file,'r')\n data = pickle.load(f)\n states.append(np.stack( data['state'] ))\n actions.append(np.stack( data['action']))\n\n # join np arrays from files together\n X = np.vstack(states)\n y = np.vstack(actions)\n\n # slipt into train and validation\n n_samples = len(X)\n X_train, y_train = X[:int((1-frac) * n_samples)], y[:int((1-frac) * n_samples)]\n X_valid, y_valid = X[int((1-frac) * n_samples):], y[int((1-frac) * n_samples):]\n\n # some state\n print(X_train.shape[0], \"training samples\", X_valid.shape[0], \"validation samples\", )\n\n return X_train, y_train, X_valid, y_valid\n\n\ndef preprocessing(X, y):\n\n # History:\n # At first you should only use the current image as input to your network to learn the next action. Then the input states\n # have shape (96, 96,1). Later, add a history of the last N images to your state so that a state has shape (96, 96, N).\n\n print(\"preprocessing...\")\n print(\" transforming to greyscale\")\n X = rgb2gray(X)\n\n print(\" encoding targets\")\n y = encode_targets(y)\n\n print(\" preprocessing done\")\n return X, y\n\n\n# cache preprocessed data for faster development\ncachefile = \"dataset_fast.cache\"\n\nif not os.path.exists(cachefile):\n # read data from cached file\n\n # read datasets 1-9\n\n # using all 9 datasets here\n X_train, y_train, X_valid, y_valid = load(\"./data_raw/datanew$i$.pkl.gzip\", 1, 9)\n\n # preprocess data\n X_train, y_train = preprocessing(X_train, y_train)\n X_valid, y_valid = preprocessing(X_valid, y_valid)\n\n # output some info\n print(X_train.shape)\n print(y_train.shape)\n print(X_valid.shape)\n print(y_valid.shape)\n\n pickle.dump([X_train, y_train, X_valid, y_valid], gzip.open(cachefile, 'wb'))\nelse:\n print(\"Data file exists - delete to reprocess\")","sub_path":"exercise3/preprocess_data.py","file_name":"preprocess_data.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"527112987","text":"mainPerson = []\nmainSubject = [\"Foundation English\",\"General Business\",\"Introduction to Computer Systems\",\"Computer Programming\"]\nmainScore = {}\npersonAndScore = {}\n\nwhile True:\n name = input(\"Your name:\")\n if name != \"\":\n mainPerson.append(name)\n for subject in mainSubject:\n score = input(subject+\":\")\n mainScore.update({subject: score})\n print(mainScore)\n personAndScore.update({name: mainScore})\n print(personAndScore)\n else:\n break\n\nprint(personAndScore)\n\nfor name in personAndScore:\n print(name)\n for score in personAndScore[name]:\n print(score, ':', personAndScore[name][score])\n\n\n","sub_path":"Exercise4_Peerapol_J.py","file_name":"Exercise4_Peerapol_J.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"589165032","text":"#!/usr/bin/env python3\n\nimport datetime\nimport subprocess\nimport sys\nimport os.path\nimport glob\n\n\nSNAPCRAFT = 'snapcraft'\nSNAPCRAFT = '/project/snap/snapcraft/bin/snapcraft'\n\n\ndef main():\n if '--loop' in sys.argv:\n looping = True\n sys.argv.remove('--loop')\n else:\n looping = False\n while True:\n if len(sys.argv) > 1:\n comment = sys.argv[1]\n else:\n comment = \"No Comment\"\n\n now = datetime.datetime.now()\n status = \"Version released at %s with comment: %s\" % (now, comment)\n here = os.path.dirname(__file__)\n target_file = os.path.join(here, 'kelvin-says.py')\n\n # Clean the old data:\n subprocess.check_call([SNAPCRAFT, 'clean'])\n\n # Edit the script file:\n subprocess.check_call([\n 'sed',\n '-i',\n 's/^MESSAGE.*/MESSAGE = %r/' % (status),\n target_file])\n\n # do a new build:\n subprocess.check_call([SNAPCRAFT])\n\n # find the snap file:\n snaps = glob.glob(os.path.join(here, '*.snap'))\n\n assert len(snaps) == 1\n\n # release the snap:\n subprocess.check_call([SNAPCRAFT, 'push', snaps[0], '--release', 'stable'])\n if not looping:\n break\n\nif __name__ == '__main__':\n main()\n","sub_path":"do_new_release.py","file_name":"do_new_release.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"111608482","text":"import torch\nfrom torch._C import dtype\nimport torch.nn as nn\nimport h5py\n\nfrom torch.nn import NLLLoss\nfrom torch.optim import Adam\n\nimport matplotlib.pyplot as plt\n\n# MLP used to measure noise\n\nclass Model(nn.Module):\n\n # Structure of network\n def __init__(self):\n super(Model, self).__init__()\n self.network = nn.Sequential(\n nn.Flatten(),\n nn.Linear(in_features=1024, out_features=128),\n nn.Tanh(),\n nn.Linear(in_features=128, out_features=10),\n nn.Softmax(dim=1)\n )\n\n # Foward pass\n def forward(self, x):\n return self.network(x)\n\n # To train model\n def train_model(self, inputs, target, epochs, silent = False):\n # define the optimization\n criterion = NLLLoss()\n optimizer = Adam(self.parameters())\n\n for epoch in range(epochs):\n optimizer.zero_grad()\n output = model(inputs)\n loss = criterion(output, target)\n _, labels = output.max(dim = 1)\n accuracy = (target == labels).sum() / labels.size()[0]*100\n\n if not silent:\n print(f\"Epoch {epoch}:\")\n print(f\"Accuracy: {accuracy}\")\n loss.backward()\n optimizer.step()\n \n\n\n\n\n\n\nif __name__ == '__main__':\n\n # Loading scaled images into tensors...\n f = h5py.File('../mnist/mnist-scaled.hdf5', 'r')\n\n test_images = torch.tensor(f.get('test_images'), dtype = torch.float).reshape(-1, 1, 32, 32)\n test_labels = torch.tensor(f.get('test_labels'), dtype = torch.int64)\n\n\n train_images = torch.tensor(f.get('train_images'), dtype = torch.float).reshape(-1, 1, 32, 32)\n train_labels = torch.tensor(f.get('train_labels'), dtype = torch.int64)\n\n\n\n\n model = Model()\n\n train_metrics = []\n test_metrics = []\n\n targets = train_labels\n\n criterion = NLLLoss()\n optimizer = Adam(model.parameters())\n\n for epoch in range(100):\n optimizer.zero_grad()\n train_output = model(train_images)\n loss = criterion(train_output, targets)\n _, train_labels_output = train_output.max(dim = 1)\n train_accuracy = (train_labels_output == train_labels).sum() / train_labels.size()[0]*100\n\n test_output = model(test_images)\n _, test_labels_output = test_output.max(dim = 1)\n test_accuracy = (test_labels_output == test_labels).sum() / test_labels.size()[0]*100\n\n train_metrics.append(train_accuracy)\n test_metrics.append(test_accuracy)\n\n loss.backward()\n optimizer.step()\n \nplt.plot(test_metrics, range(100), 'r--', train_metrics, range(100), 'b--')\n","sub_path":"scripts/noise_measure.py","file_name":"noise_measure.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"654514619","text":"import time\n\ninput_string = input(\"숫자형 문자열을 입력해주십시오.(다중 입력시 공백으로 구분) : \").split(' ')\ncounting = 0\nfor x in input_string :\n if 10 != len(input_string[counting]) :\n print(\"false\", end = ' ')\n else :\n sorted_x = sorted(x)\n # token = 0\n for y in range(10) :\n if y != int(sorted_x[y]) :\n print(\"false\", end = ' ')\n # token = 0\n break\n else : token = 1\n if token == 1 : print(\"true\", end = ' ')\n counting += 1\n token = 0\n\n# input_string = input(\"숫자형 문자열을 입력해주십시오.(다중 입력시 공백으로 구분) : \").split(' ')\nfor x in range(len(input_string)):\n if sorted(input_string[x]) == ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: print(True, end=' ')\n else: print(False, end=' ')\n\n\n# input_string = input(\"숫자형 문자열을 입력해주십시오.(다중 입력시 공백으로 구분) : \").split(' ')\nprint(list(map(lambda x : sorted(x) == ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], input_string )))\n","sub_path":"Test_Book/coding_test_8/Duplicate_number.py","file_name":"Duplicate_number.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"157448753","text":"from math import sqrt, log10, floor\nfrom numpy import array as arr\n\n\ndef err_prop(x, dx, y, dy, operator):\n if operator == \"+\" or operator == \"-\":\n dz = sqrt(dx ** 2 + dy ** 2)\n elif operator == \"*\":\n dz = abs(x * y) * sqrt((dx / x) ** 2 + (dy / y) ** 2)\n elif operator == \"/\":\n dz = abs(x / y) * sqrt((dx / x) ** 2 + (dy / y) ** 2)\n return dz\n\n\ndef resolution_error(Delta_x):\n return (Delta_x / sqrt(12))\n\n\ndef error_mean(dx, N):\n return dx / N\n\n\ndef get_value_error(value, mode='R'):\n return value, get_error(value, mode)\n\n\ndef get_error(value, mode='R'):\n multimiter_setting = set_multimiter(mode)\n for ranges, xcent_val, xcent_range in multimiter_setting:\n if value < ranges:\n return (value * xcent_val) / 100 + (ranges * xcent_range) / 100\n\n\ndef set_multimiter(mode):\n if mode == 'R' or mode == 'Ohm':\n ranges = [200.0, 2000.0, 20000.0, 200000.0,\n float(10 ** 6), float(10 ** 7)]\n percent_values = [0.010, 0.010, 0.010, 0.010, 0.012, 0.040]\n percent_ranges = [0.004, 0.001, 0.001, 0.001, 0.001, 0.001]\n elif mode == 'V':\n ranges = [0.2, 2.0, 20.0, 200.0, 1000.0]\n percent_values = [0.004, 0.0035, 0.004, 0.005, 0.0055]\n percent_ranges = [0.0025, 0.0006, 0.0005, 0.0006, 0.001]\n elif mode == 'C':\n ranges = arr([0.002, 0.02, 0.2, 2.0, 20.0, 200.0,\n 2000.0, 20000.0, 100000.0]) * 10 ** -6\n percent_values = [2., 1., 1., 1., 1., 1., 1., 1., 3.]\n percent_ranges = [2.5, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.2]\n\n return zip(ranges, percent_values, percent_ranges)\n\n\ndef round_to_err(x, dx):\n to_decimal = - log10(dx) + 1\n return round(x, int(to_decimal))\n\n\ndef round_to_last2(x):\n return round(x, -int(floor(log10(abs(x)))) + 1)\n","sub_path":"Esp5/error_lib.py","file_name":"error_lib.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"139562809","text":"#!/usr/bin/env python3\n\nclass Settings():\n ''' settings class '''\n\n def __init__(self, width, height, bg_color, speed, bullet_speed, \\\n bullet_width, bullet_height, bullet_color, bullet_allowed):\n ''' screen setting '''\n self.screen_width = width\n self.screen_height = height\n self.bg_color = bg_color\n\n ''' ship setting '''\n self.ship_speed_factor = speed\n self.ship_limit = 3\n\n ''' bullet setting '''\n self.bullet_speed_factor = bullet_speed\n self.bullet_width = bullet_width\n self.bullet_height = bullet_height\n self.bullet_color = bullet_color\n self.bullet_allowed = bullet_allowed\n\n ''' alien setting '''\n self.alien_speed_factor = 1\n self.fleet_drop_speed = 1\n self.fleet_direction = 1 # 1: right moving, -1: left moving\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"434735527","text":"\"\"\"Extending CRUDLFAP features.\"\"\"\n\nfrom crudlfap import crudlfap\n\nfrom .models import Post\n\ncrudlfap.Router(\n Post,\n views=[]\n).register()\n\n\nclass PostMixin:\n \"\"\"Create mixin.\"\"\"\n def get_exclude(self):\n if not self.request.user.is_staff:\n return ['owner']\n return super().get_exclude()\n\n\nclass PostCreateView(PostMixin, crudlfap.CreateView):\n \"\"\"Override Post create view.\"\"\"\n def form_valid(self):\n \"\"\"Assigned currnet user.\"\"\"\n self.form.instance.owner = self.request.user\n return super().form_valid()\n\n\ncrudlfap.Router(\n Post,\n material_icon='forum',\n # https://material.io/tools/icons/?style=baseline\n namespace='posts',\n views=[\n crudlfap.ListView.clone(\n filter_fields=['owner'],\n search_fields=['name', 'publish', 'owner'],\n ),\n PostCreateView,\n crudlfap.UpdateView,\n crudlfap.DeleteView,\n ]\n).register()\n","sub_path":"assets/sample/crudlfap.py","file_name":"crudlfap.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"351164185","text":"\"\"\"\nWRITE SENSOR DATA\n\nWORKING VERSION\n\nDESCRIPTION\n\tRead all values from Google Coral data collection for a \n specified sample size then write to a csv file\n\n\n\"\"\"\n\n# Import libraries\nimport time\nimport ADS1015\nimport Proximity_Sensor\nimport Proximity_Sensor_2\nfrom numpy import diff\nimport pandas as pd\n\n# Create objects\nadc = ADS1015.ADS1015()\nproximity_1 = Proximity_Sensor.VCNL4010()\nproximity_2 = Proximity_Sensor_2.VCNL4010()\n\n# Create storage lists\nForceData = []\nProximityData_1 = []\nProximityData_2 = []\nd_ForceData = []\nd_ProximityData_1 = []\nd_ProximityData_2 = []\ntimeTracker = []\n\n# Set scaling ranges\nMin_Force = 1500\nMax_Force = 28000\nMin_Proximity = 2100\nMax_Proximity = 16000\n\n# Initiatize timer\nstartTime = time.time()\n\nprint('Reading Google Coral Data values, press Ctrl-C to quit...')\n\n# Print column headers\nprint('| ADS | VCNL_1 | VCNL_2 | Time | dADS |dVCNL_1 |dVCNL_2 |'.format(*range(2)))\nprint('-' * 60)\n\nfor i in range(0, 700):\n # Read all the ADC channel values in a list\n values = [0]*7\n\n # Read force, proximity, and time values\n Force = adc.read_adc(0, gain = 2/3)\n Proximity_1 = proximity_1.proximity\n Proximity_2 = proximity_2.proximity\n timeTracker.append(time.time() - startTime)\n\n # Scale 0-1 according to projected min and max values\n # Force\n if adc.read_adc(0) > Max_Force:\n Force = 1\n elif adc.read_adc(0) < Min_Force:\n Force = 0\n else:\n Force = (adc.read_adc(0) - Min_Force) / (Max_Force - Min_Force)\n\n # Proximity_1\n if proximity_1.proximity > Max_Proximity:\n Proximity_1 = 1\n elif proximity_1.proximity < Min_Proximity:\n Proximity_1 = 0\n else:\n Proximity_1 = (proximity_1.proximity - Min_Proximity) / (Max_Proximity - Min_Proximity)\n\n # Proximity_2\n if proximity_2.proximity > Max_Proximity:\n Proximity_2 = 1\n elif proximity_2.proximity < Min_Proximity:\n Proximity_2 = 0\n else:\n Proximity_2 = (proximity_2.proximity - Min_Proximity) / (Max_Proximity - Min_Proximity)\n\n # Save data to respective lists\n ForceData.append(Force)\n ProximityData_1.append(Proximity_1)\n ProximityData_2.append(Proximity_2)\n\n # Gather derivative data\n # Force\n if len(ForceData) > 1:\n d_Force = (ForceData[-1] - ForceData[-2]) / (timeTracker[-1] - timeTracker[-2])\n else:\n d_Force = 0\n\n # Proximity 1\n if len(ProximityData_1) > 1:\n d_Proximity_1 = (ProximityData_1[-1] - ProximityData_1[-2]) / (timeTracker[-1] - timeTracker[-2])\n else:\n d_Proximity_1 = 0\n\n # Proximity 2\n if len(ProximityData_2) > 1:\n d_Proximity_2 = (ProximityData_2[-1] - ProximityData_2[-2]) / (timeTracker[-1] - timeTracker[-2])\n else:\n d_Proximity_2 = 0\n\n # Save derivative data\n d_ForceData.append(Force)\n d_ProximityData_1.append(Proximity_1)\n d_ProximityData_2.append(Proximity_2)\n\n # Format data to view in console\n values[0] = Force\n values[1] = Proximity_1\n values[2] = Proximity_2\n values[3] = timeTracker[-1]\n values[4] = d_Force\n values[5] = d_Proximity_1\n values[6] = d_Proximity_2\n print('|', '%.4f'%values[0], ' |', '%.4f'%values[1], '|', '%.4f'%values[2], '|', '%.4f'%values[3], '|', '%.4f'%values[4], '|', '%.4f'%values[5], '|', '%.4f'%values[6], '|')\n # Pause for display\n time.sleep(0)\n\n# Excel Spreadsheet (within current folder)\nSensorData = {'timeTracker': timeTracker, 'Force': ForceData, 'Proximity_1': d_ProximityData_1, 'Proximity_2': ProximityData_2, 'd_Force': d_ForceData, 'd_Proximity_1': d_ProximityData_1, 'd_Proximity_2': d_ProximityData_2}\nResults = pd.DataFrame(data = SensorData)\nwriter = pd.ExcelWriter('SensorData.xlsx', engine='xlsxwriter')\nResults.to_excel(writer, sheet_name = 'Sheet1')\nwriter.save()","sub_path":"Archive/Write_Sensor_Data.py","file_name":"Write_Sensor_Data.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"128538974","text":"#!/usr/bin/env python3\n\n\n'''\nRevature is building a new API! This API contains functions for validating data, \nsolving problems, and encoding data. \n\nThe API consists of 10 functions that you must implement.\n\nGuidelines:\n1) Edit the file to match your first name and last name with the format shown.\n\n2) Provide tests in the main method for all functions, We should be able to run\nthis script and see the outputs in an organized manner.\n\n3) You can leverage the operating system if needed, however, do not use any non\nlegacy command that solves the problem by just calling the command.\n\n4) We believe in self commenting code, however, provide comments to your solutions\nand be organized.\n\n5) Leverage resources online if needed, but remember, be able to back your solutions\nup since you can be asked.\n\n6) Plagiarism is a serious issue, avoid it at all costs.\n\n7) Don't import external libraries which are not python native\n\n8) Don't change the parameters or returns, follow the directions.\n\n9) Assignment is due on Monday (9:00 am), send assigment to Trainer through Slack\n\nHappy Scripting!\n\n© 2018 Revature. All rights reserved.\n'''\n\n'''\nUse the main function for testing purposes and to show me results for all functions.\n'''\ndef main():\n\tprint(\"\\nReverse String Tests:\")\n\tprint('example'[::-1]) #one method found online\n\tprint(reverse('example')) #method I developed\n\t\n\tprint(\"Acronym Tests:\\n\")\n\tprint(\"Should be 'PNG'\")\n\tprint(acronym('Portable Network Graphics'))\n\tprint(\"Shoulbe be 'TBC'\")\n\tprint(acronym('the block chain'))\n\t\n\tprint(\"Triangle Tests: \\n\")\n\tprint('Should be equilateral.')\n\tprint(whichTriangle(4,4,4))\n\t\n\tprint('Should be iso.')\n\tprint(whichTriangle(1,4,1))\n\t\n\tprint('Should be iso.')\n\tprint(whichTriangle(4, 1,1))\n\t\n\tprint('Should be iso.')\n\tprint(whichTriangle(1,1,4))\n\t\n\tprint('Should be scalene.')\n\tprint(whichTriangle(1,2,3))\n\t\n\tprint('Should be error message.')\n\tprint(whichTriangle(0,1,1))\n\t\n\tprint(\"Scrabble Tests:\\n\")\n\tprint('Testing \"cabbage\", should be 14 points.')\n\tprint(scrabble('cabbage'))\n\tprint()\n\tprint('Testing \"example4\", will give error message.')\n\tprint(scrabble('example4'))\n\tprint()\n\tprint('testing \"reACtionary\", should be 16 points.')\n\tprint(scrabble('reactionary'))\n\t\n\tprint(\"\\nArmstrong Number Tests:\")\n\tprint(\"\\nTesting '9', should be True.\")\n\tprint(armstrong(9))\n\tprint(\"\\nTesting '10', should be False.\")\n\tprint(armstrong(10))\n\tprint(\"\\nTesting '153', should be True.\")\n\tprint(armstrong(153))\n\tprint(\"\\nTesting '154', should be False.\")\n\tprint(armstrong(154))\n\t\n\tprint(\"\\nTesting Primes Numbers:\")\n\tprint(\"\\nPrime test '10'\")\n\tprint(primeFactors(10))\n\tprint(\"\\nPrime test '400'\") \n\tprint(primeFactors(400))\n\tprint(\"\\nPrime test '37'\")\t\n\tprint(primeFactors(37))\n\t\n\tprint(\"\\nTesting Pangram:\")\n\tprint(pangram(\"The quick brown fox jumps over the lazy dog.\"))\n\tprint(pangram(\"Books a million.\"))\n\t\n\tprint(\"\\nTesting Sort:\")\n\tprint(sort([2,4,5,1,3,1]))\n\tprint(sort([9,2,4,6,0,9,10000]))\n\t\n\t\n#\tprint(\"\\nTesting Evens/Odds\")\n#\tevenAndOdds()\n\n\n\tprint(\"\\nTesting Cipher:\")\n\tprint(\"\\nTesting 'abc'\")\n\tprint(rotate(3, 'abc'))\n\tprint(\"\\nTesting 'The quick brown fox jumps over the lazy dog.\\nShould be: \\n\\nGur dhvpx oebja sbk whzcf bire gur ynml qbt.\\n\")\n\tprint(rotate(13, 'The quick brown fox jumps over the lazy dog.'))\n\t\n\t\n\t\n\t\n\t\n\t\n'''\n1. Reverse a String. Example: reverse(\"example\"); -> \"elpmaxe\"\n\nRules:\n- Do NOT use built-in tools\n- Reverse it your own way\n\nparam: str\nreturn: str\n'''\n\ndef reverse(string):\n\tnewString = \"\"\n\tif string.isalpha():\n\t\tfor i in range(len(string)-1, -1, -1): #fun index out of bounds errors\n\t\t\tnewString += string[i]\n\telse:\n\t\tnewString = \"Please use a string made of only alphabetic characters.\"\n\treturn newString + '\\n'\n\n\n'''\n2. Convert a phrase to its acronym. Techies love their TLA (Three Letter\nAcronyms)! Help generate some jargon by writing a program that converts a\nlong name like Portable Network Graphics to its acronym (PNG).\n\nparam: str\nreturn: str\n'''\n\n#\t\tGrabs first character of each word\t\t#\n#\t\tEnsures the characters are upper case.\t#\ndef acronym(phrase):\n\tif phrase.isalnum():\n\t\tphrase = phrase.split(' ')\n\t\tacr = ''\n\t\tfor c in phrase:\n\t\t\tacr += c[0].upper()\n\telse:\n\t\tacr = \"Acronyms do not generally contain special characters.\"\n\treturn acr + '\\n'\n\n\t\n\t\n'''\n3. Determine if a triangle is equilateral, isosceles, or scalene. An\nequilateral triangle has all three sides the same length. An isosceles\ntriangle has at least two sides the same length. (It is sometimes specified\nas having exactly two sides the same length, but for the purposes of this\nexercise we'll say at least two.) A scalene triangle has all sides of\ndifferent lengths.\n\nparam: float, float, float\nreturn: str -> 'equilateral', 'isoceles', 'scalene'\n'''\n\n#\t\tFound it easier to give rules for the two extremes:\t\t\t#\n#\t\t\"None match\"\t\t\t\t\t\t\t\t\t\t\t\t#\n#\t\t\"All match\"\t\t\t\t\t\t\t\t\t\t\t\t\t#\n#\t\tAfter that, it either isn't a triangle, or is iscoseles.\t#\n\ndef whichTriangle(sideOne, sideTwo, sideThree):\n\ttriangle = ''\n\tif (sideOne == 0 or sideTwo == 0 or sideThree == 0):\n\t\ttriangle = 'Please enter valid dimensions for a triangle.'\n\t\t\n\telif sideOne == sideTwo and sideOne == sideThree:\n\t\ttriangle = 'equilateral'\n\t\n\telif sideOne != sideTwo and sideOne != sideThree and sideTwo != sideThree:\n\t\ttriangle = 'scalene'\n\t\n\telse:\n\t\ttriangle = 'isoceles'\n\t\n\t\n\treturn triangle + '\\n'\n\n\t\n'''\n4. Given a word, compute the scrabble score for that word.\n\n--Letter Values-- Letter Value A, E, I, O, U, L, N, R, S, T = 1; D, G = 2; B,\nC, M, P = 3; F, H, V, W, Y = 4; K = 5; J, X = 8; Q, Z = 10; Examples\n\"cabbage\" should be scored as worth 14 points:\n\n3 points for C, 1 point for A, twice 3 points for B, twice 2 points for G, 1\npoint for E And to total:\n\n3 + 2*1 + 2*3 + 2 + 1 = 3 + 2 + 6 + 3 = 5 + 9 = 14\n\nparam: str\nreturn: int\n'''\ndef scrabble(word):\n\n\tif word.isalpha() and len(word) > 0:\n\t\tword = word.upper()\n\t\tscrabble = {'A':1, 'E':1, 'I':1, 'O':1, 'U':1, 'L':1, 'N':1, 'S':1, 'T':1, 'R':1, 'D':2, 'G':2, 'B':3, 'C':3, 'M':3, 'P':3, 'F':4, 'H':4, 'V':4, 'W':4, 'Y':4, 'K':5, 'J':8, 'X':8, 'Q':10, 'Z':10}\n\t\tscore = 0\n\t\tfor i in word:\n\t\t\tscore += int(scrabble[i])\n\telse: \n\t\tscore = \"Please enter only valid alphabetic characters.\"\n\treturn score \n\n\t\n'''\n5. An Armstrong number is a number that is the sum of its own digits each\nraised to the power of the number of digits.\n\nFor example:\n\n9 is an Armstrong number, because 9 = 9^1 = 9. \n\n10 is not an Armstrong number ,because 10 !==> (1^2 + 0^2) = 2.\n\n153 is an Armstrong number, because: 153 ==> (1^3 +5^3 + 3^3) = 1 + 125 + 27 = 153. \n\n154 is not an Armstrong number, because: \n\t154 ==> 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190 \n\nWrite some code to determine whether if a number is an Armstrong number.\n\nparam: int\nreturn: bool\n'''\n\ndef armstrong(number):\n\tisArmstrong = False\n\t\n\tlength = len(str(number)) #number of characters\n\tarm = 0\n\tstrNum = str(number)\n\tfor i in range(0, length):\n\t\tarm += int(strNum[i])**length\n\t\n\tif arm == number:\n\t\tisArmstrong = True\n\n\treturn isArmstrong\n\t\n\t\n'''\n6. Compute the prime factors of a given natural number.\n\nA prime number is only evenly divisible by itself and 1.\n \nNote that 1 is not a prime number.\n\nparam: int\nreturn: list\n'''\n\ndef primeFactors(number):\n\t\n\tprimes = [] \n\twhile number % 2 == 0 :\n\t\tprimes.append(2)\n\t\tnumber /= 2\n\tfor i in range(3, int(pow(number,.5))+1,2):\t #source: geeksForGeeks for the explanation of the range\n\t\t\t\t\t\t\t\t\t\t\t\t\t#I can try my best to explain, as well.\n\t\twhile number % i == 0:\n\t\t\tprimes.append(i)\n\t\t\tnumber /= i\n\tif number > 2:\n\t\tprimes.append(int(number))\n\t\t\n\treturn primes\n\t\n\t\n'''\n7. Determine if a sentence is a pangram. A pangram (Greek: παν γράμμα, pan\ngramma, \"every letter\") is a sentence using every letter of the alphabet at\nleast once. The best known English pangram is:\n\nThe quick brown fox jumps over the lazy dog.\n \nThe alphabet used consists of ASCII letters a to z, inclusive, and is case\ninsensitive. Input will not contain non-ASCII symbols.\n \nparam: str\nreturn: bool\n'''\ndef pangram(sentence):\n\tparam = sentence\n\tletters = []\n\tisPangram = False\n\n\tsentence = sentence.upper()\n\n\tfor i in sentence:\n\t\tif i.isalnum():\n\t\t\tletters.append(i)\n\n\talpha = {\n\t\t\t\t'A':0, 'B':0, 'C':0, 'D':0, 'E':0, 'F':0, 'G':0, 'H':0, 'I':0, 'J':0, 'K':0, 'L':0, 'M':0, \n\t\t\t\t'N':0, 'O':0, 'P':0, 'Q':0, 'R':0, 'S':0, 'T':0, 'U':0, 'V':0, 'W':0, 'X':0, 'Y':0, 'Z':0\n\t\t\t}\n\n\tfor l in letters:\n\t\talpha[l] = 1\n\n\ttotal = 0\n\tfor a in alpha:\n\t\ttotal += alpha[a]\n\t\n\tif total == 26:\n\t\tisPangram = True\n\tprint(\"\\n\" + param)\n\treturn isPangram\n\t\n\t\n\t\n\t\n\t\n'''\n8. Sort list of integers.\nf([2,4,5,1,3,1]) = [1,1,2,3,4,5]\n\nRules:\n- Do NOT sort it with .sort() or sorted(list) or any built-in tools.\n- Sort it your own way\n\nparam: list\nreturn: list\n'''\n\n\n\n\ndef sort(numbers):\n\t#def isSorted(numList):\n\t\n\tfor x in range(0, len(numbers)-1):\n\t\tfor i in range(0, len(numbers)-1):\n\t\t\tif numbers[i] > numbers[i+1]:\n\t\t\t\ttemp = numbers[i+1]\n\t\t\t\tnumbers[i+1]= numbers[i]\n\t\t\t\tnumbers[i]=temp\n\n\treturn numbers\n\n\t\n\t\n\t\n'''\n9. Create an implementation of the rotational cipher, also sometimes called\nthe Caesar cipher.\n\nThe Caesar cipher is a simple shift cipher that relies on transposing all the\nletters in the alphabet using an integer key between 0 and 26. Using a key of\n0 or 26 will always yield the same output due to modular arithmetic. The\nletter is shifted for as many values as the value of the key.\n\nThe general notation for rotational ciphers is ROT + . The most commonly\nused rotational cipher is ROT13.\n\nA ROT13 on the Latin alphabet would be as follows:\n\nPlain: abcdefghijklmnopqrstuvwxyz Cipher: nopqrstuvwxyzabcdefghijklm It is\nstronger than the Atbash cipher because it has 27 possible keys, and 25\nusable keys.\n\nCiphertext is written out in the same formatting as the input including\nspaces and punctuation.\n\nExamples: ROT5 omg gives trl ROT0 c gives c ROT26 Cool gives Cool ROT13 The\nquick brown fox jumps over the lazy dog. gives Gur dhvpx oebja sbk whzcf bire\ngur ynml qbt. ROT13 Gur dhvpx oebja sbk whzcf bire gur ynml qbt. gives The\nquick brown fox jumps over the lazy dog.\n\nparam: int, str\nreturn: str\n'''\n\n\n\ndef rotate(key, string):\n\tupper = {ascii:chr(ascii) for ascii in range(65,91)}\t#source: stackoverflow, ANSI, Bob Bemer#\n\tlower = {ascii:chr(ascii) for ascii in range(97,123)}\n\t\n\tscrambled = \"\"\n\t\n\n\tfor char in string:\n\t\tvalue = ord(char)\n\t\tif value in lower and value + key < 123:\n\t\t\tscrambled += chr(value+key)\n\t\t\n\t\telif value in lower and value+ key > 122:\n\t\t\tscrambled += chr(value+key-26)\n\t\t\n\t\telif value in upper and value + key <92:\n\t\t\tscrambled += chr(value+key)\n\t\t\t\n\t\telif value in upper and value+ key > 91:\n\t\t\tscrambled += chr(value+key-26)\n\t\telse:\n\t\t\tscrambled += char\n\treturn scrambled\n\n'''\n10. Take 10 numbers as input from the user and store all the even numbers in a file called even.txt and\nthe odd numbers in a file called odd.txt.\n\nparam: none, from the keyboard\nreturn: nothing\n'''\n\n\ndef evenAndOdds():\n\t\n\t\n\tefile = open('even.txt', 'w')\n\tofile = open('odd.txt', 'w')\n\t\n\ti = 0\n\t\n\twhile i < 10:\n\t\ttry:\n\t\t\tnumber = int(input('give number\\n'))\n\t\t\tif number % 2 == 0:\n\t\t\t\tefile.write(str(number)+ '\\n')\n\t\t\telse:\n\t\t\t\tofile.write(str(number)+ '\\n')\n\t\t\ti+=1\n\t\texcept ValueError:\n\t\t\tprint(\"Enter only numeric characters.\")\n\t\t\t\n\t\n\tefile.close()\n\tofile.close()\n\n\nif __name__ == '__main__':\n\tmain() \n","sub_path":"Assignment2/TaylorBartley.py","file_name":"TaylorBartley.py","file_ext":"py","file_size_in_byte":11270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"348913338","text":"import sys\nimport os\nimport re\nimport math\nimport random\n\n\"\"\"\n ============================================================================================\n For any two distinct people a and b, a may or may not know b. In the context of this problem,\n the \"knows\" relation is not necessary symmetric: a may know b, but b may not know a. At a\n party, every one knows someone else. Now a celebrity joins the party - everyone knows him, but\n he knows no one.\n\n Let F be a n x n boolean 2D array repersenting the \"knows\" relations for n people - F[a][b]\n is true if and only if a knows b. Design an algorithm to find the celebrity.\n ============================================================================================\n\"\"\"\ndef findCelebrity(F):\n \"\"\"\n Brute force: The goal is to find a column with all 1's except for one spot which is the\n celebrity himself.\n \"\"\"\n m = len(F)\n n = len(F[0])\n\n for j in range(0, n):\n count = 0\n for i in range(0, m):\n if m[i][j] == False and i != j:\n break\n count += 1\n\n if count == m:\n i = 0\n while i < n and F[i][j] == False:\n i += 1\n\n if i == n:\n return j\n\ndef findCelebrity2(F):\n \"\"\"\n The challenge to avoid having to look at all of F, which result in a O(n^2) time complexity.\n\n The key to achieving time efficiency is to process people in order, and eliminate at least\n one people from the set with each lookup into F. We begin by checking F[0][1], i.e, the\n relation between Person 0 and Person 1.\n \n Suppose we check F[i][j] where i < j. The problem statement guarantees that if F[i][j] is false,\n j is not celebrity and i is still a possible celebrity candidate. Hence we eliminate j from\n the set of celebrity and move to F[i][j + 1].\n\n If F[i][j] is true, than Person i cannot be the celebrity, and for all j' < j, j' is not a celebrity\n because F[i][j'] must be false. We then move to F[j][j + 1] since i < j.\n\n Time complexity: O(n), space O(1)\n \"\"\"\n i = 0\n j = 1\n while j < len(F):\n if F[i][j]:\n i += j\n\n # we need to increment j both when F[i][j] is true or fales\n j += 1\n\n return i\n","sub_path":"EPI/Python/Array/6_26_identifyTheCelebrity.py","file_name":"6_26_identifyTheCelebrity.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"622510573","text":"from flask import g\nfrom flask_restful import Resource, reqparse, abort\n\nfrom model.books import BooksModel\nfrom model.reviews import ReviewsModel\nfrom model.users import UsersModel, auth, Roles\nfrom utils.lock import lock\n\n\ndef parse_review(required=True):\n parser = reqparse.RequestParser(bundle_errors=True)\n\n parser.add_argument('isbn', required=required, type=int,\n help=\"ISBN of the book associated to the review. Can't be null.\")\n parser.add_argument('email', required=required, type=str,\n help=\"Email of the user associated to the review. Can't be null.\")\n parser.add_argument('score', required=required, type=int,\n help=\"Integer score ranging from 1 to 5 which indicates book score. Can't be null.\")\n parser.add_argument('review', required=False, type=str,\n help=\"Review message the user has posted with the score. Can be null.\")\n\n return parser.parse_args()\n\n\ndef check_user_and_book(user_model, isbn, ignore_if_admin=False):\n if not user_model:\n abort(404, message={\"message\": f\"User Not Found\"})\n\n if not BooksModel.find_by_isbn(isbn):\n abort(404, message={\"message\": f\"Book with ['isbn': {isbn}] Not Found\"})\n\n if ignore_if_admin:\n # First statement checks if the role is user and that it doesn't try to modify an other user\n # Second statement checks if the user who wants to modify it's not and Admin\n if (g.user.role is not Roles.User or g.user != user_model) and g.user.role is not Roles.Admin:\n abort(401, message={\"message\": \"Invalid user to remove, can only be yourself\"})\n else:\n if g.user != user_model:\n abort(401, message={\"message\": \"Invalid user to remove, can only be yourself\"})\n\n\nclass Reviews(Resource):\n\n @auth.login_required(role=Roles.User)\n def post(self):\n data = parse_review()\n with lock:\n user = UsersModel.find_by_email(data['email'])\n check_user_and_book(user, data['isbn'])\n\n if data['score'] < 1 or data['score'] > 5:\n return {\"message\": f\"{data['score']} is not a valid value for score. Score must be an integer ranging \"\n f\"from 1 to 5.\"}, 418\n\n if ReviewsModel.find_by_isbn_user_id(data.isbn, user.id) is not None:\n return {\"message\": \"Given user already posted a review. Did you meant to update it?\"}, 403\n\n data['user_id'] = user.id\n del data['email']\n try:\n review = ReviewsModel(**data)\n review.save_to_db()\n except Exception as e:\n return {\"message\": str(e)}, 500\n\n return review.json(), 201\n\n @auth.login_required\n def delete(self, user_id, isbn):\n with lock:\n user = UsersModel.find_by_id(user_id)\n check_user_and_book(user, isbn, True)\n\n review = ReviewsModel.find_by_isbn_user_id(isbn, user_id)\n if review is None:\n return {\"message\": \"Given user hasn't posted a review yet. Did you meant to post it?\"}, 404\n\n try:\n review.delete_from_db()\n except Exception as e:\n return {\"message\": str(e)}, 500\n\n return {\"message\": f\"Review with ['user_id': {user_id}, 'isbn': {isbn}] deleted\"}, 200\n\n @auth.login_required(role=Roles.User)\n def put(self, user_id, isbn):\n data = parse_review(False)\n with lock:\n user = UsersModel.find_by_id(user_id)\n check_user_and_book(user, isbn)\n\n review = ReviewsModel.find_by_isbn_user_id(isbn, user_id)\n if review is None:\n return {\"message\": \"Given user hasn't posted a review yet. Did you meant to post it?\"}, 404\n\n try:\n review.update_from_db(data)\n except Exception as e:\n return {\"message\": str(e)}, 500\n\n return {\"review\": review.json()}, 200\n\n","sub_path":"backend/resources/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"348334709","text":"from threading import Thread\nfrom evdev import InputDevice\nfrom select import select\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import RPi.GPIO as GPIO\nexcept RuntimeError as error:\n print(error)\n from mock import GPIO\n\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(13,GPIO.OUT)\n\n\nclass Rfid(Thread):\n def __init__(self, app):\n super().__init__()\n self.app = app\n self.dev = InputDevice('/dev/input/event0')\n self.running = True\n self.buffer = []\n print(app)\n\n def run(self):\n while self.running:\n self.read_events()\n\n def stop(self):\n self.running = False\n \n def read_events(self):\n r, x, z = select([self.dev], [], [])\n for event in self.dev.read():\n if event.type==1 and event.value==1 and event.code == 28:\n # Key code 28 (Enter)\n # 4804804 (last 7 character)\n\n\n logging.warning('push enter')\n logging.warning(''.join(map(str, self.buffer)))\n self.buffer = []\n else:\n self.buffer.append(event.code)\n","sub_path":"rfid.py","file_name":"rfid.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"178547432","text":"# -*- coding: utf-8 -*-\n\n\n\nfrom selenium import webdriver\n\nfrom selenium.common.exceptions import TimeoutException\n\nfrom selenium.webdriver.common.by import By\n\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom scrapy.http import HtmlResponse\n\nfrom logging import getLogger\n\n\n\n\n\nclass SeleniumMiddleware():\n\n def __init__(self, timeout=None):\n\n self.logger = getLogger(__name__)\n\n self.timeout = timeout\n\n self.browser = webdriver.Chrome()\n\n self.browser.set_window_size(1400, 700)\n\n self.browser.set_page_load_timeout(self.timeout)\n\n self.wait = WebDriverWait(self.browser, self.timeout)\n\n \n\n def __del__(self):\n\n self.browser.close()\n\n \n\n def process_request(self, request, spider):\n\n \"\"\"\n\n 用PhantomJS抓取页面\n\n :param request: Request对象\n\n :param spider: Spider对象\n\n :return: HtmlResponse\n\n \"\"\"\n\n self.logger.debug('PhantomJS is Starting')\n\n page = request.meta.get('page', 1)\n\n try:\n\n self.browser.get(request.url)\n\n if page > 1:\n\n input = self.wait.until(\n\n EC.presence_of_element_located((By.XPATH, '//input[@id=\"Jumper\"]')))\n\n submit = self.wait.until(\n\n EC.element_to_be_clickable((By.XPATH, '//a[@class=\"pageConfirm\"]')))\n\n input.clear()\n\n input.send_keys(page)\n\n submit.click()\n\n self.wait.until(\n\n EC.text_to_be_present_in_element((By.XPATH, '//span[@class=\"page-cur\"]'), str(page)))\n\n self.wait.until(EC.presence_of_element_located((By.XPATH, '//div[@id=\"mainsrp-itemlist\"]//div[@class=\"items\"][1]//div[contains(@class, \"item\")]')))\n\n return HtmlResponse(url=request.url, body=self.browser.page_source, request=request, encoding='utf-8',\n\n status=200)\n\n except TimeoutException:\n\n return HtmlResponse(url=request.url, status=500, request=request)\n\n \n\n @classmethod\n\n def from_crawler(cls, crawler):\n\n return cls(timeout=crawler.settings.get('SELENIUM_TIMEOUT'))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"scrapyseleniumtest/scrapyseleniumtest/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"121914749","text":"from rest_framework.response import Response\nfrom rest_framework.utils import json\nfrom rest_framework.views import APIView\nfrom utils.restful_data import Restful\nfrom .models import User\nimport time\nimport hashlib\nimport re\n\n\nclass RegisterView(APIView):\n def get(self, request, *args, **kwargs):\n print(request.GET)\n return Response({'code': 500, 'msg': 'message', 'data': {}})\n\n def post(self, request, *args, **kwargs):\n try:\n params = json.loads(request.body.decode('utf-8').replace(\"'\", \"\\\"\")) if request.body else None\n if re.match(r'\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,8}\\b', params['email']):\n email = params['email']\n phone = ''\n elif re.match(r'^1(3\\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\\d{8}$', params['email']):\n email = ''\n phone = params['email']\n else:\n return Restful.response(400, '手机号 或 邮箱 格式错误', {})\n if User().select({'username': params['username']}):\n return Restful.response(401, '用户名重复', {})\n if User().select({'$or': [{'telephone': params['email']}, {'email': params['email']}]}):\n return Restful.response(402, '手机号 或 邮箱 已存在', {})\n b = hashlib.md5()\n b.update(params['password'].encode(encoding='utf-8'))\n user = {\n 'username': params['username'],\n 'password': b.hexdigest(),\n 'avatar': '/static/avatar.jpg',\n 'fullname': '',\n 'sex': '不男不女',\n 'birthday': '',\n 'description': 'My name is ' + params['username'],\n 'last': '',\n 'email': email,\n 'telephone': phone,\n 'role': 5,\n 'join_date': time.strftime('%Y-%m-%d', time.localtime(time.time())),\n 'mark': '',\n 'level': '0',\n 'empirical': '0',\n 'lang': 'zh',\n 'disable': 0,\n }\n User().insert(user)\n return Restful.ok('注册成功')\n except Exception as e:\n return Restful.response(500, str(e), {})\n\n def put(self, request, *args, **kwargs):\n params = json.loads(request.body.decode('utf-8').replace(\"'\", \"\\\"\")) if request.body else None\n print(type(params), params)\n return Response({'code': 500, 'msg': 'message', 'data': {}})\n\n def delete(self, request, *args, **kwargs):\n params = request.body.decode('utf-8') if request.body else None\n print(type(params), params)\n # QueryDict(params).get('')\n return Response({'code': 500, 'msg': 'message', 'data': {}})\n","sub_path":"interface/authentication/register_views.py","file_name":"register_views.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"560061313","text":"import pywt\nimport os\nimport numpy\nimport matplotlib.pylab as plt\n\nif __name__ == '__main__':\n dbFamily = ['db1', 'db2', 'db4']\n\n for wavlet in dbFamily:\n loadpath = 'D:\\\\ProjectData\\\\Csv\\\\'\n for indexA in os.listdir(loadpath):\n for indexB in os.listdir(loadpath + indexA):\n pngSavepath = 'F:\\\\WaveletTransform-Again\\\\' + wavlet + '-png\\\\' + indexA + '\\\\' + indexB + '\\\\'\n if os.path.exists(pngSavepath): continue\n\n os.makedirs(pngSavepath + 'cA')\n os.makedirs(pngSavepath + 'cH')\n os.makedirs(pngSavepath + 'cV')\n os.makedirs(pngSavepath + 'cD')\n\n csvSavePath = 'F:\\\\WaveletTransform-Again\\\\' + wavlet + '-csv\\\\' + indexA + '\\\\' + indexB + '\\\\'\n os.makedirs(csvSavePath + 'cA')\n os.makedirs(csvSavePath + 'cH')\n os.makedirs(csvSavePath + 'cV')\n os.makedirs(csvSavePath + 'cD')\n\n for indexC in os.listdir(loadpath + indexA + '\\\\' + indexB):\n print(wavlet, indexA, indexB, indexC)\n treatData = numpy.genfromtxt(loadpath + indexA + '\\\\' + indexB + '\\\\' + indexC, dtype=int,\n delimiter=',')\n cA, (cH, cV, cD) = pywt.dwt2(data=treatData, wavelet=wavlet)\n\n plt.figure(figsize=(numpy.shape(cA)[0] / 100, numpy.shape(cA)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cA, cmap='gray')\n plt.savefig(pngSavepath + 'cA\\\\' + indexC + '.png')\n plt.clf()\n plt.close()\n\n plt.figure(figsize=(numpy.shape(cH)[0] / 100, numpy.shape(cH)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cH, cmap='gray')\n plt.savefig(pngSavepath + 'cH\\\\' + indexC + '.png')\n plt.clf()\n plt.close()\n\n plt.figure(figsize=(numpy.shape(cV)[0] / 100, numpy.shape(cV)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cV, cmap='gray')\n plt.savefig(pngSavepath + 'cV\\\\' + indexC + '.png')\n plt.clf()\n plt.close()\n\n plt.figure(figsize=(numpy.shape(cD)[0] / 100, numpy.shape(cD)[1] / 100))\n plt.axis('off')\n plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n plt.imshow(cD, cmap='gray')\n plt.savefig(pngSavepath + 'cD\\\\' + indexC + '.png')\n plt.clf()\n plt.close()\n\n file = open(csvSavePath + 'cA\\\\' + indexC, 'w')\n for indexX in range(len(cA)):\n for indexY in range(len(cA[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cA[indexX][indexY]))\n file.write('\\n')\n file.close()\n\n file = open(csvSavePath + 'cH\\\\' + indexC, 'w')\n for indexX in range(len(cH)):\n for indexY in range(len(cH[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cH[indexX][indexY]))\n file.write('\\n')\n file.close()\n\n file = open(csvSavePath + 'cV\\\\' + indexC, 'w')\n for indexX in range(len(cV)):\n for indexY in range(len(cV[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cV[indexX][indexY]))\n file.write('\\n')\n file.close()\n\n file = open(csvSavePath + 'cD\\\\' + indexC, 'w')\n for indexX in range(len(cD)):\n for indexY in range(len(cD[indexX])):\n if indexY != 0: file.write(',')\n file.write(str(cD[indexX][indexY]))\n file.write('\\n')\n file.close()\n","sub_path":"LIDC_Project/Records/Fragment/WaveletTransformTest.py","file_name":"WaveletTransformTest.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"304309056","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport argparse\nimport os\nimport subprocess\n\n\nTEMPLATE_DIR = os.getenv('CLEAN_OUTPUT_TEMPLATE')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Use on an ipynb to out html using the clean_output.tpl')\n parser.add_argument('infile', help='Input ipynb file (.ipynb ext optional)')\n parser.add_argument('--output', help='Optional output file name. Defaults to adding _output to the original input filename.')\n args = parser.parse_args()\n\n if args.infile.endswith('.ipynb'):\n input_file = args.infile\n elif args.infile.endswith('.'): # helps with autocomplete\n input_file = args.infile[:-1] + '.ipynb'\n else:\n input_file = args.infile.split('.')[-1] + '.ipynb'\n\n if not args.output:\n output_file = input_file.split('.')[0] + '_output.html'\n else:\n output_file = args.output\n\n # https://github.com/ihuston/jupyter-hide-code-html\n # $ jupyter nbconvert --to html --template ./clean_output.tpl my_notebook.ipynb\n subprocess.run(['jupyter', 'nbconvert', '--to', 'html', '--template', TEMPLATE_DIR, input_file, '--output', output_file])\n","sub_path":"cleantemplate.py","file_name":"cleantemplate.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"99280081","text":"# -*- coding: utf-8 -*-\nfrom domain.models import TilskuddsordningSaksbehandler\nfrom repo.base_repo import BaseRepo\n\n\nclass TilskuddsordningSaksbehandlereRepo(BaseRepo):\n # used by BaseRepo\n model_class = TilskuddsordningSaksbehandler\n\n @classmethod\n def map_model(cls, tilskuddsordningsaksbehandler_post, data):\n TilskuddsordningSaksbehandlereRepo.update_model(tilskuddsordningsaksbehandler_post, 'saksbehandler_id', data)","sub_path":"flod_sak/repo/tilskuddsordning_saksbehandlere_repo.py","file_name":"tilskuddsordning_saksbehandlere_repo.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"231011920","text":"from maintain_frontend.services.validation.field_validator import FieldValidator\nfrom maintain_frontend.services.validation.validation_error_builder import ValidationErrorBuilder\n\n\nclass PaymentReasonValidator(object):\n @staticmethod\n def validate(payment_for):\n \"\"\"Specifies which validation methods should be called for each input field.\n\n\n parameters:\n - payment_for: The reason for payment e.g. LON or official search\n\n returns:\n dict: A validation errors dict with the fieldname as a key and the associated validation errors in a list\n as the value.\n \"\"\"\n\n validation_error_builder = ValidationErrorBuilder()\n\n FieldValidator(payment_for, 'payment_for', 'Payment link reason', validation_error_builder,\n inline_message='Choose one option') \\\n .is_required()\n\n validation_errors = validation_error_builder.get()\n\n return validation_errors\n","sub_path":"maintain_frontend/send_payment_link/validation/payment_reason_validator.py","file_name":"payment_reason_validator.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"188693484","text":"import numpy as np\nfrom celluloid import Camera\nfrom matplotlib import pyplot as plt\n\nr_min = 0.1\nr_max = 1.9\nc = 1.5\na = 0.6\nb = 1.2\n\nN = 200\ndim = 1\nC = 0.4\nM = 1.5\nk = 3\n\nh = (r_max - r_min) / N\ntau = C * h / c\nnt = int(M / tau)\nrs = np.arange(r_min - h / 2, r_max + h, h)\n\n\ndef v0(x):\n if a < x < b:\n return np.exp((-4 * (2 * x - (a + b)) * (2 * x - (a + b))) /\n ((b - a) * (b - a) - (2 * x - (a + b)) * (2 * x - (a + b))))\n else:\n return 0\n\n\ndef dv(x):\n if a < x < b:\n return - ((a - b) ** 2 * (-a - b + 2 * x) * np.exp(-((a + b - 2 * x) ** 2 / ((a - x) * (x - b))))) / (\n (a - x) ** 2 * (b - x) ** 2)\n else:\n return 0\n\n\ndef analit_u(r, x):\n return r ** ((1 - dim) / 2) * v0(x)\n\n\ndef analit_du(r, x):\n return ((1 - dim) / 2) * r ** (-(1 + dim) / 2) * v0(x) - r ** ((1 - dim) / 2) * dv(x)\n\n\ndef u(N):\n h = (r_max - r_min) / N\n tau = C * h / c\n nt = int(M / tau)\n rs = np.arange(r_min - h / 2, r_max + h, h)\n\n # coefs\n A = [tau * tau * c * c * rs[i] ** (1 - dim) / h * (rs[i] + h / 2) ** (dim - 1) / h for i in range(N + 2)]\n B = [tau * tau * c * c * rs[i] ** (1 - dim) / h * (rs[i] - h / 2) ** (dim - 1) / h for i in range(N + 2)]\n\n u0 = [analit_u(rs[i], rs[i]) for i in range(N + 2)]\n u1 = [0] * (N + 2)\n u_n = [0] * (N + 2)\n\n for i in range(1, N + 1):\n u1[i] = analit_u(rs[i], -c * tau + rs[i])\n\n res = [[0 for _ in range(N)] for _ in range(nt)]\n res[0] = u0[1:N + 1]\n res[1] = u1[1:N + 1]\n\n for i in range(1, nt):\n for j in range(1, N + 1):\n u_n[j] = 2 * u1[j] - u0[j] + A[j] * (u1[j + 1] - u1[j]) - B[j] * (u1[j] - u1[j - 1])\n u_n[0] = u_n[1] + h * analit_du(r_min, r_min - c * tau * (i + 1))\n u_n[-1] = u_n[-2] - h * analit_du(r_max, r_max - c * tau * (i + 1))\n u0 = u1.copy()\n u1 = u_n.copy()\n res[i] = u0[1:N + 1]\n return res\n\n\ndef analytic(N):\n h = (r_max - r_min) / N\n tau = C * h / c\n nt = int(M / tau)\n rs = np.arange(r_min - h / 2, r_max + h, h)\n res = np.zeros((nt, N + 2))\n for n in range(nt):\n for i in range(N + 2):\n res[n][i] = rs[i] ** ((1 - dim) / 2) * v0(-c * tau * n + rs[i])\n return res\n\n\ndef animate(N, nt):\n X = np.linspace(0, 1.8, N)\n fig = plt.figure()\n camera = Camera(fig)\n plt.grid(\"ON\")\n # plt.xlim(0.0, 1.75)\n # plt.ylim(0.0, 1.0)\n for i in range(0, nt):\n b = a1[i][1:N + 1]\n plt.plot(X, u1[i])\n plt.plot(X, b)\n plt.text(0.1, 1.0, \"{:f}\".format(i * tau))\n camera.snap()\n animation = camera.animate()\n plt.show()\n\n\ndef l2_norma(u1, u2, u3):\n norma = [0] * nt\n for i in range(nt):\n top = 0\n bot = 0\n for j in range(N):\n top += abs(u1[i][j] - u2[3 * i][3 * j + 1]) ** 2\n bot += abs(u2[3 * i][3 * j + 1] - u3[9 * i][9 * j + 4]) ** 2\n norma[i] = np.sqrt(top / bot)\n return norma\n\n\ndef c_norma(u1, u2, u3):\n norma = [0.] * nt\n top = [[0 for _ in range(N)] for _ in range(nt)]\n bot = [[0 for _ in range(N)] for _ in range(nt)]\n for i in range(nt):\n for j in range(N):\n top[i][j] = u1[i][j] - u2[3 * i][3 * j + 1]\n bot[i][j] = u2[3 * i][3 * j + 1] - u3[9 * i][9 * j + 4]\n norma[i] = max(top[i]) / max(bot[i])\n return norma\n\n\ndef l2_norma_analyt(u1, u2, b):\n norma = [0] * nt\n\n for i in range(nt):\n a = b[i][1:N + 1]\n top = 0\n bot = 0\n for j in range(N):\n top += abs(u1[i][j] - a[j]) ** 2\n bot += abs(u2[3 * i][3 * j + 1] - a[j]) ** 2\n if top != 0:\n norma[i] = np.sqrt(top / bot)\n else:\n norma[i] = 9\n return norma\n\n\ndef c_norma_analyt(u1, u2, b):\n norma = [0.] * nt\n top = [[0 for _ in range(N)] for _ in range(nt)]\n bot = [[0 for _ in range(N)] for _ in range(nt)]\n for i in range(nt):\n a = b[i][1:N + 1]\n for j in range(N):\n top[i][j] = u1[i][j] - a[j]\n bot[i][j] = u2[3 * i][3 * j + 1] - a[j]\n if (top != 0) & (bot != 0):\n norma[i] = max(top[i]) / max(bot[i])\n else:\n norma[i] = 9\n return norma\n\n\nu1 = u(N)\na1 = analytic(N)\nu2 = u(k * N)\n# a2 = analytic(k * N)\n# u3 = u(k * k * N)\n# a3 = analytic(k * k * N)\n# print(a2[0].__sizeof__())\ntime = [i * tau for i in range(nt)]\n# l2 = l2_norma(u1, u2, u3)\n# Cn = c_norma(u1, u2, u3)\n# X = np.linspace(0, 1.8, N)\nl2 = l2_norma_analyt(u1, u2, a1)\nCn = c_norma_analyt(u1, u2, a1)\nplt.plot(time, l2, label='L2-norm')\nplt.plot(time, Cn, label='C-norm')\nplt.plot(time, [9 for _ in time], label='Ref=9')\nplt.title(u\"O2 for 1D in R{}\".format(dim))\nplt.xlim(0.0, 1.5)\nplt.grid()\nplt.legend()\nplt.show()\n# animate(N, nt)\n","sub_path":"3rd_task.py","file_name":"3rd_task.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"188061156","text":"T = int(input())\r\n\r\nfor i in range(T):\r\n alienNum, sourceLang, targetLang = input().split()\r\n \r\n sourceLangCharDict = {}\r\n sourceBase = 0\r\n for x in sourceLang:\r\n sourceLangCharDict[x] = sourceBase\r\n sourceBase += 1\r\n\r\n targetLangCharIndexer = [x for x in targetLang]\r\n targetBase = len(targetLangCharIndexer)\r\n\r\n alienNumDigitCharList = [x for x in alienNum]\r\n alienNumDigitCharList.reverse()\r\n alienNumInDecimal = 0\r\n for digitPosition in range(len(alienNumDigitCharList)):\r\n alienNumInDecimal += (sourceLangCharDict[alienNumDigitCharList[digitPosition]] * (sourceBase**digitPosition))\r\n\r\n '''\r\n 101101 (binary): --> base = 2\r\n 1 * 2**0 = 1\r\n 0 * 2**1 = 0\r\n 1 * 2**2 = 4\r\n 1 * 2**3 = 8\r\n 0 * 2**4 = 0\r\n 1 * 2**5 = 32\r\n 1 + 0 + 4 + 8 + 0 + 32 = 45\r\n '''\r\n\r\n tmp = alienNumInDecimal\r\n translatedNum = []\r\n while tmp > 0:\r\n digit = tmp % targetBase\r\n translatedNum.append(targetLangCharIndexer[digit])\r\n tmp //= targetBase\r\n\r\n translatedNum.reverse()\r\n print(\"\".join(translatedNum))\r\n","sub_path":"basic/aliennumbers.py","file_name":"aliennumbers.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361650086","text":"import argparse\nfrom ast import literal_eval\nfrom astropy.io import fits\nimport base64\nfrom bson.json_util import loads\nimport confluent_kafka\nfrom copy import deepcopy\nimport datetime\nimport fastavro\nimport gzip\nimport io\nfrom matplotlib.colors import LogNorm\nimport matplotlib.pyplot as plt\nimport multiprocessing\nimport numpy as np\nimport os\nimport pandas as pd\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport subprocess\nimport sys\nfrom tensorflow.keras.models import load_model\nimport time\nimport traceback\n\nfrom utils import (\n datetime_to_jd,\n deg2dms,\n deg2hms,\n great_circle_distance,\n in_ellipse,\n load_config,\n Mongo,\n radec2lb,\n time_stamp,\n)\n\n\n''' load config and secrets '''\nconfig = load_config(config_file='config.yaml')['kowalski']\n\n\nDEFAULT_TIMEOUT = 5 # seconds\n\n\nclass TimeoutHTTPAdapter(HTTPAdapter):\n def __init__(self, *args, **kwargs):\n self.timeout = DEFAULT_TIMEOUT\n if \"timeout\" in kwargs:\n self.timeout = kwargs[\"timeout\"]\n del kwargs[\"timeout\"]\n super().__init__(*args, **kwargs)\n\n def send(self, request, **kwargs):\n timeout = kwargs.get(\"timeout\")\n if timeout is None:\n kwargs[\"timeout\"] = self.timeout\n return super().send(request, **kwargs)\n\n\ndef read_schema_data(bytes_io):\n \"\"\"Read data that already has an Avro schema.\n\n Parameters\n ----------\n bytes_io : `_io.BytesIO`\n Data to be decoded.\n\n Returns\n -------\n `dict`\n Decoded data.\n \"\"\"\n bytes_io.seek(0)\n message = fastavro.reader(bytes_io)\n return message\n\n\nclass EopError(Exception):\n \"\"\"\n Exception raised when reaching end of partition.\n\n Parameters\n ----------\n msg : Kafka message\n The Kafka message result from consumer.poll().\n \"\"\"\n def __init__(self, msg):\n message = f'{time_stamp()}: topic:{msg.topic()}, partition:{msg.partition()}, '\\\n f'status:end, offset:{msg.offset()}, key:{str(msg.key())}\\n'\n self.message = message\n\n def __str__(self):\n return self.message\n\n\ndef log(message):\n print(f\"{time_stamp()}: {message}\")\n\n\ndef make_photometry(alert: dict, jd_start: float = None):\n \"\"\"Make a de-duplicated pandas.DataFrame with photometry of alert['objectId']\n\n :param alert: ZTF alert packet/dict\n :param jd_start:\n :return:\n \"\"\"\n alert = deepcopy(alert)\n df_candidate = pd.DataFrame(alert['candidate'], index=[0])\n\n df_prv_candidates = pd.DataFrame(alert['prv_candidates'])\n df_light_curve = pd.concat(\n [df_candidate, df_prv_candidates],\n ignore_index=True,\n sort=False\n )\n\n ztf_filters = {1: 'ztfg', 2: 'ztfr', 3: 'ztfi'}\n df_light_curve['ztf_filter'] = df_light_curve['fid'].apply(lambda x: ztf_filters[x])\n df_light_curve['magsys'] = \"ab\"\n df_light_curve['mjd'] = df_light_curve['jd'] - 2400000.5\n\n df_light_curve['mjd'] = df_light_curve['mjd'].apply(lambda x: np.float64(x))\n df_light_curve['magpsf'] = df_light_curve['magpsf'].apply(lambda x: np.float32(x))\n df_light_curve['sigmapsf'] = df_light_curve['sigmapsf'].apply(lambda x: np.float32(x))\n\n df_light_curve = (\n df_light_curve\n .drop_duplicates(subset=[\"mjd\", \"magpsf\"])\n .reset_index(drop=True)\n .sort_values(by=['mjd'])\n )\n\n # filter out bad data:\n mask_good_diffmaglim = df_light_curve[\"diffmaglim\"] > 0\n df_light_curve = df_light_curve.loc[mask_good_diffmaglim]\n\n # only \"new\" photometry requested?\n if jd_start is not None:\n w_after_jd = df_light_curve['jd'] > jd_start\n df_light_curve = df_light_curve.loc[w_after_jd]\n\n return df_light_curve\n\n\ndef make_thumbnail(alert, ttype: str, ztftype: str):\n \"\"\"Convert lossless FITS cutouts from ZTF alerts into PNGs\n\n :param alert: ZTF alert packet/dict\n :param ttype: \n :param ztftype: \n :return:\n \"\"\"\n alert = deepcopy(alert)\n\n cutout_data = alert[f'cutout{ztftype}']['stampData']\n with gzip.open(io.BytesIO(cutout_data), 'rb') as f:\n with fits.open(io.BytesIO(f.read())) as hdu:\n header = hdu[0].header\n data_flipped_y = np.flipud(hdu[0].data)\n # fixme: png, switch to fits eventually\n buff = io.BytesIO()\n plt.close('all')\n fig = plt.figure()\n fig.set_size_inches(4, 4, forward=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n\n # remove nans:\n img = np.array(data_flipped_y)\n img = np.nan_to_num(img)\n\n if ztftype != 'Difference':\n img[img <= 0] = np.median(img)\n plt.imshow(img, cmap=\"bone\", norm=LogNorm(), origin='lower')\n else:\n plt.imshow(img, cmap=\"bone\", origin='lower')\n plt.savefig(buff, dpi=42)\n\n buff.seek(0)\n plt.close('all')\n\n thumb = {\n \"obj_id\": alert[\"objectId\"],\n \"data\": base64.b64encode(buff.read()).decode(\"utf-8\"),\n \"ttype\": ttype,\n }\n\n return thumb\n\n\n''' Alert filters '''\n\n\ndef make_triplet(alert, to_tpu: bool = False):\n \"\"\"Make an L2-normalized cutout triplet out of a ZTF alert\n\n :param alert:\n :param to_tpu:\n :return:\n \"\"\"\n cutout_dict = dict()\n\n for cutout in ('science', 'template', 'difference'):\n cutout_data = alert[f'cutout{cutout.capitalize()}']['stampData']\n\n # unzip\n with gzip.open(io.BytesIO(cutout_data), 'rb') as f:\n with fits.open(io.BytesIO(f.read())) as hdu:\n data = hdu[0].data\n # replace nans with zeros\n cutout_dict[cutout] = np.nan_to_num(data)\n # L2-normalize\n cutout_dict[cutout] /= np.linalg.norm(cutout_dict[cutout])\n\n # pad to 63x63 if smaller\n shape = cutout_dict[cutout].shape\n if shape != (63, 63):\n # print(f'Shape of {candid}/{cutout}: {shape}, padding to (63, 63)')\n cutout_dict[cutout] = np.pad(cutout_dict[cutout], [(0, 63 - shape[0]), (0, 63 - shape[1])],\n mode='constant', constant_values=1e-9)\n\n triplet = np.zeros((63, 63, 3))\n triplet[:, :, 0] = cutout_dict['science']\n triplet[:, :, 1] = cutout_dict['template']\n triplet[:, :, 2] = cutout_dict['difference']\n\n if to_tpu:\n # Edge TPUs require additional processing\n triplet = np.rint(triplet * 128 + 128).astype(np.uint8).flatten()\n\n return triplet\n\n\ndef alert_filter__ml(alert, ml_models: dict = None) -> dict:\n \"\"\"Execute ML models on ZTF alerts\n\n :param alert:\n :param ml_models:\n :return:\n \"\"\"\n\n scores = dict()\n\n try:\n ''' braai '''\n triplet = make_triplet(alert)\n triplets = np.expand_dims(triplet, axis=0)\n braai = ml_models['braai']['model'].predict(x=triplets)[0]\n # braai = 1.0\n scores['braai'] = float(braai)\n scores['braai_version'] = ml_models['braai']['version']\n except Exception as e:\n print(time_stamp(), str(e))\n\n return scores\n\n\n# cone search radius:\ncone_search_radius = float(config['database']['xmatch']['cone_search_radius'])\n# convert to rad:\nif config['database']['xmatch']['cone_search_unit'] == 'arcsec':\n cone_search_radius *= np.pi / 180.0 / 3600.\nelif config['database']['xmatch']['cone_search_unit'] == 'arcmin':\n cone_search_radius *= np.pi / 180.0 / 60.\nelif config['database']['xmatch']['cone_search_unit'] == 'deg':\n cone_search_radius *= np.pi / 180.0\nelif config['database']['xmatch']['cone_search_unit'] == 'rad':\n cone_search_radius *= 1\nelse:\n raise Exception('Unknown cone search unit. Must be in [deg, rad, arcsec, arcmin]')\n\n\ndef alert_filter__xmatch(database, alert) -> dict:\n \"\"\"\n Cross-match alerts\n \"\"\"\n\n xmatches = dict()\n\n try:\n ra_geojson = float(alert['candidate']['ra'])\n # geojson-friendly ra:\n ra_geojson -= 180.0\n dec_geojson = float(alert['candidate']['dec'])\n\n ''' catalogs '''\n for catalog in config['database']['xmatch']['catalogs']:\n catalog_filter = config['database']['xmatch']['catalogs'][catalog]['filter']\n catalog_projection = config['database']['xmatch']['catalogs'][catalog]['projection']\n\n object_position_query = dict()\n object_position_query['coordinates.radec_geojson'] = {\n '$geoWithin': {'$centerSphere': [[ra_geojson, dec_geojson], cone_search_radius]}}\n s = database[catalog].find(\n {**object_position_query, **catalog_filter},\n {**catalog_projection}\n )\n xmatches[catalog] = list(s)\n\n except Exception as e:\n print(time_stamp(), str(e))\n\n return xmatches\n\n\n# cone search radius in deg:\ncone_search_radius_clu = 3.0\n# convert deg to rad:\ncone_search_radius_clu *= np.pi / 180.0\n\n\ndef alert_filter__xmatch_clu(database, alert, size_margin=3, clu_version='CLU_20190625') -> dict:\n \"\"\"\n Filter to apply to each alert: cross-match with the CLU catalog\n\n :param database:\n :param alert:\n :param size_margin: multiply galaxy size by this much before looking for a match\n :param clu_version: CLU catalog version\n :return:\n \"\"\"\n\n xmatches = dict()\n\n try:\n ra = float(alert['candidate']['ra'])\n dec = float(alert['candidate']['dec'])\n\n # geojson-friendly ra:\n ra_geojson = float(alert['candidate']['ra']) - 180.0\n dec_geojson = dec\n\n catalog_filter = {}\n catalog_projection = {\n \"_id\": 1, \"name\": 1, \"ra\": 1, \"dec\": 1,\n \"a\": 1, \"b2a\": 1, \"pa\": 1, \"z\": 1,\n \"sfr_fuv\": 1, \"mstar\": 1, \"sfr_ha\": 1,\n \"coordinates.radec_str\": 1\n }\n\n # first do a coarse search of everything that is around\n object_position_query = dict()\n object_position_query['coordinates.radec_geojson'] = {\n '$geoWithin': {'$centerSphere': [[ra_geojson, dec_geojson], cone_search_radius_clu]}\n }\n galaxies = list(\n database[clu_version].find(\n {**object_position_query, **catalog_filter},\n {**catalog_projection}\n )\n )\n\n # these guys are very big, so check them separately\n M31 = {\n '_id': 596900, 'name': 'PGC2557',\n 'ra': 10.6847, 'dec': 41.26901, 'a': 6.35156, 'b2a': 0.32, 'pa': 35.0,\n 'z': -0.00100100006, 'sfr_fuv': None, 'mstar': 253816876.412914, 'sfr_ha': 0,\n 'coordinates': {'radec_str': [\"00:42:44.3503\", \"41:16:08.634\"]}\n }\n M33 = {\n '_id': 597543, 'name': 'PGC5818',\n 'ra': 23.46204, 'dec': 30.66022, 'a': 2.35983, 'b2a': 0.59, 'pa': 23.0,\n 'z': -0.000597000006, 'sfr_fuv': None, 'mstar': 4502777.420493, 'sfr_ha': 0,\n 'coordinates': {'radec_str': [\"01:33:50.8900\", \"30:39:36.800\"]}\n }\n\n # do elliptical matches\n matches = []\n\n for galaxy in galaxies + [M31, M33]:\n alpha1, delta01 = galaxy['ra'], galaxy['dec']\n d0, axis_ratio, PA0 = galaxy['a'], galaxy['b2a'], galaxy['pa']\n\n # no shape info for galaxy? replace with median values\n if d0 < -990:\n d0 = 0.0265889\n if axis_ratio < -990:\n axis_ratio = 0.61\n if PA0 < -990:\n PA0 = 86.0\n\n in_galaxy = in_ellipse(ra, dec, alpha1, delta01, size_margin * d0, axis_ratio, PA0)\n\n if in_galaxy:\n match = galaxy\n distance_arcsec = round(great_circle_distance(ra, dec, alpha1, delta01) * 3600, 2)\n match['coordinates']['distance_arcsec'] = distance_arcsec\n matches.append(match)\n\n xmatches[clu_version] = matches\n\n except Exception as e:\n print(time_stamp(), str(e))\n\n return xmatches\n\n\ndef alert_filter__user_defined(\n database, filter_templates, alert, catalog: str = 'ZTF_alerts', max_time_ms: int = 500\n) -> list:\n \"\"\"\n Evaluate user-defined filters\n :param database:\n :param filter_templates:\n :param alert:\n :param catalog:\n :param max_time_ms:\n :return:\n \"\"\"\n passed_filters = []\n\n for filter_template in filter_templates:\n try:\n _filter = deepcopy(filter_template)\n # match candid\n _filter['pipeline'][0][\"$match\"][\"candid\"] = alert['candid']\n\n filtered_data = list(\n database[catalog].aggregate(\n _filter['pipeline'],\n allowDiskUse=False,\n maxTimeMS=max_time_ms\n )\n )\n # passed filter? then len(passed_filter) must be = 1\n if len(filtered_data) == 1:\n log(f'{alert[\"objectId\"]} {alert[\"candid\"]} passed filter {_filter[\"fid\"]}')\n passed_filters.append(\n {\n 'group_id': _filter[\"group_id\"],\n 'filter_id': _filter[\"filter_id\"],\n 'group_name': _filter[\"group_name\"],\n 'filter_name': _filter[\"filter_name\"],\n 'fid': _filter['fid'],\n 'permissions': _filter['permissions'],\n 'data': filtered_data[0]\n }\n )\n\n except Exception as e:\n print(f'{time_stamp()}: filter {filter_template[\"fid\"]} execution failed on alert {alert[\"candid\"]}: {e}')\n continue\n\n return passed_filters\n\n\nclass AlertConsumer(object):\n \"\"\"\n Creates an alert stream Kafka consumer for a given topic.\n\n Parameters\n ----------\n topic : `str`\n Name of the topic to subscribe to.\n schema_files : Avro schema files\n The reader Avro schema files for decoding data. Optional.\n **kwargs\n Keyword arguments for configuring confluent_kafka.Consumer().\n \"\"\"\n\n def __init__(self, topic, **kwargs):\n\n self.verbose = kwargs.get(\"verbose\", 2)\n\n # keep track of disconnected partitions\n self.num_disconnected_partitions = 0\n self.topic = topic\n\n def error_cb(err, _self=self):\n log(f'error_cb --------> {err}')\n # print(err.code())\n if err.code() == -195:\n _self.num_disconnected_partitions += 1\n if _self.num_disconnected_partitions == _self.num_partitions:\n log(f'All partitions got disconnected, killing thread')\n sys.exit()\n else:\n log(f'{_self.topic}: disconnected from partition. total: {_self.num_disconnected_partitions}')\n\n # 'error_cb': error_cb\n kwargs['error_cb'] = error_cb\n\n self.consumer = confluent_kafka.Consumer(**kwargs)\n self.num_partitions = 0\n\n def on_assign(consumer, partitions, _self=self):\n # force-reset offsets when subscribing to a topic:\n for part in partitions:\n # -2 stands for beginning and -1 for end\n part.offset = -2\n # keep number of partitions.\n # when reaching end of last partition, kill thread and start from beginning\n _self.num_partitions += 1\n log(consumer.get_watermark_offsets(part))\n\n self.consumer.subscribe([topic], on_assign=on_assign)\n\n self.config = config\n\n # MongoDB collections to store the alerts:\n self.collection_alerts = self.config['database']['collections']['alerts_ztf']\n self.collection_alerts_aux = self.config['database']['collections']['alerts_ztf_aux']\n self.collection_alerts_filter = self.config['database']['collections']['alerts_ztf_filter']\n\n self.mongo = Mongo(\n host=config['database']['host'],\n port=config['database']['port'],\n username=config['database']['username'],\n password=config['database']['password'],\n db=config['database']['db'],\n verbose=self.verbose\n )\n\n # create indexes\n if self.config[\"database\"][\"build_indexes\"]:\n for index_name, index in self.config['database']['indexes'][self.collection_alerts].items():\n ind = [tuple(ii) for ii in index]\n self.mongo.db[self.collection_alerts].create_index(\n keys=ind, name=index_name, background=True\n )\n\n # ML models:\n self.ml_models = dict()\n for model in config['ml_models']:\n try:\n model_version = config[\"ml_models\"][model][\"version\"]\n # todo: allow other formats such as SavedModel\n model_filepath = os.path.join(config[\"path\"][\"ml_models\"], f'{model}_{model_version}.h5')\n self.ml_models[model] = {'model': load_model(model_filepath), 'version': model_version}\n except Exception as e:\n log(f\"Error loading ML model {model}: {str(e)}\")\n _err = traceback.format_exc()\n log(_err)\n continue\n\n # talking to SkyPortal?\n if config['misc']['broker']:\n # session to talk to SkyPortal\n self.session = requests.Session()\n self.session_headers = {'Authorization': f\"token {config['skyportal']['token']}\"}\n\n retries = Retry(\n total=3,\n backoff_factor=1,\n status_forcelist=[405, 429, 500, 502, 503, 504],\n method_whitelist=[\"HEAD\", \"GET\", \"PUT\", \"POST\", \"PATCH\"]\n )\n adapter = TimeoutHTTPAdapter(timeout=5, max_retries=retries)\n self.session.mount(\"https://\", adapter)\n self.session.mount(\"http://\", adapter)\n\n # get ZTF instrument id\n self.instrument_id = 1\n try:\n tic = time.time()\n response = self.api_skyportal(\"GET\", \"/api/instrument\", {\"name\": \"ZTF\"})\n toc = time.time()\n if self.verbose > 1:\n log(f\"Getting ZTF instrument_id from SkyPortal took {toc - tic} s\")\n if response.json()['status'] == 'success' and len(response.json()[\"data\"]) > 0:\n self.instrument_id = response.json()[\"data\"][0][\"id\"]\n log(f\"Got ZTF instrument_id from SkyPortal: {self.instrument_id}\")\n else:\n log(\"Failed to get ZTF instrument_id from SkyPortal\")\n raise ValueError(\"Failed to get ZTF instrument_id from SkyPortal\")\n except Exception as e:\n log(e)\n # config['misc']['broker'] = False\n\n # filter pipeline upstream: select current alert, ditch cutouts, and merge with aux data\n # including archival photometry and cross-matches:\n self.filter_pipeline_upstream = config['database']['filters'][self.collection_alerts]\n log('Upstream filtering pipeline:')\n log(self.filter_pipeline_upstream)\n\n # load *active* user-defined alert filter templates\n active_filters = list(\n self.mongo.db[config['database']['collections']['filters']].aggregate(\n [\n {\n '$match': {\n 'catalog': 'ZTF_alerts',\n 'active': True\n }\n },\n {\n '$project': {\n 'group_id': 1,\n 'filter_id': 1,\n 'permissions': 1,\n 'fv': {\n '$arrayElemAt': [\n {\n '$filter': {\n 'input': '$fv',\n 'as': 'fvv',\n 'cond': {\n '$eq': [\n '$$fvv.fid', '$active_fid'\n ]\n }\n }\n }, 0\n ]\n }\n }\n }\n ]\n )\n )\n\n # todo: query SP to make sure the filters still exist there and we're not out of sync;\n # clean up if necessary\n\n self.filter_templates = []\n for active_filter in active_filters:\n # collect additional info from SkyPortal\n tic = time.time()\n response = self.api_skyportal(\"GET\", f\"/api/groups/{active_filter['group_id']}\")\n toc = time.time()\n if self.verbose > 1:\n log(f\"Getting info on group id={active_filter['group_id']} from SkyPortal took {toc - tic} s\")\n log(response.json())\n if response.json()['status'] == 'success':\n group_name = (\n response.json()[\"data\"][\"nickname\"]\n if response.json()[\"data\"][\"nickname\"] is not None\n else response.json()[\"data\"][\"name\"]\n )\n filter_name = [\n f[\"name\"] for f in response.json()[\"data\"][\"filters\"] if f[\"id\"] == active_filter['filter_id']\n ][0]\n else:\n log(f\"Failed to get info on group id={active_filter['group_id']} from SkyPortal\")\n group_name, filter_name = None, None\n # raise ValueError(f\"Failed to get info on group id={active_filter['group_id']} from SkyPortal\")\n log(f\"Group name: {group_name}, filter name: {filter_name}\")\n\n # prepend upstream aggregation stages:\n pipeline = self.filter_pipeline_upstream + loads(active_filter['fv']['pipeline'])\n # match permissions\n pipeline[0][\"$match\"][\"candidate.programid\"][\"$in\"] = active_filter['permissions']\n pipeline[3][\"$project\"][\"prv_candidates\"][\"$filter\"][\"cond\"][\"$and\"][0][\"$in\"][1] = active_filter['permissions']\n\n filter_template = {\n 'group_id': active_filter['group_id'],\n 'filter_id': active_filter['filter_id'],\n 'group_name': group_name,\n 'filter_name': filter_name,\n 'fid': active_filter['fv']['fid'],\n 'permissions': active_filter['permissions'],\n 'pipeline': pipeline\n }\n\n self.filter_templates.append(filter_template)\n\n log('Science filters:')\n log(self.filter_templates)\n\n def api_skyportal(self, method: str, endpoint: str, data=None):\n \"\"\"Make an API call to a SkyPortal instance\n\n :param method:\n :param endpoint:\n :param data:\n :return:\n \"\"\"\n method = method.lower()\n methods = {\n 'head': self.session.head,\n 'get': self.session.get,\n 'post': self.session.post,\n 'put': self.session.put,\n 'patch': self.session.patch,\n 'delete': self.session.delete\n }\n\n if endpoint is None:\n raise ValueError('Endpoint not specified')\n if method not in ['head', 'get', 'post', 'put', 'patch', 'delete']:\n raise ValueError(f'Unsupported method: {method}')\n\n if method == 'get':\n response = methods[method](\n f\"{config['skyportal']['protocol']}://\"\n f\"{config['skyportal']['host']}:{config['skyportal']['port']}\"\n f\"{endpoint}\",\n params=data,\n headers=self.session_headers\n )\n else:\n response = methods[method.lower()](\n f\"{config['skyportal']['protocol']}://\"\n f\"{config['skyportal']['host']}:{config['skyportal']['port']}\"\n f\"{endpoint}\",\n json=data,\n headers=self.session_headers\n )\n\n return response\n\n @staticmethod\n def alert_mongify(alert):\n\n doc = dict(alert)\n\n # let mongo create a unique _id\n\n # placeholders for classifications\n doc['classifications'] = dict()\n\n # GeoJSON for 2D indexing\n doc['coordinates'] = {}\n _ra = doc['candidate']['ra']\n _dec = doc['candidate']['dec']\n # string format: H:M:S, D:M:S\n _radec_str = [deg2hms(_ra), deg2dms(_dec)]\n doc['coordinates']['radec_str'] = _radec_str\n # for GeoJSON, must be lon:[-180, 180], lat:[-90, 90] (i.e. in deg)\n _radec_geojson = [_ra - 180.0, _dec]\n doc['coordinates']['radec_geojson'] = {'type': 'Point',\n 'coordinates': _radec_geojson}\n\n # Galactic coordinates l and b\n l, b = radec2lb(doc['candidate']['ra'], doc['candidate']['dec'])\n doc['coordinates']['l'] = l\n doc['coordinates']['b'] = b\n\n prv_candidates = deepcopy(doc['prv_candidates'])\n doc.pop('prv_candidates', None)\n if prv_candidates is None:\n prv_candidates = []\n\n return doc, prv_candidates\n\n def alert_post_candidate(self, alert, filter_ids):\n # post metadata with all filter_ids in single call to /api/candidates\n alert_thin = {\n \"id\": alert['objectId'],\n \"ra\": alert['candidate'].get('ra'),\n \"dec\": alert['candidate'].get('dec'),\n \"score\": alert['candidate'].get('drb', alert['candidate']['rb']),\n \"filter_ids\": filter_ids,\n \"passing_alert_id\": alert[\"candid\"],\n \"passed_at\": datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n }\n if self.verbose > 1:\n log(alert_thin)\n\n tic = time.time()\n response = self.api_skyportal(\"POST\", f\"/api/candidates\", alert_thin)\n toc = time.time()\n if self.verbose > 1:\n log(f\"Posting metadata to SkyPortal took {toc - tic} s\")\n if response.json()['status'] == 'success':\n log(f\"Posted {alert['objectId']} {alert['candid']} metadata to SkyPortal\")\n else:\n log(f\"Failed to post {alert['objectId']} {alert['candid']} metadata to SkyPortal\")\n log(response.json())\n\n def alert_post_annotations(self, alert, passed_filters):\n for passed_filter in passed_filters:\n annotations = {\n \"obj_id\": alert[\"objectId\"],\n \"origin\": f\"{passed_filter.get('group_name')}:{passed_filter.get('filter_name')}\",\n \"data\": passed_filter.get('data', dict()).get('annotations', dict()),\n \"group_ids\": [passed_filter.get(\"group_id\")]\n }\n tic = time.time()\n response = self.api_skyportal(\"POST\", f\"/api/annotation\", annotations)\n toc = time.time()\n if self.verbose > 1:\n log(f\"Posting annotation for {alert['objectId']} to skyportal took {toc - tic} s\")\n if response.json()['status'] == 'success':\n log(f\"Posted {alert['objectId']} annotation to SkyPortal\")\n else:\n log(f\"Failed to post {alert['objectId']} annotation to SkyPortal\")\n log(response.json())\n\n def alert_post_thumbnails(self, alert):\n for ttype, ztftype in [('new', 'Science'), ('ref', 'Template'), ('sub', 'Difference')]:\n tic = time.time()\n thumb = make_thumbnail(alert, ttype, ztftype)\n toc = time.time()\n if self.verbose > 1:\n log(f\"Making {ztftype} thumbnail took {toc - tic} s\")\n\n tic = time.time()\n response = self.api_skyportal(\"POST\", f\"/api/thumbnail\", thumb)\n toc = time.time()\n if self.verbose > 1:\n log(f\"Posting {ztftype} thumbnail to SkyPortal took {toc - tic} s\")\n\n if response.json()['status'] == 'success':\n log(f\"Posted {alert['objectId']} {alert['candid']} {ztftype} cutout to SkyPortal\")\n else:\n log(f\"Failed to post {alert['objectId']} {alert['candid']} {ztftype} cutout to SkyPortal\")\n log(response.json())\n\n def alert_put_photometry(self, alert, groups):\n \"\"\"PUT photometry to SkyPortal\n\n :param alert:\n :param groups: array of dicts containing at least\n [{\"group_id\": , \"permissions\": }]\n :return:\n \"\"\"\n tic = time.time()\n df_photometry = make_photometry(alert)\n toc = time.time()\n if self.verbose > 1:\n log(f\"Making alert photometry took {toc - tic} s\")\n\n # post data from different program_id's\n for pid in set(df_photometry.programid.unique()):\n group_ids = [f.get(\"group_id\") for f in groups if pid in f.get(\"permissions\", [1])]\n\n if len(group_ids) > 0:\n pid_mask = df_photometry.programid == int(pid)\n\n photometry = {\n \"obj_id\": alert['objectId'],\n \"group_ids\": group_ids,\n \"instrument_id\": self.instrument_id,\n \"mjd\": df_photometry.loc[pid_mask, \"mjd\"].tolist(),\n \"mag\": df_photometry.loc[pid_mask, \"magpsf\"].tolist(),\n \"magerr\": df_photometry.loc[pid_mask, \"sigmapsf\"].tolist(),\n \"limiting_mag\": df_photometry.loc[pid_mask, \"diffmaglim\"].tolist(),\n \"magsys\": df_photometry.loc[pid_mask, \"magsys\"].tolist(),\n \"filter\": df_photometry.loc[pid_mask, \"ztf_filter\"].tolist(),\n \"ra\": df_photometry.loc[pid_mask, \"ra\"].tolist(),\n \"dec\": df_photometry.loc[pid_mask, \"dec\"].tolist(),\n }\n\n if len(photometry.get('mag', ())) > 0:\n tic = time.time()\n response = self.api_skyportal(\"PUT\", f\"/api/photometry\", photometry)\n toc = time.time()\n if self.verbose > 1:\n log(\n f\"Posting photometry of {alert['objectId']} {alert['candid']}, \"\n f\"program_id={pid} to SkyPortal took {toc - tic} s\"\n )\n if response.json()['status'] == 'success':\n log(f\"Posted {alert['objectId']} program_id={pid} photometry to SkyPortal\")\n else:\n log(f\"Failed to post {alert['objectId']} program_id={pid} photometry to SkyPortal\")\n log(response.json())\n\n def alert_sentinel_skyportal(self, alert, prv_candidates, passed_filters):\n \"\"\"\n Post alerts to SkyPortal, if need be.\n\n Logic:\n - check if candidate/source exist on SP\n - if candidate does not exist:\n - if len(passed_filters) > 0\n - post metadata with all filter_ids in single call to /api/candidates\n - post full light curve with all group_ids in single call to /api/photometry\n - post thumbnails\n - if candidate exists:\n - get filter_ids of saved candidate from SP\n - post to /api/candidates with new_filter_ids, if any\n - post alert curve with group_ids of corresponding filters in single call to /api/photometry\n - if source exists:\n - get groups and check stream access\n - decide which points to post to what groups based on permissions\n - post alert curve with all group_ids in single call to /api/photometry\n\n :param alert: ZTF_alert with a stripped-off prv_candidates section\n :param prv_candidates: could be plain prv_candidates section of an alert, or extended alert history\n :param passed_filters: list of filters that alert passed, with their output\n :return:\n \"\"\"\n # check if candidate/source exist in SP:\n tic = time.time()\n response = self.api_skyportal(\"HEAD\", f\"/api/candidates/{alert['objectId']}\")\n toc = time.time()\n is_candidate = response.status_code == 200\n if self.verbose > 1:\n log(f\"Checking if object is Candidate took {toc - tic} s\")\n log(f\"{alert['objectId']} {'is' if is_candidate else 'is not'} Candidate in SkyPortal\")\n tic = time.time()\n response = self.api_skyportal(\"HEAD\", f\"/api/sources/{alert['objectId']}\")\n toc = time.time()\n is_source = response.status_code == 200\n if self.verbose > 1:\n log(f\"Checking if object is Source took {toc - tic} s\")\n log(f\"{alert['objectId']} {'is' if is_source else 'is not'} Source in SkyPortal\")\n\n # obj does not exit in SP:\n if (not is_candidate) and (not is_source):\n # passed any filters?\n if len(passed_filters) > 0:\n # post candidate\n filter_ids = [f.get(\"filter_id\") for f in passed_filters]\n self.alert_post_candidate(alert, filter_ids)\n\n # post annotations\n self.alert_post_annotations(alert, passed_filters)\n\n # post full light curve\n try:\n alert['prv_candidates'] = list(self.mongo.db[self.collection_alerts_aux].find(\n {'_id': alert[\"objectId\"]},\n {\"prv_candidates\": 1},\n limit=1\n ))[0][\"prv_candidates\"]\n except Exception as e:\n # this should never happen, but just in case\n log(e)\n alert['prv_candidates'] = prv_candidates\n\n self.alert_put_photometry(alert, passed_filters)\n\n # post thumbnails\n self.alert_post_thumbnails(alert)\n\n # obj exists in SP:\n else:\n if len(passed_filters) > 0:\n filter_ids = [f.get(\"filter_id\") for f in passed_filters]\n # already posted as a candidate?\n if is_candidate:\n # get filter_ids of saved candidate from SP\n tic = time.time()\n response = self.api_skyportal(\"GET\", f\"/api/candidates/{alert['objectId']}\")\n toc = time.time()\n if self.verbose > 1:\n log(f\"Getting candidate info on {alert['objectId']} took {toc - tic} s\")\n if response.json()['status'] == 'success':\n existing_filter_ids = response.json()['data'][\"filter_ids\"]\n filter_ids = list(set(filter_ids) - set(existing_filter_ids))\n else:\n log(f\"Failed to get candidate info on {alert['objectId']}\")\n\n if len(filter_ids) > 0:\n # post candidate with new filter ids\n self.alert_post_candidate(alert, filter_ids)\n\n # post annotations\n self.alert_post_annotations(\n alert,\n [pf for pf in passed_filters if pf.get(\"filter_id\") in filter_ids]\n )\n\n groups = passed_filters\n group_ids = [f.get(\"group_id\") for f in passed_filters]\n # already saved as a source?\n if is_source:\n # get info on the corresponding groups:\n tic = time.time()\n response = self.api_skyportal(\"GET\", f\"/api/sources/{alert['objectId']}\")\n toc = time.time()\n if self.verbose > 1:\n log(f\"Getting source info on {alert['objectId']} took {toc - tic} s\")\n if response.json()['status'] == 'success':\n existing_group_ids = [g[\"id\"] for g in response.json()['data'][\"groups\"]]\n for group_id in set(existing_group_ids) - set(group_ids):\n tic = time.time()\n response = self.api_skyportal(\"GET\", f\"/api/groups/{group_id}\")\n toc = time.time()\n if self.verbose > 1:\n log(f\"Getting info on group id={group_id} from SkyPortal took {toc - tic} s\")\n log(response.json())\n if response.json()['status'] == 'success':\n selector = {1}\n for stream in response.json()['data'][\"streams\"]:\n if \"ztf\" in stream[\"name\"].lower():\n selector.update(set(stream[\"altdata\"].get(\"selector\", [])))\n\n selector = list(selector)\n\n groups.append(\n {\n \"group_id\": group_id,\n \"permissions\": selector\n }\n )\n else:\n log(f\"Failed to get info on group id={group_id} from SkyPortal\")\n else:\n log(f\"Failed to get source info on {alert['objectId']}\")\n\n # post alert photometry with all group_ids in single call to /api/photometry\n alert['prv_candidates'] = prv_candidates\n\n self.alert_put_photometry(alert, groups)\n\n def poll(self, verbose=2):\n \"\"\"\n Polls Kafka broker to consume topic.\n\n :param verbose: 1 - main, 2 - debug\n :return:\n \"\"\"\n msg = self.consumer.poll()\n\n if msg is None:\n print(time_stamp(), 'Caught error: msg is None')\n\n if msg.error():\n print(time_stamp(), 'Caught error:', msg.error())\n raise EopError(msg)\n\n elif msg is not None:\n try:\n # decode avro packet\n msg_decoded = self.decode_message(msg)\n for record in msg_decoded:\n\n candid = record['candid']\n objectId = record['objectId']\n\n log(f\"{self.topic} {objectId} {candid}\")\n\n # check that candid not in collection_alerts\n if self.mongo.db[self.collection_alerts].count_documents({'candid': candid}, limit=1) == 0:\n # candid not in db, ingest decoded avro packet into db\n # todo: ?? restructure alerts even further?\n # move cutouts to ZTF_alerts_cutouts? reduce the main db size for performance\n # group by objectId similar to prv_candidates?? maybe this is too much\n tic = time.time()\n alert, prv_candidates = self.alert_mongify(record)\n toc = time.time()\n if verbose > 1:\n print(f'{time_stamp()}: mongification took {toc - tic} s')\n\n # ML models:\n tic = time.time()\n scores = alert_filter__ml(record, ml_models=self.ml_models)\n alert['classifications'] = scores\n toc = time.time()\n if verbose > 1:\n print(f'{time_stamp()}: mling took {toc - tic} s')\n\n print(f'{time_stamp()}: ingesting {alert[\"candid\"]} into db')\n tic = time.time()\n self.mongo.insert_one(collection=self.collection_alerts, document=alert)\n toc = time.time()\n if verbose > 1:\n print(f'{time_stamp()}: ingesting {alert[\"candid\"]} took {toc - tic} s')\n\n # prv_candidates: pop nulls - save space\n prv_candidates = [\n {kk: vv for kk, vv in prv_candidate.items() if vv is not None}\n for prv_candidate in prv_candidates\n ]\n\n # cross-match with external catalogs if objectId not in collection_alerts_aux:\n if self.mongo.db[self.collection_alerts_aux].count_documents({'_id': objectId}, limit=1) == 0:\n tic = time.time()\n xmatches = alert_filter__xmatch(self.mongo.db, alert)\n toc = time.time()\n if verbose > 1:\n log(f\"Xmatch took {toc - tic} s\")\n # CLU cross-match:\n tic = time.time()\n xmatches = {**xmatches, **alert_filter__xmatch_clu(self.mongo.db, alert)}\n toc = time.time()\n if verbose > 1:\n log(f\"CLU xmatch took {toc - tic} s\")\n\n alert_aux = {\n '_id': objectId,\n 'cross_matches': xmatches,\n 'prv_candidates': prv_candidates\n }\n\n tic = time.time()\n self.mongo.insert_one(collection=self.collection_alerts_aux, document=alert_aux)\n toc = time.time()\n if verbose > 1:\n print(f'{time_stamp()}: aux ingesting took {toc - tic} s')\n\n else:\n tic = time.time()\n self.mongo.db[self.collection_alerts_aux].update_one(\n {'_id': objectId},\n {'$addToSet': {'prv_candidates': {'$each': prv_candidates}}},\n upsert=True\n )\n toc = time.time()\n if verbose > 1:\n print(f'{time_stamp()}: aux updating took {toc - tic} s')\n\n if config['misc']['broker']:\n # execute user-defined alert filters\n tic = time.time()\n passed_filters = alert_filter__user_defined(self.mongo.db, self.filter_templates, alert)\n toc = time.time()\n if verbose > 1:\n log(f\"Filtering took {toc-tic} s\")\n\n # post to SkyPortal\n self.alert_sentinel_skyportal(alert, prv_candidates, passed_filters)\n\n except Exception as e:\n log(e)\n _err = traceback.format_exc()\n log(_err)\n\n @staticmethod\n def decode_message(msg):\n \"\"\"Decode Avro message according to a schema.\n\n Parameters\n ----------\n msg : Kafka message\n The Kafka message result from consumer.poll().\n\n Returns\n -------\n `dict`\n Decoded message.\n \"\"\"\n # print(msg.topic(), msg.offset(), msg.error(), msg.key(), msg.value())\n message = msg.value()\n decoded_msg = message\n\n try:\n bytes_io = io.BytesIO(message)\n decoded_msg = read_schema_data(bytes_io)\n except AssertionError:\n decoded_msg = None\n except IndexError:\n literal_msg = literal_eval(str(message, encoding='utf-8')) # works to give bytes\n bytes_io = io.BytesIO(literal_msg) # works to give \n decoded_msg = read_schema_data(bytes_io) # yields reader\n except Exception:\n decoded_msg = message\n finally:\n return decoded_msg\n\n\ndef listener(topic, bootstrap_servers='', offset_reset='earliest', group=None, test=False):\n \"\"\"\n Listen to a topic\n :param topic:\n :param bootstrap_servers:\n :param offset_reset:\n :param group:\n :param test: when testing, terminate once reached end of partition\n :return:\n \"\"\"\n\n # Configure consumer connection to Kafka broker\n conf = {\n 'bootstrap.servers': bootstrap_servers,\n 'default.topic.config': {'auto.offset.reset': offset_reset}\n }\n if group is not None:\n conf['group.id'] = group\n else:\n conf['group.id'] = os.environ.get('HOSTNAME', 'kowalski')\n\n # make it unique:\n conf['group.id'] = f\"{conf['group.id']}_{datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S.%f')}\"\n\n # Start alert stream consumer\n stream_reader = AlertConsumer(topic, **conf)\n\n while True:\n try:\n # poll!\n stream_reader.poll()\n\n except EopError as e:\n # Write when reaching end of partition\n print(f'{time_stamp()}: {e.message}')\n if test:\n # when testing, terminate once reached end of partition:\n sys.exit()\n except IndexError:\n print(time_stamp(), '%% Data cannot be decoded\\n')\n except UnicodeDecodeError:\n print(time_stamp(), '%% Unexpected data format received\\n')\n except KeyboardInterrupt:\n print(time_stamp(), '%% Aborted by user\\n')\n sys.exit()\n except Exception as e:\n print(time_stamp(), str(e))\n _err = traceback.format_exc()\n print(time_stamp(), str(_err))\n sys.exit()\n\n\ndef ingester(obs_date=None, test=False):\n \"\"\"\n Watchdog for topic listeners\n\n :param obs_date: observing date: YYYYMMDD\n :param test: test mode\n :return:\n \"\"\"\n\n topics_on_watch = dict()\n\n while True:\n\n try:\n # get kafka topic names with kafka-topics command\n if not test:\n # Production Kafka stream at IPAC\n kafka_cmd = [\n os.path.join(config['path']['kafka'], 'bin', 'kafka-topics.sh'),\n '--zookeeper',\n config['kafka']['zookeeper'],\n '-list'\n ]\n else:\n # Local test stream\n kafka_cmd = [\n os.path.join(config['path']['kafka'], 'bin', 'kafka-topics.sh'),\n '--zookeeper',\n config['kafka']['zookeeper.test'],\n '-list'\n ]\n\n topics = subprocess.run(kafka_cmd, stdout=subprocess.PIPE).stdout.decode('utf-8').split('\\n')[:-1]\n\n if obs_date is None:\n datestr = datetime.datetime.utcnow().strftime('%Y%m%d')\n else:\n datestr = obs_date\n # as of 20180403, the naming convention is ztf_%Y%m%d_programidN\n # exclude ZUDS, ingest separately\n topics_tonight = [t for t in topics if (datestr in t) and ('programid' in t) and ('zuds' not in t)]\n print(f'{time_stamp()}: Topics: {topics_tonight}')\n\n for t in topics_tonight:\n if t not in topics_on_watch:\n print(f'{time_stamp()}: starting listener thread for {t}')\n offset_reset = config['kafka']['default.topic.config']['auto.offset.reset']\n if not test:\n bootstrap_servers = config['kafka']['bootstrap.servers']\n else:\n bootstrap_servers = config['kafka']['bootstrap.test.servers']\n group = config['kafka']['group']\n\n topics_on_watch[t] = multiprocessing.Process(\n target=listener,\n args=(t, bootstrap_servers, offset_reset, group, test)\n )\n topics_on_watch[t].daemon = True\n topics_on_watch[t].start()\n\n else:\n print(f'{time_stamp()}: performing thread health check for {t}')\n try:\n if not topics_on_watch[t].is_alive():\n print(f'{time_stamp()}: {t} died, removing')\n # topics_on_watch[t].terminate()\n topics_on_watch.pop(t, None)\n else:\n print(f'{time_stamp()}: {t} appears normal')\n except Exception as _e:\n print(f'{time_stamp()}: Failed to perform health check', str(_e))\n pass\n\n if test:\n time.sleep(240)\n # when testing, wait for topic listeners to pull all the data, then break\n for t in topics_on_watch:\n topics_on_watch[t].kill()\n break\n\n except Exception as e:\n log(str(e))\n _err = traceback.format_exc()\n log(str(_err))\n\n if obs_date is None:\n time.sleep(60)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Fetch AVRO packets from Kafka streams and ingest them into DB')\n parser.add_argument('--obsdate', help='observing date YYYYMMDD')\n parser.add_argument('--test', help='listen to the test stream', action='store_true')\n\n args = parser.parse_args()\n\n ingester(obs_date=args.obsdate, test=args.test)\n","sub_path":"kowalski/alert_watcher_ztf.py","file_name":"alert_watcher_ztf.py","file_ext":"py","file_size_in_byte":49758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"440451857","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom cugbacm.core_hq import main\nfrom cugbacm.core_hq import UserSubmit\nfrom cugbacm.models import User, Submit, Problem, OJAttribute\nfrom celery.task import task\nimport ssdb_api\nfrom cugbacm.api.judge import Judge\n@task\ndef test(problemID):\n submit = Submit(\n runID = 111,\n userID = \"QQ\",\n problemID = problemID,\n status = \"queueing\",\n memory = 10000,\n runTime = 1000,\n codeLength = 100,\n language = 'g++',\n code = \"fuck you\")\n submit.save()\n Judge(submit)\n\ndef problem(request, problem_id):\n languages = (\"g++\",\"gcc\",\"java\",\"python2\",\"python3\")\n try:\n user = User.objects.get(userID = request.session['userID'])\n except:\n return HttpResponseRedirect(\"/index/login\")\n oj_attribute = OJAttribute.objects.all()[0]\n problem = Problem.objects.get(problemID=problem_id)\n user = User.objects.get(userID = request.session['userID'])\n submits = Submit.objects.filter(problemID = problem_id, userID = user.userID).order_by('-id')\n if request.method == 'POST':\n code = request.POST['code']\n language = request.POST['language']\n for i in range(1):\n submit = Submit(\n runID = 111,\n userID = request.session[\"userID\"],\n problemID = problem_id,\n status = \"queueing\",\n memory = 10000,\n runTime = 1000,\n codeLength = 100,\n language = language,\n code = code)\n submit.save()\n Judge.delay(submit)\n return HttpResponseRedirect(\"/index/problem/\" + str(problem_id) + \"?show_submit=true\")\n else:\n show_submit = request.GET.get('show_submit')\n if problem.visible == False:\n return HttpResponseRedirect(\"/index/problemList/\")\n try:\n submit = Submit.objects.get(id = request.GET.get('submit'))\n if submit.userID == user.userID and str(submit.problemID) == str(problem_id):\n return render(request,\n 'cugbacm/problem.html',\n {\n 'problem': problem,\n 'userID': user.userID,\n 'submit': submit,\n 'submits': submits,\n 'languages': languages,\n 'show_submit': show_submit,\n 'oj_attribute': oj_attribute,\n }\n )\n else:\n return HttpResponseRedirect(\"/index/problem/\" + str(problem_id))\n except:\n return render(request,\n 'cugbacm/problem.html',\n {\n 'problem': problem,\n 'userID': user.userID,\n 'submits': submits,\n 'languages': languages,\n 'show_submit': show_submit,\n 'oj_attribute': oj_attribute,\n }\n )\n\n\n","sub_path":"oj/cugbacm/views/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"220820205","text":"import json\n\nfrom Constants import Constants\nfrom DatabaseHelper import DatabaseHelper\nfrom EC2InfoScrapper import Scrapper\n\n\nclass StoreEC2Data:\n def __init__(self):\n constants = Constants()\n self.database = DatabaseHelper()\n self.database_connection = self.database.get_database_connection()\n self.JSON_KEYNAME = constants.JSON_KEYNAME\n\n def store_data(self, json_data):\n cursor = self.database_connection.cursor()\n\n for obj in json_data:\n data = [obj[key] for key in self.JSON_KEYNAME]\n SQL = 'INSERT INTO ' + self.database.tablename + ' (name, apiname, memory, vcpus, storage, networkperf, cost_ondemand_linux, cost_reserved_linux, cost_ondemand_mswin, cost_reserved_mswin) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) '\n cursor.execute(SQL, data)\n\n self.database_connection.commit()\n\n\nif __name__ == '__main__':\n scrapper = Scrapper()\n print('Getting data from the website... Please wait...')\n json_data = scrapper.get_data()\n print('Data scrapped...')\n\n print('Storing the data into DB... Please wait')\n store_data_obj = StoreEC2Data()\n store_data_obj.store_data(json_data['data'])\n print('Data is stored in database...')\n","sub_path":"EC2Scrapper/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"444586613","text":"import setuptools\n\nVER = '0.4.2'\n\nprint('*'*80)\nprint('* {:<76} *'.format('pgtools version {} by phageghost'.format(VER)))\nprint('*'*80)\nprint()\n\nsetuptools.setup(name='pgtools',\n\t\t\t\tversion=VER,\n\t\t\t\tdescription='A collection of useful Python code, primarily focused on bioinformatics, with particular attention to working with HOMER', \n\t\t\t\turl='http://github.com/phageghost/pg_tools',\n\t\t\t\tauthor='phageghost',\n\t\t\t\tauthor_email='pgtools@phageghost.net',\n\t\t\t\tlicense='MIT',\n\t\t\t\tpackages=['pgtools'],\n install_requires=['numpy', 'scipy', 'pandas', 'seaborn', 'weblogo'],\n\t\t\t\tzip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"507562642","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom datetime import timedelta\n\n#Category Lists\nDEPTS = ['Other','Academic English', 'American Studies', 'Anthropology', 'Applied Linguistics', 'Applied Math and Statistics', 'Arabic', 'Art', 'Astronomy and Astrophysics', 'Biochemistry and Molecular Bio', 'Biology', 'Computer Science', 'Mathematics', 'Physics','Psychology']\nSTATUS = ['New', 'Like New',\"Used Good\", \"Used Acceptable\"]\nEDITIONS = ['First Edition', 'Second Edition', 'Third Edition', 'Forth Edition', 'Fifth Edition','Sixth Edition', 'Seventh Edition', 'Eigth Edition', 'Ninth Edition', 'Tenth Edition']\n\n\n\ndb.define_table('post',\n Field('department', requires=IS_IN_SET(DEPTS, error_message=\"Invalid Selection!\")),\n Field('title', 'string', requires=IS_NOT_EMPTY()),\n Field('seller', db.auth_user, default=auth.user_id, readable=False, writable=False),\n Field('edition', requires=IS_IN_SET(EDITIONS,error_message=\"Invalid Selection!\")),\n Field('status', requires=IS_IN_SET(STATUS, error_message=\"Invalid Selection!\")),\n Field('price', 'string', requires = IS_FLOAT_IN_RANGE(0, 100000, error_message='The price should be in the range 0..100000'),required=True),\n Field('description', 'text', requires=IS_NOT_EMPTY()),\n Field('photos','upload'),\n Field('creation_date', 'datetime', default=datetime.now(),writable=False,readable=False),\n Field('delete_date', 'datetime', default=datetime.now() + timedelta(days=30),writable=False),\n auth.signature,\n format='%(title)s') \n \ndb.define_table('rating',\n Field('avrg','integer', default=0),\n Field('seller',db.auth_user),\n Field('cnt','integer',default=0),\n Field('rawNum','integer',default=0)\n )\ndb.define_table('rate_record',\n Field('rater',db.auth_user),\n Field('rated',db.auth_user)\n)\n \n\n\n\n","sub_path":"models/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"300197948","text":"import json\nimport os\nfrom collections import deque\n\nprn_json = open(os.path.join(os.path.dirname(__file__), 'prn_info.json')).read()\nprn_info = json.loads(prn_json)\n\n\nclass ShiftRegister:\n \"\"\"\n This class implements a shift register as described in the ICD 200 for using two taps.\n This is used by :class:`PRN`.\n \"\"\"\n\n def __init__(self, poly_taps, prn_taps):\n \"\"\"\n\n :param poly_taps: The polynomial taps to be used for the shift register. Usually G1, or G2 as specified in the\n ICD 200.\n :param prn_taps: The taps for the output, generally 10 for G1, or the sv taps listed in the ICD 200.\n \"\"\"\n self.G = deque([1 for i in range(10)]) # Needs to be ints for binary addition)\n self.poly_taps = poly_taps\n self.prn_taps = prn_taps\n\n def next(self):\n \"\"\"\n Generate the next output and return it. This method includes the feedback step.\n\n :return: Bit\n \"\"\"\n out = self.get_output()\n self.do_feedback()\n return out\n\n def do_feedback(self):\n \"\"\"\n Generate the feedback, and shift the values.\n\n :return:\n \"\"\"\n fb = [self.G[i - 1] for i in self.poly_taps]\n fb = sum(fb) % 2\n self.G.pop()\n self.G.appendleft(fb)\n\n def get_output(self):\n \"\"\"\n Generate the next output value for the sequence.\n\n :return: Bit\n \"\"\"\n out = [self.G[i - 1] for i in self.prn_taps]\n out = sum(out) % 2\n return out\n\n\nclass PRN:\n \"\"\"\n This class implements the coarse acquisition prn sequence as described in ICD 200.\n \"\"\"\n\n def __init__(self, prn):\n \"\"\"\n\n :param prn: SV ID No. as described in the ICD 200.\n \"\"\"\n sv_range_message = \"prn must be 1-63\"\n self.prn = prn\n if prn < 1 or prn > 63:\n ValueError(sv_range_message)\n if prn < 38:\n self.sv_prn = prn\n else:\n self.sv_prn = 0\n self.sv_taps = prn_info['taps'][str(self.sv_prn)]\n self.g1 = ShiftRegister(prn_info['taps']['G1'], [10])\n self.g2 = ShiftRegister(prn_info['taps']['G2'], self.sv_taps)\n if prn > 37:\n delays = prn_info['delays'][str(self.prn)]\n delays = list(bin(int(delays, 8))[2:])\n while len(delays) < 10:\n delays.insert(0, 0)\n for i in range(10):\n self.g2.G[i] = int(delays[i])\n self.iteration = 0\n self.ca = []\n\n def next(self):\n \"\"\"\n Get the next chip in the sequence.\n\n :return:\n \"\"\"\n if self.iteration < 1023:\n g1 = self.g1.next()\n g2 = self.g2.next()\n ca = (g1 + g2) % 2\n self.ca.append(ca)\n self.iteration += 1\n else:\n ca = self.ca[self.iteration % 1023]\n self.iteration += 1\n if self.iteration == 2047:\n self.iteration = 1023\n return ca\n\n def prn_seq(self):\n \"\"\"\n Return the full ca sequence. (1023 bits)\n Uses :func:`PRN.next` to generate full sequence.\n\n :return:\n \"\"\"\n if self.iteration < 1023:\n while self.iteration < 1023:\n self.next()\n return self.ca","sub_path":"gps_helper/_prn.py","file_name":"_prn.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"479217038","text":"from apogee import sets\nimport numpy as np\n\n\ndef two_factor_operation(func):\n def _wrapped(a, b):\n scope = sets.union(a.scope, b.scope) # calculate the new scope.\n maps_a = sets.maps(scope, a.scope) # generate map of scope of a in new scope.\n maps_b = sets.maps(scope, b.scope) # repeat\n\n card = np.zeros_like(scope, dtype=np.int64)\n card[maps_a] = a.cards\n card[maps_b] = b.cards\n\n assignments = sets.cartesian_product(*[sets.arange(n) for n in card])\n\n vals = np.empty(len(assignments), dtype=type(a.parameters[0]))\n a_idx = sets.indices(assignments[:, maps_a], a.assignments)\n b_idx = sets.indices(assignments[:, maps_b], b.assignments)\n\n avals, bvals = a.params, b.params\n\n return scope, card, func(avals, a_idx, bvals, b_idx, vals)\n\n\n@two_factor_operation\ndef factor_division_(avals, amap, bvals, bmap, empty_):\n for i, (j, k) in enumerate(zip(amap, bmap)):\n empty_[i] = avals[j] - bvals[k]\n return empty_\n\n\ndef factor_division(a, b):\n \"\"\"\n Calculate the division of two factors. Currently aimed at discrete factors.\n\n Parameters\n ----------\n a: Factor-like\n A factor object.\n b: Factor-like\n A factor object.\n\n Returns\n -------\n scope: ndarray\n An array containing the scope of the resulting factor.\n card: ndarray\n An array containing the cardinality of the resulting factor.\n vals: ndarray\n An array containing the probability distribution of the resulting factor.\n\n Examples\n --------\n >>> a = Factor([0], [2], [0.1, 0.9])\n >>> b = Factor([1, 0], [2, 2], [[0.2, 0.8], [0.7, 0.3]])\n >>> c = Factor(*factor_division(a, b)) # generate new factor from factors a and b\n\n \"\"\"\n\n scope = sets.union(a.scope, b.scope) # calculate the new scope.\n maps_a = sets.maps(scope, a.scope) # generate map of scope of a in new scope.\n maps_b = sets.maps(scope, b.scope) # repeat\n\n card = np.zeros_like(scope, dtype=np.int64)\n card[maps_a] = a.cards\n card[maps_b] = b.cards\n\n assignments = sets.cartesian_product(*[sets.arange(n) for n in card])\n\n vals = np.empty(len(assignments), dtype=type(a.parameters[0]))\n a_idx = sets.indices(assignments[:, maps_a], a.assignments)\n b_idx = sets.indices(assignments[:, maps_b], b.assignments)\n\n avals, bvals = a.parameters, b.parameters\n for i, (j, k) in enumerate(zip(a_idx, b_idx)):\n vals[i] = avals[j] - bvals[k]\n\n return scope, card, vals","sub_path":"apogee/models/probabilistic/core/structures/discrete/operations/divide.py","file_name":"divide.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"417291814","text":"import csv\nimport time\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib import style\nfrom matplotlib.pylab import *\nfrom mpl_toolkits.axes_grid1 import host_subplot\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport random\nfrom datetime import datetime\n\nstyle.use('fivethirtyeight')\n# plt.rcParams['animation.html'] = 'jshtml'\n\n# Sent for figure\nfont = {'size' : 9}\nmatplotlib.rc('font', **font)\n\n\nfig = plt.figure(dpi=80, num=\"BAMS Data Accelerometer 1\") # num = 2, figsize = (2, 3)\nax1 = fig.add_subplot(111)\n\narray = [] #array\n\ndef animate(i):\n\tnode = \"\"\n\tacc1, acc2 = [], []\n\ttimestamp = []\n\tdata = []\n\twith open(\"csvfile/sb4.csv\", \"r\") as csvfile: #with untuk streaming file, secara otomatis akan close bersihin file saat ga di pake lagi\n\t csvreader = csv.DictReader(csvfile) #bentuk dictionary\n\t array = list(csvreader)\n\t print(\"total baris : \", csvreader.line_num, \"\\n\")\n\n\tfor x in array:\n\t\tnode = x[\"node\"]\n\t\tacc1.append(double(x[\"acc1\"]))\n\t\ttimestamp = x[\"timestamp\"]\n\n\tif len(data) < 100:\n\t\tfor i in range(100):\n\t\t\t# acc1.append(random.randint(0,10))\n\t\t\tdata.append(i)\n\telse:\n\t\tdata = []\n\t\t# acc1 = []\n\t\tfor i in range(100):\n\t\t\t# acc1.append(random.randint(0,10))\n\t\t\tdata.append(i)\n\n\tprint(node)\n\n\tprint(timestamp)\n\tprint(acc1)\n\tprint(\"Length Times\",len(timestamp))\n\tprint(\"Length Acc1\", len(acc1))\n\tprint(\"Jumlah data\", len(data))\n\ttime.sleep(1)\n\n\tax1.clear()\n\t# ax1.bar(timestamp, acc1)\n\tax1.plot(data, acc1)\n\t# ax1.scatter(timestamp, acc1)\n\tplt.ylabel('Accelerometer 1 (m/s^2)')\n\tplt.xlabel('Number Of Data')\n\tplt.title('Bridge Aeroelastic Monitoring System\\nLive Data From Node : {}\\n Timestamp: {}'.format(node, timestamp))\n\ndef show_data():\n\tani=animation.FuncAnimation(fig, animate, interval=5000)\n\tplt.show()\n\nif __name__ == '__main__':\n\tshow_data()\n\t# animate()","sub_path":"sb4_graph_acc1.py","file_name":"sb4_graph_acc1.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"459642629","text":"# -- coding: UTF-8 --\nimport requests\nfrom bs4 import BeautifulSoup\nfrom threading import Lock,Thread\nimport os\nbasePath = r\"/mm\"\nthreadLimit = 10\nthreadNum = 0\nos.chdir(basePath)\n# 遍历打印出图片地址\nurlPool = [\"http://www.meitulu.com/item/{}.html\".format(str(i)) for i in range(3465, 5645)]\nmutex = Lock()\ndef downloadImg(url):\n dirname = url.split(\"/\")[-1].split(\".\")[0]\n print(dirname)\n if not os.path.isdir(dirname):\n os.mkdir(dirname)\n ordinal = 1\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36\"}\n linkPool = []\n while True:\n try:\n resp = requests.get(url, headers=headers).text\n soup = BeautifulSoup(resp, \"html.parser\")\n links = soup.select(\"body > div.content > center > img\")\n for urlLink in links:\n link = urlLink.get(\"src\")\n linkPool.append(link)\n nextPageUrl = soup.findAll(\"a\", {\"class\": \"a1\"})[1].get(\"href\")\n if nextPageUrl == url:\n break\n else:\n url = nextPageUrl\n except Exception:\n print(\"Connection Error, or BeautifulSoup going Wrong, forget it:\", url)\n break\n for link in linkPool:\n try:\n content = requests.get(link, headers=headers)\n title = str(ordinal) + \".jpg\"\n # 文件就保存在工作目录了\n file = open(dirname + \"/\" + title, \"wb\")\n print(dirname + \"/\" + title)\n file.write(content.content)\n file.close()\n ordinal += 1\n except Exception:\n print(\"Couldn't Parse!\", link)\n break\n print('爬取完成')\nclass MyThread(Thread):\n def __init__(self, url):\n self.url = url\n Thread.__init__(self)\n def run(self):\n downloadImg(self.url)\n mutex.acquire()\n global threadNum\n threadNum -= 1\n mutex.release()\nwhile urlPool != []:\n if threadNum < threadLimit:\n newUrl = urlPool.pop()\n threadNum += 1\n newThread = MyThread(newUrl)\n newThread.start()","sub_path":"suess.py","file_name":"suess.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"186210733","text":"import pickle\nfrom typing import Dict, Any\n\nimport chainerrl\nimport gym\nimport numpy as np\nimport tensorflow as tf\nimport argparse\n\nfrom envs import SubprocVecEnv_tf2\nfrom envs import Replay_Buffer\nfrom envs.common_envs_utils.env_wrappers import *\nfrom envs.gym_car_intersect_fixed.environment import CarRacingHackatonContinuousFixed\n\nfrom sac import SAC_Agent_Torch_NoPic\nfrom SAC_github import SAC_Discrete, SAC_Continues\nfrom sac import SAC_Agent_Torch_Continues\n\n\nclass Holder:\n ENV_DONE_FLAGS = {'need_reset'}\n def __init__(\n self,\n name,\n learning_rate=3e-4,\n device='cpu',\n args=None,\n ):\n self.batch_size = args.batch_size\n self.env_num = args.num_env\n self.args = args\n self._state_maker = lambda x: x\n\n # init environment and agent\n _make_env = None\n if args.env_type == 'my':\n def f():\n env = CarRacingHackatonContinuousFixed(settings_file_path=args.settings)\n env = chainerrl.wrappers.ContinuingTimeLimit(env, max_episode_steps=250)\n env = MaxAndSkipEnv(env, skip=4)\n env = WarpFrame(env, channel_order='chw')\n return env\n _make_env = f\n self._state_maker = lambda x: x.astype(np.float32) / 255\n if args.env_type == 'lun':\n def f():\n env = gym.make('LunarLanderContinuous-v2')\n env = chainerrl.wrappers.ContinuingTimeLimit(env, max_episode_steps=350)\n # env = RewardClipperWrapper(env)\n return env\n _make_env = f\n # if args.env_type == 'cart':\n # def f():\n # env = gym.make('CartPole-v1')\n # env = ContinuesCartPolyWrapper(env)\n # return env\n # _make_env = f\n # if args.env_type == 'pend':\n # def f():\n # env = gym.make('Pendulum-v0')\n # env = chainerrl.wrappers.ContinuingTimeLimit(env, max_episode_steps=350)\n # env = RewardClipperWrapper(env)\n # return env\n # _make_env = f\n\n if args.env_type == 'hopper':\n def f():\n env = gym.make('Hopper-v2')\n env = MaxAndSkipEnv(env, skip=4)\n return env\n _make_env = f\n\n self.single_test_env = _make_env()\n\n self.agent = None\n # if args.agent_type == 'torch-nopic':\n # self.agent = SAC_Agent_Torch_NoPic(\n # state_size=self.single_test_env.observation_space.shape[0],\n # action_size=self.single_test_env.action_space.n,\n # hidden_size=args.hidden_size,\n # start_lr=learning_rate,\n # device=device,\n # )\n if args.agent_type == 'torch-cont':\n self.agent = SAC_Agent_Torch_Continues(\n state_size=8,\n action_size=2,\n hidden_size=args.hidden_size,\n start_lr=learning_rate,\n device=device,\n )\n # if args.agent_type == 'git':\n # self.agent = SAC_Discrete(\n # state_size=self.single_test_env.observation_space.shape[0],\n # action_size=self.single_test_env.action_space.n,\n # hidden_size=args.hidden_size,\n # device=device,\n # )\n if args.agent_type == 'git-cont':\n self.agent = SAC_Continues(\n state_size=self.single_test_env.observation_space.shape,\n action_size=self.single_test_env.action_space.shape,\n hidden_size=256,\n lr=args.lr,\n device=device,\n )\n\n if self.agent is None:\n raise ValueError()\n\n\n # for reward history\n self.episode_number = 0\n self.name = name\n self._stats = {}\n\n log_dir = 'logs/' + name\n self.log_summary_writer = tf.summary.create_file_writer(log_dir)\n\n # init replay buffer\n self.buffer = Replay_Buffer(\n buffer_size=args.buffer_size,\n batch_size=args.batch_size,\n seed=42,\n device=args.device,\n state_maker=self._state_maker,\n )\n\n self.env = SubprocVecEnv_tf2([_make_env for _ in range(self.env_num)])\n self.env_test = SubprocVecEnv_tf2([_make_env for _ in range(10)])\n\n def publish_log(self):\n with self.log_summary_writer.as_default():\n for loss_name, loss_values in self._stats.items():\n tf.summary.scalar(\n name=f'{loss_name}',\n data=np.array(loss_values).mean(),\n step=self.episode_number,\n )\n del self._stats\n self._stats = {}\n\n def store_logs(self, log_dict: Dict[str, Any]):\n for name, value in log_dict.items():\n if name not in self._stats.keys():\n self._stats[name] = []\n self._stats[name].append(value)\n\n def run_episode(self, is_eval: bool):\n state_batch = self.env.reset()\n\n done_flags = np.zeros(self.env_num, dtype=np.float32)\n total_rewards = np.zeros(self.env_num, dtype=np.float32)\n if not is_eval and self.buffer.size() >= self.args.start_buffer_size:\n self.episode_number += 1\n\n while done_flags.sum() < max(1, self.env_num * 0.75):\n action_batch = self.agent.batch_action(self._state_maker(state_batch))\n next_state_batch, reward_batch, done_batch, info_batch = self.env.step(action_batch)\n\n total_rewards += reward_batch.reshape((self.env_num, )) * (1.0 - done_flags)\n done_flags += np.clip(done_batch.reshape((self.env_num, )), 0.0, 1.0)\n\n if not is_eval:\n self.buffer.add_batch_experience(\n state_batch,\n action_batch,\n reward_batch,\n next_state_batch,\n done_batch,\n )\n if self.buffer.size() >= self.args.start_buffer_size:\n for _ in range(2):\n q1_loss, q2_loss, v_loss, policy_loss, temperature = self.agent.update_step(self.buffer.sample())\n self.store_logs({\n 'q1 loss': q1_loss,\n 'q2 loss': q2_loss,\n 'v loss': v_loss,\n 'policy loss': policy_loss,\n 'temperature': temperature,\n })\n\n state_batch = next_state_batch\n\n for index, (done, info) in enumerate(zip(done_batch, info_batch)):\n if done or ('need_reset' in info.keys() and info['need_reset']):\n done_flags[index] = 1.0\n state_batch[index] = self.env.force_reset([index])[0]\n\n self.store_logs({'reward': total_rewards.mean()})\n self.agent.hard_target_update()\n return total_rewards.mean()\n\n def save(self):\n import os\n folder = os.path.join('model_saves', f'{self.name}__{self.episode_number}')\n if not os.path.exists(folder):\n os.makedirs(folder)\n self.agent.save(folder)\n pickle.dump(self.episode_number, open(os.path.join(folder, 'episodes_number.pkl'), 'wb'))\n\n def load(self, folder_name):\n import os\n if not os.path.exists(folder_name):\n raise ValueError(f\"folder doesn't exist : {folder_name}\")\n self.episode_number = pickle.load(open(os.path.join(folder_name, 'episodes_number.pkl'), 'rb'))\n self.agent.load(folder_name)\n\n def train(self):\n for step_index in range(10000):\n print(f'episode : {step_index}')\n mean_reward = self.run_episode(is_eval=False)\n\n if self.buffer.size() >= self.args.start_buffer_size:\n print(f'mean reward : {mean_reward}')\n self.publish_log()\n\n print(f'buffer size : {self.buffer.size()}')\n\n if step_index % 50 == 49:\n self.save()\n\n\ndef main(args):\n print('start...')\n print('creat holder...')\n holder = Holder(\n name=args.name,\n learning_rate=3e-4,\n args=args,\n )\n\n if args.load_folder is not None:\n holder.load(args.load_folder)\n\n print('start training...')\n holder.train()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--load-folder', type=str, default=None, help='folder to preload weights')\n parser.add_argument('--video-only', type=bool, default=False,\n help='flag to just record animation from saved weights')\n parser.add_argument('--name', type=str, default='test', help='name for saves')\n parser.add_argument('--num-env', type=int, default=32, help='env num to train process')\n parser.add_argument('--batch-size', type=int, default=256, help='batch size')\n parser.add_argument('--hidden-size', type=int, default=256, help='hidden size')\n parser.add_argument('--buffer-size', type=int, default=3 * 10**5, help='buffer size')\n parser.add_argument('--start-buffer-size', type=int, default=5 * 10**4, help='initial size of replay buffer')\n parser.add_argument('--device', type=str, default='cpu', help='use animation records')\n parser.add_argument('--eval', action='store_true', default=False, help='do not eval runs')\n parser.add_argument('--env-type', type=str, default='lun', help='old or new')\n parser.add_argument('--agent-type', type=str, default='git', help='old or new')\n parser.add_argument('--lr', type=float, default=3e-4, help='learning rate')\n parser.add_argument(\n '--settings',\n type=str,\n default='./envs/gym_car_intersect_fixed/settings_v2.json',\n help='path to reward settings'\n )\n\n args = parser.parse_args()\n main(args)\n","sub_path":"sac_holder.py","file_name":"sac_holder.py","file_ext":"py","file_size_in_byte":9960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"596808164","text":"from Products.CMFPlone import PloneMessageFactory as _\nfrom plone.app.registry.browser import controlpanel\n# from Products.CMFPlone.interfaces import IFilterSchema\nfrom Products.CMFCore.interfaces import ISiteRoot\nfrom plone.app.layout.navigation.interfaces import INavigationRoot\nfrom plone.registry.interfaces import IRegistry\nfrom zope.interface import Interface\nfrom zope.component import adapts\nfrom zope import schema\nfrom zope.component import getUtility\nfrom zope.interface import implements\n\n\nclass IPloneSiteRoot(ISiteRoot, INavigationRoot):\n \"\"\"\n Marker interface for the object which serves as the root of a\n Plone site.\n \"\"\"\n\n\nclass ITagAttrPair(Interface):\n tags = schema.TextLine(title=u\"tags\")\n attributes = schema.TextLine(title=u\"attributes\")\n\n\nclass TagAttrPair:\n implements(ITagAttrPair)\n\n def __init__(self, tags='', attributes=''):\n self.tags = tags\n self.attributes = attributes\n\n\nclass IFilterTagsSchema(Interface):\n nasty_tags = schema.List(\n title=_(u'Nasty tags'),\n description=_(u\"These tags, and their content are completely blocked \"\n \"when a page is saved or rendered.\"),\n default=[u'applet', u'embed', u'object', u'script'],\n value_type=schema.TextLine(),\n required=False\n )\n\n stripped_tags = schema.List(\n title=_(u'Stripped tags'),\n description=_(u\"These tags are stripped when saving or rendering, \"\n \"but any content is preserved.\"),\n default=[u'font', ],\n value_type=schema.TextLine(),\n required=False\n )\n\n custom_tags = schema.List(\n title=_(u'Custom tags'),\n description=_(u\"Add tag names here for tags which are not part of \"\n \"XHTML but which should be permitted.\"),\n default=[],\n value_type=schema.TextLine(),\n required=False\n )\n\n\nclass IFilterAttributesSchema(Interface):\n stripped_attributes = schema.List(\n title=_(u'Stripped attributes'),\n description=_(u\"These attributes are stripped from any tag when \"\n \"saving.\"),\n default=(u'dir lang valign halign border frame rules cellspacing '\n 'cellpadding bgcolor').split(),\n value_type=schema.TextLine(),\n required=False)\n\n# stripped_combinations = schema.List(\n# title=_(u'Stripped combinations'),\n# description=_(u\"These attributes are stripped from those tags when \"\n# \"saving.\"),\n# default=[],\n# #default=u'dir lang valign halign border frame rules cellspacing\n# # cellpadding bgcolor'.split()\n# value_type=schema.Object(ITagAttrPair, title=u\"combination\"),\n# required=False)\n\n\nclass IFilterEditorSchema(Interface):\n\n style_whitelist = schema.List(\n title=_(u'Permitted styles'),\n description=_(u'These CSS styles are allowed in style attributes.'),\n default=u'text-align list-style-type float'.split(),\n value_type=schema.TextLine(),\n required=False)\n\n class_blacklist = schema.List(\n title=_(u'Filtered classes'),\n description=_(u'These class names are not allowed in class '\n 'attributes.'),\n default=[],\n value_type=schema.TextLine(),\n required=False)\n\n\nclass IFilterSchema(IFilterTagsSchema, IFilterAttributesSchema,\n IFilterEditorSchema):\n \"\"\"Combined schema for the adapter lookup.\n \"\"\"\n\n\n# filtertagset = FormFieldsets(IFilterTagsSchema)\n# filtertagset.id = 'filtertags'\n# filtertagset.label = _(u'label_filtertags', default=u'Tags')\n#\n# filterattributes = FormFieldsets(IFilterAttributesSchema)\n# filterattributes.id = 'filterattributes'\n# filterattributes.label = _(u'label_filterattributes', default=u'Attributes')\n#\n# filtereditor = FormFieldsets(IFilterEditorSchema)\n# filtereditor.id = 'filtereditor'\n# filtereditor.label = _(u'filterstyles', default=u'Styles')\n#\n# tagattr_widget = CustomWidgetFactory(ObjectWidget, TagAttrPair)\n# combination_widget = CustomWidgetFactory(ListSequenceWidget,\n# subwidget=tagattr_widget)\n\n\nclass FilterControlPanelForm(controlpanel.RegistryEditForm):\n\n id = \"FilterControlPanel\"\n label = _(\"HTML Filter settings\")\n description = _(\"Plone filters HTML tags that are considered security \"\n \"risks. Be aware of the implications before making \"\n \"changes below. By default only tags defined in XHTML \"\n \"are permitted. In particular, to allow 'embed' as a tag \"\n \"you must both remove it from 'Nasty tags' and add it to \"\n \"'Custom tags'. Although the form will update \"\n \"immediately to show any changes you make, your changes \"\n \"are not saved until you press the 'Save' button.\")\n form_name = _(\"HTML Filter settings\")\n schema = IFilterSchema\n schema_prefix = \"plone\"\n\n# form_fields = FormFieldsets(filtertagset, filterattributes, filtereditor)\n# form_fields['stripped_combinations'].custom_widget = combination_widget\n\n # form_fields = FormFieldsets(searchset)\n # form_fields['types_not_searched'].custom_widget = MCBThreeColumnWidget\n # form_fields['types_not_searched'].custom_widget.cssClass='label'\n\n def updateFields(self):\n super(FilterControlPanelForm, self).updateFields()\n\n\nclass FilterControlPanel(controlpanel.ControlPanelFormWrapper):\n form = FilterControlPanelForm\n\n\nclass FilterControlPanelAdapter(object):\n\n adapts(IPloneSiteRoot)\n implements(IFilterSchema)\n\n def __init__(self, context):\n registry = getUtility(IRegistry)\n self.settings = registry.forInterface(IFilterSchema, prefix=\"plone\")\n\n def get_nasty_tags(self):\n return self.settings.nasty_tags\n\n def set_nasty_tags(self, value):\n self.settings.nasty_tags = value\n\n def get_stripped_tags(self):\n return self.settings.stripped_tags\n\n def set_stripped_tags(self, value):\n self.settings.stripped_tags = value\n\n def get_custom_tags(self):\n return self.settings.custom_tags\n\n def set_custom_tags(self, value):\n self.settings.custom_tags = value\n\n def get_stripped_attributes(self):\n return self.settings.stripped_attributes\n\n def set_stripped_attributes(self, value):\n self.settings.stripped_attributes = value\n\n def get_style_whitelist(self):\n return self.settings.style_whitelist\n\n def set_style_whitelist(self, value):\n self.settings.style_whitelist = value\n\n def get_class_blacklist(self):\n return self.settings.class_blacklist\n\n def set_class_blacklist(self, value):\n self.settings.class_blacklist = value\n\n nasty_tags = property(get_nasty_tags, set_nasty_tags)\n stripped_tags = property(get_stripped_tags, set_stripped_tags)\n custom_tags = property(get_custom_tags, set_custom_tags)\n stripped_attributes = property(\n get_stripped_attributes,\n set_stripped_attributes\n )\n style_whitelist = property(get_style_whitelist, set_style_whitelist)\n class_blacklist = property(get_class_blacklist, set_class_blacklist)\n","sub_path":"src/experimental/safe_html_transform/browser/controlpanel.py","file_name":"controlpanel.py","file_ext":"py","file_size_in_byte":7219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"636318216","text":"from pathlib import Path\n\nfrom fpdf import FPDF, HTMLMixin\nfrom test.conftest import assert_pdf_equal\n\nHERE = Path(__file__).resolve().parent\n\n\nclass PDF(FPDF, HTMLMixin):\n pass\n\n\ndef test_links(tmp_path):\n pdf = PDF()\n pdf.add_page()\n pdf.set_font(\"helvetica\", size=24)\n line_height = 10\n\n pdf.set_xy(80, 50)\n pdf.cell(\n w=40,\n h=line_height,\n txt=\"Cell link\",\n border=1,\n align=\"C\",\n link=\"https://github.com/PyFPDF/fpdf2\",\n )\n\n pdf.set_xy(60, 100)\n pdf.write_html('Link defined as HTML')\n\n text = \"Text link\"\n pdf.text(x=80, y=150, txt=text)\n width = pdf.get_string_width(text)\n pdf.link(\n x=80,\n y=150 - line_height,\n w=width,\n h=line_height,\n link=\"https://github.com/PyFPDF/fpdf2\",\n )\n\n pdf.add_page()\n link = pdf.add_link()\n pdf.set_link(link, page=1)\n pdf.set_xy(50, 50)\n pdf.cell(\n w=100, h=10, txt=\"Internal link to first page\", border=1, align=\"C\", link=link\n )\n\n assert_pdf_equal(pdf, HERE / \"links.pdf\", tmp_path)\n\n\ndef test_link_alt_text(tmp_path):\n \"\"\"\n It can be tested that the reference file for this test\n has the link description read out loud by the NVDA screen reader\n when opened with Adobe Acrobat Reader.\n \"\"\"\n pdf = FPDF()\n pdf.add_page()\n pdf.set_font(\"helvetica\", size=24)\n text = \"PyFPDF/fpdf2\"\n pdf.text(x=80, y=150, txt=text)\n width = pdf.get_string_width(text)\n line_height = 10\n pdf.link(\n x=80,\n y=150 - line_height,\n w=width,\n h=line_height,\n link=\"https://github.com/PyFPDF/fpdf2\",\n alt_text=\"GitHub repository of the fpdf2 library\",\n )\n assert_pdf_equal(pdf, HERE / \"link_alt_text.pdf\", tmp_path)\n\n\ndef test_link_with_zoom_and_shift(tmp_path):\n pdf = FPDF()\n pdf.set_font(\"helvetica\", size=24)\n pdf.add_page()\n link = pdf.add_link()\n pdf.set_link(link, page=2, x=pdf.epw / 4, y=pdf.epw / 3, zoom=4)\n pdf.set_xy(30, 50)\n pdf.cell(\n w=140,\n h=10,\n txt=\"Link to 2nd page zoomed & shifted\",\n border=1,\n align=\"C\",\n link=link,\n )\n pdf.add_page()\n pdf.multi_cell(\n pdf.epw,\n txt=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\"\n \" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\"\n \" Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\"\n \" Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\"\n \" Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\",\n )\n assert_pdf_equal(pdf, HERE / \"link_with_zoom_and_shift.pdf\", tmp_path)\n","sub_path":"venv/Lib/site-packages/test/test_links.py","file_name":"test_links.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"64814661","text":"\"\"\"handles feature extraction\"\"\"\n# rewrite of https://github.com/leelabcnbc/tang-paper-2017/blob/master/tang_2017/feature_extraction.py\nfrom torchvision.models import vgg16, vgg16_bn, vgg19, vgg19_bn\n\nfrom leelabtoolbox.feature_extraction.cnn import (cnnsizehelper, generic_network_definitions)\nfrom leelabtoolbox.preprocessing import pipeline\n\nfrom collections import defaultdict, OrderedDict\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom functools import partial\nfrom skimage.transform import rescale\nimport numpy as np\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom torch import FloatTensor\nimport h5py\n\n\ndef blobinfo():\n # copied from\n # https://github.com/leelabcnbc/leelab-toolbox/blob/fe57c8577993c9c9883eee1ca0b527cb8300226f/leelabtoolbox/feature_extraction/cnn/pytorch_network_definitions.py\n blob_corresponding_info_inner = dict()\n blob_corresponding_info_inner['vgg16'] = OrderedDict([('conv1_1', 'features.1'),\n ('conv1_2', 'features.3'),\n ('pool1', 'features.4'),\n ('conv2_1', 'features.6'),\n ('conv2_2', 'features.8'),\n ('pool2', 'features.9'),\n ('conv3_1', 'features.11'),\n ('conv3_2', 'features.13'),\n ('conv3_3', 'features.15'),\n ('pool3', 'features.16'),\n ('conv4_1', 'features.18'),\n ('conv4_2', 'features.20'),\n ('conv4_3', 'features.22'),\n ('pool4', 'features.23'),\n ('conv5_1', 'features.25'),\n ('conv5_2', 'features.27'),\n ('conv5_3', 'features.29'),\n ('pool5', 'features.30'),\n ('fc6', 'classifier.1'),\n ('fc7', 'classifier.4')])\n\n blob_corresponding_info_inner['vgg16_bn'] = OrderedDict([('conv1_1', 'features.2'),\n ('conv1_2', 'features.5'),\n ('pool1', 'features.6'),\n ('conv2_1', 'features.9'),\n ('conv2_2', 'features.12'),\n ('pool2', 'features.13'),\n ('conv3_1', 'features.16'),\n ('conv3_2', 'features.19'),\n ('conv3_3', 'features.22'),\n ('pool3', 'features.23'),\n ('conv4_1', 'features.26'),\n ('conv4_2', 'features.29'),\n ('conv4_3', 'features.32'),\n ('pool4', 'features.33'),\n ('conv5_1', 'features.36'),\n ('conv5_2', 'features.39'),\n ('conv5_3', 'features.42'),\n ('pool5', 'features.43'),\n ('fc6', 'classifier.1'),\n ('fc7', 'classifier.4')])\n\n blob_corresponding_info_inner['vgg19'] = OrderedDict([('conv1_1', 'features.1'),\n ('conv1_2', 'features.3'),\n ('pool1', 'features.4'),\n ('conv2_1', 'features.6'),\n ('conv2_2', 'features.8'),\n ('pool2', 'features.9'),\n ('conv3_1', 'features.11'),\n ('conv3_2', 'features.13'),\n ('conv3_3', 'features.15'),\n ('conv3_4', 'features.17'),\n ('pool3', 'features.18'),\n ('conv4_1', 'features.20'),\n ('conv4_2', 'features.22'),\n ('conv4_3', 'features.24'),\n ('conv4_4', 'features.26'),\n ('pool4', 'features.27'),\n ('conv5_1', 'features.29'),\n ('conv5_2', 'features.31'),\n ('conv5_3', 'features.33'),\n ('conv5_4', 'features.35'),\n ('pool5', 'features.36'),\n ('fc6', 'classifier.1'),\n ('fc7', 'classifier.4')])\n\n blob_corresponding_info_inner['vgg19_bn'] = OrderedDict([('conv1_1', 'features.2'),\n ('conv1_2', 'features.5'),\n ('pool1', 'features.6'),\n ('conv2_1', 'features.9'),\n ('conv2_2', 'features.12'),\n ('pool2', 'features.13'),\n ('conv3_1', 'features.16'),\n ('conv3_2', 'features.19'),\n ('conv3_3', 'features.22'),\n ('conv3_4', 'features.25'),\n ('pool3', 'features.26'),\n ('conv4_1', 'features.29'),\n ('conv4_2', 'features.32'),\n ('conv4_3', 'features.35'),\n ('conv4_4', 'features.38'),\n ('pool4', 'features.39'),\n ('conv5_1', 'features.42'),\n ('conv5_2', 'features.45'),\n ('conv5_3', 'features.48'),\n ('conv5_4', 'features.51'),\n ('pool5', 'features.52'),\n ('fc6', 'classifier.1'),\n ('fc7', 'classifier.4')])\n\n blob_corresponding_reverse_info_inner = dict()\n for net_name, net_info in blob_corresponding_info_inner.items():\n blob_corresponding_reverse_info_inner[net_name] = OrderedDict()\n for x, y in net_info.items():\n blob_corresponding_reverse_info_inner[net_name][y] = x\n assert len(blob_corresponding_reverse_info_inner[net_name]) == len(net_info)\n\n return blob_corresponding_info_inner, blob_corresponding_reverse_info_inner\n\n\nblob_corresponding_info, blob_corresponding_reverse_info = blobinfo()\n\n\ndef get_one_network_meta(net_name, ec_size=22, blobs_to_extract=None):\n if blobs_to_extract is None:\n blobs_to_extract = list(blob_corresponding_info[net_name].keys())\n\n # get meta info needed for this network\n if net_name.endswith('_bn'):\n net_name_for_check = net_name[:-3]\n else:\n net_name_for_check = net_name\n input_size = generic_network_definitions.input_size_info[net_name_for_check]\n blob_info = generic_network_definitions.blob_info[net_name_for_check]\n helper_this = cnnsizehelper.CNNSizeHelper(blob_info, input_size)\n\n # 22 is the original setting, since we rescale image to 2/3 of original\n # (which is found to be (marginally?) better for RSA analysis, in both Corentin's case and Tang)\n\n top_bottom = input_size[0] / 2 - ec_size / 2, input_size[0] / 2 + ec_size / 2\n left_right = input_size[1] / 2 - ec_size / 2, input_size[1] / 2 + ec_size / 2\n\n slicing_dict = defaultdict(lambda: ((None, None), (None, None)))\n\n # compute how many columns to extract.\n for layer in helper_this.layer_info_dict:\n slicing_dict[layer] = helper_this.compute_minimum_coverage(layer, top_bottom, left_right)\n\n slicing_dict = cnnsizehelper.get_slice_dict(slicing_dict, blobs_to_extract=blobs_to_extract)\n\n def correspondence_func(x):\n # handle no correspondence case\n return blob_corresponding_reverse_info[net_name].get(x, None)\n\n return helper_this, slicing_dict, blobs_to_extract, correspondence_func\n\n\ndef get_pretrained_network(net_name):\n a = {'vgg16': vgg16, 'vgg19': vgg19, 'vgg16_bn': vgg16_bn, 'vgg19_bn': vgg19_bn}[net_name](pretrained=True)\n # a.cuda()\n a = a.eval()\n return a\n\n\ndef _forward_hook(m, in_, out_, module_name, callback_dict, slice_this):\n assert isinstance(out_, Variable)\n data_all = out_.data.cpu().numpy()\n # then slice it\n slice_r, slice_c = slice_this\n if data_all.ndim == 4:\n data_this_to_use = data_all[:, :, slice_r, slice_c]\n else:\n assert data_all.ndim == 2\n data_this_to_use = data_all\n # print(f'{data_all.shape} -> {data_this_to_use.shape}')\n # extra copy to guard against weird things.\n callback_dict[module_name]['output'].append(data_this_to_use.copy())\n\n\ndef augment_module_pre(net: nn.Module, module_names: set, module_correspondence=None, slice_dict=None) -> (dict, list):\n callback_dict = OrderedDict() # not necessarily ordered, but this can help some readability.\n\n if module_correspondence is None:\n # this maps internal PyTorch name to standard names (in Caffe).\n module_correspondence = lambda x_: x_\n\n forward_hook_remove_func_list = []\n for x, y in net.named_modules():\n if module_correspondence(x) in module_names:\n callback_dict[module_correspondence(x)] = {}\n callback_dict[module_correspondence(x)]['output'] = []\n forward_hook_remove_func_list.append(\n y.register_forward_hook(\n partial(_forward_hook, module_name=module_correspondence(x), callback_dict=callback_dict,\n slice_this=slice_dict[module_correspondence(x)])))\n\n def remove_handles():\n for h in forward_hook_remove_func_list:\n h.remove()\n\n return callback_dict, remove_handles\n\n\ndef preprocess_dataset(images, bgcolor, input_size, rescale_ratio=None):\n # rescale\n if rescale_ratio is not None:\n images = np.asarray([rescale(im, scale=rescale_ratio, order=1, mode='edge') for im in images])\n\n # make sure images are 3D\n if images.ndim == 3:\n images = np.concatenate((images[..., np.newaxis],) * 3, axis=-1)\n assert images.ndim == 4 and images.shape[-1] == 3\n assert np.all(images <= 1) and np.all(images >= 0)\n\n # use leelab-toolbox pipeline\n steps_naive = ['putInCanvas']\n pars_naive = {'putInCanvas': {'canvas_size': input_size,\n 'canvas_color': bgcolor,\n },\n }\n pipeline_naive, realpars_naive, order_naive = pipeline.preprocessing_pipeline(steps_naive, pars_naive,\n order=steps_naive)\n images_new = pipeline_naive.transform(images.astype(np.float32, copy=False))\n\n # normalize\n # check\n # http://pytorch.org/docs/master/torchvision/models.html\n images_new -= np.array([0.485, 0.456, 0.406])\n images_new /= np.array([0.229, 0.224, 0.225])\n # transpose\n images_new = np.transpose(images_new, (0, 3, 1, 2))\n # done\n return images_new\n\n\ndef extract_features_one_case(net, dataset_preprocessed, blobs_to_extract, correspondence_func, slicing_dict,\n batch_size, verbose=True):\n callback_dict, remove_handles = augment_module_pre(net, blobs_to_extract,\n module_correspondence=correspondence_func,\n slice_dict=slicing_dict)\n\n # then create tensor dataset\n loader_this = DataLoader(TensorDataset(FloatTensor(dataset_preprocessed),\n FloatTensor(np.zeros(len(dataset_preprocessed), dtype=np.float32))),\n batch_size=batch_size)\n for batch_idx, (inputs, _) in enumerate(loader_this):\n inputs = Variable(inputs.cuda(), volatile=True) # pure inference mode.\n net(inputs)\n if (batch_idx + 1) % 20 == 0 and verbose:\n print(f'[{batch_idx}/{len(loader_this)}]')\n\n # then collect data\n features_all = OrderedDict()\n for blob_name, blob in callback_dict.items():\n features_all[blob_name] = np.concatenate(blob['output'])\n if verbose:\n print(blob_name, features_all[blob_name].shape)\n # maybe save some memory.\n del callback_dict\n # remove handles.\n remove_handles()\n return features_all\n\n\ndef process_one_case_wrapper(net_name_this, net_this, dataset_np_this, grp_name,\n setting_this, bg_color, batch_size, file_to_save_input, file_to_save_feature):\n (helper_this, slicing_dict,\n blobs_to_extract, correspondence_func) = get_one_network_meta(net_name_this, setting_this['ec_size'])\n print(grp_name, blobs_to_extract)\n\n with h5py.File(file_to_save_feature) as f_feature:\n if grp_name not in f_feature:\n\n # then preproces dataset\n # wrap this in hdf5, so that loading can be a lot faster.\n # for why `ascontiguousarray`, see \n with h5py.File(file_to_save_input) as f_input:\n if grp_name not in f_input:\n dataset_preprocessed = preprocess_dataset(dataset_np_this, bg_color,\n input_size=helper_this.input_size,\n rescale_ratio=setting_this['scale'])\n f_input.create_dataset(grp_name, data=dataset_preprocessed, compression=\"gzip\")\n f_input.flush()\n print(f'{grp_name} input computation done')\n else:\n dataset_preprocessed = f_input[grp_name][...]\n print(f'{grp_name} input computation done before')\n dataset_preprocessed = np.ascontiguousarray(dataset_preprocessed)\n\n print(dataset_preprocessed.shape)\n\n features_all = extract_features_one_case(net_this, dataset_preprocessed,\n blobs_to_extract, correspondence_func, slicing_dict, batch_size)\n for blob_idx, blob_data in enumerate(features_all.values()):\n f_feature.create_dataset(f'{grp_name}/{blob_idx}', data=blob_data, compression=\"gzip\")\n f_feature.flush()\n print(f'{grp_name} feature extraction done')\n # save blob names\n f_feature[grp_name].attrs['blobs_to_extract'] = np.array([np.string_(x) for x in blobs_to_extract])\n else:\n print(f'{grp_name} feature extraction done before')\n","sub_path":"tang_jcompneuro/cnn_pretrained.py","file_name":"cnn_pretrained.py","file_ext":"py","file_size_in_byte":17036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532738552","text":"from array import array\nfrom glob import glob\nfrom math import *\nimport os.path\nfrom CMGTools.RootTools.utils.DeltaR import deltaR,deltaPhi\n\nimport os, ROOT\nif \"/smearer_cc.so\" not in ROOT.gSystem.GetLibraries(): \n ROOT.gROOT.ProcessLine(\".L %s/src/CMGTools/TTHAnalysis/python/plotter/smearer.cc+\" % os.environ['CMSSW_BASE']);\nif \"/mcCorrections_cc.so\" not in ROOT.gSystem.GetLibraries(): \n ROOT.gROOT.ProcessLine(\".L %s/src/CMGTools/TTHAnalysis/python/plotter/mcCorrections.cc+\" % os.environ['CMSSW_BASE']);\n\n\nclass MVAVar:\n def __init__(self,name,func,corrfunc=None):\n self.name = name\n self.var = array('f',[0.])\n self.func = func\n self.corrfunc = corrfunc\n def set(self,lep,ncorr): ## apply correction ncorr times\n self.var[0] = self.func(lep)\n if self.corrfunc:\n for i in range(ncorr):\n self.var[0] = self.corrfunc(self.var[0], lep.pdgId(),lep.pt(),lep.eta(),lep.mcMatchId,lep.mcMatchAny)\nclass MVATool:\n def __init__(self,name,xml,specs,vars):\n self.name = name\n self.reader = ROOT.TMVA.Reader(\"Silent\")\n self.specs = specs\n self.vars = vars\n for s in specs: self.reader.AddSpectator(s.name,s.var)\n for v in vars: self.reader.AddVariable(v.name,v.var)\n #print \"Would like to load %s from %s! \" % (name,xml)\n self.reader.BookMVA(name,xml)\n def __call__(self,lep,ncorr): ## apply correction ncorr times\n for s in self.specs: s.set(lep,ncorr)\n for s in self.vars: s.set(lep,ncorr)\n return self.reader.EvaluateMVA(self.name) \nclass CategorizedMVA:\n def __init__(self,catMvaPairs):\n self.catMvaPairs = catMvaPairs\n def __call__(self,lep,ncorr):\n for c,m in self.catMvaPairs:\n if c(lep): return m(lep,ncorr)\n return -99.\n\n_CommonSpect = [ \n]\n_CommonVars = [ \n MVAVar(\"neuRelIso := relIso - chargedIso/pt\",lambda x: x.relIso(dBetaFactor=0.5) - x.chargedHadronIso()/x.pt()), \n MVAVar(\"chRelIso := chargedIso/pt\",lambda x: x.chargedHadronIso()/x.pt()),\n MVAVar(\"jetDR_in := min(dr_in,0.5)\", lambda x : min(deltaR(x.eta(),x.phi(),x.jet.eta(),x.jet.phi()),0.5), corrfunc=ROOT.correctJetDRMC),\n MVAVar(\"jetPtRatio_in := min(ptf_in,1.5)\", lambda x : min(x.pt()/x.jet.pt(),1.5), corrfunc=ROOT.correctJetPtRatioMC),\n MVAVar(\"jetBTagCSV_in := max(CSV_in,0)\", lambda x : max( (x.jet.btag('combinedSecondaryVertexBJetTags') if hasattr(x.jet, 'btag') else -99) ,0.)),\n #MVAVar(\"jetDR_out := min(dr_out,5)\", lambda x : min(x.dr_out,5.)),\n #MVAVar(\"jetPtRatio_out := min(ptf_out,1.5)\", lambda x : min(x.ptf_out,1.5)),\n #MVAVar(\"jetBTagCSV_out := max(CSV_out,0)\", lambda x : max(x.CSV_out,0.)),\n MVAVar(\"sip3d\",lambda x: x.sip3D(), corrfunc=ROOT.scaleSip3dMC),\n]\n\n_MuonVars = [\n MVAVar(\"dxy := log(abs(dxy))\",lambda x: log(abs(x.dxy())), corrfunc=ROOT.scaleDxyMC),\n MVAVar(\"dz := log(abs(dz))\", lambda x: log(abs(x.dz())), corrfunc=ROOT.scaleDzMC),\n]\n\n_ElectronVars = [\n MVAVar(\"mvaId\",lambda x: x.mvaNonTrigV0()),\n MVAVar(\"innerHits\",lambda x: x.numberOfHits()),\n]\n\n\nclass LeptonMVA:\n def __init__(self, basepath, isMC):\n global _CommonVars, _CommonSpect, _ElectronVars\n self._isMC = isMC\n self.mu = CategorizedMVA([\n ( lambda x: x.pt() <= 15 and abs(x.eta()) < 1.5 , MVATool(\"BDTG\",basepath%\"mu_pteta_low_b\", _CommonSpect,_CommonVars+_MuonVars) ),\n ( lambda x: x.pt() <= 15 and abs(x.eta()) >= 1.5 , MVATool(\"BDTG\",basepath%\"mu_pteta_low_e\", _CommonSpect,_CommonVars+_MuonVars) ),\n ( lambda x: x.pt() > 15 and abs(x.eta()) < 1.5 , MVATool(\"BDTG\",basepath%\"mu_pteta_high_b\",_CommonSpect,_CommonVars+_MuonVars) ),\n ( lambda x: x.pt() > 15 and abs(x.eta()) >= 1.5 , MVATool(\"BDTG\",basepath%\"mu_pteta_high_e\",_CommonSpect,_CommonVars+_MuonVars) ),\n ])\n self.el = CategorizedMVA([\n ( lambda x: x.pt() <= 10 and abs(x.eta()) < 0.8 , MVATool(\"BDTG\",basepath%\"el_pteta_low_cb\", _CommonSpect,_CommonVars+_ElectronVars) ),\n ( lambda x: x.pt() <= 10 and abs(x.eta()) >= 0.8 and abs(x.eta()) < 1.479 , MVATool(\"BDTG\",basepath%\"el_pteta_low_fb\", _CommonSpect,_CommonVars+_ElectronVars) ),\n ( lambda x: x.pt() <= 10 and abs(x.eta()) >= 1.479 , MVATool(\"BDTG\",basepath%\"el_pteta_low_ec\", _CommonSpect,_CommonVars+_ElectronVars) ),\n ( lambda x: x.pt() > 10 and abs(x.eta()) < 0.8 , MVATool(\"BDTG\",basepath%\"el_pteta_high_cb\",_CommonSpect,_CommonVars+_ElectronVars) ),\n ( lambda x: x.pt() > 10 and abs(x.eta()) >= 0.8 and abs(x.eta()) < 1.479 , MVATool(\"BDTG\",basepath%\"el_pteta_high_fb\",_CommonSpect,_CommonVars+_ElectronVars) ),\n ( lambda x: x.pt() > 10 and abs(x.eta()) >= 1.479 , MVATool(\"BDTG\",basepath%\"el_pteta_high_ec\",_CommonSpect,_CommonVars+_ElectronVars) ),\n ])\n def __call__(self,lep,ncorr=0):\n if abs(lep.pdgId()) == 11: return self.el(lep,ncorr)\n elif abs(lep.pdgId()) == 13: return self.mu(lep,ncorr)\n else: return -99\n def addMVA(self,lep):\n if self._isMC:\n lep.mvaValue = self(lep,1)\n lep.mvaNoCorr = self(lep,0)\n lep.mvaDoubleCorr = self(lep,2)\n else:\n lep.mvaValue = self(lep,0)\n\n","sub_path":"CMGTools/TTHAnalysis/python/leptonMVA.py","file_name":"leptonMVA.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"431150572","text":"import json\nimport logging\n\nimport requests\nfrom django.conf import settings\nfrom ..decorators import run_async\n\nlogger = logging.getLogger(__name__)\n\n\nclass KgxClient(object):\n \"\"\"KG-Xpress Client\"\"\"\n def __init__(self, base_url, username, password, origin_zip_code):\n self.auth = (username, password)\n self.origin_zip_code = origin_zip_code\n self.base_url = base_url\n self.headers = {'Content-Type': 'application/json'}\n\n @run_async\n def check_rate(self, zip_code, weight):\n url = '%s/check_rate' % (self.base_url,)\n params = {\n \"origin_zipcode\": self.origin_zip_code,\n \"destination_zipcode\": zip_code,\n \"weight\": weight\n }\n\n return self.kgx_client(url, self.headers, params, 'post')\n\n @run_async\n def create_order(self, order, weight):\n url = '%s/create_order' % (self.base_url,)\n pickup_type = \"reg\"\n\n params = {\n \"web_order_id\": order.number,\n \"sender\": settings.SHIPPING_SENDER,\n \"origin\": settings.SHIPPING_ORIGIN,\n \"recipient\": {\n \"name\": order.shipping_address.name,\n \"mobile\": \"%d%d\" % (\n order.shipping_address.phone_number.country_code,\n order.shipping_address.phone_number.national_number),\n \"email\": order.email\n },\n \"destination\": {\n \"address\": order.shipping_address.summary,\n \"city\": order.shipping_address.regency_district.name,\n \"state\": order.shipping_address.province.name,\n \"country\": order.shipping_address.country.printable_name,\n \"postcode\": order.shipping_address.postcode\n },\n \"package\": {\n \"quantity\": order.num_items,\n \"size\": \"Motorcycle\",\n \"weight\": weight\n },\n \"pickup_type\": pickup_type\n }\n\n return self.kgx_client(url, self.headers, params, 'post')\n\n @run_async\n def get_order_history(self, order_id):\n url = '%s/get_order_history' % (self.base_url,)\n params = {\n \"web_order_id\": order_id\n }\n\n return self.kgx_client(url, self.headers, params, 'get')\n\n def kgx_client(self, url, headers, params, method):\n try:\n if method == 'post':\n r = requests.post(url, headers=headers, data=json.dumps(params), auth=self.auth)\n else:\n r = requests.get(url, headers=headers, params=params, auth=self.auth)\n response = r.json()\n if r.status_code != 200:\n result = {'status': r.status_code, 'message': response['error']['message'], 'data': None}\n else:\n result = {'status': r.status_code, 'message': 'Success', 'data': response}\n except:\n result = {'status': 500, 'message': 'Something wrong with the system!', 'data': None}\n\n return result\n\n\n","sub_path":"src/smesco/apps/partner_api/client/kgx.py","file_name":"kgx.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"579618548","text":"import os\nfrom shutil import copyfile\n\ndic_path = './VOC2012/ImageSets/Main'\nobject_categories = ['aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor']\ntrain_all = []\nval_all = []\n\nsource = './VOC2012/JPEGImages/'\n\n\ndef read_all():\n for i,str in enumerate(object_categories,long(1)):\n print(str)\n if not os.path.exists('train/'+str+'/'):\n os.makedirs('train/'+str+'/')\n if not os.path.exists('val/'+str+'/'):\n os.makedirs('val/'+str+'/')\n\n # train\n f = open(dic_path+\"/\"+str+'_train.txt')\n iter_f = iter(f)\n for line in iter_f:\n if(int((line[12:14])) == 1):\n line = line[0:11]\n copyfile(source+line+'.jpg','train/'+str+'/'+line+'.jpg')\n\n\n # val\n f = open(dic_path+\"/\"+str+'_val.txt')\n iter_f = iter(f)\n for line in iter_f:\n if(int((line[12:14])) == 1):\n line = line[0:11]\n copyfile(source+line+'.jpg','val/'+str+'/'+line+'.jpg')\n\n\nread_all()\n# print(train_all)","sub_path":"create_pascal_voc.py","file_name":"create_pascal_voc.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"384824881","text":"import pandas as pd\nfrom unittest2 import TestCase # or `from unittest import ...` if on Python 3.4+\nimport category_encoders.tests.test_utils as tu\nimport numpy as np\n\nimport category_encoders as encoders\n\n\nnp_X = tu.create_array(n_rows=100)\nnp_X_t = tu.create_array(n_rows=50, extras=True)\nnp_y = np.random.randn(np_X.shape[0]) > 0.5\nnp_y_t = np.random.randn(np_X_t.shape[0]) > 0.5\nX = tu.create_dataset(n_rows=100)\nX_t = tu.create_dataset(n_rows=50, extras=True)\ny = pd.DataFrame(np_y)\ny_t = pd.DataFrame(np_y_t)\n\n\nclass TestTargetEncoder(TestCase):\n\n def test_target_encoder(self):\n\n enc = encoders.TargetEncoder(verbose=1, smoothing=2, min_samples_leaf=2)\n enc.fit(X, y)\n tu.verify_numeric(enc.transform(X_t))\n tu.verify_numeric(enc.transform(X_t, y_t))\n\n def test_target_encoder_fit_HaveConstructorSetSmoothingAndMinSamplesLeaf_ExpectUsedInFit(self):\n k = 2\n f = 10\n binary_cat_example = pd.DataFrame(\n {'Trend': ['UP', 'UP', 'DOWN', 'FLAT', 'DOWN', 'UP', 'DOWN', 'FLAT', 'FLAT', 'FLAT'],\n 'target': [1, 1, 0, 0, 1, 0, 0, 0, 1, 1]})\n encoder = encoders.TargetEncoder(cols=['Trend'], min_samples_leaf=k, smoothing=f)\n encoder.fit(binary_cat_example, binary_cat_example['target'])\n trend_mapping = encoder.mapping['Trend']\n self.assertAlmostEqual(0.4125, trend_mapping['DOWN'], delta=1e-4)\n self.assertEqual(0.5, trend_mapping['FLAT'])\n self.assertAlmostEqual(0.5874, trend_mapping['UP'], delta=1e-4)\n\n def test_target_encoder_fit_transform_HaveConstructorSetSmoothingAndMinSamplesLeaf_ExpectCorrectValueInResult(self):\n k = 2\n f = 10\n binary_cat_example = pd.DataFrame(\n {'Trend': ['UP', 'UP', 'DOWN', 'FLAT', 'DOWN', 'UP', 'DOWN', 'FLAT', 'FLAT', 'FLAT'],\n 'target': [1, 1, 0, 0, 1, 0, 0, 0, 1, 1]})\n encoder = encoders.TargetEncoder(cols=['Trend'], min_samples_leaf=k, smoothing=f)\n result = encoder.fit_transform(binary_cat_example, binary_cat_example['target'])\n values = result['Trend'].values\n self.assertAlmostEqual(0.5874, values[0], delta=1e-4)\n self.assertAlmostEqual(0.5874, values[1], delta=1e-4)\n self.assertAlmostEqual(0.4125, values[2], delta=1e-4)\n self.assertEqual(0.5, values[3])\n\n def test_target_encoder_fit_transform_HaveCategoricalColumn_ExpectCorrectValueInResult(self):\n k = 2\n f = 10\n binary_cat_example = pd.DataFrame(\n {'Trend': pd.Categorical(['UP', 'UP', 'DOWN', 'FLAT', 'DOWN', 'UP', 'DOWN', 'FLAT', 'FLAT', 'FLAT'],\n categories=['UP', 'FLAT', 'DOWN']),\n 'target': [1, 1, 0, 0, 1, 0, 0, 0, 1, 1]})\n encoder = encoders.TargetEncoder(cols=['Trend'], min_samples_leaf=k, smoothing=f)\n result = encoder.fit_transform(binary_cat_example, binary_cat_example['target'])\n values = result['Trend'].values\n self.assertAlmostEqual(0.5874, values[0], delta=1e-4)\n self.assertAlmostEqual(0.5874, values[1], delta=1e-4)\n self.assertAlmostEqual(0.4125, values[2], delta=1e-4)\n self.assertEqual(0.5, values[3])\n\n def test_target_encoder_noncontiguous_index(self):\n data = pd.DataFrame({'x': ['a', 'b', np.nan, 'd', 'e'], 'y': range(5)}).dropna()\n result = encoders.TargetEncoder(cols=['x']).fit_transform(data[['x']], data['y'])\n self.assertTrue(np.allclose(result, 2.0))\n\n","sub_path":"category_encoders/tests/test_target_encoder.py","file_name":"test_target_encoder.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"85692674","text":"import sys\nimport signal\nimport argparse\nfrom edman import DB, File\nfrom action import Action\n\n# Ctrl-Cを押下された時の対策\nsignal.signal(signal.SIGINT, lambda sig, frame: sys.exit('\\n'))\n\n# コマンドライン引数処理\nparser = argparse.ArgumentParser(\n description='ファイルを実験データからダウンロードするスクリプト')\n# parser.add_argument('-c', '--collection', help='collection name.')\nparser.add_argument('objectid', help='objectid str.')\nparser.add_argument('path', help='Download Dir path.')\n# クエリは structureがembの時だけ\nparser.add_argument('-q', '--query', default=None,\n help='Ref is ObjectId or Emb is query list strings.')\nparser.add_argument('-i', '--inifile', help='DB connect file path.')\n\n# 引数を付けなかった場合はヘルプを表示して終了する\nif len(sys.argv) == 1:\n parser.parse_args([\"-h\"])\n sys.exit(0)\nargs = parser.parse_args()\n\ntry:\n # iniファイル読み込み\n con = Action.reading_config_file(args.inifile)\n\n db = DB(con)\n file = File(db.get_db)\n\n # 対象oidの所属コレクションを自動的に取得 ※動作が遅い場合は使用しないこと\n collection = db.find_collection_from_objectid(args.objectid)\n\n # ドキュメント構造の取得\n structure = db.get_structure(collection, args.objectid)\n\n # クエリの変換\n query = Action.file_query_eval(args.query, structure)\n\n # ファイル名一覧を取得\n file_names = file.get_file_names(collection, args.objectid, structure,\n query)\n if not file_names:\n sys.exit('ファイルは存在しません')\n\n file_oids = []\n # ファイル名一覧を画面表示&file_oid用リスト作成\n for idx, (oid, filename) in enumerate(file_names.items()):\n print('(' + str(idx) + ')', filename, oid)\n file_oids.append(oid)\n\n # 複数ファイルの場合、表示されている選択番号を入力\n if len(file_names) > 1:\n while True:\n selected_idx = input('0 - ' + str(len(file_names) - 1) + ' > ')\n if selected_idx.isdecimal() and (\n 0 <= int(selected_idx) < len(file_names)):\n break\n else:\n print('Required!')\n # ファイルが一つしかない場合は選択無しでDL\n elif len(file_names) == 1:\n selected_idx = 0\n else:\n sys.exit('インデックスが不正です')\n\n # 指定のディレクトリにダウンロード\n if file.download(file_oids[int(selected_idx)], args.path):\n print('DLしました')\n\nexcept Exception as e:\n tb = sys.exc_info()[2]\n sys.stderr.write(f'{type(e).__name__}: {e.with_traceback(tb)}\\n')\n sys.exit(1)\n","sub_path":"scripts/file_dl.py","file_name":"file_dl.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"434492865","text":"\"\"\"players table\n\nRevision ID: 4d63b7f2b118\nRevises: 327d1c7ea13e\nCreate Date: 2018-12-19 08:25:02.817262\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4d63b7f2b118'\ndown_revision = '327d1c7ea13e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('player',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=64), nullable=True),\n sa.Column('is_active', sa.Boolean(), nullable=True),\n sa.Column('is_available', sa.Boolean(), nullable=True),\n sa.Column('current_score', sa.Integer(), nullable=True),\n sa.Column('event_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['event_id'], ['event.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_player_current_score'), 'player', ['current_score'], unique=False)\n op.create_index(op.f('ix_player_is_active'), 'player', ['is_active'], unique=False)\n op.create_index(op.f('ix_player_is_available'), 'player', ['is_available'], unique=False)\n op.create_index(op.f('ix_player_name'), 'player', ['name'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_player_name'), table_name='player')\n op.drop_index(op.f('ix_player_is_available'), table_name='player')\n op.drop_index(op.f('ix_player_is_active'), table_name='player')\n op.drop_index(op.f('ix_player_current_score'), table_name='player')\n op.drop_table('player')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/4d63b7f2b118_players_table.py","file_name":"4d63b7f2b118_players_table.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"510396273","text":"from dataclasses import dataclass, field\nfrom functools import partial\nfrom typing import Set, Tuple, Dict, Callable, Any\n\nfrom .sgrecord import SgRecord\nfrom sglogging import SgLogSetup\n\n_log = SgLogSetup().get_logger('SgRecordID')\n\n\n@dataclass(frozen=True)\nclass SgRecordID:\n id_fields: Set[SgRecord.Headers.HeaderUnion] = field(default_factory=set)\n fail_on_empty_field: bool = False\n fail_on_empty_id: bool = True\n transformations: Dict[SgRecord.Headers.HeaderUnion, Tuple[str, Callable[[Any], str]]] = field(default_factory=dict)\n\n def with_truncate(self, header: SgRecord.Headers.HeaderUnion, nums_after_decimal: int) -> 'SgRecordID':\n def truncate_decimal(after_decimal: int, value: Any) -> str:\n str_val = str(value)\n if '.' in str_val:\n i = str_val.index('.')\n return str_val[0:i+1+after_decimal]\n else:\n return value\n\n return self.__with_transform(header, partial(truncate_decimal, nums_after_decimal), identifier=f\".{nums_after_decimal}\")\n\n def __with_transform(self, header: SgRecord.Headers.HeaderUnion, fn: Callable[[Any], str], identifier: str) -> 'SgRecordID':\n if \"%\" in identifier or \":\" in identifier:\n raise ValueError(f\"Identifier {identifier} cannot contain the '%' or ':' characters\")\n\n upd_transforms = dict()\n upd_transforms.update(self.transformations.copy(), **{header: (identifier, fn)})\n return SgRecordID(id_fields=self.id_fields, transformations=upd_transforms)\n\n def generate_id(self, record: SgRecord) -> str:\n \"\"\"\n Generates a human-readable string identity for a record based on the provided fields.\n\n Fails with `ValueError` either when one of the fields is empty or marked missing,\n or else when composite identity is empty.\n \"\"\"\n rec_dict = record.as_dict()\n ident = \"\"\n for field in self.id_fields:\n value = rec_dict.get(field)\n if value and value != SgRecord.MISSING:\n transform = self.transformations.get(field)\n value = transform[1](value) if transform else value\n ident += f\"{field}:{value} \"\n elif self.fail_on_empty_field:\n raise ValueError(f\"Record identity field '{field}' cannot be empty or {SgRecord.MISSING}. Value: {value}\")\n\n if not ident:\n if self.fail_on_empty_id:\n raise ValueError(f\"Composite record identity '{self.__str__()}' is empty. Record: {record}\")\n else:\n _log.debug(f\"Composite record identity '{self.__str__()}' is empty. Record: {record}\")\n\n return ident\n\n def __str__(self) -> str:\n reprs = []\n for field in self.id_fields:\n transform = self.transformations.get(field)\n t_id = f\"%{transform[0]}\" if transform else \"\"\n reprs.append(f\"{field}{t_id}\")\n\n return \":\".join(reprs)\n\n\nclass RecommendedRecordIds:\n pass\n # PhoneNumberId = SgRecordID({SgRecord.Headers.PHONE})\n # GeoSpatialId = SgRecordID({SgRecord.Headers.LATITUDE, SgRecord.Headers.LONGITUDE})\\\n # .with_truncate(SgRecord.Headers.LATITUDE, 3)\\\n # .with_truncate(SgRecord.Headers.LONGITUDE, 3)\n # StoreNumberId = SgRecordID({SgRecord.Headers.STORE_NUMBER})\n # PageUrlId = SgRecordID({SgRecord.Headers.PAGE_URL})\n # StoreNumAndPageUrlId = SgRecordID({SgRecord.Headers.STORE_NUMBER, SgRecord.Headers.PAGE_URL})\n\n\n","sub_path":"sgscrape/sgrecord_id.py","file_name":"sgrecord_id.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"559902928","text":"import cv2\nimport numpy as np\nimport pygame.mixer\nimport time\nimport threading\n\nMAX_WIDTH = 800\nMAX_HEIGHT = 480\nSIGN_HEIGHT = (int)(MAX_HEIGHT / 3)\nSIGN_WIDTH = SIGN_HEIGHT\nGUIDE_WIDTH = MAX_WIDTH - SIGN_WIDTH\nGUIDE_HEIGHT = MAX_HEIGHT\nOIL_TEXT_WIDTH = 200\nOIL_TEXT_MARGIN = 100\nLIST_MARGIN = 60\nLIST_HEIGHT = 93\nLIST_WIDTH = 217\n\ndef soundPlay():\n pygame.mixer.music.play(1)\n time.sleep(10)\n pygame.mixer.music.stop()\n\ndef windowInit(lang):\n #cv2.namedWindow('drive', cv2.WINDOW_AUTOSIZE)\n cv2.namedWindow('drive', cv2.WINDOW_NORMAL)\n cv2.setWindowProperty('drive', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\n \n pygame.init()\n pygame.mixer.music.load(lang + '/voice/turn.mp3')\n\n images = {}\n images['OIL'] = cv2.imread('./img/oil/regular.png')\n images['OILTEXT'] = cv2.imread(lang + '/img/refuel.png')\n images['LEFT'] = cv2.imread('./img/turn_left.png')\n images['RIGHT'] = cv2.imread('./img/turn_right.png')\n images['STOP'] = cv2.imread(lang + '/img/stop.png')\n images['SLOW'] = cv2.imread(lang + '/img/slow.png')\n images['OVER'] = cv2.imread(lang + '/img/overtaking.png')\n images['ATTENTION'] = cv2.imread(lang + '/img/attention.png')\n images['DOOR'] = cv2.imread(lang + '/img/door.png')\n\n return images\n\ndef pastePicture(background, src, x, y):\n \n row, col, channel = src.shape\n \n graySrc = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)\n ret, mask = cv2.threshold(graySrc, 10, 255, cv2.THRESH_BINARY)\n mask_inv = cv2.bitwise_not(mask)\n \n roi = background[0 + y : row + y, 0 + x : col + x]\n \n bg = cv2.bitwise_and(roi, roi, mask = mask_inv)\n srcFg = cv2.bitwise_and(src, src, mask = mask)\n dst = cv2.add(bg, srcFg)\n background[0 + y : row + y, 0 + x : col + x] = dst\n\ndef makeWindow(base, images, state_string):\n turn, stop, slow, over = state_string.split(',')\n \n #main area \n if turn == 'left':\n pastePicture(base, images['LEFT'], SIGN_WIDTH, 0)\n soundThread = threading.Thread(target = soundPlay)\n if soundThread.is_alive == False:\n soundThread.start()\n \n elif turn == 'right':\n pastePicture(base, images['RIGHT'], SIGN_WIDTH, 0)\n soundThread = threading.Thread(target = soundPlay)\n if soundThread.is_alive == False:\n soundThread.start()\n \n else :\n pastePicture(base, images['ATTENTION'], SIGN_WIDTH, 0)\n \n #sign area\n if stop == 'stop':\n pastePicture(base, images['STOP'], 0, 0)\n \n if over == 'over':\n pastePicture(base, images['OVER'], 0, SIGN_HEIGHT)\n \n if slow == 'slow':\n pastePicture(base, images['SLOW'], 0, SIGN_HEIGHT * 2)\n \n cv2.imshow('drive', base)\n\ndef fuelWindow(base, images):\n pastePicture(base, images['OIL'], 0, 0)\n pastePicture(base, images['OILTEXT'], MAX_WIDTH - OIL_TEXT_WIDTH - OIL_TEXT_MARGIN, OIL_TEXT_MARGIN)\n \n cv2.imshow('drive', base)\n \ndef langSelectWindow(bg_origin, frame, lang):\n bg = bg_origin.copy()\n if lang == 'en':\n pastePicture(bg, frame, LIST_WIDTH, LIST_MARGIN + LIST_HEIGHT * 0)\n elif lang == 'zh-tw':\n pastePicture(bg, frame, LIST_WIDTH, LIST_MARGIN + LIST_HEIGHT * 1)\n elif lang == 'zh-cn':\n pastePicture(bg, frame, LIST_WIDTH, LIST_MARGIN + LIST_HEIGHT * 2)\n elif lang == 'ko':\n pastePicture(bg, frame, LIST_WIDTH, LIST_MARGIN + LIST_HEIGHT * 3)\n \n cv2.imshow('drive', bg)\n cv2.waitKey(1)\n \n","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"67190107","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server.models.wallet import Wallet # noqa: F401,E501\nfrom swagger_server import util\n\n\nclass Balance(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n def __init__(self, balance: int=None, wallet: Wallet=None): # noqa: E501\n \"\"\"Balance - a model defined in Swagger\n\n :param balance: The balance of this Balance. # noqa: E501\n :type balance: int\n :param wallet: The wallet of this Balance. # noqa: E501\n :type wallet: Wallet\n \"\"\"\n self.swagger_types = {\n 'balance': int,\n 'wallet': Wallet\n }\n\n self.attribute_map = {\n 'balance': 'balance',\n 'wallet': 'wallet'\n }\n self._balance = balance\n self._wallet = wallet\n\n @classmethod\n def from_dict(cls, dikt) -> 'Balance':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The balance of this Balance. # noqa: E501\n :rtype: Balance\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def balance(self) -> int:\n \"\"\"Gets the balance of this Balance.\n\n\n :return: The balance of this Balance.\n :rtype: int\n \"\"\"\n return self._balance\n\n @balance.setter\n def balance(self, balance: int):\n \"\"\"Sets the balance of this Balance.\n\n\n :param balance: The balance of this Balance.\n :type balance: int\n \"\"\"\n if balance is None:\n raise ValueError(\"Invalid value for `balance`, must not be `None`\") # noqa: E501\n\n self._balance = balance\n\n @property\n def wallet(self) -> Wallet:\n \"\"\"Gets the wallet of this Balance.\n\n\n :return: The wallet of this Balance.\n :rtype: Wallet\n \"\"\"\n return self._wallet\n\n @wallet.setter\n def wallet(self, wallet: Wallet):\n \"\"\"Sets the wallet of this Balance.\n\n\n :param wallet: The wallet of this Balance.\n :type wallet: Wallet\n \"\"\"\n if wallet is None:\n raise ValueError(\"Invalid value for `wallet`, must not be `None`\") # noqa: E501\n\n self._wallet = wallet\n","sub_path":"goldrush/examples/stub_server/swagger_server/models/balance.py","file_name":"balance.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279606478","text":"from htmlReportWriters import BaseHTMLReportWriter\r\n\r\n\r\n# Should have a base to share between the writers.\r\nclass ReportHTMLWriterTransactions(BaseHTMLReportWriter):\r\n def __init__(self, fh):\r\n self.file_handle = fh\r\n\r\n def write(self, list_of_list_of_dicts):\r\n \"\"\"\r\n writes the report.\r\n :param list_of_list_of_dicts: each file generates a list of dicts. Dicts have only 2 keys.\r\n Thus all files are combined into a list of lists.\r\n :return: void\r\n \"\"\"\r\n self.create_html_head()\r\n self.create_html_body()\r\n\r\n self.create_html_table()\r\n hdr_list = [\"File\", \"Result line\", \"Ctor line\", \"Commit line\"]\r\n self.create_table_header(hdr_list)\r\n total_result = 0\r\n trans_result = 0\r\n for list_of_dicts_tup in list_of_list_of_dicts:\r\n file_path = list_of_dicts_tup[0]\r\n list_of_dicts = list_of_dicts_tup[1]\r\n for info_dict in list_of_dicts:\r\n total_result += 1\r\n line = info_dict[\"line\"]\r\n ctor_str = info_dict.get(\"ctor\", \"none\")\r\n if info_dict.get(\"ctor\") is not None:\r\n trans_result += 1\r\n commit_str = info_dict.get(\"commit\", \"none\")\r\n self.write_results(file_path, info_dict, line, ctor_str, commit_str)\r\n self.end_html_table()\r\n self.file_handle.write(\"

{trans} Transactions out of {total} results. Percent: {percent}

\\n\".format(\r\n trans=trans_result, total=total_result,\r\n percent=round((trans_result/total_result)*100, 2)\r\n ))\r\n self.end_html_body()\r\n self.end_html()\r\n\r\n def write_results(self, file_path, info_dict, line, ctor, commit):\r\n self.start_table_row()\r\n self.add_table_column(file_path)\r\n self.add_table_column(line)\r\n self.add_table_column(ctor)\r\n self.add_table_column(commit)\r\n self.end_table_row()\r\n\r\n","sub_path":"reportHTMLTransactions.py","file_name":"reportHTMLTransactions.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"5386903","text":"# -------------------------------- #\n# #\n# Requires a_simpleAnalysis #\n# Requires c_advancedAnalysis #\n# Requires d_probabilisticAnalysis #\n# #\n# -------------------------------- #\n\nimport os\nimport sys\nimport copy\n\ndirectory = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.dirname(os.path.dirname(directory)))\nsys.path.append(os.path.dirname(directory))\nimport tools\nimport settings\n\nmaskedCollection = tools.maskedCollection.MaskedCollection(settings.database['format'])\nmaskedCollection.loadDirectory( \n settings.database['directory'], \n settings.database['format'],\n settings.histograms['selections'],\n)\n\nadvancedCollection = copy.deepcopy(maskedCollection)\nprobabilisticCollection = copy.deepcopy(maskedCollection)\n\nmaskedCollection.loadMasks(settings.simpleAnalysis['directory'])\nadvancedCollection.loadMasks(settings.advancedAnalysis['directory'])\nprobabilisticCollection.loadMasks(settings.probabilisticAnalysis['directory'])\n\nprint('Advanced analysis compared to simple analysis')\nprint(tools.compare.compare(maskedCollection, advancedCollection))\n\nprint('Probabilistic analysis compared to simple analysis')\nprint(tools.compare.compare(maskedCollection, probabilisticCollection))\n","sub_path":"TP1/Scripts/e_comparison.py","file_name":"e_comparison.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"381692092","text":"# -*- coding: utf-8 -*-\nimport subprocess\nfrom classes.play.IPlay import IPlay\nfrom time import sleep, time\nimport env_variables\nimport logging, logging.config\nlogging.config.dictConfig(env_variables.LOGGING)\n\nclass PlaySlide(IPlay):\n\n def __init__(self, display_duration):\n self.display_duration = display_duration\n\n def play(self, play_thread, singleContentSlide):\n \"\"\" \n function that displays the slide using feh command during \n display_duration number of timer_in_seconds\n \"\"\"\n try:\n logging.info(\"slide montre: %s\" % singleContentSlide.filepath)\n command = \"export DISPLAY=:0;/usr/bin/feh --no-fehbg --bg-scale '\" + singleContentSlide.filepath +\"'\"\n return_code = subprocess.call(command, shell=True)\n if self.display_duration != 0:\n if return_code == 0:\n target_time = time() + self.display_duration\n while time() < target_time and not play_thread.stoprequest.isSet() \\\n and not play_thread.nextrequest.isSet() and not play_thread.previousrequest.isSet():\n sleep(0.5)\n else:\n raise RuntimeError(\"error when displaying the slide\")\n\n except Exception as e:\n logging.error(\"command is: %s\" % command)\n logging.error(\"display slide return code: %i\" % return_code)\n logging.error('image display failed: %s' % str(e))","sub_path":"classes/play/PlaySlide.py","file_name":"PlaySlide.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"304905080","text":"import logging\n\nfrom tak.config import Module\n\n\ndef get_server_logger(level_=logging.INFO):\n \"\"\" Creates main server logger \"\"\"\n formatter = logging.Formatter('[%(levelname)s] %(asctime)s: %(message)s')\n\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n\n logger = logging.getLogger('tak_server')\n logger.addHandler(handler)\n logger.setLevel(level_)\n\n return logger\n\n\ndef get_http_logger(name, format_, level_, file_log):\n \"\"\" Creates HTTP logger with format from config \"\"\"\n logger = logging.getLogger(name)\n logger.setLevel(level_)\n\n formatter = logging.Formatter(format_, style='{')\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(formatter)\n logger.addHandler(stream_handler)\n\n if file_log is not None:\n file_handler = logging.FileHandler(filename=file_log)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n return logger\n\n\nclass LogModule(Module):\n \"\"\" Provides access_log and error_log loggers instances for each VirtualHost \"\"\"\n def process_config(self, config):\n self.validate(\n config=config,\n name='log.access_log.format',\n default='{ip} [{asctime}] \"{request.method} {request.uri} {request.http_version}\" '\n '{response.status_code} {response_length} \"{request.referer}\" '\n '\"{request.user-agent}\"'\n )\n\n access_log = None\n if 'log.access_log.path' in config:\n access_log = config['log.access_log.path']\n\n config['log.access_log.level'] = logging.INFO\n config['log.access_log'] = get_http_logger('{0}.access_log'.format(config.name),\n config['log.access_log.format'],\n config['log.access_log.level'],\n access_log)\n\n self.validate(config=config, name='log.error_log.format', default='{ip} [{asctime}] {message}')\n\n error_log = None\n if 'log.error_log.path' in config:\n error_log = config['log.error_log.path']\n\n config['log.error_log.level'] = logging.INFO\n config['log.error_log'] = get_http_logger('{0}.error_log'.format(config.name),\n config['log.error_log.format'],\n config['log.error_log.level'],\n error_log)\n","sub_path":"tak/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"626060058","text":"# Autor: María Fernanda García Gastélum A01376181, grupo 03\r\n# Completar misión 8\r\n\r\n\r\ndef combinarLetras(cadena):\r\n may = cadena.upper() # Convierte en mayúscula\r\n min = cadena.lower() # Convierte en minúscula\r\n nuevaCadena = \"\" # Empieza acumulador\r\n if len(cadena) % 2 == 0: # determinar si el número de letras en la cadena es par\r\n for letra in range(0, len(cadena), 2):\r\n nuevaCadena = nuevaCadena + may[letra] + min[letra + 1] # Acumular en la nueva cadena\r\n else:\r\n cadenaImpar = cadena + \" \" # No funcionaba con numero impar, agregar un espacio para volverlo par\r\n minImpar = cadenaImpar.lower()\r\n for letra in range(0, len(cadenaImpar), 2):\r\n nuevaCadena = nuevaCadena + may[letra] + minImpar[letra + 1]\r\n longitud = len(nuevaCadena) - 1\r\n if \" \" in nuevaCadena[longitud]:\r\n nuevaCadena = nuevaCadena[:longitud:]\r\n\r\n return nuevaCadena\r\n\r\n\r\ndef contieneLasVocales(cadena):\r\n # Empezar contador para cada vocal, si todas las vocales son mayor a 1, se cumple la condicion\r\n a = 0\r\n e = 0\r\n i = 0\r\n o = 0\r\n u = 0\r\n for vocal in cadena:\r\n # No puedo poner todas las vocales en un if porque no funcionaría\r\n if vocal == \"a\" or vocal == \"A\" or vocal == \"á\" or vocal == \"Á\": # Así no importa si es mayúscula o minúscula o si tiene acentos\r\n a += 1\r\n elif vocal == \"e\" or vocal == \"E\" or vocal == \"é\" or vocal == \"É\":\r\n e += 1\r\n elif vocal == \"i\" or vocal == \"I\" or vocal == \"í\" or vocal == \"Í\":\r\n i += 1\r\n elif vocal == \"o\" or vocal == \"O\" or vocal == \"ó\" or vocal == \"Ó\":\r\n o += 1\r\n elif vocal == \"u\" or vocal == \"U\" or vocal == \"ú\" or vocal == \"Ú\":\r\n u += 1\r\n if a >= 1 and e >= 1 and i >= 1 and o >= 1 and u >= 1: # Verificar que tenga todas las vocales\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef formarNombreUsuario(nombre, apellido, matricula):\r\n nombreMin = nombre.lower() # convierte en minuscula\r\n apellidoMin = apellido.lower()\r\n nuevaMatricula = str(matricula)\r\n usuario = nombreMin[0:3:1] + apellidoMin[0:3:1] + nuevaMatricula[4::]\r\n return usuario\r\n\r\n\r\ndef esCorrecto(nombreCompleto):\r\n nombre = nombreCompleto\r\n separados = nombre.split() # esto separa las palabras\r\n resultado = True\r\n for palabra in separados:\r\n # definir cual es la primera letra de cada palabra\r\n primeraLetra = palabra[0:1:]\r\n otrasLetras = palabra[1::]\r\n if primeraLetra.islower() or otrasLetras.isupper():\r\n resultado = False\r\n\r\n return resultado\r\n\r\n\r\ndef traducirTelefono(numero):\r\n # hay que hacer que el número se vuelva string\r\n nNumero = str(numero)\r\n # directorio para telefono\r\n n2 = [\"A\", \"B\", \"C\"]\r\n n3 = [\"D\", \"E\", \"F\"]\r\n n4 = [\"G\", \"H\", \"I\"]\r\n n5 = [\"J\", \"K\", \"L\"]\r\n n6 = [\"M\", \"N\", \"O\"]\r\n n7 = [\"P\", \"Q\", \"R\", \"S\"]\r\n n8 = [\"T\", \"U\", \"V\"]\r\n n9 = [\"W\", \"X\", \"Y\", \"Z\"]\r\n # Empieza acumulador\r\n nuevoNumero = \"01800\"\r\n for n in nNumero[0::]:\r\n # Ver si la letra está dentro de nuestro directorio y su equivalente en número\r\n if n in n2:\r\n # Sumar esto al acumulador\r\n nuevoNumero += \"2\"\r\n elif n in n3:\r\n nuevoNumero += \"3\"\r\n elif n in n4:\r\n nuevoNumero += \"4\"\r\n elif n in n5:\r\n nuevoNumero += \"5\"\r\n elif n in n6:\r\n nuevoNumero += \"6\"\r\n elif n in n7:\r\n nuevoNumero += \"7\"\r\n elif n in n8:\r\n nuevoNumero += \"8\"\r\n elif n in n9:\r\n nuevoNumero += \"9\"\r\n elif n == \"-\":\r\n nuevoNumero += \"-\"\r\n return nuevoNumero\r\n\r\n","sub_path":"Misión_08.py","file_name":"Misión_08.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"516808462","text":"\"\"\"\nビュークラス\nV120_userKoshn\n質問作成ページ用View\nエラーフラグ:0(正常終了),1(業務エラー),2(システムエラー)\nflg_return:0(render),1(redirect)\n\nflg_return==0の時、「template」「context」必須\nflg_return==1の時、「path_name」必須\n\n\"\"\"\n\nimport datetime\nfrom django.urls import reverse\nfrom . import (C010_Const,C030_MessageUtil,\n S110_UpdateTask,\n)\n\ndef main(request,urlID,seq):\n #--View共通----------------------------------------------\n #戻り値用の変数宣言\n flg_return = \"\"\n template = ''\n context = {}\n path_name = ''\n #-------------------------------------------------------\n try:\n if request.method == 'POST':\n #POSTの場合\n \"\"\"\n POST時の処理を書く。\n パターンに応じてflg_returnの値を設定する。\n bottunパターンによって処理を分けたりもするかも。\n 例は、redirect\n \"\"\"\n errflg = \"0\"\n #更新ボタンの場合\n #サービスのパラメータをリクエストから取得する--------------------------------------\n projectID = request.session['projectID']\n updUserID = \"SYSTEM000000000000\"\n #loginKbn = \"0\"\n #サービスのパラメータをリクエストから取得する--------------------------------------\n #--S110-------------------------------------------------------------------------\n json_S110 = S110_UpdateTask.updateDelflg(projectID,seq,updUserID)\n #個々の値を取得\n flg_S110 = json_S110[\"json_CommonInfo\"][\"errflg\"]\n list_msgInfo_S110 = json_S110[\"json_CommonInfo\"][\"list_msgInfo\"]\n #str_userID_S160 = json_S110[\"str_userID\"]\n #メッセージ格納\n C030_MessageUtil.setMessageList(request,list_msgInfo_S110)\n #-------------------------------------------------------------------------------\n flg_return = \"1\"\n path_name = C010_Const.APP_NAME_DEFAULT + ':projectTop'\n else:\n #POST以外の場合\n \"\"\"\n POST以外時の処理を書く。\n パターンに応じてflg_returnの値を設定する。\n bottunパ��ーンによって処理を分けたりもするかも。\n 例は、render\n \"\"\"\n \n #戻り値用のjsonを作成\n json_view = {'flg_return':flg_return, 'template':template, 'context':context, 'path_name':path_name}\n return json_view\n #==例外処理==========================================================================================\n except Exception as e :\n #システムエラー共通処理\n C030_MessageUtil.systemErrorCommonMethod()\n raise\n #====================================================================================================\n\n","sub_path":"app001_projectManagement/process/V100_TaskDelete.py","file_name":"V100_TaskDelete.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"520389493","text":"from collections import deque\n\n\ndef bfs():\n value = deque()\n value.append(n)\n count = 0\n while True:\n for _ in range(len(value)):\n num = value.popleft()\n visit[num] = 1\n if num == k:\n return count\n if num + 1 <= k and not visit[num + 1]:\n value.append(num + 1)\n if num - 1 >= 0 and not visit[num - 1]:\n value.append(num - 1)\n if num * 2 <= 100000 and not visit[num * 2]:\n value.append(num * 2)\n count += 1\n\n\nn, k = map(int, input().split())\nvisit = [0]*100001\nif k < n:\n min_num = n - k\nelse:\n min_num = bfs()\nprint(min_num)","sub_path":"problemSolving/baekjoon/solved/python/bj_1697_숨바꼭질.py","file_name":"bj_1697_숨바꼭질.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"632808401","text":"# coding=utf-8\n# Copyright 2023 Google LLC and HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nConvert T5X checkpoint to PyTorch\n\nSteps:\n- Install gsutil according to https://cloud.google.com/storage/docs/gsutil_install\n- Get a T5X checkpoint at https://github.com/google-research/t5x/blob/main/docs/models.md#t5-11-checkpoints Example:\n `gsutil -m cp -r gs://t5-data/pretrained_models/t5x/t5_1_1_small $HOME/`\n- Create or download a corresponding config for the downloaded model. E.g. for T5 v1.1 small, you can use\n https://huggingface.co/google/t5-v1_1-small/blob/main/config.json\n- Convert:\n ```\n python3 convert_t5x_checkpoint_to_pytorch.py --t5x_checkpoint_path=$HOME/t5_1_1_small --config_file=config.json\\\n --pytorch_dump_path=$HOME/t5_1_1_small_pt\n ```\n\"\"\"\n\nimport argparse\nimport collections\n\nimport numpy as np\nimport torch\nfrom flax import traverse_util\nfrom t5x import checkpoints\n\nfrom transformers import MT5Config, UMT5EncoderModel, UMT5ForConditionalGeneration\nfrom transformers.utils import logging\n\n\nlogging.set_verbosity_info()\n\n\ndef t5x_relpos_bias_lookup(params, i, prefix):\n \"\"\"Returns the Relative Position Bias parameters of a layer. Does not transpose.\"\"\"\n return params[f\"{prefix}/{prefix}/relpos_bias/rel_embedding\"][:, i, :]\n\n\ndef t5x_attention_lookup(params, i, prefix, layer_name=\"attention\"):\n \"\"\"Returns the KOQV parameters of (self-)attention. Does not transpose.\"\"\"\n k_tmp = k_tmp = np.ascontiguousarray(params[f\"{prefix}/{prefix}/{layer_name}/key/kernel\"][:, i, :, :])\n k = k_tmp.reshape(k_tmp.shape[0], k_tmp.shape[1] * k_tmp.shape[2])\n o_tmp = np.ascontiguousarray(params[f\"{prefix}/{prefix}/{layer_name}/out/kernel\"][:, i, :, :])\n o = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1], o_tmp.shape[2])\n q_tmp = np.ascontiguousarray(params[f\"{prefix}/{prefix}/{layer_name}/query/kernel\"][:, i, :, :])\n q = q_tmp.reshape(q_tmp.shape[0], q_tmp.shape[1] * q_tmp.shape[2])\n v_tmp = np.ascontiguousarray(params[f\"{prefix}/{prefix}/{layer_name}/value/kernel\"][:, i, :, :])\n v = v_tmp.reshape(v_tmp.shape[0], v_tmp.shape[1] * v_tmp.shape[2])\n return k, o, q, v\n\n\ndef t5x_mlp_lookup(params, i, prefix, split_mlp_wi=False):\n \"\"\"Returns the MLP parameters of a layer. Does not transpose.\"\"\"\n if split_mlp_wi:\n wi_0 = params[f\"{prefix}/{prefix}/mlp/wi_0/kernel\"][:, i, :]\n wi_1 = params[f\"{prefix}/{prefix}/mlp/wi_1/kernel\"][:, i, :]\n wi = (wi_0, wi_1)\n else:\n wi = params[f\"{prefix}/{prefix}/mlp/wi/kernel\"][:, i, :]\n\n wo = params[f\"{prefix}/{prefix}/mlp/wo/kernel\"][:, i, :]\n return wi, wo\n\n\ndef t5x_layer_norm_lookup(params, i, prefix, layer_name):\n \"\"\"Returns the layer norm param of a layer.\"\"\"\n return params[f\"{prefix}/{prefix}/{layer_name}/scale\"][:, i]\n\n\ndef convert_t5x_to_pytorch(\n variables: dict, *, num_layers: int, is_encoder_only: bool, scalable_attention: bool = False\n):\n \"\"\"Converts the parameters from T5X-Flax to Transformers-PyTorch.\"\"\"\n old = traverse_util.flatten_dict(variables[\"target\"])\n old = {\"/\".join(k): v for k, v in old.items()}\n\n # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi\n split_mlp_wi = \"encoder/encoder/mlp/wi_0/kernel\" in old\n print(\"Split MLP:\", split_mlp_wi)\n\n new = collections.OrderedDict()\n\n # Shared embeddings.\n new[\"shared.weight\"] = old[\"token_embedder/embedding\"]\n\n # Encoder.\n for i in range(num_layers):\n # Block i, layer 0 (Self Attention).\n layer_norm = t5x_layer_norm_lookup(old, i, \"encoder\", \"pre_attention_layer_norm\")\n k, o, q, v = t5x_attention_lookup(old, i, \"encoder\", \"attention\")\n new[f\"encoder.block.{i}.layer.0.layer_norm.weight\"] = layer_norm\n new[f\"encoder.block.{i}.layer.0.SelfAttention.k.weight\"] = k.T\n new[f\"encoder.block.{i}.layer.0.SelfAttention.o.weight\"] = o.T\n new[f\"encoder.block.{i}.layer.0.SelfAttention.q.weight\"] = q.T\n new[f\"encoder.block.{i}.layer.0.SelfAttention.v.weight\"] = v.T\n\n # Block i, layer 1 (MLP).\n layer_norm = t5x_layer_norm_lookup(old, i, \"encoder\", \"pre_mlp_layer_norm\")\n wi, wo = t5x_mlp_lookup(old, i, \"encoder\", split_mlp_wi)\n new[f\"encoder.block.{i}.layer.1.layer_norm.weight\"] = layer_norm\n if split_mlp_wi:\n new[f\"encoder.block.{i}.layer.1.DenseReluDense.wi_0.weight\"] = wi[0].T\n new[f\"encoder.block.{i}.layer.1.DenseReluDense.wi_1.weight\"] = wi[1].T\n else:\n new[f\"encoder.block.{i}.layer.1.DenseReluDense.wi.weight\"] = wi.T\n new[f\"encoder.block.{i}.layer.1.DenseReluDense.wo.weight\"] = wo.T\n if scalable_attention:\n # convert the rel_embedding of each layer\n new[f\"encoder.block.{i}.layer.0.SelfAttention.relative_attention_bias.weight\"] = t5x_relpos_bias_lookup(\n old, i, \"encoder\"\n ).T\n\n new[\"encoder.final_layer_norm.weight\"] = old[\"encoder/encoder_norm/scale\"]\n\n if not scalable_attention:\n new[\"encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight\"] = t5x_relpos_bias_lookup(\n old, 0, \"encoder\"\n ).T\n new[\"decoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight\"] = t5x_relpos_bias_lookup(\n old, 0, \"decoder\"\n ).T\n\n if not is_encoder_only:\n # Decoder.\n for i in range(num_layers):\n # Block i, layer 0 (Self Attention).\n layer_norm = t5x_layer_norm_lookup(old, i, \"decoder\", \"pre_self_attention_layer_norm\")\n k, o, q, v = t5x_attention_lookup(old, i, \"decoder\", \"self_attention\")\n new[f\"decoder.block.{i}.layer.0.layer_norm.weight\"] = layer_norm\n new[f\"decoder.block.{i}.layer.0.SelfAttention.k.weight\"] = k.T\n new[f\"decoder.block.{i}.layer.0.SelfAttention.o.weight\"] = o.T\n new[f\"decoder.block.{i}.layer.0.SelfAttention.q.weight\"] = q.T\n new[f\"decoder.block.{i}.layer.0.SelfAttention.v.weight\"] = v.T\n\n # Block i, layer 1 (Cross Attention).\n layer_norm = t5x_layer_norm_lookup(old, i, \"decoder\", \"pre_cross_attention_layer_norm\")\n k, o, q, v = t5x_attention_lookup(old, i, \"decoder\", \"encoder_decoder_attention\")\n new[f\"decoder.block.{i}.layer.1.layer_norm.weight\"] = layer_norm\n new[f\"decoder.block.{i}.layer.1.EncDecAttention.k.weight\"] = k.T\n new[f\"decoder.block.{i}.layer.1.EncDecAttention.o.weight\"] = o.T\n new[f\"decoder.block.{i}.layer.1.EncDecAttention.q.weight\"] = q.T\n new[f\"decoder.block.{i}.layer.1.EncDecAttention.v.weight\"] = v.T\n\n # Block i, layer 2 (MLP).\n layer_norm = t5x_layer_norm_lookup(old, i, \"decoder\", \"pre_mlp_layer_norm\")\n wi, wo = t5x_mlp_lookup(old, i, \"decoder\", split_mlp_wi)\n new[f\"decoder.block.{i}.layer.2.layer_norm.weight\"] = layer_norm\n if split_mlp_wi:\n new[f\"decoder.block.{i}.layer.2.DenseReluDense.wi_0.weight\"] = wi[0].T\n new[f\"decoder.block.{i}.layer.2.DenseReluDense.wi_1.weight\"] = wi[1].T\n else:\n new[f\"encoder.block.{i}.layer.2.DenseReluDense.wi.weight\"] = wi.T\n new[f\"decoder.block.{i}.layer.2.DenseReluDense.wo.weight\"] = wo.T\n\n if scalable_attention:\n # convert the rel_embedding of each layer\n new[\n f\"decoder.block.{i}.layer.0.SelfAttention.relative_attention_bias.weight\"\n ] = t5x_relpos_bias_lookup(old, i, \"decoder\").T\n\n new[\"decoder.final_layer_norm.weight\"] = old[\"decoder/decoder_norm/scale\"]\n\n # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)\n if \"decoder/logits_dense/kernel\" in old:\n new[\"lm_head.weight\"] = old[\"decoder/logits_dense/kernel\"].T\n\n return new\n\n\ndef make_state_dict(converted_params, is_encoder_only: bool):\n \"\"\"Prepares a state dict for the PyTorch model.\"\"\"\n # Make a state dict with torch tensors.\n state_dict = collections.OrderedDict([(k, torch.from_numpy(v.copy())) for (k, v) in converted_params.items()])\n\n # Add what is missing.\n if \"encoder.embed_tokens.weight\" not in state_dict:\n state_dict[\"encoder.embed_tokens.weight\"] = state_dict[\"shared.weight\"]\n\n if not is_encoder_only:\n if \"decoder.embed_tokens.weight\" not in state_dict:\n state_dict[\"decoder.embed_tokens.weight\"] = state_dict[\"shared.weight\"]\n\n if \"lm_head.weight\" not in state_dict: # For old 1.0 models.\n print(\"Using shared word embeddings as lm_head.\")\n state_dict[\"lm_head.weight\"] = state_dict[\"shared.weight\"]\n\n return state_dict\n\n\ndef load_t5x_weights_in_t5(model, config, t5x_checkpoint_path, is_encoder_only, scalable_attention):\n \"\"\"Replaces the params in model witht the T5X converted params.\"\"\"\n variables = checkpoints.load_t5x_checkpoint(t5x_checkpoint_path)\n converted = convert_t5x_to_pytorch(\n variables, num_layers=config.num_layers, is_encoder_only=is_encoder_only, scalable_attention=scalable_attention\n )\n state_dict = make_state_dict(converted, is_encoder_only)\n model.load_state_dict(state_dict, strict=True)\n\n\ndef convert_t5x_checkpoint_to_pytorch(\n t5x_checkpoint_path,\n config_file,\n pytorch_dump_path,\n is_encoder_only: bool = False,\n scalable_attention: bool = False,\n):\n \"\"\"Loads the config and model, converts the T5X checkpoint, and saves a PyTorch checkpoint.\"\"\"\n # Initialise PyTorch model\n config = MT5Config.from_json_file(config_file)\n print(f\"Building PyTorch model from configuration: {config}\")\n # Non-v1.1 checkpoints could also use T5Model, but this works for all.\n # The v1.0 checkpoints will simply have an LM head that is the word embeddings.\n if is_encoder_only:\n model = UMT5EncoderModel(config)\n else:\n model = UMT5ForConditionalGeneration(config)\n\n # Load weights from tf checkpoint\n load_t5x_weights_in_t5(model, config, t5x_checkpoint_path, is_encoder_only, scalable_attention)\n\n # Save pytorch-model\n print(f\"Save PyTorch model to {pytorch_dump_path}\")\n model.save_pretrained(pytorch_dump_path)\n\n # Verify that we can load the checkpoint.\n model.from_pretrained(pytorch_dump_path)\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Converts a native T5X checkpoint into a PyTorch checkpoint.\")\n # Required parameters\n parser.add_argument(\n \"--t5x_checkpoint_path\", default=None, type=str, required=True, help=\"Path to the T5X checkpoint.\"\n )\n parser.add_argument(\n \"--config_file\",\n default=None,\n type=str,\n required=True,\n help=\"The config json file corresponding to the pre-trained T5 model.\\nThis specifies the model architecture.\",\n )\n parser.add_argument(\n \"--pytorch_dump_path\", default=None, type=str, required=True, help=\"Path to the output PyTorch model.\"\n )\n parser.add_argument(\n \"--is_encoder_only\", action=\"store_true\", help=\"Check if the model is encoder-decoder model\", default=False\n )\n parser.add_argument(\n \"--scalable_attention\",\n action=\"store_true\",\n help=\"Whether the model uses scaled attention (umt5 model)\",\n default=False,\n )\n args = parser.parse_args()\n convert_t5x_checkpoint_to_pytorch(\n args.t5x_checkpoint_path,\n args.config_file,\n args.pytorch_dump_path,\n args.is_encoder_only,\n args.scalable_attention,\n )\n","sub_path":"src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py","file_name":"convert_umt5_checkpoint_to_pytorch.py","file_ext":"py","file_size_in_byte":12070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"556351331","text":"import os\nimport csv\n\ncwd = os.path.dirname(os.path.abspath(__file__))\ncsvpath = os.path.join(cwd,'Resources','budget_data.csv')\n\n# i = total months j = placeholder for previous month's revenue\ni = 0\nj = 0\nrevenue = 0\ndates = []\ndeltalist = []\nwith open(csvpath) as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n next(csvreader)\n\n for row in csvreader:\n date = row[0]\n dates.append(date)\n # Net total profit / losses\n revenue = revenue + int(row[1])\n # Average variance = (total profit / i)\n # Delta in a list max(list) and min(list) for biggest increase and smallest increase\n deltalist.append(int(row[1]) - j)\n j = int(row[1])\n # Total # of months\n i = i + 1\n\navgchange = (sum(deltalist) - deltalist[0])/(i-1)\ngreat_date = dates[deltalist.index(max(deltalist))]\nleast_date = dates[deltalist.index(min(deltalist))]\n\noutput = (f'''\n Financial Analysis\n ----------------------------\n Total Months: {i}\n Total: {revenue}\n Average Change: $-2315.12\n Greatest Increase in Profits: {great_date} (${max(deltalist)})\n Greatest Decrease in Profits: {least_date} (${min(deltalist)})\n '''\n)\nprint(output)\nwith open(\"output.txt\",\"w\") as outfile:\n outfile.write(output)","sub_path":"PyBank/PyBank.py","file_name":"PyBank.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"422081399","text":"#! /Library/Frameworks/Python.framework/Versions/2.7/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nplatformName_andr = 'Android';\n\nplatformVersion = '4.4';\n\ndeviceName_andr = 'Android';\n\nappPackage_ffan = 'com.wanda.app.wanhui';\nappPackage_bp = 'com.feifan.bp.test';\n\nappActivity_ffan = 'com.ffan.o2o.business.launch.LauncherActivity';\nappActivity_bp = 'com.feifan.bp.SplashActivity';\n\ndriver_url = 'http://localhost:4723/wd/hub';","sub_path":"com/qa/automation/appium/configs/driver_configs.py","file_name":"driver_configs.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"568802664","text":"'''\nCreated on 2014-10-25\n\n@author: didia\n'''\nimport unittest\nfrom google.appengine.ext import testbed\nfrom trackdidia.models import user\n\nclass DatastoreTest(unittest.TestCase):\n\n\n def setUp(self):\n # First, create an instance of the Testbed class.\n self.testbed = testbed.Testbed()\n # Then activate the testbed, which prepares the service stubs for use.\n self.testbed.activate()\n # Next, declare which service stubs you want to use.\n self.testbed.init_datastore_v3_stub()\n self.testbed.init_memcache_stub()\n self.testbed.init_user_stub()\n self.testbed.init_mail_stub()\n\n\n def tearDown(self):\n self.testbed.deactivate()\n \n\nclass NormalTest(unittest.TestCase):\n pass\n\n \nclass TestTracking(DatastoreTest):\n \n def setUp(self):\n super(TestTracking, self).setUp()\n self.user = user.get_or_create_user('TheFuture', 'thefuture2092@gmail.com', 'Aristote')\n self.week = self.user.get_week()\n\n","sub_path":"trackdidia/tests/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136079945","text":"from django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .models import *\n\n\nclass CustomerForm(forms.ModelForm):\n class Meta:\n model = Customer\n fields = [\"name\", \"email\", \"description\"]\n widgets = {\"description\": forms.Textarea(attrs={\"rows\": 3})}\n\n\nclass ProductForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = [\"name\", \"description\", \"product_type\"]\n widgets = {\"description\": forms.Textarea(attrs={\"rows\": 3})}\n\n def clean(self):\n super().clean()\n\n if self.cleaned_data.get(\n \"product_type\"\n ) == Product.SERVICE and self.cleaned_data.get(\"description\"):\n raise ValidationError(\n _(\"You can't set description for services\"), \"service_description\"\n )\n\n\nclass PlanForm(forms.ModelForm):\n product = forms.ModelChoiceField(queryset=Product.services)\n\n class Meta:\n model = Plan\n fields = [\n \"name\",\n \"description\",\n \"product\",\n \"amount\",\n \"interval\",\n \"interval_count\",\n \"currency\",\n ]\n widgets = {\"description\": forms.Textarea(attrs={\"rows\": 3})}\n\n\nclass SKUForm(forms.ModelForm):\n product = forms.ModelChoiceField(queryset=Product.goods)\n\n class Meta:\n model = SKU\n fields = [\"name\", \"description\", \"product\", \"price\", \"currency\"]\n widgets = {\"description\": forms.Textarea(attrs={\"rows\": 3})}\n\n\nclass SubscribeForm(forms.Form):\n plan = forms.ModelChoiceField(\n queryset=None, empty_label=\"Select a plan\", label=\"Plan\"\n )\n token = forms.CharField(\n max_length=128,\n required=False,\n help_text=\"Stripe.js token used to reset the source on the customer\",\n )\n\n def __init__(self, *args, customer: Customer, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[\"plan\"].queryset = Plan.objects.not_subscribed_by(customer)\n\n def subscribe(self, customer: Customer):\n if not hasattr(self, \"cleaned_data\"):\n raise Exception(\n \"cleaned_data is undefined. Maybe you forgot to call `is_valid()`?.\"\n )\n token = self.cleaned_data.get(\"token\", None)\n plan = self.cleaned_data[\"plan\"]\n if token:\n customer.set_source(token)\n customer.subscribe(plan)\n\n\nclass UnsubscribeForm(forms.Form):\n plan = forms.ModelChoiceField(\n queryset=None, empty_label=\"Select a plan\", label=\"Plan\"\n )\n\n def __init__(self, *args, customer: Customer, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[\"plan\"].queryset = Plan.objects.subscribed_by(customer)\n\n def unsubscribe(self, customer: Customer):\n if not hasattr(self, \"cleaned_data\"):\n raise Exception(\n \"cleaned_data is undefined. Maybe you forgot to call `is_valid()`?.\"\n )\n plan = self.cleaned_data[\"plan\"]\n customer.cancel_subscription(plan)\n\n\nclass OrderForm(forms.Form):\n sku = forms.ModelChoiceField(SKU.objects, empty_label=\"Select an SKU\", label=\"SKU\")\n token = forms.CharField(\n max_length=128,\n required=False,\n help_text=\"Stripe.js token used to reset the source on the customer\",\n )\n save_source = forms.BooleanField(\n required=False, label=\"Use this card for future payments\"\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = super().clean()\n save_source = self.cleaned_data[\"save_source\"]\n token = self.cleaned_data[\"token\"]\n\n if save_source and not token:\n raise forms.ValidationError(\n \"You must provide card info to save if for later use\"\n )\n\n def order(self, customer: Customer):\n if not hasattr(self, \"cleaned_data\"):\n raise Exception(\n \"cleaned_data is undefined. Maybe you forgot to call `is_valid()`?.\"\n )\n sku = self.cleaned_data[\"sku\"]\n save_source = self.cleaned_data[\"save_source\"]\n token = self.cleaned_data[\"token\"]\n\n if save_source:\n customer.set_source(token)\n token = None\n customer.order(sku, token)\n","sub_path":"dt_stripe/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414659935","text":"import sys\nimport argparse\nimport os\nimport json\nimport re\nimport spacy\nimport time\n\nnlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])\nsentencizer = nlp.create_pipe(\"sentencizer\")\nnlp.add_pipe(sentencizer)\n\n###\nimport html\n###\n\ndef preproc1(comment , steps=range(1, 5)):\n ''' This function pre-processes a single comment\n\n Parameters: \n comment : string, the body of a comment\n steps : list of ints, each entry in this list corresponds to a preprocessing step \n\n Returns:\n modComm : string, the modified comment \n '''\n modComm = comment\n if 1 in steps: # replace newlines with spaces\n modComm = re.sub(r\"\\n{1,}\", \" \", modComm)\n if 2 in steps: # unescape html\n modComm = html.unescape(modComm) # TODO\n if 3 in steps: # remove URLs\n modComm = re.sub(r\"(http|http|www)\\S+\", \"\", modComm)\n if 4 in steps: # remove duplicate spaces\n #strip initial and final spaces if exist\n modComm = modComm.strip()\n modComm = re.sub(r'\\s+',' ',modComm) # TODO\n\n # TODO: get Spacy document for modComm\n\n utt = nlp(modComm)\n cleaned = ''\n #loop through all sentences\n for sent in utt.sents:\n #loop through tokens\n for i,token in enumerate(sent):\n #get lemma and tag\n lemma = token.lemma_\n tag = token.tag_\n #use token if lemma starts with - and token does not start with -\n if(lemma[0] == '-' and token.text[0] != '-'):\n cleaned += token.text + '/' + tag\n else:\n #else use the lemma\n cleaned += lemma + '/' + tag\n\n #check if the lemma and tag were the last elements of the sentence, if not, add space, if yes, add new line character to the end.\n if (i != len(sent) - 1):\n cleaned += ' '\n else:\n cleaned += '\\n'\n \n modComm = cleaned[:]\n\n return modComm\n\n\ndef main(args):\n start = time.time()\n allOutput = []\n for subdir, dirs, files in os.walk(indir):\n for file in files:\n fullFile = os.path.join(subdir, file)\n print( \"Processing \" + fullFile)\n\n data = json.load(open(fullFile))\n counter = 0\n #read until the max specified\n while(counter != args.max):\n #get the sampling index using the formula in assignment sheet\n index = (args.ID[0] + counter) % len(data)\n #load the data of index\n post = json.loads(data[index])\n #create the required format and it to the allOutput\n to_add = {'id': post['id'], 'body': preproc1(post['body']) , 'cat': file}\n allOutput.append(to_add)\n counter += 1\n \n #save the results to the file specified\n fout = open(args.output, 'w')\n fout.write(json.dumps(allOutput))\n fout.close()\n print('Took {0} seconds.'.format(time.time() - start))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Process each .')\n parser.add_argument('ID', metavar='N', type=int, nargs=1,\n help='your student ID')\n parser.add_argument(\"-o\", \"--output\", help=\"Directs the output to a filename of your choice\", required=True)\n parser.add_argument(\"--max\", help=\"The maximum number of comments to read from each file\", default=10000)\n parser.add_argument(\"--a1_dir\", help=\"The directory for A1. Should contain subdir data. Defaults to the directory for A1 on cdf.\", default='/u/cs401/A1')\n \n args = parser.parse_args()\n \n ###\n #args = parser.parse_args(['1002401634','-o',r'C:\\Users\\Shahin\\Documents\\School\\Skule\\Year 4\\Winter\\CSC401\\A1\\preproc.json','--a1_dir',r'C:\\Users\\Shahin\\Documents\\School\\Skule\\Year 4\\Winter\\CSC401\\A1'])\n ###\n\n\n if (args.max > 200272):\n print( \"Error: If you want to read more than 200,272 comments per file, you have to read them all.\" )\n sys.exit(1)\n \n indir = os.path.join(args.a1_dir, 'data')\n main(args)\n","sub_path":"code/a1_preproc.py","file_name":"a1_preproc.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"11744490","text":"x = list()\n\nop = ''\n\npares = list()\n\nimpares = list()\n\nwhile True:\n\n x.append(int(input('Digite um número: ')))\n\n op = str(input('Quer continuar? [S/N]: ')).upper()\n\n if op == 'N':\n\n break\n\nfor c in range(0, len(x)):\n\n if x[c] % 2 == 0:\n\n pares.append(x[c])\n\nfor c in range(0, len(x)):\n\n if x[c] % 2 != 0:\n\n impares.append(x[c])\n\nprint(f'A lista completa é {x}')\n\nprint(f'A lista de Pares é {pares}')\n\nprint(f'A lista de Ímpares é {impares}')\n\n\n\n","sub_path":"ex082dividindo_valores_em_varis_listas.py","file_name":"ex082dividindo_valores_em_varis_listas.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125313715","text":"from socket import *\nfrom threading import *\nimport time\nimport json\nclass MultiChatServer:\n clients = []\n final_recived_message = \"\"\n member_dict = {}\n member_dict['dictionary_info'] = 'member'\n message_dict = {}\n message_dict['dictionary_info'] = 'message'\n message = {}\n\n def __init__(self):\n self.s_sock = socket(AF_INET, SOCK_STREAM)\n self.ip =''\n self.port = 2500\n # so_reuseaddr = timewait 상태의 ip,port에 새로운 소켓 할당\n self.s_sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n self.s_sock.bind((self.ip, self.port))\n print(\"waiting for clinets...\")\n self.s_sock.listen(100)\n self.accept_client()\n\n def accept_client(self):\n while True:\n client = c_socket, (ip, port) = self.s_sock.accept()\n if client not in self.clients:\n self.clients.append(client)\n print(ip,':',str(port),' 연결되었습니다.')\n t = Thread(target=self.receive_messages, args=(c_socket,))\n t.start()\n\n def receive_messages(self, c_socket):\n while True:\n try:\n incoming_message = c_socket.recv(1024)\n if not incoming_message:\n break\n except:\n continue\n else:\n self.final_received_message = incoming_message.decode(\"utf-8\")\n\n # dict\n self.message_dict[\"message\"] = self.final_received_message\n self.message['message'] = self.final_received_message\n\n self.get_member(c_socket, self.final_received_message)\n self.send_message_clients(c_socket)\n #self.send_member_clients(c_socket)\n # server quit \n if \"/q\" == self.final_received_message.rstrip()[self.final_received_message.find(\":\")+2:]:\n c_socket.close()\n\n def send_message_clients(self, senders_socket):\n # add to constinusouly connect\n for client in self.clients:\n socket, (ip,port) = client\n try:\n print(\"send success\")\n #message = json.dumps(self.message_dict).encode('utf-8')\n message = json.dumps(self.message).encode('utf-8')\n #socket.sendall(self.final_received_message.encode('utf-8'))\n socket.sendall(message)\n except:\n print(\"send fail\")\n #self.clients.remove(client)\n #print(ip,port,\"연결이 종료되었습니다.\")\n pass\n \n def send_member_clients(self, senders_socket):\n # add to constinusouly connect\n for client in self.clients:\n socket, (ip,port) = client\n try:\n member = json.dumps(self.member_dict).encode('utf-8')\n socket.sendall(member)\n except:\n pass\n\n def get_member(self, sock, message):\n member = message[:message.find(\":\")-1]\n\n# if sock.getpeername()[1] in self.member_dict:\n# if self.member_dict[sock.getpeername()[1]] is not member:\n# self.member_dict[sock.getpeername()[1]] = member\n# else:\n# self.member_dict[sock.getpeername()[1]] = member\n print('port', sock.getpeername()[1])\n if sock.getpeername()[1] in self.message:\n if self.message[sock.getpeername()[1]] is not member:\n self.message[sock.getpeername()[1]] = member\n else:\n self.message[sock.getpeername()[1]] = member\n\nif __name__ == \"__main__\":\n MultiChatServer()\n","sub_path":"w15/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"291574753","text":"\"\"\"add type to verdict\n\nRevision ID: 34006d718603\nRevises: 11b537c3987e\nCreate Date: 2020-08-12 07:24:25.463329\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '34006d718603'\ndown_revision = '11b537c3987e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n post_type = sa.Enum('ARTICLE', 'CLAIM', 'INSIGHT', 'VIDEO', name='posttype')\n post_type.create(op.get_bind())\n op.add_column('verdict',\n sa.Column('type',\n post_type,\n nullable=True))\n\n\ndef downgrade():\n op.drop_column('verdict', 'type')\n post_type = sa.Enum(name='posttype')\n post_type.drop(op.get_bind())\n","sub_path":"api/alembic/versions/34006d718603_add_type_to_verdict.py","file_name":"34006d718603_add_type_to_verdict.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175305825","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 The PsiZ Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Test trials module.\"\"\"\n\nimport h5py\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom psiz.trials.experimental.outcomes.continuous import Continuous\nfrom psiz.trials import stack\n\n\ndef test_init_0(continuous_0):\n \"\"\"Test initialization.\"\"\"\n desired_n_sequence = 4\n desired_max_timestep = 1\n desired_n_unit = 1\n desired_value = np.array(\n [[[0.0]], [[2.0]], [[-0.1]], [[1.3]]], dtype=np.float32\n )\n\n assert desired_n_sequence == continuous_0.n_sequence\n assert desired_max_timestep == continuous_0.max_timestep\n assert desired_n_unit == continuous_0.n_unit\n np.testing.assert_array_equal(\n desired_value, continuous_0.value\n )\n\n\ndef test_init_1(continuous_1):\n \"\"\"Test initialization.\"\"\"\n desired_n_sequence = 4\n desired_max_timestep = 1\n desired_n_unit = 1\n desired_value = np.array(\n [[[0.0]], [[2.0]], [[-0.1]], [[1.3]]], dtype=np.float32\n )\n\n assert desired_n_sequence == continuous_1.n_sequence\n assert desired_max_timestep == continuous_1.max_timestep\n assert desired_n_unit == continuous_1.n_unit\n np.testing.assert_array_equal(\n desired_value, continuous_1.value\n )\n\n\ndef test_init_2(continuous_2):\n \"\"\"Test initialization.\"\"\"\n desired_n_sequence = 4\n desired_max_timestep = 3\n desired_n_unit = 1\n desired_value = np.array(\n [\n [[0.0], [0.0], [0.0]],\n [[2.0], [0.0], [0.0]],\n [[-0.1], [-1.0], [0.3]],\n [[1.0], [1.0], [1.0]],\n ], dtype=np.float32\n )\n\n assert desired_n_sequence == continuous_2.n_sequence\n assert desired_max_timestep == continuous_2.max_timestep\n assert desired_n_unit == continuous_2.n_unit\n np.testing.assert_array_equal(\n desired_value, continuous_2.value\n )\n\n\ndef test_init_3(continuous_3):\n \"\"\"Test initialization.\"\"\"\n desired_n_sequence = 4\n desired_max_timestep = 3\n desired_n_unit = 2\n desired_value = np.array(\n [\n [[0.0, 0.1], [0.0, 0.2], [0.0, 0.3]],\n [[2.0, 0.4], [0.0, 0.5], [0.0, 0.6]],\n [[-0.1, 0.7], [-1.0, 0.8], [0.3, 0.9]],\n [[1.0, 1.1], [1.0, 1.2], [1.0, 1.3]],\n ], dtype=np.float32\n )\n\n assert desired_n_sequence == continuous_3.n_sequence\n assert desired_max_timestep == continuous_3.max_timestep\n assert desired_n_unit == continuous_3.n_unit\n np.testing.assert_array_equal(\n desired_value, continuous_3.value\n )\n\n\ndef test_init_wrong():\n \"\"\"Test initialization.\"\"\"\n outcome = np.array(\n [\n [\n [[0.0, 0.1], [0.0, 0.2], [0.0, 0.3]],\n [[2.0, 0.4], [0.0, 0.5], [0.0, 0.6]],\n ],\n [\n [[-0.1, 0.7], [-1.0, 0.8], [0.3, 0.9]],\n [[1.0, 1.1], [1.0, 1.2], [1.0, 1.3]],\n ]\n ], dtype=np.float32\n )\n with pytest.raises(Exception) as e_info:\n Continuous(outcome)\n assert e_info.type == ValueError\n\n\ndef test_export_0(continuous_0):\n desired_y = tf.constant(\n np.array(\n [[[0.0]], [[2.0]], [[-.1]], [[1.3]]],\n dtype=np.float32\n )\n )\n\n tf.debugging.assert_equal(desired_y, continuous_0.export())\n\n\ndef test_export_1(continuous_1):\n desired_y = tf.constant(\n np.array(\n [[[0.0]], [[2.0]], [[-0.1]], [[1.3]]], dtype=np.float32\n )\n )\n\n tf.debugging.assert_equal(desired_y, continuous_1.export())\n\n\ndef test_export_2a(continuous_2):\n desired_y = tf.constant(\n np.array(\n [\n [[0.0], [0.0], [0.0]],\n [[2.0], [0.0], [0.0]],\n [[-0.1], [-1.0], [0.3]],\n [[1.0], [1.0], [1.0]],\n ], dtype=np.float32\n )\n )\n\n tf.debugging.assert_equal(desired_y, continuous_2.export())\n\n\ndef test_export_2b(continuous_2):\n \"\"\"Test for_dataset\n\n Use timestep=False\n\n \"\"\"\n desired_y = tf.constant(\n np.array(\n [\n [0.0], [0.0], [0.0], [2.0], [0.0], [0.0], [-0.1], [-1.0],\n [0.3], [1.0], [1.0], [1.0]\n ], dtype=np.float32\n )\n )\n\n y = continuous_2.export(timestep=False)\n tf.debugging.assert_equal(desired_y, y)\n\n\ndef test_export_3a(continuous_3):\n desired_y = tf.constant(\n np.array(\n [\n [[0.0, 0.1], [0.0, 0.2], [0.0, 0.3]],\n [[2.0, 0.4], [0.0, 0.5], [0.0, 0.6]],\n [[-0.1, 0.7], [-1.0, 0.8], [0.3, 0.9]],\n [[1.0, 1.1], [1.0, 1.2], [1.0, 1.3]],\n ], dtype=np.float32\n )\n )\n\n tf.debugging.assert_equal(desired_y, continuous_3.export())\n\n\ndef test_export_3b(continuous_3):\n \"\"\"Test for_dataset\n\n Use timestep=False\n\n \"\"\"\n desired_y = tf.constant(\n np.array(\n [\n [0.0, 0.1], [0.0, 0.2], [0.0, 0.3],\n [2.0, 0.4], [0.0, 0.5], [0.0, 0.6],\n [-0.1, 0.7], [-1.0, 0.8], [0.3, 0.9],\n [1.0, 1.1], [1.0, 1.2], [1.0, 1.3],\n ], dtype=np.float32\n )\n )\n\n y = continuous_3.export(timestep=False)\n tf.debugging.assert_equal(desired_y, y)\n\n\ndef test_export_wrong(continuous_3):\n \"\"\"Test export.\n\n Using incorrect `export_format`.\n\n \"\"\"\n with pytest.raises(Exception) as e_info:\n continuous_3.export(export_format='garbage')\n assert e_info.type == ValueError\n assert (\n str(e_info.value) == \"Unrecognized `export_format` 'garbage'.\"\n )\n\n\ndef test_persistence(continuous_2, tmpdir):\n \"\"\"Test save and load.\"\"\"\n group_name = \"value\"\n\n original = continuous_2\n fn = tmpdir.join('persistence_test.hdf5')\n\n # Save group.\n f = h5py.File(fn, \"w\")\n grp_stimulus = f.create_group(group_name)\n original.save(grp_stimulus)\n f.close()\n\n # Load group.\n f = h5py.File(fn, \"r\")\n grp = f[group_name]\n # Encoding/read rules changed in h5py 3.0, requiring asstr() call.\n try:\n class_name = grp[\"class_name\"].asstr()[()]\n except AttributeError:\n class_name = grp[\"class_name\"][()]\n reconstructed = Continuous.load(grp)\n f.close()\n\n # Check for equivalency.\n assert class_name == \"Continuous\"\n assert original.n_sequence == reconstructed.n_sequence\n assert original.max_timestep == reconstructed.max_timestep\n np.testing.assert_array_equal(\n original.value, reconstructed.value\n )\n\n\ndef test_subset_3(continuous_3):\n \"\"\"Test subset.\"\"\"\n desired_n_sequence = 2\n desired_max_timestep = 3\n desired_value = np.array(\n [\n [[2.0, 0.4], [0.0, 0.5], [0.0, 0.6]],\n [[-0.1, 0.7], [-1.0, 0.8], [0.3, 0.9]],\n ], dtype=np.float32\n )\n desired_n_unit = 2\n\n sub = continuous_3.subset(np.array([1, 2]))\n\n assert desired_n_sequence == sub.n_sequence\n assert desired_max_timestep == sub.max_timestep\n assert desired_n_unit == sub.n_unit\n np.testing.assert_array_equal(\n desired_value, sub.value\n )\n\n\ndef test_stack_0(continuous_3, continuous_4):\n \"\"\"Test stack.\"\"\"\n desired_n_sequence = 6\n desired_max_timestep = 3\n desired_value = np.array(\n [\n [[0.0, 0.1], [0.0, 0.2], [0.0, 0.3]],\n [[2.0, 0.4], [0.0, 0.5], [0.0, 0.6]],\n [[-0.1, 0.7], [-1.0, 0.8], [0.3, 0.9]],\n [[1.0, 1.1], [1.0, 1.2], [1.0, 1.3]],\n [[2.0, 2.1], [2.0, 2.2], [2.0, 2.3]],\n [[3.0, 3.4], [3.0, 3.5], [3.0, 3.6]],\n ], dtype=np.float32\n )\n desired_n_unit = 2\n\n stacked = stack((continuous_3, continuous_4))\n\n assert desired_n_sequence == stacked.n_sequence\n assert desired_max_timestep == stacked.max_timestep\n np.testing.assert_array_equal(\n desired_value, stacked.value\n )\n assert desired_n_unit == stacked.n_unit\n\n\ndef test_stack_1(continuous_2, continuous_3):\n \"\"\"Test stack.\n\n Incompatible `n_unit`.\n\n \"\"\"\n with pytest.raises(Exception) as e_info:\n stack((continuous_2, continuous_3))\n assert e_info.type == ValueError\n","sub_path":"tests/trials/outcomes/test_continuous.py","file_name":"test_continuous.py","file_ext":"py","file_size_in_byte":8715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7311762","text":"import unittest\nfrom unittest.mock import patch\n\nfrom bot.exts.filters import filtering\nfrom tests.helpers import MockBot, autospec\n\n\nclass FilteringCogTests(unittest.IsolatedAsyncioTestCase):\n \"\"\"Tests the `Filtering` cog.\"\"\"\n\n def setUp(self):\n \"\"\"Instantiate the bot and cog.\"\"\"\n self.bot = MockBot()\n with patch(\"bot.utils.scheduling.create_task\", new=lambda task, **_: task.close()):\n self.cog = filtering.Filtering(self.bot)\n\n @autospec(filtering.Filtering, \"_get_filterlist_items\", pass_mocks=False, return_value=[\"TOKEN\"])\n async def test_token_filter(self):\n \"\"\"Ensure that a filter token is correctly detected in a message.\"\"\"\n messages = {\n \"\": False,\n \"no matches\": False,\n \"TOKEN\": True,\n\n # See advisory https://github.com/python-discord/bot/security/advisories/GHSA-j8c3-8x46-8pp6\n \"https://google.com TOKEN\": True,\n \"https://google.com something else\": False,\n }\n\n for message, match in messages.items():\n with self.subTest(input=message, match=match):\n result, _ = await self.cog._has_watch_regex_match(message)\n\n self.assertEqual(\n match,\n bool(result),\n msg=f\"Hit was {'expected' if match else 'not expected'} for this input.\"\n )\n if result:\n self.assertEqual(\"TOKEN\", result.group())\n","sub_path":"tests/bot/exts/filters/test_filtering.py","file_name":"test_filtering.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"575106997","text":"# coding:utf-8\nimport os\n\nfrom casslr.app import app\n\nfrom casslr.test.util import FarmRoleEngineTestCase\n\n\nclass CasslrTestCase(FarmRoleEngineTestCase):\n def setUp(self):\n super(CasslrTestCase, self).setUp()\n\n for response in [\"user-data.xml\", \"roles-valid.xml\"]:\n with open(os.path.join(self.test_data, response)) as f:\n self.engine.responses.append(f.read())\n\n app.config[\"ENGINE\"] = self.engine\n self.client = app.test_client()\n\n def test_seeds(self):\n response = self.client.get('/seeds')\n self.assertEqual(200, response.status_code)\n\n seeds = response.data.decode(\"utf-8\").split(\",\")\n self.assertEqual(2, len(seeds))\n\n self.assertEqual(set((\"10.190.214.199\", \"10.157.42.57\")), set(seeds))\n\n def test_status(self):\n response = self.client.get('/status')\n self.assertEqual(200, response.status_code)\n","sub_path":"python/casslr/test/test_casslr.py","file_name":"test_casslr.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"449878591","text":"# csv_to_json.py to convert csv file to proper JSON\n# USE THIS FOR UNIQUE IDS\n\nimport csv\nimport json\ncsvFilePath = 'targeted/groups/files/csv/targeted-test-changed.csv'\njsonFilePath = 'targeted/groups/files/json/targeted-test.json'\n\n# want to read csv and add it to dictionary via loop\n# can either read it line by line or read it all at once and add it to file\n# if csv is small enough, can read it all at once\n\ndata = {}\nwith open(csvFilePath) as csvFile:\n\tcsvReader = csv.DictReader(csvFile)\n\n\t# loop to go through and read each line in csv\n\tfor csvRow in csvReader:\n\t\t# what does each row start with?\n\t\trow_id = csvRow[\"id\"]\n\t\tdata[row_id] = csvRow\n\n\n# want to write data to json file. Use \"w\" for write. Make sure to indent = 4 so that it all won't be on one line\nwith open(jsonFilePath, \"w\") as jsonFile:\n\tjsonFile.write(json.dumps(data, indent = 4));\n","sub_path":"targeted/csv_to_json.py","file_name":"csv_to_json.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"45668997","text":"#!/usr/bin/python3\n\n# Terminengine by digits version 0.1.2019.6\n\nfrom os import path, chdir, mkdir, system\nfrom sys import stdin, stdout, platform\nfrom time import sleep\n\nfrom var import *\n\ngame_folder = path.dirname(__file__)\n\nclear_cmd = ''\n\nif platform.startswith('win32'):\n clear_cmd = 'cls'\nelse:\n clear_cmd = 'clear'\n\ntry:\n mkdir(path.join(game_folder, 'data'))\n data_folder = path.join(game_folder, 'data')\n mkdir(path.join(data_folder, 'save'))\n save_folder = path.join(data_folder, 'save')\nexcept FileExistsError:\n data_folder = path.join(game_folder, 'data')\n save_folder = path.join(data_folder, 'save')\n\nclass Data:\n\n def menu():\n print(\"(1) Save\")\n print(\"(2) Load\")\n print(\"(3) Name\")\n print(\"(0) Back\")\n sel = input(\": \")\n Text.clear()\n if sel == \"1\":\n Data.select_save(mode='s')\n if sel == \"2\":\n Data.select_save(mode='l')\n if sel == \"3\":\n Data.select_save(mode='n')\n if sel == \"0\":\n pass\n\n def select_save(mode=''):\n Data.loadsaves()\n print(\"(1) {}\".format(SAVE['data']['1']))\n print(\"(2) {}\".format(SAVE['data']['2']))\n print(\"(3) {}\".format(SAVE['data']['3']))\n print(\"(4) {}\".format(SAVE['data']['4']))\n print(\"(5) {}\".format(SAVE['data']['5']))\n print(\"(6) {}\".format(SAVE['data']['6']))\n print(\"(7) {}\".format(SAVE['data']['7']))\n print(\"(8) {}\".format(SAVE['data']['8']))\n print(\"(9) {}\".format(SAVE['data']['9']))\n sel = input(\": \")\n Text.clear()\n if sel == \"1\":\n save = '1'\n if sel == \"2\":\n save = '2'\n if sel == \"3\":\n save = '3'\n if sel == \"4\":\n save = '4'\n if sel == \"5\":\n save = '5'\n if sel == \"6\":\n save = '6'\n if sel == \"7\":\n save = '7'\n if sel == \"8\":\n save = '8'\n if sel == \"9\":\n save = '9'\n else:\n if SAVE['data']['current_save_slot'] != '':\n save = SAVE['data']['current_save_slot']\n\n if mode == 's':\n try:\n mkdir(path.join(save_folder, save))\n except FileExistsError:\n pass\n Text.cstream(\"Saving Data\", spd=0, end='', clr='b')\n Text.cstream(\"...\", spd=0.09, dly=.5/0.09, clr='a')\n for save_data in SAVE_DATA:\n Data.save(save, save_data)\n Data.name(save)\n Data.savesaves()\n SAVE['data']['current_save_slot'] = save\n\n if mode == 'l':\n for save_data in SAVE_DATA:\n Data.load(save, save_data, quick=True)\n\n SAVE['data']['current_save_slot'] = save\n\n if mode == 'n':\n Data.name(save)\n\n def name(save):\n if SAVE['data'][save] == '':\n print(\"Enter Save Tag\")\n SAVE['data'][save] = input(\": \")\n #input()\n Text.clear()\n elif SAVE['data'][save] != '':\n print(\"Rename Save Tag? Y/N\")\n sel = input(\": \").lower()\n Text.clear()\n if sel == \"y\":\n print(\"Enter New Save Tag\")\n SAVE['data'][save] = input(\": \")\n #input()\n system('clear')\n if sel == \"n\":\n pass\n\n def save(save, target, quick=False):\n if quick == False:\n Text.cstream(\"Saving Data\", spd=0, end='', clr='b')\n Text.cstream(\"...\", spd=0.09, dly=.5/0.09, clr='a')\n\n chdir(save_folder)\n with open(path.join(save, target['file']), 'w') as f:\n if target['type'] == 'dict':\n for data in target['data']:\n if target['data'][data]['type'] == 'list':\n for l in target['data'][data]['data']['data']:\n for value in target['data'][data]['data']['data'][l]:\n f.write(str(value)+\"|\")\n f.write(\"\\n\")\n else:\n for d in target['data'][data]['data']:\n f.write(str(target['data'][data]['data'][d]))\n f.write(\"\\n\")\n else:\n if target['type'] == 'list':\n for L in target['data']['data']:\n for l in target['data']['data'][L]:\n f.write(str(l)+\"|\")\n f.write(\"\\n\")\n else:\n for data in target['data']:\n f.write(str(target['data'][data]))\n f.write(\"\\n\")\n chdir(game_folder)\n\n def load(save, target, quick=False):\n try:\n if quick == False:\n Text.cstream(\"Loading Data\", spd=0, end='', clr='b')\n Text.cstream(\"...\", spd=0.09, dly=.5/0.09, clr='a')\n\n chdir(save_folder)\n with open(path.join(save, target['file']), 'r') as f:\n if target['type'] == 'dict':\n for data in target['data']:\n if target['data'][data]['type'] == 'list':\n for d in target['data'][data]['data']['data']:\n line = f.readline().strip()\n temp_data = ''\n x = 0\n for l in line:\n if l != \"|\":\n temp_data += l\n else:\n if target['data'][data]['data']['type'] == 'str':\n target['data'][data]['data']['data'][d][x] = str(temp_data)\n if target['data'][data]['data']['type'] == 'int':\n target['data'][data]['data']['data'][d][x] = int(temp_data)\n x += 1\n temp_data = ''\n else:\n for attribute in target['data'][data]['data']:\n if target['data'][data]['type'] == 'str':\n target['data'][data]['data'][attribute] = str(f.readline().strip())\n if target['data'][data]['type'] == 'bool':\n target['data'][data]['data'][attribute] = bool(f.readline().strip())\n if target['data'][data]['type'] == 'int':\n target['data'][data]['data'][attribute] = int(f.readline().strip())\n if target['data'][data]['type'] == 'float':\n target['data'][data]['data'][attribute] = float(f.readline().strip())\n else:\n if target['type'] == 'list':\n for data in target['data']['data']:\n line = f.readline().strip()\n temp_data = ''\n x = 0\n for l in line:\n if l != \"|\":\n temp_data += l\n else:\n if target['data']['type'] == 'str':\n target['data']['data'][data][x] = str(temp_data)\n if target['data']['type'] == 'int':\n target['data']['data'][data][x] = int(temp_data)\n x += 1\n temp_data = ''\n else:\n for data in target['data']:\n if target['type'] == 'str':\n target['data'][data] = str(f.readline().strip())\n if target['type'] == 'int':\n target['data'][data] = int(f.readline().strip())\n if target['type'] == 'float':\n target['data'][data] = float(f.readline().strip())\n if target['type'] == 'bool':\n target['data'][data] = bool(f.readline().strip())\n\n f.close()\n chdir(game_folder)\n except FileNotFoundError:\n print(\"No Data\")\n\n def savesaves():\n chdir(save_folder)\n for x in range(1, 9):\n try:\n with open(path.join('{}'.format(str(x).strip()), SAVE['file']), 'w') as f:\n for data in SAVE['data']:\n f.write(str(SAVE['data'][data]))\n f.write('\\n')\n except FileNotFoundError:\n pass\n chdir(game_folder)\n\n def loadsaves():\n chdir(save_folder)\n for x in range(1, 9):\n try:\n with open(path.join('{}'.format(str(x).strip()), SAVE['file']), 'r') as f:\n for data in SAVE['data']:\n SAVE['data'][data] = str(f.readline().strip())\n\n f.close()\n except FileNotFoundError:\n pass\n chdir(game_folder)\n\nclass Text:\n\n def clear():\n system(clear_cmd)\n\n def sstream(txt, spd=0.06, clr=''):\n if clr == 'b':\n system(clear_cmd)\n for c in txt:\n stdout.write(c)\n stdout.flush()\n sleep(spd)\n print(\"\")\n\n def cstream(txt, spd=0.06, dly=0, hdr='', hdr_m=1, end='', end_x=1, clr=''):\n if dly == 0:\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for c in txt:\n stdout.write(c)\n stdout.flush()\n sleep(spd)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n print(end * end_x, end='')\n\n if dly > 0:\n delay = spd * dly\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for c in txt:\n stdout.write(c)\n stdout.flush()\n sleep(spd)\n print(end * end_x, end='')\n sleep(delay)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n\n def fstream(text_file, spd=0.06, dly=0, hdr='', hdr_m=1, end='', end_x=1, clr=''):\n with open(text_file, 'r') as txt:\n if dly == 0:\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for char in txt:\n for c in char:\n stdout.write(c)\n stdout.flush()\n sleep(spd)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n print(end * end_x, end='')\n\n if dly > 0:\n delay = spd * dly\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for char in txt:\n for c in char:\n stdout.write(c)\n stdout.flush()\n sleep(spd)\n print(end * end_x, end='')\n sleep(delay)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n\n def stream(text_file, r, g, b, spd=0.06, dly=0, hdr='', hdr_m=1, end='', end_x=1, clr=''):\n if '.txt' in text_file:\n FBG = 38#48\n with open(text_file, 'r') as txt:\n if dly == 0:\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for char in txt:\n for c in char:\n stdout.write(\"\\x1b[{};2;{};{};{}m\".format(FBG, r, g, b) + c + '\\x1b[0m')\n stdout.flush()\n sleep(spd)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n print(end * end_x, end='')\n\n if dly > 0:\n delay = spd * dly\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for char in txt:\n for c in char:\n stdout.write(\"\\x1b[{};2;{};{};{}m\".format(FBG, r, g, b) + c + '\\x1b[0m')\n stdout.flush()\n sleep(spd)\n print(end * end_x, end='')\n sleep(delay)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n else:\n FBG=38#48\n if dly == 0:\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for c in text_file:\n stdout.write(\"\\x1b[{};2;{};{};{}m\".format(FBG, r, g, b) + c + '\\x1b[0m')\n stdout.flush()\n sleep(spd)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n print(end * end_x, end='')\n\n if dly > 0:\n delay = spd * dly\n if clr == 'b':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n if hdr != '':\n print(hdr + '\\n' * hdr_m)\n for c in text_file:\n stdout.write(\"\\x1b[{};2;{};{};{}m\".format(FBG, r, g, b) + c + '\\x1b[0m')\n stdout.flush()\n sleep(spd)\n print(end * end_x, end='')\n sleep(delay)\n if clr == 'a':\n system(clear_cmd)\n if clr == 'b+a':\n system(clear_cmd)\n\nclass Event:\n\n def get_key():\n system(\"stty raw -echo\")\n c = stdin.read(1)\n system(\"stty -raw echo\")\n return c\n\nclass Sprite():\n\n def new(f, w=4, h=4, x=0, y=0):\n sprite = {\n 'file' : '{}.txt'.format(f),\n 'type' : 'dict',\n 'data' : {\n 'info' : {\n 'type' : 'int',\n 'data' : {\n 'height' : h,\n 'width' : w,\n 'x' : x,\n 'y' : y\n }\n },\n 'img' : {\n 'type' : 'list',\n 'data' : {\n 'type' : 'int',\n 'data' : {}\n }\n }\n }\n }\n for y in range(sprite['data']['info']['data']['height']):\n for x in range(sprite['data']['info']['data']['width']):\n pixel = [x, y, 0, 0, 0]\n sprite['data']['img']['data']['data']['{}-{}'.format(x, y)] = pixel\n return sprite\n\n def set_pixels(sprite, r, g, b):\n for p in sprite['data']['img']['data']['data']:\n sprite['data']['img']['data']['data'][p][2] = r\n sprite['data']['img']['data']['data'][p][3] = g\n sprite['data']['img']['data']['data'][p][4] = b\n\n def draw(sprite):\n for p in sprite['data']['img']['data']['data']:\n x = sprite['data']['img']['data']['data'][p][0] + sprite['data']['info']['data']['x']\n y = sprite['data']['img']['data']['data'][p][1] + sprite['data']['info']['data']['y']\n r = sprite['data']['img']['data']['data'][p][2]\n g = sprite['data']['img']['data']['data'][p][3]\n b = sprite['data']['img']['data']['data'][p][4]\n Display.draw(x, y, r, g, b)\n\nclass Display:\n\n def display():\n pixel = [TEXT['data']['list']['data']['data']['background'][0],\n TEXT['data']['list']['data']['data']['background'][1],\n TEXT['data']['list']['data']['data']['background'][2]]\n for y in range(DISPLAY['data']['height']):\n for x in range(DISPLAY['data']['width']):\n key = '{}-{}'.format(x,y)\n screen_buffer[key] = pixel\n\n def get_pixel(x, y):\n pixel = screen_buffer['{}-{}'.format(x, y)]\n R = pixel[0]\n G = pixel[1]\n B = pixel[2]\n return R, G, B\n\n def draw(x, y, r, g, b):\n screen_buffer['{}-{}'.format(x, y)] = [r, g, b]\n\n def render(pxl='', margin=0):\n Text.clear()\n pixels = ['░░', '▒▒', '▓▓', '██']\n if pxl == '':\n pxl = pixels[DISPLAY['data']['brightness']]\n for y in range(DISPLAY['data']['height']):\n for x in range(DISPLAY['data']['width']):\n r, g, b = Display.get_pixel(x, y)\n stdout.write(\"\\x1b[{};2;{};{};{}m\".format(38, r, g, b) + pxl + '\\x1b[0m')\n print(\"\")\n print(\"\\n\"*margin)\n","sub_path":"digits_engine.py","file_name":"digits_engine.py","file_ext":"py","file_size_in_byte":18323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"486527650","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport pandas as pd\nimport os\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.pipeline import Pipeline\n\nfrom utils import load_config, create_log, preprocessor, models_validation\n\n\ndef model_selection(config_file):\n '''Build and compare various models'''\n # Load the settings\n config = load_config(config_file)\n\n # Create a log file for model selection\n logger = create_log(log_file=config['model_selection_log'])\n\n ############################\n # Read cleaned training data\n ############################ \n logger.info(f'Load clean data')\n\n derived_dir = config['data_dir'] + config['derived_dir']\n train = pd.read_csv(os.path.join(derived_dir, config['train_derived']))\n\n x_train = train.drop(['salary'], axis=1)\n y_train = train['salary']\n\n ###################\n # Model validation\n ###################\n logger.info(f'Build and compare models')\n # Define and compare linear and non-linear models\n\n # Extract numerical and categorical columns from x_train\n features_num = x_train.select_dtypes(exclude='object')\n features_cat = x_train.select_dtypes(include='object')\n\n num_cols = features_num.columns\n cat_cols = features_cat.columns\n\n preproc = preprocessor(num_cols, cat_cols, interaction_term=False)\n preproc_interac = preprocessor(num_cols, cat_cols, interaction_term=True)\n\n # Baseline model\n baseline = Pipeline(steps=[\n ('Preprocess', prepoc),\n ('model', DummyRegressor(strategy=\"mean\"))])\n\n # Linear models\n lr = Pipeline(steps=[\n ('Preprocess', prepoc),\n ('model', LinearRegression())])\n lr_interaction = Pipeline(steps=[\n ('Preprocess', prepoc_interac),\n ('model', LinearRegression())])\n\n # Random Forest\n rf = Pipeline(steps=[\n ('Preprocess', prepoc),\n ('model', RandomForestRegressor(n_estimators=200,\n max_depth=15,\n max_features=10))])\n\n # Evaluate and compare models\n models = list([baseline, lr, lr_interaction, rf])\n model_names = list(['baseline',\n 'linear regression',\n 'linear regression with interaction',\n 'random forest'])\n\n mse_means, mse_stdevs = models_validation(x_train, y_train, models)\n for i in range(len(models)):\n logger.info(f'Model: {model_names[i]}')\n logger.info(f'Mean Squared Error = {mse_means[i]:.2f} , '\n f'Standard deviation = {mse_stdevs[i]:.2f}')\n\n\nif __name__ == '__main__':\n model_selection('scripts/config.yaml')\n","sub_path":"scripts/model_selection.py","file_name":"model_selection.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"540426089","text":"#!/usr/bin/env python\n#\n# Load in the necessary libraries (importing them as smaller strings for brevity).\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# SN data to plot\n\nI = 2\nIa = 110\nIa_91bg_like = 9\nIa_91T_like = 6\nIax_02cx_like = 2\nIb = 12\nIbn = 1\nIc = 13\nIc_BL = 4\nIbc = 1\nII = 113\nII_P = 19\nII_pec = 1\nIIb = 6\nIIn = 7\nIIn_AGN = 1\n\nblue_I = 'midnightblue'\nblue_Ia = 'blue'\nblue_Ia_91bg_like = 'mediumblue'\nblue_Ia_91T_like = 'royalblue'\nblue_Iax_02cx_like = 'navy'\nblue_Ib = 'deepskyblue'\nblue_Ibn = 'dodgerblue'\nblue_Ic = 'darkturquoise'\nblue_Ic_BL = 'turquoise'\nblue_Ibc = 'steelblue'\n\nred_II = 'red'\nred_II_P = 'indianred'\nred_II_pec = 'lightcoral'\nred_IIb = 'crimson'\nred_IIn = 'orangered'\nred_IIn_AGN = 'maroon'\n\n#purple_SN = 'violet'\n\nlabels_1 = 'II','Ia','Ibc','I'\nsizes_1 = [II+II_P+II_pec+IIb+IIn+IIn_AGN, Ia+Ia_91bg_like+Ia_91T_like+Iax_02cx_like, Ib+Ibn+Ic+Ic_BL+Ibc, I]\ncolors_1 = [red_II, blue_Ia, blue_Ib, blue_I]\nexplode_1 = (0, 0, 0, 0)\n\nlabels_2 = 'Ia Normal','Ia 91bg like','Ia 91T like','Iax[02cx like]'\nsizes_2 = [Ia, Ia_91bg_like, Ia_91T_like, Iax_02cx_like]\ncolors_2 = [blue_Ia, blue_Ia_91bg_like, blue_Ia_91T_like, blue_Iax_02cx_like]\nexplode_2 = (0, 0, 0, 0)\n\nlabels_3 = 'Ic','Ibc','Ib'\nsizes_3 = [Ic+Ic_BL, Ibc, Ib+Ibn]\ncolors_3 = [blue_Ic, blue_Ibc, blue_Ib]\nexplode_3 = (0, 0, 0)\n\nlabels_4 = 'II P','II pec','IIb','IIn'\nsizes_4 = [II_P, II_pec, IIb, IIn+IIn_AGN]\ncolors_4 = [red_II_P, red_II_pec, red_IIb, red_IIn]\nexplode_4 = (0, 0, 0, 0)\n\n\n# Plot\nplt.figure(\"Supernovae\")\nplt.subplots_adjust(hspace=0.7, wspace=0)\n\nplt.subplot(141)\nchart_1 = plt.pie(sizes_1, explode=explode_1, colors=colors_1, labels=labels_1, autopct='%.2f%%', shadow=False, labeldistance=0.5, pctdistance=1.5, startangle=90, counterclock=True)\nplt.legend(chart_1[0], labels_1, loc='best')\nplt.axis('equal')\n\nplt.subplot(142)\nchart_2 = plt.pie(sizes_2, explode=explode_2, colors=colors_2, labels=labels_2, autopct='%.2f%%', shadow=False, labeldistance=0.5, pctdistance=1.5, startangle=90, counterclock=True)\nplt.legend(chart_2[0], labels_2, loc='best')\nplt.axis('equal')\n\nplt.subplot(143)\nchart_3 = plt.pie(sizes_3, explode=explode_3, colors=colors_3, labels=labels_3, autopct='%.2f%%', shadow=False, labeldistance=0.5, pctdistance=1.5, startangle=90, counterclock=True)\nplt.legend(chart_3[0], labels_3, loc='best')\nplt.axis('equal')\n\nplt.subplot(144)\nchart_4 = plt.pie(sizes_4, explode=explode_4, colors=colors_4, labels=labels_4, autopct='%.2f%%', shadow=False, labeldistance=0.5, pctdistance=1.5, startangle=90, counterclock=True)\nplt.legend(chart_4[0], labels_4, loc='best')\nplt.axis('equal')\n\n\nplt.savefig(\"SN_pie_chart_sans_unclassified.pdf\")\n#plt.tight_layout()\nplt.show()\n","sub_path":"python_scripts/SN_pie_chart_grouped_2.py","file_name":"SN_pie_chart_grouped_2.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"77716377","text":"import serial #import serial library\nimport numpy #import numpy\nimport matplotlib.pyplot as plt #import matplotlib library \nfrom drawnow import * \nimport tkinter as tk\n\ndist = [] #an array to put the arduino information before print\n\narduinoData = serial.Serial('/dev/ttyACM0', 9600) #comunication with Arduino Serial\nplt.ion() #to interactive\ncount = 0 #limit to pop the data from de array\n\n\ndef firstFunction():\n\tprint(\"Doing somthing\")\n\nwindow = Tk()\n\nwindow.title(\"Arduino Control\")\n\nwindow.geometry(\"500x500\")\n\t\ndef makeFig(): #function to plot the graphics\n\tplt.plot(dist, 'ro-')\n\nwhile True:\n\twhile (arduinoData.inWaiting()==0):\n\t\tpass\n\t\n\tarduinoString = arduinoData.readline()\n\tarduinoArray = arduinoString\n\tdistance = float (arduinoArray)\n\tdist.append(distance)\n\n\t#print (arduinoString.decode('utf-8'))\n\t#print (arduinoArray.decode('utf-8'))\n\t#print (dist)\n\tdrawnow(makeFig)\n\tplt.pause(.000001)\n\tcount = count + 1\n\tif(count>50):\n\t\tdistance.pop(0)\n\n\n\nlabel_1 = Label(text='My First Python Program')\nlabel_1.place(x=100,y=300)\n\nfirstButton = Button(text='First Button', command = firstFunction).place(x=70, y=200)\n\nwindow.mainloop()\n\n\n\n","sub_path":"pendulo/ultrassom-plt_v2.py","file_name":"ultrassom-plt_v2.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"413589367","text":"class Node:\n def __init__(self, val, _next=None):\n self.val = val\n self._next = _next\n\n def __str__(self):\n return f'{self.val}'\n\n def __repr__(self):\n return f''\n\n\nclass Queue:\n \"\"\" Queue class\n \"\"\"\n def __init__(self, val_list=None):\n \"\"\" Constructor for Queue\n \"\"\"\n self.front = None\n self.rear = None\n self._length = 0\n\n if val_list is not None:\n for val in val_list:\n self.enqueue(val)\n\n def __len__(self):\n \"\"\" returns the length of the queue\n \"\"\"\n return self._length\n\n def __repr__(self):\n \"\"\" returns the detail information about the queue\n \"\"\"\n return f'< Queue | Front {self.front} | Rear {self.rear} | Length: {self._length} >'\n\n def __str__(self):\n \"\"\" returns the information about the queue\n \"\"\"\n return f'{self.front} | {self.rear} | Length: {self._length} '\n\n def enqueue(self, val):\n \"\"\" Adds a new node into the queue\n \"\"\"\n if self._length == 0:\n self.rear = Node(val)\n self.front = self.rear\n else:\n self.rear._next = Node(val)\n self.rear = self.rear._next\n self._length += 1\n\n def dequeue(self):\n \"\"\" Removes the last node in the queue\n \"\"\"\n if self._length == 0:\n raise IndexError\n if self.front._next is None:\n temp = self.front\n self.front = None\n self.rear = None\n self._length = 0\n else:\n temp = self.front\n try:\n self.front = self.front._next\n except AttributeError:\n self.front = None\n self._length -= 1\n return temp.val\n","sub_path":"data_structures/graph/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"369579999","text":"import cntk as C\nimport numpy as np\nfrom . import sequence\nfrom . import random\nfrom cntk.layers.blocks import _inject_name\n\n\n##########################################################################\n# linear ops\n##########################################################################\ndef scalar(x, name=''):\n \"\"\" select first element of x with shape (1,)\n\n Arguments:\n x: input tensor\n\n Returns:\n :class:`~cntk.ops.functions.Function`\n a scalar of shape (1,)\n \"\"\"\n @C.BlockFunction('scalar', name)\n def inner(x):\n return C.slice(C.reshape(x, (-1,)), 0, 0, 1)\n\n return inner(x)\n\n\ndef cumsum(x, axis: int = -1):\n \"\"\" Calculates the cumulative sum across a static axis\n\n Arguments:\n x: input tensor\n axis (int): static axis of tensor to cumsum over\n\n Returns:\n :class:`~cntk.ops.functions.Function`\n \"\"\"\n d = x.shape[axis]\n u = C.constant(np.triu(np.ones((d, d))).astype(x.dtype))\n if axis != -1:\n x = C.swapaxes(x, -1, axis)\n z = C.times(x, u)\n if axis != -1:\n z = C.swapaxes(z, -1, axis)\n return z\n\n\ndef batchmatmul(left, right, output_rank=1, infer_input_rank_to_map=C.TIMES_NO_INFERRED_INPUT_RANK, name=''):\n \"\"\" Batch Matrix Multiplication\n\n The output of this operation is the matrix product of the two input batch matrices.\n\n This implementation is similar to tensorflow.matmul.\n\n Currently assumes the first axis to be the static batch axis. Does not accept multiple static batch axis.\n\n Example:\n a = C.sequence.input_variable((3, 4, 5)) # batch matrix\n b = C.sequence.input_variable((3, 5, 6)) # batch matrix\n c = Cx.batchmatmul(a, b)\n assert c.shape == (3, 4, 6) # 3 is treated as a batch axis\n\n\n a = C.sequence.input_variable((3, 4, 5)) # batch matrix\n b = C.sequence.input_variable((3, 5, 6, 7)) # batch tensor\n c = Cx.batchmatmul(a, b, output_rank=2)\n assert c.shape == (3, 4, 6, 7) # 3 is treated as a batch axis\n\n\n a = C.input_variable((3, 4, 5)) # batch matrix\n b = C.input_variable((3, 5, 6, 7)) # batch tensor\n c = Cx.batchmatmul(a, b, output_rank=2)\n assert c.shape == (3, 4, 6, 7)\n\n\n Arguments:\n left: left side matrix or tensor\n right: right side matrix or tensor\n output_rank (int): in case we have tensors as arguments, output_rank represents\n the number of axes to be collapsed in order to transform the tensors\n into matrices, perform the operation and then reshape back (explode the axes)\n infer_input_rank_to_map (int): meant for internal use only. Always use default value\n name (str, optional): the name of the Function instance in the network\n\n Returns:\n :class:`~cntk.ops.functions.Function`\n \"\"\"\n\n left_shape = left.shape\n right_shape = right.shape\n\n seq_axis_present = len(left.dynamic_axes) == 2\n static_batch_axis = left_shape[0] # assumes the first axis to be the static batch axis.\n\n if left_shape[0] != right_shape[0]:\n raise ValueError(\"first axis of left operand and right operand must be the same\")\n\n if (left_shape[0] < 0 or right_shape[0] < 0) and seq_axis_present:\n raise ValueError(\"Static batch axis cannot be a free axis when dynamic sequence axis is also present\")\n\n # Combine dynamic sequence axis and static batch axis\n if not seq_axis_present:\n left_unpacked = left\n right_unpacked = right\n else:\n left_unpacked = C.sequence.unpack(left, padding_value=0, no_mask_output=True)\n right_unpacked = C.sequence.unpack(right, padding_value=0, no_mask_output=True)\n\n left_unpacked = C.reshape(left_unpacked, (-1,) + left_shape[1:])\n right_unpacked = C.reshape(right_unpacked, (-1,) + right_shape[1:])\n\n # Fold static batch axis into dynamic sequence axis\n left_folded = C.to_sequence(left_unpacked) # do not set sequence length as batch axis has been folded in\n right_folded = C.to_sequence_like(right_unpacked, left_folded) # seq_length / axis set here to tell cntk they have the same seq axis\n\n # Matrix Multiply when no static batch axis is present\n result = C.times(left_folded, right_folded, output_rank=output_rank, infer_input_rank_to_map=infer_input_rank_to_map)\n\n # Split dynamic sequence axis back to original dynamic sequence and static batch axis\n result_unpacked = C.sequence.unpack(result, padding_value=0, no_mask_output=True)\n if not seq_axis_present:\n result_packed = C.reshape(result_unpacked, (static_batch_axis, ) + result.shape)\n else:\n result_unfolded = C.reshape(result_unpacked, (-1, static_batch_axis) + result.shape)\n result_packed = C.to_sequence_like(result_unfolded, left)\n\n return _inject_name(result_packed, name)\n\n\ndef upsample(x):\n \"\"\" Up sample image by a factor of 2 using nearest neighbour.\n\n Example:\n a = C.input_variable((3, 32, 32)\n b = UpSampling2D(a)\n\n assert b.shape == (3, 64, 64)\n\n Arguments:\n x: input image tensor, assumed (channel, row, col)\n\n Returns:\n :class:`~cntk.ops.functions.Function`\n\n \"\"\"\n xr = C.reshape(x, (x.shape[0], x.shape[1], 1, x.shape[2], 1))\n xx = C.splice(xr, xr, axis=-1) # axis=-1 refers to the last axis\n xy = C.splice(xx, xx, axis=-3) # axis=-3 refers to the middle axis\n r = C.reshape(xy, (x.shape[0], x.shape[1] * 2, x.shape[2] * 2))\n return r\n\n\ndef centre_crop(larger_image, smaller_image, name: str = ''):\n \"\"\" Centre crop spatial dimensions only.\n\n Arguments:\n larger_image: class:`~cntk.ops.functions.Function` that outputs the tensor to be centre cropped\n smaller_image: class:`~cntk.ops.functions.Function` that outputs the reference tensor\n name (str, optional): the name of the Function instance in the network\n\n Returns:\n :class:`~cntk.ops.functions.Function`\n\n \"\"\"\n input_shape = larger_image.shape # larger\n referent_shape = smaller_image.shape # smaller\n row_offset = int((input_shape[1] - referent_shape[1]) / 2)\n col_offset = int((input_shape[2] - referent_shape[2]) / 2)\n\n if row_offset == 0 and col_offset == 0:\n return larger_image\n\n elif row_offset < 0 or col_offset < 0:\n raise ValueError(f\"offset became negative, check if image was passed correctly. \"\n f\"larger image {larger_image.shape}, smaller image {smaller_image.shape}\")\n\n return C.crop_manual(larger_image, smaller_image, row_offset, col_offset, name=name)\n\n\ndef centre_crop_and_splice(larger_image, smaller_image):\n \"\"\" Implementation of copy and crop found in UNET architecture.\n\n Arguments:\n larger_image: to be centre cropped and channel spliced into smaller image\n smaller_image: reference tensor\n\n Returns:\n :class:`~cntk.ops.functions.Function`\n\n \"\"\"\n return C.splice(smaller_image, centre_crop(larger_image, smaller_image), axis=0)\n\n\n##########################################################################\n# non linear and nn ops\n##########################################################################\n@C.typemap\ndef swish(x, name=''):\n \"\"\" swish activation function first introduced in 'Searching for activation function' by Prajit et al.\n Paper can be found in https://arxiv.org/abs/1710.05941 and https://arxiv.org/abs/1901.02671\n\n It typically exhibits good performance in a variety of task in vision and nlp problems.\n Can be used as a drop-in replace for relu.\n \"\"\"\n\n @C.BlockFunction('Swish', name=name)\n def inner(a):\n return a * C.sigmoid(a)\n\n return inner(x)\n\n\n@C.typemap\ndef hardmax(x, axis=-1, name=''):\n \"\"\"\n This hardmax implementation can be applied on selected axis. Original cntk hardmax can only be applied on all axis.\n\n If ``axis`` is given as integer, then the hardmax will be computed along that axis.\n If the provided ``axis`` is -1, it will be computed along the last axis. if None, it will be applied to all axes.\n\n Arguments:\n x: input_tensor\n axis (int or :class:`~cntk.axis.Axis`): axis along which the hardmax operation will be performed\n name (str, optional): the name of the Function instance in the network\n\n Returns:\n :class:`~cntk.ops.functions.Function`:\n \"\"\"\n\n @C.BlockFunction('Hardmax', name=name)\n def inner(a):\n return C.equal(C.reduce_max(a, axis=axis), a)\n\n return inner(x)\n\n\ndef erf(x, name=''):\n \"\"\"\n Computes the element-wise error function of `x`:\n\n The output tensor has the same shape as ``x``.\n\n This implementation is from the Handbook of Mathematical Functions and\n has error less than 1.5 * 10-7 for all inputs.\n book can be found here 'http://people.math.sfu.ca/~cbm/aands/frameindex.htm'\n\n \"\"\"\n\n # constants\n a1 = 0.254829592\n a2 = -0.284496736\n a3 = 1.421413741\n a4 = -1.453152027\n a5 = 1.061405429\n p = 0.3275911\n\n @C.BlockFunction('Erf', name=name)\n def inner(a):\n not_negative = C.greater_equal(a, 0)\n sign = C.element_select(not_negative, not_negative, -1)\n\n abs_x = C.abs(a)\n\n # A&S formula 7.1.26\n t = 1.0 / (1.0 + p * a)\n y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * C.exp(-abs_x * abs_x)\n return C.element_times(sign, y)\n\n return inner(x)\n\n\ndef gelu(x, name=''):\n \"\"\" Gaussian Error Linear Unit (GELU), a high-performing neuralnetwork activation function.\n The GELU nonlinearity is the expected transforma-tion of a stochastic regularizer which randomly\n applies the identity or zero mapto a neuron’s input. The GELU nonlinearity weights inputs by their\n magnitude,rather than gates inputs by their sign as in ReLUs.\n\n For more detail please refer to 'Gaussian Error Linear Units (GELU)'\n by Hendrycks and Gimpel (https://arxiv.org/abs/1606.08415)\n\n This activation is used in BERT and OpenAI GPT & GPT-2.\n\n Its computationally x2 times slower than relu with some negligible increase in memory footprint.\n\n Arguments:\n x: input_tensor\n name (str, optional): the name of the Function instance in the network\n\n Returns:\n :class:`~cntk.ops.functions.Function`:\n\n \"\"\"\n @C.BlockFunction('Gelu', name=name)\n def inner(a):\n return 0.5 * a * (1 + erf(a / 1.41421356237))\n\n return inner(x)\n\n\ndef gelu_fast(x, name=''):\n \"\"\" This version is an less good approximation of gelu but it is x2 times faster on GPU and x3.8 faster on CPU.\n This implementation just as fast as relu on GPU but x2 slower on CPU.\n\n Roughly the same memory footprint as relu.\n\n Arguments:\n x: input_tensor\n name (str, optional): the name of the Function instance in the network\n\n Returns:\n :class:`~cntk.ops.functions.Function`:\n\n \"\"\"\n @C.BlockFunction('GeluFast', name=name)\n def inner(a):\n return a * C.sigmoid(1.702 * a)\n\n return inner(x)\n\n\n##########################################################################\n# mixture density network ops\n##########################################################################\n@C.typemap\ndef gaussian_mdn_coeff(x, nmix: int, ndim: int):\n \"\"\"\n Extracts the coefficients for gaussian mixture density network.\n Assumes independence between gaussian dimensions.\n\n Example:\n ndim, nmix = 1, 3\n a = C.input_variable(ndim)\n prediction = Dense((ndim + 2) * nmix)(a)\n coeffs = C.combine(gaussian_mdn_coeff(prediction_tensor, nmix=nmix, ndim=ndim)).eval({a: x})\n\n alpha, mu, sigma = coeffs.values()\n\n Arguments:\n x: input tensor\n nmix (int): number of mixture\n ndim (int): number of dimension of gaussian\n\n Returns:\n tuple\n\n \"\"\"\n\n if len(x.shape) != 1:\n raise ValueError(\"Must be a 1d tensor, but input has shape {0}\".format(x.shape))\n\n alpha = C.softmax(C.slice(x, 0, 0, nmix), name='alpha')\n sigma = C.exp(C.slice(x, 0, nmix, 2 * nmix), name='sigma') # common variance for all components in single gaussian kernel\n mu = C.reshape(C.slice(x, 0, 2 * nmix, (ndim + 2) * nmix), shape=(nmix, ndim), name='mu')\n return alpha, mu, sigma\n\n\ndef sample_gaussian_mdn(prediction_tensor, nmix: int, ndim: int):\n \"\"\" Constructs sampling nodes from mixture density network outputs\n\n Example:\n ndim, nmix = 1, 3\n a = C.input_variable(ndim)\n prediction = Dense((ndim + 2) * nmix)(a)\n sampled = sample_gaussian_mdn(prediction, nmix, ndim)\n\n results = sampled.eval({a: x}) # different results every time you eval\n\n Arguments:\n prediction_tensor: input tensor\n nmix (int): number of mixture\n ndim (int): number of dimension of gaussian\n\n Returns:\n :class:`~cntk.ops.functions.Function`\n\n \"\"\"\n alpha_tensor, mu_tensor, sigma_tensor = gaussian_mdn_coeff(prediction_tensor, nmix=nmix, ndim=ndim)\n\n selected_alpha = random.sample(alpha_tensor)\n selected_mu_tensor = C.reduce_sum(mu_tensor * C.expand_dims(selected_alpha, axis=-1), axis=0)\n selected_sigma_tensor = C.reduce_sum(sigma_tensor * selected_alpha, axis=0)\n\n sampled = C.random.normal_like(selected_sigma_tensor) * selected_sigma_tensor + selected_mu_tensor\n return sampled\n","sub_path":"ops/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"344897549","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# \n\n# 斐波那契数列\n\nfibs = [0,1]\nfor i in range(8):\n\tfibs.append(fibs[-2] + fibs[-1])\n\nfibs = [0,1]\nfor i in range(int(input('How many Fibonacci numbers do you want? '))-2):\n\tfibs.append(fibs[-2] + fibs[-1])\nprint(fibs)","sub_path":"Unit6_abstract/6.1_fibs.py","file_name":"6.1_fibs.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"163669058","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# 2019年1月14日19:25:31\n# 线性回归 - 基本样例\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nexperiences = np.array([0,1,2,3,4,5,6,7,8,9,10])\nsalaries = np.array([103100, 104900, 106800, 108700, 110400, 112300, 114200, 116100, 117800, 119700, 121600])\n\n# 将特征数据集分为训练集和测试集,除了最后 4 个作为测试用例,其他都用于训练\nX_train = experiences[:7]\nX_train = X_train.reshape(-1, 1)\n# print(\"Xtrain:\", X_train)\nX_test = experiences[7:]\nX_test = X_test.reshape(-1, 1)\n# print(\"X_test\", X_test)\n\n# 把目标数据(特征对应的真实值)也分为训练集和测试集\ny_train = salaries[:7]\ny_test = salaries[7:]\n\n# 创建线性回归模型\nregr = linear_model.LinearRegression()\n\n# 用训练集训练模型——看就这么简单,一行搞定训练过程\nregr.fit(X_train, y_train)\n\n# 用训练得出的模型进行预测\ndiabetes_y_pred = regr.predict(X_test)\n\n# 将测试结果以图标的方式显示出来\nplt.scatter(X_test, y_test, color='red')\nprint(X_test, \"\\n\", y_test)\nplt.plot(X_test, diabetes_y_pred, color='blue', linewidth=2)\n\nplt.xticks(())\nplt.yticks(())\n\nplt.show()","sub_path":"ML_learn/linear_regression1.py","file_name":"linear_regression1.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"624989784","text":"import pydicom as dicom\nimport numpy as np\nfrom PIL import Image, ImageDraw\nimport matplotlib.pyplot as plt\nimport csv\n\n\ndef make_mask(CP_S, organ, slice_number, ref_coor, pixel_resol):\n coor = np.array(CP_S[organ].ContourSequence[slice_number].ContourData)\n coor = coor.reshape(-1, 3) # obtain coordinates for binary mask\n\n bm_coor = coor - ref_coor # change mask coordinates into coordinates in real image\n bm_coor = bm_coor[:, :2]\n bm_coor = np.round(bm_coor / pixel_resol).astype(int)\n\n img = Image.new('L', (512, 512))\n draw = ImageDraw.Draw(img)\n points = []\n for i in range(0, len(bm_coor)): points.append(tuple(bm_coor[i]))\n points = tuple(points)\n draw.polygon((points), fill=1)\n img = np.array(img)\n return img\n\n\ndef make_data(PID, mask_list, RS_file):\n RS_file_name = PID + \"/C1/\" + RS_file\n RS = dicom.read_file(RS_file_name)\n\n num_mask = len(RS.StructureSetROISequence) # Count number of masks\n RS.StructureSetROISequence[0]\n masks_name = []\n for it in range(0, num_mask):\n masks_name.append(RS.StructureSetROISequence[it].ROIName)\n\n CP_S = RS.ROIContourSequence\n\n mask_list -= 1 # Change the numbers of the mask into python index\n bladder = mask_list[0]\n rectum = mask_list[1]\n CTV_LF = mask_list[2]\n\n for organ in mask_list: # For organs (bladder, rectum, prostate)\n\n ## Find real slices that matters (not inside contours)\n num_slices = len(CP_S[organ].ContourSequence)\n real_slices = np.zeros(num_slices)\n slice_looking_at = 0\n\n while slice_looking_at < num_slices - 1:\n coor = np.array(CP_S[organ].ContourSequence[slice_looking_at].ContourData)\n next_coor = np.array(CP_S[organ].ContourSequence[slice_looking_at + 1].ContourData)\n if coor[2] == next_coor[2]: # The next slide is the same level as the one we are looking at\n real_slices[slice_looking_at] = 1\n real_slices[slice_looking_at + 1] = 2\n slice_looking_at += 2\n else:\n slice_looking_at += 1\n\n for slice_it in range(0, num_slices): # For slices of the mask\n\n ### Read reference CT image of the mask and obtain useful informations ###\n UID = CP_S[organ].ContourSequence[slice_it].ContourImageSequence[0].ReferencedSOPInstanceUID\n split_string = UID.split('.')\n slice_code = split_string[-2] + \".\" + split_string[-1]\n\n file_name = PID + \"/C1/CT.\" + UID + \".dcm\"\n ref = dicom.read_file(file_name)\n pixel_resol = float(ref.PixelSpacing[0])\n ref_coor = ref.ImagePositionPatient # obtain reference coordinate (CT image)\n ref_img = ref.pixel_array.astype(int) # obtain reference CT image\n\n if real_slices[slice_it] == 0:\n img = make_mask(CP_S, organ, slice_it, ref_coor, pixel_resol)\n if real_slices[slice_it] == 1:\n img1 = make_mask(CP_S, organ, slice_it, ref_coor, pixel_resol)\n img2 = make_mask(CP_S, organ, slice_it + 1, ref_coor, pixel_resol)\n if np.max(img1 - img2) > 1:\n img = img1 + img2\n else:\n img = img1 - img2\n\n concat_img = np.concatenate((ref_img, img), axis=1)\n save_path = \"files_npy/Segmentation/data/\"\n save_file_name = \"PID_\" + PID + \"_\" + slice_code + \"_\"\n if int(PID) <= 44382269:\n save_folder = \"train/\"\n elif (int(PID) > 44382269) & (int(PID) <= 45141803):\n save_folder = \"val/\"\n else:\n save_folder = \"test/\"\n\n if organ == bladder:\n save_file_name = save_path + \"bladder/\" + save_folder + save_file_name + \"bladder.npy\"\n if organ == rectum:\n save_file_name = save_path + \"rectum/\" + save_folder + save_file_name + \"rectum.npy\"\n if organ == CTV_LF:\n save_file_name = save_path + \"prostate/\" + save_folder + save_file_name + \"CTV_LF.npy\"\n np.save(save_file_name, concat_img)\n\n\ndef main():\n with open('data_annotation.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n PID = row[\"PID\"]\n RS_file = row[\"RS_file\"]\n bladder = int(row[\"bladder\"])\n rectum = int(row[\"rectum\"])\n prostate = int(row[\"prostate\"])\n mask_list = np.array([bladder, rectum, prostate])\n\n make_data(PID, mask_list, RS_file)\n print(PID)\n line_count += 1\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pre_proceessing.py","file_name":"pre_proceessing.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"400835697","text":"#!/bin/python\n\ndef train_classifier(X, y):\n\t\"\"\"Train a classifier using the given training data.\n\n\tTrains a logistic regression on the input data with default parameters.\n\t\"\"\"\n\tfrom sklearn.linear_model import LogisticRegression\n\tfrom sklearn.model_selection import GridSearchCV\n\tcls = LogisticRegression()\n\tparam_grid = {\n\t \t'C': [100],\n\t \t'penalty': ['l2'],\n\t \t'max_iter': list(range(400, 600, 200)),\n\t \t'solver': ['lbfgs']\n\t }\n\tparam_search = GridSearchCV(cls, param_grid=param_grid, refit=True, verbose=3, cv=3)\n\tparam_search.fit(X, y)\n\tprint(\"printing grid scores\")\n\tprint(param_search.cv_results_)\n\timport matplotlib.pyplot as plt\n\tprint(param_grid['C'])\n\tprint(param_search.cv_results_['mean_test_score'])\n\tplt.plot(param_grid['C'], param_search.cv_results_['mean_test_score'])\n\n\timport seaborn as sns\n\n\treturn param_search\n\ndef evaluate(X, yt, cls):\n\t\"\"\"Evaluated a classifier on the given labeled data using accuracy.\"\"\"\n\tfrom sklearn import metrics\n\typ = cls.predict(X)\n\tacc = metrics.accuracy_score(yt, yp)\n\tprint(\" Accuracy\", acc)\n","sub_path":"hw1/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"316037398","text":"# -*- coding: utf-8 -*-\n'''\nState for managing heroku apps.\n\n:configuration: This state can be used by either passing an api key directly\n or by specifying it in a configuration profile in pillar.\n\n It is possible to use a different API than http://api.heroku.com,\n by specifying the API URL in config as api_url, or by passing the value directly.\n\n For example:\n\n .. code-block:: yaml\n\n heroku.:\n - api_key: your_api_key\n'''\nfrom __future__ import absolute_import\nimport logging\nimport salt.config\nimport sys\n\nlog = logging.getLogger(__name__)\n\n# Global keys to maintain state of dict mismatch between Heroku and Pillar\ndiff_heroku_pillar_dict = {'key_or_value_mismatch': False,\n 'heroku_not_pillar': False,\n 'pillar_not_heroku': False}\n\n# Global dicts to store diffs between Heroku and Pillar config vars\nheroku_diff_dict = {}\npillar_diff_dict = {}\n\n\ndef __virtual__():\n '''\n Return virtual name of the module.\n\n :return: The virtual name of the module.\n '''\n return True\n\n\ndef _diff_app_config_vars(name, config_vars, api_key):\n '''\n Compare keys and values between Heroku and Pillar config vars.\n This function makes no changes to Heroku config vars and only\n lists differences.\n\n :param name: The name of the Heroku app\n :param config_vars: The config_vars specified in pillar\n :param api_key: The Heroku api_key\n :returns: Result of executing the state\n :rtype: dict\n '''\n\n ret = {'name': name,\n 'comment': '',\n 'result': None,\n 'changes': {}}\n\n try:\n app_config_vars = __salt__['heroku.list_app_config_vars'](name, api_key)\n log.debug(\"Calling _diff_heroku_pillar_vars\")\n _diff_heroku_pillar_vars(app_config_vars, config_vars)\n if all(not v for v in diff_heroku_pillar_dict.values()):\n ret['result'] = True\n ret['comment'] = 'No changes detected'\n else:\n ret['result'] = False\n ret['comment'] = 'Pillar and Heroku mismatch'\n ret['changes'] = {'old': {'heroku': heroku_diff_dict, 'pillar': pillar_diff_dict}}\n except:\n e = sys.exc_info()[0]\n ret['result'] = False\n log.exception(e)\n\n return ret\n\n\ndef _diff_heroku_pillar_vars(app_config_vars, config_vars):\n '''\n Internal function that runs multiple set operations on Heroku and Pillar\n dicts and sets the values on diff_heroku_pillar_dict accordingly\n\n :param app_config_vars: The Heroku configuration variables\n :param config_vars: The Pillar configuration variables\n :returns: three global dicts\n '''\n\n global diff_heroku_pillar_dict, heroku_diff_dict, pillar_diff_dict\n app_config_vars_set = set(app_config_vars.items())\n config_vars_set = set(config_vars.items())\n\n if app_config_vars_set.symmetric_difference(config_vars_set):\n diff_heroku_pillar_dict['key_or_value_mismatch'] = True\n heroku_diff_dict = dict(app_config_vars_set.difference(config_vars_set))\n pillar_diff_dict = dict(config_vars_set.difference(app_config_vars_set))\n if len(app_config_vars) - len(config_vars) > 0:\n diff_heroku_pillar_dict['heroku_not_pillar'] = True\n if len(app_config_vars) - len(config_vars) < 0:\n diff_heroku_pillar_dict['pillar_not_heroku'] = True\n\n log.debug(\"Completed _diff_heroku_pillar_vars\")\n return diff_heroku_pillar_dict, heroku_diff_dict, pillar_diff_dict\n\n\ndef update_app_config_vars(name, config_vars, api_key):\n '''\n Update Heroku config vars based on specified pillar config vars.\n This function will perform the following actions:\n - Change Heroku config var values for the keys that match one in pillar\n - Add keys from pillar to Heroku\n - Leave Heroku keys not find in pillar unchanged\n\n :param name: The name of the Heroku app\n :param config_vars: The config_vars specified in pillar\n :param api_key: The Heroku api_key\n :returns: Result of executing the state\n :rtype: dict\n '''\n\n ret = {'name': name,\n 'comment': '',\n 'result': True,\n 'changes': {}}\n\n diff_app_config_vars = _diff_app_config_vars(name, config_vars, api_key)\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Following changes would be performed'\n ret['changes'] = diff_app_config_vars\n return ret\n if any(v for v in diff_heroku_pillar_dict.values()):\n __salt__['heroku.update_app_config_vars'](name, config_vars, api_key)\n new_app_config_vars = __salt__['heroku.list_app_config_vars'](name, api_key)\n ret['changes']['new'] = {'heroku': new_app_config_vars}\n return ret\n\n\ndef override_app_config_vars(name, config_vars, api_key):\n '''\n * WARNING * Destructive Function\n This function will delete all Heroku config var keys and values and\n replace them with ones specified in pillar\n\n :param name: The name of the Heroku app\n :param config_vars: The config_vars specified in pillar\n :param api_key: The Heroku api_key\n :returns: Result of executing the state\n :rtype: dict\n '''\n\n ret = {'name': name,\n 'comment': 'Heroku config variables have been overwritten',\n 'result': True,\n 'changes': {}}\n\n try:\n app_config_vars = __salt__['heroku.list_app_config_vars'](name, api_key)\n if __opts__['test']:\n ret['result'] = None\n ret['comment'] = 'Following changes would be performed'\n ret['changes'] = config_vars\n return ret\n empty_values = dict.fromkeys(app_config_vars)\n for key, value in empty_values.items():\n if value is None:\n values = ''\n empty_values[key] = value\n\n log.debug(\"Created empty_dict\")\n __salt__['heroku.update_app_config_vars'](name, empty_values, api_key)\n __salt__['heroku.update_app_config_vars'](name, config_vars, api_key)\n ret['changes']['old'] = {'heroku': app_config_vars}\n ret['changes']['new'] = {'heroku': config_vars}\n except:\n e = sys.exc_info()[0]\n ret['result'] = False\n log.exception(e)\n\n return ret\n","sub_path":"extensions/_states/heroku.py","file_name":"heroku.py","file_ext":"py","file_size_in_byte":6232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"355919937","text":"from util.finance.stock import Stock\n\n\nclass MultiStock(Stock):\n def __init__(self, name, tickers, database_settings=None, database_connection=None):\n self.name = name\n self.tickers = tickers\n\n Stock.__init__(self, ticker=name, database_settings=database_settings, database_connection=database_connection)\n\n stocks = {}\n for ticker in tickers:\n stocks[ticker] = Stock(ticker=ticker, database_connection=database_connection, database_settings=database_settings)\n\n self.stocks = stocks\n\n self._data_set = None\n\n @property\n def data_set(self):\n if self._data_set is None:\n all_data_sets = [s.data_set for _, s in self.stocks.items()]\n all_data_set_dicts = []\n for i, ds in enumerate(all_data_sets):\n all_data_set_dicts.append({})\n for d in ds:\n all_data_set_dicts[i][d['Datetime']] = d\n\n all_datetimes = [d['Datetime'] for sets in all_data_sets for d in sets]\n trim_datetimes = sorted(set([d for d in all_datetimes if all_datetimes.count(d)==len(all_data_sets)]))\n\n self._data_set = []\n for tdt in trim_datetimes:\n self._data_set.append({})\n date_data_set = [ds[tdt] for ds in all_data_set_dicts]\n self._data_set[-1]['Datetime'] = tdt\n for key in ['Open', 'Close', 'High', 'Low', 'Volume']:\n self._data_set[-1][key] = sum(_[key] for _ in date_data_set)\n\n return self._data_set\n\n def set_data(self, *args, **kwargs):\n Stock.set_data(self, *args, **kwargs)\n for _, stock in self.stocks.items():\n stock.set_data(*args, **kwargs)\n","sub_path":"util/finance/multistock.py","file_name":"multistock.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"474212833","text":"from django.shortcuts import render, redirect, reverse\n\nfrom movies_project.utils import get_movies_by_id, get_pages_numbers_to_show\nfrom movies_project.context_processor_forms import SearchMoviesForm, SelectGenreForm\nfrom .models import UserProfile\nfrom movies_app.models import Comments\n\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import logout, login\n\nfrom django.core.paginator import Paginator\n\nimport urllib\n\n# Create your views here.\n\n@login_required\ndef display_profile(request):\n user_profile = UserProfile.objects.get(user=request.user)\n\n watched_list = [get_movies_by_id(movie_id) for movie_id in user_profile.watched_movies.split()[:11]] if user_profile.watched_movies else []\n wishlisted_list = [get_movies_by_id(movie_id) for movie_id in user_profile.wishlisted_movies.split()[:11]] if user_profile.wishlisted_movies else []\n\n return render(request, \"user_profiles_app/display_profile.html\", {\"user_profile\": user_profile,\n \"wishlisted_movies\": wishlisted_list,\n \"watched_movies\": watched_list})\n\ndef create_user(request):\n search_movie_form = SearchMoviesForm()\n\n if request.POST:\n user_creation_form = UserCreationForm(request.POST)\n if user_creation_form.is_valid():\n user = user_creation_form.save()\n UserProfile(user=user).save()\n login(user)\n return redirect(\"search-movies\")\n else:\n user_creation_form = UserCreationForm()\n return render(request, \"user_profiles_app/create_new_user.html\", { \"user_creation_form\": user_creation_form,\n \"search_movie_form\": search_movie_form})\n\n@login_required()\ndef logout_user(request):\n logout(request)\n return redirect(\"search-movies\")\n\n\n@login_required()\ndef watched_whslist(request, watched_or_wishlisted, page_to_display=1):\n\n selecet_genre_form = SelectGenreForm(initial={\"sort_by\": request.GET.get('sort_by')})\n\n user_profile = UserProfile.objects.get(user=request.user)\n\n if watched_or_wishlisted == \"watched\":\n watched_or_wishlisted_movies = [get_movies_by_id(movie_id) for movie_id in user_profile.watched_movies.split()] if user_profile.watched_movies else []\n elif watched_or_wishlisted == \"wishlisted\":\n watched_or_wishlisted_movies = [get_movies_by_id(movie_id) for movie_id in user_profile.wishlisted_movies.split()] if user_profile.wishlisted_movies else []\n else:\n redirect(\"display-profile\")\n\n \"\"\" check for genres in movies watched_or_wishlisted_movies, checks whether movie contains \n all of the genres selected by user \"\"\"\n movies_list = []\n\n if request.GET.get(\"with_genres\"):\n list_of_genres_from_query_parameter = list(map(int, request.GET.get('with_genres').split(\",\")))\n for m in watched_or_wishlisted_movies:\n can_append = 0\n for genre in list_of_genres_from_query_parameter:\n if genre in [genre['id'] for genre in m['genres']]:\n can_append += 1\n if can_append == len(list_of_genres_from_query_parameter):\n movies_list.append(m)\n continue\n else:\n movies_list = watched_or_wishlisted_movies\n list_of_genres_from_query_parameter = []\n\n if request.GET.get(\"sort_by\"):\n sort_option = request.GET.get(\"sort_by\").split(\".\")\n rev = True if sort_option[1] == \"desc\" else False\n movies_list = sorted(movies_list, key=lambda k: k[sort_option[0]], reverse=rev)\n\n\n pages = Paginator(movies_list, 10)\n page = pages.page(page_to_display)\n amount_of_pages = get_pages_numbers_to_show(page_to_display, pages.num_pages+1)\n\n return render(request, \"user_profiles_app/watched_wishlisted.html\", {\"movies_list\": page,\n \"watched_or_wishlisted\": watched_or_wishlisted,\n \"amount_of_pages\": amount_of_pages,\n \"selecet_genre_form\": selecet_genre_form,\n \"list_of_genres_from_query_parameter\": list_of_genres_from_query_parameter})\n\n\ndef watched_wishlist_form_hander(request):\n watched_or_wishlisted = request.GET.get('watched_or_wishlisted')\n if request.method == \"POST\":\n selecet_genre_form = SelectGenreForm(request.POST)\n if selecet_genre_form.is_valid():\n query_params = \"?\"\n for field in selecet_genre_form:\n if field.name == \"with_genres\":\n value = \",\".join(field.value())\n else:\n value = field.value()\n query_params += \"{field_name}={field_value}&\".format(field_name=field.name, field_value=value)\n return redirect(reverse(\"watched_or_wishlisted\", kwargs={\"watched_or_wishlisted\": watched_or_wishlisted, \"page_to_display\": 1}) + query_params)\n\n return redirect(\"watched_or_wishlisted\", watched_or_wishlisted=watched_or_wishlisted, page_to_display= 1)\n\n\n\"\"\"\n One function to process two actions, this could be made much simpler with two view functions but I wanted to\n try and squeeze it into one function, at the same time this function would be unnecessary with use of jqeury \n and ajax, but im focusing purely on back end\n\"\"\"\n@login_required\ndef add_to_watched_wishlisted(request, movie_id, action_to_perform):\n\n if action_to_perform == \"add_to_watched\" or action_to_perform == \"add_to_wishlisted\":\n user_profile = UserProfile.objects.get(user=request.user)\n\n watched_movies = list(map(int, user_profile.watched_movies.split())) if user_profile.watched_movies else []\n wishlisted_movies = list(map(int, user_profile.wishlisted_movies.split())) if user_profile.wishlisted_movies else []\n\n watched_or_wishlisted = watched_movies if action_to_perform == \"add_to_watched\" else wishlisted_movies\n watched_or_wishlisted_second = wishlisted_movies if action_to_perform == \"add_to_watched\" else watched_movies\n\n # DESELECT - SWAP - ADD\n if movie_id in watched_or_wishlisted: # DeSelect\n watched_or_wishlisted.remove(movie_id)\n elif movie_id in watched_or_wishlisted_second: # SWap\n watched_or_wishlisted_second.remove(movie_id)\n watched_or_wishlisted.append(movie_id)\n else: # ADD\n watched_or_wishlisted.append(movie_id)\n\n watched_or_wishlisted = \" \".join(str(s) for s in watched_or_wishlisted) if watched_or_wishlisted else None\n watched_or_wishlisted_second = \" \".join(str(s) for s in watched_or_wishlisted_second) if watched_or_wishlisted_second else None\n\n user_profile.watched_movies = watched_or_wishlisted if action_to_perform == \"add_to_watched\" else watched_or_wishlisted_second\n user_profile.wishlisted_movies = watched_or_wishlisted_second if action_to_perform == \"add_to_watched\" else watched_or_wishlisted\n\n user_profile.save()\n\n\n return_to_query = request.GET.get(\"return_to\")\n\n get = request.GET.copy()\n del get['return_to']\n query_parameters_url = \"?\" + get.urlencode()\n\n if return_to_query == \"movie\":\n return redirect(\"display-movie\", movie_id=movie_id)\n elif return_to_query == \"search\":\n return redirect(reverse(\"search-movies\") + query_parameters_url)\n\n return redirect(\"display-profile\")","sub_path":"user_profiles_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"132388089","text":"\n\n#calss header\nclass _BILLIARDS():\n\tdef __init__(self,): \n\t\tself.name = \"BILLIARDS\"\n\t\tself.definitions = [u'a game played by two people on a table covered in green cloth, in which a cue (= a long stick) is used to hit balls against each other and into pockets around the table']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_billiards.py","file_name":"_billiards.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"185152578","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /home/daniel/Documentos/projetos/pypayments/pygamento/cancel_payment.py\n# Compiled at: 2020-02-28 18:11:57\n# Size of source mod 2**32: 774 bytes\nimport requests, json\n\ndef cancel_payment(**kwargs):\n if kwargs.get('gateway') == 'Ebanx':\n item = {'integration_key':kwargs.get('key'), 'hash':kwargs.get('hash')}\n send = requests.post((kwargs.get('url')['cancel']), data=item)\n r = send.json()\n return r\n if kwargs.get('gateway') == 'PicPay':\n headers = {'content-type':'application/json', 'x-picpay-token':kwargs.get('key')}\n payload = {'authorizationId': kwargs.get('authorization_id')}\n send = requests.post(('https://appws.picpay.com/ecommerce/public/payments/{}/cancellations'.format(kwargs.get('payment_code'))), data=(json.dumps(payload)), headers=headers)\n r = send.json()\n return r","sub_path":"pycfiles/pygameoflife-0.1.1.tar/cancel_payment.cpython-36.py","file_name":"cancel_payment.cpython-36.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"20383790","text":"# -*- coding: utf-8 -*-\n\"\"\"\nEstimation of heat of fusion of triacetic acid lactone (TAL)\nby fitting solubility across temperature.\n\n\"\"\"\nimport numpy as np\nfrom thermosteam.constants import R\nfrom scipy.optimize import curve_fit\nimport flexsolve as flx\nfrom sklearn.metrics import r2_score\nimport matplotlib.pyplot as plt\nfrom thermosteam import (\n functional as fn,\n Thermo,\n Chemical,\n Chemicals,\n equilibrium as eq, \n settings,\n)\n\n# %% Solubility model\n\ndef _solubility(T, dG, gamma):\n RT = (R*T)\n return np.exp(-dG/RT)/gamma\n\nclass SLE(eq.SLE):\n __slots__ = ('dG',)\n def _solve_x(self, T):\n x = _solubility(T, self.dG, 1.) # Initial guess\n if isinstance(self._gamma, eq.IdealActivityCoefficients):\n return _solubility(T, self.dG, self.activity_coefficient or 1.)\n return flx.aitken(self._x_iter, x, xtol=1e-6, args=(T, self.dG), checkiter=False, maxiter=100)\n \n def _x_iter(self, x, T, dG):\n self._update_solubility(x)\n liquid_mol = self._liquid_mol[self._index]\n F_mol_liquid = liquid_mol.sum()\n x_l = liquid_mol / F_mol_liquid\n gamma = self._gamma(x_l, T)\n return _solubility(T, dG, gamma[self._solute_gamma_index])\n# SLE = eq.SLE\n\n# %% Data\n\ntemperatures = np.array([0, 22, 42, 65], float) # C\n#temperatures = temperatures[:-1]\ntemperatures += 273.15 # K\nTAL_g = np.array([3.52, 8.92, 16.46, 21.13], float) # g/L\n#TAL_g = TAL_g[:-1]\nTAL_mol = TAL_g / 126.11004\nWater_mol = 55.5 # mol / L\nsolubilities = TAL_mol / (Water_mol + TAL_mol) # by wt.\nRTlnx = R * temperatures * np.log(solubilities)\nPhenol = Chemical('Phenol').Cn.l[0]\nTAL = Chemical('TAL',\n search_ID='Triacetic acid lactone')\nWater = Chemical('WAter')\nWater.NIST.set_group_counts_by_name({'H2O':1})\nTAL.NIST.set_group_counts_by_name({'CH3':1, 'c-CH=C':2, 'c-CO-O':1, 'OH tert':1})\nTAL.Tm = 185 + 273.15\nrho_TAL = 1.348e-3\nmolar_volume_TAL = fn.rho_to_V(rho_TAL, TAL.MW)\nTAL.V.l.add_model(molar_volume_TAL, top_priority=True)\nTAL.V.s.add_model(molar_volume_TAL, top_priority=True)\nCn = 2 * TAL.MW\nTAL.Cn.l.add_model(Cn, top_priority=True)\nTAL.Cn.s.add_model(Cn, top_priority=True)\nWater, TAL = chemicals = Chemicals([Water, TAL])\nchemicals.compile(skip_checks=True)\nthermo = Thermo(chemicals, Gamma=eq.NISTActivityCoefficients)\nsettings.set_thermo(thermo)\n\n# %% Activity coefficients for excel fitting\n\nGamma = eq.DortmundActivityCoefficients(chemicals)\ngamma = [Gamma([1-x, x], T)[1] for x, T in zip(solubilities, temperatures)]\n\n\n# %% Solubility fitting\n\n# sle = SLE()\n# sle.imol['l', 'Water'] = 100\n# sle.imol['l', 'TAL'] = 10\n\n# @np.vectorize\n# def RTlnsolubility(T, dG): # by wt\n# sle.dG = dG\n# sle('TAL', T=T)\n# return sle.imol['l', 'Water'] / sle.imol['l', ('Water', 'TAL')].sum()\n\n# params, _ = curve_fit(RTlnsolubility, temperatures, RTlnx,\n# p0=[-40], bounds=([-np.inf], [-0.1]))\n\n# def display_solubility_results(dG):\n# plt.figure()\n# plt.plot(temperatures, RTlnsolubility(temperatures, dG), label='fit')\n# plt.scatter(temperatures, RTlnx, label='actual')\n# plt.show()\n \n# r2 = r2_score(RTlnx, RTlnsolubility(temperatures, *params))\n# print('R2:', r2)\n \n# display_solubility_results(*params)\n","sub_path":"BioSTEAM 2.x.x/biorefineries/triacetic_acid_lactone/tal_dG.py","file_name":"tal_dG.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"654469553","text":"import json\nimport os\nimport re\nfrom collections import defaultdict\nfrom bs4 import BeautifulSoup as bs\nimport html2text\n\ncnt = 0\nerror = defaultdict(list)\n\n#for file in train_files:\n #print(file){\npath = 'D:/translate/korquad'\nfile_list = os.listdir(path)\n#print(file_list)\nminus_cnt = 0\nb_cnt = 0\nfile = 'D:/translate/korquad/korquad2.1_train_07.json'\nfirst_time = 0\nwith open(file, 'r') as f:\n all_json = json.load(f)\n data = all_json['data']\n\n for qaset in data[:]:\n html_2_text = html2text.HTML2Text()\n context = qaset['context']\n title = qaset['title']\n url = qaset['url']\n raw_html = qaset['raw_html']\n # print(type(context))\n qas = qaset['qas']\n # print(type(qas))\n soup = bs(context, 'lxml')\n a_tag = soup.find('a', text='검색하러 가기')\n div_soup = a_tag.find_next('div').find('div')\n find_index = context.find('검색하러 가기')\n print(find_index)\n print(\"c: \",context)\n print(\"d: \",context[find_index+20:])\n\n sub_context = str(div_soup)\n sub_context = re.sub(r'[/]*', '', # ><\n sub_context).strip()\n\n new_context = html_2_text.handle(str(div_soup)) # 여기서 answer 이랑 변화가 다른 경우가 생김\n\n new_context = re.sub(r'[*\\'\\\"《》<>〈〉\\(\\)‘’{}&]*', '', # ><\n new_context).strip()\n\n new_context = re.sub(r'[\\t\\n]+', ' ', new_context)\n\n new_context = new_context.replace('[편집]', '[SEP]')\n\n new_context = re.sub(' +', ' ', new_context)\n p = re.compile('([-]+)([|][-]+)*') # ---|---|--- 같은 형식을 | 로 만듬\n new_context = re.sub(p, '[SEP]', new_context)\n p = re.compile('[|]+([ ]+[|]*)*') # | | | 같이 반복되면 | 로 바꿈\n new_context = re.sub(p, '| ', new_context)\n\n h3_split_list = new_context.split('##')\n temp_split_list = h3_split_list[:]\n deleted_list_idx = [False for _ in range(len(temp_split_list))]\n idx = 0\n del_prolog = False\n if h3_split_list[1].find('목차') < 3 and h3_split_list[1].find('목차') >= 0:\n # print(h3_split_list[1])\n del h3_split_list[1] # 목차 제거 , but 목차가 없는 페이지도 존재하기 때문에 이렇게 제거할 수 없음\n deleted_list_idx[1] = True\n del_prolog = True\n delete_h3 = [\"같이 보기[SEP]\", \"각주 및 참고 문헌[SEP]\", \"외부 링크[SEP]\", \"참고 문헌[SEP]\"] # \"각주[SEP]\"\n # \"목차\",\n result_context = \"\"\n for ele in h3_split_list:\n add_flag = True\n for delete in delete_h3:\n if delete in ele:\n add_flag = False\n deleted_list_idx[idx] = True\n break\n if del_prolog == True and idx == 0:\n idx += 2\n else:\n idx += 1\n if add_flag:\n result_context += ele\n\n # result_context = re.sub(' +', ' ', result_context)\n # p = re.compile('([-]+)([|][-]+)*') # ---|---|--- 같은 형식을 | 로 만듬\n # result_context = re.sub(p, '[SEP]', result_context)\n # p = re.compile('[|]+([ ]+[|]*)*') # | | | 같이 반복되면 | 로 바꿈\n # result_context = re.sub(p, '| ', result_context)\n\n for qa in qas: # 큰 1\n\n #real_flag = False\n answer = qa['answer']['text'] # 1\n question = qa['question'] # 큰 2\n id = qa['id'] # 큰 3\n html_answer_start = qa['answer']['html_answer_start'] #2\n html_answer_text = qa['answer']['html_answer_text'] #3\n\n answer_start = qa['answer']['answer_start'] #4\n\n\n split_context = context.split(answer)\n #print(split_context[0])\n #print(\"\\n\\n\")\n #print(split_context[1])\n\n if first_time == 1:\n html_2_text = html2text.HTML2Text()\n split_context0 = html_2_text.handle(context)\n soup = bs(split_context0, 'lxml')\n a_tag = soup.find('a', text='검색하러 가기')\n div_soup = a_tag.find_next('div').find('div')\n print(\"0:\\n\",div_soup)\n\n html_2_text = html2text.HTML2Text()\n split_context1 = html_2_text.handle(split_context[0])\n print(\"1:\\n\",split_context1)\n html_2_text = html2text.HTML2Text()\n split_context2 = html_2_text.handle(split_context[1])\n print(\"2:\\n\",split_context2)\n first_time += 1\n html_2_text = html2text.HTML2Text()\n\n # tt_answer = answer\n new_answer = html_2_text.handle(answer)\n #if real_flag == True:\n # print(new_answer)\n # real_flag = False\n new_answer = re.sub(r'[*\\'\\\"《》<>〈〉\\(\\)‘’{}&]*', '', # ><\n new_answer).strip()\n\n new_answer = re.sub(r'[\\t\\n]+', ' ', new_answer)\n new_answer = new_answer.replace('[편집]', '[SEP]')\n new_answer = new_answer.split('##')\n result_answer = \"\"\n for ele in new_answer:\n result_answer += ele\n result_answer = re.sub(' +', ' ', result_answer)\n\n #result_answer = re.sub(' +', ' ', result_answer)\n p = re.compile('([-]+)([|][-]+)*') # ---|---|--- 같은 형식을 | 로 만듬\n result_answer = re.sub(p, '[SEP]', result_answer)\n p = re.compile('[|]+([ ]+[|]*)*') # | | | 같이 반복되면 | 로 바꿈\n result_answer = re.sub(p, '| ', result_answer)\n\n new_answer = result_answer\n #text0 = str(text0)\n\n if result_context.find(new_answer) == -1: # 정답 매칭이 안 되면 error 리스트에 id 넣어줌\n error[file].append(id) # 없다면 일단 넣고 수작업으로 수정필요\n cnt += 1\n else: # 있다면 json에 수정해서 포함시킴\n answer_num = 0\n real_answer_order = 0\n pass_flag = False\n answer = answer.strip()\n\n a = -1\n while True:\n # a = sub_context.find(answer, a + 1)\n a = context.find(answer, a + 1)\n if a == -1:\n break\n answer_num += 1\n if a == answer_start:\n real_answer_order = answer_num\n temp_answer = answer\n temp_answer = re.sub(r'[/]*', '', # ><\n temp_answer).strip()\n\n sub_answer_num = 0\n a = -1\n while True:\n a = sub_context.find(temp_answer, a + 1)\n if a == -1:\n break\n sub_answer_num += 1\n real0 = real_answer_order\n real_answer_order -= (answer_num - sub_answer_num)\n real = real_answer_order\n answer_num_list = [0 for _ in range(len(temp_split_list))]\n count = 0\n answer_IsIn_list = 0\n bb_count = 0\n i_index = []\n i = -1\n for list in temp_split_list:\n i += 1\n a = -1\n first = True\n while True:\n a = list.find(new_answer, a + 1)\n if a == -1:\n break\n answer_num_list[i] += 1\n if deleted_list_idx[1] == True and i == 1 and first == True:\n real_answer_order -= 1\n first = False\n continue\n count += 1\n bb_count += 1\n if count == real_answer_order: # 진짜 정답의 순서가 발견되면 해당 번째 리스트가 나오는 인덱스를 저장\n answer_IsIn_list = i\n real2 = real_answer_order\n for b in range(0, answer_IsIn_list+1):\n if deleted_list_idx[b] == True: # 만약 정답이 나오는 리스트 앞에서 삭제된 리스트가 있고\n if b == answer_IsIn_list: # 찐 정답이 있는 리스트가 삭제되면 에러에 넣어주자\n b_cnt += 1\n error[file].append(id)\n pass_flag = True\n break\n if deleted_list_idx[1] == True and b == 1:\n continue\n real_answer_order -= answer_num_list[b] # 그 리스트에도 정답과 같은 문자열이 있었다면 정답의 순번을 땡겨줌\n if pass_flag == False:\n count = 0\n new_answer_start = -1\n\n a = -1\n while True:\n a = result_context.find(new_answer, a + 1)\n if a == -1:\n break\n count += 1\n if count == real_answer_order:\n new_answer_start = a\n if new_answer_start == -1:\n minus_cnt += 1\n error[file].append(id)\n elif new_answer_start == 0:\n print(\"\\n\\n\")\n\n\nprint(\"cnt:\",file, \" \", cnt)\nprint(\"bcnt:\",file,\" \",b_cnt)\nprint(\"minus:\",file, \" \", minus_cnt)","sub_path":"preprocessing/korquad_html_to_markdown.py","file_name":"korquad_html_to_markdown.py","file_ext":"py","file_size_in_byte":9953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"326657735","text":"#!/usr/bin/python3\nfrom os import getenv\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm import scoped_session\n\n# imports from model Classes\nfrom models.base_model import BaseModel, Base\nfrom models.place import Place\nfrom models.review import Review\nfrom models.state import State\nfrom models.user import User\nfrom models.amenity import Amenity\nfrom models.city import City\nimport os\n\n\nclass DBStorage:\n __engine = None\n __session = None\n\n def __init__(self):\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(\n getenv('HBNB_MYSQL_USER'),\n getenv('HBNB_MYSQL_PWD'),\n getenv('HBNB_MYSQL_HOST'),\n getenv('HBNB_MYSQL_DB')),\n pool_pre_ping=True)\n # Base.metadata.create_all(self.__engine)\n self.reload()\n if 'test' in os.environ and os.environ['HBNB_ENV'] == 'test':\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None): # JFK added =none\n dic = {}\n a = 0\n query_list = [User, State, City, Amenity, Place, Review]\n if cls is None:\n # print(\"db storage - no class\")\n for i in query_list:\n for x in self.__session.query(i):\n # print(a, \"----->>\", x)\n a += 1\n dic[\"{}.{}\".format(type(x).__name__, x.id)] = x\n\n else:\n # print(\"db storage - class\", type(cls), query_list)\n for i in query_list:\n # print(\"i -->\", i.__name__, cls)\n if i.__name__ == cls:\n # print(\"found\")\n cls = i\n break\n for lol in self.__session.query(cls):\n # print(\"A is \", lol)\n key = \"{}.{}\".format(type(lol).__name__, lol.id)\n dic[key] = lol\n return dic\n\n def new(self, obj):\n self.__session.add(obj)\n\n def save(self):\n self.__session.commit()\n\n def delete(self, obj=None):\n if obj:\n self.__session.delete(obj)\n\n def reload(self):\n Base.metadata.create_all(self.__engine)\n sessionista = sessionmaker(\n bind=self.__engine,\n expire_on_commit=False)\n Session = scoped_session(sessionista)\n self.__session = Session()\n\n def close(self):\n self.__session.close()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89780165","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Assignment 2\n\n# In this assignment, we will start with utilizing Sci-Kit learn to implement a linear regression model similar to what we did in Assignment 1. Afterwards, we will be dropping Sci-Kit learning and implementing these algorithms from scratch without the use of machine learning libraries. While you would likely never have to implement your own linear regression algorithm from scratch in practice, such a skill is valuable to have as you progress further into the field and find many scenarios where you actually may need to perform such implementations manually. Additionally, implementing algorithms from scratch will help you better understand the underlying mathematics behind each model. \n\n# ## Import Libraries\n\n# We will be using the following libraries for this homework assignment. For the questions requiring manual implementation, the pre-existing implementations from Sci-Kit Learn should *not* be used.\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport operator\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error\n\n\n# ## Preparing Data\n\n# The file named **dataset1.csv** includes data that was generated from an n-degree polynomial with some gaussian noise. The data has 2 columns - first column is the feature (input) and the second column is its label (output). The first step is to load the data and split them into training, validation, and test sets. A reminder that the purpose of each of the splitted sets are as follows:\n# \n# * **Training Set**: The sample of data used to fit the model\n# * **Validation Set**: The sample of data used to provide an unbiased evaluation of a model fit on the training dataset while tuning model hyperparameters.\n# * **Test Set**: The sample of data used to provide an unbiased evaluation of a final model fit on the training dataset.\n# \n# In the section below, we load the csv file and split the data randomnly into 3 equal sets. \n# \n# *Note that in practice, we usually aim for around a 70-20-10 split for train, valid, and test respectively, but due to limited data in our case, we will do an even split in order to have sufficient data for evaluation* \n\n# In[2]:\n\n\n# Load the data and split into 3 equal sets\ndata = pd.read_csv('dataset1.csv', header=None)\ndata = data.iloc[:, :-1]\ntrain, valid, test = np.split(data, [int(.33*len(data)), int(.66*len(data))]) #Train set from 0-33%, Valid 33%-66%, Test 67-100%\n\n# We sort the data in order for plotting purposes later\ntrain.sort_values(by=[0], inplace=True)\nvalid.sort_values(by=[0], inplace=True)\ntest.sort_values(by=[0], inplace=True)\n\n\n# Let's take a look at what our data looks like\n\n# In[3]:\n\n\nplt.scatter(train[0], train[1], s=10)\nplt.show()\n\n\n# Let's apply a linear regression model using Sci-Kit learn and see what the results look like.\n\n# In[4]:\n\n\n# Reshape arrays since sci-kit learn only takes in 2D arrays\ntrain_x = np.array(train[0])\ntrain_y = np.array(train[1])\nvalid_x = np.array(valid[0])\nvalid_y = np.array(valid[1])\ntrain_x = train_x.reshape(-1, 1)\ntrain_y = train_y.reshape(-1, 1)\nvalid_x = valid_x.reshape(-1, 1)\nvalid_y = valid_y.reshape(-1, 1)\n\n# Apply linear regression model\nmodel = LinearRegression()\nmodel.fit(train_x, train_y)\ny_pred = model.predict(train_x)\n\n# Plot the results\nplt.scatter(train_x, train_y, s=10)\nplt.plot(train_x, y_pred, color='r')\nplt.show()\n\n\n# By analyzing the line of best fit above, we can see that a straight line is unable to capture the patterns of the data. This is an example of underfitting. As seen in the latest lecture, we can generate a higher order equation by adding powers of the original features as new features. \n# \n# The linear model,: \n# \n#        ** $y(x)$ = $w_1 x$ + $w_0$ ** \n# \n# can be transformed to a polynomial model such as:\n# \n#        ** $y(x)$ = $w_2 x^2$ + $w_1 x$ + $w_0$ ** \n# \n# Note that this is still considered to be linear model as the coefficients/weights associated with the features are still linear. x2 is only a feature. However the curve that we would be fitting in this case is quadratic in nature.\n# \n# Below we show an example of a quadratic curve being fit to the data\n\n# In[5]:\n\n\n# Create polynomial features with degree 2\n#fit computes std and mean used for scaling. transform scaled i\npolynomial_features = PolynomialFeatures(degree=2)\nx_poly = polynomial_features.fit_transform(train_x)\n\n# Apply linear regression\nmodel = LinearRegression()\nmodel.fit(x_poly, train_y)\ny_poly_pred = model.predict(x_poly)\n\n# Plot the results\nplt.scatter(train_x, train_y, s=10)\nplt.plot(train_x, y_poly_pred, color='r')\nplt.show()\n\n\n# As you can see, we get a slightly better fit with a quadratic curve. Let's use the model to make predictions on our validation set and compute the mean squared error, which is the error which we wish to minimize.\n\n# In[6]:\n\n\n# Make predictions using pretrained model\nvalid_y_poly_pred = model.predict(polynomial_features.fit_transform(valid_x))\n\n# Calculate root mean squared error\nmse = mean_squared_error(valid_y, valid_y_poly_pred)\nprint(\"Mean Squared Error: {}\".format(mse))\n\n# Plot the prediction results\nplt.scatter(valid_x, valid_y, s=10)\nplt.plot(valid_x, valid_y_poly_pred, color='r')\nplt.show()\n\n\n# ## Question 1: Polynomial Regression Using Sci-Kit Learn\n# \n# Now it is your turn! Following the same format as above, implement a 10-degree polynomial regression model on the training data and plot your results. Use your model to predict the output of the validation set and calculate the mean square error. Report and plot the results. \n\n# In[7]:\n\n\n### YOUR CODE HERE - Fit a 10-degree polynomial using Sci-Kit Learn\npolynomial_features = PolynomialFeatures(degree=10)\nx_poly = polynomial_features.fit_transform(train_x)\nmodel = LinearRegression()\nmodel.fit(x_poly, train_y)\ny_poly_pred = model.predict(x_poly)\n\n### YOUR CODE HERE - Plot your the curve on the training data set\nplt.scatter(train_x, train_y, s=10)\nplt.plot(train_x, y_poly_pred, color='r')\nplt.show()\n\n### YOUR CODE HERE - Use model to predict output of validation set\nvalid_y_poly_pred = model.predict(polynomial_features.fit_transform(valid_x))\n\n### YOUR CODE HERE - Calculate the RMSE. Report and plot the curve on the validation set.\nplt.scatter(valid_x, valid_y, s=10)\nplt.plot(valid_x, valid_y_poly_pred, color='r')\nplt.show()\nmse = mean_squared_error(valid_y, valid_y_poly_pred)\nprint(\"Mean Squared Error: {}\".format(mse))\n\n\n# #### Did the root mean squared error go up or down as compared to the 2-degree polynomial curve? Why do you think this is the case?\n# \n# It is like the linear regression of degree 1 and 2. A degree 2 may not be enough to capture the complexity of all the data, where as 10 captures more. Thus, the RMSE decreases.\n\n# Now repeat the above for a 20-degree polynomial regression model.\n\n# In[8]:\n\n\n### YOUR CODE HERE - Fit a 20-degree polynomial using Sci-Kit Learn\npolynomial_features = PolynomialFeatures(degree=20)\nx_poly = polynomial_features.fit_transform(train_x)\nmodel = LinearRegression()\nmodel.fit(x_poly, train_y)\ny_poly_pred = model.predict(x_poly)\n\n### YOUR CODE HERE - Plot your the curve on the training data set\nplt.scatter(train_x, train_y, s=10)\nplt.plot(train_x, y_poly_pred, color='r')\nplt.show()\n\n### YOUR CODE HERE - Use model to predict output of validation set\nvalid_y_poly_pred = model.predict(polynomial_features.fit_transform(valid_x))\n\n### YOUR CODE HERE - Calculate the RMSE. Report and plot the curve on the validation set.\nplt.scatter(valid_x, valid_y, s=10)\nplt.plot(valid_x, valid_y_poly_pred, color='r')\nplt.show()\nmse = mean_squared_error(valid_y, valid_y_poly_pred)\nprint(\"Mean Squared Error: {}\".format(mse))\n\n\n# #### How does the mean square error compare to the previous two models? Why do you think this is the case?\n# \n# The model is capturing the noise in the training data now as well. It is a typical case of overfitting. Since overfitted on the training set (with the noise), it will try to fit the validation set as well with the noise from the training set\n\n# ## Question 2: Manual Implementation\n\n# Now it's time to appreciate the hard work that open source developers have put, in order to allow you to implemenent machine learning models without doing any math! No more Sci-Kit learn (or any other libraries like Tensorflow, Pytorch, etc) for the rest of this assignment!\n\n# Your first step is to fit a **10-degree polynomial** to the dataset we have been using above. Then using your results, calculate the mean squared error on both the training and validation set. You may use general utility libraries like numpy and pandas matrix computations and data manipulation, but pre-existing implementations of the model itself is prohibited.\n# \n# A reminder that in polynomial regression, we are looking for a solution for the equation:\n# \n#        ** $Y(X)$ = $W^T$ * $\\phi(X)$ ** \n# \n# where\n# \n#        ** $\\phi(X)$ = [ $1$, $X$, $X^2$, $X^3$, ..... $X^n$ ] **\n# \n# and the ordinary least square solution in closed form is:\n# \n#       ** $W$ = $(X^T X)^{-1}X^TY$ **\n# \n# Make sure to review the slides, do some research, and/or ask for clarification if this doesn't make sense. You must understand the underlying math before being able to implement this properly.\n# \n# *Suggestion - Use the original pandas dataframes variables named train, valid, and test instead of the reshaped arrays that were used specifically for Sci-Kit Learn. It will make your computations cleaner and more inuitive.*\n\n# In[27]:\n\n\n###Reimport the data without all the modification given above. \n# Load the data and split into 3 equal sets\ndata = pd.read_csv('dataset1.csv', header=None)\ndata = data.iloc[:, :-1]\ntrain, valid, test = np.split(data, [int(.33*len(data)), int(.66*len(data))]) #Train set from 0-33%, Valid 33%-66%, Test 67-100%\ntrain.sort_values(by=[0], inplace=True)\nvalid.sort_values(by=[0], inplace=True)\ntest.sort_values(by=[0], inplace=True)\n\n# We sort the data in order for plotting purposes later\nx_train = train[0]; y_train = train[1]\nx_valid = valid[0]; y_valid = valid[1]\nx_valid.shape[0]\n\n\n# In[10]:\n\n\n### YOUR CODE HERE - Create the polynomial matrix ϕ(X)\n#Change this if want other degrees\ndeg = 10;\n\n#Creates polynomial matrix\nX=np.array([x**a for x in x_train for a in range(deg+1)]) #creates polynomial matrix\nX=X.reshape(x_train.shape[0],(deg+1))\n### YOUR CODE HERE - Find the weighted matrix W\n#W=(X^TX)^-1 X^T Y\np1=np.dot(np.transpose(X), X)\np2=np.linalg.inv(p1)\np3=np.dot(p2,np.transpose(X))\nW= np.dot(p3, y_train)\n\n\n### YOUR CODE HERE - Make predictions on the training set and calculate the root mean squared error. Plot the results.\n#y_predict = WT * X\ny_predict_train = np.dot(X,W)\nmse = mean_squared_error(y_predict_train, y_train)\nprint(\"Mean Squared Error: {}\".format(mse))\nplt.scatter(x_train, y_train, s=10)\nplt.plot(x_train, y_predict_train, color='r')\nplt.show()\n\n\n### YOUR CODE HERE - Make predictions on the validation set and calculate the mean squared error. Plot the results.\nX_valid=np.array([x**a for x in x_valid for a in range(deg+1)]) #creates polynomial matrix\nX_valid=X_valid.reshape(x_valid.shape[0],deg+1)\ny_predict_valid = np.dot(X_valid,W)\n\nmse = mean_squared_error(y_predict_valid, y_valid)\nprint(\"Mean Squared Error: {}\".format(mse))\nplt.scatter(x_valid, y_valid, s=10)\nplt.plot(x_valid, y_predict_valid, color='r')\nplt.show()\n\n\n# For the rest of the assignment, we will use the other dataset named **dataset2.csv**. First load the csv and split the model into train, valid, and test sets as shown earlier in the assignment.\n\n# In[41]:\n\n\n### YOUR CODE HERE - Load dataset2.csv and split into 3 equal sets\ndata = pd.read_csv('dataset2.csv', header=None)\ndata = data.iloc[:, :-1]\ntrain, valid, test = np.split(data, [int(.33*len(data)), int(.66*len(data))])\n\n\n### YOUR CODE HERE - Sort the data in order for plotting purposes later\ntrain.sort_values(by=[0], inplace=True)\nvalid.sort_values(by=[0], inplace=True)\ntest.sort_values(by=[0], inplace=True)\n\nx_train = train[0]; y_train = np.array(train[1])\nx_valid = valid[0]; y_valid = np.array(valid[1])\nx_test = test[0]; y_test=np.array(test[1])\nx_train=np.array([x**i for x in x_train for i in range(2) ]).reshape(x_train.shape[0],2)\nx_valid=np.array([x**i for x in x_valid for i in range(2) ]).reshape(x_valid.shape[0],2)\nx_test=np.array([x**i for x in x_test for i in range(2) ]).reshape(x_test.shape[0],2)\n\n\n# Plot the data below to see what it looks like\n\n# In[14]:\n\n\n### YOUR CODE HERE - Plot the points for dataset2\nplt.scatter(train[0],train[1],s=4,c='r')\n\n\n# If done properly, you should see that the points fall under a relatively straight line with minor deviations. Looks like a perfect example to implement a linear regression model using the **gradient descent** method ..... without the use of any machine learning libraries!\n# \n# Since the data falls along a straight line, we can assume the solution follows the form:\n# \n#        ** $y(x)$ = $m x$ + $b$ **\n# \n# A reminder that in gradient descent, we essentially want to iteratively get closer to the minimum of our objective function (the mean squared error), such that:\n# \n#        ** MSE($w_0$) > MSE($w_1$) > MSE($w_2$) > ...**\n# \n# The algorithm is as follows:\n# \n#        ** 1) Pick initial $w_0$ randomnly. **\n# \n#        ** 2) For $k=1,2..$ $\\Rightarrow$ $w_{k+1}$ = $w_k$ - $\\alpha$ $g(w_k)$ where $\\alpha > 0$ is the learning rate and $g(w_k)$ is the gradient. **\n# \n#        ** End when | $w_k$ + $1$ - $w_k$ | < $\\epsilon$ **\n# \n# \n# Make sure to review the slides, do some research, and/or ask for clarification if this doesn't make sense. There are many resources online for gradient descent. You must understand the underlying math before being able to implement this properly.\n# \n# Now once you understand, it is time to implement the gradient descent below. You may set the learning rate to 1e-6 or whatever value you think is best. As usual, calculate the mean squared error and plot your results. This time, training should be done using the training and validation sets, while the final mean squared error should be computed using the testing set.\n\n# In[42]:\n\n\n### YOUR CODE HERE - Implement gradient decent\n###we can assume the weight to be w=[m,b].\ndef gradient_descent(X,y,alpha = 10**-6, eps = 10**-6):\n W = np.array([1,1]) #Initializes the array with \"random\" values\n epsi = np.array([eps,eps]) #create an array of epsilon to compare it with\n while True:#keeps looping until smaller than epsilon\n w1=W - (alpha * (np.matmul(np.matmul(np.transpose(X), X), W) - np.matmul(np.transpose(X), y)))\n if ((abs(w1-W)).all() download as -> python)\n# \n# 2. Submit both the notebook and python file via a pull request as specified in the README\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Assignment2/Assignment 2.py","file_name":"Assignment 2.py","file_ext":"py","file_size_in_byte":16275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"191112406","text":"# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThis module contains a utility visitor for pretty-printing an expression tree.\n\"\"\"\n\nfrom io import StringIO\nfrom typing import TextIO, NamedTuple, Union, Iterable, Optional\n\nfrom ._rewriter import RewriteContext\nfrom .expr_base import Expr, TRIGGER_ON_INIT\nfrom .expr_impl import SuiteExpr, ProgramExpr, TemplateSelectsExpr, TemplateSelectExpr, \\\n GetContractIdExpr, GetContractDataExpr, ConstantExpr, \\\n TemplateFieldExpr, UpdateBlockExpr, CreateStatementExpr, ExerciseStatementExpr, Application, \\\n AppExpr\n\nfrom ..util.tools import boundary_iter\n\n_PP = RewriteContext()\n\n\ndef pretty_print(expr: Expr) -> str:\n \"\"\"\n Return a pretty-printed representation of an :class:`Expr`, optionally ANSI color-coded.\n \"\"\"\n with StringIO() as buf:\n _PP.rewrite(expr, context=_PrettyPrintContext(buf, 0))\n return buf.getvalue()\n\n\nclass _PrettyPrintContext(NamedTuple):\n buf: TextIO\n indent: int\n\n def write(self, value: Union[None, str, Expr], **kwargs) -> None:\n if isinstance(value, str):\n self.buf.write(value)\n elif isinstance(value, Expr):\n _PP.rewrite(value, context=self, **kwargs)\n elif value is not None:\n raise ValueError(f'Only strings and Expr instances can be pretty printed (got {value})')\n\n def write_line(self, value: Union[None, str, Expr] = None) -> None:\n self.write(value)\n self.buf.write('\\n')\n\n def write_keyword(self, text: str) -> None:\n self.buf.write(self.fmt.keyword(text))\n\n def write_keyword_line(self, text: str) -> None:\n self.buf.write(self.fmt.keyword(text))\n self.buf.write('\\n')\n\n\n####################################################################################################\n# WRITER METHODS\n\n@_PP.register(Application, recurse=False)\ndef _write_application(expr: Application, context: _PrettyPrintContext):\n for suite in expr.suites:\n context.write_line(suite)\n\n\n@_PP.register(SuiteExpr, recurse=False)\ndef _write_suite(expr: SuiteExpr, context: _PrettyPrintContext):\n context.write_line(context.fmt.comments(f'-- rules for party {expr.party} --'))\n for program in expr.programs:\n context.write_line(program)\n\n\n@_PP.register(ProgramExpr, recurse=False)\ndef _write_rule(expr: ProgramExpr, context: _PrettyPrintContext):\n context.write_keyword('rule ')\n context.write_line(f'{expr.name}')\n context.write(expr.select)\n if expr.trigger == TRIGGER_ON_INIT:\n context.write_keyword_line(' initially')\n else:\n context.write_keyword_line(' continually')\n context.write_keyword_line(' do')\n context.write(expr.update)\n\n\n@_PP.register(TemplateSelectsExpr, recurse=False)\ndef _write_selects(expr: TemplateSelectsExpr, context: _PrettyPrintContext):\n context.write_keyword_line(' with')\n for tmpl in expr.select:\n context.write(' ')\n context.write(tmpl, include_type_info=True)\n context.write_line()\n\n context.write_keyword_line(' where')\n\n if expr.predicate is not None:\n context.write_keyword(' predicate ')\n context.write_line(expr.predicate)\n\n\n@_PP.register(TemplateSelectExpr, recurse=False)\ndef _write_select(expr: TemplateSelectExpr, context: _PrettyPrintContext,\n include_type_info: bool=False):\n if expr.alias is not None:\n context.write(expr.alias)\n else:\n context.write('_<' + expr.template.template_ref.name + '>')\n\n if include_type_info:\n context.write(' : ')\n context.write(expr.template.template_ref.name)\n\n\n@_PP.register(AppExpr, recurse=False)\ndef _write_app(expr: AppExpr, context: _PrettyPrintContext):\n if expr.func.infix:\n _write_infix_operator(expr.func.name, expr.args, context)\n else:\n context.write(expr.func.name)\n for arg in expr.args:\n context.write(' ')\n context.write(arg)\n\n\n@_PP.register(GetContractIdExpr, recurse=False)\ndef _write_cid(expr: GetContractIdExpr, context: _PrettyPrintContext):\n context.write('(')\n context.write_keyword('cid ')\n context.write(expr.expression)\n context.write(')')\n\n\n@_PP.register(GetContractDataExpr, recurse=False)\ndef _write_cdata(expr: GetContractDataExpr, context: _PrettyPrintContext):\n context.write('(')\n context.write_keyword('cdata ')\n context.write(expr.expression)\n context.write(')')\n\n\n@_PP.register(ConstantExpr, recurse=False)\ndef _write_constant(expr: ConstantExpr, context: _PrettyPrintContext):\n context.write(repr(expr.value))\n\n\n@_PP.register(TemplateFieldExpr, recurse=False)\ndef _write_field(expr: TemplateFieldExpr, context: _PrettyPrintContext):\n context.write(expr.expression)\n context.write('.')\n context.write(expr.field_name)\n\n\n@_PP.register(UpdateBlockExpr, recurse=False)\ndef _write_update(expr: UpdateBlockExpr, context: _PrettyPrintContext):\n if expr.statements:\n for stmt in expr.statements:\n context.write(' ')\n context.write_line(stmt)\n else:\n context.write_line('()')\n\n\n@_PP.register(CreateStatementExpr, recurse=False)\ndef _write_create(expr: CreateStatementExpr, context: _PrettyPrintContext):\n context.write_keyword('create ')\n context.write(expr.template.name)\n _write_arguments(expr.arguments, context)\n\n\n@_PP.register(ExerciseStatementExpr, recurse=False)\ndef _write_exercise(expr: ExerciseStatementExpr, context: _PrettyPrintContext):\n context.write_keyword('exercise ')\n context.write(expr.expression)\n context.write(' ')\n context.write(expr.choice_name)\n _write_arguments(expr.arguments, context)\n\n\n####################################################################################################\n# HELPER METHODS\n\ndef _write_infix_operator(infix_op: str,\n expressions: Iterable[Expr],\n context: _PrettyPrintContext) -> None:\n for is_last, child in boundary_iter(expressions):\n context.write(child)\n if not is_last:\n context.write(f' {infix_op} ')\n\n\ndef _write_arguments(arguments: Optional[dict], context: _PrettyPrintContext) -> None:\n if not arguments:\n return\n\n context.write_keyword(' with ')\n context.write('{')\n\n for is_last, (name, value) in boundary_iter(arguments.items()):\n context.write(name)\n context.write('=')\n if isinstance(value, Expr):\n context.write(value)\n else:\n context.write(repr(value))\n\n if not is_last:\n context.write(', ')\n\n context.write('}')\n","sub_path":"python/dazl/rules/visitor_pretty.py","file_name":"visitor_pretty.py","file_ext":"py","file_size_in_byte":6681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"577082220","text":"# pylint: skip-file\n\"\"\"\nTests for the Tree class.\n\"\"\"\n\nimport unittest\n\nfrom tree.search_tree import Node\nfrom tree.custom_exceptions import Existed, NotExisted\n\nclass TreeTestCase(unittest.TestCase):\n \"\"\"\n This Case of tests checks the functionality of the implementation of Binary Search Tree\n \"\"\"\n\n def test_create_tree(self):\n \"\"\"\n Create a Tree with one start node.\n Test that its value is zero.\n \"\"\"\n tree = Node(0)\n self.assertEqual(tree.data, 0)\n\n def test_create_type(self):\n \"\"\"\n Create a Tree with different types of data.\n Test that it is possible to make node with any type of data.\n \"\"\"\n data_types = [\"tree\", [], 8, {}, (), 9.0]\n for data_type in data_types:\n tree = Node(data_type)\n self.assertEqual(tree.data, data_type)\n\n def test_insert_right(self):\n \"\"\"\n Insert a number bigger than a root.\n Test that this number is right child.\n \"\"\"\n tree = Node(12)\n tree.insert(16)\n self.assertEqual(tree.right.data, 16)\n\n def test_insert_left(self):\n \"\"\"\n Insert a number smaller than a root.\n Test that this number is left child.\n \"\"\"\n tree = Node(12)\n tree.insert(10)\n self.assertEqual(tree.left.data, 10)\n\n def test_insert_existed(self):\n \"\"\"\n Insert a number that is already in a tree.\n Test that it is obedient.\n \"\"\"\n tree = Node(12)\n self.assertRaises(Existed, tree.insert, 12)\n\n def test_find_node_less(self):\n \"\"\"\n Insert a number less than a root and find it.\n Test that the same node is found.\n \"\"\"\n tree = Node(12)\n tree.insert(10)\n _, found_node = tree.find(10)\n self.assertEqual(tree.left, found_node)\n\n def test_find_node_more(self):\n \"\"\"\n Insert a number less than a root and find it.\n Test that the same node is found.\n \"\"\"\n tree = Node(12)\n tree.insert(18)\n _, found_node = tree.find(18)\n self.assertEqual(tree.right, found_node)\n\n def test_find_not_existed(self):\n \"\"\"\n Find a node that is node in a tree.\n Test that it is obedient.\n \"\"\"\n tree = Node(12)\n self.assertRaises(NotExisted, tree.find, 10)\n\n def test_height(self):\n \"\"\"\n Create a tree.\n Test the height of a tree.\n \"\"\"\n tree = Node(12)\n for element in [5, 16, 14, 19, 15, 20]:\n tree.insert(element)\n height = tree.find_height(tree)\n self.assertEqual(height, 4)\n\n def test_height_from_any_node(self):\n \"\"\"\n Create a tree.\n Test the height of a tree.\n \"\"\"\n tree = Node(12)\n for element in [5, 16, 14, 19, 15, 20]:\n tree.insert(element)\n height = tree.find_height(tree.right)\n self.assertEqual(3, height)\n\n def test_zero_height(self):\n \"\"\"\n Create a tree and try to find a height from None node.\n Test that the height is zero.\n \"\"\"\n tree = Node(12)\n height = tree.find_height(tree.right)\n self.assertEqual(0, height)\n\n def test_the_width_order(self):\n \"\"\"\n Create a tree.\n Test the width order of a new tree.\n \"\"\"\n tree = Node(12)\n for element in [5, 16, 14, 19, 15, 20, 6, 1]:\n tree.insert(element)\n tree_order = tree.in_width()\n self.assertEqual(tree_order, [12, 5, 16, 1, 14, 6, 19, 15, 20])\n\n def test_the_width_zero_level(self):\n \"\"\"\n Create a tree.\n Test the width order of a zero level.\n \"\"\"\n tree = Node(12)\n tree_order = tree.in_width()\n self.assertEqual(tree_order, [12])\n\n def test_the_width_elements(self):\n \"\"\"\n Create a tree.\n Test the width order of a new tree.\n \"\"\"\n tree = Node(12)\n elements = [5, 16, 14, 19, 15, 20, 6, 1]\n for element in elements:\n tree.insert(element)\n tree_order_length = len(tree.in_width())\n self.assertEqual(tree_order_length, len(elements) + 1)\n\n def test_delete_node_without_leaves(self):\n \"\"\"\n Delete a node without leaves.\n Test that a new tree is None.\n \"\"\"\n tree = Node(12)\n new_tree = tree.delete_node(tree, 12)\n self.assertEqual(None, new_tree)\n\n def test_delete_node_with_leaf(self):\n \"\"\"\n Delete node with a leaf.\n Test that a node is changed with the lowest left node.\n \"\"\"\n tree = Node(12)\n elements = [5, 16, 14, 19, 20]\n for element in elements:\n tree.insert(element)\n new_tree = tree.delete_node(tree, 16)\n new_tree_elements = new_tree.in_width()\n self.assertEqual([12, 5, 19, 14, 20], new_tree_elements)\n\n def test_delete_node_with_many_leaves(self):\n \"\"\"\n Delete node with a few leaves.\n Test that a new node is changed with the lowest and the order is the same.\n \"\"\"\n tree = Node(12)\n elements = [5, 16, 14, 19, 4, 8, 2, 6]\n for element in elements:\n tree.insert(element)\n new_tree = tree.delete_node(tree, 5)\n new_tree_elements = new_tree.in_width()\n self.assertEqual([12, 6, 16, 4, 14, 8, 19, 2], new_tree_elements)\n\n","sub_path":"tree/test_search_tree.py","file_name":"test_search_tree.py","file_ext":"py","file_size_in_byte":5406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"602862669","text":"import unittest\nimport numpy as np\n\nimport discretize\nfrom discretize import utils\n\nnp.random.seed(16)\n\nTOL = 1e-1\n\n\nclass TestCyl3DGeometries(unittest.TestCase):\n def setUp(self):\n hx = utils.meshTensor([(1, 1)])\n htheta = utils.meshTensor([(1.0, 4)])\n htheta = htheta * 2 * np.pi / htheta.sum()\n hz = hx\n\n self.mesh = discretize.CylMesh([hx, htheta, hz])\n\n def test_areas(self):\n area = self.mesh.area\n self.assertTrue(self.mesh.nF == len(area))\n self.assertTrue(\n area[: self.mesh.vnF[0]].sum() == 2 * np.pi * self.mesh.hx * self.mesh.hz\n )\n self.assertTrue(\n np.all(\n area[self.mesh.vnF[0] : self.mesh.vnF[1]] == self.mesh.hx * self.mesh.hz\n )\n )\n self.assertTrue(\n np.all(\n area[sum(self.mesh.vnF[:2]) :]\n == np.pi * self.mesh.hx ** 2 / self.mesh.nCy\n )\n )\n\n def test_edges(self):\n edge = self.mesh.edge\n self.assertTrue(self.mesh.nE == len(edge))\n self.assertTrue(np.all(edge[: self.mesh.vnF[0]] == self.mesh.hx))\n self.assertTrue(\n np.all(\n self.mesh.edge[self.mesh.vnE[0] : sum(self.mesh.vnE[:2])]\n == np.kron(np.ones(self.mesh.nCz + 1), self.mesh.hx * self.mesh.hy)\n )\n )\n self.assertTrue(\n np.all(\n self.mesh.edge[self.mesh.vnE[0] : sum(self.mesh.vnE[:2])]\n == np.kron(np.ones(self.mesh.nCz + 1), self.mesh.hx * self.mesh.hy)\n )\n )\n self.assertTrue(\n np.all(\n self.mesh.edge[sum(self.mesh.vnE[:2]) :]\n == np.kron(self.mesh.hz, np.ones(self.mesh.nCy + 1))\n )\n )\n\n def test_vol(self):\n self.assertTrue(self.mesh.vol.sum() == np.pi * self.mesh.hx ** 2 * self.mesh.hz)\n self.assertTrue(\n np.all(\n self.mesh.vol\n == np.pi * self.mesh.hx ** 2 * self.mesh.hz / self.mesh.nCy\n )\n )\n\n\n# ----------------------- Test Grids and Counting --------------------------- #\n\n\nclass Cyl3DGrid(unittest.TestCase):\n def setUp(self):\n self.mesh = discretize.CylMesh([2, 4, 1])\n\n def test_counting(self):\n mesh = self.mesh\n\n # cell centers\n self.assertEqual(mesh.nC, 8)\n self.assertEqual(mesh.nCx, 2)\n self.assertEqual(mesh.nCy, 4)\n self.assertEqual(mesh.nCz, 1)\n self.assertEqual(mesh.vnC, (2, 4, 1))\n\n # faces\n self.assertEqual(mesh.nFx, 8)\n self.assertEqual(mesh.nFy, 8)\n self.assertEqual(mesh.nFz, 16)\n self.assertEqual(mesh.nF, 32)\n self.assertEqual(mesh.vnFx, (2, 4, 1))\n self.assertEqual(mesh.vnFy, (2, 4, 1))\n self.assertEqual(mesh.vnFz, (2, 4, 2))\n self.assertEqual(mesh.vnF, (8, 8, 16))\n\n # edges\n self.assertEqual(mesh.nEx, 16)\n self.assertEqual(mesh.nEy, 16)\n self.assertEqual(mesh.nEz, 9) # there is an edge at the center\n self.assertEqual(mesh.nE, 41)\n self.assertEqual(mesh.vnEx, (2, 4, 2))\n self.assertEqual(mesh.vnEy, (2, 4, 2))\n self.assertEqual(mesh.vnEz, (3, 4, 1))\n self.assertEqual(mesh.vnE, (16, 16, 9))\n self.assertNotEqual(np.prod(mesh.vnEz), mesh.nEz) # periodic boundary condition\n\n # nodes\n self.assertEqual(mesh.nNx, 3)\n self.assertEqual(mesh.nNy, 4)\n self.assertEqual(mesh.nNz, 2)\n self.assertEqual(mesh.vnN, (3, 4, 2))\n self.assertEqual(mesh.nN, 18)\n self.assertNotEqual(mesh.nN, np.prod(mesh.vnN)) # periodic boundary condition\n\n def test_gridCC(self):\n mesh = self.mesh\n\n # Cell centers\n self.assertTrue((mesh.vectorCCx == [0.25, 0.75]).all())\n self.assertTrue(\n (\n mesh.vectorCCy\n == 2.0 * np.pi * np.r_[1.0 / 8.0, 3.0 / 8.0, 5.0 / 8.0, 7.0 / 8.0]\n ).all()\n )\n self.assertTrue(mesh.vectorCCz == 0.5)\n\n self.assertTrue((mesh.gridCC[:, 0] == 4 * [0.25, 0.75]).all())\n self.assertTrue(\n (\n mesh.gridCC[:, 1]\n == 2.0\n * np.pi\n * np.r_[\n 1.0 / 8.0,\n 1.0 / 8.0,\n 3.0 / 8.0,\n 3.0 / 8.0,\n 5.0 / 8.0,\n 5.0 / 8.0,\n 7.0 / 8.0,\n 7.0 / 8.0,\n ]\n ).all()\n )\n self.assertTrue((mesh.gridCC[:, 2] == 8 * [0.5]).all())\n\n def test_gridN(self):\n mesh = self.mesh\n\n # Nodes\n self.assertTrue((mesh.vectorNx == [0.0, 0.5, 1.0]).all())\n self.assertTrue(\n (mesh.vectorNy == 2 * np.pi * np.r_[0.0, 0.25, 0.5, 0.75]).all()\n )\n self.assertTrue((mesh.vectorNz == np.r_[0.0, 1.0]).all())\n\n self.assertTrue(\n (\n mesh.gridN[:, 0] == 2 * [0.0, 0.5, 1.0, 0.5, 1.0, 0.5, 1.0, 0.5, 1.0]\n ).all()\n )\n self.assertTrue(\n (\n mesh.gridN[:, 1]\n == 2\n * np.pi\n * np.hstack(\n 2 * [3 * [0.0], 2 * [1.0 / 4.0], 2 * [1.0 / 2.0], 2 * [3.0 / 4.0]]\n )\n ).all()\n )\n self.assertTrue((mesh.gridN[:, 2] == 9 * [0.0] + 9 * [1.0]).all())\n\n def test_gridFx(self):\n mesh = self.mesh\n\n # x-faces\n self.assertTrue((mesh.gridFx[:, 0] == 4 * [0.5, 1.0]).all())\n self.assertTrue(\n (\n mesh.gridFx[:, 1]\n == 2\n * np.pi\n * np.hstack(\n [2 * [1.0 / 8.0], 2 * [3.0 / 8.0], 2 * [5.0 / 8.0], 2 * [7.0 / 8.0]]\n )\n ).all()\n )\n self.assertTrue((mesh.gridFx[:, 2] == 8 * [0.5]).all())\n\n def test_gridFy(self):\n mesh = self.mesh\n\n # y-faces\n self.assertTrue((mesh.gridFy[:, 0] == 4 * [0.25, 0.75]).all())\n self.assertTrue(\n (\n mesh.gridFy[:, 1]\n == 2\n * np.pi\n * np.hstack(\n [2 * [0.0], 2 * [1.0 / 4.0], 2 * [1.0 / 2.0], 2 * [3.0 / 4.0]]\n )\n ).all()\n )\n self.assertTrue((mesh.gridFy[:, 2] == 8 * [0.5]).all())\n\n def test_gridFz(self):\n mesh = self.mesh\n\n # z-faces\n self.assertTrue((mesh.gridFz[:, 0] == 8 * [0.25, 0.75]).all())\n self.assertTrue(\n (\n mesh.gridFz[:, 1]\n == 2\n * np.pi\n * np.hstack(\n 2\n * [\n 2 * [1.0 / 8.0],\n 2 * [3.0 / 8.0],\n 2 * [5.0 / 8.0],\n 2 * [7.0 / 8.0],\n ]\n )\n ).all()\n )\n self.assertTrue((mesh.gridFz[:, 2] == np.hstack([8 * [0.0], 8 * [1.0]])).all())\n\n def test_gridEx(self):\n mesh = self.mesh\n\n # x-edges\n self.assertTrue((mesh.gridEx[:, 0] == 8 * [0.25, 0.75]).all())\n self.assertTrue(\n (\n mesh.gridEx[:, 1]\n == 2\n * np.pi\n * np.hstack(\n 2 * [2 * [0.0], 2 * [1.0 / 4.0], 2 * [1.0 / 2.0], 2 * [3.0 / 4.0]]\n )\n ).all()\n )\n self.assertTrue((mesh.gridEx[:, 2] == np.hstack([8 * [0.0], 8 * [1.0]])).all())\n\n def test_gridEy(self):\n mesh = self.mesh\n\n # y-edges\n self.assertTrue((mesh.gridEy[:, 0] == 8 * [0.5, 1.0]).all())\n self.assertTrue(\n (\n mesh.gridEy[:, 1]\n == 2\n * np.pi\n * np.hstack(\n 2\n * [\n 2 * [1.0 / 8.0],\n 2 * [3.0 / 8.0],\n 2 * [5.0 / 8.0],\n 2 * [7.0 / 8.0],\n ]\n )\n ).all()\n )\n self.assertTrue((mesh.gridEy[:, 2] == np.hstack([8 * [0.0], 8 * [1.0]])).all())\n\n def test_gridEz(self):\n mesh = self.mesh\n\n # z-edges\n self.assertTrue(\n (mesh.gridEz[:, 0] == np.hstack([[0.0, 0.5, 1.0] + 3 * [0.5, 1.0]])).all()\n )\n self.assertTrue(\n (\n mesh.gridEz[:, 1]\n == 2\n * np.pi\n * np.hstack(\n [3 * [0.0], 2 * [1.0 / 4.0], 2 * [1.0 / 2.0], 2 * [3.0 / 4.0]]\n )\n ).all()\n )\n self.assertTrue((mesh.gridEz[:, 2] == 9 * [0.5]).all())\n\n\n# ------------------- Test conversion to Cartesian ----------------------- #\n\n\nclass TestCartesianGrid(unittest.TestCase):\n def test_cartesianGrid(self):\n mesh = discretize.CylMesh([1, 4, 1])\n\n root2over2 = np.sqrt(2.0) / 2.0\n\n # cell centers\n cartCC = mesh.cartesianGrid(\"CC\")\n self.assertTrue(\n np.allclose(cartCC[:, 0], 0.5 * root2over2 * np.r_[1.0, -1.0, -1.0, 1.0])\n )\n self.assertTrue(\n np.allclose(cartCC[:, 1], 0.5 * root2over2 * np.r_[1.0, 1.0, -1.0, -1.0])\n )\n self.assertTrue(np.allclose(cartCC[:, 2], 0.5 * np.ones(4)))\n\n # nodes\n cartN = mesh.cartesianGrid(\"N\")\n self.assertTrue(\n np.allclose(cartN[:, 0], np.hstack(2 * [0.0, 1.0, 0.0, -1.0, 0.0]))\n )\n self.assertTrue(\n np.allclose(cartN[:, 1], np.hstack(2 * [0.0, 0.0, 1.0, 0.0, -1.0]))\n )\n self.assertTrue(np.allclose(cartN[:, 2], np.hstack(5 * [0.0] + 5 * [1.0])))\n\n\nclass Deflation(unittest.TestCase):\n def test_areas(self):\n mesh = discretize.CylMesh([1, 2, 1])\n\n areas = np.hstack([[np.pi] * 2, [1] * 2, [np.pi / 2] * 4])\n self.assertTrue(np.all(mesh.area == areas))\n\n edges = np.hstack([[1] * 4, [np.pi] * 4, [1] * 3])\n self.assertTrue(np.all(mesh.edge == edges))\n\n mesh = discretize.CylMesh([2, 5, 3])\n\n hangingF = np.hstack(\n [getattr(mesh, \"_ishanging_faces_{}\".format(dim)) for dim in [\"x\", \"y\", \"z\"]]\n )\n self.assertTrue(np.all(mesh._face_areas_full[~hangingF] == mesh.area))\n hangingE = np.hstack(\n [getattr(mesh, \"_ishanging_edges_{}\".format(dim)) for dim in [\"x\", \"y\", \"z\"]]\n )\n self.assertTrue(np.all(mesh._edge_lengths_full[~hangingE] == mesh.edge))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/cyl/test_cyl3D.py","file_name":"test_cyl3D.py","file_ext":"py","file_size_in_byte":10649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"237424654","text":"import pprint as pp\n\nfrom Database import *\nfrom Similarity import *\n\ndef calc_similarities(ratings, user, similarity=similarity_distance):\n '''\n calculate the specified user's similarity with all the other users\n\n @param ratings - rating matrix: USER (vertical) x MOVIE (horizontal)\n @param user - specified user\n @param similarity - similarity distance function\n @return (similarity_value, with_which_user) list\n '''\n users = set(map(lambda l: l[0], ratings.keys()))\n\n sims = [(similarity(ratings, user, u), u) for u in users if u != user]\n sims.sort() # smallest first\n sims.reverse() # biggest first\n\n print(\"SIMILARITY list for \" + user + \": \")\n pp.pprint(sims)\n return sims\n\ndef get_recommendations(ratings, user, similarity=similarity_distance):\n '''\n predict the given user's likeness on each movie by his/her similarity with\n other users and the ratings rated by other users\n\n @param ratings - rating matrix: USER (vertical) x MOVIE (horizontal)\n @param user - specified user\n @param similarity - similarity distance function\n @return (score, movie) list which represents the user's likeness on each\n moview, note that the score is normalized to [0.0, 1.0]\n '''\n users = set(map(lambda l: l[0], ratings.keys()))\n movies = set(map(lambda l: l[1], ratings.keys()))\n\n # similarity and normalized score on each movie\n # sum over all the other users in our system\n sim_on_movie = {}\n score_on_movie = {}\n for u in users:\n if u == user:\n continue\n\n sim = similarity_distance(ratings, user, u)\n if sim <= 0:\n continue\n\n for m in movies:\n if ratings[(u, m)] == \"\":\n continue\n\n sim_on_movie.setdefault(m, 0)\n sim_on_movie[m] += sim\n score_on_movie.setdefault(m, 0)\n score_on_movie[m] += float(ratings[u, m]) * sim\n\n # final weighted likeness on each movie\n likeness = [(sim_on_movie[m] / score_on_movie[m], m) for m in movies]\n likeness.sort()\n likeness.reverse()\n\n print(\"predicted LIKENESS list for \" + user + \": \")\n pp.pprint(likeness)\n return likeness\n\nif __name__ == '__main__':\n ratings = load_file()\n\n # calculate the similarity with the other users\n calc_similarities(ratings, 'User1', similarity_distance)\n\n # predict the likeness on each movie by using other users' ratings\n likeness = get_recommendations(ratings, 'User1', similarity_distance)\n","sub_path":"python/recommendation-system/Recommend.py","file_name":"Recommend.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"151065293","text":"import os\nfrom flask import Flask, render_template, redirect, request, url_for\nfrom flask_pymongo import PyMongo\nfrom bson.objectid import ObjectId\nfrom os import path\nif path.exists(\"env.py\"):\n import env\n\napp = Flask(__name__)\n\napp.config[\"MONGO_DBNAME\"] = \"gametionary\"\napp.config[\"MONGO_URI\"] = os.environ.get(\"MONGO_URI\")\n\nmongo = PyMongo(app)\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template(\"index.html\", entries=mongo.db.entries.aggregate([{'$sample': {'size': 2}}]))\n\n\n@app.route('/az')\ndef az():\n return render_template(\"az.html\", entries=mongo.db.entries.find().sort('name'))\n\n\n@app.route('/random')\ndef random():\n return render_template(\"random.html\", random_entry=mongo.db.entries.aggregate([{'$sample': {'size': 1}}]))\n\n\n@app.route('/top_rated')\ndef top_rated():\n return render_template(\"toprated.html\", entries=mongo.db.entries.find().sort('upvotes', -1).collation({'locale': 'en', 'numericOrdering': True}).limit(20))\n\n\n@app.route('/search')\ndef search():\n return render_template(\"search.html\", entries=mongo.db.entries.find(), results_hidden=\"hidden\")\n\n\n@app.route('/search_db', methods=['POST'])\ndef search_db():\n search = request.form.get('search_term')\n return render_template(\"search.html\", entries=mongo.db.entries.find({'name': {'$regex': search, '$options': 'i'}}), search_term=search, results_found=mongo.db.entries.find({'name': {'$regex': search, '$options': 'i'}}).count(), results_hidden=\"\")\n\n\n@app.route('/add_entry')\ndef add_entry():\n return render_template(\"addentry.html\")\n\n\n@app.route('/insert_entry', methods=['POST'])\ndef insert_entry():\n request_dict = request.form.to_dict()\n request_dict['upvotes'] = 0\n entries = mongo.db.entries\n entries.insert_one(request_dict)\n return redirect(url_for('add_entry'))\n\n\n@app.route('/edit_entry/')\ndef edit_entry(entry_id):\n the_entry = mongo.db.entries.find_one({\"_id\": ObjectId(entry_id)})\n return render_template('editentry.html', entry=the_entry)\n\n\n@app.route('/update_entry/', methods=['POST'])\ndef update_entry(entry_id):\n entries = mongo.db.entries\n entries.update({'_id': ObjectId(entry_id)},\n {\n 'name': request.form.get('name'),\n 'description': request.form.get('description'),\n 'upvotes': int(request.form.get('upvotes'))\n })\n return redirect(url_for('index'))\n\n\n@app.route('/delete_entry/')\ndef delete_entry(entry_id):\n mongo.db.entries.remove({'_id': ObjectId(entry_id)})\n return redirect(url_for('index'))\n\n\n@app.route('/add_upvote///')\ndef add_upvote(page, entry_id):\n entries = mongo.db.entries\n entries.update({'_id': ObjectId(entry_id)}, {'$inc': {'upvotes': 1}})\n return redirect(url_for(page))\n\n\nif __name__ == '__main__':\n app.run(host=os.environ.get('IP'),\n port=int(os.environ.get('PORT')),\n debug=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"276610258","text":"\"\"\"\nCompose subcommand\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport sys\n\nimport sh\n\nfrom .base import BaseSubcommand\n\nfrom compose_flow import docker\n\nfrom distutils.spawn import find_executable\n\n\nclass Compose(BaseSubcommand):\n \"\"\"\n Subcommand for running compose commands\n \"\"\"\n dirty_working_copy_okay = True\n\n def __init__(self, *args, **kwargs):\n # pop off the compose_args kwarg\n compose_args = kwargs.pop('compose_args', None)\n\n super().__init__(*args, **kwargs)\n\n @classmethod\n def fill_subparser(cls, parser, subparser) -> None:\n subparser.add_argument('compose_args', nargs=argparse.REMAINDER)\n\n def handle(self, compose_args:list=None) -> [None, str]:\n # check the profile to make sure it defines all the needed environment variables\n self.profile.check()\n\n command = ['docker-compose']\n command[0] = find_executable(command[0])\n\n command.extend([\n '--project-name', self.args.project_name,\n '-f', self.profile.filename,\n ])\n\n compose_args = compose_args or self.args.compose_args\n command.extend(compose_args)\n\n self.logger.info(' '.join(command))\n\n if not self.args.dry_run:\n # os.execve(command[0], command, os.environ)\n proc = getattr(sh, command[0])\n proc(*command[1:], _env=os.environ, _fg=True)\n\n @property\n def logger(self) -> logging.Logger:\n return logging.getLogger(f'{__name__}.{self.__class__.__name__}')\n","sub_path":"src/compose_flow/commands/subcommands/compose.py","file_name":"compose.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"598261008","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pathlib import Path\nimport os\n\n\nheader = {\n 'Cookie': '__mta=216432553.1536930122712.1536930173280.1536930177362.7; uuid_n_v=v1; uuid=4EF922C0B81E11E89AC36519AF5FE092C146C7B7F03F4EEC808393DA9307FCF3; _csrf=c43f46357f0a7531fd371cb08f2ee27849d1c67ea003d287dc75ffe42e43e15f; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; _lxsdk_cuid=165d82c667cc8-0f55dd532775fa-5701732-100200-165d82c667e1a; _lxsdk=4EF922C0B81E11E89AC36519AF5FE092C146C7B7F03F4EEC808393DA9307FCF3; _lxsdk_s=165d82c6680-8ba-1aa-1b1%7C%7C22',\n'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'\n}\n# page_url = 'https://movie.douban.com/top250?start={}&filter='\npage_url = 'http://maoyan.com/board/4?offset={}'\n\ndef get_more_pages(page_url):\n for i in range(0,100,10):\n url = page_url.format(i)\n get_details(url, header)\n\n\ndef get_details(url,header):\n current_path = os.getcwd()\n folder_path = current_path + \"\\\\maoyan\"\n path = Path(folder_path)\n web_data = requests.get(url,headers = header)\n soup = BeautifulSoup(web_data.text, 'lxml')\n imgs = soup.select('.board-img')\n\n if (path.exists()):\n pass\n else:\n path.mkdir()\n for img in imgs:\n print(img.get('data-src'))\n name = img.get('alt')\n print(name)\n img_download_link = img.get('data-src').split('@')[0]\n print(img_download_link)\n # pic_name = name + '.' + img_download_link.split('.')[-1]\n pic_name = name + img_download_link[-4:]\n res = requests.get(img_download_link)\n with open(str(path) + \"\\\\\" + pic_name, 'wb') as f:\n f.write(res.content)\n print(name)\n\n#url = 'https://movie.douban.com/top250?start=225&filter='\nif __name__ == \"__main__\":\n get_more_pages(page_url)\n\n# get_details('http://maoyan.com/board/4?offset=0',header)","sub_path":"get_films_top250.py","file_name":"get_films_top250.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"338010853","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\\\r\ntf.data.Dataset用のマップ関数群。\r\nJPEG2000関連の関数をまとめている。\r\n\"\"\"\r\nimport tensorflow as tf\r\nfrom ..util import get_args, dict_to_oneline\r\n\r\n\r\ndef map_add_cls(cls_id=257, log=None):\r\n \"\"\"\\\r\n 系列の先頭にを追加する。\r\n 分類問題ではこのの特徴ベクトルを使って判定する。\r\n\r\n Args:\r\n cls_id int:\r\n 語彙のIDを指定する。\r\n\r\n Returns:\r\n (function):\r\n TensorFlow Dataset用のマップ関数を返す。\r\n \"\"\"\r\n if log and isinstance(log, list):\r\n args = get_args(ignore_last=1)\r\n log.append('クラスヘッダ追加\\t%s' % dict_to_oneline(args))\r\n script = \"\"\"def map_func(sequence, label):\r\n sequence = tf.concat([\r\n tf.constant([%d], dtype=sequence.dtype),\r\n sequence], -1)\r\n return sequence, label\r\n \"\"\" % cls_id\r\n exec(script, globals())\r\n return map_func","sub_path":"maps/jpeg2000.py","file_name":"jpeg2000.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"554164028","text":"import asyncio\nimport aiorpcx\nimport logging\n\n\nasync def main():\n async with aiorpcx.ClientSession('localhost', 8888) as session:\n session.send_request('echo', [\"Howdy\"])\n session.send_request('sum', [2, 4, \"b\"])\n\n for request in session.all_requests():\n try:\n await request\n except Exception:\n print(f\"ERROR: {request} -> {request.exception()}\")\n else:\n print(f\"OK: {request} -> {request.result()}\")\n\n batch = session.new_batch()\n batch.add_request('echo', [\"Me again\"])\n batch.add_request('sum', list(range(50)))\n session.send_batch(batch)\n await batch\n for request in batch:\n try:\n print(f\"OK: {request} -> {request.result()}\")\n except Exception:\n print(f\"ERROR: {request} -> {request.exception()}\")\n\n\nlogging.basicConfig(level=logging.DEBUG)\nloop = asyncio.get_event_loop()\nloop.run_until_complete(main())\n","sub_path":"examples/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"515384160","text":"\"\"\"\nPortraits Provider\n\"\"\"\nfrom zope.interface import implements\n\nfrom AccessControl import ClassSecurityInfo\nfrom App.class_init import InitializeClass\nfrom App.special_dtml import DTMLFile\nfrom Products.BTreeFolder2.BTreeFolder2 import BTreeFolder2\n\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFCore.permissions import ManagePortal\nfrom Products.PluggableAuthService.plugins.BasePlugin import BasePlugin\nfrom Products.PlonePAS.interfaces.plugins import IPortraitManagementPlugin\nfrom Products.PlonePAS.interfaces.capabilities import IChangePortraitCapability\nfrom OFS.Image import Image\nfrom Products.PlonePAS.utils import scale_image\n\n\nclass VirtualImage(object):\n\n meta_type = 'VirtualImage'\n\n def __init__(self, id, width=None, height=None, title='', url=''):\n self.id = id\n self.url = url\n self.width = width\n self.title = title\n self.height = height\n\n def getId(self):\n return self.id\n\n def absolute_url(self):\n return self.url\n\n\ndef manage_addZODBPortraitProvider(self, id, title='',\n RESPONSE=None, **kw):\n \"\"\"\n Create an instance of a portraits manager.\n \"\"\"\n o = ZODBPortraitProvider(id, title, **kw)\n self._setObject(o.getId(), o)\n\n if RESPONSE is not None:\n RESPONSE.redirect('manage_workspace')\n\nmanage_addZODBPortraitProviderForm = DTMLFile(\n \"../zmi/PortraitProviderForm\", globals())\n\n\nclass ZODBPortraitProvider(BasePlugin):\n \"\"\"Storage for portraits in the ZODB.\n \"\"\"\n\n meta_type = 'ZODB Portrait Provider'\n\n implements(IPortraitManagementPlugin,\n IChangePortraitCapability)\n security = ClassSecurityInfo()\n\n manage_options = (BasePlugin.manage_options +\n ( { 'label' : 'Migrate portraits'\n , 'action' : 'manage_migrate_portraits'\n },))\n\n security.declareProtected(ManagePortal, 'manage_migrate_portraits')\n manage_migrate_portraits = DTMLFile('../zmi/migrate_portraits', globals())\n\n def __init__(self, id, title='', **kw):\n \"\"\"Create in-ZODB portrait provider.\n \"\"\"\n self.id = id\n self.title = title\n self.portraits=BTreeFolder2(id='portraits')\n\n def getPortrait(self, member_id):\n \"\"\" return member_id's portrait if you can \"\"\"\n return self.portraits.get(member_id, None)\n \n def setPortrait(self, portrait, member_id):\n \"\"\" store portrait for particular member.\n portrait must be file-like object\"\"\"\n if member_id in self.portraits:\n self.portraits._delObject(member_id)\n \n # ignore VirtualImage portraits\n if isinstance(portrait, VirtualImage):\n return False\n\n if portrait and portrait.filename:\n scaled, mimetype = scale_image(portrait)\n portrait = Image(id=safe_id, file=scaled, title='')\n self.portraits._setObject(id= member_id, object=portrait)\n return True\n \n def deletePortrait(self, member_id):\n \"\"\" remove member_id's portrait \"\"\"\n if member_id in self.portraits:\n self.portraits._delObject(member_id)\n return True\n\n security.declareProtected(ManagePortal, 'migratePortraits' )\n def migratePortraits(self):\n \"\"\" migrate portraits from MemberDataTool._portraits \"\"\"\n md = getToolByName(self, 'portal_memberdata')\n storage = getattr(md, 'portraits', None)\n count = removed = 0\n if storage is not None:\n for member_id, portrait in storage.items():\n if self.getPortrait(member_id) is None:\n self.portraits._setObject(id= member_id, object=portrait)\n count += 1\n del storage[member_id]\n removed += 1\n return count, removed\n \n def portraitInfo(self):\n md = getToolByName(self, 'portal_memberdata')\n result = {'md': 0, 'plugin': len(self.portraits)}\n storage = getattr(md, 'portraits', None)\n if storage is not None:\n result['md'] = len(storage)\n return result\n\n # IChangePortraitCapability \n def allowModifyPortrait(self, member_id):\n return True\n \nInitializeClass(ZODBPortraitProvider)\n\ndef manage_addPortalMemberdataPortraitProvider(self, id, title='',\n RESPONSE=None, **kw):\n \"\"\"\n Create an instance of a portraits manager.\n \"\"\"\n o = PortalMemberdataPortraitProvider(id, title, **kw)\n self._setObject(o.getId(), o)\n\n if RESPONSE is not None:\n RESPONSE.redirect('manage_workspace')\n\nmanage_addPortalMemberdataPortraitProviderForm = DTMLFile(\n \"../zmi/PortalMemberdataPortraitProviderForm\", globals())\n \nclass PortalMemberdataPortraitProvider(BasePlugin):\n \"\"\"Reuse portal_memberdata portraits storage\n \"\"\"\n\n meta_type = 'PortalMemberdata Portrait Provider'\n\n implements(IPortraitManagementPlugin,\n IChangePortraitCapability)\n\n def __init__(self, id, title='', **kw):\n \"\"\"Create portrait provider.\n \"\"\"\n self.id = id\n self.title = title\n\n def getPortrait(self, member_id):\n \"\"\" return member_id's portrait if you can \"\"\"\n mds = getattr(getToolByName(self, 'portal_memberdata'), 'portraits', None)\n if mds is not None:\n return mds.get(member_id, None)\n \n def setPortrait(self, portrait, member_id):\n \"\"\" store portrait for particular member.\n portrait must be OFS.Image.Image \"\"\"\n # ignore VirtualImage portraits\n if isinstance(portrait, VirtualImage):\n return False\n\n mds = getattr(getToolByName(self, 'portal_memberdata'), 'portraits', None)\n if mds is not None:\n if member_id in mds:\n mds._delObject(member_id)\n mds._setObject(id= member_id, object=portrait)\n return True\n \n def deletePortrait(self, member_id):\n \"\"\" remove member_id's portrait \"\"\"\n mds = getattr(getToolByName(self, 'portal_memberdata'), 'portraits', None)\n if mds is not None:\n if member_id in mds:\n mds._delObject(member_id)\n return True\n\n # IChangePortraitCapability \n def allowModifyPortrait(self, member_id):\n return True\n\nInitializeClass(PortalMemberdataPortraitProvider)\n","sub_path":"Products/PlonePAS/plugins/portraits.py","file_name":"portraits.py","file_ext":"py","file_size_in_byte":6436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"115820401","text":"import socket\r\n\r\n\r\ndef is_valid_ipv4_address(address):\r\n try:\r\n socket.inet_pton(socket.AF_INET, address)\r\n except AttributeError:\r\n try:\r\n socket.inet_aton(address)\r\n except socket.error:\r\n return False\r\n return address.count('.') == 3\r\n except socket.error:\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef is_valid_port(begin_port, end_port):\r\n if (begin_port < 1 and end_port > 65353):\r\n return False\r\n return True\r\n\r\n\r\ndef scan(ip, begin_port, end_port):\r\n open_ports = []\r\n for port in range(begin_port, end_port+1):\r\n s = socket.socket()\r\n try:\r\n\r\n s.connect((ip, port))\r\n print(\"[!] port \"+str(port), \" is open | service :\" +\r\n socket.getservbyport(port))\r\n open_ports.append(str(port))\r\n except:\r\n print(\"[X] port \" + str(port) + \" closed\")\r\n finally:\r\n s.close()\r\n\r\n print(\"****************************\")\r\n print(\"the open ports are : \")\r\n for i in open_ports:\r\n print(\"port \"+i+\" | \" + \"service : \"+socket.getservbyport(int(i)))\r\n\r\n print(\"****************************\")\r\n","sub_path":"portscanlib.py","file_name":"portscanlib.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"209559199","text":"# Python Flask Essential Training\n# Module 3: HTTP Request\n# File Upload\n\nfrom flask import Flask, render_template, request\n# from werkzeug import secure_filename\napp = Flask(__name__)\n\n@app.route('/uploader',methods = ['GET','POST'])\ndef upload_file():\n\tif request.method == 'POST':\n\t\tf = request.files['file']\n\t\tf.save(f.filename)\n\t\treturn 'file uploaded successfully'\n\n@app.route('/upload')\ndef upload():\n return render_template('upload_file.html')\n\nif __name__ == '__main__':\n app.run()","sub_path":"exercises/module3_HTTP_Requests/module3_5_Upload_file.py","file_name":"module3_5_Upload_file.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618366975","text":"#197 Выдвигаться,выдвигайся\n#181 Атаковать,атакуй\n#165 Совершить марш,соверши марш\n#149 Отойти,отойди\n#133 Провести разведку,проведи разведку\n#117 Проделать проход,проделай проход\n#101 Прекратить подавление\n#85 Подавить,подави\n\nOnlineMode = vc.getObject(\"evalvars\",\"{var.OnlineMode}\")\nstatusPodavlenie = int(vc.getObject(\"evalvars\",\"{var.Podavlenie{var.Name}}\"))\n\ncoordCommand = vc.getObject(\"payloads\",\"\")\ncoordCommand = int(coordCommand[0])\n\nif statusPodavlenie == 1 and coordCommand >= 117:\n coordCommand = coordCommand + 16\nelse:\n coordCommand = coordCommand\n\nif OnlineMode == \"1\":\n result = coordCommand + 16\nelse:\n result = coordCommand","sub_path":"PY/SBPPE.CheckCoordCommand12.py","file_name":"SBPPE.CheckCoordCommand12.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"131358828","text":"\n\nfrom xai.brain.wordbase.nouns._kicker import _KICKER\n\n#calss header\nclass _KICKERS(_KICKER, ):\n\tdef __init__(self,): \n\t\t_KICKER.__init__(self)\n\t\tself.name = \"KICKERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"kicker\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_kickers.py","file_name":"_kickers.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"128537354","text":"import numpy as np\n\nimport matplotlib.pyplot as plt\n\n\nclass GraphLive:\n\n\tgraph_count = 0\n\tplt.style.use('ggplot')\n\tauto_scale = False\n\n\tdef __init__(self, x_vec=None, y_vec=None, ax=None, title=None, x_label=None, y_label=None):\n\t\tself.x_vec = x_vec\n\t\tself.y_vec = y_vec\n\t\tself.line = []\n\t\tself.ax = ax\n\t\tself.title = title\n\t\tself.x_label = x_label\n\t\tself.y_label = y_label\n\n\tdef initialization(self):\n\t\tself.ax.set_ylabel(self.y_label)\n\t\tself.ax.set_xlabel(self.x_label)\n\t\tself.ax.set_title(self.title)\n\n\tdef live_line_evolution(self, y_limit=None, x_limit=None, pause_time=0.0002):\n\t\tif not self.line:\n\t\t\tplt.ion()\n\t\t\tif not GraphLive.auto_scale:\n\t\t\t\tself.ax.set_ylim(y_limit)\n\t\t\tself.ax.set_xlim(x_limit)\n\t\t\tself.initialization()\n\t\t\tself.line, = self.ax.plot(self.x_vec, self.y_vec, '-', alpha=0.8)\n\t\t\tplt.tight_layout(4, h_pad=3)\n\t\t\tplt.show()\n\t\tself.line.set_ydata(self.y_vec)\n\t\tif GraphLive.auto_scale:\n\t\t\tself.ax.relim()\n\t\t\tself.ax.autoscale_view()\n\t\tplt.pause(pause_time)\n\t\treturn None\n\n\tdef live_regression(self, y_limit=None, x_limit=None, theta=None, true_theta=None, pause_time=0.002):\n\t\tx_reg = np.array([0, 1.2 * np.max(self.x_vec, axis=0)])\n\t\ty_reg = theta[0] + theta[1] * x_reg\n\t\tif not self.line:\n\t\t\tplt.ion()\n\t\t\tself.ax.set_ylim(y_limit)\n\t\t\tself.ax.set_xlim(x_limit)\n\t\t\tself.initialization()\n\t\t\tself.line, = self.ax.plot(x_reg, y_reg, '-', alpha=0.8)\n\t\t\tif true_theta is not None:\n\t\t\t\ty_true = true_theta[0] + true_theta[1] * x_reg\n\t\t\t\tself.ax.plot(x_reg, y_true, '-', color=\"green\", alpha=0.3)\n\t\t\tself.ax.scatter(self.x_vec, self.y_vec, c='blue')\n\t\t\tplt.tight_layout(4, h_pad=3)\n\t\t\tplt.show()\n\t\tself.line.set_ydata(y_reg)\n\t\tplt.pause(pause_time)\n\t\treturn None\n\n\tdef draw_contour(self, f, theta=None, pause_time=0.002):\n\t\tif not self.line:\n\t\t\tplt.ion()\n\t\t\ty_min = np.min(self.y_vec)\n\t\t\ty_max = np.max(self.y_vec)\n\t\t\tx_min = np.min(self.x_vec)\n\t\t\tx_max = np.max(self.x_vec)\n\t\t\tself.ax.set_ylim((y_min, y_max))\n\t\t\tself.ax.set_xlim((x_min, x_max))\n\t\t\tself.initialization()\n\t\t\tT0, T1 = np.meshgrid(self.x_vec, self.y_vec)\n\t\t\tZ = np.array([f(np.array([t0,t1])) for t0, t1 in zip(np.ravel(T0), np.ravel(T1))])\n\t\t\tZ = Z.reshape(T0.shape)\n\t\t\tself.ax.contour(T0, T1, Z, 20, cmap='RdGy')\n\t\t\tself.line, = self.ax.plot(theta[0], theta[1], '-', alpha=0.8)\n\t\t\tplt.show()\n\t\tself.line.set_xdata(np.append(self.line.get_xdata(), theta[0]))\n\t\tself.line.set_ydata(np.append(self.line.get_ydata(), theta[1]))\n\n\t\tplt.pause(pause_time)\n\t\treturn None\n\n\t@classmethod\n\tdef close(cls, alpha, iter):\n\t\tplt.ioff()\n\t\tplt.show()\n\n","sub_path":"logreg_files/class_plot.py","file_name":"class_plot.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"160057847","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"Invokes the CSP solver to solve the Futoshiki puzzle.\n\nThis module reads the Futoshiki puzzle from the standard input and prints the solution and time taken to solve it.\nBy default, it calls the 'backtracking_search' method in '../solutions/p6_solver.py', but you can optionally\nspecify a different python filename and a method name to use as the solver.\n\nFor example:\n\n $ python solve_puzzle.py < ../problems/p6/in/input1.txt\n\nOr\n\n $ python solve_puzzle.py ../solutions/p3_basic_backtracking.py backtracking_search < ../problems/p6/in/input1.txt\n\nto use the basic backtracking solver.\n\nYou can also pipe the output from fetch_puzzle.py, for e.g.\n\n $ python fetch_puzzle.py 4 1 110 | python solve_puzzle.py\n\n\"\"\"\n\n__author__ = 'Tomoki Tsuchida'\n__email__ = 'ttsuchida@ucsd.edu'\n\nfrom time import time\nimport sys\nimport os.path\n\nfrom assignment3 import Futoshiki\n\n\ndef solve_puzzle(puzzle, solve_method):\n \"\"\"Solves the puzzle using the given solution method and returns the approximate time taken in seconds.\"\"\"\n start_time = time()\n result = puzzle.solve_with(solve_method)\n if result:\n print(puzzle)\n else:\n print(\"Failed to find the solution.\")\n return time() - start_time\n\n\nif __name__ == '__main__':\n\n python_file = '../solutions/p6_solver.py' if len(sys.argv) < 2 else sys.argv[1]\n method_name = 'backtracking_search' if len(sys.argv) < 3 else sys.argv[2]\n\n sys.path.append(os.path.abspath(os.path.dirname(python_file)))\n module = __import__(os.path.splitext(os.path.basename(python_file))[0])\n solve_method = getattr(module, method_name)\n\n puzzle = Futoshiki(sys.stdin.read().strip())\n\n start_time = time()\n result = puzzle.solve_with(solve_method)\n if result:\n print(puzzle)\n else:\n print(\"Failed to find the solution.\")\n print(\"Took %s seconds.\" % (time() - start_time))","sub_path":"hw3/src/solve_puzzle.py","file_name":"solve_puzzle.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"652838603","text":"filename = \"adult.test\"\nnewfilename = \"adult_test_result.txt\"\n\nwith open(filename,\"r\") as in_file:\n with open(newfilename,\"w\") as out_file:\n lines = in_file.readlines()\n for l in lines:\n skip=0;\n cells = l.split(\", \")\n if len(cells)!=15: continue\n for c in cells:\n if c==\"?\":\n skip=1\n break\n #skip rows with missing value\n if skip==0:\n if cells[14]==\"<=50K.\\n\":\n out_file.write(\"low\\n\")\n else:\n out_file.write(\"high\\n\")\n #put labels at the first column\n","sub_path":"gen_test_result.py","file_name":"gen_test_result.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"140856015","text":"import os\n\nimport django\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'QA_daddylab.settings')\ndjango.setup()\nfrom auto.models import ApiCase\n\nfrom myCelery.run_case.HttpRequest import HttpRequester\nimport unittest\nimport logging\n\n\nclass ParametrizedTestCase(unittest.TestCase):\n \"\"\" TestCase classes that want to be parametrized should\n inherit from this class.\n \"\"\"\n\n def __init__(self, methodName='runTest', param=None):\n super(ParametrizedTestCase, self).__init__(methodName)\n self.param = param\n\n @staticmethod\n def parametrize(testcase_klass, param=None):\n \"\"\" Create a suite containing all tests taken from the given\n subclass, passing them the parameter 'param'.\n \"\"\"\n testloader = unittest.TestLoader()\n testnames = testloader.getTestCaseNames(testcase_klass)\n suite = unittest.TestSuite()\n for name in testnames:\n suite.addTest(testcase_klass(name, param=param))\n return suite\n\n\nclass APICaseTest(ParametrizedTestCase):\n\n def test_HttpCase(self):\n print(type(self.param))\n # hr = HttpRequester(self.param)\n id = self.param\n hr = HttpRequester(id)\n\n # url\n # url = hr.reg_url()\n # # 请求data\n # data = hr.reg_data()\n #\n # cc = hr.http_request()\n # print(cc.json())\n\n # 断言\n sts = hr.validators_result()\n ApiCase.objects.filter(id=id).update(status=sts)\n\n\nif __name__ == '__main__':\n uapi = APICaseTest()\n","sub_path":"myCelery/run_case/redis1.py","file_name":"redis1.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"159382593","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom DjangoShopper.decorators import token_required\nfrom .models import Product, Order, OrderProductRelation\nfrom django.http import JsonResponse\nimport json\nfrom json import JSONEncoder\nfrom users.models import User\n\n\n# show all products\n@token_required\ndef show_products_list(request, token):\n products = Product.objects.all().values('id', 'name', 'stock', 'price')\n return JsonResponse(list(products), safe=False)\n\n\n# create an order by send a list\n@token_required\ndef new_order(request, token):\n order_list = json.loads(request.body)\n id_list = []\n orders = []\n products = []\n for i in order_list:\n id_list.append(i[\"id\"])\n p = Product.objects.get(id=i[\"id\"])\n if p.stock <= i[\"order_number\"]:\n return JsonResponse(\n {'status': 'error',\n 'product_name': p.name,\n 'product_stock': p.stock,\n 'type': 'NotEnoughInventory',\n }, encoder=JSONEncoder)\n ordered_product = {}\n ordered_product['id'] = p.id\n ordered_product['name'] = p.name\n ordered_product[\"order_number\"] = i[\"order_number\"]\n ordered_product['end_price'] = i[\"order_number\"] * p.price\n ordered_product['unit_price'] = p.price\n p.stock = p.stock - i[\"order_number\"]\n products.append(p)\n orders.append(ordered_product)\n user = User.objects.get(token=token)\n for i in products:\n i.save()\n order = Order.objects.create(user=user)\n for i in orders:\n OrderProductRelation.objects.create(order=order, product_id=i['id'], unit=i['unit_price'],\n order_number=i[\"order_number\"])\n return JsonResponse(orders, safe=False)\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"295663661","text":"\"\"\"\n37강. 코너검출(Detection Corner)\n 이미지가 회전하더라도 코너를 검출 할 수 있지만, 이미지의 크기가 커 지면 제대로 검출하지 못함\n 이미지가 작을때는 코너로 인식하지만, 이미지가 커저 평탄하게 되기 때문.\n\n Harris Corner Detection\n cv2.cornerHarris(imgray, Tile, Sobel, Value)\n imgGray : 검출대상 그레이스케일 이미지, Float32 Type\n Tile : 코너 검출을 위해 고려할 이웃 픽셀의 범위\n Sobel : Sobel 미분에 사용된 인자 값\n Value : Harris 코너 검출 수학식 R에서 K 값\n\n\n Shi-Tomasi Corner Detection\n cv2.goodFeatureToTrack(grayImg, qty, thr, min)\n grayImg : 검출대상 이미지, 그레이 스케일\n qty : 검출할 코너의 갯수\n thr : 코너 검출 품질 - 코너로 판단할 문턱 값\n min : 검출할 코너 사이의 최소거리. 이 거리 이내에 있으면 무시함.\n\n\n\n38강. 크기불변 이미지 특성 검출기법 SIFT\n\n SIFT\n 이미지의 크기가 달라지더라도 이미지의 특징적인 부분을 검출하는 기법\n 이미지에서 스케일 불변인 키포인트를 추출하고, 추출한 키포인터들의 descriptor를 계산\n SIFT는 특허에 등록된 알고리즘 임. 따라서 OpenCV무료버전에는 SIFT의 모든 알고리즘이 탑제되어 있지 않음\n OpenCV3.0이상 버전에서는 OpenCV contrib 버전을 반드시 설치해야 함.\n\n 절차\n 1. Scale-Space Extrema Detection(스케일-공간 극값 검출)\n 가우시안 필터 후, 라플라시안 필터(Laplacian of Gaussian : LOG)를 적요하면 이미지에서 다양한 크기의 방울모양 의 이미지를 검출\n 하지만 LOG는 다소 시간이 소요됨. 이에 SIFT알고리즘에서는 하나의 이미지에 서로 다른 필터를 적용한\n 가우시안 피라미드 이미지의 차(Difference of Gaussian : DOG)를 이용\n DOG를 찾으면 이미지에서 스케일-공간 좌표상 극값을 찾음. 만약 극값이 있으면 이를 잠재적 키포인트(Potential Keypoint)라고 한다.\n\n 2. Keypoint Localization(키포인트의 지역화)\n 이미지에서 잠재적 키포인트들의 위치를 모두 찾았으면 보다 정확한 결과를 위해 잠재적 키포인트들의 정제과정을 거켜 키포인트들을 추출\n 정제과정은 테일러 전개를 이용하여 수행\n\n 3. Orientaltion Assignment(방향 할당하기)\n 최종적으로 추출된 키포인트들에 방향성-불변이 되도록 방향을 할당.\n 즉 이미지가 확대되거나 회전하더라도 추출된 키포인트들은 이미지의 특징을 보존하게 됨.\n\n 4. Keypoint Descriptor(키포인트 디스크립터 계산)\n 키포인트를 이용하여 키포인트 디스크립터를 계산\n 이미지 히스트그램을 활용하여 표현. 이외 조명의 변화나 회전 등에도 키포인트득이 특징을 보존할수 있도록 몇가지 측정값을 추가\n\n 5. Keypoint Matching(키포인트 매칭)\n 두 개의 이미지에서 키포인트들을 매칭하여 동일한 이미지 추출이나 이미지 검색 등에 활용\n\n SIFT를 위해 OpenCV에서 제공하는 함수\n cv2.xfeatures2d.SIFT_create()객체 : SIFT의 키포인트, 디스크림터들을 계산하는 함수를 제공\n detect(grayimg) : grayimg에서 키포인트를 검출하여 리턴\n compute(keypoint) : keypoint에서 디스크립터를 계산한 후 키포인트와 디스크립터를 리턴\n detectAndCompute(grayimg) : grayimg에서 키포인트와 디스크립터를 한번에 계산하고 리턴\n cv2.drawKeypoints(grayimg, keypoints, outimg) : outimg에 grayimg의 keypoint들을 표시시\n\n\n\n\n39강. SIFT의 성능 향상 버전 - SURF\n\n SURF(Speeded-Up Robust Features)\n SIFT는 이미지 특징을 찾아내는 훌륭한 알고리즘이지만 상대적으로 성능이 좋지 않음.\n SURF는 박스필터로 LoG를 근사하는 방법을 사용함\n SURF는 SIFT에 비해 약 3배 이상 속도가 빠름\n SURF는 블러이미지나 회전된 이미지의 경우 이미지 특징을 제대로 잡아내지만, 뷰 포인트가 바뀌거나 조명이 달라지면 제대로 검출하지 못함\n\n 이미지 특징을 비교할 때 회전이 문제 되지 않을 경우\n 예를 들면 파노라마 사진에서 비슷한 물체 찾기 등과 같은 경우\n 키포인트 검출 시에 회전 요소를 제거하면 더 빠르게 결과를 보여줌\n 회전 요소를 제거하려면 아래의 코드를 키포인트 검출 이전에 추가합니다.\n surf.setUpright(True)\n\n OpenCV가 제공하는 SURF 객체는 디스크립터를 64차원 또는 128차원 크기의 벡터로 설정하고 초기화 할 수 있음.\n SURF 객체의 디스크립터 크기를 알고자 할 때는 다음과 같이 한다.\n surf.descriptorSize() : 이 값이 64이면 이미지 매칭을 위해 128 차원으로 변경하여야 하는데 다음과 같이 수행\n\n surf.setExtended(True)\n kp, des = surf.detectAndCompute(img, None) : 이렇게 하면 디스크립터의 크기가 128로 변경됨.\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport default_import as impDef\n\n\ndef detectCornerHarris(imgNo):\n img = cv2.imread(impDef.select_img(imgNo))\n img2 = img.copy()\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n imgGray = np.float32(imgGray)\n dst = cv2.cornerHarris(imgGray, 2, 3, 0.04)\n # 검출된 코너부분을 확대하기 위해\n dst = cv2.dilate(dst, None)\n\n # 원본에 적적할 부분을 빨간색으로 표시\n # dst.max() 앞에 곱한 상수를 적절하게 조절하면 검출된 코너를 최적화 하여 나타 낼 수 있음\n img2[dst > 0.01 * dst.max()] = [0, 0, 255]\n\n cv2.imshow('Harris', img2)\n impDef.close_window()\n\n\n\n\ndef shito(imgNo):\n img = cv2.imread(impDef.select_img(imgNo))\n grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n corners = cv2.goodFeaturesToTrack(grayImg, 25, 0.01, 10)\n corners = np.int0(corners) # 정수형 값으로 전환\n\n for i in corners:\n x , y = i.ravel()\n cv2.circle(img, (x,y), 3, 255, -1)\n\n cv2.imshow('shito', img)\n impDef.close_window()\n\n\ndef SIFT(imgNo):\n img = cv2.imread(impDef.select_img(imgNo))\n grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img2, img3 = None, None\n\n sift = cv2.xfeatures2d.SIFT_create()\n kp = sift.detect(grayImg, None)\n\n img2 = cv2.drawKeypoints(grayImg, kp, img2)\n img3 = cv2.drawKeypoints(grayImg, kp, img3, flags = cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n cv2.imshow('SIFT1', img2)\n impDef.close_window( )\n\n cv2.imshow('SIFT2', img3)\n impDef.close_window( )\n #img4 = cv2.hstack((img2, img3))\n img4 = cv2.hconcat([img2, img3])\n cv2.imshow('비교', img4)\n impDef.close_window()\n\n\ndef SURF(imgNo):\n img = cv2.imread(impDef.select_img(imgNo))\n grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img2, img3 = None, None\n\n # 회전 요소를 제거하면 더 빠른 결과를 보여줌\n # 회전요소를 제거하려면 아래의 코드를 키포인트 검출 이전에 추가\n # surf.setUpright(True)\n\n surf = cv2.xfeatures2d.SURF_create() # SURF 객체 생성\n surf.setUpright(True) # 회전요소 제거, 회전이 문제가 되지 않는 경우 사용\n surf.setHessianThreshold(10000)\n # 인자값에 따라 SURF 객체가 검출하는 키포인트의 개수가 달라짐\n # 값이 작아지면 검출하는 키포인트의 개수가 많아지고, 값이 커지면 키포인트 개수는 적어짐.\n # 만약 두개의 이미지를 비교하거나 이미지에서 특정 사물을 추출하고자 할 때 적절한 인자값은 300 ~ 500 사이\n # 위 두줄은 surf = cv2.xfeatures2d.SURF_create(10000)과 동일\n\n kp, des = surf.detectAndCompute(img, None)\n img2 = cv2.drawKeypoints(grayImg, kp, img2, (255, 0, 0), 4)\n img3 = cv2.drawKeypoints(img, kp, img3, (255, 0, 0), 4)\n\n cv2.imshow('SURF', img2)\n cv2.imshow('SURF2', img3)\n impDef.close_window()\n\n\n#detectCornerHarris(37)\n#shito(37)\n#SIFT(38)\nSURF(38)","sub_path":"OpenCV/37_Detection Corner.py","file_name":"37_Detection Corner.py","file_ext":"py","file_size_in_byte":8205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"183509296","text":"#https://github.com/opencv/opencv/blob/master/samples/python/opt_flow.py #5.3.19\n#https://pypi.org/project/paho-mqtt/\nimport paho.mqtt.client as mqtt\nimport time\nimport base64\nimport cv2\n#import numpy as np\nfrom collections import deque\nfrom threading import Thread\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport RPi.GPIO as GPIO\nimport os\nimport sys\nfrom Robot import *\nfrom Optical_Flow import *\n\ntry:\n motorrechts = 0\n motorlinks = 0\n\n GPIO.setmode(GPIO.BCM)\n\n #GPIO PWM starten\n GPIO.setup(5, GPIO.OUT)\n GPIO.setup(6, GPIO.OUT)\n GPIO.setup(13, GPIO.OUT)\n GPIO.setup(19, GPIO.OUT)\n\n rechtsvor = GPIO.PWM(19, 50)\n rechtszuruck = GPIO.PWM(13, 50)\n linksvor = GPIO.PWM(5, 50)\n linkszuruck = GPIO.PWM(6, 50)\n\n rechtsvor.start(0)\n rechtszuruck.start(0)\n linksvor.start(0)\n linkszuruck.start(0)\n\n smoothstrength=2\n smoothr = deque(maxlen=smoothstrength)\n smoothl = deque(maxlen=smoothstrength)\n for i in range(smoothstrength):\n smoothr.appendleft(0)\n smoothl.appendleft(0)\n\n # The callback for when the client receives a CONNACK response from the server.\n def on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n client.subscribe(\"fernsteuerungmotorrechts\")\n client.subscribe(\"fernsteuerungmotorlinks\")\n client.subscribe(\"steuerung\")\n\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n\n def on_message(client, userdata, msg):\n global motorlinks\n global motorrechts\n wertstr = str(msg.payload)[2:-1]\n wert = 0\n try:\n wert = int(wertstr)\n except:\n pass\n \n print(wertstr)\n #print(msg.topic+\" \"+wert)\n #print(msg.topic+\" \"+str(msg.payload)[2:-1])\n\n if(msg.topic==\"fernsteuerungmotorrechts\"):\n smoothr.appendleft(wert)\n motorrechts = checkValue(smpos(smoothr))\n elif(msg.topic==\"fernsteuerungmotorlinks\"):\n smoothl.appendleft(wert)\n motorlinks = checkValue(smpos(smoothl))\n elif(msg.topic==\"steuerung\"):\n if(wertstr==\"STOP\"):\n motorrechts=checkValue(0)\n motorlinks=checkValue(0)\n elif(wertstr==\"VOR\"):\n motorrechts=checkValue(motorrechts+20)\n motorlinks=checkValue(motorlinks+20)\n elif(wertstr==\"ZURUECK\"):\n motorrechts=checkValue(motorrechts-20)\n motorlinks=checkValue(motorlinks-20)\n elif(wertstr==\"RECHTS\"):\n motorrechts=checkValue(motorrechts-20)\n motorlinks=checkValue(motorlinks+20)\n elif(wertstr==\"LINKS\"):\n motorrechts=checkValue(motorrechts+20)\n motorlinks=checkValue(motorlinks-20)\n PWMmotoren(motorrechts,motorlinks,rechtsvor,rechtszuruck,linksvor,linkszuruck) \n\n client = mqtt.Client()\n client.on_connect = on_connect\n client.on_message = on_message\n\n #192.168.2.103\n #192.168.1.104\n #192.168.178.68\n client.connect_async(\"localhost\", port=1883, keepalive=10, bind_address=\"\")\n client.loop_start()\n\n resx = 320 #864\n resy = 240 #432\n cap = PiCamera()\n cap.resolution = (resx, resy)\n cap.framerate = 24 #90\n rawcap = PiRGBArray(cap, size=(resx, resy))\n\n prev = None\n cur_glitch = None\n cnt=0\n lastframe = None\n\n for img in cap.capture_continuous(rawcap, format=\"bgr\", use_video_port=True):\n frame = img.array\n\n#=======================================================\n \n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n if prev is None:\n prev = gray.copy()\n lastframe = frame.copy()\n flow = cv2.calcOpticalFlowFarneback(prev, gray, None, 0.5, 3, 15, 1, 5, 1.2, 0)\n #cv2.calcOpticalFlowPyrLK\n prev = gray\n \n #================Flow================\n #cv2.imshow('flow', draw_flow(gray, flow))\n #client.publish(\"image\", payload=b\"data:image/png;base64,\" + base64.b64encode(cv2.imencode('.jpg', draw_flow(gray, flow, 16))[1].tostring()), qos=0, retain=False)\n #Thread(target=client.publish, args=(\"image\", b\"data:image/png;base64,\" + base64.b64encode(cv2.imencode('.jpg', draw_flow(gray, flow, 16))[1].tostring()), 0, False)).start()\n\n #==============Flow HSV==============\n #cv2.imshow('flow HSV', draw_hsv(flow))\n #client.publish(\"image\", payload=b\"data:image/png;base64,\" + base64.b64encode(cv2.imencode('.jpg', draw_hsv(flow))[1].tostring()), qos=0, retain=False)\n Thread(target=client.publish, args=(\"image\", b\"data:image/png;base64,\" + base64.b64encode(cv2.imencode('.jpg', speed_flow(flow,lastframe))[1].tostring()), 0, False)).start()\n lastframe = frame.copy()\n\n\n #===========Glitched Image===========\n #cnt=cnt+1\n #if(cnt>100) or cur_glitch is None:\n # cur_glitch = frame.copy\n #cur_glitch = warp_flow(cur_glitch, flow)\n #cv2.imshow('glitch', cur_glitch)\n #client.publish(\"image\", payload=b\"data:image/png;base64,\" + base64.b64encode(cv2.imencode('.jpg', cur_glitch)[1].tostring()), qos=0, retain=False)\n\n#=======================================================\n\n\n #cv2.imshow(\"frame\", frame)\n\n #client.publish(\"image\", payload=b\"data:image/png;base64,\" + base64.b64encode(cv2.imencode('.jpg', frame)[1].tostring()), qos=0, retain=False)\n\n rawcap.truncate(0)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\nexcept KeyboardInterrupt:\n print(\"Keyboard interrupt\")\nexcept Exception as e:\n print(str(e))\nfinally:\n GPIO.cleanup()\n print(\"Cleaning up\")\n #cv2.destroyAllWindows()\n","sub_path":"Python/Fernsteuerung-OpticalFlow.py","file_name":"Fernsteuerung-OpticalFlow.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"585716818","text":"#-*- coding:utf-8 -*-\n\"\"\"make_change8.py\n\"\"\"\nfrom __future__ import print_function\nimport sys, re,codecs\n\n\nclass Correction(object):\n def __init__(self,line):\n self.line = line\n m = re.search(r'^ (

.*?): (.*?) +::AB:: +(.*)$',line)\n if m == None:\n print('make_dict2 skipping(1) %s' % line)\n self.status = False\n return\n \n self.cid = m.group(1)\n self.cwhere = m.group(2)\n self.new = m.group(3)\n old = m.group(4)\n if old.startswith('st. '):\n old1 = re.sub(r'^st\\. +','',old)\n else:\n old1 = old\n print('no st.: %s old1=%s' %(self.cid,old1)) # dbg\n self.old = old1 \n self.status = True\n self.used = 0\n \ndef make_dict2(lines2):\n #

101,10 v. u.: -ásā ::AB:: st. -asā\n d = {}\n for iline,line in enumerate(lines2):\n if not line.startswith('')\n return new\n newline = re.sub(r'(.*?)',changef,line)\n return newline \n\ndef check_d2(d):\n # are any unused\n for id in d:\n correction = d[id]\n n = correction.used\n if n == 1:\n continue # as expected\n print('check_d2: (%s) %s' %(n,correction.line))\n \ndef change_lines(lines1,lines2):\n ans = []\n d2 = make_dict2(lines2)\n for line1 in lines1:\n newline = make_newline(line1,d2)\n ans.append(newline)\n check_d2(d2)\n return ans\n\nif __name__==\"__main__\": \n filein1 = sys.argv[1] # temp_gra_7\n filein2 = sys.argv[2] # vn3_2\n fileout = sys.argv[3] # \n\n with codecs.open(filein1,encoding='utf-8',mode='r') as f:\n lines1 = [line.rstrip('\\r\\n') for line in f]\n print(len(lines1),\"read from\",filein1)\n\n \n with codecs.open(filein2,encoding='utf-8',mode='r') as f:\n lines2 = [line.rstrip('\\r\\n') for line in f]\n print(len(lines2),\"read from\",filein2)\n \n newlines = change_lines(lines1,lines2)\n \n with codecs.open(fileout,encoding='utf-8',mode='w') as f:\n for line in newlines:\n f.write(line + '\\n')\n print(len(newlines),\"written to\",fileout)\n \n","sub_path":"vn/gra8/make_change8.py","file_name":"make_change8.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"652107213","text":"# Scraper v3: Will periodicly scrape the con edison website to find new gas leak reports, then use the Census Bureau API to find Census Data of those locations and append to my csv file. Will then read the file and make a new csv file to trck reports per hour per Census Tract per day and create a map.\n# Part A (section 1 to 4, 6, 8): Mahmudul Hasan. Script to scrape JSON Gas Leak Data points from ConEdison everyday and put them into a csv file for further use\n # In the ConEdison Gas Leak Report Map, each report in the map represents a gas leak report. Each report has these seven keys: TicketNumber, Latitude, Longitude, Zipcode, Classification Type, Date Reported, Last Inspected.\n # a) We need to constantly add new repots to out list so what tickets do we currently have? read the ticket col of the \"csvConEdFile\" and add the tickets to \"ticketSet\"\n # b) Scrape the JSON html response and using pandas to put the contents into a dataframe called \"jsonDF\"\n # c) See if there is a new report, if there is create a new DF that stores info for those new tickets: \n # Read the csv file and make a dataframe with pandas. Now compare the \"TicketNumber\" columns of both the \"csvDF\" and \"jsonDF\" using left merge and store it as a new DF - \"mergedDF\" - which has the info of all the tickets and has a new column called \"_merged\" which shows what ticket are in both DF and what tickets are in only json response. \n # Filter \"mergedDF\" where \"_merged\" col = \"\"left_only\" (new tickets not in file) and print the list of ticket names to an array - \"newTicketsArray\" \n # Create a new DF - \"newTicketDF\" - which will have the columns of my current csv file. Will use \"newTicketArray\" to go through the \"jsonDf\" and add the rows to \"newTicketDF\" so i have a DF that has all the new tickets\n # d) If there is a new report, add append the keys of that report into \"csvConEdFile\" and push the latest changes to github\n# Part B (section 5): Will edit the csv to have new columns for the Census Tract, Census Block, County Name and the hour only\n # Will use the census bureau api to get census data from the lat and lon coords using this url request: https://geocoding.geo.census.gov/geocoder/geographies/coordinates?x=LONGITUDE&y=LATITUDE&benchmark=Public_AR_Current&vintage=Current_Current&format=json\n# Part C (section 7): Will create a new csv that lists the reports per census tract per hour for that day. Headers: Date, Hour, CensusTract, NumberOfReports\n\n\nimport json\nimport csv\nimport pandas as pd # to read csv file and store conent into a data frame. To turn json response string into a dataframe\nimport datetime,re # to turn Microsoft JSON date /Date()/ to normal date\nimport requests # Getting html data\nfrom bs4 import BeautifulSoup # Parse the HTML data\nfrom apscheduler.schedulers.blocking import BlockingScheduler # Sceduler. Will run a function every x seconds/minutes/hours\nfrom git import Repo # (GitPython) To push changes to gh\n\n\n# SETTING UP GLOBAL VARIABLES: need to change the first eight variables below\ncsvFile = \"GasHistory_ConEdisonTracts.csv\" # add new tickets to the end of the csv file\ncsvHourlyFile = \"GasHistory_ReportFrequency_Hourly.csv\" # In PART C we will turn the ticket history data to hourly data\njsonFile = \"SOME_JSON_FILE.json\" # Normally the programm will be scrape JSOn data from a url but sometimes it might need to extract JSOn data from a file. See step 2)\nurl = 'https://apps.coned.com/gasleakmapweb/GasLeakMapWeb.aspx?ajax=true&' # Url to scrape JSOn data from\ndropCol = True # If you want to drop a column, specify which ones in step 2 in WebscraperJsonToCSV()\nreplaceColWith = [\"Date\", \"Time\", \"Hour\", \"CensusTract\", \"CensusBlock\", \"CountyName\" ] # Replacing column DateReported with these \"Date\", \"Time\", \"Hour and Made 3 more cols for Part 2 Census data\n\nPATH_OF_GIT_REPO = r'/home/pi/repositories/gh/GasLeakProject' # the path to the .git file (.git location on my raspberry pi)\n# PATH_OF_GIT_REPO = r'/home/hasan/repositories/gh/GasLeakProject' # the path to the .git file (.git location on my Laptop)\nCOMMIT_MESSAGE = 'Automated Push - New Ticket Update' # the commmit message when it is pushed\nscrapingCount = 0 # Just counting how many times i have scraped the website while this was running\n\n# GIT PUSH FUNCTION: Setting up function to automatically push changes to github when there is a new ticket so that I can have access to the latest chnages\ndef git_push():\n repo = Repo(PATH_OF_GIT_REPO)\n try:\n repo.remotes.origin.pull() # try pulling new changes from the github repo (if there are any) so i can push changes\n except:\n print(\"Couldnt pull from repo\")\n repo.git.add(update=True)\n repo.index.commit(COMMIT_MESSAGE)\n origin = repo.remote(name='origin')\n try:\n origin.push() # try pushing the changes to github\n print(\"******** PUSHED TO GITHUB for Run \" + str(scrapingCount)+\"********\")\n except:\n print('Some error occured while pushing the code') \n\n\n# FUNCTION TO TURN MICROSOFT JSON DATE TO mm/dd/yyyy AND TIME: returns [\"mm/dd/yyyy\", \"hh:mm AM/PM\", \"hh AM/PM\"]\ndef turnToDateTimeHr(microsoftDate): \n TimestampUtc = str(microsoftDate)\n TimestampUtc = re.split('\\(|\\)', TimestampUtc)[1][:10]\n dateRaw = datetime.datetime.fromtimestamp(int(TimestampUtc))\n dateFormatted = str(dateRaw.strftime('%m/%d/20%y %I:%M %p')) # The datetime is of form: \"mm/dd/tt hh:mm AM/PM\"\n dateTimeSplit = dateFormatted.split(\" \") # [\"mm/dd/yyyy\", \"hh:mm\", \"AM/PM\"]\n date = dateTimeSplit[0] # Isolated the date string: \"mm/dd/yyyy\"\n time = dateTimeSplit[1] + \" \" + dateTimeSplit[2] # Isolated the time string: \"hh:mm AM/PM\"\n hour = time.split(\" \")[0].split(\":\")[0] + \" \" + dateTimeSplit[2] # Isolated the hour string: \"hh AM/PM\" (will need for part 2)\n dateTimeHr = [date, time, hour] # [\"mm/dd/yyyy\", \"hh:mm AM/PM\", \"hh AM/PM\"]\n return (dateTimeHr) \n\n# PART B FUNCTION: Get [CensusTrack, CensusBlock, CountyName] from Longitude and Latitude coordintes using the Census Beru's API which returns a JSON file \ndef getCensusTract(longitude, latitude,retryRun=0): # returns an array [censusTract, CensusBlock, CountyName]\n url = \"https://geocoding.geo.census.gov/geocoder/geographies/coordinates?x={0}&y={1}&benchmark=Public_AR_Current&vintage=Current_Current&format=json\".format(longitude,latitude)\n if retryRun == 11: # Failed to get json data 11 times with this longitude and latitude so need to skip this one\n print(\"*****Failed 11 times to get geodata so will insert 'error'*****\")\n return [str(\"error\"), str(\"error\"), str(\"error\")]\n try:\n response = requests.get(url)\n dataJSON = response.json()\n data = dataJSON[\"result\"]\n track = data[\"geographies\"][\"Census Tracts\"][0][\"BASENAME\"]\n block = data[\"geographies\"][\"2010 Census Blocks\"][0][\"BLOCK\"]\n county = data[\"geographies\"][\"Counties\"][0][\"NAME\"] \n return [str(track), str(block), str(county)]\n except:\n retryRun+=1\n print(\"Error on longitude, latitude: \"+str(longitude)+\",\"+str(latitude) + \".....retrying... \"+str(retryRun))\n return getCensusTract(longitude, latitude,retryRun) # need to return the recursive function\n\n# PART C FUNCTION: Make Hourly reports from the gas leak history csv file\ndef turnTicketHistoryToHourlyReport():\n global csvFile\n global csvHourlyFile\n csvOutHasData = False # Does the out file have data already? if so can get it and use it and modify it\n inDF = pd.read_csv(csvFile) # Read Tracts file\n csvHeader = [\"Date\",\"Hour\",\"CensusTract\",\"NumberOfReports\"] # My new csv need these headers \n \n csvOutClear = open(csvHourlyFile, \"w\")\n csvOutClear.truncate() # deleting everything in the file (will delete this code once i figure out how to update existing file)\n\n with open(csvHourlyFile, 'r') as csvFile: # Open the csv File so we can read it\n csvTable = [row for row in csv.DictReader(csvFile)]\n if len(csvTable) == 0: # a) csv is empty so add my header: ['Date', 'Hour', 'CensusTract', 'NumberOfReports']\n with open(csvHourlyFile, 'w', newline='') as outf:\n writer = csv.writer(outf)\n writer.writerow(csvHeader)\n print(\"Added Header: \"+str(csvHeader))\n else:\n csvHeader=list(pd.read_csv(csvHourlyFile).columns) # b) Since the csv already had data, it means i will append new data to it so just use the header of that csv file.\n csvOutHasData = True # There is data here, after i make a new DF using the tract csv i have, will go through the other csv and increment or keep the report counts\n\n outDF = pd.DataFrame(columns=csvHeader) # making newDF with the cols i want. This will be appended to the other csv\n skipIndex = [] \n\n print(\"Turning the Gas Leak Report data into hourly reports...\")\n for row in range(0,len(inDF)):\n if row in skipIndex:\n continue\n\n # This part is just to get the index value of the groupedDF so that i can know what index of \"inDF\" to skip since i already have them in \"groupedDF\"\n groupedDF_withIndex = pd.DataFrame(columns=csvHeader)\n groupedDF_withIndex = inDF.loc[ (inDF['Date'] == inDF['Date'][row]) & (inDF['Hour'] == inDF['Hour'][row]) & (inDF['CensusTract'] == float(inDF['CensusTract'][row])) ] \n skipIndex.extend(groupedDF_withIndex.index.tolist()) \n \n # groupedDF = pd.DataFrame(columns=csvHeader) # Making a new dataframe and letting it have the columns i want. When i append \"inDF\" rows, the cols of \"inDF\" will be added to it. Will finally get rid of unwanted cols with filter(). \n # groupedDF = groupedDF.append(inDF.loc[ # groupedDF added tickets that have the same Census Tract, Hour, and Date. Will get rid of those unwanted cols from \"inDF\" next\n # (inDF['Date'] == inDF['Date'][row]) & \n # (inDF['Hour'] == inDF['Hour'][row]) & \n # (inDF['CensusTract'] == float(inDF['CensusTract'][row])) \n # ] \n # skipIndex.extend(groupedDF.index.tolist()) # already did this indexes so will skip them when \"row\" increments to them \n # monthlyDF = monthlyDF.reset_index(drop=True) # resetting the index to restart from 0\n\n # Will now makw the dataframe with all the tickets with the same Date, Hour, Census track and append to outDF\n groupedDF = pd.DataFrame(columns=csvHeader) # Making a new dataframe and letting it have the columns i want. When i append \"inDF\" rows, the cols of \"inDF\" will be added to it. Will finally get rid of unwanted cols with filter(). \n groupedDF = groupedDF.append(inDF.loc[ # groupedDF added tickets that have the same Census Tract, Hour, and Date. Will get rid of those unwanted cols from \"inDF\" next\n (inDF['Date'] == inDF['Date'][row]) & \n (inDF['Hour'] == inDF['Hour'][row]) & \n (inDF['CensusTract'] == float(inDF['CensusTract'][row])) \n ], sort=False, ignore_index=True\n ) \n\n\n groupedDF = groupedDF.filter(csvHeader) # Getting rid of those unwanted cols i got from \"inDF\"\n\n # Appending row to \"outDF\" by using small trick to get \"groupDF\" to one row to easily add it. Since all the rows will now have the same vals, will change the \"NumberOfReports\" cell and drop the other rows by droppping na's\n groupedDF.iloc[0, groupedDF.columns.get_loc(\"NumberOfReports\")] = len(groupedDF)\n groupedDF = groupedDF.dropna()\n outDF = outDF.append(groupedDF, ignore_index=True, )\n\n\n # # Find there is data see if they need to be updated\n # if csvOutHasData == True:\n # print(\"i am deleting the csv make sure to delete that code\")\n # csvOutDF = pd.read_csv(csvHourlyFile) \n # differencesDF = outDF.merge(csvOutDF.drop_duplicates(), on=[\"Date\",\"Hour\",\"CensusTract\"], how='outer', indicator=True) \n # print(\"----------------------------a\")\n # newDataDF = differencesDF.loc[differencesDF['_merge']==\"left_only\"]\n # print(newDataDF)\n # print(\"----------------------------b\")\n # print(differencesDF.loc[differencesDF['_merge']==\"right_only\"])\n\n print(\"Printing hourly report to \"+csvHourlyFile+\"...\")\n with open(csvHourlyFile,'a') as outCSV: # Turning the DF into csv and appending the new data to the file\n outCSV.write(outDF.to_csv(header=False, index=False))\n\n\n# THE SCHEDULER WILL RUN THIS MAIN FUNCTION EVER X SECONDS/MINUTES/HOURS\ndef WebscraperJsonToCSV(): \n global scrapingCount # Setting up the web scraping global iteration counter for debugging purposes\n scrapingCount = scrapingCount + 1 \n # 1) GET JSON DATA: Webscrape the html response which is usually just the JSON data from the url and add to the JSON Dataframe: \n # jsonDF = pd.read_json(jsonFile, orient='records') # If im getting data from json file, comment out the rest of this section.\n try:\n res = requests.get(url)\n html_data = res.content # Getting the HTML JSON data from the url \n soup = BeautifulSoup(html_data, 'html.parser') # parsing the html data with html parcer (can do stuuf like soup.title to get the title, soup.div, soup.li etc)\n text = soup.find_all(text=True) # Getting all the text thats in the soup\n jsonStr = '' # turning text to string from so i can use pandas to turn it to a dataframe\n for t in text:\n jsonStr += '{} '.format(t)\n jsonDF = pd.read_json(jsonStr, orient='records') # Turning the json string to a pandas dataframe\n print(\"Run Starting \" + str(scrapingCount) + \" Reports Scraped: \"+str(len(jsonDF)))\n except:\n print(\"Couldnt get the json data so will re-run function. This is Run \"+ str(scrapingCount))\n return WebscraperJsonToCSV()\n\n\n # 2) MODIFY CSV FILE: a) CSV IS EMPTY: print the the headers I want. b) CSV NOT EMPTY: Get the header and that is what we will work with. Im also droping columns from json DF and adding new col titles to csvHeader array\n # My csv will not have the \"LastInspected\" and \"DateReported\" cols. Will drop \"LastInspeccted\" but will keep \"DateReported\" as we will break it down into three cols for my csv file: \"Date,Time,Hour\" and then will drop it at the end\n jsonDF = jsonDF.drop(columns=[\"LastInspected\"]) # Dropping this col fom the jsonDF \n csvHeader = list(jsonDF.drop(columns=[\"DateReported\"]).columns.values) # (this change will be replced is csv has header) Title: \"DateReported\" Will be replaced by \"Date,Time,Hour\" So will now \n csvHeader.extend(replaceColWith) # (this change will be replced is csv has header) Title: Adding the \"Date,Time,Hour\" to the title\n with open(csvFile, 'r') as csvfile: # Open the csv File so we can read it\n csvTable = [row for row in csv.DictReader(csvfile)]\n if len(csvTable) == 0: # a) csv is empty so add my header: [TicketNumber,Latitude,Longitude,Zip,ClassificationTyp,Date,Time,Hour\n with open(csvFile, 'w', newline='') as outf:\n writer = csv.writer(outf)\n writer.writerow(csvHeader)\n print(\"Added Header: \"+str(csvHeader))\n else:\n csvHeader=list(pd.read_csv(csvFile).columns) # b) Since the csv already had data, it means i will append new data to it so just use the header of that csv file.\n \n\n # 3) FIND THE NEW TICKETS \n csvDF = pd.read_csv(csvFile) # Reading the list of tickets i current have on file and making a dataframe to read them\n mergedDF = jsonDF.merge(csvDF.drop_duplicates(), on=['TicketNumber'], how='left', indicator=True) # Will take all the keys of jsonDF. Will merge with keys of right DF (wont display) and will keep only the merged keys \n newTicketsArray = list(mergedDF.loc[mergedDF['_merge']==\"left_only\", \"TicketNumber\"]) # This array holds all the tickets i dont have in my file\n newTicketDF = pd.DataFrame(columns=csvHeader) # Making empty dataframe that has the columns of my csv file. This will be the df that will be modified and pushed to my csv\n if len(newTicketsArray) == 0: # No new Tickets, can end this iteration\n return\n\n for row in range(0,len(newTicketsArray)): # Going through the array of new ticket number and adding only their rows to th new data frame\n print(newTicketsArray[row] + \" not in set so adding it-----\")\n newTicketDF = newTicketDF.append(jsonDF[jsonDF.TicketNumber == newTicketsArray[row]], sort=False, ignore_index=True)\n\n # 4 &) TURN THE MICROSOFT DATE IN \"DateReported\" INTO STANDARD FORMAT AND SEPERATE INTO \"Date\", \"Time\", \"Hour\" COLUMNS AND THEN DROP COLUMN \"DateReported\" :\n # 5) WILL USE THE CENSUS BUREAU API TO GET CENSUS DATA BASED ON EACH TICKET'S LONGITUDE AND LATITUDE DATA: \n for row in range(0, len(newTicketDF)): # Replacing DateReported with Date, Time, Hour columns\n dateTimeHr = turnToDateTimeHr(str(newTicketDF[\"DateReported\"][row])) # Takes the microsoft date and returns: [\"mm/dd/yyyy\", \"hh:mm AM/PM\", \"hh AM/PM\"]\n newTicketDF.iloc[row, newTicketDF.columns.get_loc(\"Date\")] = dateTimeHr[0] # Adding the Date, Time, Hour values to the appropriate cells\n newTicketDF.iloc[row, newTicketDF.columns.get_loc(\"Time\")] = dateTimeHr[1]\n newTicketDF.iloc[row, newTicketDF.columns.get_loc(\"Hour\")] = dateTimeHr[2]\n print(\"Getting Census data...\")\n returnArray = getCensusTract(float(newTicketDF.loc[row][\"Longitude\"].item()), float(newTicketDF.loc[row][\"Latitude\"].item())) # returns: [CensusTrack, CensusBlock, CountyName] from Census Beru's API\n newTicketDF.iloc[row, newTicketDF.columns.get_loc(\"CensusTract\")] = returnArray[0] # Adding the CensusTrack, CensusBlock, CountyName values to the appropriate cells\n newTicketDF.iloc[row, newTicketDF.columns.get_loc(\"CensusBlock\")] = returnArray[1]\n newTicketDF.iloc[row, newTicketDF.columns.get_loc(\"CountyName\")] = returnArray[2]\n newTicketDF = newTicketDF.drop(columns=[\"DateReported\"]) # Finally dropping the \"DateReported\" column \n\n # 6) WRITE TO CSV FILE:\n print(\"Appending new Gas Leak reports to file...\")\n with open(csvFile,'a') as outCSV: # Turning the DF into csv and appending the new data to the file\n outCSV.write(newTicketDF.to_csv(header=False, index=False))\n \n # 7) WRITING NEW HOURLY FILE BASED ON GAS LEAK HISTORY FILE AND PUSHING TO GH\n turnTicketHistoryToHourlyReport()\n git_push()\n\n\n\n# 8) RESCAN FOR TICKETS every x time using sceduler\nscheduler = BlockingScheduler()\nscheduler.add_job(WebscraperJsonToCSV, 'interval', minutes=30) # need to give enough time to go the entire process\nscheduler.start()\n\n\n# Notes: Turning the Gas Leak Report data into hourly reports...) process took forever, need to make it do it faster","sub_path":"DataFiles/Old Stuff/Old Files 2/scraper3_ConEdison.py","file_name":"scraper3_ConEdison.py","file_ext":"py","file_size_in_byte":22617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"332983526","text":"from django.urls import path\nfrom . import views\n\napp_name='cart'\n\nurlpatterns = [\n path('add//', views.add_cart, name='add_cart'),\n path('', views.cart_detail, name=\"cart_detail\"),\n path('remove//', views.cart_remove, name=\"cart_remove\"),\n path('full_remove//', views.full_remove, name=\"full_remove\"),\n path('order/', views.create_order, name=\"create_order\"),\n path('order/accept_order/', views.accept_order, name=\"accept_order\"),\n #path('order/accept_order/order_success/', views.order_success, name=\"order_success\"),\n ]\n","sub_path":"web-app/miniAmazon/cart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"652656883","text":"class Student:\n def __init__(self,name,age):\n self.name=name;\n self.age=age;\n def display(self):\n print()\n print(\"Name: %s \\n Age: %d\"%(self.name, self.age))\nstd1=Student(\"Pari\",21)\nstd2=Student(\"Varsha\",22)\nstd1.display()\nstd2.display()\n\n","sub_path":"q25.py","file_name":"q25.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"571175085","text":"import pymongo\n\n\n\ndef getDevices(\n DB: pymongo.MongoClient\n ) -> dict:\n '''\n Get the power devices\n '''\n\n solar_live = DB['solar_live'].find()\n solar_live = list(solar_live)\n gen_live = DB['gen_live'].find()\n gen_live = list(gen_live)\n assets = DB['assets'].find()\n assets = list(assets)\n\n devices = {\n 'solar' : solar_live,\n 'gen' : gen_live,\n 'assets' : assets\n }\n\n return(devices)\n\n\ndef combineDevices(\n devices: dict\n ) -> list:\n '''\n Combines each assets power devices in to a single dictionary\n '''\n assets = {}\n assets_by_id = {str(d['_id']): d for d in devices['assets']}\n for solar in devices['solar']:\n asset_id = str(solar['device']['asset_id'])\n asset = assets_by_id[asset_id]\n try:\n assets[asset_id]['solars'].append(solar)\n except:\n assets[asset_id] = {}\n assets[asset_id]['asset'] = asset\n assets[asset_id]['solars'] = []\n assets[asset_id]['solars'].append(solar)\n\n for gen in devices['gen']:\n asset = gen['asset']\n asset_id = str(gen['asset']['_id'])\n gen.pop('asset')\n try:\n assets[asset_id]['gens'] = []\n except KeyError:\n assets[asset_id] = {}\n assets[asset_id]['gens'] = []\n \n assets[asset_id]['asset'] = asset\n assets[asset_id]['gens'].append(gen)\n \n return(assets)\n\n\ndef updateDB(\n DB: pymongo.MongoClient,\n assets: dict\n ) -> None:\n '''\n Updates the collection\n '''\n\n for key, value in assets.items():\n DB['site_power'].find_one_and_update(\n {\n 'asset._id' : value['asset']['_id']\n },\n {\n '$set' : value\n },\n upsert=True\n )\n\n\ndef aggregate(\n DB: pymongo.MongoClient\n ) -> None:\n '''\n Aggregate and group the power devices per asset\n '''\n\n devices = getDevices(DB)\n assets = combineDevices(devices)\n updateDB(DB, assets)\n\n ","sub_path":"backend/mm_aggregate_rt/src/aggregates/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"271907983","text":"import numpy as np\n\nx= [1,2,3,4,5]\ny= [1,2,3,4,5]\n\nm =5\n\nteta = np.linspace(-10,10,50000)\n\n\nerror = np.zeros(50000)\n\nmini = -100\n\nfor i in range(m):\n\tsumV = 0\n\tfor thet in range(50000):\n\t\tsumV = sumV + (teta[thet] * x[i] - y[i]) **2\n\n\terror[i] = sumV / ( 2 * m )\n\tif(error [i] < mini):\n\t\tmini = error[i]\n\n\nprint(mini)\n","sub_path":"2017/ipcvgml/machineLearning/newLinear.py","file_name":"newLinear.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"644253531","text":"from __future__ import unicode_literals\n\nfrom django.utils import six\n\nfrom tagulous.models.fields import SingleTagField, TagField\n\n\n#\n# Functions to load initial tags\n# Used by tests and the management command `initialtags`\n#\n\ndef field_initialise_tags(model, field, report=None):\n \"\"\"\n Load any initial tags for the specified tag field\n \n You will not normally need to call this directly - instead use the\n management command ``initialtags``.\n \n Arguments:\n model Model containing the field\n field Field with initial tags to load\n report Optional: a file handle to write verbose reports to\n \n Returns True if loaded, False if nothing to load\n \"\"\"\n if not field.tag_options.initial:\n return False\n \n if report:\n report.write(\"Loading initial tags for %s.%s.%s\\n\" % (\n model._meta.app_label,\n model.__name__,\n field.name,\n ))\n \n descriptor = getattr(model, field.name)\n descriptor.load_initial()\n return True\n\n\ndef model_initialise_tags(model, report=None):\n \"\"\"\n Load any initial tags for the given model\n \n You will not normally need to call this directly - instead use the\n management command ``initialtags``.\n \n Arguments:\n model Model to check for tag fields to load\n report Optional: a file handle to write verbose reports to\n \"\"\"\n if hasattr(model._meta, 'get_fields'):\n # Django 1.8 uses new meta API\n fields = model._meta.get_fields()\n else:\n fields = model._meta.fields + model._meta.many_to_many\n \n for field in fields:\n if isinstance(\n field,\n (SingleTagField, TagField)\n ):\n field_initialise_tags(model, field, report)\n\n","sub_path":"env/lib/python2.7/site-packages/tagulous/models/initial.py","file_name":"initial.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"493803854","text":"mylist = [1, 2, 3, 4, 5, 6, 7]\nN = 3\ncumsum, moving_aves = [0], []\n\nfor i, x in enumerate(mylist, 1):\n cumsum.append(cumsum[i-1] + x)\n print(cumsum)\n if i>=N:\n moving_ave = (cumsum[i] - cumsum[i-N])/N\n #can do stuff with moving_ave here\n moving_aves.append(moving_ave)\n\nimport numpy as np\ndef movingaverage(interval, window_size):\n window = np.ones(int(window_size)) / float(window_size)\n return np.convolve(interval, window, 'same')\n\nmov=movingaverage(mylist, 3)\nprint(moving_aves)\nprint(mov)","sub_path":"misc/moving_average.py","file_name":"moving_average.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"566143677","text":"from argparse import ArgumentParser\nfrom random import randint, choice\nfrom time import sleep\nfrom json import dumps\n\nfrom redis_connector import Connector\nfrom redis_config import REDIS_HOST, REDIS_PORT, REDIS_DB, STATES, INIT_STATE, GENERATOR_TIMEOUT\n\nclass Generator(object):\n\tdef __init__(self):\n\t\tsuper(Generator, self).__init__()\n\t\t\n\t\tself.connection = None\n\t\t\n\tdef connect(self, host = REDIS_HOST, port = REDIS_PORT, db = REDIS_DB):\n\t\tconnector = Connector()\n\t\tconnector.connect(host = host, port = port, db = db)\n\t\t\n\t\tself.connection = connector.connection\n\t\t\n\tdef generate_message(self):\n\t\treturn dumps({'obj': randint(1, 16), 'state': choice(['open', 'closed', 'waiting'])})\n\t\n\tdef launch(self, timeout = GENERATOR_TIMEOUT):\n\t\tif self.connection:\n\t\t\tprint('Message generator launched with timeout %1.2f sec. Press Ctrl + C to stop the script.' % timeout)\n\t\t\twhile True:\n\t\t\t\tself.connection.rpush('queue', self.generate_message())\n\t\t\t\tsleep(timeout)\n\t\telse:\n\t\t\tprint('The generator is not connected to any Redis. Call Generator.connect() first.')\n\t\t\t\nif __name__ == '__main__':\n\tparser = ArgumentParser()\n\t\n\tparser.add_argument('--host')\n\tparser.add_argument('--port', type = int)\n\tparser.add_argument('--db', type = int)\n\tparser.add_argument('--timeout', type = float)\n\t\n\targs = parser.parse_args()\n\t\n\thost, port, db, timeout = args.host or REDIS_HOST, args.port or REDIS_PORT, args.db or REDIS_DB, args.timeout or GENERATOR_TIMEOUT\n\t\n\tg = Generator()\n\tg.connect(host, port, db)\n\tg.launch(timeout)","sub_path":"redis_generator.py","file_name":"redis_generator.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"197602132","text":"import pygame as pg\nimport math\nimport random\n\n\"\"\"\n implement a better way to detect collision:\n - more general\n - more intuitive and straightforward way to determine how to bounce\n\"\"\"\nclass Ball:\n def __init__(self, screen, colour, size, speed):\n self.screen = screen\n self.colour = colour\n self.size = size\n self.speed = speed\n\n self.wWidth, self.wHeight = pg.display.get_surface().get_size()\n self.x = 0\n self.y = 0\n self.angle = 0\n self.initVel()\n\n self.centre = (self.x) + self.size / 2\n self.radius = self.size / 2\n self.MAX_BOUNCE_ANGLE = -math.radians(75)\n self.xCoeff = 1\n self.yCoeff = 1\n\n def initVel(self):\n self.wWidth, self.wHeight = pg.display.get_surface().get_size()\n self.x = self.wWidth // 2\n self.y = self.wHeight // 2\n\n direc = random.randint(0,1)\n CONE_ANGLE = 75\n INC_ANGLE = -0.5*math.pi + (math.pi - math.radians(CONE_ANGLE))/2\n # left\n if direc == 0:\n initCone = math.pi + INC_ANGLE\n # right\n else:\n initCone = INC_ANGLE\n randCone = random.random() * math.radians(CONE_ANGLE)\n self.angle = initCone + randCone\n\n def move(self, blockSizes):\n self.x += self.speed * self.xCoeff * math.cos(self.angle)\n self.y += self.speed * self.yCoeff * math.sin(self.angle)\n\n self.centre = (self.x) + self.size / 2\n # reflection if it hits the edge of screen\n if self.y >= self.wHeight or self.y <= 0:\n self.yCoeff *= -1\n elif self.detectCollision(blockSizes):\n self.bounce()\n\n # MAKE THIS BETTER\n def bounce(self):\n bY = self.collY\n bHeight = self.collHeight\n relativeYIsect = (bY + (bHeight/2)) - self.y\n normalised = (relativeYIsect/(bHeight/2))\n self.xCoeff *= -1\n self.angle = normalised * self.MAX_BOUNCE_ANGLE\n\n def detectCollision(self, blockSizes):\n for block in blockSizes:\n xconst = block[0]\n bY = block[1]\n bWidth = block[2]\n bHeight = block[3]\n\n rBlockColl = abs((xconst + bWidth) - self.centre) <= self.radius\n lBlockColl = abs(xconst - self.centre) <= self.radius\n withinY = self.y >= bY and self.y <= (bY + bHeight)\n\n if withinY and (rBlockColl or lBlockColl):\n self.collY = bY\n self.collHeight = bHeight\n return True\n\n def draw(self, blockSizes):\n self.move(blockSizes)\n pg.draw.ellipse(self.screen, self.colour, [self.x, self.y, self.size, self.size])\n\n def getPos(self):\n self.middleX = (self.x) + self.size / 2\n self.middleY = self.y + (self.size / 2)\n return self.middleX, self.middleY\n","sub_path":"Ball.py","file_name":"Ball.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"395825543","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom networks.PWCNet import PWCDCNet\nfrom networks.DepthNet import get_architecture\n\nfrom utils import weights_init, inverse_flow_warp\n\ndef conv(in_planes, out_planes, kernel_size=3, stride=2):\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=(kernel_size-1)//2, stride=stride),\n nn.ReLU(inplace=True)\n )\n\ndef upconv(in_planes, out_planes):\n return nn.Sequential(\n nn.ConvTranspose2d(in_planes, out_planes, kernel_size=4, stride=2, padding=1),\n nn.ReLU(inplace=True)\n )\n\n\ndef get_depth_flow(depth1, depth2, flow12):\n depth2_warped = inverse_flow_warp(depth2, flow12)\n out_of_bound = 1 - (depth2_warped == 0).prod(1, keepdim=True).type_as(depth2_warped)\n\n depth_flow = (depth2_warped - depth1) * out_of_bound\n\n return depth_flow\n\nclass PODNet(nn.Module):\n def __init__(self, args):\n super(PODNet, self).__init__()\n\n self.depthnet = get_architecture(args)\n self.flownet = PWCDCNet()\n\n conv_planes = [16, 32, 64, 128, 256, 256]\n\n self.image_branch = nn.Sequential(\n conv(6, conv_planes[0], kernel_size=7),\n conv(conv_planes[0], conv_planes[1], kernel_size=5),\n conv(conv_planes[1], conv_planes[2]),\n conv(conv_planes[2], conv_planes[3])\n )\n\n self.depth_flow_branch = nn.Sequential(\n conv(1, 64),\n conv(64, 128),\n conv(128, 256),\n conv(256, 512)\n )\n\n self.flow2d_branch = nn.Sequential(\n conv(2, 64),\n conv(64, 128),\n conv(128, 256),\n conv(256, 512)\n )\n\n self.squeeze = nn.Conv2d(1024 + 128, 256, kernel_size=1, bias=False)\n self.relu = nn.ReLU(inplace=True)\n\n self.fc_rot = nn.Sequential(\n conv(256, 256),\n conv(256, 256),\n conv(256, 128),\n nn.Conv2d(128, 3, kernel_size=1)\n )\n\n self.fc_trans = nn.Sequential(\n conv(256, 256),\n conv(256, 256),\n conv(256, 128),\n nn.Conv2d(128, 3, kernel_size=1)\n )\n\n self.exp_decoder = nn.Sequential(\n upconv(256, 128),\n upconv(128, 64),\n upconv(64, 32),\n upconv(32, 16),\n nn.Conv2d(16, 1, kernel_size=1, bias=False),\n nn.Sigmoid()\n )\n\n self.apply(weights_init)\n\n self.reset_hidden()\n\n def reset_hidden(self):\n try:\n self.depthnet.reset_hidden()\n except AttributeError:\n print(\"Warning: DepthNet has no reset_hidden function!\")\n\n self.previous_depth = None\n self.previous_image = None\n\n def forward(self, input):\n b,c,d,h,w = input.size()\n\n depth_predictions = []\n input_images = []\n\n for i in range(d):\n if self.depthnet.training:\n depth = self.depthnet(input[:, :, i:(i+1)])\n else:\n with torch.no_grad():\n depth = self.depthnet(input[:, :, i:(i + 1)])\n\n depth_predictions.append(depth[:, :, 0])\n input_images.append(input[:,:, i])\n\n if not self.training and d == 1:\n if self.previous_depth is None:\n self.previous_depth = depth_predictions[-1]\n self.previous_image = input_images[-1]\n return depth_predictions[-1], torch.zeros(b, 2, h, w).cuda(), torch.zeros(b, 1, h, w).cuda(), torch.zeros(b, 6).cuda()\n else:\n depth_predictions.insert(0, self.previous_depth)\n input_images.insert(0, self.previous_image)\n self.previous_depth = depth_predictions[-1]\n self.previous_image = input_images[-1]\n\n flows = []\n poses = []\n exp_masks = []\n if self.training:\n input_orders = [[0, 1], [1, 0]]\n else:\n input_orders = [[0, 1]]\n\n for order in input_orders:\n ref_image = input_images[order[0]]\n tgt_image = input_images[order[1]]\n ref_depth = depth_predictions[order[0]]\n tgt_depth = depth_predictions[order[1]]\n\n sequence = torch.cat([ref_image, tgt_image], dim=1)\n image_features = self.image_branch(sequence)\n\n if self.flownet.training:\n flow = [20.0 / (4 * (2 ** i)) * flow for i, flow in\n enumerate(self.flownet(sequence))]\n else:\n with torch.no_grad():\n flow = [20.0 / 4 * self.flownet(sequence)]\n\n flow = [4 * F.interpolate(f, scale_factor=4, mode='bilinear', align_corners=False) for f in flow]\n\n flows.append(flow)\n\n depth_flow = get_depth_flow(ref_depth, tgt_depth, flow[0])\n\n depth_flow_features = self.depth_flow_branch(depth_flow.detach())\n\n flow2d_features = self.flow2d_branch(flow[0].detach())\n\n squeezed = self.squeeze(torch.cat([flow2d_features, depth_flow_features, image_features], dim=1))\n squeezed = self.relu(squeezed)\n\n exp_masks.append(self.exp_decoder(squeezed))\n\n translation = 0.001 * self.fc_trans(squeezed).mean(3).mean(2)\n rotation = 0.0001 * self.fc_rot(squeezed).mean(3).mean(2)\n\n pose = torch.cat([translation, rotation], dim=1)\n\n poses.append(pose)\n\n if self.training:\n return depth_predictions, flows, exp_masks, poses\n else:\n return depth_predictions[-1], flows[0][0], exp_masks[0], poses[0]","sub_path":"networks/PODNet.py","file_name":"PODNet.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"550701938","text":"from __future__ import print_function\nfrom data import IMDB\nfrom model import Model\nfrom config import args\n\nimport os\nimport json\nimport tensorflow as tf\n\n\ndef main():\n dataloader = IMDB()\n model = Model(dataloader.params)\n\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n\n n_batch = len(dataloader.enc_inp) // args.batch_size\n \n print(\"Loading trained model ...\")\n model.saver.restore(sess, model.model_path)\n\n for epoch in range(args.stage_2_num_epochs):\n dataloader.update_word_dropout()\n print(\"Word Dropout\")\n dataloader.shuffle()\n print(\"Data Shuffled\")\n print()\n for i, (enc_inp, dec_inp, dec_out, labels) in enumerate(dataloader.next_batch()):\n\n log = model.train_discriminator_session(sess, enc_inp, dec_inp, dec_out, labels)\n if i % args.stage_2_display_step == 0:\n print(\"------------\")\n print(\"Step %d | Train Discriminator | [%d/%d] | [%d/%d]\" % (\n log['step'], epoch+1, args.stage_2_num_epochs, i, n_batch))\n print(\"\\t| clf_loss:%.2f | clf_acc:%.2f | L_u: %.2f\" % (\n log['clf_loss'], log['clf_acc'], log['L_u']))\n print()\n \n log = model.train_encoder_session(sess, enc_inp, dec_inp, dec_out)\n if i % args.stage_2_display_step == 0:\n print(\"Step %d | Train Encoder | [%d/%d] | [%d/%d]\" % (\n log['step'], epoch+1, args.stage_2_num_epochs, i, n_batch))\n print(\"\\t| seq_loss:%.1f | kl_w:%.2f | kl_loss:%.2f\" % (\n log['nll_loss'], log['kl_w'], log['kl_loss']))\n print()\n \n log = model.train_generator_session(sess, enc_inp, dec_inp, dec_out)\n if i % args.stage_2_display_step == 0:\n print(\"Step %d | Train Generator | [%d/%d] | [%d/%d]\" % (\n log['step'], epoch+1, args.stage_2_num_epochs, i, n_batch))\n print(\"\\t| seq_loss:%.1f | kl_w:%.2f | kl_loss:%.2f\" % (\n log['nll_loss'], log['kl_w'], log['kl_loss']))\n print(\"\\t| temperature:%.2f | l_attr_z:%.2f | l_attr_c:%.2f\" % (\n log['temperature'], log['l_attr_z'], log['l_attr_c']))\n print(\"------------\")\n \n if i % (5 * args.stage_2_display_step) == 0:\n model.post_inference(sess, 'i love this film it is so good to watch')\n model.post_inference(sess, 'this movie is horrible and waste my time')\n save_path = model.saver.save(sess, './saved_temp/model.ckpt')\n print(\"Model saved in file: %s\" % save_path)\n\nif __name__ == '__main__':\n print(json.dumps(args.__dict__, indent=4))\n main()","sub_path":"nlp-models/tensorflow/toward-control/train_discriminator.py","file_name":"train_discriminator.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"360559984","text":"#uhhhhhhhhhhhhhhhhhhhhh\n#Softdev2 pd8\n#K08Ay Mon, Go Git It From Yer Flask\n#2019-03-07\n\nimport os\nfrom flask import Flask, render_template, url_for, redirect, flash, request\nfrom mango import *\n\n\napp = Flask(__name__)\napp.secret_key = os.urandom(32)\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/newaddress\", methods = [\"GET\",\"POST\"])\ndef newaddress():\n if request.method == \"POST\":\n info = {}\n ip = request.form[\"ip\"]\n if ip:\n connect(ip)\n id = request.form['id']\n if id:\n data = find_pokemon_by_id(int(id))\n if len(data) != 0:\n data = data[0]\n info['img'] = data['img']\n info['name'] = data['name']\n info['id'] = data['id']\n info['weaknesses'] = data['weaknesses']\n info['type'] = data['type']\n return render_template('index.html', **info)\n else:\n return redirect(url_for(\"index\"))\n\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n","sub_path":"08_mongosite/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"124958094","text":"import abc\nfrom functools import wraps\nfrom dbt.deprecations import warn, renamed_method\n\n\ndef _always_none(*args, **kwargs):\n return None\n\n\ndef _always_list(*args, **kwargs):\n return None\n\n\ndef available(func):\n \"\"\"A decorator to indicate that a method on the adapter will be\n exposed to the database wrapper, and will be available at parse and run\n time.\n \"\"\"\n func._is_available_ = True\n return func\n\n\ndef available_deprecated(supported_name, parse_replacement=None):\n \"\"\"A decorator that marks a function as available, but also prints a\n deprecation warning. Use like\n\n @available_deprecated('my_new_method')\n def my_old_method(self, arg):\n args = compatability_shim(arg)\n return self.my_new_method(*args)\n\n @available_deprecated('my_new_slow_method', lambda *a, **k: (0, ''))\n def my_old_slow_method(self, arg):\n args = compatibility_shim(arg)\n return self.my_new_slow_method(*args)\n\n To make `adapter.my_old_method` available but also print out a warning on\n use directing users to `my_new_method`.\n\n The optional parse_replacement, if provided, will provide a parse-time\n replacement for the actual method (see `available_parse`).\n \"\"\"\n def wrapper(func):\n func_name = func.__name__\n renamed_method(func_name, supported_name)\n\n @wraps(func)\n def inner(*args, **kwargs):\n warn('adapter:{}'.format(func_name))\n return func(*args, **kwargs)\n\n if parse_replacement:\n available = available_parse(parse_replacement)\n return available(inner)\n return wrapper\n\n\ndef available_parse(parse_replacement):\n \"\"\"A decorator factory to indicate that a method on the adapter will be\n exposed to the database wrapper, and will be stubbed out at parse time with\n the given function.\n\n @available_parse()\n def my_method(self, a, b):\n if something:\n return None\n return big_expensive_db_query()\n\n @available_parse(lambda *args, **args: {})\n def my_other_method(self, a, b):\n x = {}\n x.update(big_expensive_db_query())\n return x\n \"\"\"\n def inner(func):\n func._parse_replacement_ = parse_replacement\n available(func)\n return func\n return inner\n\n\navailable.deprecated = available_deprecated\navailable.parse = available_parse\navailable.parse_none = available_parse(lambda *a, **k: None)\navailable.parse_list = available_parse(lambda *a, **k: [])\n\n\nclass AdapterMeta(abc.ABCMeta):\n def __new__(mcls, name, bases, namespace, **kwargs):\n cls = super().__new__(mcls, name, bases, namespace, **kwargs)\n\n # this is very much inspired by ABCMeta's own implementation\n\n # dict mapping the method name to whether the model name should be\n # injected into the arguments. All methods in here are exposed to the\n # context.\n available = set()\n replacements = {}\n\n # collect base class data first\n for base in bases:\n available.update(getattr(base, '_available_', set()))\n replacements.update(getattr(base, '_parse_replacements_', set()))\n\n # override with local data if it exists\n for name, value in namespace.items():\n if getattr(value, '_is_available_', False):\n available.add(name)\n parse_replacement = getattr(value, '_parse_replacement_', None)\n if parse_replacement is not None:\n replacements[name] = parse_replacement\n\n cls._available_ = frozenset(available)\n # should this be a namedtuple so it will be immutable like _available_?\n cls._parse_replacements_ = replacements\n return cls\n","sub_path":"core/dbt/adapters/base/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"391504171","text":"\"\"\"\nVerifies basic OAUTH functionality in AMO.\n\nSample request_token query:\n /en-US/firefox/oauth/request_token/?\n oauth_consumer_key=GYKEp7m5fJpj9j8Vjz&\n oauth_nonce=A7A79B47-B571-4D70-AA6C-592A0555E94B&\n oauth_signature_method=HMAC-SHA1&\n oauth_timestamp=1282950712&\n oauth_version=1.0\n\nWith headers:\n\n Authorization: OAuth realm=\"\",\n oauth_consumer_key=\"GYKEp7m5fJpj9j8Vjz\",\n oauth_signature_method=\"HMAC-SHA1\",\n oauth_signature=\"JBCA4ah%2FOQC0lLWV8aChGAC+15s%3D\",\n oauth_timestamp=\"1282950995\",\n oauth_nonce=\"1008F707-37E6-4ABF-8322-C6B658771D88\",\n oauth_version=\"1.0\"\n\"\"\"\nimport json\nimport os\nimport time\nimport urllib\nimport urlparse\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.core import mail\nfrom django.test.client import (encode_multipart, Client, FakePayload,\n BOUNDARY, MULTIPART_CONTENT, RequestFactory)\n\nimport oauth2 as oauth\nfrom mock import Mock, patch\nfrom nose.tools import eq_\nfrom piston.models import Consumer\n\nimport amo\nfrom amo.helpers import absolutify\nfrom amo.tests import TestCase\nfrom amo.urlresolvers import reverse\nfrom api.authentication import AMOOAuthAuthentication\nfrom addons.models import Addon, AddonUser, BlacklistedGuid\nfrom devhub.models import ActivityLog, SubmitStep\nfrom files.models import File\nfrom perf.models import (Performance, PerformanceAppVersions,\n PerformanceOSVersion)\nfrom translations.models import Translation\nfrom users.models import UserProfile\nfrom versions.models import AppVersion, Version\n\n\ndef _get_args(consumer, token=None, callback=False, verifier=None):\n d = dict(oauth_consumer_key=consumer.key,\n oauth_nonce=oauth.generate_nonce(),\n oauth_signature_method='HMAC-SHA1',\n oauth_timestamp=int(time.time()),\n oauth_version='1.0')\n\n if callback:\n d['oauth_callback'] = 'http://testserver/foo'\n\n if verifier:\n d['oauth_verifier'] = verifier\n\n return d\n\n\ndef get_absolute_url(url):\n if isinstance(url, tuple):\n url = reverse(url[0], args=url[1:])\n else:\n url = reverse(url)\n\n return 'http://%s%s' % ('api', url)\n\n\ndef data_keys(d):\n # Form keys and values MUST be part of the signature.\n # File keys MUST be part of the signature.\n # But file values MUST NOT be included as part of the signature.\n return dict([k, '' if isinstance(v, file) else v] for k, v in d.items())\n\n\nclass OAuthClient(Client):\n \"\"\"OauthClient can make magically signed requests.\"\"\"\n signature_method = oauth.SignatureMethod_HMAC_SHA1()\n\n def get(self, url, consumer=None, token=None, callback=False,\n verifier=None, params=None):\n url = get_absolute_url(url)\n if params:\n url = '%s?%s' % (url, urllib.urlencode(params))\n req = oauth.Request(method='GET', url=url,\n parameters=_get_args(consumer, callback=callback,\n verifier=verifier))\n req.sign_request(self.signature_method, consumer, token)\n return super(OAuthClient, self).get(\n req.to_url(), HTTP_HOST='api', HTTP_AUTHORIZATION='OAuth realm=\"\"',\n **req)\n\n def delete(self, url, consumer=None, token=None, callback=False,\n verifier=None):\n url = get_absolute_url(url)\n req = oauth.Request(method='DELETE', url=url,\n parameters=_get_args(consumer, callback=callback,\n verifier=verifier))\n req.sign_request(self.signature_method, consumer, token)\n return super(OAuthClient, self).delete(\n req.to_url(), HTTP_HOST='api', HTTP_AUTHORIZATION='OAuth realm=\"\"',\n **req)\n\n def post(self, url, consumer=None, token=None, callback=False,\n verifier=None, data={}):\n url = get_absolute_url(url)\n params = _get_args(consumer, callback=callback, verifier=verifier)\n params.update(data_keys(data))\n req = oauth.Request(method='POST', url=url, parameters=params)\n req.sign_request(self.signature_method, consumer, token)\n return super(OAuthClient, self).post(\n req.to_url(), HTTP_HOST='api', HTTP_AUTHORIZATION='OAuth realm=\"\"',\n data=data, headers=req.to_header())\n\n def put(self, url, consumer=None, token=None, callback=False,\n verifier=None, data={}, content_type=MULTIPART_CONTENT, **kwargs):\n \"\"\"\n Send a resource to the server using PUT.\n \"\"\"\n # If data has come from JSON remove unicode keys.\n data = dict([(str(k), v) for k, v in data.items()])\n url = get_absolute_url(url)\n params = _get_args(consumer, callback=callback, verifier=verifier)\n params.update(data_keys(data))\n\n req = oauth.Request(method='PUT', url=url, parameters=params)\n req.sign_request(self.signature_method, consumer, token)\n post_data = encode_multipart(BOUNDARY, data)\n\n parsed = urlparse.urlparse(url)\n query_string = urllib.urlencode(req, doseq=True)\n r = {\n 'CONTENT_LENGTH': len(post_data),\n 'CONTENT_TYPE': content_type,\n 'PATH_INFO': urllib.unquote(parsed[2]),\n 'QUERY_STRING': query_string,\n 'REQUEST_METHOD': 'PUT',\n 'wsgi.input': FakePayload(post_data),\n 'HTTP_HOST': 'api',\n 'HTTP_AUTHORIZATION': 'OAuth realm=\"\"',\n }\n r.update(req)\n\n response = self.request(**r)\n return response\n\noclient = OAuthClient()\ntoken_keys = ('oauth_token_secret', 'oauth_token',)\n\n\ndef get_token_from_response(response):\n data = urlparse.parse_qs(response.content)\n for key in token_keys:\n assert key in data.keys(), '%s not in %s' % (key, data.keys())\n\n return oauth.Token(key=data['oauth_token'][0],\n secret=data['oauth_token_secret'][0])\n\n\ndef get_request_token(consumer, callback=False):\n r = oclient.get('oauth.request_token', consumer, callback=callback)\n return get_token_from_response(r)\n\n\ndef get_access_token(consumer, token, authorize=True, verifier=None):\n r = oclient.get('oauth.access_token', consumer, token, verifier=verifier)\n\n if authorize:\n return get_token_from_response(r)\n else:\n eq_(r.status_code, 401)\n\n\nclass BaseOAuth(TestCase):\n fixtures = ['base/users', 'base/appversion', 'base/licenses']\n\n def setUp(self):\n super(BaseOAuth, self).setUp()\n self.editor = UserProfile.objects.get(email='editor@mozilla.com')\n self.admin = UserProfile.objects.get(email='admin@mozilla.com')\n consumers = []\n for status in ('accepted', 'pending', 'canceled', ):\n c = Consumer(name='a', status=status, user=self.editor)\n c.generate_random_codes()\n c.save()\n consumers.append(c)\n self.accepted_consumer = consumers[0]\n self.pending_consumer = consumers[1]\n self.canceled_consumer = consumers[2]\n self.token = None\n\n\nclass TestBaseOAuth(BaseOAuth):\n\n def test_accepted(self):\n self.assertRaises(AssertionError, get_request_token,\n self.accepted_consumer)\n\n def test_accepted_callback(self):\n get_request_token(self.accepted_consumer, callback=True)\n\n def test_request_token_pending(self):\n get_request_token(self.pending_consumer, callback=True)\n\n def test_request_token_cancelled(self):\n get_request_token(self.canceled_consumer, callback=True)\n\n def test_request_token_fake(self):\n \"\"\"Try with a phony consumer key\"\"\"\n c = Mock()\n c.key = 'yer'\n c.secret = 'mom'\n r = oclient.get('oauth.request_token', c, callback=True)\n eq_(r.content, 'Invalid Consumer.')\n\n @patch('piston.authentication.oauth.OAuthAuthentication.is_authenticated')\n def _test_auth(self, pk, is_authenticated, two_legged=True):\n request = RequestFactory().get('/en-US/firefox/2/api/2/user/',\n data={'authenticate_as': pk})\n request.user = None\n\n def alter_request(*args, **kw):\n request.user = self.admin\n return True\n is_authenticated.return_value = True\n is_authenticated.side_effect = alter_request\n\n auth = AMOOAuthAuthentication()\n auth.two_legged = two_legged\n auth.is_authenticated(request)\n return request\n\n def test_login_nonexistant(self):\n eq_(self.admin, self._test_auth(9999).user)\n\n def test_login_deleted(self):\n # If _test_auth returns self.admin, that means the user was\n # not altered to the user set in authenticate_as.\n self.editor.update(deleted=True)\n pk = self.editor.pk\n eq_(self.admin, self._test_auth(pk).user)\n\n def test_login_unconfirmed(self):\n self.editor.update(confirmationcode='something')\n pk = self.editor.pk\n eq_(self.admin, self._test_auth(pk).user)\n\n def test_login_works(self):\n pk = self.editor.pk\n eq_(self.editor, self._test_auth(pk).user)\n\n def test_login_three_legged(self):\n pk = self.editor.pk\n eq_(self.admin, self._test_auth(pk, two_legged=False).user)\n\n\nclass TestUser(BaseOAuth):\n\n def test_user(self):\n r = oclient.get('api.user', self.accepted_consumer, self.token)\n eq_(json.loads(r.content)['email'], 'editor@mozilla.com')\n\n def test_user_lookup(self):\n partner = UserProfile.objects.get(email='partner@mozilla.com')\n c = Consumer(name='p', status='accepted', user=partner)\n c.generate_random_codes()\n c.save()\n r = oclient.get('api.user', c, None,\n params={'email': 'admin@mozilla.com'})\n eq_(r.status_code, 200)\n eq_(json.loads(r.content)['email'], 'admin@mozilla.com')\n\n def test_failed_user_lookup(self):\n partner = UserProfile.objects.get(email='partner@mozilla.com')\n c = Consumer(name='p', status='accepted', user=partner)\n c.generate_random_codes()\n c.save()\n r = oclient.get('api.user', c, None,\n params={'email': 'not_a_user@mozilla.com'})\n eq_(r.status_code, 404)\n\n def test_forbidden_user_lookup(self, response_code=401):\n r = oclient.get('api.user', self.accepted_consumer, self.token,\n params={'email': 'admin@mozilla.com'})\n eq_(r.status_code, response_code)\n\n\nclass TestDRFUser(TestUser):\n\n def setUp(self):\n super(TestDRFUser, self).setUp()\n self.create_switch('drf', db=True)\n\n def test_forbidden_user_lookup(self):\n super(TestDRFUser, self).test_forbidden_user_lookup(response_code=403)\n\n\ndef activitylog_count(type=None):\n qs = ActivityLog.objects\n if type:\n qs = qs.filter(action=type.id)\n return qs.count()\n\n\nclass TestAddon(BaseOAuth):\n created_http_status = 200\n permission_denied_http_status = 401\n\n def setUp(self):\n super(TestAddon, self).setUp()\n path = 'apps/files/fixtures/files/extension.xpi'\n xpi = os.path.join(settings.ROOT, path)\n f = open(xpi)\n\n self.create_data = dict(builtin=0,\n name='FREEDOM',\n text='This is FREE!',\n platform='mac',\n xpi=f)\n\n path = 'apps/files/fixtures/files/extension-0.2.xpi'\n self.version_data = dict(builtin=2, platform='windows',\n xpi=open(os.path.join(settings.ROOT, path)))\n self.update_data = dict(name='fu',\n default_locale='fr',\n homepage='mozilla.com',\n support_email='go@away.com',\n support_url='http://google.com/',\n description='awesome',\n summary='sucks',\n developer_comments='i made it for you',\n eula='love it',\n privacy_policy='aybabtu',\n the_reason='for shits',\n the_future='is gone',\n view_source=1,\n prerelease=1,\n binary=False,\n site_specific=1)\n\n def make_create_request(self, data):\n return oclient.post('api.addons', self.accepted_consumer, self.token,\n data=data)\n\n def create_addon(self):\n current_count = activitylog_count(amo.LOG.CREATE_ADDON)\n r = self.make_create_request(self.create_data)\n eq_(r.status_code, self.created_http_status, r.content)\n # 1 new add-on\n eq_(activitylog_count(amo.LOG.CREATE_ADDON), current_count + 1)\n return json.loads(r.content)\n\n def test_create_no_user(self):\n # The user in TwoLeggedAuth is set to the consumer user.\n # If there isn't one, we should get a challenge back.\n self.accepted_consumer.user = None\n self.accepted_consumer.save()\n r = self.make_create_request(self.create_data)\n eq_(r.status_code, 401)\n\n def test_create_user_altered(self):\n data = self.create_data\n data['authenticate_as'] = self.editor.pk\n r = self.make_create_request(data)\n eq_(r.status_code, self.created_http_status, r.content)\n\n id = json.loads(r.content)['id']\n ad = Addon.objects.get(pk=id)\n eq_(len(ad.authors.all()), 1)\n eq_(ad.authors.all()[0].pk, self.editor.pk)\n\n def test_create(self):\n # License (req'd): MIT, GPLv2, GPLv3, LGPLv2.1, LGPLv3, MIT, BSD, Other\n # Custom License (if other, req'd)\n # XPI file... (req'd)\n # Platform (All by default): 'mac', 'all', 'bsd', 'linux', 'solaris',\n # 'windows'\n\n data = self.create_addon()\n id = data['id']\n name = data['name']\n eq_(name, 'xpi name')\n assert Addon.objects.get(pk=id)\n\n def create_no_license(self):\n data = self.create_data.copy()\n del data['builtin']\n return self.make_create_request(data)\n\n def test_create_no_license(self):\n r = self.create_no_license()\n eq_(r.status_code, self.created_http_status, r.content)\n eq_(Addon.objects.count(), 1)\n\n def test_create_no_license_step(self):\n r = self.create_no_license()\n eq_(r.status_code, self.created_http_status, r.content)\n id = json.loads(r.content)['id']\n eq_(SubmitStep.objects.get(addon=id).step, 5)\n\n def test_create_no_license_url(self):\n self.create_no_license()\n self.client.login(username='editor@mozilla.com', password='password')\n res = self.client.get(reverse('devhub.submit.resume',\n args=['xpi-name']))\n self.assertRedirects(res, reverse('devhub.submit.5',\n args=['xpi-name']))\n\n def test_create_no_license_status(self):\n self.create_no_license()\n eq_(Addon.objects.get(slug='xpi-name').status, 0)\n\n def test_create_status(self):\n r = self.make_create_request(self.create_data)\n eq_(r.status_code, self.created_http_status, r.content)\n eq_(Addon.objects.get(slug='xpi-name').status, 0)\n eq_(Addon.objects.count(), 1)\n\n def test_create_slug(self):\n r = self.make_create_request(self.create_data)\n content = json.loads(r.content)\n eq_(content['slug'], 'xpi-name')\n eq_(content['resource_uri'],\n absolutify(reverse('addons.detail', args=['xpi-name'])))\n\n def test_delete(self):\n data = self.create_addon()\n id = data['id']\n guid = data['guid']\n # Force it to be public so its guid gets blacklisted.\n Addon.objects.filter(id=id).update(highest_status=amo.STATUS_PUBLIC)\n\n r = oclient.delete(('api.addon', id), self.accepted_consumer,\n self.token)\n eq_(r.status_code, 204, r.content)\n eq_(Addon.objects.filter(pk=id).count(), 0, \"Didn't delete.\")\n\n assert BlacklistedGuid.objects.filter(guid=guid)\n eq_(len(mail.outbox), 1)\n\n def test_update(self):\n # create an addon\n data = self.create_addon()\n id = data['id']\n\n current_count = activitylog_count()\n r = oclient.put(('api.addon', id), self.accepted_consumer, self.token,\n data=self.update_data)\n eq_(r.status_code, 200, r.content)\n\n # EDIT_PROPERTIES\n eq_(activitylog_count(), current_count + 1)\n\n a = Addon.objects.get(pk=id)\n for field, expected in self.update_data.iteritems():\n value = getattr(a, field)\n if isinstance(value, Translation):\n value = unicode(value)\n\n eq_(value, expected,\n \"'%s' didn't match: got '%s' instead of '%s'\"\n % (field, getattr(a, field), expected))\n\n @patch('api.handlers.AddonForm.is_valid')\n def test_update_fail(self, is_valid):\n data = self.create_addon()\n id = data['id']\n is_valid.return_value = False\n r = oclient.put(('api.addon', id), self.accepted_consumer, self.token,\n data=self.update_data)\n eq_(r.status_code, 400, r.content)\n\n def test_update_nonexistant(self):\n r = oclient.put(('api.addon', 0), self.accepted_consumer, self.token,\n data={})\n eq_(r.status_code, 410, r.content)\n\n @patch('api.handlers.XPIForm.clean_xpi')\n def test_xpi_failure(self, f):\n f.side_effect = forms.ValidationError('F')\n r = self.make_create_request(self.create_data)\n eq_(r.status_code, 400)\n\n def test_fake_license(self):\n data = self.create_data.copy()\n data['builtin'] = 'fff'\n\n r = self.make_create_request(data)\n eq_(r.status_code, 400, r.content)\n eq_(r.content, 'Bad Request: Invalid data provided: '\n 'Select a valid choice. fff is not one of the available choices. '\n '(builtin)')\n\n @patch('zipfile.ZipFile.infolist')\n def test_bad_zip(self, infolist):\n fake = Mock()\n fake.filename = '..'\n infolist.return_value = [fake]\n r = self.make_create_request(self.create_data)\n eq_(r.status_code, 400, r.content)\n\n @patch('versions.models.AppVersion.objects.get')\n def test_bad_appversion(self, get):\n get.side_effect = AppVersion.DoesNotExist()\n data = self.create_addon()\n assert data, \"We didn't get data.\"\n\n def test_wrong_guid(self):\n data = self.create_addon()\n id = data['id']\n addon = Addon.objects.get(pk=id)\n addon.guid = 'XXX'\n addon.save()\n\n # Upload new version of file\n r = oclient.post(('api.versions', id,), self.accepted_consumer,\n self.token, data=self.version_data)\n eq_(r.status_code, 400)\n eq_(r.content, 'Bad Request: Add-on did not validate: '\n \"UUID doesn't match add-on.\")\n\n def test_duplicate_guid(self):\n self.create_addon()\n data = self.create_data.copy()\n data['xpi'] = self.version_data['xpi']\n r = self.make_create_request(data)\n eq_(r.status_code, 400)\n eq_(r.content, 'Bad Request: Add-on did not validate: '\n 'Duplicate UUID found.')\n\n def test_create_version(self):\n # Create an addon and let's use this for the new version.\n data = self.create_addon()\n id = data['id']\n\n log_count = activitylog_count()\n\n # Upload new version of file\n r = oclient.post(('api.versions', id,), self.accepted_consumer,\n self.token, data=self.version_data)\n\n eq_(r.status_code, 200, r.content)\n\n # verify we've logged a new version and a new app version\n eq_(log_count + 2, activitylog_count())\n\n # validate that the addon has 2 versions\n a = Addon.objects.get(pk=id)\n eq_(a.versions.all().count(), 2)\n\n # validate the version number\n v = a.versions.get(version='0.2')\n eq_(v.version, '0.2')\n # validate any new version data\n eq_(amo.PLATFORMS[v.files.get().platform].shortname, 'windows')\n\n def test_create_version_bad_license(self):\n data = self.create_addon()\n id = data['id']\n data = self.version_data.copy()\n data['builtin'] = 'fu'\n r = oclient.post(('api.versions', id,), self.accepted_consumer,\n self.token, data=data)\n\n eq_(r.status_code, 400, r.content)\n\n def test_create_version_no_license(self):\n data = self.create_addon()\n id = data['id']\n data = self.version_data.copy()\n del data['builtin']\n r = oclient.post(('api.versions', id,), self.accepted_consumer,\n self.token, data=data)\n\n eq_(r.status_code, 200, r.content)\n data = json.loads(r.content)\n id = data['id']\n v = Version.objects.get(pk=id)\n assert not v.license\n\n def create_for_update(self):\n data = self.create_addon()\n id = data['id']\n a = Addon.objects.get(pk=id)\n v = a.versions.get()\n eq_(v.version, '0.1')\n return a, v, 'apps/files/fixtures/files/extension-0.2.xpi'\n\n def test_update_version_no_license(self):\n a, v, path = self.create_for_update()\n data = dict(release_notes='fukyeah', platform='windows',\n xpi=open(os.path.join(settings.ROOT, path)))\n r = oclient.put(('api.version', a.id, v.id), self.accepted_consumer,\n self.token, data=data, content_type=MULTIPART_CONTENT)\n eq_(r.status_code, 200, r.content)\n v = a.versions.get()\n eq_(v.version, '0.2')\n eq_(v.license, None)\n\n def test_update_version_bad_license(self):\n a, v, path = self.create_for_update()\n data = dict(release_notes='fukyeah', builtin=3, platform='windows',\n xpi=open(os.path.join(settings.ROOT, path)))\n r = oclient.put(('api.version', a.id, v.id), self.accepted_consumer,\n self.token, data=data, content_type=MULTIPART_CONTENT)\n eq_(r.status_code, 400, r.content)\n\n def test_update_version(self):\n a, v, path = self.create_for_update()\n data = dict(release_notes='fukyeah', builtin=2, platform='windows',\n xpi=open(os.path.join(settings.ROOT, path)))\n log_count = activitylog_count()\n # upload new version\n r = oclient.put(('api.version', a.id, v.id), self.accepted_consumer,\n self.token, data=data, content_type=MULTIPART_CONTENT)\n eq_(r.status_code, 200, r.content[:1000])\n\n # verify we've logged a version update and a new app version\n eq_(activitylog_count(), log_count + 2)\n # verify data\n v = a.versions.get()\n eq_(v.version, '0.2')\n eq_(str(v.releasenotes), 'fukyeah')\n eq_(str(v.license.builtin), '2')\n\n def test_update_version_bad_xpi(self):\n data = self.create_addon()\n id = data['id']\n\n # verify version\n a = Addon.objects.get(pk=id)\n v = a.versions.get()\n\n eq_(v.version, '0.1')\n\n data = dict(release_notes='fukyeah', platform='windows')\n\n # upload new version\n r = oclient.put(('api.version', id, v.id), self.accepted_consumer,\n self.token, data=data, content_type=MULTIPART_CONTENT)\n eq_(r.status_code, 400)\n\n def test_update_version_bad_id(self):\n r = oclient.put(('api.version', 0, 0), self.accepted_consumer,\n self.token, data={}, content_type=MULTIPART_CONTENT)\n eq_(r.status_code, 410, r.content)\n\n def test_get_version(self):\n data = self.create_addon()\n a = Addon.objects.get(pk=data['id'])\n r = oclient.get(('api.version', data['id'], a.versions.get().id),\n self.accepted_consumer, self.token)\n eq_(r.status_code, 200)\n\n def test_get_version_statuses(self):\n data = self.create_addon()\n a = Addon.objects.get(pk=data['id'])\n r = oclient.get(('api.version', data['id'], a.versions.get().id),\n self.accepted_consumer, self.token)\n eq_(json.loads(r.content)['statuses'],\n [[File.objects.all()[0].pk, 1]])\n\n @patch('api.authorization.AllowRelatedAppOwner.has_object_permission')\n @patch('api.authorization.AllowAppOwner.has_object_permission')\n @patch('access.acl.action_allowed')\n @patch('access.acl.check_addon_ownership')\n def test_not_my_addon(self, addon_ownership, action_allowed,\n app_owner, related_app_owner):\n data = self.create_addon()\n id = data['id']\n a = Addon.objects.get(pk=id)\n v = a.versions.get()\n # The first one is for piston, the 3 next ones are for DRF.\n addon_ownership.return_value = False\n action_allowed.return_value = False\n app_owner.return_value = False\n related_app_owner.return_value = False\n\n r = oclient.put(('api.version', id, v.id), self.accepted_consumer,\n self.token, data={}, content_type=MULTIPART_CONTENT)\n eq_(r.status_code, self.permission_denied_http_status, r.content)\n\n r = oclient.put(('api.addon', id), self.accepted_consumer, self.token,\n data=self.update_data)\n eq_(r.status_code, self.permission_denied_http_status, r.content)\n\n def test_delete_version(self):\n data = self.create_addon()\n id = data['id']\n\n a = Addon.objects.get(pk=id)\n v = a.versions.get()\n\n log_count = activitylog_count()\n r = oclient.delete(('api.version', id, v.id), self.accepted_consumer,\n self.token)\n eq_(activitylog_count(), log_count + 1)\n\n eq_(r.status_code, 204, r.content)\n eq_(a.versions.count(), 0)\n\n def test_retrieve_versions(self):\n data = self.create_addon()\n id = data['id']\n\n a = Addon.objects.get(pk=id)\n v = a.versions.get()\n\n r = oclient.get(('api.versions', id), self.accepted_consumer,\n self.token)\n eq_(r.status_code, 200, r.content)\n data = json.loads(r.content)\n for attr in ('id', 'version',):\n expect = getattr(v, attr)\n val = data[0].get(attr)\n eq_(expect, val,\n 'Got \"%s\" was expecting \"%s\" for \"%s\".' % (val, expect, attr,))\n\n def test_no_addons(self):\n r = oclient.get('api.addons', self.accepted_consumer, self.token)\n eq_(json.loads(r.content)['count'], 0)\n\n def test_no_user(self):\n addon = Addon.objects.create(type=amo.ADDON_EXTENSION)\n AddonUser.objects.create(addon=addon, user=self.admin,\n role=amo.AUTHOR_ROLE_DEV)\n r = oclient.get('api.addons', self.accepted_consumer, self.token)\n eq_(json.loads(r.content)['count'], 0)\n\n def test_my_addons_only(self):\n for num in range(0, 2):\n addon = Addon.objects.create(type=amo.ADDON_EXTENSION)\n AddonUser.objects.create(addon=addon, user=self.editor,\n role=amo.AUTHOR_ROLE_DEV)\n r = oclient.get('api.addons', self.accepted_consumer, self.token,\n params={'authenticate_as': self.editor.pk})\n j = json.loads(r.content)\n eq_(j['count'], 1)\n eq_(j['objects'][0]['id'], addon.id)\n\n def test_one_addon(self):\n addon = Addon.objects.create(type=amo.ADDON_EXTENSION)\n AddonUser.objects.create(addon=addon, user=self.editor,\n role=amo.AUTHOR_ROLE_DEV)\n r = oclient.get(('api.addon', addon.pk), self.accepted_consumer,\n self.token, params={'authenticate_as': self.editor.pk})\n eq_(json.loads(r.content)['id'], addon.pk)\n\n def test_my_addons_role(self):\n addon = Addon.objects.create(type=amo.ADDON_EXTENSION)\n AddonUser.objects.create(addon=addon, user=self.editor,\n role=amo.AUTHOR_ROLE_VIEWER)\n r = oclient.get('api.addons', self.accepted_consumer, self.token)\n eq_(json.loads(r.content)['count'], 0)\n\n def test_my_addons_disabled(self):\n addon = Addon.objects.create(type=amo.ADDON_EXTENSION,\n status=amo.STATUS_DISABLED)\n AddonUser.objects.create(addon=addon, user=self.editor,\n role=amo.AUTHOR_ROLE_DEV)\n r = oclient.get('api.addons', self.accepted_consumer, self.token)\n eq_(json.loads(r.content)['count'], 0)\n\n def test_my_addons_deleted(self):\n addon = Addon.objects.create(type=amo.ADDON_EXTENSION,\n status=amo.STATUS_DELETED)\n AddonUser.objects.create(addon=addon, user=self.editor,\n role=amo.AUTHOR_ROLE_DEV)\n r = oclient.get('api.addons', self.accepted_consumer, self.token)\n eq_(json.loads(r.content)['count'], 0)\n\n\nclass TestDRFAddon(TestAddon):\n created_http_status = 201\n permission_denied_http_status = 403\n\n def setUp(self):\n super(TestDRFAddon, self).setUp()\n self.create_switch('drf', db=True)\n\n def _compare_dicts(self, drf_data, piston_data):\n \"\"\"\n Given 2 dicts of data from DRF and Piston, compare keys then values.\n \"\"\"\n eq_(sorted(drf_data.keys()), sorted(piston_data.keys()),\n ('Keys inexistent from Piston: {0}\\n'\n 'Keys inexistent from DRF: {1}').format(\n set(piston_data) - set(drf_data),\n set(drf_data) - set(piston_data)))\n for drf_item, piston_item in zip(sorted(drf_data.items()),\n sorted(piston_data.items())):\n eq_(drf_item[0], piston_item[0])\n eq_(drf_item[1], piston_item[1],\n ('Different representations for key \"{0}\": DRF={1}, Piston={2}'\n .format(drf_item[0], drf_item[1], piston_item[1])))\n\n def compare_output(self, url, listed=False):\n \"\"\"\n Load responses from DRF and Piston given the `url` parameter and\n compare returned data dicts, key by key. Useful to make sure\n that both responses are similar.\n\n Set `listed` to True for comparing responses as lists.\n \"\"\"\n r = oclient.get(url, self.accepted_consumer, self.token)\n eq_(r.status_code, 200, r.content)\n drf_data = json.loads(r.content)\n self.create_switch('drf', **{'active': False})\n r = oclient.get(url, self.accepted_consumer, self.token)\n eq_(r.status_code, 200, r.content)\n piston_data = json.loads(r.content)\n if listed:\n eq_(len(drf_data), len(piston_data))\n for items in zip(drf_data, piston_data):\n self._compare_dicts(items[0], items[1])\n else:\n self._compare_dicts(drf_data, piston_data)\n\n def test_diff_versions(self):\n data = self.create_addon()\n self.compare_output(('api.versions', data['id']), listed=True)\n\n def test_diff_version(self):\n data = self.create_addon()\n addon = Addon.objects.get(pk=data['id'])\n version = addon.versions.get()\n self.compare_output(('api.version', addon.id, version.id))\n\n def test_diff_addons(self):\n self.create_addon()\n self.compare_output(('api.addons'))\n\n def test_diff_addon(self):\n data = self.create_addon()\n self.compare_output(('api.addon', data['id']))\n\n\nclass TestPerformanceAPI(BaseOAuth):\n fixtures = ['base/users']\n\n def get_data(self):\n return {\n 'os': 'WINNT',\n 'version': '123',\n 'platform': 'x86',\n 'product': 'firefox',\n 'product_version': 'x.y.z',\n 'average': '1.25',\n 'test': 'ts'\n }\n\n def make_create_request(self, data):\n return oclient.post('api.performance.add', self.accepted_consumer,\n self.token, data=data)\n\n def test_form_fails(self):\n res = self.make_create_request({})\n eq_(res.status_code, 400)\n\n def test_not_allowed(self):\n res = self.client.post(reverse('api.performance.add'), {})\n eq_(res.status_code, 401)\n\n def test_form_incomplete(self):\n data = self.get_data()\n del data['test']\n res = self.make_create_request(data)\n eq_(res.status_code, 400)\n assert 'This field is required. (test)' in res.content\n\n def test_form_validate(self):\n data = self.get_data()\n data['os'] = 'WebOS hotness'\n res = self.make_create_request(data)\n eq_(res.status_code, 400)\n assert 'WebOS hotness' in res.content\n\n def test_no_addon(self):\n data = self.get_data()\n data['addon_id'] = '123'\n res = self.make_create_request(data)\n eq_(res.status_code, 400)\n assert 'Add-on not found' in res.content\n\n def test_addon(self):\n data = self.get_data()\n data['addon_id'] = Addon.objects.create(type=amo.ADDON_EXTENSION).pk\n res = self.make_create_request(data)\n eq_(res.status_code, 200)\n perfs = Performance.objects.all()\n eq_(perfs[0].addon_id, data['addon_id'])\n\n def test_form_data(self):\n res = self.make_create_request(self.get_data())\n eq_(res.status_code, 200)\n perfs = Performance.objects.all()\n eq_(perfs.count(), 1)\n eq_(perfs[0].average, 1.25)\n\n def test_form_updates(self):\n self.test_form_data()\n data = self.get_data()\n data['average'] = 1.3\n self.make_create_request(data)\n perfs = Performance.objects.all()\n eq_(len(perfs), 1)\n eq_(perfs[0].average, 1.3)\n\n def test_creates_app_version(self):\n self.test_form_data()\n apps = PerformanceAppVersions.objects.all()\n eq_(len(apps), 1)\n eq_(apps[0].app, 'firefox')\n eq_(apps[0].version, 'x.y.z')\n\n def test_gets_app_version(self):\n self.test_form_data()\n eq_(PerformanceAppVersions.objects.all().count(), 1)\n self.test_form_data()\n eq_(PerformanceAppVersions.objects.all().count(), 1)\n\n def test_creates_os_version(self):\n self.test_form_data()\n apps = PerformanceOSVersion.objects.all()\n eq_(apps.count(), 1)\n eq_(apps[0].os, 'WINNT')\n\n def test_gets_os_version(self):\n self.test_form_data()\n eq_(PerformanceOSVersion.objects.all().count(), 1)\n self.test_form_data()\n eq_(PerformanceOSVersion.objects.all().count(), 1)\n","sub_path":"apps/api/tests/test_oauth.py","file_name":"test_oauth.py","file_ext":"py","file_size_in_byte":34999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"251927659","text":"import os\nimport time\ntest_dict={}\nfinaList=[]\ndateTime = time.strftime('%Y%m',time.localtime(time.time()))\nfileName='portList%s.txt' % str(int(dateTime)-1)\nnewFileName='portList%s.txt' % dateTime\nwith open(fileName,'r',encoding='utf-8') as f:\n all_dict =eval(f.read())\n# newTime = time.strftime(\"%Y%m \", time.localtime())\n# for key,values in all_dict:\n# print(key)\nfor key,value in all_dict.items():\n # print(value)\n pass\nmaxKey = max(all_dict,key=all_dict.get)\nmaxValue = all_dict[maxKey]\nnewPortList = [ x+int(maxValue) for x in range(1,19) ]\nprint (newPortList)\ntext1=\"find ./ -name test -type f|xargs sed -i 's/\"\nfinaList=[ text1 for i in range(len(all_dict))]\n# print(finaList)\nnum =0\nfor values in all_dict.values():\n # ret2 =\"port=%s/\" % values\n ret2 = \"%s/\" % values\n finaList[num] = finaList[num] + ret2\n num +=1\n\nfor i in range(len(newPortList)):\n # print('port='+all_dict[i].keys())\n # ret1='port='+str(newPortList[i])\n ret1 = str(newPortList[i])\n finaList[i]=finaList[i] + ret1+ \"/g'|sh\"\n # print(finaList[i])\n\n# print(finaList)\nfor i in range(len(all_dict)):\n # print(type(finaList[i]))\n code = (list(all_dict.values())[i])\n finaList[i] = finaList[i].replace('test',\"'*%s*'\" % code)\n print(finaList[i])\n\n#重命名配置文件\n#例如:storage201902_df_oldport.conf 改成 storage201902_df_newport.conf\ntext2 = \"find ./ -name 'test1' -type f|sed 's/\\(.*\\)\\(test2\\)\\(.*\\)/mv \\\\1\\\\2\\\\3 \\\\1test3\\\\3/'|sh\"\n# print(text2)\nmv_configure =[ text2 for i in range(len(all_dict))]\nfor i in range(len(all_dict)):\n code1 = (list(all_dict.values())[i])\n code2 = newPortList[i]\n mv_configure[i] =mv_configure[i].replace('test1',\"*%s*\" % code1)\n mv_configure[i] = mv_configure[i].replace('test2', \"%s\" % code1)\n mv_configure[i] = mv_configure[i].replace('test3', \"%s\" % code2)\n print(mv_configure[i])\n\n#批量创建文件夹\n#定义日期\n#这个是针对配置文件修改后才能执行的,就改了个日期,例如把201902改成20192,然后批量创建,取其中一个就可以了。\n#\ndate = dateTime\ndate_final = dateTime[1:-2] + dateTime[-1]\ntext3 = \"find ./ -name '*test1*' -type f|sed 's/\\(.*\\)\\(test2\\)\\(.*\\)\\(.conf\\)/mkdir \\/fastdfs2\\/storage_data\\/20193\\/storagetest3\\\\3/'|sh\"\nmd_dist = [text3 for i in range(len(all_dict))]\nfor i in range(len(all_dict)):\n code3 = (list(all_dict.values())[i])\n code4 = newPortList[i]\n md_dist[i] = md_dist[i].replace('test1',\"%s\" % date)\n md_dist[i] = md_dist[i].replace('test2', \"%s\" % date)\n md_dist[i] = md_dist[i].replace('test3', \"%s\" % date_final,2)\n\n#生成新的组和port一一对应的字典,供下个月使用\nindex=0\nnew_all_dict ={}\nfor key,value in all_dict.items():\n new_all_dict[key] = newPortList[index]\n index +=1\nwith open(newFileName,'w',encoding='utf-8') as f:\n f.write(str(new_all_dict))\n\n# print(finaList)\n# print(mv_configure)\nprint(md_dist[1])","sub_path":"fastdfs组名设置/fastdfs_rename.py","file_name":"fastdfs_rename.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"37513337","text":"import struct\nimport logging\nimport tornado.web\nimport simhash\nimport jieba.analyse\nimport dataservice2\nimport naivematcher\ndb = dataservice2.DataService2()\n\nclass defaultHandler(tornado.web.RequestHandler):\n logger = logging.getLogger(\"sypireme\")\n logger.setLevel(logging.DEBUG)\nclass dialogueHandler(defaultHandler):\n def post(self):\n lang = self.get_argument(\"lang\")\n reply = self.get_argument(\"reply\")\n self.logger.debug(\"Got lang: {}, reply:{}\".format(lang, reply))\n lang_keywords = jieba.analyse.extract_tags(lang, topK=None, allowPOS=None)\n #if len(lang_keywords) == 0:\n # lang_keywords=[(lang, 1)]\n if len(lang_keywords) == 0:\n lang_keywords=[lang]\n #simhash_value = simhash.Simhash(lang_keywords).value\n self.logger.debug(\"Got keywords: {}, reply:{}\".format(lang_keywords, reply))\n db.write(lang_keywords, reply)\n self.write({\n \"status\": \"Success\",\n \"data\": None\n })\n @tornado.gen.coroutine\n def get(self):\n lang = self.get_argument(\"lang\")\n self.logger.debug(\"Got lang: {}\".format(lang))\n lang_keywords = jieba.analyse.extract_tags(lang, topK=None , allowPOS=None)\n #if len(lang_keywords) == 0:\n # lang_keywords=[(lang, 1)]\n if len(lang_keywords) == 0:\n lang_keywords=[lang]\n self.logger.debug(\"Got keywords:{}\".format(lang_keywords))\n #s1 = simhash.Simhash(lang_keywords)\n #self.logger.debug(\"Got simhash for lang:{}\".format(s1.value))\n results = db.find_replies(lang_keywords)\n matcher = naivematcher.CachedNaiveMatcher(lang_keywords)\n max_match = matcher.match(results[0][\"key\"])\n best_reply = results[0][\"reply\"]\n #for simhash_value2, reply in db:\n # s2 = simhash.Simhash(simhash_value2)\n # distance = s1.distance(s2)\n # if min_distance == None or distance < min_distance:\n # min_distance = distance\n # best_reply = reply\n for result in results:\n match = matcher.match(result[\"key\"])\n if match > max_match:\n max_match = match\n best_reply = result[\"reply\"]\n self.logger.debug(\"Got max_match:{}, best_reply: {}\".format(max_match, best_reply))\n self.write({\n \"status\": \"Success\",\n \"data\": {\n \"lang\": lang,\n \"reply\": best_reply\n }\n })\n def write_error(self, status_code, **kwargs):\n if status_code == 404:\n self.write({\n \"status\": \"Not found\",\n \"data\": {\n \"lang\": kwargs[\"lang\"],\n \"reply\": \"\"\n }\n })\n else:\n tornado.web.RequestHandler.write_error(self, status_code, **kwargs)\n","sub_path":"wsgi/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"368104898","text":"# 多线程糗事百科抓取程序\n\nimport time\nfrom queue import Queue\nfrom threading import Thread, Lock\n\nimport requests\nfrom lxml import etree\n\ncrawl_switch = False\nparse_switch = False\n\n\nclass CrawlThread(Thread):\n def __init__(self, thread_name, page_queue, data_queue):\n super(CrawlThread, self).__init__()\n self.thread_name = thread_name\n self.page_queue = page_queue\n self.data_queue = data_queue\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/6.0)\"}\n\n def run(self):\n while not crawl_switch:\n try:\n num = self.page_queue.get(block=False)\n url = \"https://www.qiushibaike.com/textnew/page/\" + str(num)\n print(self.thread_name, url)\n res = requests.get(url, headers=self.headers)\n html = res.text\n self.data_queue.put(html)\n time.sleep(1)\n except:\n pass\n\n\nclass ParseThread(Thread):\n def __init__(self, thread_name, data_queue, filename, lock):\n super(ParseThread, self).__init__()\n self.thread_name = thread_name\n self.data_queue = data_queue\n self.filename = filename\n self.lock = lock\n\n def parse(self, data):\n\n html = etree.HTML(data)\n node_list = html.xpath(\"//div[contains(@id, 'qiushi_tag_')]\")\n\n for node in node_list:\n item = {}\n\n name = node.xpath('./div/a[2]/h2/text()')\n content = node.xpath('.//div[@class=\"content\"]/span/text()')\n\n if len(name) > 0:\n item[\"name\"] = name[0]\n else:\n item[\"name\"] = \"匿名用户\"\n if len(content) > 0:\n content = [i.strip() for i in content]\n content = ''.join(content)\n item['content'] = content\n\n with self.lock:\n with open(self.filename, \"a\", encoding='utf-8') as f:\n f.write(str(item) + \"\\r\\n\")\n\n def run(self):\n while not parse_switch:\n try:\n data = self.data_queue.get(block=False)\n print(\"{}正在工作...\".format(self.thread_name))\n self.parse(data)\n except:\n pass\n\n\ndef main():\n url = \"https://www.qiushibaike.com/textnew/\"\n\n global crawl_switch\n global parse_switch\n\n html = requests.get(url)\n html = html.text\n html = etree.HTML(html)\n page = html.xpath(\"//li[7]/a/span/text()\")[0].strip()\n # print(page)\n\n page_queue = Queue()\n data_queue = Queue()\n\n lock = Lock()\n for i in range(1, int(page) + 1):\n page_queue.put(i)\n\n thread_names = [\"采集线程1\", \"采集线程2\", \"采集线程3\"]\n for thread_name in thread_names:\n crawl = CrawlThread(thread_name, page_queue, data_queue)\n crawl.start()\n\n while not page_queue.empty():\n pass\n\n crawl_switch = True\n\n filename = \"qiubai.txt\"\n\n thread_parse = []\n\n thread_names = [\"清洗线程1\", \"清洗线程2\", \"清洗线程3\"]\n for thread_name in thread_names:\n parse = ParseThread(thread_name, data_queue, filename, lock)\n parse.start()\n thread_parse.append(parse)\n\n while not data_queue.empty():\n pass\n\n parse_switch = True\n\n for parse in thread_parse:\n parse.join()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"0708/test02_多线程抓取糗百段子.py","file_name":"test02_多线程抓取糗百段子.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"460390028","text":"import tensorflow as tf\n\n# Create Operations, Tensor, etc(using default graph)\na = tf.add(2, 3)\nb = tf.multiply(a, 4)\n\n# Start up a 'Session' using the default graph\nsess = tf.Session()\n\n# Define a dictionary that says to replace the value of 'a' with 15\nreplace_dict = {a: 15}\n\n# Run the session, passing in 'replace_dict' as the value to 'feed_dict'\no = sess.run(b, feed_dict=replace_dict) # return 60\n\nprint(o)","sub_path":"tensorflow-practice/src/04-feed-dictionary.py","file_name":"04-feed-dictionary.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"31271652","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n###################################################################\n#\n# make_smil.py\n#\n# Turns alignment into formatted SMIL for ReadAlongs WebComponent\n####################################################################\n\n\nimport argparse\n\nimport chevron\n\nfrom readalongs.text.util import save_txt\n\nSMIL_TEMPLATE = \"\"\"\n \n {{#words}}\n \n \n \n {{/words}}\n \n\n\"\"\"\n\nBASENAME_IDX = 0\nSTART_TIME_IDX = 9\nWORDS_IDX = 10\nWORD_SPAN = 4\nWORD_SUBIDX = 2\nEND_SUBIDX = 3\n\n\ndef parse_hypseg(text):\n \"\"\"Parse hypseg alignments file and return alignements\n\n Args:\n text(str): hypseg text\n\n Returns:\n dict: a dictionary of all start and end points for each word in text\n \"\"\"\n results = {\"words\": []}\n tokens = text.strip().split()\n # results[\"basename\"] = tokens[BASENAME_IDX]\n start = float(tokens[START_TIME_IDX]) * 0.01\n i = WORDS_IDX\n while i < len(tokens):\n word = tokens[i + WORD_SUBIDX]\n end = tokens[i + END_SUBIDX]\n end = float(end) * 0.01\n if word != \"\":\n results[\"words\"].append({\"id\": word, \"start\": start, \"end\": end})\n start = end\n i += WORD_SPAN\n return results\n\n\ndef make_smil(text_path: str, audio_path: str, results: dict) -> str:\n \"\"\"Actually render the SMIL\n\n Args:\n text_path(str): path to text\n audio_path(str): path to audio\n results(dict): all alignements\n\n Returns:\n str: formatted SMIL\n \"\"\"\n results[\"text_path\"] = text_path\n results[\"audio_path\"] = audio_path\n return chevron.render(SMIL_TEMPLATE, results)\n\n\ndef go(seg_path, text_path, audio_path, output_path):\n results = make_smil(text_path, audio_path, parse_hypseg(seg_path))\n save_txt(output_path, results)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Convert XML to another orthography while preserving tags\"\n )\n parser.add_argument(\"input_seg\", type=str, help=\"Input hypseg file\")\n parser.add_argument(\"text_path\", type=str, help=\"Text filename\")\n parser.add_argument(\"audio_path\", type=str, help=\"Audio filename\")\n parser.add_argument(\"output\", type=str, help=\"Output SMIL file\")\n args = parser.parse_args()\n go(args.input_seg, args.text_path, args.audio_path, args.output)\n","sub_path":"readalongs/text/make_smil.py","file_name":"make_smil.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"247953474","text":"import cv2 as cv\nimport numpy as np\n\ndefault_kernel\ndef sharp(image):\n kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)\n dst = cv.filter2D(image, -1, kernel=kernel)\n return dst\n\nif __name__ == \"__main__\":\n src = cv.imread(\"img\\\\test.png\")\n sharp(src)\n","sub_path":"application/sharp.py","file_name":"sharp.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"37932080","text":"#!/usr/bin/env python3\n#coding=utf-8\n#外資及陸資買賣超彙總表\n#Installed in Windows by shell\n#pip install requests\n#pip install pandas\n#pip --list\n#python --version\n\nfrom datetime import datetime, timedelta, date\nimport time\nimport pandas as pd\n#from io import StringIO #使用內存\nimport os\nimport random\nimport os.path\nimport json,csv\nimport requests\n\n#取得當前工作路徑加存檔路徑\nworkpath = os.path.split(os.path.realpath(__file__))[0] #windows path + \"子目錄\"\n#股票代碼 (2018/01/08 當日成交值前10檔股票)\n#stock_list=[2330,2303] #請任意新增股票代碼\n\ndef get_buy(date): \n try:\n user_agent=\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\"\n headers={\"User-Agent\":user_agent}\n url_twse='https://www.twse.com.tw/fund/TWT38U?response=jsonl&date=20190716'\n #url_twse='https://www.twse.com.tw/fund/TWT43U?response=jsonl&date=20190716'\n #url_twse='https://www.twse.com.tw/fund/TWT44U?response=jsonl&date=20190716'\n #r=requests.get(url_twse,) #最後一天OK\n r=requests.get(url_twse, headers=headers) #日期之外陸資買賣OK\n\n if len(r.text)<5000:\n print(date+' holiday')\n time.sleep(0.5)\n return None\n else:\n print(date) #normally\n except:\n print(date +' error')\n time.sleep(0.5)\n return None\n \n data = json.loads(r.text)\n\n #存檔路徑\n mydir=os.path.join(workpath)\n #filename='外陸資_'+str(year)+'_'+'{0:0=2d}'.format(month)+'.csv'\n filename = date\n if not os.path.isfile(os.path.join(mydir,filename)): #檢查檔案是否存在\n with open(filename,'w', newline='') as outfile:\n outfile=open(os.path.join(mydir,filename),'w',newline='')\n outputwriter=csv.writer(outfile)\n outputwriter.writerow(data['title'])\n outputwriter.writerow(data['fields'])\n for data in(data['data']):\n outputwriter.writerow(data)\n #outfile.close() \n print('sussess') \n else: \n print('已有相同檔名的檔案存在!!!')\n\n time.sleep(3 + random.uniform(1,3))\n\ndef daterange(start, end):\n for n in range(int ((end - start).days)+1):\n yield start + timedelta(n)\n\nyear = 2019\nmonth = 7\nstart_dt = date(2019, 7, 16)\nend_dt = date(year, month, 16)\nfor dt in daterange(start_dt, end_dt):\n #week =dt.weekday()\n #if week < 5: #星期一是0 ~6 故小於五等於weekday 星期一~日\n dt=dt.strftime('%Y%m%d.csv') #當地日期時間...格式\n if not os.path.isfile(dt): #如果檔案尚未被讀取\n get_buy(dt)\n else:\n print(dt+' had ')\n\n\n\n","sub_path":"Stock_TWT38U.py","file_name":"Stock_TWT38U.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"101238651","text":"# -*- coding:utf-8 -*-\nfrom django.shortcuts import render, redirect\nfrom forms import RegistrationForm, AddNote, AddFolderForm\nfrom django.contrib import auth\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom app.models import Note, Genre, Icon\nfrom django.contrib.auth.models import User\n\n\ndef index(request):\n mydict = dict()\n note_name = Note.objects.all()\n tree = Genre.objects.filter(name='root')\n users = User.objects.all()\n mydict['username'] = auth.get_user(request).username\n mydict['notes'] = note_name\n mydict['users'] = users\n mydict['tree'] = tree\n return render(request, 'app/boot_index.html', mydict)\n\n\ndef login(request):\n args = dict()\n args['form'] = AuthenticationForm()\n if request.POST:\n user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])\n if user is not None:\n auth.login(request, user)\n return redirect('/')\n else:\n args['login_error'] = \"Пользователь не найден\"\n return render(request, 'app/enter.html', args)\n else:\n return render(request, 'app/enter.html', args)\n\n\ndef logout(request):\n auth.logout(request)\n return redirect('/')\n\n\ndef registration(request):\n form = dict()\n form['form'] = RegistrationForm()\n if request.POST:\n newuser_form = RegistrationForm(request.POST)\n if newuser_form.is_valid():\n if newuser_form.save():\n new_user = auth.authenticate(username=request.POST['username'], password=request.POST['password1'])\n auth.login(request, new_user)\n\n return redirect('/')\n\n else:\n form['form'] = newuser_form\n return render(request, 'app/registration.html', form)\n\n\ndef addnote(request, pk):\n form = dict()\n form['form'] = AddNote()\n form['icons'] = Icon.objects.all()\n form['directory'] = Genre.objects.get(id=pk)\n note_name = Note.objects.all()\n form['notes'] = note_name\n form['username'] = auth.get_user(request).username\n form['parent'] = Genre.objects.get(id=pk)\n form['tree'] = Genre.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n form['tree_files'] = Note.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n if request.POST:\n new_add_note = Note()\n new_add_note.note_name = request.POST['note_name']\n new_add_note.note_text = request.POST['note_text']\n new_add_note.user = User.objects.get(username=auth.get_user(request).username)\n new_add_note.parent = Genre.objects.get(id=pk)\n if new_add_note.valid():\n new_add_note.save()\n for icon in request.POST.getlist('checkbox'):\n new_add_note.icon_name.add(Icon.objects.get(id=icon))\n form['saved'] = 'Сохранено в базе данных'\n else:\n form['saved'] = 'Название заметки обязательное поле'\n return render(request, 'app/boot_index.html', form)\n\n return render(request, 'app/add.html', form)\n\n\ndef shownote(request, pk, pk_f):\n form = dict()\n tree = Genre.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n tree_files = Note.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n parent = Genre.objects.get(id=pk)\n note = Note.objects.get(id=pk_f)\n\n return render(request, 'app/content_shownote.html', {'username': auth.get_user(request).username,\n 'tree': tree,\n 'tree_files': tree_files,\n 'parent': parent,\n 'note': note,\n })\n\n\ndef NextElemTree(request, pk):\n tree = Genre.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n tree_files = Note.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n parent = Genre.objects.get(id=pk)\n #print parent\n return render(request, 'app/boot_index.html', {'username': auth.get_user(request).username,\n 'tree': tree,\n 'tree_files': tree_files,\n 'parent': parent\n })\n\n\ndef AddFolder(request, pk):\n form = dict()\n form['form'] = AddFolderForm()\n form['note_name'] = Note.objects.all()\n form['directory'] = Genre.objects.get(id=pk)\n form['tree'] = Genre.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n form['username'] = auth.get_user(request).username\n form['parent'] = Genre.objects.get(id=pk)\n form['tree_files'] = Note.objects.filter(parent_id=pk, user_id=auth.get_user(request).id)\n if request.POST:\n new_folder = Genre()\n new_folder.name = request.POST['name']\n new_folder.user = User.objects.get(username=auth.get_user(request).username)\n new_folder.parent_id = pk\n new_folder.save()\n return render(request, 'app/boot_index.html', form)\n return render(request, 'app/addfolder.html', form)\n\n\ndef DeleteFolder(request, pk):\n elem = Genre.objects.get(id=pk)\n elem.delete()\n note_name = Note.objects.all()\n tree = Genre.objects.filter(name='root')\n mydict = dict()\n mydict['username'] = auth.get_user(request).username\n mydict['notes'] = note_name\n mydict['tree'] = tree\n return render(request, 'app/index.html', mydict)\n\n\ndef editnotes(request, pk):\n form = dict()\n form['note'] = Note.objects.get(id=pk)\n form['icons'] = Icon.objects.all()\n form['username'] = auth.get_user(request).username\n form['tree'] = Genre.objects.filter(parent_id=form['note'].parent_id, user_id=auth.get_user(request).id)\n form['tree_files'] = Note.objects.filter(parent_id=form['note'].parent_id, user_id=auth.get_user(request).id)\n form['parent'] = Genre.objects.get(id = form['note'].parent_id)\n if request.POST and (\"save_edit_note\" in request.POST):\n if request.POST['note_name'] != '':\n form['note'].delete()\n form['note'].note_name = request.POST['note_name']\n form['note'].note_text = request.POST['note_text']\n form['note'].save()\n for icon in request.POST.getlist('checkbox'):\n form['note'].icon_name.add(Icon.objects.get(id=icon))\n form['saved'] = 'Изменения сохранены'\n else:\n form['saved'] = 'Поле с именем обязательно для заполнения'\n return render(request, 'app/index.html', form)\n elif request.POST and (\"delete_note\" in request.POST):\n form['note'].delete()\n return render(request, 'app/index.html', form)\n return render(request, 'app/edit.html', form)\n\n\ndef saveicon(request):\n mydict = dict()\n\n note_name = Note.objects.all()\n tree = Genre.objects.filter(name='root')\n\n users = User.objects.all()\n\n mydict['username'] = auth.get_user(request).username\n mydict['notes'] = note_name\n mydict['users'] = users\n mydict['tree'] = tree\n\n return render(request, 'app/index.html', mydict)","sub_path":"proj/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"578039824","text":"'''\nRESPOSTAS DO PLEBOT\n'''\n # Saudações\nlistResponses = [[r'tarde|noite|dia|eae|olá|ola|oi', \"\\nSaudações nobre cliente\"],\n\n [r'comida|cardapio',\n \"\\nAqui está o nosso cardapio:\"\n \"\\n- Hambúrguer Rei Arthur . R$ 25.00\"\n \"\\n- Porção de batatas mágicas . R$ 10.00\"\n \"\\n- Esfirra secreta de frango . R$ 7.50\"],\n\n [r'hamburguer|hambúrguer|batata|esfirra', \"\\nBoa escolha forasteiro\"],\n\n [r'bebida',\n \"\\nAinda não temos nada, acabou o rum e só tem água\"],\n\n [r'bem|como vai', \"\\nVou ficar melhor se comprar alguma coisa\"],\n\n [r'caro', \"\\ntenho que pagar minhas contas\"],\n\n # Despedidas\n [r'até mais', \"\\nVolte sempre que quiser o melhor produto\"],\n [r'até a próxima', \"\\nAté a próxima, forasteiro...\"],\n [r'adeus', \"\\nQue os deuses lhe guiem!\"],\n [r'tchau', \"\\nVá pela sombra jovem!\"]]\n","sub_path":"interacoes.py","file_name":"interacoes.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"558982892","text":"import os\nfrom skimage import io\nfrom skimage.transform import resize\nfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Flatten, Activation, Dropout\nfrom keras.models import Model\nfrom keras.utils import to_categorical\nfrom keras import backend as K\nimport numpy as np\nfrom keras import optimizers\nimport pickle\nfrom matplotlib import pyplot as plt\nfrom keras.utils.vis_utils import plot_model\nimport random\nimport sys\nimport datetime\nfrom lxml import etree\n\n# parameters that you should set before running this script\nfilter = ['aeroplane', 'car', 'chair', 'dog', 'bird'] # select class, this default should yield 1489 training and 1470 validation images\nvoc_root_folder = \"D:/computervisiondatabase/VOCtrainval_11-May-2009/VOCdevkit/\" # please replace with the location on your laptop where you unpacked the tarball\nimage_size = 144 # image size that you will use for your network (input images will be resampled to this size), lower if you have troubles on your laptop (hint: use io.imshow to inspect the quality of the resampled images before feeding it into your network!)\n # image_size should be divisible by 8 for the best result\nif False:\n # step1 - build list of filtered filenames\n annotation_folder = os.path.join(voc_root_folder, \"VOC2009/Annotations/\")\n annotation_files = os.listdir(annotation_folder)\n filtered_filenames = []\n for a_f in annotation_files:\n tree = etree.parse(os.path.join(annotation_folder, a_f))\n if np.any([tag.text == filt for tag in tree.iterfind(\".//name\") for filt in filter]):\n filtered_filenames.append(a_f[:-4])\n \n # step2 - build (x,y) for TRAIN/VAL (classification)\n classes_folder = os.path.join(voc_root_folder, \"VOC2009/ImageSets/Main/\")\n classes_files = os.listdir(classes_folder)\n train_files = [os.path.join(classes_folder, c_f) for filt in filter for c_f in classes_files if filt in c_f and '_train.txt' in c_f]\n val_files = [os.path.join(classes_folder, c_f) for filt in filter for c_f in classes_files if filt in c_f and '_val.txt' in c_f]\n \n \n def build_classification_dataset(list_of_files):\n \"\"\" build training or validation set\n \n :param list_of_files: list of filenames to build trainset with\n :return: tuple with x np.ndarray of shape (n_images, image_size, image_size, 3) and y np.ndarray of shape (n_images, n_classes)\n \"\"\"\n temp = []\n train_labels = []\n for f_cf in list_of_files:\n with open(f_cf) as file:\n lines = file.read().splitlines()\n temp.append([line.split()[0] for line in lines if int(line.split()[-1]) == 1])\n label_id = [f_ind for f_ind, filt in enumerate(filter) if filt in f_cf][0]\n train_labels.append(len(temp[-1]) * [label_id])\n train_filter = [item for l in temp for item in l]\n \n image_folder = os.path.join(voc_root_folder, \"VOC2009/JPEGImages/\")\n image_filenames = [os.path.join(image_folder, file) for f in train_filter for file in os.listdir(image_folder) if\n f in file]\n x = np.array([resize(io.imread(img_f), (image_size, image_size, 3)) for img_f in image_filenames]).astype(\n 'float32')\n # changed y to an array of shape (num_examples, num_classes) with 0 if class is not present and 1 if class is present\n y_temp = []\n for tf in train_filter:\n y_temp.append([1 if tf in l else 0 for l in temp])\n y = np.array(y_temp)\n \n return x, y\n \n \n x_train, y_train = build_classification_dataset(train_files)\n print('%i training images from %i classes' %(x_train.shape[0], y_train.shape[1]))\n x_val, y_val = build_classification_dataset(val_files)\n print('%i validation images from %i classes' %(x_val.shape[0], y_train.shape[1]))\n \n# ^^^ Given code ^^^\n# -----------------------------------------------------------------------------\n# ⌄⌄⌄ Own code ⌄⌄⌄\n \n # Saving the objects:\n with open('x_train.txt', 'wb') as f:\n pickle.dump(x_train, f)\n with open('y_train.txt', 'wb') as f:\n pickle.dump(y_train, f)\n with open('x_val.txt', 'wb') as f:\n pickle.dump(x_val, f)\n with open('y_val.txt', 'wb') as f:\n pickle.dump(y_val, f)\nelse:\n # Getting back the objects:\n with open('x_train.txt', 'rb') as f:\n x_train = pickle.load(f)\n with open('y_train.txt', 'rb') as f:\n y_train = pickle.load(f)\n with open('x_val.txt', 'rb') as f:\n x_val = pickle.load(f)\n with open('y_val.txt', 'rb') as f:\n y_val = pickle.load(f)\n\n\n# =============================================================================\n# 1. Constructing the auto-encoder\n# - This auto-encoder model will take (image_size, image_size, 3) as input\n# and will output an image of the same size.\n# - The encoded layer has size (image_size/8,image_size/8,32) and will thus\n# reduce the imput by a factor 6.\n# =============================================================================\ninput_img = Input(shape=(image_size, image_size, 3))\n\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img) \nx = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = MaxPooling2D((2, 2), padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n\nencoded = MaxPooling2D((2, 2), padding='same')(x)\n\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x) #tegenovergestelde van MaxPooling2D\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\nx = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\nx = UpSampling2D((2, 2))(x)\ndecoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)\nautoencoder = Model(input_img, decoded)\nautoencoder.compile(optimizer='adam', loss='mse', metrics=['accuracy'])\n\n\n# =============================================================================\n# 2. Training the model\n# - When trainModel is TRUE, the model will learn how to encode pictures \n# by encoding and decoding the train images and try to learn a way that \n# minimizes the mean square error.\n# - The weights are stored in the data folder.\n# - The training metrics accuracy, loss, validation accuracy and validation\n# accuracy are plotted when the training is done.\n# - When loadModelFromDisk is TRUE, the model will load previously trained \n# weights and possibly train them further based on \n# the trainModel parameter.\n# - When the weights are loaded in a picture is encoded and decoded to see\n# the result.\n# =============================================================================\ntrainModel = False\nloadModelFromDisk = True\n\nif loadModelFromDisk:\n autoencoder.load_weights(\"data/weights.h5\")\nif trainModel:\n history = autoencoder.fit(x_train, x_train,\n epochs=2,\n batch_size=64,\n shuffle=True,\n validation_data=(x_val, x_val))\n \n tijd = datetime.datetime.now()\n tijdstring = tijd.strftime(\"%H:%M:%S\").replace(\":\", \"_\")\n autoencoder.save_weights(\"data/weights\"+tijdstring+\".h5\")\n \n print(history.history.keys())\n # summarize history for accuracy\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n # summarize history for loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\nif ((not trainModel) and (not loadModelFromDisk)):\n print('model is untrained, part runPart3_1 will be skipped')\n runPart3_1 = False\nelse:\n # show result of the model\n io.imshow(x_val[0])\n plt.show()\n testPicture = np.asarray([x_val[0].tolist()])\n uitkomst = autoencoder.predict(testPicture)[0]\n io.imshow(uitkomst)\n plt.show()\n\n# =============================================================================\n# CLASSIFICATION\n# - Part3_1 is a model that takes the encoder from the previous auto-encoder \n# and sticks 2 fully connected layers that will preform the task of classifier\n# - When runPart3_1 is True the model will be constructed and when\n# trainPart3_1 is True it will train the model from scratch, when it is\n# False, the weights are loaded in. NOTE: this model can only train\n# weights of the new layers. The encoder layers still have their \n# weights from the previous section.\n# - Part3_2 is the same model as 3_1 but now all the weights are trainable\n# - In both cases, training metrics will be printed, newly traind weights are\n# Stored to disk and the model is tested on 20 randomly selected validation\n# images. Those results will be printed in the console.\n# =============================================================================\nrunPart3_1 = True\ntrainPart3_1 = False\nrunPart3_2 = True\ntrainPart3_2 = False\n\ninput_dim = 10368 #18*18*32\noutput_dim = nb_classes = len(filter)\n\ny_train_parts = []\ny_val_parts = []\nfor i in range (0,nb_classes):\n helper = y_train[:,i].ravel()\n helper2 = helper.copy()\n helper = np.append(helper,helper2,axis=0)\n y_train_parts.append(helper)\n y_val_parts.append(y_val[:,i].ravel())\n\nx_trainMirror = x_train[...,::-1,:].copy()\nx_train = np.append(x_train,x_trainMirror, axis=0)\n\nif runPart3_1:\n \n for i in range(len(autoencoder.layers)):\n autoencoder.layers[i].trainable = False\n \n x = autoencoder.layers[12].output\n\n x = Flatten()(x)\n x = Dense(2048, input_dim = input_dim, activation='relu')(x)\n x = Dropout(0.5)(x)\n x = Dense(2048, input_dim = 2048, activation='relu')(x)\n x = Dropout(0.5)(x)\n \n output1 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output2 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output3 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output4 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output5 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n\n modelPredict = Model(autoencoder.inputs,[output1,output2,output3,output4,output5]) \n \n plot_model(modelPredict, to_file='model_plot_modelPredict.png', show_shapes=True, show_layer_names=True)\n modelPredict.summary()\n \n modelPredict.compile(optimizer = \"adam\", loss = [\"binary_crossentropy\",\"binary_crossentropy\",\"binary_crossentropy\",\"binary_crossentropy\",\"binary_crossentropy\"], metrics=[])\n \n \n if trainPart3_1:\n history = modelPredict.fit(x_train, y_train_parts,shuffle=True, batch_size=64, nb_epoch=30,verbose=1, validation_data=(x_val, y_val_parts))\n tijd = datetime.datetime.now()\n tijdstring = tijd.strftime(\"%H:%M:%S\").replace(\":\", \"_\")\n modelPredict.save_weights(\"data/weightsdeel31\"+tijdstring+\".h5\")\n \n print(history.history.keys())\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n else:\n modelPredict.load_weights(\"data/weightsdeel31.h5\")\n \n predictedValues = modelPredict.predict(x_val)\n \n predictedValues = np.asarray(predictedValues)\n predictedValues = np.transpose(predictedValues)\n predictedValuesBU = np.copy(predictedValues)\n \n # accuracy test\n highestClassification = np.apply_along_axis(np.argmax,1,predictedValues[0])\n \n predictedRight = 0\n for i,row in enumerate(y_val):\n if row[highestClassification[i]] == 1:\n predictedRight += 1\n accuracy = predictedRight/len(y_val)\n print(\"accuracy is: \" + str(accuracy))\n \n for _ in range (0,20):\n i = random.randint(0, len(y_val))\n io.imshow(x_val[i])\n \n text = \"\"\n for j,classe in enumerate(filter):\n text = text + classe + \": \" + str(round(predictedValuesBU[0,i,j],2)) + \"\\n\"\n for k,l in enumerate(y_val[i]):\n if l == 1:\n text = text + \" \" + filter[k] + \"\\n\"\n \n plt.xlabel(text)\n plt.show()\n \n#-------------------------\n#SECOND MODEL\n#-------------------------\nif runPart3_2:\n \n input_img = Input(shape=(image_size, image_size, 3))\n x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img) \n x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n encoded = MaxPooling2D((2, 2), padding='same')(x)\n \n x = Flatten()(encoded)\n x = Dense(2048, input_dim = input_dim, activation='relu')(x)\n x = Dropout(0.5)(x)\n x = Dense(2048, input_dim = 2048, activation='relu')(x)\n x = Dropout(0.5)(x)\n \n output1 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output2 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output3 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output4 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n output5 = Dense(1, input_dim = 2048, activation = 'sigmoid')(x)\n\n modelPredict = Model(input_img,[output1,output2,output3,output4,output5]) \n modelPredict.summary()\n modelPredict.compile(optimizer = \"adam\", loss = [\"binary_crossentropy\",\"binary_crossentropy\",\"binary_crossentropy\",\"binary_crossentropy\",\"binary_crossentropy\"], metrics=[])\n\n\n if trainPart3_2:\n history = modelPredict.fit(x_train, y_train_parts, batch_size=64,shuffle=True, nb_epoch=6,verbose=1, validation_data=(x_val, y_val_parts))\n \n print(history.history.keys())\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n \n tijd = datetime.datetime.now()\n tijdstring = tijd.strftime(\"%H:%M:%S\").replace(\":\", \"_\")\n modelPredict.save_weights(\"data/weightsdeel32\"+tijdstring+\".h5\")\n else:\n modelPredict.load_weights(\"data/weightsdeel32.h5\")\n \n predictedValues = modelPredict.predict(x_val)\n predictedValues = np.asarray(predictedValues)\n predictedValues = np.transpose(predictedValues)\n predictedValuesBU = np.copy(predictedValues)\n \n # accuracy test\n highestClassification = np.apply_along_axis(np.argmax,1,predictedValues[0])\n \n predictedRight = 0\n for i,row in enumerate(y_val):\n if row[highestClassification[i]] == 1:\n predictedRight += 1\n accuracy = predictedRight/len(y_val)\n print(\"accuracy is: \" + str(accuracy))\n \n for _ in range (0,20):\n i = random.randint(0, len(y_val))\n io.imshow(x_val[i])\n \n text = \"\"\n for j,classe in enumerate(filter):\n text = text + classe + \": \" + str(round(predictedValuesBU[0,i,j],2)) + \"\\n\"\n for k,l in enumerate(y_val[i]):\n if l == 1:\n text = text + \" \" + filter[k] + \"\\n\"\n \n plt.xlabel(text)\n plt.show()\n\n\n","sub_path":"hand_in/Encode_classify.py","file_name":"Encode_classify.py","file_ext":"py","file_size_in_byte":16653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"219295416","text":"#!/usr/bin/python3\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser(description='Checks for symbols not affected by fgkaslr.\\nYou need two different dumps of /proc/kallsyms for this to work.', formatter_class=argparse.RawTextHelpFormatter)\nparser.add_argument('file1', help='file containing first dump', type=str)\nparser.add_argument('file2', help='file containing second dump', type=str)\nargs = parser.parse_args()\n\ndef file_len(fname):\n with open(fname, 'r') as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\nif file_len(args.file1) != file_len(args.file2):\n print(\"Error, the two files do not contain the same amount of symbols!\")\n sys.exit(1)\n\nf1 = open(args.file1, 'r')\nf2 = open(args.file2, 'r')\nlines1 = f1.readlines()\nlines2 = f2.readlines()\nf1.close()\nf2.close()\n\ndef compute(lines):\n ret = {}\n docomp = False\n for line in lines:\n line = line.strip()\n if \"secondary_startup_64\" in line:\n base = int('0x' + line.split()[0], 16)-0x30\n docomp = True\n if docomp:\n try:\n delta = int('0x' + line.split()[0], 16) - base\n ret.update({line.split()[1] + ' ' + line.split()[2]: delta})\n except:\n break\n return ret\n\ndef compare(dic1, dic2):\n final = {}\n for i in dic1:\n if dic1[i] == dic2[i]:\n bak = i\n if i.split()[0].lower() == 't':\n i = 'TEXT ' + i.split()[1]\n elif i.split()[0].lower() == 'r':\n i = 'RONLY ' + i.split()[1]\n elif i.split()[0].lower() == 'd':\n i = 'DATA ' + i.split()[1]\n else:\n i = 'OTHER ' + i.split()[1]\n final.update({i: dic1[bak]})\n return final\n\nsyms1 = compute(lines1)\nsyms2 = compute(lines2)\nnochange = compare(syms1, syms2)\n\nf = open('no_fgkaslr.txt', 'w')\nfor i in nochange:\n f.write(hex(nochange[i]) + ' ' + i + '\\n')\nf.close()\n\nprint('Complete! Result stored in no_fgkaslr.txt as {offset} {symbol name}')\n","sub_path":"check_fgkaslr.py","file_name":"check_fgkaslr.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"545088323","text":"\n\nfrom xai.brain.wordbase.nouns._adjunct import _ADJUNCT\n\n#calss header\nclass _ADJUNCTS(_ADJUNCT, ):\n\tdef __init__(self,): \n\t\t_ADJUNCT.__init__(self)\n\t\tself.name = \"ADJUNCTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"adjunct\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_adjuncts.py","file_name":"_adjuncts.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"34657382","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\nhhids = [59,93,94,101,114,171,187,26,77,86]\n#scenarios=[\"sb4b64\",\"sb4b135\",\"sb8b64\",\"sb8b135\",\"sb10b64\",\"sb10b135\",\"sb20b64\",\"sb20b135\"]\nscenarios=[\"sb4b64\",\"sb4b135\",\"sb8b64\",\"sb8b135\",\"sb10b64\",\"sb10b135\",\"sb20b135\"]\n#hhid = 114\n#scenario = \"sb8b135\"\nalgos = [\"OPTIMAL\", \"MPC\", \"RBC\", \"DLC\", \"SAC\", \"A2C\", \"TD3\", \"DDPG\"]\n\n\n\nfor hhid in hhids:\n for sc in scenarios:\n fig, ax = plt.subplots()\n #print(str(hhid)+\": \"+sc)\n for algo in algos:\n table = pd.read_csv(\"../\" + algo + \"/result_\" + str(hhid) + \"/\" + sc + \".csv\")\n if algo==\"OPTIMAL\":\n ax.plot(range(8616), (table[\"Best_Bill\"][0:8616]+0.00*np.array(range(8616))), label=algo)\n elif algo==\"MPC\":\n ax.plot(range(8616), (table[\"Best_Bill\"][0:8616]-0.00*np.array(range(8616))), label=algo)\n else:\n ax.plot(range(8616), (table[\"Best_Bill\"][0:8616]), label=algo)\n ax.set_title(str(hhid)+\": \"+sc)\n ax.set_ylabel('Cumulative electricity bill ($)',fontsize='15')\n ax.legend(loc=2, borderaxespad=0., bbox_to_anchor=(.00, 1.00), fontsize = '15')\n plt.yticks(fontsize='15')\n plt.xticks(np.arange(0, 8616, 714), ('Jan', 'Feb', 'Mar', 'Apr', 'May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),rotation=45,fontsize = '15')\n plt.show()\n\n\"\"\"\n#compile\nfor j in scenarios:\n print(\"In scenarios\",j)\n csvfile = open('bill_curve/{}.csv'.format(j),'w', newline='')\n writer = csv.writer(csvfile, delimiter=',')\n writer.writerow([\"Home\",\"no_solar\",\"no_battery\",\"baseline\",\"RL\",\"MILP\",\"MPC\",\"optimal\"])\n for i in hhids:\n #no solar no battery\n #table = pd.read_csv('nopv_4/{}_2_nopv/{}.csv'.format(i,j))\n if j[2]=='4':\n table = pd.read_csv('nopv_4/{}_4_nopv/sb4b0.csv'.format(i))\n if j[2]=='8':\n table = pd.read_csv('nopv_4/{}_4_nopv/sb8b0.csv'.format(i))\n if j[2]=='1':\n table = pd.read_csv('nopv_4/{}_4_nopv/sb10b0.csv'.format(i))\n if j[2]=='2':\n table = pd.read_csv('nopv_4/{}_4_nopv/sb20b0.csv'.format(i))\n nos = table['Base_Bill'].iloc[8735]-table['Base_Bill'].iloc[167]\n nos_curve = table['Base_Bill'][168:8736]-table['Base_Bill'].iloc[167]\n print(\"no solar bill: \",nos)\n\n #solar no battery\n if j[2]=='4':\n table = pd.read_csv('nostorage_2/{}_2_nostorage/sb4b0.csv'.format(i))\n if j[2]=='8':\n table = pd.read_csv('nostorage_2/{}_2_nostorage/sb8b0.csv'.format(i))\n if j[2]=='1':\n table = pd.read_csv('nostorage_2/{}_2_nostorage/sb10b0.csv'.format(i))\n if j[2]=='2':\n table = pd.read_csv('nostorage_2/{}_2_nostorage/sb20b0.csv'.format(i))\n nob = table['Base_Bill'].iloc[8735]-table['Base_Bill'].iloc[167]\n nob_curve = table['Base_Bill'][168:8736]-table['Base_Bill'].iloc[167]\n print(\"no battery bill: \",nob)\n\n\n #Baseline bill\n table = pd.read_csv('rbc_2/{}_2_rbc/{}.csv'.format(i,j))\n bab = table['Base_Bill'].iloc[8735]-table['Base_Bill'].iloc[167]\n bab_curve = table['Base_Bill'][168:8736]-table['Base_Bill'].iloc[167]\n print(\"Baseline bill: \",bab)\n\n #RL bill\n table = pd.read_csv('rl_2_bill/{}_2_pre2_bill/{}.csv'.format(i,j))\n beb = table['Bill'].iloc[-1]\n beb_curve = table['Bill'][0:8568]\n print(\"RL bill: \",beb)\n\n # #MILP\n # table = pd.read_csv('{}_2_sc_bill/{}.csv'.format(i,j))\n # sc = table['Bill'].iloc[-1]\n # sc_curve = table['Bill'][0:8568]\n # print(\"MILP bill: \",sc)\n\n #MPC\n table = pd.read_csv('mpc_2_bill/{}_2_mpc_bill/{}.csv'.format(i,j))\n mpc = table['Bill'].iloc[-1]\n mpc_curve = table['Bill'][0:8568]\n print(\"mpc bill: \",mpc)\n\n table = pd.read_csv('olc_2_bill/{}_2_olc_bill/{}.csv'.format(i,j))\n olc = table['Bill'].iloc[-1]\n olc_curve = table['Bill'][0:8568]\n hour = table['Step'][0:8568]\n print(\"olc bill: \",olc)\n\n\n #optimal bill\n nj=j[0:2]+'-'+j[2:]\n table = pd.read_csv('op_2/{}_2_op/{}.csv'.format(i,nj))\n opt2 = table['total_reward'].iloc[8735]-table['total_reward'].iloc[167]\n\n\n table = pd.read_csv('op_2_bill/{}_2_op_bill/{}.csv'.format(i,j))\n opt = table['Bill'].iloc[-1]\n opt_curve = table['Bill'][0:8568]\n print(\"opt bill2\",opt2)\n print(\"opt bill: \",opt)\n # print(\"optimal bill: \",opt)\n print(\"\\n\")\n #writer.writerow([i,nos,nob,bab,beb,sc,mpc,opt])\n csvfile.close()\n fig, ax = plt.subplots()\n #plt.tight_layout()\n #ax.plot(hour, nos_curve, label=\"No Solar\")\n #ax.plot(hour, nob_curve, label=\"No Battery\")\n ax.plot(hour, bab_curve, label=\"RBC\")\n ax.plot(hour, beb_curve, label=\"RL\")\n #ax.plot(hour, sc_curve, label=\"MILP\")\n ax.plot(hour, olc_curve, label=\"DLC\")\n ax.plot(hour, mpc_curve, label=\"MPC\")\n ax.plot(hour, opt_curve, label=\"Optimal\")\n #ax.set_title(\"Policies, Home Load and PV Output\")\n ax.set_ylabel('Cumulative electricity bill ($)',fontsize='15')\n ax.legend(loc=2, borderaxespad=0., bbox_to_anchor=(.00, 1.00), fontsize = '15')\n if j[2]=='4':\n plt.ylim(0,900)\n if j[2]=='8':\n plt.ylim(0,800)\n if j[2]=='1':\n plt.ylim(0,650)\n if j[2]=='2':\n plt.ylim(-200,400)\n #plt.ylim\n plt.yticks(fontsize='15')\n plt.xticks(np.arange(0,8568,714), ('Jan', 'Feb', 'Mar', 'Apr', 'May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),rotation=45,fontsize = '15')\n plt.savefig('bill_curve/{}_{}_billadded.png'.format(i,j),bbox_inches = \"tight\")\n #plt.show()\n\"\"\"\n# #plot\n# for j in scenarios:\n# d = pd.read_csv('bill/{}.csv'.format(j))\n# no_solar = d['no_solar']\n# #no_battery = d['no_battery']\n# baseline = d['baseline']\n# legend = ['no solar','Baseline', 'SolarReinforce','Optimal']\n# RL = d['RL']\n# optimal = d['optimal']\n# #plt.hist([baseline, RL, optimal], color=['orange', 'green','red'])\n# plt.hist([no_solar, baseline, RL, optimal], color=['navy','orange', 'green','red'])\n# plt.xlabel(\"Bills\")\n# plt.ylabel(\"Frequency\")\n# #plt.axvline(no_solar.mean(), color='sienna', linestyle='dashed', linewidth=1)\n# plt.axvline(no_solar.mean(), color='navy', linestyle='dashed', linewidth=1)\n# plt.axvline(baseline.mean(), color='orange', linestyle='dashed', linewidth=1)\n# plt.axvline(RL.mean(), color='green', linestyle='dashed', linewidth=1)\n# plt.axvline(optimal.mean(), color='red', linestyle='dashed', linewidth=1)\n# plt.legend(legend)\n# #plt.xticks(range(0,7))\n# #plt.yticks(range(1, 20))\n# plt.title('Bills for year 2016\\n Scenario: {}'.format(j))\n# #plt.show()\n# plt.savefig('bill/2016_{}_all.png'.format(j))\n# plt.show()\n","sub_path":"NewBoost/plot/cumi_bull.py","file_name":"cumi_bull.py","file_ext":"py","file_size_in_byte":6883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"81469753","text":"import pandas as pd\n\ndf_wine = pd.read_csv(\"wine.data\", header = None)\nprint(df_wine.shape)\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nX,y = df_wine.iloc[:, 1:].values, df_wine.loc[:,0].values\n\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)\n\nsc = StandardScaler()\nX_train_std = sc.fit_transform(X_train)\nX_test_std = sc.transform(X_test)\n\nimport numpy as np\n\ncov_mat = np.cov(X_train_std.T)\neigen_vals, eigen_vecs = np.linalg.eig(cov_mat)\nprint(\"Eigenvalues:\", eigen_vals)\n\n\ntot = sum(eigen_vals)\nvar_exp = [(i/tot) for i in sorted(eigen_vals, reverse = True)] #variance explained ratio => the fraction of an eigenvalue and the total sum of eigenvalues\n\ncum_var_exp = np.cumsum(var_exp)\n\nimport matplotlib.pyplot as plt\n\nplt.bar(range(1,14), var_exp, alpha = 0.5, align = \"center\", label = \"individual explained variance\")\n\nplt.step(range(1,14), cum_var_exp, where = \"mid\", label = \"cumulative explained variance\")\nplt.ylabel(\"Explained variance ratio\")\nplt.xlabel(\"Principal components\")\nplt.legend(loc=\"best\")\nplt.show()\n\n#now generate eigen pairs, get projection matrix, and transform data into the lower-dimentional subspace\n\neigen_pairs =[ (np.abs(eigen_vals[i]), eigen_vecs[:,i]) for i in range(len(eigen_vals))]\neigen_pairs.sort(reverse = True)\n\nw = np.hstack( (eigen_pairs[0][1][:,np.newaxis], eigen_pairs[1][1][:,np.newaxis] ) )\n\nprint(\"matrix w: \",w)\n\nX_train_compressed = X_train_std[0].dot(w)\nprint(\"original:\", X_train_std[0])\nprint(\"compressed:\",X_train_compressed)\n\n#similarly, we can trasform the entire 124*13 training dataset\nX_train_pca = X_train_std.dot(w)\nprint(X_train_pca.shape)\n\n#now visualize the compressed data in a 2D scatterplot\ncolors = ['r', 'b', 'g']\nmarkers = ['s', 'x', 'o']\nfor l,c,m in zip(np.unique(y_train), colors, markers):\n plt.scatter(X_train_pca[y_train == l, 0], X_train_pca[y_train == l, 1], c=c, label=l, marker = m)\n\nplt.xlabel(\"PC 1\")\nplt.ylabel(\"PC 2\")\nplt.legend(loc = \"lower left\")\nplt.show()\n\n\n\n","sub_path":"Chap5/PCAIntro.py","file_name":"PCAIntro.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"237746731","text":"\nimport FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Multileptonanalyse\")\n\n\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.threshold = ''\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\n\n\nprocess.load(\"Configuration.Geometry.GeometryIdeal_cff\")\n#process.load(\"Configuration.StandardSequences.Geometry_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\n#Give the global tag -- can be found from config file on DBS\n#process.GlobalTag.globaltag =cms.string('FT_R_53_V6::All')\nprocess.GlobalTag.globaltag =cms.string('START53_V7A::All') #MC \n#process.GlobalTag.globaltag =cms.string('START52_V11B::All') #MC\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\n\n\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nprocess.source = cms.Source(\"PoolSource\",\n noEventSort = cms.untracked.bool(True),\n duplicateCheckMode = cms.untracked.string('noDuplicateCheck'),\n fileNames = cms.untracked.vstring(\n\n # '/store/user/ghellwig/NMSSM_sqgo_8TeV_mH1_65_mH2_125p3_MSUSY_1000/NMSSM_sqgo_8TeV_mH1_65_mH2_125p3_MSUSY_1000/7f49fdb7ce01732f191af9409dedeb7c/PYTHIA6_SUSY_sqgo_8TeV_mH1_65_mH2_125p3_MSUSY_1000_cff_py_GEN_SIM_DIGI_L1_DIGI2RAW_HLT_RAW2DIGI_L1Reco_RECO_PU_575_2_PpY.root'\n # '/store/results/higgs/DoubleMu/StoreResults-DoubleMu_Run2012A_13Jul2012_v1_embedded_trans1_tau123_pttau1_18tau2_8_v1-f456bdbb960236e5c696adfe9b04eaae/DoubleMu/USER/StoreResults-DoubleMu_Run2012A_13Jul2012_v1_embedded_trans1_tau123_pttau1_18tau2_8_v1-f456bdbb960236e5c696adfe9b04eaae/0000/0020A5CA-EF0F-E211-AF12-0023AEFDEBBC.root'\n#'/store/data/Run2012A/DoubleMu/AOD/13Jul2012-v1/00000/DA9DAE8F-B4CF-E111-AC5C-002618943980.root'\n 'file:/afs/naf.desy.de/user/t/troendle/public/CMSSW_5_3_7_patch5/src/Madgraph_Prod/test.root'\n\n \n )\n)\n\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string(\"tmp.root\") )\n\n\n### Some recomende Filterst here ##############\n#### https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookCollisionsDataAnalysis#Recipes_to_get_started\nprocess.noscraping = cms.EDFilter(\"FilterOutScraping\",\n applyfilter = cms.untracked.bool(True),\n #debugOn = cms.untracked.bool(True),\n numtrack = cms.untracked.uint32(10),\n thresh = cms.untracked.double(0.25)\n )\n\n\nprocess.primaryVertexFilter = cms.EDFilter(\"GoodVertexFilter\",\n vertexCollection = cms.InputTag('offlinePrimaryVertices'),\n minimumNDOF = cms.uint32(4) ,\n maxAbsZ = cms.double(15), \n maxd0 = cms.double(2) \n )\n\n\n\nprocess.load('CommonTools/RecoAlgos/HBHENoiseFilter_cfi')\n#### HBHENoiseFilter\n\n###additional filters....\n## The iso-based HBHE noise filter ___________________________________________||\n##process.load('CommonTools.RecoAlgos.HBHENoiseFilter_cfi')\n\n## The CSC beam halo tight filter ____________________________________________||\nprocess.load('RecoMET.METAnalyzers.CSCHaloFilter_cfi')\n\n## The HCAL laser filter _____________________________________________________||\nprocess.load(\"RecoMET.METFilters.hcalLaserEventFilter_cfi\")\nprocess.hcalLaserEventFilter.vetoByRunEventNumber=cms.untracked.bool(False)\nprocess.hcalLaserEventFilter.vetoByHBHEOccupancy=cms.untracked.bool(True)\n\n## The ECAL dead cell trigger primitive filter _______________________________||\nprocess.load('RecoMET.METFilters.EcalDeadCellTriggerPrimitiveFilter_cfi')\n## For AOD and RECO recommendation to use recovered rechits\nprocess.EcalDeadCellTriggerPrimitiveFilter.tpDigiCollection = cms.InputTag(\"ecalTPSkimNA\")\n\n## The EE bad SuperCrystal filter ____________________________________________||\nprocess.load('RecoMET.METFilters.eeBadScFilter_cfi')\n\n## The Good vertices collection needed by the tracking failure filter ________||\nprocess.goodVertices = cms.EDFilter(\n \"VertexSelector\",\n #filter = cms.bool(False),\n filter = cms.bool(True),\n src = cms.InputTag(\"offlinePrimaryVertices\"),\n cut = cms.string(\"!isFake && ndof >= 4 && abs(z) <= 24 && position.rho < 2\")\n)\n\n## The tracking failure filter _______________________________________________||\nprocess.load('RecoMET.METFilters.trackingFailureFilter_cfi')\nprocess.trackingFailureFilter.TrackSource = cms.InputTag('tmfTracks')\n\n\n\n\n\n\n\n\nprocess.goodVertices = cms.EDFilter(\n \"VertexSelector\",\n #filter = cms.bool(False),\n filter = cms.bool(True),\n src = cms.InputTag(\"offlinePrimaryVertices\"),\n #cut = cms.string(\"\")\n cut = cms.string(\"!isFake && ndof >= 4 && abs(z) <= 24 && position.Rho < 2\")\n)\n\n#### HBHENoiseFilter\n## process.HBHENoiseFilter = cms.EDFilter(\n## 'HBHENoiseFilter',\n## noiselabel = cms.InputTag('hcalnoise'),\n## minRatio = cms.double(-999.0),\n## maxRatio = cms.double(999.0),\n## minHPDHits = cms.int32(17),\n## minRBXHits = cms.int32(999),\n## minHPDNoOtherHits = cms.int32(10),\n## minZeros = cms.int32(10),\n## minHighEHitTime = cms.double(-9999.0),\n## maxHighEHitTime = cms.double(9999.0),\n## maxRBXEMF = cms.double(-999.0),\n## minNumIsolatedNoiseChannels = cms.int32(10),\n## minIsolatedNoiseSumE = cms.double(50.0),\n## minIsolatedNoiseSumEt = cms.double(25.0),\n## useTS4TS5 = cms.bool(True)\n## )\n\n\n########## Rho25 for photons ##### not more needed \n#process.load('RecoJets.Configuration.RecoPFJets_cff')\n#process.kt6PFJets25 = process.kt6PFJets.clone( doRhoFastjet = True )\n#process.kt6PFJets25.Rho_EtaMax = cms.double(2.5)\n\n\nprocess.load(\"RecoJets.JetProducers.kt4PFJets_cfi\")\nprocess.kt6PFJets25 = process.kt4PFJets.clone( rParam = 0.6, doRhoFastjet = True )\nprocess.kt6PFJets25.Rho_EtaMax = cms.double(2.5)\n\n\n\n\n\n### My Skim Classes ####\nprocess.load(\"MDSM.MDSM_Ana.mdsm_ana_cfi\")\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_pfseq_cfi\")\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_vertex_cfi\")\n#process.mdsm_vertex.vertex_collection=\"offlinePrimaryVertices\"\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_muons_cfi\")\n\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_electrons_cfi\")\n\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_photons_cfi\")\n\n\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_taus_cfi\")\nprocess.mdsm_taus.pf_tau_collection=\"hpsPFTauProducer\"\nprocess.mdsm_taus.tau_min_pt=10\nprocess.mdsm_taus.tau_discrimintator_cuts = cms.untracked.vstring(\n 'hpsPFTauDiscriminationByDecayModeFinding',\n # 'hpsPFTauDiscriminationByLooseMuonRejection',\n # 'hpsPFTauDiscriminationByLooseElectronRejection',\n # 'hpsPFTauDiscriminationByVLooseIsolation',\n # 'hpsPFTauDiscriminationByDecayModeFinding',\n # 'hpsPFTauDiscriminationByTightCombinedIsolationDBSumPtCorr',\n # 'hpsPFTauDiscriminationByTightMuonRejection',\n # 'hpsPFTauDiscriminationByTightElectronRejection',\n # 'hpsPFTauDiscriminationByTightIsolation'\n # 'hpsPFTauDiscriminationByVLooseIsolation'\n )\n\n\n\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_jets_cfi\")\nprocess.mdsm_jets_raw.jet_collection=\"patJets\"\nprocess.patJetCorrFactors.levels=cms.vstring('L1FastJet','L2Relative', 'L3Absolute')\n\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_met_cfi\")\n#process.pfJetMETcorr.jetCorrLabel = cms.string(\"ak5PFL1FastL2L3Residual\") #DATA\nprocess.pfJetMETcorr.jetCorrLabel = cms.string(\"ak5PFL1FastL2L3\")#MC\n\n\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_mc_cfi\")\nprocess.mdsm_mc.is_embedded_sample=True\n\n\nprocess.load('CommonTools/RecoAlgos/HBHENoiseFilter_cfi')\n\n#process.load('RecoMET.METAnalyzers.CSCHaloFilter_cfi')\n#process.load(\"RecoMET.METFilters.hcalLaserEventFilter_cfi\")\n\n\n\n\n#process.load('RecoMET.METFilters.trackingFailureFilter_cfi')\n\n#process.p = cms.Path(\n# process.goodVertices*process.trackingFailureFilter\n#)\n\n\nprocess.load(\"MDSM.MDSM_Ana.mdsm_trigger_cfi\")\nprocess.mdsm_trigger.trigger_collection=\"HLT\"\nprocess.mdsm_trigger.trigger_collection=\"TriggerResults\"\n\n#process.mdsm_trigger.select_triggers=cms.untracked.vstring('HLTriggerFinalPath','HLT_Mu')\n#process.mdsm_trigger.veto_triggers=cms.untracked.vstring('HLT_Mu17')\n#process.mdsm_trigger.print_trigger_info=cms.untracked.bool(True)\n\n\n\nfrom RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex\nprocess.jetTracksAssociatorAtVertexalt=ak5JetTracksAssociatorAtVertex.clone()\nprocess.jetTracksAssociatorAtVertexalt.jets='ak5PFJets'\nfrom PhysicsTools.PatAlgos.tools.jetTools import *\n(process.btestalt,labels) =runBTagging(process, cms.InputTag('ak5PFJets'),\"AOD\",\"alt\")\n#for embedded sample\n#process.jetTracksAssociatorAtVertexalt.tracks = cms.InputTag(\"tmfTracks\")\n\n\nprocess.p = cms.Path(process.noscraping * ### some filters\n process.primaryVertexFilter * ## some filters\n #process.HBHENoiseFilter * \n\t\t #process.CSCTightHaloFilter *\n #process.hcalLaserEventFilter *\n #process.EcalDeadCellTriggerPrimitiveFilter *\n #process.goodVertices * \n #process.trackingFailureFilter *\n #process.eeBadScFilter *\n\n\n \n process.kt6PFJets25* ## produce rho25 for photons \n process.jetTracksAssociatorAtVertexalt*\n process.btestalt*\n \n \n process.mdsm_pfseq*\n process.mdsm_vertex*\n process.mdsm_muons*\n process.mdsm_electrons*\n process.mdsm_photons*\n process.mdsm_taus*\n process.mdsm_jets*\n process.mdsm_met*\n process.mdsm_mc*\n\t\t process.mdsm_trigger*\t\n process.mdsm_ana) ## Has to be at the end\n","sub_path":"MDSM_Ana/test/mdsm_ana_mc_cfg.py","file_name":"mdsm_ana_mc_cfg.py","file_ext":"py","file_size_in_byte":10211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"91877838","text":"# -序列化\nimport pickle\n\nd = dict(name='Bob', age=20, score=88)\n\n# 1. pickle.dumps()方法将任意对象序列化成一个bytes\npickle.dumps(d)\n\nwith open('../../introduction_dir/se.txt', 'wb') as f:\n # 2. pickle.dump()将对象序列化后写入一个文件中\n pickle.dump(d, f) # 序列化\n\nwith open('../../introduction_dir/se.txt', 'rb') as f:\n # 3. pickle.load()方法从一个file-like Object中直接反序列化出对象\n print(pickle.load(f)) # 反序列化\n\n# -json\n## 1. json和python内置的数据类型对应\n# {} dict\n# [] list\n# \"string\" str\n# 1234.56 int或float\n# true/false True/False\n# null None\nimport json\n\nj = json.dumps(d)\nprint(j) # 序列化为json,返回一个str,内容就是标准的json\n\ns = json.loads(j)\nprint(s) # 反序列化json\n\n\n# -json进阶:序列化对象\nclass User(object):\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n\n# 增加转换函数\ndef user2dict(s):\n return {'name': s.name, 'age': s.age}\n\n\n# user实例先被转换成dict,再被序列化为json\nu = User('zhangsan', 17)\nj = json.dumps(u, default=user2dict)\nprint(j)\n\n# 如上可简写\nj = json.dumps(u, default=lambda obj: obj.__dict__)\nprint(j)\n\n\n# json的对象反序列化\ndef dict2user(d):\n return User(d['name'], d['age'])\n\n\nu = json.loads(j, object_hook=dict2user)\nprint(u.name)\n","sub_path":"py_pure/src/catface/introduction/09_io/4_serialization.py","file_name":"4_serialization.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250339585","text":"# pip install google_speech\n\nfrom google_speech import Speech\nimport PyPDF2\n\n# ABRIR O ARQUIVO PDF\nbook = open(\"oop.pdf\", \"rb\")\npdfReader = PyPDF2.PdfFileReader(book)\n# pages = pdfReader.numPages\n# print(pages)\n\n# OBTER O TEXTO\npage = pdfReader.getPage(7)\ntext = page.extractText().encode(\"utf-8\").decode(\"utf-8\")\ntext = text.replace('\\n', '')\nprint(text)\n\n# LER O TEXTO\nlang = \"en_us\"\nspeech = Speech(text, lang)\n# speech.play()\n\n# GRAVAR ARQUIVO\nspeech.save(\"saidaOOP.mp3\")","sub_path":"LeituraGoogle.py","file_name":"LeituraGoogle.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"71793677","text":"import numpy as np\nfrom hmmlearn import hmm\n#import librosa\n\n# def getMFCC(episode):\n# filename = getPathToGroundtruth(episode)\n# y, sr = librosa.load(filename) # Y gives \n# data = librosa.feature.mfcc(y=y, sr=sr)\n# return data\n\n# Needs to provide a numpy array\n# In example, this is a [20 X 56829]\ndef getFeatures(filename):\n data = np.loadtxt(filename)\n return data\n\ndef hmm_init(n,data): #n = states d = no of feautures\n states =[]\n N=n\n model = hmm.GaussianHMM(n_components=N, covariance_type=\"full\")\n model.transmat_ = np.ones((N, N)) / N\n model.startprob_ = np.ones(N) / N\n fit = model.fit(data.T)\n z=fit.decode(data.T,algorithm='viterbi')[1]\n states.append(z)\n return states\n\ndef main():\n# data_m = getMFCC(1) # Provides MFCC features of numpy array [20 X 56829]\n data= getFeatures('features.mat')\n N = 500\n D= len(data) # What is D used for? \n states = hmm_init(N,data)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/hmm.py","file_name":"hmm.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"117680062","text":"import json\n\n\nclass SmartJson(object):\n def __init__(self, json_obj):\n if isinstance(json_obj, str):\n self.json_obj = json.loads(json_obj)\n else:\n self.json_obj = json_obj\n\n def getValueFromPath(self, path):\n try:\n if path is '.':\n return self.json_obj\n splitted_path = path.split('.')\n except ValueError as e:\n raise e\n\n return self.__getValueByPath(splitted_path, self.json_obj)\n\n def append(self, path, value):\n json_value = self.getValueFromPath(path)\n\n if self.__isRoot(json_value):\n if isinstance(json_value, dict):\n json_value.update(value)\n\n elif self.__isValue(value):\n if self.__isListOfPrimitives(json_value):\n json_value.append(value)\n if self.__isValue(json_value):\n self.__setValue(path, [json_value, value])\n\n elif isinstance(value, dict):\n if self.__isListOfObjects(json_value):\n json_value.append(value)\n if isinstance(json_value, dict):\n if self.__isExist(json_value, value):\n self.__setValue(path, [json_value, value])\n else:\n json_value.update(value)\n\n return self\n\n def modify(self, path, value):\n if self.getValueFromPath(path):\n self.__setValue(path, value)\n return self\n else:\n raise ValueError(\"Key not found\")\n\n def remove(self, path):\n self.__setValue(path, None)\n return self\n\n def __isExist(self, json_obj, value):\n if isinstance(value, dict) and isinstance(json_obj, dict):\n return True if self.__getOneLevelDeeper(list(value.keys())[0], json_obj) else False\n return False\n\n\n\n def __setValue(self, path, value):\n if path.count('.') >= 1:\n cuttedPath = path.rsplit('.', 1)\n obj = self.getValueFromPath(cuttedPath[0])\n if value is None:\n del obj[cuttedPath[1]]\n else:\n obj[cuttedPath[1]] = value\n else:\n if value is None:\n del self.json_obj[path]\n else:\n self.json_obj[path] = value\n\n def __getValueByPath(self, path, json_obj):\n if len(path) == 0:\n return json_obj\n e = path[0]\n json_obj = self.__getOneLevelDeeper(e, json_obj)\n path.remove(e)\n return self.__getValueByPath(path, json_obj)\n\n def __getOneLevelDeeper(self, input_key, json_obj):\n if isinstance(json_obj, dict):\n for key, value in json_obj.items():\n if key == input_key:\n return value\n elif isinstance(json_obj, list):\n if self.__isListOfObjects(json_obj):\n self.__isThereMoreKeyWithSameName(input_key, json_obj)\n return self.__getOneLevelDeeper(input_key, json_obj[0])\n else:\n return json_obj\n\n def __isRoot(self, input_json):\n return True if input_json is self.json_obj else False\n\n def __isListOfObjects(self, inputList):\n if isinstance(inputList, list) and len(inputList) > 0:\n return True if isinstance(inputList[0], dict) else False\n\n def __isListOfPrimitives(self, input_list):\n if isinstance(input_list, list) and len(input_list) > 0:\n return True if self.__isValue(input_list[0]) else False\n\n def __isValue(self, value):\n return True if isinstance(value, (int, str, float, complex)) else False\n\n def __isThereMoreKeyWithSameName(self, key, json_obj):\n if self.__isListOfObjects(json_obj):\n count = 0\n for e in json_obj:\n for keys in e.keys():\n if keys == key:\n count += 1\n if count >= 2:\n raise ValueError(\"More object with same key!\")\n","sub_path":"smartJson.py","file_name":"smartJson.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"85624901","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nclass Kalman:\n def __init__(self, dt=0.0019):\n self.measnoise = 0.1\n self.accelnoise = 0.1\n self.x = np.matrix([[0], [0]])\n self.xhat = self.x.copy()\n self.Sz = 0.0001#self.measnoise ** 2\n self.Sw = self.accelnoise ** 2 * np.matrix([[dt ** 4 / 4, dt ** 3 / 2], [dt ** 3 / 2, dt ** 2]])\n self.P = self.Sw\n self.c = np.matrix([1, 0])\n\n self.pos = []\n self.poshat = []\n self.posmeas = []\n self.vel = []\n self.velhat = []\n self.t = [0]\n \n def update(self, u, dt, noise=False):\n self.t.append(self.t[-1] + dt)\n\n print(dt)\n a = np.matrix([[1, dt], [0, 1]])\n b = np.matrix([[dt ** 2 / 2], [dt]])\n self.Sw = self.accelnoise ** 2 * np.matrix([[dt ** 4 / 4, dt ** 3 / 2], [dt ** 3 / 2, dt ** 2]])\n\n if noise:\n self.ProcessNoise = self.accelnoise * np.matrix([\n [(dt ** 2 / 2) * np.random.randn()],\n [dt * np.random.randn()]\n ])\n self.MeasNoise = self.measnoise * np.random.randn()\n else:\n self.ProcessNoise = 0\n self.MeasNoise = 0\n\n self.x = a * self.x + b * u + self.ProcessNoise\n\n y = self.c * self.x + self.MeasNoise\n self.xhat = a * self.xhat + b * u\n Inn = y - self.c * self.xhat\n s = self.c * self.P * np.transpose(self.c) + self.Sz\n K = a * self.P * np.transpose(self.c) * np.linalg.inv(s)\n self.xhat = self.xhat + K * Inn\n self.P = a * self.P * np.transpose(a) - a * self.P * np.transpose(self.c) * \\\n np.linalg.inv(s) * self.c * self.P * np.transpose(a) + self.Sw\n self.pos.append(self.x[0, 0])\n self.posmeas.append(y[0, 0])\n self.poshat.append(self.xhat[0, 0])\n self.vel.append(self.x[1, 0])\n self.velhat.append(self.xhat[1, 0])\n \n def plot_results(self):\n \n plt.figure(figsize=(15,10))\n plt.subplot(2, 2, 1)\n plt.plot(self.t[1:], self.pos, label='position')\n plt.plot(self.t[1:], self.posmeas, label='measured position')\n plt.plot(self.t[1:], self.poshat, label='estimated position')\n plt.xlabel('Time (sec)')\n plt.ylabel('Position (feet)')\n plt.title('Figure 1 - Vehicle Position (True, Measured, and Estimated)')\n plt.legend()\n\n plt.subplot(2, 2, 2)\n plt.plot(self.t[1:], [x - y for x, y in zip(self.pos, self.posmeas)], label='measured error')\n plt.plot(self.t[1:], [x - y for x, y in zip(self.pos, self.poshat)], label='estimated error')\n plt.xlabel('Time (sec)')\n plt.ylabel('Position Error (feet)')\n plt.title('Figure 2 - Position Measurement Error and Position Estimation Error')\n plt.legend()\n\n plt.subplot(2, 2, 3)\n plt.plot(self.t[1:], self.vel, label='real velocity')\n plt.plot(self.t[1:], self.velhat, label='estimated velocity')\n plt.xlabel('Time (sec)')\n plt.ylabel('Velocity (feet/sec)')\n plt.title('Figure 3 - Velocity (True and Estimated)')\n plt.legend()\n\n plt.subplot(2, 2, 4)\n plt.plot(self.t[1:], [x - y for x, y in zip(self.vel, self.velhat)])\n plt.xlabel('Time (sec)')\n plt.ylabel('Velocity Error (feet/sec)')\n plt.title('Figure 4 - Velocity Estimation Error')\n print(f'MSE: {np.mean([(x - y) ** 2 for x, y in zip(self.pos, self.poshat)])}')\n\n\n\nif __name__ == \"__main__\":\n kalman = Kalman()\n for i in range(600):\n kalman.update(1, 0.1)\n\n kalman.plot_results()\n","sub_path":"kalman.py","file_name":"kalman.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"339534841","text":"import os\nimport matplotlib.pyplot as plt\n\nlog_dir = \"C:/GamesTech/3rd-year/CCTP/EMG-interpreter/EMG-Interpreter/logs/\"\n\n# line colour lookup\nlookup = {\n 0: 'r-',\n 1: 'g-',\n 2: 'b-',\n 3: 'm-',\n 4: 'c-',\n 5: 'y-',\n}\n\ndef draw(filename, subdir) :\n print(\"Processing...\")\n data = []\n output_size = 0\n with open(log_dir + subdir + filename) as f :\n fseq = f.readlines()\n for sid in range(len(fseq)) :\n data.append([])\n \n log_entries = fseq[sid].split()\n output_size = int(log_entries.pop(0))\n for j in range(2 * output_size) :\n data[sid].append([])\n \n \n for j in range(int(len(log_entries) / (2 * output_size))) :\n for k in range(2 * output_size) :\n data[sid][k].append(float(log_entries[j * 2 * output_size + k]))\n\n\n #sid = input()\n legend_names = []\n for i in range(output_size) :\n legend_names.append(\"Output\" + str(i + 1))\n legend_names.append(\"Target\" + str(i + 1))\n\n for sid in range(len(data)) :\n #print(\"drawing \", sid)\n length = len(data[sid][0]) * 2\n if (length < 1300) :\n length = 1300\n if (length > 4000) :\n length = 4000\n plt.figure(figsize = (length / 96, 800 / 96), dpi = 96)\n plt.tight_layout()\n plt.axis([0, len(data[sid][0]) - 1, 0, 1.01])\n for i in range(output_size) :\n plt.plot(data[sid][2 * i], lookup[i])\n plt.plot(data[sid][2 * i + 1], lookup[i] + '-')\n plt.legend(legend_names)\n plt.ylabel(\"Activation\")\n plt.xlabel(\"Timestep\")\n #plt.savefig(\"sequence_log_graphs/\" + filename + \"_\" + str(sid) + \".png\", bbox_inches = 'tight')\n plt.savefig(\"sequence_log_graphs/\" + subdir + filename + \".png\", bbox_inches = 'tight')\n plt.close()\n\n\n#local_dir = \"train_seqs/\"\n#f_list = os.listdir(log_dir + local_dir)\n#for f in f_list :\n# draw(f, local_dir)\nlocal_dir = \"test_seqs/\"\nf_list = os.listdir(log_dir + local_dir)\nfor f in f_list :\n draw(f, local_dir)\n\n\nprint(\"Complete\")\n\n\n\n #plt.plot(data[sid][0], 'r-')\n #plt.plot(data[sid][1], 'g-')\n #plt.plot(data[sid][2], 'b-')\n #plt.plot(data[sid][3], 'm-')\n #plt.plot(data[sid][4], 'c-')\n #plt.plot(data[sid][5], 'r--')\n #plt.plot(data[sid][6], 'g--')\n #plt.plot(data[sid][7], 'b--')\n #plt.plot(data[sid][8], 'm--')\n #plt.plot(data[sid][9], 'c--')\n #plt.legend([\"Thumb\", \"Index\", \"Middle\", \"Ring\", \"Little\", \"Thumb Target\", \"Index Target\", \"Middle Target\", \"Ring Target\", \"Little Target\"])","sub_path":"Py/draw_seq_log.py","file_name":"draw_seq_log.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"543408423","text":"import frappe\nfrom frappe.utils.data import nowdate\nfrom toolz import reduceby\n\nfrom ashbee.utils.date import year_diff\nfrom . import DAYS_PER_YEAR\n\n\ndef calculate_gross_gratuity():\n \"\"\"\n Calculate gratuity / indemnity on Employee\n :return:\n \"\"\"\n\n employees = frappe.db.sql(\"\"\"\n SELECT name, employee_name, date_of_joining, nationality, ashbee_gratuity_paid_till_date\n FROM `tabEmployee`\n WHERE status = 'Active'\n \"\"\", as_dict=1)\n\n filtered_employees = list(filter(lambda x: x['nationality'] != 'Bahraini', employees))\n salaries = _get_salaries()\n\n now = nowdate()\n\n for employee in filtered_employees:\n name = employee.get('name')\n date_of_joining = employee.get('date_of_joining')\n working_years, last_working_year_days = year_diff(now, date_of_joining)\n\n salary = salaries.get(name, 0.00)\n total_gratuity = sum([\n _get_gross_gratuity(working_years, salary),\n _get_per_day_gratuity(working_years, last_working_year_days, salary),\n -employee.get('ashbee_gratuity_paid_till_date', 0)\n ])\n\n frappe.db.set_value('Employee', name, 'ashbee_gratuity_till_date', total_gratuity)\n\n\ndef _get_salaries():\n gratuity_base_on = frappe.db.get_single_value('Ashbee Settings', 'gratuity_base_on')\n\n salary_columns = ['base']\n if gratuity_base_on == 'Gross':\n salary_columns.append('variable')\n\n salary_select = \" + \".join(salary_columns)\n\n salaries = frappe.db.sql(\"\"\"\n SELECT\n {} AS salary,\n employee\n FROM `tabSalary Structure Assignment`\n WHERE docstatus = 1\n \"\"\".format(salary_select), as_dict=1)\n\n return {salary['employee']: salary['salary'] for salary in salaries}\n\n\ndef _get_gross_gratuity(working_years, gross_salary):\n \"\"\"\n Calculates yearly gratuity and summed gratuity\n :param working_years:\n :param gross_salary:\n :return:\n \"\"\"\n gratuities = []\n for nth_year in range(1, working_years + 1):\n gratuity_days = 30.0 if nth_year > 3 else 15.0\n gratuity = _calculate_gratuity(1, DAYS_PER_YEAR, gratuity_days, gross_salary)\n gratuities.append(gratuity)\n\n return sum(gratuities)\n\n\ndef _get_per_day_gratuity(working_years, last_working_days, gross_salary):\n \"\"\"\n Calculates gratuity for the year\n :param working_years:\n :param gross_salary:\n :return:\n \"\"\"\n last_working_year = last_working_days / DAYS_PER_YEAR\n\n if working_years > 3:\n gratuity = gross_salary * last_working_year\n else:\n gratuity = (gross_salary / 2) * last_working_year\n\n return gratuity\n\n\ndef _calculate_gratuity(no_of_years, days_per_year, gratuity_days, gross_salary):\n \"\"\"\n Indemnity calculation\n Source: https://github.com/hafeesk/Hr/blob/master/hr_bahrain/hr_bahrain/hr_controllers.py\n\n :param no_of_years:\n :param days_per_year:\n :param gratuity_days:\n :param gross_salary:\n :return:\n \"\"\"\n total_no_of_months = no_of_years * 12\n # total_no_of_months = 168\n\n total_no_of_days_gratuity = no_of_years * days_per_year\n # total_no_of_days_gratuity = 4936\n\n total_no_of_days_for_gratuity = no_of_years * gratuity_days\n # total_no_of_days_for_gratuity =====> 11 years = 330, 3 years = 45 ===> 375\n\n days_per_month_gratuity = total_no_of_days_for_gratuity / total_no_of_months\n # days_per_month_gratuity = 2.2321425\n\n gratuity_per_working_day = days_per_month_gratuity / 30\n # gratuity_per_working_day = 0.07440475\n\n gratuity_for_total_working_days = gratuity_per_working_day * total_no_of_days_gratuity\n # gratuity_for_total_working_days = 367.261846\n\n basic_salary = gross_salary * 12\n # basic_salary = 5400\n\n per_day_basic_salary = basic_salary / 365\n # per_day_basic_salary = 14.79\n\n amount_of_gratuity = (per_day_basic_salary * gratuity_for_total_working_days) or 0\n # amount_of_gratuity = 5431.8027\n return amount_of_gratuity\n","sub_path":"ashbee/scheduler_events/employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"27760146","text":"\"\"\" Encoder-decoder \"\"\"\nimport torch.nn as nn\n\nfrom . import TorchModel\nfrom .layers import ConvBlock, Upsample, Crop, Combine\nfrom .utils import get_shape\nfrom ..utils import unpack_args\n\n\nclass EncoderDecoder(TorchModel):\n \"\"\" Encoder-decoder architecture. Allows to combine features of different models,\n e.g. ResNet, in order to create new ones with just a few lines of code.\n\n Parameters\n ----------\n inputs : dict\n Dictionary with 'images' (see :meth:`~.TorchModel._make_inputs`)\n\n body : dict\n encoder : dict\n base : TorchModel, optional\n Model implementing ``make_encoder`` method which returns tensors\n with encoded representation of the inputs.\n\n num_stages : int\n Number of downsampling stages.\n\n downsample : dict\n Parameters for downsampling (see :func:`~.layers.conv_block`)\n\n blocks : dict\n Parameters for pre-processing blocks:\n\n base : callable, optional\n Tensor processing function. Default is :func:`~.layers.ConvBlock`.\n other args : dict\n Parameters for the base block.\n\n other args : dict\n Parameters for ``make_encoder`` method.\n\n embedding : dict or sequence of dicts\n base : callable, optional\n Tensor processing function. Default is :func:`~.layers.ConvBlock`.\n other args\n Parameters for the base block.\n\n decoder : dict\n num_stages : int\n Number of upsampling blocks.\n\n factor : int or list of int\n If int, the total upsampling factor for all stages combined.\n If list, upsampling factors for each stage.\n\n skip : bool\n Whether to concatenate upsampled tensor with stored pre-downsample encoding.\n upsample : dict\n Parameters for upsampling (see :func:`~.layers.Upsample`).\n\n blocks : dict\n Parameters for post-processing blocks:\n\n base : callable\n Tensor processing function. Default is :func:`~.layers.ConvBlock`.\n other args : dict\n Parameters for the base block.\n\n Examples\n --------\n Preprocess input image with 7x7 convolutions, downsample it 4 times with ResNet blocks in between,\n use convolution block in the bottleneck, then restore original image size with subpixel convolutions and\n ResNeXt blocks in between:\n\n >>> config = {\n 'inputs/images/shape': B('image_shape'),\n 'inputs/masks/shape': B('mask_shape'),\n 'initial_block': {'inputs': 'images',\n 'layout': 'cna', 'filters': 4, 'kernel_size': 7},\n 'body/encoder': {'num_stages': 4,\n 'blocks': {'base': ResNet.block,\n 'resnext': False,\n 'filters': [8, 16, 32, 64]}},\n 'body/embedding': {'filters': 128},\n 'body/decoder': {'upsample': {'layout': 'X'},\n 'blocks': {'base': ResNet.block,\n 'filters': [128, 64, 32, 16],\n 'resnext': True}},\n }\n \"\"\"\n @classmethod\n def default_config(cls):\n config = TorchModel.default_config()\n config['common/conv/padding'] = 'same'\n config['body/encoder'] = dict(base=None, num_stages=None)\n config['body/encoder/downsample'] = dict(layout='p', pool_size=2, pool_strides=2)\n config['body/encoder/blocks'] = dict(base=cls.block)\n\n config['body/embedding'] = dict(base=cls.block)\n\n config['body/decoder'] = dict(skip=True, num_stages=None, factor=None)\n config['body/decoder/upsample'] = dict(layout='tna')\n config['body/decoder/blocks'] = dict(base=cls.block, combine_op='concat')\n config['head'] += dict(layout='c', kernel_size=1)\n return config\n\n def build_config(self, names=None):\n config = super().build_config(names)\n\n if config.get('head/units') is None:\n config['head/units'] = self.num_classes('targets')\n if config.get('head/filters') is None:\n config['head/filters'] = self.num_classes('targets')\n return config\n\n @classmethod\n def body(cls, inputs, **kwargs):\n \"\"\" Create encoder, embedding and decoder.\n\n Returns\n -------\n nn.Module\n \"\"\"\n kwargs = cls.get_defaults('body', kwargs)\n encoder = kwargs.pop('encoder')\n embeddings = kwargs.get('embedding')\n decoder = kwargs.pop('decoder')\n\n # Encoder: transition down\n encoder_args = {**kwargs, **encoder}\n encoders = cls.encoder(inputs, **encoder_args)\n x = encoders[-1]\n\n # Bottleneck: working with compressed representation via multiple steps of processing\n embeddings = embeddings if isinstance(embeddings, (tuple, list)) else [embeddings]\n\n for embedding in embeddings:\n embedding_args = {**kwargs, **embedding}\n x = cls.embedding(x, **embedding_args)\n encoders.append(x)\n\n # Decoder: transition up\n decoder_args = {**kwargs, **decoder}\n decoders = cls.decoder(encoders, **decoder_args)\n return EncoderDecoderBody(encoders, decoders, skip=decoder_args.get('skip'))\n\n @classmethod\n def head(cls, inputs, filters, **kwargs):\n \"\"\" Linear convolutions. \"\"\"\n kwargs = cls.get_defaults('head', kwargs)\n x = super().head(inputs=inputs, filters=filters, **kwargs)\n\n if get_shape(x)[1] != filters:\n args = {**kwargs, **dict(layout='c', filters=filters, kernel_size=1)}\n x = ConvBlock(inputs, **args)\n return x\n\n @classmethod\n def block(cls, inputs, **kwargs):\n \"\"\" Default conv block for processing tensors. Makes 3x3 convolutions followed by batch-norm and activation.\n Does not change tensor shapes.\n \"\"\"\n layout = kwargs.pop('layout', None) or 'cna'\n filters = kwargs.pop('filters', None) or get_shape(inputs)[1]\n return ConvBlock(inputs, layout=layout, filters=filters, **kwargs)\n\n\n @classmethod\n def encoder(cls, inputs, base_class=None, **kwargs):\n \"\"\" Create encoder either by using ``make_encoder`` of passed `base` model,\n or by combining building blocks, specified in `blocks/base`.\n\n Parameters\n ----------\n inputs\n Input tensor.\n\n base : TorchModel\n Model class. Should implement ``make_encoder`` method.\n\n name : str\n Scope name.\n\n num_stages : int\n Number of downsampling stages.\n\n blocks : dict\n Parameters for tensor processing before downsampling.\n\n downsample : dict\n Parameters for downsampling.\n\n kwargs : dict\n Parameters for ``make_encoder`` method.\n\n Returns\n -------\n list of nn.Modules\n \"\"\"\n base_class = kwargs.pop('base')\n steps, downsample, block_args = cls.pop(['num_stages', 'downsample', 'blocks'], kwargs)\n\n if base_class is not None:\n encoder_outputs = base_class.make_encoder(inputs, **kwargs)\n else:\n x = inputs\n encoder_outputs = [x]\n\n for i in range(steps):\n d_args = {**kwargs, **downsample, **unpack_args(downsample, i, steps)}\n d_args['filters'] = d_args.get('filters') or get_shape(x)[1]\n b_args = {**kwargs, **block_args, **unpack_args(block_args, i, steps)}\n x = EncoderBlock(x, d_args, b_args, **kwargs)\n encoder_outputs.append(x)\n return encoder_outputs\n\n @classmethod\n def embedding(cls, inputs, **kwargs):\n \"\"\" Create embedding from inputs tensor.\n\n Parameters\n ----------\n inputs\n Input tensor.\n\n name : str\n Scope name.\n\n base : callable\n Tensor processing function. Default is :func:`~.layers.ConvBlock`.\n\n kwargs : dict\n Parameters for `base` block.\n\n Returns\n -------\n torch.nn.Module\n \"\"\"\n base_block = kwargs.get('base', cls.block)\n return base_block(inputs, **kwargs)\n\n @classmethod\n def decoder(cls, inputs, **kwargs):\n \"\"\" Create decoder with a given number of upsampling stages.\n\n Parameters\n ----------\n inputs\n Input tensor.\n\n name : str\n Scope name.\n\n steps : int\n Number of upsampling stages. Defaults to the number of downsamplings.\n\n factor : int or list of ints\n If int, the total upsampling factor for all stages combined.\n If list, upsampling factors for each stage.s, then each entry is increase of size on i-th upsampling stage.\n\n skip : bool\n Whether to concatenate upsampled tensor with stored pre-downsample encoding.\n\n upsample : dict\n Parameters for upsampling.\n\n blocks : dict\n Parameters for post-processing blocks.\n\n kwargs : dict\n Parameters for :func:`~.layers.Upsample` method.\n\n Returns\n -------\n torch.nn.Module\n\n Raises\n ------\n TypeError\n If passed `factor` is not integer or list.\n \"\"\"\n steps = kwargs.pop('num_stages') or len(inputs)-2\n factor = kwargs.pop('factor') or [2]*steps\n skip, upsample, block_args = cls.pop(['skip', 'upsample', 'blocks'], kwargs)\n\n if isinstance(factor, int):\n factor = int(factor ** (1/steps))\n factor = [factor] * steps\n elif not isinstance(factor, list):\n raise TypeError('factor should be int or list of int, but %s was given' % type(factor))\n\n x = inputs[-1]\n decoders = []\n for i in range(steps):\n if factor[i] == 1:\n continue\n # Make upsample/block args, as well as prepare the skip connection if needed\n u_args = {**kwargs, **upsample, **unpack_args(upsample, i, steps)}\n u_args['filters'] = u_args.get('filters') or get_shape(x)[1]\n u_args['factor'] = u_args.get('factor') or factor[i]\n b_args = {**kwargs, **block_args, **unpack_args(block_args, i, steps)}\n skip_ = inputs[-i-3] if (skip and (i < len(inputs)-2)) else None\n\n x = DecoderBlock(x, skip_, u_args, b_args, **kwargs)\n decoders.append(x)\n return decoders\n\n\n\nclass EncoderDecoderBody(nn.Module):\n \"\"\" A sequence of encoder and decoder blocks with optional skip connections \"\"\"\n def __init__(self, encoders, decoders, skip=True):\n super().__init__()\n self.encoders = nn.ModuleList(encoders)\n self.decoders = nn.ModuleList(decoders)\n self.skip = skip\n self.output_shape = self.decoders[-1].output_shape\n\n def forward(self, x):\n skips = [x]\n for encoder in self.encoders[1:]:\n x = encoder(x)\n skips.append(x)\n\n for i, decoder in enumerate(self.decoders):\n skip = skips[-i-3] if (self.skip and (i < len(skips)-2)) else None\n x = decoder(x, skip=skip)\n return x\n\n\nclass EncoderBlock(nn.Module):\n \"\"\" Pass tensor through complex block, then downsample. \"\"\"\n def __init__(self, inputs, d_args, b_args, **kwargs):\n _ = kwargs\n super().__init__()\n\n # Preprocess tensor with given block\n base_block = b_args.get('base')\n self.encoder = base_block(inputs, **b_args)\n\n # Downsampling\n if d_args.get('layout'):\n self.downsample = ConvBlock(get_shape(self.encoder), **d_args)\n else:\n self.downsample = self.encoder\n self.output_shape = self.downsample.output_shape\n\n def forward(self, x):\n x = self.encoder(x)\n x = self.downsample(x)\n return x\n\n\nclass DecoderBlock(nn.Module):\n \"\"\" Upsample tensor, then pass it through complex block and combine with skip if needed. \"\"\"\n def __init__(self, inputs, skip, u_args, b_args, **kwargs):\n _ = kwargs\n super().__init__()\n\n # Upsample by a desired factor\n if u_args.get('layout'):\n self.upsample = Upsample(inputs=inputs, **u_args)\n else:\n self.upsample = inputs\n\n # Process tensor with block\n base_block = b_args.get('base')\n self.decoder = base_block(get_shape(self.upsample), **b_args)\n\n # Output shape: take skip into account\n shape = get_shape(self.decoder)\n if skip is not None:\n self.crop = Crop(shape, skip)\n self.combine = Combine([skip, get_shape(self.crop)], b_args.get('combine_op'))\n shape = self.combine.output_shape\n self.output_shape = shape\n\n def forward(self, x, skip):\n x = self.upsample(x)\n x = self.decoder(x)\n\n if skip is not None:\n x = self.crop(x, skip)\n x = self.combine([skip, x])\n return x\n","sub_path":"batchflow/models/torch/encoder_decoder.py","file_name":"encoder_decoder.py","file_ext":"py","file_size_in_byte":13249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"40767865","text":"#coding:utf-8\r\nfrom __future__ import print_function\r\n__author__ = 'Nick'\r\n\r\n\r\nfrom PIL import Image\r\n\r\nimg=Image.open(r'D:\\Temp\\file.jpg')\r\nprint(img.format,img.size,img.mode)\r\nimg.show()\r\nbox = (100, 100, 400, 400)\r\nregion = img.crop(box)\r\nregion.show()\r\n# the region is exactly 300x300 pixels.\r\nregion = region.transpose(Image.ROTATE_180)\r\nimg.paste(region, box)\r\nimg.show()\r\n\r\n\r\n\r\n\r\n\r\n'''\r\nsys.argv\r\nThe list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not).\r\nIf the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'.\r\nIf no script name was passed to the Python interpreter, argv[0] is the empty string.\r\n\r\nTo loop over the standard input, or the list of files given on the command line, see the fileinput module.\r\n\r\n\r\n\r\n\r\n\r\n\r\nos.path.splitext(path)\r\nSplit the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period.\r\n分离文件名与扩展名,默认返回(name,extension)元组\r\n\r\n'''\r\nimport os,sys\r\nroot,ext=os.path.splitext(r'C:\\programe\\text\\love.bmp')\r\nprint(root,ext)\r\n\r\n\r\n\r\nprint(sys.argv[1:])","sub_path":"Exercises/one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"153085513","text":"#!/usr/bin/env python\n# encoding: utf-8\nfrom django.conf import settings\nfrom .utils import logger, cache\n\n\ndef seo_processor(requests):\n key = 'seo_processor'\n value = cache.get(key)\n if value:\n logger.info('get processor cache.')\n return value\n else:\n\n logger.info('set processor cache.')\n value = {\n 'SITE_URL' : settings.SITE_URL,\n 'SITE_NAME': settings.SITE_NAME,\n 'SITE_KEYWORDS': settings.SITE_SEO_KEYWORDS,\n 'SITE_BASE_URL': requests.scheme + '://' + requests.get_host() + '/',\n\n }\n cache.set(key, value, 60 * 60 * 10)\n return value\n","sub_path":"accounts/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"576592732","text":"from PIL import Image\nfrom torchvision import models\nimport numpy as np\nimport torch\n\nfrom misc_functions import get_example_params, save_class_activation_images\n\n\nclass CamExtractor():\n \"\"\"\n Extracts cam features from the model\n \"\"\"\n def __init__(self, model, target_layer):\n self.model = model\n self.target_layer = target_layer\n self.gradients = None\n\n def forward_pass(self, x):\n x = self.model.conv1(x)\n x = self.model.bn1(x)\n x = self.model.relu(x)\n x = self.model.maxpool(x)\n\n x = self.model.layer1(x)\n x = self.model.layer2(x)\n x = self.model.layer3(x)\n x = self.model.layer4(x)\n\n # only support target_layer == layer4\n conv_output = x # Save the convolution output on that layer\n\n x = self.model.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.model.fc(x)\n\n return conv_output, x\n\n def get_weights(self, index):\n return self.model.fc.weight.data[index, :]\n\n\nclass Cam():\n \"\"\"\n Produces class activation map\n \"\"\"\n def __init__(self, model, target_layer):\n self.model = model\n self.model.eval()\n # Define extractor\n self.extractor = CamExtractor(self.model, target_layer)\n\n def generate_cam(self, input_image, target_class=None):\n # Full forward pass\n # conv_output is the output of convolutions at specified layer\n # model_output is the final output of the model (1, 1000)\n conv_output, model_output = self.extractor.forward_pass(input_image)\n if target_class is None:\n target_class = np.argmax(model_output.data.numpy())\n weight_softmax = self.extractor.get_weights(target_class)\n weight_softmax = weight_softmax.data.numpy() # C\n conv_output = conv_output.data.squeeze(0).numpy() # C*H*W\n c, h, w = conv_output.shape\n cam = weight_softmax.dot(conv_output.reshape(c, h*w)) # (C)x(C*HW) -> HW\n cam = cam.reshape(h, w)\n cam = cam - np.min(cam)\n cam = cam / np.max(cam)\n cam = np.uint8(255 * cam)\n cam = np.uint8(Image.fromarray(cam).resize((input_image.shape[2],\n input_image.shape[3]), Image.ANTIALIAS))#/255\n return cam\n\n\nif __name__ == '__main__':\n # cat_dog\n target_example = 1\n (original_image, prep_img, target_class, file_name_to_export, pretrained_model) =\\\n get_example_params(target_example, 'resnet50')\n cam = Cam(pretrained_model, target_layer='layer4')\n # Generate cam mask\n mask = cam.generate_cam(prep_img, target_class)\n # Save mask\n save_class_activation_images(original_image, mask, file_name_to_export)\n print('Cam completed')\n","sub_path":"src/cam_resnet.py","file_name":"cam_resnet.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"564410526","text":"import sys \nimport json \n\nregions = json.load(open(sys.argv[1],\"r\"))\nprefix = sys.argv[2]\n\nresult = []\n\nfor region in regions:\n\ts = prefix + \"/region_%d_%d/\" % (region[0], region[1])\n\n\tresult.append(s)\n\njson.dump(result,open(\"tmp.json\",\"w\"), indent=2)","sub_path":"pre_alpha_clean_version/lightpole_preprocess_convert.py","file_name":"lightpole_preprocess_convert.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"247723132","text":"import sys\nsys.path.insert(0, '../blocksim')\nimport time\nimport csv\nfrom pathlib import Path\nfrom json import dumps as dump_json\nfrom blocksim.world import SimulationWorld\nfrom blocksim.node_factory import NodeFactory\nfrom blocksim.transaction_factory import TransactionFactory\nfrom blocksim.models.network import Network\n\ndef write_report(world, report_directory):\n # with open(report_directory + 'report.json', 'w') as f:\n # f.write(dump_json(world.env.data))\n with open(report_directory + '/propagation-time.csv', 'w') as f:\n f.write('connection, count, sum, average\\n')\n for connection in world.env.data['block_propagation']:\n propagation_values = world.env.data['block_propagation'][connection]\n if len(propagation_values) > 0:\n sum = 0\n for i in propagation_values:\n sum = + propagation_values[i]\n avg = sum / len(propagation_values)\n f.write(connection + ', ' + str(len(propagation_values)) + ', ' + str(sum) + ', ' + str(avg) + '\\n')\n # f.write(dump_json(world.env.data['block_propagation']))\n\n with open(report_directory + 'verification-time.csv', 'w') as f:\n f.write(dump_json(world.env.data['block_verification']))\n\n vf_node = {}\n with open(report_directory + '_block-verification-time.csv', 'w') as f:\n # f.write(str(world.report_verification_time()))\n writer = csv.writer(f)\n for block_vf in world.report_verification_time():\n split = block_vf.split(':')\n writer.writerow([split[1]])\n if split[0] in vf_node:\n value = vf_node[split[0]]\n split_value = value.split(',')\n split_value[0] = str(int(split_value[0]) + 1)\n split_value[1] = str(float(split[1]) + float(split_value[1]))\n split_value[2] = str(float(split_value[1]) / float(split_value[0]))\n vf_node[split[0]] = split_value[0] + ', ' + split_value[1] + ', ' + split_value[2]\n else:\n vf_node[split[0]] = '1, ' + split[1] + ', ' + split[1]\n with open(report_directory + '/node-verification-time-average.csv', 'w') as f:\n f.write('node, count, sum, average\\n')\n for block_vf in vf_node:\n f.write(block_vf + ', ' + vf_node[block_vf] + '\\n')\n # writer.writerow([block_vf + ', ' + vf_node[block_vf]])\n\n\ndef report_node_chain(world, nodes_list):\n for node in nodes_list:\n head = node.chain.head\n chain_list = []\n num_blocks = 0\n for i in range(head.header.number):\n b = node.chain.get_block_by_number(i)\n chain_list.append(str(b.header))\n num_blocks += 1\n chain_list.append(str(head.header))\n key = f'{node.address}_chain'\n world.env.data[key] = {\n 'head_block_hash': f'{head.header.hash[:8]} #{head.header.number}',\n 'number_of_blocks': num_blocks,\n 'chain_list': chain_list\n }\n\n\ndef run_model(block_size, verification_mode):\n duration = 864000 # seconds\n # duration = 80 # seconds\n n1 = 20 # 40 80\n n2 = 14 # 28 56\n n3 = 16 # 32 64\n n4 = 14 # 28 56\n n5 = 20 # 40 80\n n6 = 16 # 32 64\n n = n1 + n2 + n3 + n4 + n5 + n6\n tr_a = 400 # 2000 4500\n tr_b = 1000 # 2000 2000\n\n report_directory = 'results/report/n' + str(n) + 'b' + str(block_size) + verification_mode\n Path(report_directory).mkdir(parents=True, exist_ok=True)\n\n now = int(time.time()) # Current time\n world = SimulationWorld(\n verification_mode,\n duration,\n now,\n 'input-parameters/config' + str(block_size) + '.json',\n 'input-parameters/latency.json',\n 'input-parameters/throughput-received.json',\n 'input-parameters/throughput-sent.json',\n 'input-parameters/delays.json')\n\n # Create the network\n network = Network(world.env, 'NetworkXPTO')\n\n\n miners = {\n 'USA': {\n 'how_many': n1,\n 'mega_hashrate_range': \"(20, 40)\"\n },\n 'Japan': {\n 'how_many': n2,\n 'mega_hashrate_range': \"(20, 40)\"\n },\n 'Canada': {\n 'how_many': n3,\n 'mega_hashrate_range': \"(20, 40)\"\n }\n }\n\n non_miners = {\n 'Japan': {\n 'how_many': n4\n },\n 'Canada': {\n 'how_many': n5\n },\n 'Ireland': {\n 'how_many': n6\n }\n }\n\n node_factory = NodeFactory(world, network)\n # Create all nodes\n nodes_list = node_factory.create_nodes(miners, non_miners)\n # Start the network heartbeat\n world.env.process(network.start_heartbeat())\n # Full Connect all nodes\n for node in nodes_list:\n node.verification_mode = verification_mode\n node.connect(nodes_list)\n\n transaction_factory = TransactionFactory(world)\n # transaction_factory.broadcast(100, 400, 15, nodes_list)\n transaction_factory.broadcast(tr_a, tr_b, 15, nodes_list)\n\n world.start_simulation()\n\n report_node_chain(world, nodes_list)\n write_report(world, report_directory)\n\n\nif __name__ == '__main__':\n verification_mode = \"WithMerkle\" # \"WithoutMerkle\"\n block_size = 50 # 100 200 300\n run_model(50, \"WithMerkle\")\n run_model(50, \"WithoutMerkle\")\n run_model(100, \"WithMerkle\")\n run_model(100, \"WithoutMerkle\")\n run_model(200, \"WithMerkle\")\n run_model(200, \"WithoutMerkle\")\n run_model(300, \"WithMerkle\")\n run_model(300, \"WithoutMerkle\")\n","sub_path":"blocksim/main_console.py","file_name":"main_console.py","file_ext":"py","file_size_in_byte":5533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"490800481","text":"from numpy import *\nimport pandas as pd\nclass Conveyor:\n def __init__(self):\n self.in_belt = []\n self.item_in_line = 0\n def retrieveProduct(self, id_product):\n self.in_belt.append(id_product)\n print(\"Place product id \"+id_product+\" on the belt\")\n self.item_in_line += 1\n print(\"Retrieving Successfully! \")\n return self.in_belt\n def getProduct(self):\n if self.item_in_line == 0:\n print(\"The belt is empty. Cannot retrieve the product from the belt. \")\n else:\n print(\"Retrieve a product with id \"+self.in_belt[0]+\" from the belt\")\n r.rehash_key[self.in_belt[0]] = \" \"\n del self.in_belt[0]\n self.item_in_line -= 1\n print(\"The belt now has \"+str(self.item_in_line)+\" products on the line\")\n def getItem(self):\n return self.item_in_line\nclass Warehouse:\n def __init__(self, names, rows, grids):\n \"\"\"defualt name warehouse\"\"\"\n self.name = names\n \"\"\"defualt parameter name row grid\"\"\"\n self.num_rows = rows\n \"\"\"what warehouse name is How many row and grid\"\"\"\n self.grids = grids\n self.rows = []\n self.total_product = 0\n self.list_slot = []\n self.slot = 0\n \"\"\"defualt position x,y\"\"\"\n self.x = 0\n self.y = 0\n self.list_product = []\n def createWarehouse(self):\n \"\"\"Create Warehouse with data from\"\"\"\n print(\"Create Warehouse \"+self.name)\n print(\"Number of Rows : \"+str(self.num_rows))\n print(\"Warehouse is Building\")\n \"\"\"create grids for each row\"\"\"\n ###################################################################################\n \"\"\"create row\"\"\"\n for r in range(self.num_rows):\n self.rows.append([])\n \"\"\"create parameter to store id product that is stored in that row\"\"\"\n self.list_product.append([])\n for num in range(0, (self.grids*self.grids)): #build grid x grid\n self.list_slot.append(\" \") #position x,y in grid we call slot\n data_slot = array(self.list_slot).reshape(self.grids, self.grids)\n ###################################################################################\n for i in range(self.num_rows): #take grid 2 dimension into rows of that warehouse\n self.rows[i] = pd.DataFrame(data=data_slot, columns=[y for y in range(self.grids)], index=[x for x in range(self.grids)])\n # \"\"\"Recheck Here!!! all of # below here\"\"\"\n # print(\"__________________________________________________\")\n # for i in range(self.num_rows):\n # print(\"rows : \"+str(i+1))\n # print(self.rows[i])\n # print(\"__________________________________________________\")\n print(\"Create Warehouse \"+self.name+\" Successfully\")\n # print(\"---------------------------------------------------------------------------\")\n # print(\"---------------------------------------------------------------------------\")\n def getInfo(self): #show Information about warehouse\n print(\"Warehouse \"+self.name)\n print(\"Number of Rows : \"+str(self.num_rows))\n print(\"Numbers of total product : \"+str(self.total_product))\n for i in range(self.num_rows):\n string = \" \"\n if len(self.list_product[i])>0:\n for item in (self.list_product[i]):\n string = string+str(item)+\", \"\n print(\"Product in row \"+str(i+1)+\" : id\"+string[0:-2])\n else:\n print(\"Product in row \"+str(i+1)+\" : id -\")\n def checkSlot(self,row,slot): #check Dose it has id_product in slot right?\n x = int(slot / self.grids)\n y = int(slot % self.grids)\n return self.rows[row][y][x]\n def addProduct(self,id_product,row,slot): #store product into warehouse\n x = int(slot / self.grids)\n y = int(slot % self.grids)\n self.rows[row][y][x] = id_product\n self.list_product[row].append(id_product)\n self.total_product += 1\n def removeProduct(self, id_product, row, slot): #retrieve product from warehouse\n x = int(slot / self.grids)\n y = int(slot % self.grids)\n self.list_product[row].remove(id_product)\n self.rows[row][y][x] = \" \"\n self.total_product -= 1\n def sortRow(self, row):\n self.list_product[row].sort()\n return self.list_product[row]\n def stateData(self):\n print(\"Warehouse \" + self.name)\n print(\"Number of Rows : \" + str(self.num_rows))\n print(\"Numbers of total product : \" + str(self.total_product))\n for i in range(self.num_rows):\n string = \" \"\n if len(self.list_product[i]) > 0:\n for item in (self.list_product[i]):\n string = string + str(item) + \", \"\n print(\"Product in row \" + str(i + 1) + \" : id\" + string[0:-2])\n else:\n print(\"Product in row \" + str(i + 1) + \" : id -\")\n print(\"__________________________________________________\")\n for i in range(self.num_rows):\n print(\"rows : \"+str(i+1))\n print(self.rows[i])\n print(\"__________________________________________________\")\n print(\"---------------------------------------------------------------------------\")\n print(\"---------------------------------------------------------------------------\")\nbelt = Conveyor()\nwh1 = Warehouse('A', 5, 10)\nwh1.createWarehouse()\nwh2 = Warehouse('B', 5, 10)\nwh2.createWarehouse()\nwh3 = Warehouse('C', 5, 10)\nwh3.createWarehouse()\nwh4 = Warehouse('D', 7, 5)\nwh4.createWarehouse()\nwh5 = Warehouse('E', 20, 20)\nwh5.createWarehouse()\ndef showdataAll():\n wh1.stateData()\n wh2.stateData()\n wh3.stateData()\n wh4.stateData()\n wh5.stateData()\ndef getInfoAll():return wh1.getInfo(), wh2.getInfo(), wh3.getInfo(), wh4.getInfo(), wh5.getInfo()\nclass Robot:\n def __init__(self):\n self.list_wh = [wh1, wh2, wh3, wh4, wh5]\n self.rehash_key = {}\n self.hash_warehouse = 0\n self.hash_row = 0\n self.hash_slot = 0\n for i in \"ABCDEFGHIJKLMNOPQRSTUVWXY\":\n for j in \"12345\":\n for k in \"0123456789\":\n for l in \"0123456789\":\n id_product = i+j+k+l\n self.rehash_key[id_product] = \" \"\n self.id_product = \" \"\n def findProduct(self, product_id):\n if (self.rehash_key[product_id] != \" \") and (self.rehash_key[product_id] != \"Belt\"):\n print(\"Found the product at \" + self.rehash_key[product_id])\n else:\n print(\"Product not found\")\n def hashing_key(self, id_product):\n self.id_product = id_product\n \"\"\"transform product_id in charactor to number_code\"\"\"\n if ord(id_product[0]) % 2 == 0:\n position = int(ord(id_product[0]) / 2) * 1000 + int(id_product[1:])\n else:\n position = int(ord(id_product[0]) / 2) * 1000 + 500 + int(id_product[1:])\n ##########################################################################################################\n \"\"\"hashing id product for store in the warehouse\"\"\"\n if (position >= 32600) and (position < 33100):\n self.hash_warehouse = 1\n self.hash_row = int(position / 100) - 326\n self.hash_slot = (position - 32600) % 100\n elif (position >= 33100) and (position < 33600):\n self.hash_warehouse = 2\n self.hash_row = int(position / 100) - 331\n self.hash_slot = (position - 33100) % 100\n elif (position >= 33600) and (position < 34100):\n self.hash_warehouse = 3\n self.hash_row = int(position / 100) - 336\n self.hash_slot = (position - 33600) % 100\n elif (position >= 34100) and (position < 34600):\n self.hash_warehouse = 4\n self.hash_row = int((position - 34100) / 25) % 7\n self.hash_slot = int((position - 34100) % 25)\n else:\n self.hash_warehouse = 5\n self.hash_row = int((position - 34600) / 400) % 20\n self.hash_slot = int((position - 34600) % 400)\n def retrieve(self,id_product):\n if belt.getItem() == 10:\n return print(\"Belt is full. Cannot retrieve the product\")\n if self.rehash_key[id_product] == \" \":\n return print(\"Slot is empty. Cannot retrieve the product\")\n if self.rehash_key[id_product] == \"Belt\":\n return print(\"now product \" + id_product + \" is on belt. Cannot retrieve the product\")\n else:\n self.id_product = id_product\n self.hashing_key(self.rehash_key[self.id_product])\n print(\"Moving from Belt to A\")\n self.list_wh[self.hash_warehouse-1].removeProduct(id_product, self.hash_row, self.hash_slot)\n if self.hash_warehouse == 1:\n print(\"Getting a product id \" + id_product + \" in warehouse A : row \" + str(self.hash_row + 1) + \" slot \" + str(self.hash_slot))\n elif self.hash_warehouse == 2:\n print(\"Moving from A to B \")\n print(\"Getting a product id \" + id_product + \" in warehouse B : row \" + str(self.hash_row + 1) + \" slot \" + str(self.hash_slot))\n print(\"Moving from B to A \")\n elif self.hash_warehouse == 3:\n print(\"Moving from A to C \")\n print(\"Getting a product id \" + id_product + \" in warehouse C : row \" + str(self.hash_row + 1) + \" slot \" + str(self.hash_slot))\n print(\"Moving from C to A \")\n elif self.hash_warehouse == 4:\n print(\"Moving from A to B\\nMoving from B to D \")\n print(\"Getting a product id \" + id_product + \" in warehouse D : row \" + str(self.hash_row + 1) + \" slot \" + str(self.hash_slot))\n print(\"Moving from D to B\\nMoving from B to A \")\n elif self.hash_warehouse == 5:\n print(\"Moving from A to B\\nMoving from B to E \")\n print(\"Getting a product id \" + id_product + \" in warehouse E : row \" + str(self.hash_row + 1) + \" slot \" + str(self.hash_slot))\n print(\"Moving from E to B\\nMoving from B to A \")\n self.rehash_key[id_product] = \"Belt\"\n print(\"Moving from A to Start \")\n belt.retrieveProduct(product_id1)\n def store(self, id_product):\n self.hashing_key(id_product)\n warehouse = self.hash_warehouse\n row = self.hash_row\n slot = self.hash_slot\n if self.rehash_key[id_product] == \"Belt\":\n return print(\"now product \" + id_product + \" is on belt. Cannot store the product. \")\n if self.rehash_key[id_product] != \" \":\n return print(\"product has been stored. Cannot store the product.\")\n self.list_wh[warehouse-1].checkSlot(row, slot)\n if self.list_wh[warehouse-1].checkSlot(row, slot) != \" \":\n return print(\"Slot is occupied. Cannot store the product. \")\n else:\n print(\"Moving from Belt to A\")\n self.list_wh[warehouse - 1].addProduct(id_product, row, slot)\n if warehouse == 1:\n print(\"Storing a product id \" + id_product + \" in warehouse A : row \" + str(row + 1) + \" slot \" + str(slot))\n elif warehouse == 2:\n print(\"Moving from A to B \")\n print(\"Storing a product id \" + id_product + \" in warehouse B : row \" + str(row + 1) + \" slot \" + str(slot))\n print(\"Moving from B to A \")\n elif warehouse == 3:\n print(\"Moving from A to C \")\n print(\"Storing a product id \" + id_product + \" in warehouse C : row \" + str(row + 1) + \" slot \" + str(slot))\n print(\"Moving from C to A \")\n elif warehouse == 4:\n print(\"Moving from A to B\\nMoving from B to D \")\n print(\"Storing a product id \" + id_product + \" in warehouse D : row \" + str(row + 1) + \" slot \" + str(slot))\n print(\"Moving from D to B\\nMoving from B to A \")\n elif warehouse == 5:\n print(\"Moving from A to B\\nMoving from B to E \")\n print(\"Storing a product id \" + id_product + \" in warehouse E : row \" + str(row + 1) + \" slot \" + str(slot))\n print(\"Moving from E to B\\nMoving from B to A \")\n print(\"Moving from A to Start \")\n self.rehash_key[id_product] = id_product\n print(\"Storing Successfully!\")\n def manuallmove(self, id_product1, id_product2):\n self.hashing_key(id_product2)\n if self.list_wh[self.hash_warehouse - 1].checkSlot(self.hash_row, self.hash_slot) != \" \":\n return print(\"Slot is occupied. Cannot move the product. \")\n if self.rehash_key[id_product1] == \"Belt\":\n return print(\"now product \" + id_product1 + \" is on belt. Cannot move the product.\")\n if self.rehash_key[id_product1] == \" \":\n return print(\"Slot is empty. Cannot move the product\")\n if self.rehash_key[id_product1] != \" \":\n self.hashing_key(self.rehash_key[id_product1])\n self.list_wh[self.hash_warehouse - 1].removeProduct(id_product1, self.hash_row, self.hash_slot)\n self.hashing_key(id_product2)\n self.list_wh[self.hash_warehouse - 1].addProduct(id_product1, self.hash_row, self.hash_slot)\n self.rehash_key[id_product1] = id_product2\n return print(\"Move product \" + id_product1 + \" to \" + id_product2)\n def sortWarehouse(self, sort_warehouse, rows):\n rows = rows - 1\n product_move = []\n product_row = self.list_wh[sort_warehouse-1].sortRow(rows)\n for item in range(0, len(product_row)):\n if self.rehash_key[product_row[item]] != product_row[item]:\n product_move.append(product_row[item])\n self.hashing_key(product_row[item])\n if self.list_wh[self.hash_warehouse - 1].checkSlot(self.hash_row, self.hash_slot) != \" \":\n return print(\"Slot is occupied. Fail to sort. \")\n if len(product_move) != 0:\n for item in range(0, len(product_move)):\n self.hashing_key(self.rehash_key[product_move[item]])\n self.list_wh[self.hash_warehouse - 1].removeProduct(product_move[item], self.hash_row, self.hash_slot)\n self.hashing_key(product_move[item])\n self.list_wh[self.hash_warehouse - 1].addProduct(product_move[item], self.hash_row, self.hash_slot)\n self.rehash_key[product_move[item]] = product_move[item]\n print(\"Sorting process for warehouse \"+self.list_wh[sort_warehouse-1].name+\" is complete\")\n\"\"\"INPUT COMMAND\"\"\"\ninput_command = \"\"\nr = Robot()\nwhile(input_command != \"stop\"):\n print(\"0XXXX\\t\\tRetrieve a product id XXXX \")\n print(\"1XXXX\\t\\tStore a product id XXXX \")\n print(\"2XYY0\\t\\tSort warehouse X at row Y \")\n print(\"30000\\t\\tRetrieve a product from the conveyor belt \")\n print(\"40000\\t\\tOutput information of all warehouses\")\n print(\"5XXXX\\t\\tSearch for a product ID XXXX \")\n print(\"60000\\t\\tshow all id_product and position_id\")\n print(\"70000\\t\\tshow inside of all warehouse\")\n print(\"9XXXXYYYY\\tManually put a product id XXXX at position YYYY\")\n print(\"stop\\t\\tstop program\")\n print(\"-----------------------------------------------------------------------------------------\")\n input_command = input(\"Input Command : \")\n if input_command != \"stop\":\n if (len(input_command) == 5) or (len(input_command) == 9):\n order = input_command[0]\n product_id1 = input_command[1:5]\n product_id2 = input_command[5:9]\n if ord(product_id1[0]) > 96 & ord(product_id1[0]) < 122:\n product_id1 = product_id1[0].upper() + input_command[2:5]\n if len(input_command) == 9:\n if ord(product_id2[0]) > 96 & ord(product_id2[0]) < 122:\n product_id2 = product_id2[0].upper() + input_command[6:9]\n if input_command == str('30000'):belt.getProduct()\n if input_command == str('40000'):getInfoAll()\n if input_command == str('60000'):print(r.rehash_key)\n if input_command == str('70000'):showdataAll()\n if order == str('0'):r.retrieve(product_id1)\n if order == str('1'):r.store(product_id1)\n if order == str('2'):r.sortWarehouse(ord(input_command[1].upper()) - 64, int(input_command[2:4]))\n if order == str('5'):r.findProduct(product_id1)\n if order == str('9'):r.manuallmove(product_id1, product_id2)\n else:\n print(\"your order is not clear please input again\")","sub_path":"WH5/WarehouseSD.py","file_name":"WarehouseSD.py","file_ext":"py","file_size_in_byte":16734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"365912216","text":"from collections import Counter\nfrom collections import defaultdict\nusers = [\n {\"id\": 0, \"name\": \"Hero\"},\n {\"id\": 1, \"name\": \"Dunn\"},\n {\"id\": 2, \"name\": \"Sue\"},\n {\"id\": 3, \"name\": \"Chi\"},\n {\"id\": 4, \"name\": \"Thor\"},\n {\"id\": 5, \"name\": \"Clive\"},\n {\"id\": 6, \"name\": \"Hicks\"},\n {\"id\": 7, \"name\": \"Devin\"},\n {\"id\": 8, \"name\": \"Kate\"},\n {\"id\": 9, \"name\": \"Klein\"}\n\n]\n\n# lista = [1, 2, 3, 4, 5]\n# lista[2] = 7\n# lista = [1, 2]\n\n\n# tupla = (1, 2, 3, 4, 5)\n# print (tupla[2])\n# tupla[2] = 3\n# tupla = (9, 9, 1)\n\n# tupla = 2\n\nfriendships = [\n (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5),\n (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)\n]\n\nfor user in users:\n user[\"friends\"] = []\n\n\nfor i, j in friendships:\n users[i][\"friends\"].append(users[j])\n users[j][\"friends\"].append(users[i])\n\n# print(users)\n\n# int numero (int a, int b){\n# return a + b;\n# }\n\n\n# def soma(a, b):\n# c = a + b\n\n\n# resultado = soma (2, 3)\n\n# print(soma(2, 3))\n\n\ndef number_of_friends(user):\n return len(user['friends'])\n#print(number_of_friends(users[0]))\n\ntotal_connections = sum(number_of_friends(u) for u in users)\n#print (total_connections)\n\nnum_users = len(users)\navg_connections = total_connections / num_users\n#print (avg_connections)\n\nnum_friends_by_id = [(user[\"id\"], number_of_friends(user)) for user in users]\n#print (num_friends_by_id)\n\nlista_ordenada = sorted (num_friends_by_id, key = lambda num_friends: num_friends[1], reverse = True)\n\n#print (lista_ordenada)\n\ndef friends_of_friends_ids_bad (user):\n return[\n foaf[\"id\"]\n for friend in user[\"friends\"]\n for foaf in friend[\"friends\"]\n ]\n\ndef not_the_same (user, other_user):\n return user[\"id\"] != other_user[\"id\"]\n\ndef not_friends (user, other_user):\n return all(not_the_same (friend, other_user) for friend in user[\"friends\"])\n\n#print (not_friends(users[0], users[9]))\n\ndef friends_of_friends_ids (user):\n return set([\n foaf[\"id\"]\n for friend in user['friends']\n for foaf in friend['friends']\n if not_the_same (user, foaf)\n and not_friends (user, foaf)\n ])\n\n#print (friends_of_friends_ids(users[0]))\n\n#teste = [1, 2, 5, 4, 3, 2, 1, 2, 3, 2, 1]\n#c = Counter (teste)\n\n#print (c)\ndef friends_of_friends_ids_frequency (user):\n return Counter([\n foaf[\"id\"]\n for friend in user [\"friends\"]\n for foaf in friend [\"friends\"]\n if not_the_same (user, foaf)\n and not_friends (user, foaf)\n ])\n\n\n#print (friends_of_friends_ids_frequency(users[4]))\n\ninterests = [\n (0, \"Hadoop\"), (0, \"Big Data\"), (0, \"HBase\"), (0, \"Java\"),\n (0, \"Spark\"), (0, \"Storm\"), (0, \"Cassandra\"),\n (1, \"NoSQL\"), (1, \"MongoDB\"), (1, \"Cassandra\"), (1, \"HBase\"),\n (1, \"Postgres\"), (2, \"Python\"), (2, \"scikit-learn\"), (2, \"scipy\"),\n (2, \"numpy\"), (2, \"statsmodel\"), (2, \"pandas\"), (3, \"R\"), (3, \"Python\"),\n (3, \"statistics\"), (3, \"regression\"), (3, \"probability\"),\n (4, \"machine learning\"), (4, \"regression\"), (4, \"decision trees\"),\n (4, \"libsvm\"), (5, \"Python\"), (5, \"R\"), (5, \"Java\"), (5, \"C++\"),\n (5, \"Haskell\"), (5, \"programming languages\"), (6, \"theory\"),\n (7, \"machine learning\"), (7, \"scikit-learn\"), (7, \"Mahout\"),\n (7, \"neural networks\"), (8, \"neural networks\"), (8, \"deep learning\"),\n (8, \"Big Data\"), (8, \"artificial intelligence\"), (8, \"Hadoop\"),\n (9, \"Java\"), (9, \"MapReduce\"), (9, \"Big Data\"), (0, \"GraphQL\")\n]\n\ndef data_scientists_who_like (target_interest):\n return [\n user_id for user_id, interest in interests if interest == target_interest\n ]\n\n#print (data_scientists_who_like (\"Big Data\"))\n\n#def f ():\n return 5\n\n#d = defaultdict (list)\n\n#d[\"Big Data\"].append (2)\n#print (d[\"teste\"])\n\n\n#(0, \"Hadoop\"), (0, \"Big Data\"), (0, \"HBase\"), (1, \"Java\"),\ninterests_by_user_id = defaultdict(list)\nfor user_id, interest in interests:\n interests_by_user_id[user_id].append(interest)\n\nuser_id_by_interest = defaultdict (list)\nfor user_id, interest in interests:\n user_id_by_interest[interest].append(user_id)\n\n#print (\"Interesses por usuário\")\n#print (interests_by_user_id)\n#print (\"Usuários por interesse\")\n#print (user_id_by_interest)\n\ndef user_with_common_interest_with (user):\n return set([\n interested_user_id\n for interest in interests_by_user_id[user[\"id\"]]\n for interested_user_id in user_id_by_interest[interest]\n if interested_user_id != user [\"id\"]\n ])\n\n#print (user_with_common_interest_with (users[0]))\n\ndef most_common_interests_with (user):\n return Counter (\n interested_user_id\n for interest in interests_by_user_id[user[\"id\"]]\n for interested_user_id in user_id_by_interest [interest]\n if interested_user_id != user[\"id\"]\n )\n\n#print (most_common_interests_with(users[0]))\n\nsalario_e_experiencia = [\n (83000, 8.7), (88000, 8.1),\n (48000, 0.7), (76000, 6),\n (69000, 6.5), (76000, 7.5),\n (60000, 2.5), (83000, 10),\n (48000, 1.9), (63000, 4.2)\n]\n\nsalario_por_experiencia = defaultdict (list)\nfor salario, experiencia in salario_e_experiencia:\n salario_por_experiencia[experiencia].append(salario)\n\n#print(salario_por_experiencia)\nsalario_medio_por_experiencia = {\n experiencia: sum (salarios) / len (salarios)\n for experiencia, salarios in salario_por_experiencia.items()\n}\n\n#print (salario_medio_por_experiencia)\n\ndef rotulo_por_experiencia (experiencia):\n if experiencia < 2:\n return \"(0,2)\"\n elif experiencia < 5:\n return \"[2,5)\"\n else:\n return \"[5,...)\"\n\nsalario_por_rotulo = defaultdict(list)\nfor salario, experiencia in salario_e_experiencia:\n salario_por_rotulo[rotulo_por_experiencia(experiencia)].append(salario)\n\n#print (salario_por_rotulo)\n\nsalario_medio_por_rotulo = {\n rotulo: sum(salarios) / len(salarios)\n for rotulo, salarios in salario_por_rotulo.items()\n}\n\n#print (salario_medio_por_rotulo)\n\nexperiencia_e_tipo_de_conta = [\n (0.7, 'paga'),\n (1.9, 'gratuita'),\n (2.5, 'paga'),\n (4.2, 'gratuita'),\n (6, 'gratuita'),\n (6.5, 'gratuita'),\n (7.5, 'gratuita'),\n (8.1, 'gratuita'),\n (8.7, 'paga'),\n (10, 'paga')\n]\n\ndef classificar_como_paga_ou_gratuita (experiencia):\n if experiencia < 3:\n return 'paga'\n elif experiencia < 8.5:\n return 'gratuita'\n else:\n return 'paga'\n\nprint (classificar_como_paga_ou_gratuita (1.9))","sub_path":"aula-3/aula3.py","file_name":"aula3.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"115474423","text":"import random\nquestions={\n '1':['Q.2+3=?','a:4','b:5','c:6','b'],\n '2':['Q.5+3/3','a:4','b:5','c:6','c'],\n '3':['Q.Highest peak of world','a:Mount Everest','b:Mount Baton','c:MountValley','a'],\n \n }\nls=['1','2','3']\n\n\nmarks=0\nname=input('Enter your name:')\nprint('\\n\\nWelcome to the trivia game\\nRule #1:Right Score +10\\nRule #2:Wrong Score -5')\nrandom.shuffle(ls)\nif input('\\n\\nPress any key if you wanna start:'):\n for i in range(0,len(ls)):\n print(\"\\n\\n\",questions[ls[i]][0])\n print(\"\",questions[ls[i]][1])\n print(\"\",questions[ls[i]][2])\n print(\"\",questions[ls[i]][3])\n x=input(' Enter your choice:')\n if(x==questions[ls[i]][4]):\n marks=marks+10\n else:\n marks=marks-5\n\n print('\\n\\n{},Your score is:{}'.format(name,marks))\nelse:\n print('You should have confident in yourself')\n\n\n","sub_path":"kbc.py","file_name":"kbc.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"431081912","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2016-12-30 16:20:01\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\nfrom collections import namedtuple,deque\n\ndef namedtupleTest():\n Points = namedtuple('Test1', ['x', 'y'])\n p = Points(1, 2)\n print(p, p.x, p.y, isinstance(p, Points), isinstance(p, tuple))\n\ndef dequeTest():\n q = deque(['a', 'b', 'c'])\n q.appendleft(q.pop())\n print(q)\n q.append(q.popleft())\n print(q)\n\n\nif __name__ == '__main__':\n namedtupleTest()\n dequeTest()\n","sub_path":"BasicProject/PythonBasic/Learn-12.30-Collections.py","file_name":"Learn-12.30-Collections.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"642246254","text":"\r\nimport random\r\nimport threading\r\nimport subprocess\r\nimport time,os\r\nfrom dialog import Dialog\r\nfrom audioManager import AudioRecorder\r\nfrom pathlib import Path\r\nimport face_recognition\r\nimport cv2\r\nimport numpy as np\r\nfrom subprocess import PIPE, run\r\n\r\nfrom dialog import Dialog\r\n\r\nclass FaceRecognition(object):\r\n def __init__(self, audio_recorder):\r\n \"\"\"if audio_recorder is None:\r\n print(\"none param\")\r\n self.audio_recorder = AudioRecorder(Dialog())\r\n else :\"\"\"\r\n self.audio_recorder = audio_recorder\r\n threading.Thread(target=self.run).start()\r\n\r\n def run(self):\r\n \r\n self.detecter = False\r\n \r\n self.discute = False\r\n self.dialog = Dialog()\r\n self.unknown_file = {\"inconnu\":0}\r\n self.known_file = {\"percent\":0,\"name\":\"inconnu\"}\r\n self.existe = {}\r\n self.pre_nom_detecter = \"\"\r\n self.new=False\r\n with open(\"unknown\",\"w\") as f : f.write(str(self.unknown_file))\r\n with open(\"known\",\"w\") as f : f.write(str(self.known_file))\r\n with open(\"existe\",\"w\") as f : f.write(str(self.existe))\r\n with open(\"new\",\"w\") as f : f.write(str(self.new))\r\n threading.Thread(target=lambda: subprocess.Popen(\"python3 face_system/facerec.py\",shell=True)).start()\r\n self.check_unknown()\r\n\r\n \r\n\r\n def check_unknown(self):\r\n # print(\"ici\")\r\n \r\n while True :\r\n if (self.discute==False) : \r\n with open(\"known\", \"r\") as f : self.known_file = eval(f.read())\r\n with open(\"existe\",\"r\") as f : self.existe=eval(f.read())\r\n self.detecter=self.known_file[\"percent\"]>40\r\n name=self.known_file[\"name\"]\r\n if self.detecter and self.pre_nom_detecter !=name : \r\n # if self.detecter and self.pre_nom_detecter !=name and name not in self.existe: \r\n self.pre_nom_detecter = self.known_file[\"name\"]\r\n if self.dialog.attente_isplein: continue \r\n else :\r\n print(\"envoi de message ...\")\r\n self.dialog.process_init(\"salut je suis \" + self.pre_nom_detecter)\r\n # self.dialog.send_user_msg_to_chatbot(\"salut je suis \" + self.pre_nom_detecter)\r\n # self.dialog.add_file_attente(self.dialog.response)\r\n #self.dialog.add_file_attente(\"Bonjour \"+self.pre_nom_detecter)\r\n\r\n # self.dialog.SpeakText(\"Bonjour \"+self.pre_nom_detecter)\r\n if name not in self.existe : \r\n self.existe[name]=self.detecter\r\n with open(\"existe\",\"w\") as f : f.write(str(self.existe))\r\n # subprocess.Popen(\"py -3.5 dialog.py --input \\\"je suis \"+self.known_file[\"name\"]+\"\\\"\", shell=True)\r\n continue\r\n\r\n with open(\"unknown\",\"r\") as f : self.unknown_file=eval(f.read())\r\n # if self.unknown_file[\"inconnu\"] > 60 :\r\n # self.discute=True\r\n # self.train_model()\r\n\r\n # self.discute=False\r\n \r\n time.sleep(1)\r\n\r\n def train_model(self):\r\n if self.dialog.attente_isplein: return \r\n else : \r\n # self.audio_recorder.pause=True\r\n with open(\"is_lecture\", \"w\") as f : f.write(\"True\")\r\n self.dialog.add_file_attente(\"Bonjour, je ne vous connais pas\")\r\n # self.dialog.SpeakText(\"Bonjour, je ne vous connais pas\")\r\n time.sleep(1000)\r\n # nom=\"lol\"\r\n nom = self.audio_recorder.simple_recognize(\"quel est votre nom ?\")\r\n if nom is None : print(\"entrainement incomplet\")\r\n else:\r\n print(\"son nom : \"+str(nom))\r\n if nom==\"inconnu\" or nom ==\"\" or len(nom)<2 or nom is None:\r\n if self.dialog.attente_isplein : return \r\n else : self.dialog.add_file_attente(\"desolé je n'est pas saisie votre nom\")\r\n # if not self.dialog.en_lecture : self.dialog.SpeakText(\"desolé je n'est pas saisie votre nom\")\r\n else :\r\n if not self.dialog.en_lecture : self.dialog.SpeakText(\"enchanté \"+nom)\r\n self.take_photo(nom,time.time())\r\n time.sleep(1000)\r\n # self.audio_recorder.pause=False\r\n with open(\"is_lecture\", \"w\") as f : f.write(\"False\")\r\n self.unknown_file ={\"inconnu\":0}\r\n with open(\"unknown\",\"w\") as f : f.write(str(self.unknown_file))\r\n print(\"entrainement terminé\")\r\n def take_photo(self,name, date):\r\n print(\"enregistrement de \"+name+\"\\ndate: \"+str(date))\r\n # video_capture = cv2.VideoCapture(0)\r\n cam = cv2.VideoCapture(0)\r\n cv2.namedWindow(\"saving\")\r\n directory = \"face_system/images/\" + name + \"/\"\r\n t = 0\r\n take = False\r\n while t < 4 or take == False:\r\n ret, frame = cam.read()\r\n if not ret:\r\n print(\"Echec de la capture \")\r\n else:\r\n cv2.imshow(\"test\", frame)\r\n img_name = \"image_{}.png\".format(date)\r\n # Path(directory).mkdir(parents=True, exist_ok=True)\r\n if not os.path.exists(directory):\r\n os.makedirs(directory, exist_ok=False)\r\n run(\"chown -R oda03 \" + directory, stdout=PIPE,stderr=PIPE, universal_newlines=True, shell=True).stdout\r\n run(\"chmod -R 755 \" + directory, stdout=PIPE,stderr=PIPE, universal_newlines=True, shell=True).stdout\r\n # run(\"chmod 755 \" + directory, stdout=PIPE,stderr=PIPE, universal_newlines=True, shell=True).stdout\r\n \r\n if face_recognition.face_encodings(frame):\r\n cv2.imwrite(directory + img_name, frame)\r\n run(\"chown -R oda03 \" + directory, stdout=PIPE,stderr=PIPE, universal_newlines=True, shell=True).stdout\r\n run(\"chmod -R 755 \" + directory, stdout=PIPE,stderr=PIPE, universal_newlines=True, shell=True).stdout\r\n # run(\"chmod -R 777 \" + directory + \"*\", stdout=PIPE,stderr=PIPE, universal_newlines=True, shell=True).stdout\r\n # run(\"chown ${USER:=$(/usr/bin/id -run)}:$USER \" + directory + \"*\", stdout=PIPE,stderr=PIPE, universal_newlines=True, shell=True).stdout\r\n print(\"{} written!\".format(img_name))\r\n self.new=True\r\n take = True\r\n\r\n else:\r\n print(\"Image not OK to save \")\r\n time.sleep(2)\r\n t += 2\r\n if self.new==True : \r\n with open(\"new\",\"w\") as f : f.write(str(self.new)) \r\n cam.release()\r\n cv2.destroyWindow(\"saving\")\r\n print(\"sauvé\")\r\n\r\n#s=FaceRecognition()\r\n","sub_path":"faceManager.py","file_name":"faceManager.py","file_ext":"py","file_size_in_byte":6977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"143762477","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 29 20:13:31 2020\r\n\r\n@author: pc\r\n\"\"\"\r\n\r\nfrom wikidata.client import Client\r\nclient = Client() # doctest: +SKIP\r\nentity = client.get('Q20145', load=True)\r\nentity\r\n#\r\n\r\n#label,altlabel可以这样获取\r\n#获取中文标签和别名\r\na=entity.attributes\r\nzh_key=['zh','zh-hans','zh-hant','zh-tw','zh-my','zh-sg','zh-hk','zh-cn','zh-mo','zh-my']\r\nlabel=[]\r\nfor k in zh_key: \r\n if type(a['aliases'].get(k))==list:#altlabel每个语言的value是一个列表\r\n label.extend(a['aliases'].get(k))\r\n if type(a['labels'].get(k))==dict:#label每个语言的value是一个字典\r\n label.append(a['labels'].get(k))\r\nlabel=set(x['value'] for x in label)\r\n\r\n#获取英文标签和别名\r\na=entity.attributes\r\nlabel=[]\r\nlabel.extend(list(a['aliases']['en']))\r\nlabel.append(a['labels']['en'])\r\nlabel=list(set(x['value'] for x in label))\r\nlabel=[[x[:x.find('(s)')]+'s',x[:x.find('(s)')]] if '(s)' in x else [x] for x in label]\r\nlabel=list(set(sum(label,[])))\r\n\r\n#获取其他属性\r\nimage_prop = client.get('P18')#获取P18属性\r\nimage = entity[image_prop]#访问entity的这个属性\r\nimage.image_resolution #访问entity的这个属性的属性\r\n#(820, 1122)\r\nimage.image_url\r\n#'https://upload.wikimedia.org/wikipedia/commons/6/60/KBS_%22The_Producers%22_press_conference%2C_11_May_2015_10.jpg'\r\n\r\n\r\n\r\n'''\r\n不知道en,wikidata,wikipedia这些设置的作用\r\n这两个的区别\r\nrepo = site.data_repository()\r\npage = pywikibot.Page(site, \"Douglas Adams\")\r\n'''\r\nimport pywikibot\r\nsite = pywikibot.Site(\"en\", \"wikipedia\")\r\npage = pywikibot.Page(site, \"Douglas Adams\")\r\nitem = pywikibot.ItemPage.fromPage(page)\r\nprint(item)#ItemPage('Q42')\r\nitem_dict = item.get()#所有有用信息,每个key的value是一个pywikibot.page对象\r\nprint(item_dict.keys())#所有的有用信息的key,dict_keys(['labels', 'descriptions', 'aliases', 'claims', 'sitelinks'])\r\n#以labels这个属性为例,获取信息\r\nallLabel=item_dict['labels'].toJSON()#⭐⭐如何得到pywokobot.page对象的内容,toJSON方法\r\nenLabel=allLabel['en']['value']\r\n#获取别名\r\nallAlia=[x['value'] for x in item_dict['aliases'].toJSON()['en']]\r\n\r\n\r\n\r\n\r\n\r\nimport pywikibot\r\n\r\nsite = pywikibot.Site(\"wikidata\", \"wikidata\")\r\nrepo = site.data_repository()\r\nitem = pywikibot.ItemPage(repo, \"Q2225\")\r\n\r\nitem_dict = item.get()\r\nclm_dict = item_dict[\"claims\"]\r\nclm_list = clm_dict[\"P2069\"]\r\n\r\nfor clm in clm_list:\r\n print(clm.toJSON())\r\n \r\nfor clm in clm_list:\r\n #getTarget相当于\r\n #clm_list[0].toJSON()['mainsnak']['datavalue']['value']\r\n clm_trgt = clm.getTarget()\r\n print(clm_trgt)\r\n \r\ndef altLabel(wikiId='Q20145'):\r\n \r\n from wikidata.client import Client\r\n client = Client() # doctest: +SKIP\r\n entity = client.get(wikiId, load=True)\r\n a=entity.attributes\r\n label=[]\r\n label.extend(list(a['aliases']['en']))\r\n label.append(a['labels']['en'])\r\n label=list(set(x['value'] for x in label))\r\n label=[[x[:x.find('(s)')]+'s',x[:x.find('(s)')]] if '(s)' in x else [x] for x in label]\r\n label=list(set(sum(label,[])))\r\n \r\ndef altLabelBot(idOrLabel):\r\n import pywikibot\r\n p=re.compile(r'(P|Q)[1-9][0-9]*')\r\n if p.fullmatch(idOrLabel)!=None: \r\n wikiId=idOrLabel#\"Q2225\" \r\n site = pywikibot.Site(\"en\", \"wikipedia\")\r\n page = pywikibot.Page(site, labelName)\r\n item = pywikibot.ItemPage.fromPage(page)\r\n else:\r\n labelName=idOrLabel#\"Douglas Adams\" \r\n site = pywikibot.Site(\"wikidata\", \"wikidata\")\r\n repo = site.data_repository()\r\n item = pywikibot.ItemPage(repo,wikiId)\r\n \r\n item_dict = item.get()#所有有用信息,每个key的value是一个pywikibot.page对象\r\n #以labels这个属性为例,获取信息\r\n allLabel=item_dict['labels'].toJSON()#⭐⭐如何得到pywokobot.page对象的内容,toJSON方法\r\n enLabel=allLabel['en']['value']\r\n #获取别名\r\n allAlia=[x['value'] for x in item_dict['aliases'].toJSON()['en']]\r\n \r\n \r\n\r\ndef OKBQARL2(text):\r\n url = \"https://www.wikidata.org/w/api.php?action=opensearch&format=json&formatversion=2&search=Douglas%20Adam&namespace=0%7C120&limit=10\"\r\n \r\n \r\n url = \"https://www.wikidata.org/w/index.php?sort=relevance&search=Douglas+Adam&title=Special%3ASearch&profile=advanced&fulltext=1&advancedSearch-current=%7B%7D&ns0=1&ns120=1\"\r\n result = requests.get(url).content \r\n \r\n \r\n from bs4 import BeautifulSoup as bs\r\n soup = bs(result)\r\n #c只有一个Tag元素\r\n c=soup.find_all('ul',class_='mw-search-results')\r\n d=c[0].select('li')[0]#c[0]所有li标签中,第一个\r\n \r\n wikiId=c[0].select('li')[0].select('a')[0]['href']\r\n wikiId=wikiId[wikiId.rfind('/')+1:]\r\n wikiId=wikiId[wikiId.rfind(':')+1:]#href=\"/wiki/Property:P50\"\r\n title=c[0].select('li')[0].select('a')[0]['title']\r\n ","sub_path":"wikidata_func.py","file_name":"wikidata_func.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"403482820","text":"# -*- coding: utf-8 -*-\n\nfrom pipobot.lib.module_test import ModuleTest\nfrom pipobot.lib.modules import SyncModule, defaultcmd\n\nfrom .fact import fact\n\nclass CmdQuote(SyncModule):\n '''Retrieve a sentence from reverso.net, matching keywords and a language.\n\n Configuration keys:\n - lang: Define the default language used to retrieve the \"quotes\"/\"facts\".\n - size: Define the history size (the bot tries to doesn't repeat itself).\n - fall: Define the fallback keyword used when no history is available.'''\n _config = ((\"lang\", str, \"fr\"), (\"size\", int, 256), (\"fall\", str, \"fr\"))\n\n def __init__(self, bot):\n desc = _('fact [-]: find a fact with in on reverso.net')\n SyncModule.__init__(self,\n bot,\n desc=desc,\n name='fact')\n # config: lang, size, fall\n self.last = self.fall\n self.buff = []\n\n @defaultcmd\n def answer(self, sender, message):\n return fact(self, message)\n\nclass QuoteTest(ModuleTest):\n def test_fact(self):\n rep = self.bot_answer('!fact furet mort')\n self.assertEqual(rep[:77], 'De tout. Al Qaeda, les furets, les édulcorants artificiels, les distributeurs')\n rep = self.bot_answer('!fact furet')\n self.assertEqual(rep[:73], 'Des manipulations quotidiennes pendant ce stade critique du développement')\n rep = self.bot_answer('!fact chargé')\n self.assertEqual(rep[:71], u'Plus pr\\xe9cis\\xe9ment, le porteur charg\\xe9 positivement est un polypeptide cha')\n","sub_path":"fact/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130620166","text":"str = \"forgeeksskeegfor\"\nstr = \"BBABCBCAB\"\n# str = \"geeks for geeks\"\n\nn = len(str)\ntable = [[0 for _ in range(n)] for _ in range(n)]\n\nfor i in range(n):\n table[i][i] = 1\n\nk = n - 1\ncount = 1\nwhile k >= 0:\n for i in range(k):\n j = i + count\n if str[i] != str[j]:\n table[i][j] = max(table[i][j - 1], table[i + 1][j])\n else:\n if count == 1:\n table[i][j] = 2\n else:\n table[i][j] = table[i+1][j-1] + 2\n k -= 1\n count += 1\n\nfor ele in table:\n print(ele, end=\"\\n\")\n\n","sub_path":"datastructures_algorithms/String-LongestPalindromicSubsequence.py","file_name":"String-LongestPalindromicSubsequence.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"507462957","text":"\ndef parse_train_file(fname):\n coarse_ls, fine_ls, qs = [], [], []\n with open(fname, 'r') as f:\n for line in f.readlines():\n line = line.replace('\\n', '')\n parts = line.split(' ')\n fine_l, question = parts[0], ' '.join(parts[1:])\n coarse_l = fine_l.split(':')[0]\n coarse_ls.append(coarse_l)\n fine_ls.append(fine_l)\n qs.append(question)\n return coarse_ls, fine_ls, qs\n\n\n_, fine_ls, qs = parse_train_file('DEV.txt')\n\nwith open('DEV-questions.txt', 'w') as f:\n for question in qs:\n f.write(question + '\\n')\n\nwith open('DEV-labels.txt', 'w') as f:\n for fine_l in fine_ls:\n f.write(fine_l + '\\n')\n","sub_path":"divide.py","file_name":"divide.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"639782073","text":"#CalPiV2.py\n\n# 引入random库和time库\nfrom random import random\nfrom time import perf_counter\n# 设置值一共1000*1000个灰尘,落入灰尘设为初始值0,设置开始时间。\nDARTS = 1000*1000\nhits = 0.0\nstart = perf_counter()\n# 随机落入灰尘,根据直角公式求第三边也就是灰尘到圆心的距离,距离小于1则在圆内,距离大于1则在圆外。叠加在圆内的灰尘。\n#圆的直径是1,则圆面积就是π。\n\nfor i in range(1,DARTS+1):\n x, y =random(), random()\n dist = pow(x ** 2 + y ** 2, 0.5)\n if dist <=1.0:\n hits = hits + 1\n\n# 因为算的是1/4的面积,所以算所有的圆面积,则乘以4 \npi = 4 * (hits/DARTS)\nprint(\"圆周率值是:{}\".format(pi))\nprint(\"运行时间是:{:.5f}s\".format(perf_counter()-start))\n\n ","sub_path":"CalPiV2_20200922.py","file_name":"CalPiV2_20200922.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380749412","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfile_name = 'spec_qtm_all.dat'\nfile_dir = '../dat/'\nnz, nx = 1600, 400\ngrid_lower_x, grid_upper_x = 0.0, 1.0\ngrid_lower_z, grid_upper_z = -2.0, 2.0\norders = 4.0\n\n\ndata = np.loadtxt( file_dir + file_name )\ndata_pz = data[:,0]\ndata_px = data[:,1]\ndata_w = data[:,2]\n\npz = data_pz.reshape( nx, nz )\npx = data_px.reshape( nx, nz )\nw = data_w.reshape( nx, nz )\nw_max = np.amax(w)\nw_lower_limit = np.log10(w_max) - orders\ni_too_small = np.where( w < 10 ** w_lower_limit )\nw[i_too_small] = 10 ** w_lower_limit\nw = np.log10(w)\n\n\nfig = plt.figure(figsize=(16,6), frameon = False )\nax = fig.add_subplot(111, aspect='equal')\nfig.patch.set_alpha(0.0)\nplt.imshow( w, interpolation='bilinear',\n origin='lower', #cmap=cm.gray,\n extent=[grid_lower_z, grid_upper_z, grid_lower_x, grid_upper_x] )\nplt.grid()\nplt.show()\n","sub_path":"ana/plot/plot_spec.py","file_name":"plot_spec.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"265878196","text":"#영화 상세정보 DB에 저장\n#def movie_detail(year)\nimport datetime\nimport requests\nimport json\nfrom DbConn import *\nfrom datetime import datetime, timedelta\n\nMOVIE_DETAIL_URL='http://www.kobis.or.kr/kobisopenapi/webservice/rest/movie/searchMovieInfo.json'\n# 민수 \n# API_KEY = \"d9dbe114c7c43200437493cbcb36ee74\"\n# 태욱\n# API_KEY = \"ef0d1cc93bc2ef58555e96b5dd6af1e4\"\n# 성은\nAPI_KEY = \"de94fab2e7564e8d9c7a4e43a6a452ba\"\n# 문정\n# API_KEY = \"115e6f48c454984e7ac6975401bd9544\"\n# API_KEY = \"13891b89e385e48aa8433f01dc61d577\"\n# API_KEY = \"c8fc5344160dbc22af948de275908b90\"\n# API_KEY = \"1f7ced99b26cb1c06c18e6fe86d22308\"\n\ndef insert_moviedetail(moviecd):\n db = DbConn()\n \n url = MOVIE_DETAIL_URL+'?key='+API_KEY+'&movieCd='+str(moviecd)\n data = requests.get(url).json()\n\n movie_info_list = data['movieInfoResult']['movieInfo']\n \n insert_query = '''\n INSERT INTO movie (movieCd,movieNm,movieNmEn,prdtYear,showTm,openDt,prdtStatNm,typeNm,nations,genre,genreSub,director,actors1,actors2,actors3,actors4,audits,prodCd,prodNm,distCd,distNm,staffs)\n VALUES(:movieCd,:movieNm,:movieNmEn,:prdtYear,:showTm,:openDt,:prdtStatNm,:typeNm,:nations,:genre,:genreSub,:director,:actors1,:actors2,:actors3,:actors4,:audits,:prodCd,:prodNm,:distCd,:distNm,:staffs)\n '''\n select_query=\"SELECT * FROM movie WHERE MOVIECD = :MOVIECD\"\n\n #변수 조건\n actor1 = movie_info_list['actors'][0]['peopleNm'] if len(movie_info_list['actors']) > 0 else ''\n actor2 = movie_info_list['actors'][1]['peopleNm'] if len(movie_info_list['actors']) > 1 else ''\n actor3 = movie_info_list['actors'][2]['peopleNm'] if len(movie_info_list['actors']) > 2 else ''\n actor4 = movie_info_list['actors'][3]['peopleNm'] if len(movie_info_list['actors']) > 3 else ''\n \n nations = movie_info_list['nations'][0]['nationNm'] if len(movie_info_list['nations']) > 0 else ''\n \n genre = movie_info_list['genres'][0]['genreNm'] if len(movie_info_list['genres']) > 0 else ''\n genreSub= movie_info_list['genres'][1]['genreNm'] if len(movie_info_list['genres']) > 1 else ''\n\n director= movie_info_list['directors'][0]['peopleNm'] if len(movie_info_list['directors']) > 0 else ''\n\n audits = movie_info_list['audits'][0]['watchGradeNm'] if len(movie_info_list['audits']) > 0 else ''\n \n openDt = datetime.strptime(movie_info_list['openDt'], '%Y%m%d')\n prodCd=\"\"\n prodNm=''\n distCd=''\n distNm=''\n\n if len(movie_info_list['companys']) > 0 :\n for n in movie_info_list['companys']:\n if n['companyPartNm'] == '제작사':\n prodCd = n['companyCd']\n prodNm = n['companyNm']\n break\n for n in movie_info_list['companys']:\n if n['companyPartNm'] == '배급사':\n distCd = n['companyCd']\n distNm = n['companyNm']\n break\n\n\n staffs = movie_info_list['staffs'][0]['peopleNm'] if len(movie_info_list['staffs']) > 0 else ''\n\n query_params={\n 'movieCd' : movie_info_list['movieCd'],\n 'movieNm' : movie_info_list['movieNm'],\n 'movieNmEn' : movie_info_list['movieNmEn'],\n 'prdtYear' : movie_info_list['prdtYear'],\n 'showTm' : movie_info_list['showTm'],\n 'openDt' : openDt,\n 'prdtStatNm' : movie_info_list['prdtStatNm'],\n 'typeNm' : movie_info_list['typeNm'],\n 'nations' : nations,\n 'genre' : genre,\n 'genreSub' : genreSub,\n 'director' : director,\n 'actors1' : actor1,\n 'actors2' : actor2,\n 'actors3' : actor3,\n 'actors4' : actor4,\n 'audits' : audits,\n 'prodCd' : prodCd,\n 'prodNm' : prodNm,\n 'distCd' : distCd,\n 'distNm' : distNm,\n 'staffs' : staffs\n }\n\n select_result = db.execute(select_query, {\"MOVIECD\": moviecd})\n\n if len(select_result) == 0:\n # print(insert_query, query_params)\n db.execute(insert_query, query_params)\n\n print(movie_info_list['movieNm'], \"작업 완료. -----\")\n db.disconnect()\n\n# insert_moviedetail(20124079)\n\n\ndef movie_detail(year):\n db = DbConn()\n sql = \"select moviecd from boxoffice2 where dailydate between TO_DATE('\"+str(year)+\"/01/01', 'YYYY/MM/DD') and TO_DATE('\"+str(year)+\"/12/31', 'YYYY/MM/DD') group by moviecd\"\n print(sql)\n cd_list = db.execute(sql)\n db.disconnect()\n\n for movie_cd in cd_list:\n insert_moviedetail(movie_cd[0])\n\n print(len(cd_list),\"개 인서트 끝~~~~\")\n\n# for i in range(2015,2018):\n# movie_detail(i)\nmovie_detail(2010)\n","sub_path":"test/movie_detail.py","file_name":"movie_detail.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"580767719","text":"from scipy.misc import imsave\r\nimport os\r\nimport nibabel as nb\r\nimport numpy as np\r\nfrom glob import glob\r\n\r\n\r\n\r\ninput_dir = \"D:\\data\\ds000030_tf2\"\r\n\r\noutput_dir = \"D:\\data\\ds000030_tf\"\r\n\r\n\r\ndef process_s(t1w_file):\r\n print(\"processing %s\" % t1w_file)\r\n mask_file = t1w_file.replace(\"_preproc.nii.gz\", \"_brainmask.nii.gz\")\r\n bold_files = sorted(glob(\r\n t1w_file.replace(\"_T1w_preproc.nii.gz\", \"*space-T1w_preproc.nii.gz\")))\r\n bold_niis = [nb.load(bold_file) for bold_file in bold_files]\r\n mask_nii = nb.load(mask_file)\r\n t1w_nii = nb.load(t1w_file)\r\n for i in range(mask_nii.shape[0]):\r\n if mask_nii.dataobj[i, :, :].sum() > 0:\r\n # imsave(mask_file.replace(\".nii.gz\", \"_%03d.png\") % i, np.flipud(mask_nii.dataobj[i, :, :].T))\r\n imsave(t1w_file.replace(\".nii.gz\", \"_%03d.png\") % i,\r\n np.flipud(t1w_nii.dataobj[i, :, :].T))\r\n imsave(bold_files[0].replace(\".nii.gz\", \"_%03d.png\") % i,\r\n np.flipud(bold_niis[0].dataobj[i, :, :].T))\r\n\r\n\r\nfrom joblib import Parallel, delayed\r\n\r\nif __name__ == '__main__':\r\n Parallel(n_jobs=8)(delayed(process_s)(s) for s in glob(os.path.join(input_dir, \"*_T1w_preproc.nii.gz\")))\r\n\r\n","sub_path":"tools/nifit2png.py","file_name":"nifit2png.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"397779178","text":"#!/root/.pyenv/shims/python\n#coding: utf-8\nfrom tencentcloud.common import credential\nfrom tencentcloud.common.profile.client_profile import ClientProfile\nfrom tencentcloud.common.profile.http_profile import HttpProfile\nfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException\nfrom tencentcloud.redis.v20180412 import redis_client, models\nfrom datetime import datetime, timedelta, timezone\nimport getopt, sys, json, wget\n\nutc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)\ncn_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))\ncurrent_bj_time = cn_dt.strftime(\"%Y-%m-%d %H:%M\")\ncurrent_bj_date = cn_dt.strftime(\"%Y-%m-%d\")\nspecifies_bj_time = \"%s 04:\" % current_bj_date\n\n\ncred = credential.Credential(\"AKIDgAPSJzIcaNuCH7J4A4mERRBgw0pVEEI9\", \"lGYaQ0KRPBtKizDJjuqY1FHDzby75oIX\")\nhttpProfile = HttpProfile()\nhttpProfile.endpoint = \"redis.tencentcloudapi.com\"\n\nclientProfile = ClientProfile()\nclientProfile.httpProfile = httpProfile\nclient = redis_client.RedisClient(cred, \"ap-tokyo\", clientProfile)\n\nBackupId = None\n\n\ndef getbackuplist(InstanceId):\n try:\n req = models.DescribeInstanceBackupsRequest()\n params = '{\"InstanceId\":\"%s\"}' % InstanceId\n # print(\"params\",params)\n req.from_json_string(params)\n resp = client.DescribeInstanceBackups(req)\n # print(resp.to_json_string())\n return resp.to_json_string()\n except TencentCloudSDKException as err:\n print(err)\n\n\ndef manualbackup(InstanceId, current_bj_time):\n try:\n req = models.ManualBackupInstanceRequest()\n params = '{\"InstanceId\":\"%s\", \"Remark\": \"%s\"}' % (InstanceId, current_bj_time)\n req.from_json_string(params)\n resp = client.ManualBackupInstance(req)\n print(resp.to_json_string())\n return resp.to_json_string()\n except TencentCloudSDKException as err:\n print(err)\n\n\ndef geturl(InstanceId, BackupId):\n try:\n req = models.DescribeBackupUrlRequest()\n params = '{\"InstanceId\":\"%s\",\"BackupId\":\"%s\"}' % (InstanceId, BackupId)\n req.from_json_string(params)\n resp = client.DescribeBackupUrl(req)\n return resp.to_json_string()\n except TencentCloudSDKException as err:\n print(err)\n\n\ndef usage():\n print(\"Instances ID List:\", instance_ids)\n print('''usage: alice-redis-backup-op.py [options] arg1 ...'\n options:\n -h, Show This Help Message And Exit\n --create At Current Time Create Backup\n --list List All Backup\n --autodown Auto Download The Crontab Backup At 04:00 Everyday\n --download InstanceID BackupID Download Specifies Instance And Specifies Backup\n ''')\n\n\nif __name__ == \"__main__\":\n options = None\n args = None\n tmp_dic = {}\n #instance_ids = {\"172.16.6.3\": \"crs-c3hjmvm8\", \"172.16.6.12\": \"crs-qjdj8zv8\"}\n instance_ids = {\"172.16.6.3\": \"crs-c3hjmvm8\", \"172.16.6.20\": \"crs-qzf91dlm\", \"172.16.6.12\": \"crs-qjdj8zv8\", \"172.16.6.44\": \"crs-n0u1xupg\"}\n if len(sys.argv) == 1:\n usage()\n exit(1)\n try:\n options, args = getopt.getopt(sys.argv[1:], \"h\", ['create', 'list', 'download', 'autodown'])\n except Exception as e:\n print(str(e))\n exit(1)\n for name, value in options:\n if name == '--list':\n for k in instance_ids:\n res = getbackuplist(instance_ids[k])\n tmp_dic.update({k: json.loads(res)['BackupSet']})\n for k, v in tmp_dic.items():\n print(k, instance_ids[k], v[0])\n elif name == '--autodown':\n for k in instance_ids:\n res = getbackuplist(instance_ids[k])\n for each in json.loads(res)['BackupSet']:\n if specifies_bj_time in each['StartTime']:\n url = geturl(instance_ids[k], each['BackupId'])\n tmp_dic.update({k: json.loads(url)['InnerDownloadUrl'][0]})\n print(tmp_dic)\n for k in tmp_dic:\n wget.download(tmp_dic[k],\"/home/www/%s-dump.rdb\" % k)\n elif name == '--create':\n for k in instance_ids:\n res = manualbackup(instance_ids[k], current_bj_time)\n elif name == '--download':\n if len(args) != 2:\n usage()\n exit(255)\n url = json.loads(geturl(args[0], args[1]))['InnerDownloadUrl'][0]\n print('URL:',url)\n for k in instance_ids:\n if instance_ids[k] == args[0]:\n wget.download(url,k)\n elif name == \"-h\":\n usage()\n exit(0)\n\n","sub_path":"git/Alice-test/alice-redis-backup-op.py","file_name":"alice-redis-backup-op.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46040483","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 18 Apr 2018\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nDESCRIPTION\nThe csv_logger_conf utility is used to specify the filesystem path to the log files generated by csv_logger. It also\nspecifies the csv_logger behaviour when the volume becomes full: if delete-oldest is true, the oldest logs are\nremoved to make space, if false, then logging stops. A write-interval parameter may be used to specify time between\nflushes, in order to extend the life of SD cards.\n\nNote that the logging process(es) must be restarted for changes to take effect.\n\nSYNOPSIS\ncsv_logger_conf.py { [-r ROOT_PATH] [-o DELETE_OLDEST] [-i WRITE_INTERVAL] | -d } [-v]\n\nEXAMPLES\n./csv_logger_conf.py -r /srv/removable_data_storage -o 1 -i 0\n\nFILES\n~/SCS/conf/csv_logger_conf.json\n\nDOCUMENT EXAMPLE\n{\"root-path\": \"/srv/removable_data_storage\", \"delete-oldest\": true, \"write-interval\": 0}\n\nSEE ALSO\nscs_dev/csv_logger\n\"\"\"\n\nimport sys\n\nfrom scs_core.csv.csv_logger_conf import CSVLoggerConf\nfrom scs_core.data.json import JSONify\nfrom scs_core.sys.filesystem import Filesystem\n\nfrom scs_host.sys.host import Host\n\nfrom scs_mfr.cmd.cmd_csv_logger_conf import CmdCSVLoggerConf\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n # ----------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdCSVLoggerConf()\n\n if not cmd.is_valid():\n cmd.print_help(sys.stderr)\n exit(2)\n\n if cmd.verbose:\n print(\"csv_logger_conf: %s\" % cmd, file=sys.stderr)\n sys.stderr.flush()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # resources...\n\n # check for existing document...\n conf = CSVLoggerConf.load(Host)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # run...\n\n if cmd.set():\n if conf is None and not cmd.is_complete():\n print(\"csv_logger_conf: No configuration is present - you must therefore set all fields.\", file=sys.stderr)\n cmd.print_help(sys.stderr)\n exit(2)\n\n root_path = conf.root_path if cmd.root_path is None else cmd.root_path\n delete_oldest = conf.delete_oldest if cmd.delete_oldest is None else cmd.delete_oldest\n write_interval = conf.write_interval if cmd.write_interval is None else cmd.write_interval\n\n try:\n Filesystem.mkdir(root_path)\n except PermissionError:\n print(\"csv_logger_conf: You do not have permission to write in that directory.\", file=sys.stderr)\n exit(1)\n\n conf = CSVLoggerConf(root_path, delete_oldest, write_interval)\n conf.save(Host)\n\n elif cmd.delete and conf is not None:\n conf.delete(Host)\n conf = None\n\n if conf:\n print(JSONify.dumps(conf))\n","sub_path":"src/scs_mfr/csv_logger_conf.py","file_name":"csv_logger_conf.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"119319207","text":"# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ------------------------------------------------------------------------------\n\"\"\"This test module contains the tests for CLI Registry fetch methods.\"\"\"\n\nfrom unittest import TestCase, mock\n\nfrom aea.cli.fetch import _fetch_agent_locally\n\nfrom tests.test_cli.tools_for_testing import ContextMock, PublicIdMock\n\n\n@mock.patch(\"aea.cli.fetch.copy_tree\")\n@mock.patch(\"aea.cli.fetch.os.path.join\", return_value=\"joined-path\")\n@mock.patch(\"aea.cli.fetch.try_get_item_source_path\", return_value=\"path\")\n@mock.patch(\"aea.cli.fetch.try_to_load_agent_config\")\nclass FetchAgentLocallyTestCase(TestCase):\n \"\"\"Test case for fetch_agent_locally method.\"\"\"\n\n def test_fetch_agent_locally_positive(\n self,\n try_to_load_agent_config_mock,\n try_get_item_source_path_mock,\n join_mock,\n copy_tree,\n ):\n \"\"\"Test for fetch_agent_locally method positive result.\"\"\"\n _fetch_agent_locally(ContextMock(), PublicIdMock(), ContextMock())\n copy_tree.assert_called_once_with(\"path\", \"joined-path\")\n","sub_path":"tests/test_cli/test_fetch.py","file_name":"test_fetch.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"559320067","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2021.3.24\n\n@author: liu\n\nfrom https://scikit-image.org/docs/dev/auto_examples/edges/plot_active_contours.html\n\"\"\"\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import data, img_as_float\nfrom skimage.segmentation import (morphological_chan_vese,\n morphological_geodesic_active_contour,\n inverse_gaussian_gradient,\n checkerboard_level_set)\nfrom skimage.io import imread, imsave\n\ndef store_evolution_in(lst):\n \"\"\"Returns a callback function to store the evolution of the level sets in\n the given list.\n \"\"\"\n def _store(x):\n lst.append(np.copy(x))\n\n return _store\n\nif __name__ == '__main__':\n fig, axes = plt.subplots(2, 2, figsize=(8, 8))\n ax = axes.flatten()\n\n img_color = imread('data/card.png')\n\n image = (imread('data/card.png', 1)*255)\n image = img_as_float(image)\n gimage = inverse_gaussian_gradient(image)\n\n # Initial level set\n init_ls = np.zeros(image.shape, dtype=np.int8)\n init_ls[10:-10, 10:-10] = 1\n\n # List with intermediate results for plotting the evolution\n evolution = []\n callback = store_evolution_in(evolution)\n ls = morphological_geodesic_active_contour(gimage, 200, init_ls,\n smoothing=1, balloon=-1.2,\n threshold=0.05,\n iter_callback=callback)\n ax[0].imshow(img_color)\n ax[0].set_title(\"original\", fontsize=12)\n ax[1].imshow(img_color)\n\n ax[2].imshow(img_color, cmap=\"gray\")\n ax[2].contour(ls, [0.5], colors='r')\n ax[2].set_title(\"result\", fontsize=12)\n\n ax[3].imshow(img_color)\n ax[3].imshow(ls, cmap=\"gray\")\n\n ax[3].set_axis_off()\n contour = ax[3].contour(evolution[0], [0.5], colors='g')\n contour.collections[0].set_label(\"Iteration 0\")\n contour = ax[3].contour(evolution[100], [0.5], colors='y')\n contour.collections[0].set_label(\"Iteration 100\")\n contour = ax[3].contour(evolution[-1], [0.5], colors='r')\n contour.collections[0].set_label(\"Iteration 200\")\n ax[3].legend(loc=\"upper right\")\n ax[3].set_title('process', fontsize=12)\n\n for i in range(4): ax[i].set_axis_off()\n\n fig.tight_layout()\n plt.show()\n\n gif_list = []\n\n #save gif\n for i in range(11):\n plt.clf()\n plt.imshow(img_color)\n contour = plt.contour(evolution[20*i], [0.5], colors='y')\n plt.axis('off')\n plt.title(\"Iteration %d\"%(20*i))\n plt.savefig('temp.png')\n gif_list.append(imread('temp.png'))\n\n img, *imgs = [Image.fromarray(gif_list[i]) for i in range(len(gif_list))]\n img.save(fp='snake.gif', format='GIF', append_images=imgs,\n save_all=True, duration=1000, loop=0)\n","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"399224420","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport binascii\n\ndef main(files):\n for file in files:\n data = None\n with open(file, 'rb') as f:\n data = f.read()\n\n crc = binascii.crc32(data)\n print('{} - {:08X}'.format(file, crc))\n\n\nif (__name__ == '__main__'):\n main(sys.argv[1:])\n","sub_path":"crc32sum.py","file_name":"crc32sum.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"205495439","text":"import numpy as np\nimport tensorflow as tf\n\nfrom tf2rl.algos.policy_base import OffPolicyAgent\nfrom tf2rl.envs.atari_wrapper import LazyFrames\nfrom tf2rl.misc.target_update_ops import update_target_variables\nfrom tf2rl.misc.huber_loss import huber_loss\n\n\nclass QFunc(tf.keras.Model):\n def __init__(self, state_shape, action_dim, units=[32, 32], name=\"QFunc\", enable_dueling_dqn=False):\n super().__init__(name=name)\n self._enable_dueling_dqn = enable_dueling_dqn\n\n self.l1 = tf.keras.layers.Dense(units[0], name=\"L1\")\n self.l2 = tf.keras.layers.Dense(units[1], name=\"L2\")\n self.l3 = tf.keras.layers.Dense(action_dim, name=\"L3\")\n\n if enable_dueling_dqn:\n self.l4 = tf.keras.layers.Dense(1, name=\"L3\")\n\n with tf.device(\"/cpu:0\"):\n self(inputs=tf.constant(np.zeros(shape=(1,)+state_shape, dtype=np.float64)))\n\n def call(self, inputs):\n features = tf.concat(inputs, axis=1)\n features = tf.nn.relu(self.l1(features))\n features = tf.nn.relu(self.l2(features))\n if self._enable_dueling_dqn:\n advantages = self.l3(features)\n v_values = self.l4(features)\n q_values = v_values + (advantages - tf.reduce_mean(advantages, axis=1, keep_dims=True))\n else:\n q_values = self.l3(features)\n return q_values\n\n\nclass DQN(OffPolicyAgent):\n def __init__(\n self,\n state_shape,\n action_dim,\n q_func=None,\n name=\"DQN\",\n lr=0.001,\n units=[32, 32],\n epsilon=0.1,\n n_warmup=int(1e4),\n target_replace_interval=int(5e3),\n memory_capacity=int(1e6),\n enable_double_dqn=False,\n enable_dueling_dqn=False,\n **kwargs):\n super().__init__(name=name, memory_capacity=memory_capacity, n_warmup=n_warmup, **kwargs)\n\n q_func = q_func if q_func is not None else QFunc\n # Define and initialize Q-function network\n self.q_func = q_func(state_shape, action_dim, units)\n self.q_func_target = q_func(state_shape, action_dim, units)\n self.q_func_optimizer = tf.train.AdamOptimizer(learning_rate=lr)\n update_target_variables(self.q_func_target.weights, self.q_func.weights, tau=1.)\n\n self._action_dim = action_dim\n\n # Set hyperparameters\n self.epsilon = epsilon\n self.target_replace_interval = target_replace_interval\n self.n_update = 0\n\n # DQN variants\n self._enable_double_dqn = enable_double_dqn\n self._enable_dueling_dqn = enable_dueling_dqn\n\n def get_action(self, state, test=False):\n if isinstance(state, LazyFrames):\n state = np.array(state)\n assert isinstance(state, np.ndarray)\n\n if not test and np.random.rand() < self.epsilon:\n action = np.random.randint(self._action_dim)\n else:\n state = np.expand_dims(state, axis=0).astype(np.float64)\n action = self._get_action_body(tf.constant(state))\n action = np.argmax(action)\n\n return action\n\n @tf.contrib.eager.defun\n def _get_action_body(self, state):\n return self.q_func(state)\n\n def train(self, states, actions, next_states, rewards, done, weights=None):\n if weights is None:\n weights = np.ones_like(rewards)\n td_error, q_func_loss = self._train_body(\n states, actions, next_states, rewards, done, weights)\n\n tf.contrib.summary.scalar(name=\"QFuncLoss\", tensor=q_func_loss, family=\"loss\")\n\n # Remove following by using tf.global_step\n self.n_update += 1\n # Update target networks\n if self.n_update % self.target_replace_interval == 0:\n update_target_variables(self.q_func_target.weights, self.q_func.weights, tau=1.)\n\n return td_error\n\n @tf.contrib.eager.defun\n def _train_body(self, states, actions, next_states, rewards, done, weights):\n with tf.device(self.device):\n with tf.GradientTape() as tape:\n td_errors = self._compute_td_error_body(states, actions, next_states, rewards, done)\n q_func_loss = tf.reduce_mean(tf.square(td_errors) * weights * 0.5)\n # q_func_loss = tf.reduce_mean(huber_loss(diff=td_errors) * weights)\n\n q_func_grad = tape.gradient(q_func_loss, self.q_func.trainable_variables)\n self.q_func_optimizer.apply_gradients(zip(q_func_grad, self.q_func.trainable_variables))\n\n return td_errors, q_func_loss\n\n @tf.contrib.eager.defun\n def _compute_td_error_body(self, states, actions, next_states, rewards, done):\n # TODO: Clean code\n not_done = 1. - tf.cast(done, dtype=tf.float64)\n actions = tf.cast(actions, dtype=tf.int32)\n with tf.device(self.device):\n indices = tf.concat(\n values=[tf.expand_dims(tf.range(self.batch_size), axis=1),\n actions], axis=1)\n current_Q = tf.expand_dims(\n tf.gather_nd(self.q_func(states), indices), axis=1)\n\n if self._enable_double_dqn:\n max_q_indexes = tf.argmax(self.q_func(next_states),\n axis=1, output_type=tf.int32)\n # TODO: Reuse predefined `indices`\n indices = tf.concat(\n values=[tf.expand_dims(tf.range(self.batch_size), axis=1),\n tf.expand_dims(max_q_indexes, axis=1)], axis=1)\n target_Q = tf.expand_dims(\n tf.gather_nd(self.q_func_target(next_states), indices), axis=1)\n target_Q = rewards + not_done * self.discount * target_Q\n else:\n target_Q = rewards + not_done * self.discount * tf.reduce_max(\n self.q_func_target(next_states), keepdims=True, axis=1)\n target_Q = tf.stop_gradient(target_Q)\n td_errors = current_Q - target_Q\n return td_errors\n\n @staticmethod\n def get_argument(parser=None):\n import argparse\n if parser is None:\n parser = argparse.ArgumentParser(conflict_handler='resolve')\n parser.add_argument('--enable-double-dqn', action='store_true')\n parser.add_argument('--enable-dueling-dqn', action='store_true')\n return parser\n","sub_path":"tf2rl/algos/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":6357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"650790385","text":"\"\"\"\nCopyright 2018 Skyscanner Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\n\nimport pytest\nimport os\nimport pycfmodel\n\nfrom cfripper.rules.SQSQueuePolicyPublicRule import SQSQueuePolicyPublicRule\nfrom cfripper.s3_adapter import S3Adapter\nfrom cfripper.model.result import Result\n\n\nclass TestSQSQueuePolicyPublicRule:\n\n @pytest.fixture(scope=\"class\")\n def template(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n cf_script = open('{}/test_templates/sqs_policy_public.json'.format(dir_path))\n cf_template = S3Adapter().convert_json_or_yaml_to_dict(cf_script.read())\n return pycfmodel.parse(cf_template)\n \n def test_public(self, template):\n result = Result()\n rule = SQSQueuePolicyPublicRule(None, result)\n\n rule.invoke(template.resources)\n\n assert not result.valid\n assert len(result.failed_rules) == 4\n assert result.failed_rules[0]['reason'] == 'SQS Queue policy QueuePolicyPublic1 is public'\n assert result.failed_rules[1]['reason'] == 'SQS Queue policy QueuePolicyPublic2 is public'\n assert result.failed_rules[2]['reason'] == 'SQS Queue policy QueuePolicyPublic3 is public'\n assert result.failed_rules[3]['reason'] == 'SQS Queue policy QueuePolicyPublic4 is public'\n","sub_path":"tests/test_rules_sqs_policy_public.py","file_name":"test_rules_sqs_policy_public.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"112532219","text":"# -*- coding: utf-8 -*-\n#import smtplib\nfrom django.shortcuts import render\nfrom django import forms\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\n#from email.mime.multipart import MIMEMultipart\n#from email.mime.text import MIMEText\n\n\nfrom studentsdb.settings import ADMIN_EMAIL\n\nclass ContactForm(forms.Form):\n from_email = forms.EmailField(\n label=u\"Enter Your Email Address\")\n\n subject = forms.CharField(\n label = u\"Enter Subject\",\n max_length=128)\n\n message = forms.CharField(\n label=u\"Enter Your Message\",\n widget=forms.Textarea)\n\ndef contact_admin(request):\n # check if form was posted\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = ContactForm(request.POST)\n # check whether user data is valid:\n if form.is_valid():\n # send email\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n from_email = form.cleaned_data['from_email']\n \n try:\n send_mail(subject, message, from_email, [ADMIN_EMAIL])\n\n except Exeption:\n message = u'error sending email'\n\n else:\n message = u'message sent'\n # redirect to same contact page with success message\n return HttpResponseRedirect(\n u'%s?status_message=%s' % (reverse('contact_admin'),message))\n # if there was not POST render blank form\n else:\n form = ContactForm()\n return render(request, 'contact_admin/form.html', {'form': form})","sub_path":"students/views/contact_admin.py","file_name":"contact_admin.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"57354964","text":"\"\"\"\r\nWritten by: Hadi Frohar\r\n\r\nEx3: This program takes from the user an sql file and converts each non-empty table in the file\r\nto csv file (tableName.csv) that has all the values of the table\r\n\r\n\"\"\"\r\nimport os\r\nfiletype = \".csv\" #filetype to convert\r\nlockedTable = None #global variable states which table we we are converting\r\ndefaultFileName = \"demo.sql\" #default file name\r\n\r\n#table class, contains table details such as name, fields, items..\r\nclass Table(object):\r\n def __init__(self, name):\r\n self._name = name\r\n self._items = []\r\n self._fields = []\r\n self._outputFile = None\r\n\r\n def extract(self): #extracts the output file (csv) of the table\r\n if len(self._items) == 0: #means no items in table\r\n return\r\n\r\n #checks if the file already exists, if yes it deletes it\r\n os.remove(self._name+filetype) if os.path.isfile(self._name+filetype) else None\r\n self._outputFile = open(self._name+filetype, 'w') #creates output file\r\n printList(self._fields, self._outputFile) #write fields to output file\r\n for item in self._items: #writes items in table to output file\r\n item.print(self._outputFile)\r\n self._outputFile.close()\r\n\r\n#item class, it contains its fields\r\nclass Item(object):\r\n def __init__(self):\r\n self._fields = []\r\n\r\n def print(self, file): #writes field items to output file\r\n printList(self._fields, file)\r\n\r\n#takes a list (fields) and file, and writes all the list to the file\r\ndef printList(listToPrint, file):\r\n for i in listToPrint:\r\n file.write(i) #write item\r\n file.write(',') #sep items in csv file\r\n file.write('\\n')\r\n\r\n#this function takes a string, substring and then returns substring starts after the passed substring\r\ndef sliceString(string, substr):\r\n return string[string.find(substr)+len(substr):]\r\n\r\n#checks if passed string is number or not\r\ndef isNumber(content):\r\n if not isinstance(content, str):\r\n return\r\n content = content.replace('.', '0', 1) #if it is float then replace dot with 0\r\n if content.isdigit():\r\n return True\r\n return False\r\n\r\n#returns substring that is between the passed char (c), with(True)\\without(False) the char (c)\r\ndef getName(content, c, withChar):\r\n start = content.find(c)\r\n if start == -1: #no substring like this\r\n return content\r\n\r\n if not withChar:\r\n start+=1 #start after the char\r\n\r\n end = start+1\r\n\r\n while content[end] != c:\r\n end+=1\r\n\r\n if withChar:\r\n end+=1 #add the char to substring\r\n\r\n return content[start:end]\r\n\r\n#checks if it is sql table field, we use this function so we don't engage with keys\r\ndef isField(content):\r\n i = 0\r\n while content[i] == ' ':\r\n i+=1\r\n if content[i] == '`':\r\n return True\r\n return False\r\n\r\n#removes table from list, it takes a list and the line (command) which contains the table to remove\r\ndef dropTable(l, content):\r\n tableToDrop = getName(content, '`', False) #gets table name\r\n for i in l:\r\n if i._name == tableToDrop:\r\n l.remove(i)\r\n #os.remove(tableToDrop + filetype) if os.path.isfile(tableToDrop + filetype) else None #removes file\r\n break\r\n\r\n#creates table, it takes file, and line (command) taht contains which table to create\r\ndef createTable(file, content):\r\n tableName = getName(content, '`', False) #gets table name\r\n newTable = Table(tableName) #creates table\r\n content = file.readline()\r\n while isField(content): #reads line by line till we finish all table fields\r\n newTable._fields.append(getName(content, '`', False)) #gets field name and adds it to list\r\n content = file.readline()\r\n return newTable\r\n\r\n#gets the values of item fields (like name), it takes line (insert to command) which has all the values\r\ndef getItemField(content, fields, numOfFields):\r\n if not isinstance(fields, list):\r\n return\r\n i=0\r\n content = sliceString(content, '(') #removes ( from the string\r\n while i < numOfFields and content: #moves on all fields, the line should have numOfFields values\r\n if isNumber( content[:content.find(',')]): #checks if its number so we add it without ''\r\n field = content[0: content.find(',')]\r\n elif content[0] == 'N': #checks if it null\r\n field = 'NULL'\r\n else: #any other value is added with ''\r\n field = getName(content, '\\'', True)\r\n\r\n\r\n fields.append(field)\r\n content = sliceString(content, field + ',') #takes out the value from the line to move for the next value\r\n i += 1\r\n content = sliceString(content, ')') #removes ) from the line, in order we have more than one item in on row\r\n\r\n return content\r\n\r\n#def getTable(tableName, tableList):\r\n#returns the table that is locked (that we are converting)\r\ndef getTable(tableList):\r\n for table in tableList:\r\n if table._name == lockedTable:\r\n return table\r\n return None\r\n\r\n#inserts item to the table (values)\r\ndef insertItem(content, tableList):\r\n #tableName = getName(content, '`', False)\r\n #table=getTable(tableName, tableList)\r\n\r\n table = getTable(tableList) #gets the locked table (that we are converting)\r\n if table == None:\r\n return\r\n\r\n content = sliceString(content, \"VALUES\") #removes VALUES from the line, to start taking the values\r\n x=0\r\n while content.find('(') > 0: #moves on all the items to insert (in case we have more than one in same line)\r\n item = Item() #creates new empty item\r\n content = getItemField(content, item._fields, len(table._fields)) #add values to fields\r\n table._items.append(item) #adds item to table (list of items in table)\r\n x+=1\r\n\r\n#extracts table, creates csv file with the values of the table\r\ndef extractLockedTable(tableList):\r\n global lockedTable\r\n for table in tableList:\r\n if table._name == lockedTable:\r\n table.extract()\r\n #tableList.remove(table)\r\n lockedTable = None #no locked table (unlock command)\r\n break\r\n\r\n#changes the table we are converting\r\ndef lockTables(content):\r\n global lockedTable\r\n lockedTable = getName(content, '`', False)\r\n\r\n\r\n#opens sql file based on user input (or default file)\r\ndef openFile():\r\n global defaultFileName\r\n fileName = input(\"Enter sql file to convert (or empty for default: {}): \".format(defaultFileName))\r\n if fileName.isspace() or fileName == \"\":\r\n fileName = defaultFileName\r\n while not os.path.isfile(fileName):\r\n fileName = input(\"There is no such file {}, enter correct file name: \".format(fileName))\r\n\r\n file = open(fileName, 'r')\r\n return file\r\n\r\n#converts sql file to csv files\r\ndef convert():\r\n file = openFile()\r\n tableList =[] #empty table list\r\n while True: #reads line by line till EOF\r\n content = file.readline()\r\n if not content: #EOF\r\n break\r\n elif \"DROP TABLE IF EXISTS\" in content:\r\n dropTable(tableList, content)\r\n elif \"CREATE TABLE\" in content:\r\n tableList.append(createTable(file, content))\r\n elif \"INSERT INTO\" in content:\r\n insertItem(content, tableList)\r\n elif \"UNLOCK TABLES\" in content:\r\n extractLockedTable(tableList)\r\n elif \"LOCK TABLES\" in content:\r\n lockTables(content)\r\n file.close()\r\n\r\nif __name__ == '__main__':\r\n convert()","sub_path":"ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"501392271","text":"# csv reader - writer παράδειγμα\nimport csv\nvouna = [['Όλυμπος',\t2917,\t'Θεσσαλία'],\n ['Σμόλικας',\t2637,\t'Ήπειρος'],\n [ 'Βόρας',\t2524,\t'Μακεδονία']]\n\nfor v in vouna:\n print(v)\nprint('...writing')\nwith open('vouna.csv', 'wt', encoding='utf-8') as f:\n writer = csv.writer(f, delimiter=';', quoting=csv.QUOTE_NONNUMERIC)\n for v in vouna:\n writer.writerow(v)\n\nprint('...reading')\nwith open('vouna.csv', 'rt', encoding='utf-8') as f:\n reader = csv.reader(f, delimiter=';', quoting=csv.QUOTE_NONNUMERIC)\n for row in reader:\n print(row)\n","sub_path":"data/cds.py","file_name":"cds.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"355883231","text":"'''\r\n*:0到n a* a aa aa\r\n+:1到n a+ a aa aaa\r\n?:可选 a? a\r\n'''\r\n#匹配 a b c 三个字母按顺序从左到右排列, 而且这3个字母都必须至少有一个 abc\r\n#例如 abc aabc abbbccc bca(不匹配)\r\nimport re\r\nre.compile()\r\ns = 'a+b+c+'\r\nstrlist = ['abc','aabc','bbabc','aabbbcccxyz']\r\nfor value in strlist:\r\n x = re.match(s,value)\r\n if x is not None:\r\n # print(x.group())\r\n print(value)\r\n else:\r\n print(\"{}不匹配\".format(value))\r\n\r\n#匹配任意3个数字-任意3个小写字母\r\n'''\r\n123-abc 543-xyz\r\n[0-9]表示任意一个数字 或者\\d\r\n[a-z]表示任意一个字母\r\n'[0-9]'*3+\"-\"+'[a-z]'*3 或者\\d{3} [a-z]*{3}\r\n'''\r\nx = '[0-9]'*3+\"-\"+'[a-z]'*3\r\nnumber = \"123-abcd\"\r\ninter = re.match(x,number)\r\n\r\nif inter is not None and len(number)==7:\r\n print(\"匹配成功\")\r\nelse:\r\n print(\"不匹配\")\r\nprint()\r\n'''\r\n匹配以a到z的26个字母中的任意一个作为前缀(也可以没有这个前缀),\r\n后面至少有一个数字\r\n'''\r\ns = \"[a-z]?[0-9]+\"\r\nse = \"12345是我的最爱,而他最喜欢的是a123\"\r\nq = re.search(s,se)\r\nprint(q.group())\r\nstrlist = ['1234','a123','ab456','b234abc']\r\nfor value in strlist:\r\n m = re.match(s,value)\r\n if m is not None:\r\n print(value)\r\n\r\n","sub_path":"Python学习基础知识/高级python篇/第11章:正则表达式/重复、可选、特殊字符.py","file_name":"重复、可选、特殊字符.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"94070677","text":"#!/usr/bin/env python\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"This adds an expanded text ad using advanced features of upgraded URLs.\"\"\"\n\n\nimport argparse\nimport sys\n\nimport google.ads.google_ads.client\n\n\ndef main(client, customer_id, ad_group_id):\n ad_group_ad_service = client.get_service('AdGroupAdService', version='v2')\n ad_group_service = client.get_service('AdGroupService', version='v2')\n\n # Create ad group ad.\n ad_group_ad_operation = client.get_type('AdGroupAdOperation', version='v2')\n ad_group_ad = ad_group_ad_operation.create\n ad_group_ad.ad_group.value = ad_group_service.ad_group_path(\n customer_id, ad_group_id)\n ad_group_ad.status = client.get_type('AdGroupAdStatusEnum',\n version='v2').PAUSED\n\n # Set expanded text ad info\n final_url = ad_group_ad.ad.final_urls.add()\n final_url.value = 'http://www.example.com/cruise/space/'\n final_url = ad_group_ad.ad.final_urls.add()\n final_url.value = 'http://www.example.com/locations/mars/'\n\n ad_group_ad.ad.expanded_text_ad.description.value = (\n 'Low-gravity fun for everyone!')\n ad_group_ad.ad.expanded_text_ad.headline_part1.value = (\n 'Luxury cruise to Mars')\n ad_group_ad.ad.expanded_text_ad.headline_part2.value = (\n 'Visit the Red Planet in Style.')\n\n # Specify a tracking URL for 3rd party tracking provider. You may specify\n # one at customer, campaign, ad group, ad, criterion, or feed item levels.\n ad_group_ad.ad.tracking_url_template.value = (\n 'http://tracker.example.com/?season={_season}&promocode={_promocode}&'\n 'u={lpurl}'\n )\n\n # Since your tracking URL has two custom parameters, provide their values\n # too. This can be provided at campaign, ad group, ad, criterion, or feed\n # item levels.\n param_1 = ad_group_ad.ad.url_custom_parameters.add()\n param_1.key.value = 'season'\n param_1.value.value = 'easter123'\n\n param_2 = ad_group_ad.ad.url_custom_parameters.add()\n param_2.key.value = 'promocode'\n param_2.value.value = 'nj123'\n\n # Specify a list of final mobile URLs. This field cannot be set if URL field\n # is set, or finalUrls is unset. This may be specified at ad, criterion, and\n # feed item levels.\n final_mobile_url = ad_group_ad.ad.final_mobile_urls.add()\n final_mobile_url.value = 'http://mobile.example.com/cruise/space/'\n final_mobile_url = ad_group_ad.ad.final_mobile_urls.add()\n final_mobile_url.value = 'http://mobile.example.com/locations/mars/'\n\n # Add the ad group ad.\n try:\n ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(\n customer_id, [ad_group_ad_operation])\n except google.ads.google_ads.errors.GoogleAdsException as ex:\n print('Request with ID \"%s\" failed with status \"%s\" and includes the '\n 'following errors:' % (ex.request_id, ex.error.code().name))\n for error in ex.failure.errors:\n print('\\tError with message \"%s\".' % error.message)\n if error.location:\n for field_path_element in error.location.field_path_elements:\n print('\\t\\tOn field: %s' % field_path_element.field_name)\n sys.exit(1)\n\n print('Created expanded text ad %s.'\n % ad_group_ad_response.results[0].resource_name)\n\n\nif __name__ == '__main__':\n # GoogleAdsClient will read the google-ads.yaml configuration file in the\n # home directory if none is specified.\n google_ads_client = (google.ads.google_ads.client.GoogleAdsClient\n .load_from_storage())\n\n parser = argparse.ArgumentParser(\n description=('Adds an expanded text ad to the specified ad group ID, '\n 'for the given customer ID.'))\n # The following argument(s) should be provided to run the example.\n parser.add_argument('-c', '--customer_id', type=str,\n required=True, help='The Google Ads customer ID.')\n parser.add_argument('-a', '--ad_group_id', type=str,\n required=True, help='The ad group ID.')\n args = parser.parse_args()\n\n main(google_ads_client, args.customer_id, args.ad_group_id)\n","sub_path":"examples/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py","file_name":"add_expanded_text_ad_with_upgraded_urls.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"184025282","text":"from data_processing import read_dataset_csv,split_train_test\nfrom models import k_nearest_neighbors\n\ndef main():\n\n dataset_path = \"data/iris.csv\"\n k = 3\n\n df = read_dataset_csv(dataset_path)\n train_set, test_set = split_train_test(df,split=0.70,random_state=0)\n\n knn = k_nearest_neighbors()\n knn.fit(train_set)\n knn.predict(test_set,k=k)\n knn.get_model_info()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"202742522","text":"\"\"\"\r\nFile: chapter02/dweet_led.py\r\n\r\nA Python program to control an LED using the public dweet.io service.\r\n\r\nDependencies:\r\n pip3 install gpiozero pigpio requests\r\n\r\nBuilt and tested with Python 3.7 on Raspberry Pi 4 Model B\r\n\"\"\"\r\nimport signal\r\nimport json\r\nimport os\r\nimport sys\r\nimport logging\r\nfrom gpiozero import Device, LED\r\nfrom gpiozero.pins.pigpio import PiGPIOFactory\r\nfrom time import sleep\r\nfrom uuid import uuid1\r\nimport requests # (1)\r\n\r\n\r\n# Global Variables\r\nLED_GPIO_PIN = 21 # GPIO Pin that LED is connected to\r\nTHING_NAME_FILE = 'thing_name.txt' # The name of our \"thing\" is persisted into this file\r\nURL = 'https://dweet.io' # Dweet.io service API\r\nlast_led_state = None # Current state of LED (\"on\", \"off\", \"blinking\")\r\nthing_name = None # Thing name (as persisted in THING_NAME_FILE)\r\nled = None # GPIOZero LED instance\r\n\r\n\r\n# Initialize Logging\r\nlogging.basicConfig(level=logging.WARNING) # Global logging configuration\r\nlogger = logging.getLogger('main') # Logger for this module\r\nlogger.setLevel(logging.INFO) # Debugging for this file. # (2)\r\n\r\n\r\n# Initialize GPIO\r\nDevice.pin_factory = PiGPIOFactory()\r\n\r\n\r\n# Function Definitions\r\ndef init_led():\r\n \"\"\"Create and initialise an LED Object\"\"\"\r\n global led\r\n led = LED(LED_GPIO_PIN)\r\n led.off()\r\n\r\n\r\ndef resolve_thing_name(thing_file):\r\n \"\"\"Get existing, or create a new thing name\"\"\"\r\n if os.path.exists(thing_file): # (3)\r\n with open(thing_file, 'r') as file_handle:\r\n name = file_handle.read()\r\n logger.info('Thing name ' + name + ' loaded from ' + thing_file)\r\n return name.strip()\r\n else:\r\n name = str(uuid1())[:8] # UUID object to string. # (4)\r\n logger.info('Created new thing name ' + name)\r\n\r\n with open(thing_file, 'w') as f: # (5)\r\n f.write(name)\r\n\r\n return name\r\n\r\n\r\ndef get_latest_dweet():\r\n \"\"\"Get the last dweet made by our thing.\"\"\"\r\n resource = URL + '/get/latest/dweet/for/' + thing_name # (6)\r\n logger.debug('Getting last dweet from url %s', resource)\r\n\r\n r = requests.get(resource) # (7)\r\n\r\n if r.status_code == 200: # (8)\r\n dweet = r.json() # return a Python dict.\r\n logger.debug('Last dweet for thing was %s', dweet)\r\n\r\n dweet_content = None\r\n\r\n if dweet['this'] == 'succeeded': # (9)\r\n # We're just interested in the dweet content property.\r\n dweet_content = dweet['with'][0]['content'] # (10)\r\n\r\n return dweet_content\r\n\r\n else:\r\n logger.error('Getting last dweet failed with http status %s', r.status_code)\r\n return {}\r\n\r\n\r\ndef poll_dweets_forever(delay_secs=2):\r\n \"\"\"Poll dweet.io for dweets about our thing.\"\"\"\r\n while True:\r\n dweet = get_latest_dweet() # (11)\r\n if dweet is not None:\r\n process_dweet(dweet) # (12)\r\n\r\n sleep(delay_secs) # (13)\r\n\r\n\r\ndef stream_dweets_forever():\r\n \"\"\"Listen for streaming for dweets\"\"\"\r\n resource = URL + '/listen/for/dweets/from/' + thing_name\r\n logger.info('Streaming dweets from url %s', resource)\r\n\r\n session = requests.Session()\r\n request = requests.Request(\"GET\", resource).prepare()\r\n\r\n while True: # while True to reconnect on any disconnections.\r\n try:\r\n response = session.send(request, stream=True, timeout=1000)\r\n\r\n for line in response.iter_content(chunk_size=None):\r\n if line:\r\n try:\r\n json_str = line.splitlines()[1]\r\n json_str = json_str.decode('utf-8')\r\n dweet = json.loads(eval(json_str)) # json_str is a string in a string.\r\n logger.debug('Received a streamed dweet %s', dweet)\r\n\r\n dweet_content = dweet['content']\r\n process_dweet(dweet_content)\r\n except Exception as e:\r\n logger.error(e, exc_info=True)\r\n logger.error('Failed to process and parse dweet json string %s', json_str)\r\n\r\n except requests.exceptions.RequestException as e:\r\n # Lost connection. The While loop will reconnect.\r\n #logger.error(e, exc_info=True)\r\n pass\r\n\r\n except Exception as e:\r\n logger.error(e, exc_info=True)\r\n\r\n\r\ndef process_dweet(dweet):\r\n \"\"\"Inspect the dweet and set LED state accordingly\"\"\"\r\n global last_led_state\r\n\r\n if not 'state' in dweet:\r\n return\r\n\r\n led_state = dweet['state']\r\n\r\n if led_state == last_led_state: # (14)\r\n return # LED is already in requested state.\r\n\r\n if led_state == 'on': # (15)\r\n led.on()\r\n elif led_state == 'blink':\r\n led.blink()\r\n else: # Off, including any unhandled state.\r\n led_state = 'off'\r\n led.off()\r\n\r\n if led_state != last_led_state: # (16)\r\n last_led_state = led_state\r\n logger.info('LED ' + led_state)\r\n\r\n\r\ndef print_instructions():\r\n \"\"\"Print instructions to terminal.\"\"\"\r\n print(\"LED Control URLs - Try them in your web browser:\")\r\n print(\" On : \" + URL + \"/dweet/for/\" + thing_name + \"?state=on\")\r\n print(\" Off : \" + URL + \"/dweet/for/\" + thing_name + \"?state=off\")\r\n print(\" Blink : \" + URL + \"/dweet/for/\" + thing_name + \"?state=blink\\n\")\r\n\r\n\r\ndef signal_handler(sig, frame):\r\n \"\"\"Release resources and clean up as needed.\"\"\"\r\n print('You pressed Control+C')\r\n led.off()\r\n sys.exit(0)\r\n\r\n\r\n# Initialise Module\r\nthing_name = resolve_thing_name(THING_NAME_FILE)\r\ninit_led()\r\n\r\n\r\n# Main entry point\r\nif __name__ == '__main__':\r\n signal.signal(signal.SIGINT, signal_handler) # Capture CTRL + C\r\n print_instructions() # (17)\r\n\r\n # Initialise LED from last dweet.\r\n last_dweet = get_latest_dweet() # (18)\r\n if (last_dweet):\r\n process_dweet(last_dweet)\r\n\r\n print('Waiting for dweets. Press Control+C to exit.')\r\n # Only use one of the following. See notes later in Chapter.\r\n # stream_dweets_forever() # Stream dweets real-time.\r\n poll_dweets_forever() # Get dweets by polling a URL on a schedule. # (19)\r\n","sub_path":"modul-praktikum-iot/modul02/dweet_led.py","file_name":"dweet_led.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"232278567","text":"\"\"\"\nAR_CreateVertexMap\n\nAuthor: Arttu Rautio (aturtur)\nWebsite: http://aturtur.com/\nName-US: AR_CreateVertexMap\nVersion: 1.0\nDescription-US: Creates a vertex map tag for selected objects\n\nWritten for Maxon Cinema 4D R21.207\nPython version 2.7.14\n\"\"\"\n# Libraries\nimport c4d\nfrom c4d.modules import mograph as mo\n\n# Functions\ndef GetKeyMod():\n bc = c4d.BaseContainer() # Initialize a base container\n keyMod = \"None\" # Initialize a keyboard modifier status\n # Button is pressed\n if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD,c4d.BFM_INPUT_CHANNEL,bc):\n if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QSHIFT:\n if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL: # Ctrl + Shift\n if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt + Ctrl + Shift\n keyMod = 'Alt+Ctrl+Shift'\n else: # Shift + Ctrl\n keyMod = 'Ctrl+Shift'\n elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt + Shift\n keyMod = 'Alt+Shift'\n else: # Shift\n keyMod = 'Shift'\n elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL:\n if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt + Ctrl\n keyMod = 'Alt+Ctrl'\n else: # Ctrl\n keyMod = 'Ctrl'\n elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt\n keyMod = 'Alt'\n else: # No keyboard modifiers used\n keyMod = 'None'\n return keyMod\n\ndef MakeEditable(op, doc):\n if (not op): return op # Check if object is already editable\n clone = op.GetClone() # Get clone\n doc.AddUndo(c4d.UNDOTYPE_NEW, clone)\n clone.InsertAfter(op) # Insert clone to document\n #clone.SetMg(op.GetMg()) # Copy global matrix\n bc = c4d.BaseContainer() # Initialize Base Container\n op = c4d.utils.SendModelingCommand(c4d.MCOMMAND_MAKEEDITABLE,\n [clone],\n c4d.MODELINGCOMMANDMODE_ALL,\n bc,\n doc,\n c4d.MODELINGCOMMANDFLAGS_CREATEUNDO) # Make editable\n #op = c4d.utils.SendModelingCommand(makeEditable, [clone], 0, bc, doc) # Make editable\n if op: return op[0] # Return object\n else: return None # Otherwise return nothing\n\ndef CreateVertexMap(op, keyMod):\n wtag = op.MakeVariableTag(c4d.Tvertexmap, op.GetPointCount()) # Initialize weight tag\n doc.AddUndo(c4d.UNDOTYPE_NEW, wtag) # Add undo command for inserting new tag\n if keyMod == \"Shift\":\n wtag[c4d.ID_TAGFIELD_ENABLE] = 1 # Enable fields\n fieldObject = mo.FieldObject(440000266) # Initialize 'Linear Field'\n fieldList = wtag[c4d.ID_TAGFIELDS] # Get field list\n fieldLayer = mo.FieldLayer(440000251) # Initialize linear field layer\n fieldLayer.SetLinkedObject(fieldObject) # Link field object to field layer\n fieldList.InsertLayer(fieldLayer) # Add layer to field list\n wtag[c4d.ID_TAGFIELDS] = fieldList # Update fields\n fieldObject.InsertUnder(op) # Insert field object under the object\n doc.AddUndo(c4d.UNDOTYPE_NEW, fieldObject) # Add undo command for inserting new object\n fieldObject.SetBit(c4d.BIT_ACTIVE) # Select field object\n doc.AddUndo(c4d.UNDOTYPE_BITS, op) # Add undo command for changing bits\n op.DelBit(c4d.BIT_ACTIVE) # Deselect operator\n wtag.SetBit(c4d.BIT_ACTIVE) # Select tag\n\ndef main():\n doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document\n doc.StartUndo() # Start recording undos\n\n #try: # Try to execute following script\n keyMod = GetKeyMod() # Get keymodifier\n selection = doc.GetActiveObjects(0) # Get active selection\n for s in selection: # Iterate through selected objects\n if s.GetType() != 5100: # If no polygon object\n e = MakeEditable(s, doc)\n doc.AddUndo(c4d.UNDOTYPE_DELETE, s)\n s.Remove()\n CreateVertexMap(e, keyMod)\n else:\n CreateVertexMap(s, keyMod) # Do the thing\n\n #except: # If something goes wrong\n #pass # Do nothing\n\n doc.EndUndo() # Stop recording undos\n c4d.EventAdd() # Refresh Cinema 4D\n\n# Execute main()\nif __name__=='__main__':\n main()","sub_path":"AR_Scripts_1.0.16_R21_Deprecated/AR_CreateVertexMap.py","file_name":"AR_CreateVertexMap.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"513918834","text":"#未完成,待完善功能有: 1.记录下载失败的文件,重新下载。 2.selenium操作错误处理\n\n\nimport requests\nfrom selenium import webdriver\n\n\ndef start():\n ID = input('输入主播ID号:')\n return 'http://www.lizhi.fm/%s/' % ID\n\n\ndef page():\n urls = []\n names = []\n lists = browser.find_element_by_class_name('js-audio-list').find_elements_by_tag_name('li')\n for L in lists:\n urls.append(L.find_element_by_tag_name('a').get_attribute('data-url'))\n names.append(L.find_element_by_tag_name('a').get_attribute('title'))\n return urls, names\n\n\ndef down(urls, names):\n for url, name in zip(urls, names):\n try:\n with open(name + '.mp3', 'wb') as f:\n f.write(requests.get(url).content)\n except:\n print('下载{}失败',format(name))\n\n\nif __name__ == '__main__':\n browser = webdriver.Chrome()\n browser.maximize_window()\n url = start()\n\n browser.get(url)\n if browser.find_element_by_id('time'):\n print('ID无效,默认下载半岛玫瑰的音频.')\n browser.get('http://www.lizhi.fm/303996/')\n\n while browser.find_element_by_link_text('下一页'):\n down(*page())\n browser.find_element_by_link_text('下一页').click()\n\n print('下载完毕.')\n","sub_path":"005荔枝FM.py","file_name":"005荔枝FM.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"262407818","text":"import numpy as np\nfrom surface import Surface\nfrom water import Water\nfrom plant import Plant\nimport pytest\n\n\n@pytest.fixture\ndef create_surface():\n # filename = 'images/flat.jpg'\n filename = 'images/slope.pny'\n surface = Surface(filename, 3)\n return surface\n\n\n@pytest.fixture\ndef create_water(create_surface):\n surface = create_surface\n water = Water(surface)\n water.add()\n return water\n\n\n@pytest.fixture\ndef create_plant(create_water):\n water = create_water\n plant = Plant(water.surface, water)\n return plant\n\n\ndef test_check_shape_surface(create_surface):\n surface = create_surface\n assert surface.level.shape == (10, 10)\n\n\ndef test_height_water(create_water):\n water = create_water\n assert np.all(water.height == 1)\n\n\ndef test_add_water(create_water):\n water = create_water\n water.add(50)\n assert np.any(water.height == 2)\n\n\ndef test_move_water(create_water):\n water = create_water\n qty = water.height.sum()\n water.move()\n qty_after = water.height.sum()\n assert qty == qty_after\n\n\ndef test_plant_in_surface(create_plant):\n plant = create_plant\n plant.seed(10)\n assert plant.seeds.sum() == 10\n\n\ndef test_plant_grows(create_plant):\n plant = create_plant\n plant.seed(10)\n plant.water.move()\n plant.grow_by_points()\n assert np.any(plant.energy > 0.5)\n\n","sub_path":"test_simulation.py","file_name":"test_simulation.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"641722330","text":"import math\nfrom listaExercicio.uteis.util import Util\n\n\ndef main():\n Util().enunciadoEmDuasPartes(\n 'LER UM NÚMERO INTEIRO. SE O NÚMERO LIDO FOR NEGATIVO, ESCREVA A MENSAGEM “ NÚMERO INVÁLIDO”.',\n 'SE O NÚMERO FOR POSITIVO, CALCULAR O LOGARITMO DESTE NUMERO.', 120)\n\n valor = float(input(f'Digite um numero: ').replace(',', '.'))\n\n if valor >= 0:\n print('O logaritmo de {} na base 10 é de: {} '.format(valor, round(math.log(valor, 10), 4)))\n else:\n print('O Valor deve ser maior positivo')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"exercicio28/exercicio28.py","file_name":"exercicio28.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"326319418","text":"#! /usr/bin/env python\n# encoding UTF-8\n\n'''\nAssignment14Task1 biol7800\nZacCarver 03/15/2016\nThere are 2 chapters of Darwin's Origin of Species in this repository within a\ndirectory entitled task1-files. Write a program that uses argparse and glob to\nopen and read these chapters and some other code to get a list of all words in\neach chapter. Then output, to the command line, a pretty-printed list of the\nfollowing:\n ~the total count of words in Chapter 1\n ~the count of unique words in Chapter 1\n ~the total count of words in Chapter 2\n ~the count of unique words in Chapter 2\n ~the count of words in Chapter 1 that ARE in Chapter 2\n ~the count of words in Chapter 1 that ARE NOT in Chapter 2\n ~the count of words in Chapter 2 that ARE NOT in Chapter 1\n'''\n\nimport argparse\nfrom collections import Counter\nimport glob\nimport os\nimport re\n\n\ndef args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--directory\", type=str,\n help=\"provide a path to a couple of files\")\n return parser.parse_args()\n\n'''\ndef clean(f):\n txt = re.sub(r'\\W+', ' ', f)\n txt = txt.lower()\n return txt\n'''\n\n\ndef ls(f):\n with open(f, 'r') as txt:\n txt = txt.read().lower()\n txt = re.sub(r'\\W+', ' ', txt)\n txt = re.sub('[.]', ' ', txt)\n ls = list(txt.split())\n return ls\n\n\ndef uni(f, ls):\n s = set(ls)\n counts = Counter()\n counts.update(s)\n print('{} words are unique to {}'.format(len(counts), f))\n\n\ndef setting(ls):\n s = set(ls)\n return s\n\n\ndef main():\n arg = args()\n files = glob.glob(os.path.join(arg.directory, '*.txt'))\n files = sorted(files)\n f1 = files[0]\n f2 = files[1]\n #txt = clean(f1)\n #txt2 = clean(f2)\n ls1 = ls(f1)\n ls2 = ls(f2)\n uni(f1, ls1)\n uni(f2, ls2)\n s1 = setting(ls1)\n s2 = setting(ls2)\n same = s1.intersection(s2)\n diff = s1.difference(s2)\n diff2 = s2.difference(s1)\n print('words that are shared between both files: {}'.format(len(same)))\n print('words that are unique to file one: {}'.format(len(diff)))\n print('words that are unique to file two: {}'.format(len(diff2)))\n print('total # of words in file1: {}'.format(len(ls1)))\n print('total # of words in file2: {}'.format(len(ls2)))\n\nif __name__ == '__main__':\n main()\n","sub_path":"answers/zcarver/A14T1.py","file_name":"A14T1.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"70737133","text":"import sys\r\nimport os\r\nimport pandas as pd\r\nimport xlrd\r\nimport re\r\nimport numpy as np\r\n\r\ndef getCompName(inputFileName): # just working with name here\r\n workBook = xlrd.open_workbook(inputFileName)\r\n workSheet = workBook.sheet_by_index(0)\r\n inputString = str(workSheet.cell(0, 0))\r\n splatString = re.split('for | as', inputString)\r\n compName = splatString[1]\r\n return compName\r\n\r\n\r\ndef readFromFile(inputFile, frames): # only working with name here\r\n companyName = getCompName(inputFile)\r\n df = pd.read_excel(inputFile, skiprows=0, header=1)\r\n df['Category'].replace('', np.nan, inplace=True)\r\n df.dropna(subset=['Category'], inplace=True)\r\n df = df[df.Category != 'Non ITO']\r\n df = df[df.Category != 'Category']\r\n df.insert(0, \"Company\", [companyName] * len(df), True)\r\n frames.append(df)\r\n\r\n\r\nif __name__ == '__main__':\r\n directory = sys.argv[1]\r\n xls_files = os.listdir(directory)\r\n frames = []\r\n for file in xls_files:\r\n readFromFile(directory + '\\\\' + file, frames)\r\n final_table = pd.concat(frames)\r\n final_table.to_excel('myOutPut.xlsx')\r\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"542828080","text":"#coding:utf-8\nimport json\n\n#dict转换成json字符串\nd=dict(name=\"Bob\",age=20,score=100)\nj=json.dumps(d)\nprint(j)\n\n#json字符串转换成dict\nj='{\"name\":\"Bob\",\"age\":20,\"score\":100}'\nd=json.loads(j)\nprint(d)\n\nclass Student(object):\n\tdef __init__(self,name,age,score):\n\t\tself.name=name\n\t\tself.age=age\n\t\tself.score=score\n\t\t\ndef student_dict(std):\n\treturn {\n\t\t\"name\":std.name,\n\t\t\"age\":std.age,\n\t\t\"score\":std.score\n\t}\n\t\ns=Student(\"Bob\",20,100)\nprint(json.dumps(s,default=student_dict))\n#不需要自己写函数,直接把对象转换成dict\nprint(json.dumps(s,default=lambda obj:obj.__dict__))","sub_path":"pythonAPI/29.json.py","file_name":"29.json.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236272711","text":"with open('nomes.txt') as nome:\r\n with open('notas.txt') as nota:\r\n with open('troca_de_nota,txt', 'w')as saida:\r\n nome = list(nome)\r\n nota = list(nota)\r\n def troca(nome_inserido,nota_antiga,nota_nova): \r\n \r\n cont= 0\r\n for posicao in nome:\r\n if nome_inserido == posicao:\r\n break\r\n cont += 1\r\n\r\n cont1= 0\r\n for lugar in nota:\r\n if cont1 == cont:\r\n lugar= lugar.replace(nota_antiga,nota_nova)\r\n cont1 += 1\r\n return lugar\r\n \r\n print(troca('Kevin','8','0'))","sub_path":"listas/lista-de-exercicio-06/questao05.py","file_name":"questao05.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"451491724","text":"def resolve():\n N, Y = list(map(int, input().split(\" \")))\n for i in range(N+1):\n for j in range(N-i+1):\n k = N - i - j\n total = 10000*i + 5000*j + 1000*k\n if total == Y:\n print(\"{} {} {}\".format(i, j, k))\n return\n print(\"-1 -1 -1\")\n\n\n\nif '__main__' == __name__:\n resolve()","sub_path":"ABC085/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"52177507","text":"# Коллекционные включения позволяют эффективнее создавать коллекции\n\n# 1. Формирование списка чисел от 1 до 100, оканчивающихся на 1\n\n# Стандартный способ\nnums = tuple(range(100))\n\nlst = []\nfor i in nums:\n if i % 10 == 1:\n lst.append(i)\n\n# Списковое включение\nlst2 = [i for i in nums if i % 10 == 1]\n\nprint(lst == lst2) # True\n\n# 2. В Python коллекционные включения также доступны и для других типов\n\n# Словарь\n# Определяем слова и их длину\nwords = \"Без труда не вытащишь и рыбку из пруда\"\n\nstats = {w.lower(): len(w) for w in words.split()}\nprint(stats) # {'вытащишь': 8, 'рыбку': 5, 'не': 2, 'пруда': 5,\n # 'и': 1, 'из': 2, 'без': 3, 'труда': 5}\n","sub_path":"yuripetrov.pythonanywhere.com/_downloads/04_01_11.py","file_name":"04_01_11.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332817738","text":"import logging\r\nfrom queue import Queue\r\nfrom threading import Thread\r\nfrom telegram import Bot\r\nfrom telegram.ext import Dispatcher, MessageHandler, Updater\r\nimport urllib.request\r\nfrom bs4 import BeautifulSoup\r\n\r\nTOKEN = '269537018:AAGvoqX5V8SGNH3BGfQb6ce2Ykxzwzonieg'\r\n#Texts\r\nstartMsg = \"Ciao! Sono un'intelligenza artificiale molto affamata. Come te, probabilmente. Scrivi /menu per sapere il menu di oggi.\"\r\nmenuMsg = \"Ecco cosa c'è da mangiare oggi, a pranzo e a cena.\"\r\n#ADISU web page\r\nbaseUrl = \"http://www.adisu.sa.it/\"\r\nwebpageUrl = \"http://www.adisu.sa.it/4/servizi-edisu/ristorazione/menu-del-giorno.html\"\r\n\r\n#For command 'start'\r\ndef start(bot, update):\r\n bot.sendMessage(chat_id=update.message.chat_id, text=startMsg)\r\n\r\n\r\ndef menu(bot, update):\r\n bot.sendMessage(chat_id=update.message.chat_id, text=menuMsg)\r\n #Loop through all the PDFs\r\n for li in soup.findAll('li', {\"class\": \"ddl-file-list-item\"}):\r\n #Create file name\r\n fileName = str(li.a['href']).replace('fileadmin/user_upload/menu/', '')\r\n print(\"Trovato file: \"+fileName)\r\n print(\"Download...\")\r\n \r\n #Download the pdf\r\n with urllib.request.urlopen(baseUrl+li.a['href']) as response, open(fileName, 'wb') as out_file:\r\n data = response.read()\r\n out_file.write(data)\r\n\r\n if 'PREZZI' not in fileName:\r\n document = open(fileName, 'rb')\r\n print(\"Invio documento \"+fileName)\r\n bot.sendDocument(chat_id=update.message.chat_id, document=document)\r\n\r\n\r\ndef setup(webhook_url=None):\r\n \"\"\"If webhook_url is not passed, run with long-polling.\"\"\"\r\n logging.basicConfig(level=logging.WARNING)\r\n #BeautifulSoup config\r\n page = urllib.request.urlopen(webpageUrl).read()\r\n soup = BeautifulSoup(page, 'html.parser')\r\n \r\n if webhook_url:\r\n bot = Bot(TOKEN)\r\n update_queue = Queue()\r\n dp = Dispatcher(bot, update_queue)\r\n else:\r\n updater = Updater(TOKEN)\r\n bot = updater.bot\r\n dp = updater.dispatcher\r\n dp.add_handler(CommandHandler('/start', start))\r\n dp.add_handler(CommandHandler('/menu', menu))\r\n # Add your handlers here\r\n if webhook_url:\r\n bot.set_webhook(webhook_url=webhook_url)\r\n thread = Thread(target=dp.start, name='dispatcher')\r\n thread.start()\r\n return update_queue, bot\r\n else:\r\n bot.set_webhook() # Delete webhook\r\n updater.start_polling()\r\n updater.idle()\r\n\r\n\r\nif __name__ == '__main__':\r\n setup()\r\n\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"186283356","text":"#### ====================================================================================================================== ####\r\n############# ENEMY_CLASS #############\r\n#### ====================================================================================================================== ####\r\n\r\nimport csv\r\n\r\ndef csv_loader(filename, readall=False):\r\n ''' Helper function that reads in a CSV file. Optional flag for including header row.\r\n Input: filename (string), bool_flag (optional)\r\n Output: List of Rows (comma separated)\r\n '''\r\n returnList = []\r\n with open(filename) as csvfile:\r\n for row in csv.reader(csvfile):\r\n returnList.append(row)\r\n if readall:\r\n return returnList\r\n else:\r\n return returnList[1:]\r\n\r\n\r\nclass Enemy:\r\n # Represents common data for all enemies - only loaded once, not per new Enemy (Class Variable)\r\n enemy_data = {}\r\n for enemy in csv_loader(\"data/enemies.csv\"):\r\n enemy_data[enemy[0]] = { \"name\": enemy[1], \"health\": int(enemy[2]), \"damage\": int(enemy[3]), \"armor\": int(enemy[4]), \"description\": enemy[5], \"end\": enemy[6], \"reward\": enemy[7]}\r\n\r\n def __init__(self, enemy_type):\r\n self.name = Enemy.enemy_data[enemy_type][\"name\"]\r\n self.health = Enemy.enemy_data[enemy_type][\"health\"]\r\n self.damage = Enemy.enemy_data[enemy_type][\"damage\"]\r\n self.armor = Enemy.enemy_data[enemy_type][\"armor\"]\r\n self.description = Enemy.enemy_data[enemy_type][\"description\"]\r\n self.end = Enemy.enemy_data[enemy_type][\"end\"]\r\n self.reward = Enemy.enemy_data[enemy_type][\"reward\"]\r\n\r\n#### ====================================================================================================================== ####\r\n############# ENEMY_FUNCTIONS #############\r\n#### ====================================================================================================================== ####\r\n","sub_path":"Test Based Adventure Game/enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"49647054","text":"import sys, os \nINTERP = \"/home/bhadmin13/opt/python-3.6.0/bin/python\"\n\nif sys.executable != INTERP:\n xsys = sys.executable\n if sys.executable != INTERP:os.execl(INTERP, INTERP, *sys.argv)\n\n\n\ncwd = os.getcwd()\nmyapp_directory = cwd + '/relix2'\n\n#os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"relix2.settings\")\nos.environ['DJANGO_SETTINGS_MODULE'] = \"relix2.settings\"\n\nsys.path.insert(0,myapp_directory)\nsys.path.append(os.getcwd())\n\nsys.path.insert(0,'$HOME/opt/python-3.6.0/lib/python3.6/site-packages')\nsys.path.insert(0,'$HOME/opt/python-3.6.0/lib/python3.6/site-packages/django')\n\n\nspp = sys.path\n \n#from paste.exceptions.errormiddleware import ErrorMiddleware\nimport django.core.handlers.wsgi\n##this is the line that triggers the \"Apps aren't loaded yet.\" error\n#application = django.core.handlers.wsgi.WSGIHandler()\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n\n# To cut django out of the loop, comment the above application = ... line ,\n# and remove \"test\" from the below function definition.\ndef TESTapplication(environ, start_response):\n status = '200 OK'\n output = 'Hello HEAVILY VUNKY World! Running Python version ' + sys.version + '\\n\\n'\n response_headers = [('Content-type', 'text/plain'),\n ('Content-Length', str(len(output)))]\n # to test paste's error catching prowess, uncomment the following line\n # while this function is the \"application\"\n #raise(\"error\")\n start_response(status, response_headers)\n return [output]\n\n#application = ErrorMiddleware(application, debug=True)\n\n\n\n \n","sub_path":"relix/pass_others/6allowedhosts_pass.py","file_name":"6allowedhosts_pass.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"230084449","text":"import numpy as np\nimport random\nimport copy\nfrom collections import namedtuple, deque\nfrom pprint import pprint\n\nfrom model import Actor, Critic\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nBUFFER_SIZE = int(1e6) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR_ACTOR = 1e-4 # learning rate of the actor \nLR_CRITIC = 1e-3 # learning rate of the critic\nWEIGHT_DECAY = 0. # L2 weight decay\nFC1_UNITS = 400 # Number of hidden units for the first hidden layer of the Actor and Critic networks\nFC2_UNITS = 300 # Number of hidden units fro the second hidden layer of the Actor and Critic networks\n\n## Added by Ray\nUPDATE_EVERY = 20 # At every multiple of this value, we update our actor and critic\nNUM_ITERS_LEARN = 10 # When we finally do the update, we run the learning process this many times\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass Agents():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n \n def __init__(self, state_size, action_size, num_agents, random_seed, config: dict = {}):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n num_agents (int): number of agents\n random_seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.num_agents = num_agents # Added by Ray - store the number of agents\n self.seed = random.seed(random_seed)\n self.num_timesteps = 0 # Added by Ray - store the number of timesteps every time we step\n self.config = {'batch_size': BATCH_SIZE, 'buffer_size': BUFFER_SIZE, 'gamma': GAMMA,\n 'tau': TAU, 'lr_actor': LR_ACTOR, 'lr_critic': LR_CRITIC, 'weight_decay': WEIGHT_DECAY,\n 'update_every': UPDATE_EVERY, 'num_iters_learn': NUM_ITERS_LEARN, 'fc1_units': FC1_UNITS,\n 'fc2_units': FC2_UNITS}\n\n if len(config) != 0:\n print('Using user-defined parameters')\n for k in config:\n if k.lower() in config:\n self.config[k.lower()] = config[k.lower()]\n else:\n print('Using default hyperparameters')\n\n pprint(self.config)\n\n # Actor Network (w/ Target Network)\n ## Note - Each agent's states and actions come from Unity as independent observations of the same\n ## environment so we can simply use one Actor and Critic and the batch size is simply the number\n ## of agents in play\n self.actor_local = Actor(state_size, action_size, random_seed, fc1_units=self.config['fc1_units'], fc2_units=self.config['fc2_units']).to(device)\n self.actor_target = Actor(state_size, action_size, random_seed, fc1_units=self.config['fc1_units'], fc2_units=self.config['fc2_units']).to(device)\n self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=self.config['lr_actor'])\n\n # Critic Network (w/ Target Network)\n ## Note - Each agent's states and actions come from Unity as independent observations of the same\n ## environment so we can simply use one Actor and Critic and the batch size is simply the number\n self.critic_local = Critic(state_size, action_size, random_seed, fcs1_units=self.config['fc1_units'], fc2_units=self.config['fc2_units']).to(device)\n self.critic_target = Critic(state_size, action_size, random_seed, fcs1_units=self.config['fc1_units'], fc2_units=self.config['fc2_units']).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=self.config['lr_critic'], weight_decay=self.config['weight_decay'])\n\n # Noise process\n self.noise = OUNoise(action_size, random_seed)\n\n # Replay memory - note: all agents share this memory\n self.memory = ReplayBuffer(self.config['buffer_size'], self.config['batch_size'], random_seed)\n \n def step(self, states, actions, rewards, next_states, dones):\n \"\"\"Save experiences in replay memory, and use random sample from buffer to learn.\"\"\"\n\n ## Added by Ray - Sanity checks to make sure the incoming lengths and shapes make sense\n assert(states.shape[0] == self.num_agents)\n assert(states.shape[1] == self.state_size)\n assert(next_states.shape[0] == self.num_agents)\n assert(next_states.shape[1] == self.state_size)\n assert(actions.shape[0] == self.num_agents)\n assert(actions.shape[1] == self.action_size)\n assert(len(rewards) == self.num_agents)\n assert(len(dones) == self.num_agents)\n\n ## Modified by Ray\n # Save experiences / rewards - iterate through each SARSD tuple from each agent, add it into\n # the memory\n for state, action, reward, next_state, done in zip(states, actions, rewards, next_states, dones):\n self.memory.add(state, action, reward, next_state, done)\n\n # Increment counter and reset if necessary\n self.num_timesteps = (self.num_timesteps + 1) % self.config['update_every']\n\n # Learn, if enough samples are available in memory\n if len(self.memory) >= self.config['batch_size']:\n ## Added by Ray -\n # If we reach the number of timesteps needed to update...\n if self.num_timesteps == 0:\n # Update the parameters for NUM_ITERS_LEARN times\n for _ in range(self.config['num_iters_learn']):\n experiences = self.memory.sample()\n self.learn(experiences, self.config['gamma'])\n \n def act(self, states, add_noise=True):\n \"\"\"Returns actions for given state as per current policy.\"\"\"\n ## Added by Ray - Sanity checks to make sure the incoming lengths and shapes make sense\n assert(states.shape[0] == self.num_agents)\n assert(states.shape[1] == self.state_size)\n\n # Convert input states into Tensor\n states = torch.from_numpy(states).float().to(device)\n\n # Set Actor network to eval mode due to Batch Norm\n self.actor_local.eval()\n\n # Now collect the actions\n with torch.no_grad():\n ## Output should be num_agents x num_actions\n actions = self.actor_local(states).cpu().data.numpy()\n \n # Now set to train mode again for training\n self.actor_local.train()\n\n ## Modified by Ray - Iterate through each action and add noise to it\n if add_noise:\n final_actions = [action + self.noise.sample() for action in actions]\n else:\n # Just keep a view of it if we haven't added any noise\n final_actions = actions\n\n # Stack the NumPy arrays together to generate a num_agents x num_actions array\n final_actions = np.vstack(actions)\n return np.clip(final_actions, -1, 1)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self, experiences, gamma):\n \"\"\"Update policy and value parameters using given batch of experience tuples.\n Q_targets = r + γ * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # ---------------------------- update critic ---------------------------- #\n # Get predicted next-state actions and Q values from target models\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n # Compute Q targets for current states (y_i)\n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))\n # Compute critic loss\n Q_expected = self.critic_local(states, actions)\n critic_loss = F.mse_loss(Q_expected, Q_targets)\n # Minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n\n ## Added by Ray - Perform gradient clipping for more stability\n torch.nn.utils.clip_grad_norm_(self.critic_local.parameters(), 1)\n self.critic_optimizer.step()\n\n # ---------------------------- update actor ---------------------------- #\n # Compute actor loss\n actions_pred = self.actor_local(states)\n actor_loss = -self.critic_local(states, actions_pred).mean()\n # Minimize the loss\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # ----------------------- update target networks ----------------------- #\n self.soft_update(self.critic_local, self.critic_target, self.config['tau'])\n self.soft_update(self.actor_local, self.actor_target, self.config['tau']) \n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model: PyTorch model (weights will be copied from)\n target_model: PyTorch model (weights will be copied to)\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n\nclass OUNoise:\n \"\"\"Ornstein-Uhlenbeck process.\"\"\"\n\n def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2):\n \"\"\"Initialize parameters and noise process.\"\"\"\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.seed = random.seed(seed)\n self.reset()\n\n def reset(self):\n \"\"\"Reset the internal state (= noise) to mean (mu).\"\"\"\n self.state = copy.copy(self.mu)\n\n def sample(self):\n \"\"\"Update internal state and return it as a noise sample.\"\"\"\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))])\n self.state = x + dx\n return self.state\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n Params\n ======\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n \"\"\"\n self.memory = deque(maxlen=buffer_size) # internal memory (deque)\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n \n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n \n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)\n\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)","sub_path":"p2_continuous-control/ddpg_agent.py","file_name":"ddpg_agent.py","file_ext":"py","file_size_in_byte":12137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"349114531","text":"number=input()\nstr=input()\nlist1=str.split(\" \")\ncontain=[]\nresult=[]\nfor i in list1:\n contain.append(i)\n length=len(contain)\n father=\"\".join(contain)\n for j in range(1,length+1):\n for n in range(length-j+1):\n son=father[n:n+j]\n result.append(son)\n someone=set(result)\n print(len(someone))\n result.clear()","sub_path":"Code/CodeRecords/2178/60760/247691.py","file_name":"247691.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"77580209","text":"import django\nimport time\n\nfrom autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory\nfrom collections import deque\nfrom twisted.internet import reactor\n\nfrom channels import Channel, channel_backends, DEFAULT_CHANNEL_BACKEND\n\n\nclass InterfaceProtocol(WebSocketServerProtocol):\n \"\"\"\n Protocol which supports WebSockets and forwards incoming messages to\n the websocket channels.\n \"\"\"\n\n def onConnect(self, request):\n self.channel_backend = channel_backends[DEFAULT_CHANNEL_BACKEND]\n self.request_info = {\n \"path\": request.path,\n \"GET\": request.params,\n }\n\n def onOpen(self):\n # Make sending channel\n self.reply_channel = Channel.new_name(\"!websocket.send\")\n self.request_info[\"reply_channel\"] = self.reply_channel\n self.last_keepalive = time.time()\n self.factory.protocols[self.reply_channel] = self\n # Send news that this channel is open\n Channel(\"websocket.connect\").send(self.request_info)\n\n def onMessage(self, payload, isBinary):\n if isBinary:\n Channel(\"websocket.receive\").send(dict(\n self.request_info,\n content = payload,\n binary = True,\n ))\n else:\n Channel(\"websocket.receive\").send(dict(\n self.request_info,\n content = payload.decode(\"utf8\"),\n binary = False,\n ))\n\n def serverSend(self, content, binary=False, **kwargs):\n \"\"\"\n Server-side channel message to send a message.\n \"\"\"\n if binary:\n self.sendMessage(content, binary)\n else:\n self.sendMessage(content.encode(\"utf8\"), binary)\n\n def serverClose(self):\n \"\"\"\n Server-side channel message to close the socket\n \"\"\"\n self.sendClose()\n\n def onClose(self, wasClean, code, reason):\n if hasattr(self, \"reply_channel\"):\n del self.factory.protocols[self.reply_channel]\n Channel(\"websocket.disconnect\").send(self.request_info)\n\n def sendKeepalive(self):\n \"\"\"\n Sends a keepalive packet on the keepalive channel.\n \"\"\"\n Channel(\"websocket.keepalive\").send(self.request_info)\n self.last_keepalive = time.time()\n\n\nclass InterfaceFactory(WebSocketServerFactory):\n \"\"\"\n Factory which keeps track of its open protocols' receive channels\n and can dispatch to them.\n \"\"\"\n\n # TODO: Clean up dead protocols if needed?\n\n def __init__(self, *args, **kwargs):\n super(InterfaceFactory, self).__init__(*args, **kwargs)\n self.protocols = {}\n\n def reply_channels(self):\n return self.protocols.keys()\n\n def dispatch_send(self, channel, message):\n if message.get(\"close\", False):\n self.protocols[channel].serverClose()\n else:\n self.protocols[channel].serverSend(**message)\n\n\nclass WebsocketTwistedInterface(object):\n \"\"\"\n Easy API to run a WebSocket interface server using Twisted.\n Integrates the channel backend by running it in a separate thread, using\n the always-compatible polling style.\n \"\"\"\n\n def __init__(self, channel_backend, port=9000):\n self.channel_backend = channel_backend\n self.port = port\n\n def run(self):\n self.factory = InterfaceFactory(\"ws://0.0.0.0:%i\" % self.port, debug=False)\n self.factory.protocol = InterfaceProtocol\n reactor.listenTCP(self.port, self.factory)\n reactor.callInThread(self.backend_reader)\n reactor.callLater(1, self.keepalive_sender)\n reactor.run()\n\n def backend_reader(self):\n \"\"\"\n Run in a separate thread; reads messages from the backend.\n \"\"\"\n while True:\n channels = self.factory.reply_channels()\n # Quit if reactor is stopping\n if not reactor.running:\n return\n # Don't do anything if there's no channels to listen on\n if channels:\n channel, message = self.channel_backend.receive_many(channels)\n else:\n time.sleep(0.1)\n continue\n # Wait around if there's nothing received\n if channel is None:\n time.sleep(0.05)\n continue\n # Deal with the message\n self.factory.dispatch_send(channel, message)\n\n def keepalive_sender(self):\n \"\"\"\n Sends keepalive messages for open WebSockets every\n (channel_backend expiry / 2) seconds.\n \"\"\"\n expiry_window = int(self.channel_backend.expiry / 2)\n for protocol in self.factory.protocols.values():\n if time.time() - protocol.last_keepalive > expiry_window:\n protocol.sendKeepalive()\n reactor.callLater(1, self.keepalive_sender)\n","sub_path":"channels/interfaces/websocket_twisted.py","file_name":"websocket_twisted.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401966427","text":"r\"\"\"\n--- GNU APL (all-permissive license)\n--- https://www.gnu.org/licenses/license-list.html#GNUAllPermissive\n\nCopyright (C) 2018 Hiroki Horiuchi \n\nCopying and distribution of this file, with or without modification,\nare permitted in any medium without royalty\nprovided the copyright notice and this notice are preserved.\nThis file is offered as-is, without any warranty.\n\"\"\"\n\nfrom unittest import TestCase\n\nfrom ....cm.shallow_bind import shallow_bind, shallow_bind_kw\n\n\nclass Dict(dict):\n @property\n def __dict__(self):\n return self\n\n dict_copy = dict.copy\n\n\nclass Obj(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n def dict_copy(self):\n return dict(**self.__dict__)\n\n\nclass T(TestCase):\n def test0no_kw0dict(self):\n self._0no_kw(Dict())\n\n def test0no_kw1obj(self):\n self._0no_kw(Obj())\n\n def test1kw0dict(self):\n self._1kw(Dict())\n\n def test1kw1obj(self):\n self._1kw(Obj())\n\n def _0no_kw(self, feed):\n feed.__init__(a=0, z=9)\n expected = (True,) * 3\n namespace = feed.dict_copy()\n e0 = dict(a=1, b=2, z=9)\n e1 = dict(a=1, b=2)\n e2 = feed.dict_copy()\n with shallow_bind(namespace, dict(a=1, b=2)):\n a0 = e0 == namespace\n with shallow_bind(namespace, dict(a=1, b=2), delete=(r'z',)):\n a1 = e1 == namespace\n a2 = e2 == namespace\n actual = a0, a1, a2\n self.assertEqual(expected, actual)\n\n def _1kw(self, feed):\n r\"\"\"\n Copy+paste of _0no_kw. Not to optimize too much.\n \"\"\"\n feed.__init__(a=0, z=9)\n expected = (True,) * 3\n namespace = feed.dict_copy()\n e0 = dict(a=1, b=2, z=9)\n e1 = dict(a=1, b=2)\n e2 = feed.dict_copy()\n with shallow_bind_kw(namespace, a=1, b=2):\n a0 = e0 == namespace\n with shallow_bind_kw(namespace, (r'z',), a=1, b=2):\n a1 = e1 == namespace\n a2 = e2 == namespace\n actual = a0, a1, a2\n self.assertEqual(expected, actual)\n","sub_path":"x19290/test/cm/shallow_bind/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"599838260","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Sort',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sort_name', models.CharField(max_length=20, verbose_name='\\u5206\\u7c7b\\u540d\\u79f0')),\n ('belong', models.IntegerField(verbose_name='\\u5c5e\\u4e8e', choices=[(0, '\\u535a\\u5ba2'), (1, '\\u6536\\u85cf')])),\n ],\n options={\n 'db_table': 'sort',\n 'verbose_name': '\\u5206\\u7c7b',\n 'verbose_name_plural': '\\u5206\\u7c7b',\n },\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('tag_name', models.CharField(max_length=10, verbose_name='\\u5206\\u7c7b\\u540d\\u79f0')),\n ('belong', models.IntegerField(verbose_name='\\u5c5e\\u4e8e', choices=[(0, '\\u535a\\u5ba2'), (1, '\\u6536\\u85cf')])),\n ],\n options={\n 'db_table': 'tag',\n 'verbose_name': '\\u6807\\u7b7e',\n 'verbose_name_plural': '\\u6807\\u7b7e',\n },\n ),\n ]\n","sub_path":"apps/common/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130169986","text":"import os\t\t\t\t\t\t\t\t\t\t\t\t# Used for shifting the path of templates\nimport re\t\t\t\t\t\t\t\t\t\t\t\t# Used for regular expressions\nimport random\t\t\t\t\t\t\t\t\t\t\t# Used for creating random letters while salting the passwords\nimport webapp2\nimport jinja2\t\t\t\t\t\t\t\t\t\t\t# Used for templates\nimport hmac\t\t\t\t\t\t\t\t\t\t\t\t# hmac is used for securing the cookie. User can't cheat you now!\nimport hashlib\t\t\t\t\t\t\t\t\t\t\t# hashlib is used for hashing the passwords\nimport json\nimport logging\nimport string\nimport time\n\nfrom string import letters\nfrom google.appengine.ext import db\t\t\t\t\t\t# promotes usage of GQL database\nfrom validities import *\nfrom Static import *\nfrom BaseHandler import *\nfrom user import *\nfrom pages import *\nfrom twilio.rest import TwilioRestClient\nfrom admin import *\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\t\t\t\t\t\t\t\t\t# Providing the path to our templates\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)\t# Setting up the jinja2 environment\nACCOUNT_SID = \"AC8de5892b3f8494db67d451dd265c97c4\"\nAUTH_TOKEN = \"***\"\nclient = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)\n\n\nclass MultipleSMS(LogHandler):\n def get(self):\n params = dict()\n if self.loggedin():\n params['login'] = bar_in % self.get_username()\n else:\n params['login'] = bar_out\n self.render('multiplesms.html', **params)\n\n\nclass MultipleSMS_login(LogHandler):\n def get(self):\n params = dict()\n if not self.loggedin() or (self.loggedin() and not self.emailverified()):\n self.redirect('/multiplesms')\n else:\n user = self.get_user()\n params['login'] = bar_in % user.username\n params['limit'] = user.sms_allowed - user.sms_sent\n if user.mobile:\n params['number'] = user.mobile\n self.render('multiplesms_login.html', **params)\n def post(self):\n params = dict()\n params['number'] = number = self.request.get('number')\n if number and number!=\"+12568260936\":\n user = self.get_user()\n if user.sms_allowed > user.sms_sent:\n verify_mobile = ''.join(random.choice(letters) for x in range(5))\n user.verify_mobile = verify_mobile\n user.sms_sent+=1\n user.check_verify_mobile = False\n sms = client.sms.messages.create(to = number, from_ = \"+12568260936\", body = \"Please enter this code %s\" % verify_mobile)\n user.mobile = number\n user.put()\n self.redirect('/multiplesms/verify')\n else:\n params['login'] = bar_in % user.username\n params['error'] = \"You don't have enough balance!\"\n params['limit'] = user.sms_allowed - user.sms_sent\n self.render('multiplesms_login.html', **params)\n else:\n user = self.get_user()\n params['login'] = bar_in % user.username\n params['error'] = \"Please enter your number!\"\n params['limit'] = user.sms_allowed - user.sms_sent\n self.render('multiplesms_login.html', **params)\n\n\nclass AddNumbers(LogHandler):\n def get(self):\n params = dict()\n if not self.loggedin() or (self.loggedin() and not self.emailverified()):\n self.redirect('/multiplesms')\n else:\n params['login'] = bar_in % self.get_username()\n user = self.get_user()\n if user.loved_number:\n numbers = user.loved_number.split(',')\n params['numbers'] = numbers\n params['action'] = \"Add\"\n self.render('editnumbers.html', **params)\n def post(self):\n params = dict()\n params['number'] = number = self.request.get('number')\n if number and number!=\"+12568260936\":\n user = self.get_user()\n if user.loved_number:\n numbers = user.loved_number.split(',')\n if not number in numbers:\n user.loved_number = user.loved_number + \",\" + number\n user.put()\n else:\n user.loved_number = number\n user.put()\n self.redirect('/multiplesms/add')\n else:\n params['login'] = bar_in % self.get_username()\n params['error'] = \"Please enter the number!\"\n params['action'] = \"Add\"\n self.render('editnumbers.html', **params)\n\n\nclass RemoveNumbers(LogHandler):\n def get(self):\n params = dict()\n if not self.loggedin() or (self.loggedin() and not self.emailverified()):\n self.redirect('/multiplesms')\n else:\n params['login'] = bar_in % self.get_username()\n user = self.get_user()\n if user.loved_number:\n numbers = user.loved_number.split(',')\n params['numbers'] = numbers\n params['action'] = \"Remove\"\n self.render('editnumbers.html', **params)\n def post(self):\n params = dict()\n params['number'] = number = self.request.get('number')\n if number and number!=\"+12568260936\":\n user = self.get_user()\n numbers = user.loved_number.split(',')\n if number in numbers:\n numbers.remove(number)\n user.loved_number = \",\".join(numbers)\n user.put()\n self.redirect('/multiplesms/remove')\n else:\n params['login'] = bar_in % self.get_username()\n params['error'] = \"Please enter the number!\"\n params['action'] = \"Remove\"\n self.render('editnumbers.html', **params)\n\n\nclass SendSMS(LogHandler):\n def get(self):\n sms_sender = self.request.get('From')\n user = User.all().filter('mobile =', sms_sender).get()\n if user and user.sms_allowed > user.sms_sent and user.check_verify_mobile:\n recipients = user.loved_number.split(',')\n for recipient in recipients:\n sms = client.sms.messages.create(to = recipient, from_ = \"+12568260936\", body = \"Hello! Your friend/relative %s is in some problem. He/she might need your help.\" % user.username)\n user.sms_sent+=1\n if user.sms_allowed == user.sms_sent:\n break\n user.put()\n\n\nclass SendSMSOnline(LogHandler):\n def get(self):\n params = dict()\n if not self.loggedin() or (self.loggedin() and not self.emailverified()):\n self.redirect('/multiplesms')\n else:\n user = self.get_user()\n params['login'] = bar_in % user.username\n if user.loved_number:\n numbers = user.loved_number.split(',')\n params['numbers'] = numbers\n self.render('sendmsg.html', **params)\n def post(self):\n user = self.get_user()\n if user and user.sms_allowed > user.sms_sent and user.check_verify_mobile:\n if user.loved_number:\n recipients = user.loved_number.split(',')\n content = \"Hello! Your friend/relative %s is in some problem. He/she might need your help.\" % user.username\n for recipient in recipients:\n sms = client.sms.messages.create(to = recipient, from_ = \"+12568260936\", body = content)\n if user.sms_logs :\n user.sms_logs = \"Recipient : \" + recipient + \"
Content : \" + content + \"



\" + user.sms_logs\n else:\n user.sms_logs = \"Recipient : \" + recipient + \"
Content : \" + content\n user.sms_sent+=1\n if user.sms_allowed == user.sms_sent:\n break\n user.put()\n self.redirect('/multiplesms/main')\n else:\n params = dict()\n params['login'] = bar_in % user.username\n params['error'] = \"You don't have any recipients!\"\n if user.loved_number:\n numbers = user.loved_number.split(',')\n params['numbers'] = numbers\n self.render('sendmsg.html', **params)\n\n\nclass ManageSMS(LogHandler):\n def get(self):\n params = dict()\n if not self.loggedin() or not self.emailverified():\n self.redirect('/multiplesms')\n user = self.get_user()\n if not user.username == \"lingalarahul7\" and not user.username == \"lrahul7\":\n self.redirect('/multiplesms')\n else:\n params['login'] = bar_in % user.username\n self.render('managesms.html', **params)\n def post(self):\n params = dict()\n params['username'] = username = self.request.get('username')\n params['increment'] = increment = self.request.get('increment')\n user = User.all().filter('username =', username).get()\n isError = False\n if not user:\n params['error'] = \"Please enter correct username\"\n isError = True\n elif increment:\n user.sms_allowed+=int(increment)\n user.put()\n self.redirect('/multiplesms/manage')\n else:\n params['error'] = \"Please enter the value of increment\"\n isError = True\n if isError:\n params['login'] = bar_in % self.get_username()\n self.render('managesms.html', **params)\n\n\nclass VerifyMobile(LogHandler):\n def get(self):\n if not self.loggedin():\n self.redirect('/multiplesms')\n else:\n user = self.get_user()\n if user.check_verify_mobile:\n self.redirect('/multiplesms/main')\n else:\n params = dict()\n params['login'] = bar_in % user.username\n self.render('mobileverify.html', **params)\n def post(self):\n self.code = self.request.get('code')\n user = self.get_user()\n if self.code == user.verify_mobile:\n user.check_verify_mobile = True\n user.put()\n self.redirect('/multiplesms/main')\n else:\n params = dict()\n params['login'] = bar_in % user.username\n params['error_code'] = \"Please enter correct verfication code\"\n params['code'] = self.code\n self.render('mobileverify.html', **params)\n\n\nclass ManualSMS(LogHandler):\n def get(self):\n params = dict()\n if not self.loggedin() or (self.loggedin() and not self.verified()):\n self.redirect('/multiplesms')\n else:\n user = self.get_user()\n params['login'] = bar_in % user.username\n params['limit'] = user.sms_allowed - user.sms_sent\n self.render('manualsms.html', **params)\n def post(self):\n params = dict()\n params['number'] = number = self.request.get('number')\n params['content'] = content = self.request.get('content')\n if number and number!=\"+12568260936\" and content:\n user = self.get_user()\n if user.sms_allowed > user.sms_sent:\n user.speech = content\n user.sms_sent+=1\n if user.sms_logs :\n user.sms_logs = \"Recipient : \" + number + \"
Content : \" + content + \"


\" + user.sms_logs\n else:\n user.sms_logs = \"Recipient : \" + number + \"
Content : \" + content\n user.put()\n sms = client.sms.messages.create(to = number, from_ = \"+12568260936\", body = content)\n self.redirect('/manualsms')\n else:\n params['login'] = bar_in % user.username\n params['error'] = \"You don't have enough balance!\"\n params['limit'] = user.sms_allowed - user.sms_sent\n self.render('manualsms.html', **params)\n else:\n user = self.get_user()\n params['login'] = bar_in % user.username\n params['error'] = \"Please fill the form!\"\n params['limit'] = user.sms_allowed - user.sms_sent\n self.render('manualsms.html', **params)\n\n\nclass ViewMsgLogs(LogHandler):\n def get(self):\n params = dict()\n if not self.loggedin() or (self.loggedin() and not self.verified()):\n self.redirect('/texttospeech')\n else:\n params['login'] = bar_in % self.get_username()\n user = self.get_user()\n params['user'] = user\n params['service'] = \"SMS\"\n self.render('logs.html', **params)\n","sub_path":"multiplesms.py","file_name":"multiplesms.py","file_ext":"py","file_size_in_byte":12537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"294400905","text":"##SOLUÇAO EM PYTHON\nimport random as r\ndef StableMaching(PrefHomens, PrefMulheres):\n N = len(PrefHomens)\n HDisp = [i for i in range(N)]\n DicMulheres = [i[0] for i in PrefMulheres]\n PrefMulheres = [i[1] for i in PrefMulheres]\n DicHomens = [i[0] for i in PrefHomens]\n PrefHomens = [i[1] for i in PrefHomens]\n print(PrefHomens)\n parzinhos = [-1 for mulher in PrefHomens]\n while len(HDisp) > 0:\n r.shuffle(HDisp)\n m = HDisp[0]\n w = DicMulheres.index(PrefHomens[m][0])\n if parzinhos[w] == -1:\n parzinhos[w] = HDisp.pop(HDisp.index(m))\n PrefHomens[m].pop(0)\n elif PrefMulheres[w].index(DicHomens[m]) < PrefMulheres[w].index(DicHomens[parzinhos[w]]):\n HDisp.append(parzinhos.pop(w))\n parzinhos.insert(w, m)\n PrefHomens[m].pop(0)\n else:\n PrefHomens[m].pop(0)\n return [(DicHomens[x], DicMulheres[parzinhos.index(x)]) for x in parzinhos]\n","sub_path":"stable-matching.py","file_name":"stable-matching.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"185146891","text":"from models.db_models.models import UnitCatalog\nfrom db.db import session\nfrom flask import Flask, jsonify, request\nfrom flask_restful import Resource, fields, marshal_with, abort, reqparse\nimport modules.db_model_tranformer_modules.db_model_transformer_module as db_transformer\n\n#PARAMS\nENTITY_NAME = \"Unit Catalog\"\nMODEL = UnitCatalog\nROUTE =\"/unitCatalog\"\nEND_POINT = \"unit-catalog\"\n\n#NESTED SCHEMA FIELDS\n\n#OUTPUT SCHEMA\noutput_fields = {\n 'id': fields.Integer,\n 'system_name':fields.String,\n 'display_value':fields.String,\n 'name':fields.String,\n 'is_default': fields.Boolean\n}\n\n\n#API METHODS FOR SINGLE ENTITY\nclass UnitCatalogResource(Resource):\n def __init__(self):\n self.route = ROUTE+'/'\n self.end_point = END_POINT\n pass\n\n @marshal_with(output_fields)\n def get(self, id):\n entity = session.query(MODEL).filter(MODEL.id == id).first()\n if not entity:\n abort(404, message=ENTITY_NAME+\" {} doesn't exist\".format(id))\n return entity\n\n def delete(self, id):\n try:\n entity = session.query(MODEL).filter(MODEL.id == id).first()\n if not entity:\n abort(404, message=ENTITY_NAME+\" {} doesn't exist\".format(id))\n session.delete(entity)\n session.commit()\n return {}, 204\n except Exception as e:\n session.rollback()\n abort(400, message=\"Error while remove \"+ENTITY_NAME)\n\n @marshal_with(output_fields)\n def put(self, id):\n try:\n json_data = request.get_json(force=True)\n entity = session.query(MODEL).filter(MODEL.id == id).first()\n if not entity:\n abort(404, message=ENTITY_NAME + \" {} doesn't exist\".format(id))\n db_transformer.transform_update_params(entity,json_data)\n session.add(entity)\n session.commit()\n return entity, 201\n except Exception as e:\n session.rollback()\n abort(400, message=\"Error while update \"+ENTITY_NAME)\n\n#API METHODS FOR LIST ENTITIES\nclass UnitCatalogListResource(Resource):\n def __init__(self):\n self.route = ROUTE\n self.end_point = END_POINT+'-list'\n pass\n\n @marshal_with(output_fields)\n def get(self):\n entities = session.query(MODEL).all()\n return entities\n\n @marshal_with(output_fields)\n def post(self):\n try:\n json_data = request.get_json(force=True)\n entity = MODEL(json_data)\n session.add(entity)\n session.commit()\n return entity, 201\n except Exception as e:\n session.rollback()\n abort(400, message=\"Error while adding record \"+ENTITY_NAME)\n\n","sub_path":"res/unit_catalog_resources.py","file_name":"unit_catalog_resources.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"200232003","text":"from django.db import models\nfrom PIL import Image\nimport numpy as np\nfrom io import BytesIO\nfrom django.core.files.base import ContentFile\nfrom .utils import get_filtered_image\n#import cv2\n# Create your models here.\nACTION_CHOICES=(\n ('NO_FILTER','no filter'),\n ('COLORIZED','colorized'),\n ('GRAY_SCALE','grayscale'),\n ('BLURRED','blurred'),\n ('BINARY','binary'),\n ('INVERT','invert'),\n)\nclass Upload(models.Model):\n image=models.ImageField(upload_to=\"images\")\n action=models.CharField(max_length=50,choices=ACTION_CHOICES)\n updated=models.DateTimeField(auto_now=True)\n created=models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.id)\n\n def save(self,*args,**kwargs):\n \n img=Image.open(self.image)\n \n img1=get_filtered_image(img,self.action)\n \n \n buffer=BytesIO()\n img.save(buffer,format=\"png\")\n image_png=buffer.getvalue()\n with open(\"write.txt\",\"a\") as file:\n file.write(str(self.image)+str(\" \"))\n self.image.save(str(self.image),ContentFile(image_png),save=False)\n super().save(*args,**kwargs)\n \n ","sub_path":"major_project/opencv/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"440727787","text":"class Solution(object):\n def divide(self, dividend, divisor):\n MAXINT = (1<<31) - 1\n if divisor == -1: return MAXINT if dividend == -(1<<31) else -dividend\n sign = 1 if not (dividend > 0)^(divisor > 0) else -1\n dividend = abs(dividend)\n divisor = abs(divisor)\n tmp = divisor\n count = 0\n while tmp <= dividend:\n if dividend // 2 < tmp: break #此处防止越界\n tmp = tmp << 1\n count += 1\n res = 0\n while count >= 0:\n if dividend >= tmp:\n res |= (1<> 1\n count -= 1\n return sign * res\n'''\n这题我不会\n原来无论哪个进制的除法都是一样的,可以从大到小去除之后得到余数再继续除的\n所以十进制除法可以转化为二进制除法\n'''\n\n'''\n另一种解法:\n从底到上加上二进制值\n'''\n\nclass Solution(object):\n def divide(self, dividend, divisor):\n MAXINT = (1<<31) - 1\n if divisor == -1: return MAXINT if dividend == -(1<<31) else -dividend\n res = 0\n sign = 1 if not (dividend > 0)^(divisor > 0) else -1\n if dividend > 0: dividend *= -1\n if divisor > 0: divisor *= -1\n while dividend <= divisor:\n tmp_res = 1\n tmp_divisor = divisor\n while dividend <= tmp_divisor:\n if (tmp_divisor<<1 < (-(1<<31)>>1)) or ((tmp_divisor<<1)< dividend): break\n tmp_divisor <<= 1\n tmp_res <<= 1\n dividend -= tmp_divisor\n res += tmp_res\n return sign * res\n'''\n另一款从高位到低位\n但是题目要求不能用 * 和 /\n'''\nclass Solution(object):\n def divide(self, dividend, divisor):\n MAXINT = (1<<31) - 1\n if divisor == -1: return MAXINT if dividend == -(1<<31) else -dividend\n res = 0\n sign = 1 if not (dividend > 0)^(divisor > 0) else -1\n if dividend > 0: dividend *= -1\n if divisor > 0: divisor *= -1\n tmp_res = 1\n while dividend <= divisor:\n if dividend <= tmp_res * divisor:\n dividend -= tmp_res * divisor\n res += tmp_res\n tmp_res += tmp_res\n else:\n tmp_res //= 2\n return sign * res\n\n\n\n\na = Solution()\nprint(a.divide(10,3))","sub_path":"Bitwise/Leetcode_29/lc29.py","file_name":"lc29.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"473954","text":"class Disk:\n\n # Initialize\n def __init__(self, size, thin = False):\n self.size = size\n self.thin = thin\n\nclass Network:\n\n # Initialize\n def __init__(self, name, ip, gateway, subnet_mask):\n self.name = name\n self.ip = ip\n self.gateway = gateway\n self.subnet_mask = subnet_mask\n \nclass VM:\n\n # Initialize\n def __init__(self, name, cpus, memory, data_center, cluster,\n host, data_store, template, folder, networks, disks,\n host_name, domain, dns_servers, dns_search_domains,\n host_selection, data_store_selection):\n self.name = name\n self.cpus = cpus\n self.memory = memory\n self.host = host\n self.data_store = data_store\n self.template = template\n self.folder = folder\n self.data_center = data_center\n self.cluster = cluster\n self.networks = networks\n self.disks = disks\n self.host_name = host_name\n self.domain = domain\n self.dns_servers = dns_servers\n self.dns_search_domains = dns_search_domains\n self.host_selection = host_selection\n self.data_store_selection = data_store_selection\n","sub_path":"lib/vmfleet/vm.py","file_name":"vm.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"106001942","text":"class Grid(object):\n\n def __init__(self, grid):\n self._grid = grid\n self._m = len(grid)\n self._n = len(grid[0])\n\n def _get_children(self, i, j):\n res = {}\n for p in [-1, 0, 1]:\n for q in [-1, 0, 1]:\n if p == q == 0:\n continue\n ii = i + p\n jj = j + q\n if 0 <= ii < self._m and 0 <= jj < self._n:\n res[(ii, jj)] = self._grid[ii][jj]\n return res\n\n def find_path(self, word):\n self._visited = set()\n res = []\n for i in range(self._m):\n for j in range(self._n):\n self._results = []\n self._find_path_aux(0, word, [], i, j)\n res.extend(self._results[:])\n return res\n\n def _find_path_aux(self, idx, word, one_result, i, j):\n if idx == len(word) - 1:\n target = word[idx]\n if target == self._grid[i][j] and ((i, j) not in self._visited):\n self._results.append(one_result + [(i, j)])\n else:\n # 0 <= idx < len(word) - 1\n target = word[idx]\n if target == self._grid[i][j] and ((i, j) not in self._visited):\n self._visited.add((i, j))\n children = self._get_children(i, j)\n for key in children:\n ii = key[0]\n jj = key[1]\n self._find_path_aux(idx + 1, word, one_result + [(i, j)],\n ii, jj)\n self._visited.remove((i, j))\n else:\n return\n","sub_path":"Practice/Interview/Google/word_grid/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"635375219","text":"#Author: Toluwanimi Salako\r\n\r\nfrom collections import defaultdict\r\nimport random\r\n\r\nteam_name = \"StudentAI-Default\"\r\n\r\nclass StudentAI():\r\n\tdef __init__(self, player, state):\r\n\t\tself.last_move = state.get_last_move()\r\n\t\tself.model = state\r\n\tdef make_move(self, deadline):\r\n\t\t'''Write AI Here. Return a tuple (col, row)'''\r\n\t\twidth = self.model.get_width()\r\n\t\theight = self.model.get_height()\r\n\t\tspaces = defaultdict(int)\r\n\r\n\t\tfor i in range(width):\r\n\t\t\tfor j in range(height):\r\n\t\t\t\tspaces[(i,j)] = self.model.get_space(i, j)\r\n\r\n\t\tmoves = [k for k in spaces.keys() if spaces[k] == 0]\r\n\t\treturn moves[random.randint(0, len(moves) - 1)]","sub_path":"ConnectKSource_python/student_ai.py","file_name":"student_ai.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"519292758","text":"# -*- coding=utf8 -*-\n__author__ = 'cosven'\n\n\nclass DataModel(object):\n def user(self):\n user_model = {\n 'uid': int,\n 'username': unicode,\n 'avatar': unicode\n }\n return user_model\n\n def music(self):\n music_model = {\n 'id': int,\n 'name': unicode,\n 'artists': list,\n 'album': dict,\n 'duration': unicode,\n 'mp3Url': unicode\n }\n return music_model\n\n def playlist(self):\n playlist_model = {\n 'id': int,\n 'name': unicode\n }\n return playlist_model\n\n def search_result(self):\n \"\"\"\n from search result: data['result']['songs']\n \"\"\"\n search_list = {\n 'id': int,\n 'name': unicode,\n 'artists': list,\n 'album': dict\n }\n return search_list\n\n\n def set_datamodel_from_data(self, data, datamodel):\n \"\"\"\n before generating model, the data should be validated\n requirement: the datastructure of model is similar with standard\n :param data: dict, input data\n :param type: string, the target model type\n \"\"\"\n # temperarily: no validation check\n for key in datamodel:\n datamodel[key] = data[key]\n return datamodel\n\n def validate(self, data, model_type):\n \"\"\"\n compare data with the standard model, to validate the data basicllay.\n 1. check those keys which data must contain\n :param data: dict type,\n :param model: dict type, standard data model. base on the doc\n :return: if validated: true\n \"\"\"\n return True\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"501392953","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Author:\n\n# Python3 Standard library\nimport os\nimport csv\nimport pprint\n\n# import pprint\n\n# External library (need pip install command)\n\n\n\"\"\"\nReference文献\n PSF公式\n csv --- CSV ファイルの読み書き\n \n note.nkmk.me\n Pythでファイルの読み込み、書き込み(作成・追記)\n\"\"\"\nBASE_DIR = \"E:/2018_Python_学習環境/PyLesson/py_basic/test_data/file_test/\"\nOUT_DIR = BASE_DIR + \"out/\"\n\n\ndef lesson1():\n print('1: read():ファイル全体をテキストとして読み込む')\n l_infile = [\"csv_utf8.csv\", \"csv_sjis.csv\"]\n l_outfile = [\"csv_utf8_out.csv\", \"csv_sjis_out.csv\"]\n l_encode = [\"utf_8\", \"cp932\"]\n\n for inf, outf, f_encode in zip(l_infile, l_outfile, l_encode):\n infile = BASE_DIR + inf\n outfile = OUT_DIR + outf\n print(F\"** 入力ファイル名:{infile}/エンコード:{f_encode}\")\n try:\n with open(infile, newline='', encoding=f_encode) as f:\n all_file = f.read()\n print(F\"** print(f.read())で表示: type={type(all_file)}\")\n print(all_file)\n except Exception as e:\n print(F\"Exception: {type(e)}\")\n return\n\n\ndef lesson2():\n print('2: readline():テキストファイルを一行づつリストとして読み込む')\n print(F\"※ リスト要素には改行文字コードが含まれる点に注意\")\n\n l_infile = [\"csv_utf8.csv\", \"csv_sjis.csv\"]\n l_outfile = [\"csv_utf8_out.csv\", \"csv_sjis_out.csv\"]\n l_encode = [\"utf_8\", \"cp932\"]\n\n for inf, outf, f_encode in zip(l_infile, l_outfile, l_encode):\n infile = BASE_DIR + inf\n outfile = OUT_DIR + outf\n print(F\"** 入力ファイル名:{infile}/エンコード:{f_encode}\")\n try:\n with open(infile, newline='', encoding=f_encode) as f:\n line = f.readline()\n while line:\n line = f.readline()\n print(F\"\\tline='{line}'/{type(line)}/len={len(line)}\")\n\n except Exception as e:\n print(F\"Exception: {type(e)}\")\n return\n\n\ndef lesson3():\n print('3: readlines():ファイル全体を改行文字を区切りとしたリストとして読み込む')\n print(F\"※ リスト要素には改行文字コードが含まれる点に注意\")\n\n l_infile = [\"csv_utf8.csv\", \"csv_sjis.csv\"]\n l_outfile = [\"csv_utf8_out.csv\", \"csv_sjis_out.csv\"]\n l_encode = [\"utf_8\", \"cp932\"]\n\n for inf, outf, f_encode in zip(l_infile, l_outfile, l_encode):\n infile = BASE_DIR + inf\n outfile = OUT_DIR + outf\n print(F\"** 入力ファイル名:{infile}/エンコード:{f_encode}\")\n\n try:\n print(F\"** pprint.pprint()で出力結果を表示\")\n with open(infile, newline='', encoding=f_encode) as f:\n pprint.pprint(f.readlines())\n\n print(F\"** print()で出力結果を表示\")\n with open(infile, newline='', encoding=f_encode) as f:\n print(f.readlines())\n\n except Exception as e:\n print(F\"Exception: {type(e)}\")\n\n\n# Test用メニュー\n# ----------------------------------------------------\n# For Test: Test Menuとパラメータの表示\n# ----------------------------------------------------\nMAX_MENU_ID = 5\n\n\ndef select_menu() -> int:\n \"\"\"\n Function: Show test menu and get menu number.\n Return: selected menu number\n \"\"\"\n while True:\n try:\n print(\"==================================\")\n print(F' 現ディレクトリ:{os.getcwd()}')\n print(\"============= Menu ===============\")\n print('0: ** Exit menu')\n print('1: read():ファイル全体読み込み')\n print('2: readline():テキストファイルを一行づつリストとして読み込む')\n print('3: readlines():ファイル全体を改行文字を区切りとしたリストとして読み込む')\n print(\"=============================\")\n print(\"Enter Test ID or 0(=Exit Test)\", end='')\n menu = input(' >>>')\n\n if 0 <= int(menu) <= MAX_MENU_ID:\n return int(menu)\n else:\n print(f'==ERROR 入力番号:{menu}は、入力エラーです。 ')\n except (ValueError, TypeError):\n print(f'==ERROR 正しいメニュー番号を入力してください ')\n\n\n# Main\nif __name__ == \"__main__\":\n # Select TEST-ID\n while True:\n TEST_ID = select_menu()\n if TEST_ID == 0:\n print(\"== 処理を終了します \")\n break\n elif TEST_ID == 1:\n lesson1()\n elif TEST_ID == 2:\n lesson2()\n elif TEST_ID == 3:\n lesson3()\n","sub_path":"py05_基本File_read&readline&readlines.py","file_name":"py05_基本File_read&readline&readlines.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"639703209","text":"import time\nimport zipfile\nimport utils\nimport json\nimport os\nimport io\nimport shutil\n\nclass file_manager(object):\n '''\n all function use absolute path\n '''\n\n def __init__(self, logname = 'file_manager'):\n self.log = utils.logger().getLogger(logname)\n\n def getPathInfo(self, path):\n '''\n return a list of path infomation\n '''\n pathInfo = []\n if isinstance(path, str) and os.path.exists(path) and os.path.isdir(path):\n pathInfo = os.listdir(path)\n \n advancePathInfo = []\n for p in pathInfo:\n fullpath = os.path.join(path,p)\n if os.path.isdir(fullpath):\n advancePathInfo.append(p + '/')\n elif os.path.isfile(fullpath):\n advancePathInfo.append(p)\n \n return {'file_list' : advancePathInfo}\n \n def getZipBytes(self, path):\n '''\n return zip bytes of the specified direction or files\n '''\n zipBytes = bytes()\n if isinstance(path, str) and os.path.exists(path):\n # zipname = '~' + os.path.split(path)[1] + '.zip'\n # zippath = os.path.join(os.path.split(path)[0], zipname) \n # self.log.info(\"create zip file : %s\" % zippath)\n\n try:\n bytesIO = io.BytesIO()\n # create zip file into bytesIO\n with zipfile.ZipFile(bytesIO, 'w', zipfile.ZIP_DEFLATED) as zf:\n if os.path.isdir(path):\n for dirpath, dirnames, filenames in os.walk(path): \n for filename in filenames: \n fullpath = os.path.join(dirpath,filename)\n zf.write(fullpath, fullpath[len(path):])\n else:\n zf.write(path, os.path.split(path)[1])\n # get zip bytes\n zipBytes = bytesIO.getvalue()\n # close bytesIO\n bytesIO.close()\n except BaseException as e:\n self.log.critical(e)\n\n return zipBytes\n\n def unzip2path(self, srcBytes, releasePath, mode = 0):\n '''\n param: srcBytes is the zip bytes\n releasePath is where the files released\n mode is 0 -> if releasePath is not exist, return\n mode is 1 -> if releasePath is not exist, create a new path\n '''\n\n if 0 == mode:\n if (not isinstance(releasePath, str)) or \\\n (not os.path.exists(releasePath)) or \\\n (not os.path.isdir(releasePath)) :\n self.log.error(\"the release path '%s' is not an avalible directory\" % releasePath)\n return\n elif 1 == mode:\n try:\n # will occur in very small posibility\n if os.path.exists(releasePath) and (not os.path.isdir(releasePath)):\n os.remove(releasePath)\n # not exist then create\n if (not os.path.exists(releasePath)):\n os.mkdir(releasePath)\n self.log.info(\"create dir: %s\" % releasePath)\n except BaseException as e:\n self.log.error(e)\n self.log.error(\"the release path '%s' is not avalible\" % releasePath)\n return\n\n try:\n bytesIO = io.BytesIO(srcBytes)\n with zipfile.ZipFile(bytesIO, 'r') as zf:\n for file in zf.namelist():\n zf.extract(file, releasePath)\n bytesIO.close()\n\n except BaseException as e:\n self.log.critical(e)\n\n def remove(self, path):\n '''\n remove a file or a dir\n '''\n try:\n if not os.path.exists(path):\n return\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n except BaseException as e:\n self.log.critical(e)\n \n \nif __name__ == '__main__':\n fs = file_manager()\n print(json.dumps(fs.getPathInfo('D:/Workspace/daemon\\\\log')))\n\n fbytes = fs.getZipBytes('D:/Workspace/daemon/log/debug')\n print(len(fbytes))\n # with open('D:/Workspace/daemon/log/aaa.zip', 'wb') as f:\n # f.write(fbytes)\n \n\n fs.unzip2path(fbytes,'D:/Workspace/daemon/log/ff',1)\n fs.remove('D:/Workspace/daemon/log/ff//')","sub_path":"file_manager.py","file_name":"file_manager.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"445437859","text":"\n\n#calss header\nclass _OVERSENSITIVE():\n\tdef __init__(self,): \n\t\tself.name = \"OVERSENSITIVE\"\n\t\tself.definitions = [u'too easily upset: ', u'damaged, changed, or harmed by something that would not affect most people or things: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_oversensitive.py","file_name":"_oversensitive.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"2889108","text":"#! /usr/bin/env python3\nimport subprocess\nimport argparse\nimport os.path\nimport os\nimport re\n# py3 make_page.py /Users/anything/THU/astro/softwares/aeroastro/gravlen/microlensing_table/pdfs --destdir lcs --htmlname lcs.html --htmltitle \"Microlensing Planet Lightcurves\"\n\ncss = '''\nbody {\n font-family: helvetica, arial, freesans, clean, sans-serif;\n font-size: 18px;\n color: #222;\n background-color: lightgrey;\n}\n.lfbtable {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n align-items: center;\n justify-content: space-around;\n}\n\n.row {\n display: flex;\n flex-direction: row;\n}\n\n.cell {\n max-width: 24.9%;\n max-height: 24.9%;\n width: auto;\n height: auto;\n background-position: center center;\n background-repeat: no-repeat;\n background-size: cover;\n overflow: hidden;\n transition: .2s ease opacity;\n\n position:relative;\n float:left; /* optional */\n\n}\n\n.cell > p {\n margin-bottom: 0;\n}\n\n.image {\n position:relative;\n float:left; /* optional */\n}\n.cell .text {\n position:relative;\n top:0px; /* in conjunction with left property, decides the text position */\n left:1px;\n width:300px; /* optional, though better have one */\n color: black;\n}\n\nimg {\n max-width: 100%;\n display: block;\n padding-bottom: 2px;\n}\n\n.cell:hover {\n opacity: 0.8;\n}\n.cell:hover:after {\n opacity: 1;\n}\n\n.copy {\n font-size: 1.2rem;\n}\n\nh1 {\n font-size: 1.8rem;\n margin-bottom: 0.63rem;\n}\n\nh2 {\n font-size: 1.6rem;\n margin-bottom: 0.86rem;\n}\n\nh3 {\n font-size: 1.4rem;\n}\n\nh4 {\n font-size: 1.2rem;\n}\n@media screen and (max-width: 990px) {\n .cell {\n max-width: 33.15%;\n max-height: 33.15%;\n }\n}\n@media screen and (max-width: 640px) {\n .cell {\n max-width: 49.9%;\n max-height: 49.9%;\n }\n}\n'''\n\n\nclass Picture(object):\n '''Picture represents the portions of a picture we're interested in.'''\n\n def __init__(self, name, diskpath, relpath, thumbpath):\n self.name = name\n self.diskpath = diskpath\n self.relpath = relpath\n self.thumbpath = thumbpath\n\ndef re_match_urls(txtfilename):\n contents = \"\"\n with open(txtfilename) as f:\n for line in f.readlines():\n contents += line\n urls = re.findall(\"https://.*?abstract\", contents)\n # print(urls)\n # print(len(urls))\n return urls\n\n\ndef make_thumbnail(diskpath, thumbfolder, maxsize=640):\n '''Takes the path to an image on disk and the path to the output thumbnail\n folder and creates a thumbnail image in the thumbnail directory. If the\n thumbnail directory doesn't exist, it's created.'''\n if not os.path.exists(thumbfolder):\n os.makedirs(thumbfolder)\n # Use imagemagick for thumbnail creation\n thumbpath = os.path.join(\n os.path.abspath(thumbfolder), os.path.basename(diskpath))\n # resize_opts = '-resize {size}x{size}^ -gravity Center -crop {size}x{size}+0+0 '.format(size=maxsize)\n # resize_opts = '-resize {size}x{size}^ -gravity Center'.format(size=maxsize)\n resize_opts = '-thumbnail {size}x{size} -gravity Center'.format(size=maxsize)\n # https://apple.stackexchange.com/questions/335635/where-is-the-convert-command-in-macos\n # Where is the convert command in macOS?\n args = ['convert', \"'{}'\".format(diskpath), resize_opts, '-quality', '60',\n \"'{}'\".format(thumbpath)]\n if os.path.exists(thumbpath):\n print(\"Thumbnail path '{}' already exists, skipping\".format(thumbpath))\n return thumbpath\n os.system(\" \".join(args))\n return thumbpath\n\n\ndef link_image(diskpath, output_dir):\n '''Creates a symbolic link in the output_dir pointing to the diskpath. The\n name of the symbolic link is the basename of the diskpath.'''\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n source = os.path.abspath(diskpath)\n dest = os.path.join(output_dir, os.path.basename(diskpath))\n if os.path.exists(dest):\n print(\"Symlink '{}' already exists, skipping\".format(dest))\n return dest\n # os.symlink(source, dest)\n try:\n os.system(\" \".join([ \"cp\", source, dest ]))\n except:\n print(\"cp source failed, maybe not exists\")\n return dest\n\ndef render_markdown(md):\n '''Calls out to pandoc to render markdown. '''\n args = ['pandoc', '-f', 'markdown', '-t', 'html']\n pandoc = subprocess.Popen(\n args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)\n output = pandoc.communicate(input=md)[0]\n return output\n\ndef group_rows(pictures,urls,solimgsfolder,maxsize=480):\n rv = \"\"\n cells = []\n for pic in pictures:\n # \"Your\n # pic.relpath = orgimgs/01_OGLE20120563.png\n solimgpath = solimgsfolder + \"/\" + pic.relpath.split(\"/\")[-1][:-4]+\"_sol.png\"\n # print(solimgpath)\n # input()\n\n\n # print(solimgpath)\n # input()\n\n # print(pic.diskpath)\n # input()\n # soldiskpath = pic.diskpath.split(\"/\")\n # soldiskpath[-2] = \"solimgs\"\n # diskpath = \"\"\n # for sec in soldiskpath:\n # diskpath += sec+\"/\"\n # diskpath = diskpath[:-1]\n # diskpath = diskpath[:-4]+\"_sol.png\"\n\n\n\n if os.path.exists(solimgpath):\n solimgtitle = \"solution\"\n else:\n solimgtitle = \"\"\n solimgpath = solimgpath.split(\"/\")[-2]+\"/\"+solimgpath.split(\"/\")[-1]\n\n refurl = urls[int(pic.relpath.split(\"/\")[-1][:2])-1]\n\n cell = '''\n \n '''.format(pic.relpath, pic.thumbpath, pic.relpath.split(\"/\")[-1][:-4], size=maxsize, solimg=solimgpath, refurl=refurl, solimgtitle=solimgtitle)\n cells.append(cell)\n rv = \"\\n\".join(cells)\n return rv\n\ndef create_gallery(dir_full_path, target=None):\n images = []\n solimgs = []\n for filename in os.listdir(dir_full_path):\n #目录的路径和文件名拼接起来,得到了文件的绝路路径\n # print(os.path.join(path,filename))\n # print(filename)\n if filename.endswith(\".png\") or filename.endswith(\".jpg\"):\n if not \"sol\" in filename:\n images.append(os.path.join(dir_full_path,filename))\n solimgs.append(os.path.join(dir_full_path,filename[:-4]+\"_sol.png\"))\n\n images = sorted(images, key=lambda k: float(k.split(\"/\")[-1][:2]))\n solimgs = sorted(solimgs, key=lambda k: float(k.split(\"/\")[-1][:2]))\n return images, solimgs\n\n\n\ndef create_page_v2(imagesdir, output_dir, copy_path, htmlname,htmltitle,urls):\n '''Create_page accepts a list of paths to images and the location of the\n directory to place the gallery within. Each image must have an extension of\n one of the following:\n .jpg\n .jpeg\n .png\n .gif\n Any file that lacks those extensions will be ignored.\n '''\n \n thumbfolder = os.path.join(os.path.abspath(output_dir), \"thumbnails\")\n orgimgsfolder = os.path.join(os.path.abspath(output_dir), \"orgimgs\")\n solimgsfolder = os.path.join(os.path.abspath(output_dir), \"solimgs\")\n pictures = []\n\n accepted_extensions = ['.jpg', '.jpeg', '.png', '.gif']\n # images = [img for img in images if img.endswith(tuple(accepted_extensions))]\n images, solimgs = create_gallery(imagesdir)\n for solimg in solimgs:\n _ = link_image(solimg, solimgsfolder)\n\n for idx, img in enumerate(images):\n abs_thumbpath = make_thumbnail(img, thumbfolder)\n rel_thumbpath = os.path.relpath(abs_thumbpath, output_dir)\n # relpath is the path to the full-resolution image, relative to the\n # output directory. Will point to a symlink, usually.\n # fullres_link = link_image(img, output_dir)\n fullres_link = link_image(img, orgimgsfolder)\n relpath = os.path.relpath(fullres_link, output_dir)\n pic = Picture(\"\", os.path.abspath(img), relpath, rel_thumbpath)\n pictures.append(pic)\n\n print(\"{}% complete\\r\".format(int(100 * (idx / len(images)))), end=\"\")\n print()\n\n body_md = \"\"\n if copy_path and os.path.exists(copy_path):\n with open(copy_path) as c:\n body_md = render_markdown(c.read())\n if copy_path and not os.path.exists(copy_path):\n print(\"The provided path '{}' to a markdown file for the body text does not exist\".format(copy_path))\n\n\n page = \"\"\"\n\n\n\n\n {title}\n\n

{title}

\n
\n{}\n
\n{}\n\n\"\"\"\n table = '
{}\\n
'\n rows = group_rows(pictures, urls, solimgsfolder)\n table = table.format(rows)\n\n rv = \"\"\n rv = page.format(css, body_md, table,title=htmltitle)\n\n # with open(os.path.join(output_dir, 'index.html'), 'w+') as index:\n with open(os.path.join(output_dir, htmlname), 'w+') as index:\n index.write(rv)\n\n return rv\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Create a web-page with nice tiled links to all the images provided.'\n )\n parser.add_argument('--destdir', type=str, default=\"./gallery/\")\n parser.add_argument('--htmlname', type=str, default=\"index.html\")\n parser.add_argument('--htmltitle', type=str, default=\"Title\")\n parser.add_argument('--bodymarkdown', type=str, help='Location of markdown file to use for the body text.')\n parser.add_argument('images', type=str, nargs='+')\n # parser.add_argument('images', type=str, nargs='+')\n\n args = parser.parse_args()\n\n # _ = create_page(args.images, args.destdir, args.bodymarkdown)\n # print(args.images)\n # print(type(args.images))\n pdffolder = args.images[0]\n urltextfile = pdffolder+\"/infos.txt\"\n urls = re_match_urls(urltextfile)\n\n _ = create_page_v2(args.images[0], args.destdir, args.bodymarkdown, args.htmlname, args.htmltitle, urls)\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n# def create_page(images, output_dir, copy_path):\n# '''Create_page accepts a list of paths to images and the location of the\n# directory to place the gallery within. Each image must have an extension of\n# one of the following:\n# .jpg\n# .jpeg\n# .png\n# .gif\n# Any file that lacks those extensions will be ignored.\n# '''\n# thumbfolder = os.path.join(os.path.abspath(output_dir), \"thumbnails\")\n\n# pictures = []\n\n# accepted_extensions = ['.jpg', '.jpeg', '.png', '.gif']\n# images = [img for img in images if img.endswith(\n# tuple(accepted_extensions))]\n# for idx, img in enumerate(images):\n# abs_thumbpath = make_thumbnail(img, thumbfolder)\n# rel_thumbpath = os.path.relpath(abs_thumbpath, output_dir)\n# # relpath is the path to the full-resolution image, relative to the\n# # output directory. Will point to a symlink, usually.\n# fullres_link = link_image(img, output_dir)\n# relpath = os.path.relpath(fullres_link, output_dir)\n# pic = Picture(\"\", os.path.abspath(img), relpath, rel_thumbpath)\n# pictures.append(pic)\n\n# print(\"{}% complete\\r\".format(int(100 * (idx / len(images)))), end=\"\")\n# print()\n\n# body_md = \"\"\n# if copy_path and os.path.exists(copy_path):\n# with open(copy_path) as c:\n# body_md = render_markdown(c.read())\n# if copy_path and not os.path.exists(copy_path):\n# print(\"The provided path '{}' to a markdown file for the body text does not exist\".format(copy_path))\n\n\n# page = \"\"\"\n# \n# \n# \n#
\n# {}\n#
\n# {}\n# \n# \"\"\"\n# # page = \"\"\"\n# # \n# # \n# # \n# #
\n# # {}\n# #
\n# # {}\n# # \n# # \"\"\"\n# table = '
{}\\n
'\n# rows = group_rows(pictures)\n# table = table.format(rows)\n\n# rv = \"\"\n# rv = page.format(css, body_md, table)\n\n# with open(os.path.join(output_dir, 'index.html'), 'w+') as index:\n# index.write(rv)\n\n# return rv","sub_path":"funpython/pyhtml/make_page.py","file_name":"make_page.py","file_ext":"py","file_size_in_byte":12401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"329437630","text":"from functools import partial\nimport pyecore.ecore as Ecore\nfrom pyecore.ecore import *\nfrom model import ISynchable\nfrom model import Node\n\nname = 'values'\nnsURI = 'https://raw.githubusercontent.com/openworm/org.geppetto.model/development/src/main/resources/geppettoModel.ecore#//values'\nnsPrefix = 'gep'\n\neClass = EPackage(name=name, nsURI=nsURI, nsPrefix=nsPrefix)\n\neClassifiers = {}\ngetEClassifier = partial(Ecore.getEClassifier, searchspace=eClassifiers)\n\n\nConnectivity = EEnum('Connectivity', literals=['DIRECTIONAL', 'BIDIRECTIONAL', 'NON_DIRECTIONAL']) # noqa\nImageFormat = EEnum('ImageFormat', literals=['PNG', 'JPEG', 'IIP']) # noqa\n\n\nclass StringToValueMap(EObject):\n __metaclass__ = MetaEClass\n key = EAttribute(eType=EString)\n value = EReference()\n\n def __init__(self, key=None, value=None, **kwargs):\n if kwargs:\n raise AttributeError('unexpected arguments: {}'.format(kwargs))\n\n super(StringToValueMap, self).__init__()\n if key is not None:\n self.key = key\n if value is not None:\n self.value = value\n\n\nclass PointerElement(EObject):\n __metaclass__ = MetaEClass\n index = EAttribute(eType=EInteger)\n variable = EReference()\n type = EReference()\n\n def __init__(self, variable=None, type=None, index=None, **kwargs):\n if kwargs:\n raise AttributeError('unexpected arguments: {}'.format(kwargs))\n\n super(PointerElement, self).__init__()\n if index is not None:\n self.index = index\n if variable is not None:\n self.variable = variable\n if type is not None:\n self.type = type\n\n\nclass FunctionPlot(EObject):\n __metaclass__ = MetaEClass\n title = EAttribute(eType=EString)\n xAxisLabel = EAttribute(eType=EString)\n yAxisLabel = EAttribute(eType=EString)\n initialValue = EAttribute(eType=EDouble)\n finalValue = EAttribute(eType=EDouble)\n stepValue = EAttribute(eType=EDouble)\n\n def __init__(self, title=None, xAxisLabel=None, yAxisLabel=None, initialValue=None, finalValue=None, stepValue=None, **kwargs):\n if kwargs:\n raise AttributeError('unexpected arguments: {}'.format(kwargs))\n\n super(FunctionPlot, self).__init__()\n if title is not None:\n self.title = title\n if xAxisLabel is not None:\n self.xAxisLabel = xAxisLabel\n if yAxisLabel is not None:\n self.yAxisLabel = yAxisLabel\n if initialValue is not None:\n self.initialValue = initialValue\n if finalValue is not None:\n self.finalValue = finalValue\n if stepValue is not None:\n self.stepValue = stepValue\n\n\nclass SkeletonTransformation(EObject):\n __metaclass__ = MetaEClass\n skeletonTransformation = EAttribute(eType=EDouble, upper=-1)\n\n def __init__(self, skeletonTransformation=None, **kwargs):\n if kwargs:\n raise AttributeError('unexpected arguments: {}'.format(kwargs))\n\n super(SkeletonTransformation, self).__init__()\n if skeletonTransformation:\n self.skeletonTransformation.extend(skeletonTransformation)\n\n\n@abstract\nclass Value(ISynchable):\n\n def __init__(self, **kwargs):\n super(Value, self).__init__(**kwargs)\n\n\nclass Composite(Value):\n value = EReference(upper=-1, containment=True)\n\n def __init__(self, value=None, **kwargs):\n super(Composite, self).__init__(**kwargs)\n if value:\n self.value.extend(value)\n\n\nclass Quantity(Value):\n scalingFactor = EAttribute(eType=EInt)\n value = EAttribute(eType=EDouble)\n\n def __init__(self, scalingFactor=None, value=None, **kwargs):\n super(Quantity, self).__init__(**kwargs)\n if scalingFactor is not None:\n self.scalingFactor = scalingFactor\n if value is not None:\n self.value = value\n\n\nclass Unit(Value):\n unit = EAttribute(eType=EString)\n\n def __init__(self, unit=None, **kwargs):\n super(Unit, self).__init__(**kwargs)\n if unit is not None:\n self.unit = unit\n\n\nclass TimeSeries(Value):\n scalingFactor = EAttribute(eType=EInt)\n value = EAttribute(eType=EDouble, upper=-1)\n unit = EReference(containment=True)\n\n def __init__(self, unit=None, scalingFactor=None, value=None, **kwargs):\n super(TimeSeries, self).__init__(**kwargs)\n if scalingFactor is not None:\n self.scalingFactor = scalingFactor\n if value:\n self.value.extend(value)\n if unit is not None:\n self.unit = unit\n\n\n@abstract\nclass MetadataValue(Value):\n\n def __init__(self, **kwargs):\n super(MetadataValue, self).__init__(**kwargs)\n\n\nclass Pointer(Value):\n path = EAttribute(eType=EString)\n elements = EReference(upper=-1, containment=True)\n point = EReference(containment=True)\n\n def __init__(self, elements=None, point=None, path=None, **kwargs):\n super(Pointer, self).__init__(**kwargs)\n if path is not None:\n self.path = path\n if elements:\n self.elements.extend(elements)\n if point is not None:\n self.point = point\n def getInstancePath(self):\n raise NotImplementedError('Operation getInstancePath(...) is not yet implemented')\n\n\nclass Point(Value):\n x = EAttribute(eType=EDouble)\n y = EAttribute(eType=EDouble)\n z = EAttribute(eType=EDouble)\n\n def __init__(self, x=None, y=None, z=None, **kwargs):\n super(Point, self).__init__(**kwargs)\n if x is not None:\n self.x = x\n if y is not None:\n self.y = y\n if z is not None:\n self.z = z\n\n\nclass Dynamics(Value):\n initialCondition = EReference(containment=True)\n dynamics = EReference(containment=True)\n\n def __init__(self, initialCondition=None, dynamics=None, **kwargs):\n super(Dynamics, self).__init__(**kwargs)\n if initialCondition is not None:\n self.initialCondition = initialCondition\n if dynamics is not None:\n self.dynamics = dynamics\n\n\nclass Function(Value):\n arguments = EReference(upper=-1, containment=True)\n expression = EReference(containment=True)\n functionPlot = EReference(containment=True)\n\n def __init__(self, arguments=None, expression=None, functionPlot=None, **kwargs):\n super(Function, self).__init__(**kwargs)\n if arguments:\n self.arguments.extend(arguments)\n if expression is not None:\n self.expression = expression\n if functionPlot is not None:\n self.functionPlot = functionPlot\n\n\nclass Argument(Value):\n argument = EAttribute(eType=EString)\n\n def __init__(self, argument=None, **kwargs):\n super(Argument, self).__init__(**kwargs)\n if argument is not None:\n self.argument = argument\n\n\nclass Expression(Value):\n expression = EAttribute(eType=EString)\n\n def __init__(self, expression=None, **kwargs):\n super(Expression, self).__init__(**kwargs)\n if expression is not None:\n self.expression = expression\n\n\n@abstract\nclass VisualValue(Value):\n groupElements = EReference(upper=-1)\n position = EReference(containment=True)\n\n def __init__(self, groupElements=None, position=None, **kwargs):\n super(VisualValue, self).__init__(**kwargs)\n if groupElements:\n self.groupElements.extend(groupElements)\n if position is not None:\n self.position = position\n\n\nclass VisualGroupElement(Node):\n defaultColor = EAttribute(eType=EString)\n parameter = EReference(containment=True)\n\n def __init__(self, defaultColor=None, parameter=None, **kwargs):\n super(VisualGroupElement, self).__init__(**kwargs)\n if defaultColor is not None:\n self.defaultColor = defaultColor\n if parameter is not None:\n self.parameter = parameter\n\n\nclass VisualGroup(Node):\n lowSpectrumColor = EAttribute(eType=EString)\n highSpectrumColor = EAttribute(eType=EString)\n type = EAttribute(eType=EString)\n visualGroupElements = EReference(upper=-1, containment=True)\n\n def __init__(self, lowSpectrumColor=None, highSpectrumColor=None, type=None, visualGroupElements=None, **kwargs):\n super(VisualGroup, self).__init__(**kwargs)\n if lowSpectrumColor is not None:\n self.lowSpectrumColor = lowSpectrumColor\n if highSpectrumColor is not None:\n self.highSpectrumColor = highSpectrumColor\n if type is not None:\n self.type = type\n if visualGroupElements:\n self.visualGroupElements.extend(visualGroupElements)\n\n\nclass Connection(Value):\n connectivity = EAttribute(eType=Connectivity)\n a = EReference(containment=True)\n b = EReference(containment=True)\n\n def __init__(self, a=None, b=None, connectivity=None, **kwargs):\n super(Connection, self).__init__(**kwargs)\n if connectivity is not None:\n self.connectivity = connectivity\n if a is not None:\n self.a = a\n if b is not None:\n self.b = b\n\n\nclass ArrayElement(Value):\n index = EAttribute(eType=EInt)\n position = EReference(containment=True)\n initialValue = EReference(containment=True)\n\n def __init__(self, index=None, position=None, initialValue=None, **kwargs):\n super(ArrayElement, self).__init__(**kwargs)\n if index is not None:\n self.index = index\n if position is not None:\n self.position = position\n if initialValue is not None:\n self.initialValue = initialValue\n\n\nclass ArrayValue(Value):\n elements = EReference(upper=-1, containment=True)\n\n def __init__(self, elements=None, **kwargs):\n super(ArrayValue, self).__init__(**kwargs)\n if elements:\n self.elements.extend(elements)\n\n\nclass Image(Value):\n data = EAttribute(eType=EString)\n name = EAttribute(eType=EString)\n reference = EAttribute(eType=EString)\n format = EAttribute(eType=ImageFormat)\n\n def __init__(self, data=None, name=None, reference=None, format=None, **kwargs):\n super(Image, self).__init__(**kwargs)\n if data is not None:\n self.data = data\n if name is not None:\n self.name = name\n if reference is not None:\n self.reference = reference\n if format is not None:\n self.format = format\n\n\nclass ImportValue(Value):\n modelInterpreterId = EAttribute(eType=EString)\n\n def __init__(self, modelInterpreterId=None, **kwargs):\n super(ImportValue, self).__init__(**kwargs)\n if modelInterpreterId is not None:\n self.modelInterpreterId = modelInterpreterId\n\n\nclass PhysicalQuantity(Quantity):\n unit = EReference(containment=True)\n\n def __init__(self, unit=None, **kwargs):\n super(PhysicalQuantity, self).__init__(**kwargs)\n if unit is not None:\n self.unit = unit\n\n\nclass Text(MetadataValue):\n text = EAttribute(eType=EString)\n\n def __init__(self, text=None, **kwargs):\n super(Text, self).__init__(**kwargs)\n if text is not None:\n self.text = text\n\n\nclass URL(MetadataValue):\n url = EAttribute(eType=EString)\n\n def __init__(self, url=None, **kwargs):\n super(URL, self).__init__(**kwargs)\n if url is not None:\n self.url = url\n\n\nclass HTML(MetadataValue):\n html = EAttribute(eType=EString)\n\n def __init__(self, html=None, **kwargs):\n super(HTML, self).__init__(**kwargs)\n if html is not None:\n self.html = html\n\n\nclass Collada(VisualValue):\n collada = EAttribute(eType=EString)\n\n def __init__(self, collada=None, **kwargs):\n super(Collada, self).__init__(**kwargs)\n if collada is not None:\n self.collada = collada\n\n\nclass OBJ(VisualValue):\n obj = EAttribute(eType=EString)\n\n def __init__(self, obj=None, **kwargs):\n super(OBJ, self).__init__(**kwargs)\n if obj is not None:\n self.obj = obj\n\n\nclass Sphere(VisualValue):\n radius = EAttribute(eType=EDouble)\n\n def __init__(self, radius=None, **kwargs):\n super(Sphere, self).__init__(**kwargs)\n if radius is not None:\n self.radius = radius\n\n\nclass Cylinder(VisualValue):\n bottomRadius = EAttribute(eType=EDouble)\n topRadius = EAttribute(eType=EDouble)\n height = EAttribute(eType=EDouble)\n distal = EReference(containment=True)\n\n def __init__(self, bottomRadius=None, topRadius=None, height=None, distal=None, **kwargs):\n super(Cylinder, self).__init__(**kwargs)\n if bottomRadius is not None:\n self.bottomRadius = bottomRadius\n if topRadius is not None:\n self.topRadius = topRadius\n if height is not None:\n self.height = height\n if distal is not None:\n self.distal = distal\n\n\nclass SkeletonAnimation(VisualValue):\n skeletonTransformationSeries = EReference(upper=-1)\n\n def __init__(self, skeletonTransformationSeries=None, **kwargs):\n super(SkeletonAnimation, self).__init__(**kwargs)\n if skeletonTransformationSeries:\n self.skeletonTransformationSeries.extend(skeletonTransformationSeries)\n\n\nclass Particle(VisualValue, Point):\n\n def __init__(self, **kwargs):\n super(Particle, self).__init__(**kwargs)\n","sub_path":"model/values/values.py","file_name":"values.py","file_ext":"py","file_size_in_byte":13306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"437537554","text":"import pandas as pd\nfrom math import log\n\ndef calc_calendar_ledger(blotter, starting_cash, ivv_hist, start_date):\n\n calendar_ledger = []\n cash = starting_cash\n position = 0\n\n for ivv_row in ivv_hist[\n ivv_hist['Date'] >= pd.to_datetime(start_date)\n ].iterrows():\n ivv_row = ivv_row[1]\n trading_date = ivv_row['Date']\n ivv_close = ivv_row['Close']\n trades = blotter[\n (blotter['filled_or_cancelled'] == trading_date) & (\n blotter['status'] == 'FILLED'\n )]\n\n if len(trades) > 0:\n position = position + sum(\n trades['size'][trades['action'] == 'BUY']\n ) - sum(\n trades['size'][trades['action'] == 'SELL']\n )\n cash = cash - sum(\n trades['size'][trades['action'] == 'BUY'] *\n trades['fill_price'][\n trades['action'] == 'BUY'\n ]\n ) + sum(\n trades['size'][trades['action'] == 'SELL'] *\n trades['fill_price'][\n trades['action'] == 'SELL'\n ]\n )\n stock_value = position * ivv_close\n total_value = cash + stock_value\n else:\n stock_value = position * ivv_close\n total_value = cash + stock_value\n\n ledger_row = [\n trading_date, position, ivv_close, cash, stock_value, total_value\n ]\n calendar_ledger.append(ledger_row)\n\n calendar_ledger = pd.DataFrame(calendar_ledger)\n calendar_ledger.columns = [\n 'Date', 'position', 'ivv_close', 'cash', 'stock_value', 'total_value'\n ]\n calendar_ledger.round(2)\n\n calendar_ledger.to_csv('app_data/calendar_ledger.csv', index=False)\n\n return calendar_ledger\n\ndef calc_trade_ledger(blotter, ivv_hist):\n\n trade_ledger = []\n\n for trade in blotter['ID'].unique():\n\n round_trip_trade = blotter[\n (blotter['ID'] == trade) & (blotter['status'] == 'FILLED')\n ]\n\n if len(round_trip_trade) < 2:\n continue\n\n print(round_trip_trade)\n\n trade_id = round_trip_trade['ID'].unique().item()\n\n date_opened = min(round_trip_trade['filled_or_cancelled'])\n date_closed = max(round_trip_trade['filled_or_cancelled'])\n\n ivv_df = ivv_hist[\n (ivv_hist['Date'] <= date_closed) & \\\n (ivv_hist['Date'] >= date_opened)\n ]\n\n print(ivv_df)\n\n buy_price = round_trip_trade['fill_price'][\n round_trip_trade['action'] == 'BUY'\n ].item()\n sell_price = round_trip_trade['fill_price'][\n round_trip_trade['action'] == 'SELL'\n ].item()\n\n ivv_price_enter = ivv_df['Open'][\n ivv_df['Date'] == date_opened\n ].item()\n ivv_price_exit = ivv_df['Close'][\n ivv_df['Date'] == date_closed\n ].item()\n\n trade_rtn = log(sell_price / buy_price)\n ivv_rtn = log(ivv_price_exit / ivv_price_enter)\n\n trading_days_open = len(ivv_df)\n\n trade_rtn_per_trading_day = trade_rtn / trading_days_open\n benchmark_rtn_per_trading_day = ivv_rtn / trading_days_open\n\n trade_ledger_row = [\n trade_id, date_opened, date_closed, trading_days_open, buy_price,\n sell_price, ivv_price_enter, ivv_price_exit, trade_rtn, ivv_rtn,\n trade_rtn_per_trading_day, benchmark_rtn_per_trading_day\n ]\n\n trade_ledger.append(trade_ledger_row)\n\n trade_ledger = pd.DataFrame(trade_ledger)\n trade_ledger.columns = [\n 'trade_id', 'open_dt', 'close_dt', 'trading_days_open', 'buy_price',\n 'sell_price', 'benchmark_buy_price', 'benchmark_sell_price',\n 'trade_rtn', 'benchmark_rtn', 'trade_rtn_per_trading_day',\n 'benchmark_rtn_per_trading_day'\n ]\n\n trade_ledger.to_csv('app_data/trade_ledger.csv', index=False)\n\n return trade_ledger\n","sub_path":"ledger.py","file_name":"ledger.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"489082354","text":"#CRUD methods for Google Cloud Storage\n\n#standard python libraries\nimport os\nimport requests\nimport uuid\nimport datetime\nimport re\n\n#external lib for cropping images\nfrom PIL import Image\n\n#authenticated API for google cloud storage\nfrom gcs_connection import storage_client\n\n#two variables that are used many times in the methods below\nGOOGLE_STORAGE_BUCKET = os.environ.get('GOOGLE_STORAGE_BUCKET', 'restaurant-app-314718-public')\nTEMP_UPLOAD_FOLDER = './user-uploads'\n\n#CRUD methods for google cloud storage\n\n#read method for internal server use\ndef user_blobs():\n USER_IMAGES_PREFIX = 'user-images/img' \n return storage_client.list_blobs(GOOGLE_STORAGE_BUCKET, prefix=USER_IMAGES_PREFIX)\n\n#read method that returns resourse URLs\ndef image_urls():\n \"\"\"Lists all the blobs in the bucket.\"\"\"\n # Note: Client.list_blobs requires at least package version 1.17.0.\n GCS_BASE_URL = \"https://storage.googleapis.com\"\n\n blobs = user_blobs()\n\n return [f'{GCS_BASE_URL}/{GOOGLE_STORAGE_BUCKET}/{blob.name}' for blob in blobs] \n\n#delete method\ndef delete_blob(blob_name):\n \"\"\"Deletes a blob from the bucket.\"\"\"\n # bucket_name = \"your-bucket-name\"\n # blob_name = \"your-object-name\"\n bucket = storage_client.bucket(GOOGLE_STORAGE_BUCKET)\n blob = bucket.blob(blob_name)\n blob.delete()\n\n#create method that manipulates the image before uploading\ndef process_image(image_file):\n\n #save original image to server\n extension = re.findall(\"(jpg|jpeg|png|gif|bmp)\", image_file.filename)[0]\n filename = f'img-{uuid.uuid4()}.{extension}'\n image_path = os.path.join(TEMP_UPLOAD_FOLDER, filename)\n image_file.save(image_path)\n\n #crop to fit carousel\n crop(image_path)\n\n #create policy that google requires to POST images\n policy = storage_client.generate_signed_post_policy_v4(\n GOOGLE_STORAGE_BUCKET,\n f'user-images/{filename}',\n expiration=datetime.timedelta(minutes=10),\n conditions=[\n [\"content-length-range\", 0, 1000000]\n ],\n )\n\n #POST image to google cloud storage\n with open(image_path, \"rb\") as f:\n files = {\"file\": (image_path, f)}\n #try this, if fails then return False\n response = requests.post(policy[\"url\"], data=policy[\"fields\"], files=files)\n return response\n\n\n#PIL/pillow (python image library)\n\n#method used when cropping image before upload\ndef crop(image_path):\n with Image.open(image_path) as im:\n im_new = crop_max_square(im)\n im_new.save(image_path, quality=95)\n\n#helper method for crop() above\ndef crop_center(pil_img, crop_width, crop_height):\n img_width, img_height = pil_img.size\n return pil_img.crop(((img_width - crop_width) // 2,\n (img_height - crop_height) // 2,\n (img_width + crop_width) // 2,\n (img_height + crop_height) // 2))\n\n#helper method for crop() above\ndef crop_max_square(pil_img):\n return crop_center(pil_img, min(pil_img.size), min(pil_img.size))\n\n","sub_path":"gcs_module.py","file_name":"gcs_module.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"537662808","text":"import setuptools\nfrom pathlib import Path\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"scmer\",\n version=\"v0.1.0a3\",\n author=\"Shaoheng Liang\",\n author_email=\"\",\n description=\"Manifold preserving marker selection for single-cell data\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://scmer.readthedocs.io/\",\n packages=['scmer'], #setuptools.find_packages(),\n install_requires=[\n l.strip() for l in Path('requirements.txt').read_text('utf-8').splitlines()\n ],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"632578021","text":"from time import process_time\nfrom typing import Callable, Generator\nfrom functools import wraps\n\n\ndef time_it(func: Callable) -> Callable:\n \"\"\"\n декоратор вычисления system и user время выполнения декорируемой ф-и func\n \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n start_time = process_time()\n result = [item for item in func(*args, **kwargs)]\n end_time = process_time()\n number = args[0]\n print(str.format(\n '[!] elapsed time for \"{}\" fibonacci calculated: {} seconds',\n number,\n round(end_time - start_time, 5)\n ))\n\n return result\n\n return wrapper\n\n\n@time_it\ndef fibonacci(n: int) -> Generator:\n one, two, i = 0, 1, 1\n\n while i <= n:\n yield one + two\n one, two = two, one + two\n i += 1\n\n\ndef main():\n fibonacci(10000)\n\n \nif __name__ == '__main__':\n main()\n","sub_path":"core/builtin_features/decorators/time_it_fibonacci.py","file_name":"time_it_fibonacci.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"451489928","text":"# !/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n:copyright (c) 2014 - 2020, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Department of Energy) and contributors. All rights reserved. # NOQA\n:author\n\"\"\"\n\nimport json\nimport os.path as osp\n\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.urls import reverse_lazy\n\nfrom seed.data_importer import tasks\nfrom seed.data_importer.models import ImportFile, ImportRecord\nfrom seed.data_importer.tests.util import (\n FAKE_EXTRA_DATA,\n FAKE_MAPPINGS,\n FAKE_ROW,\n)\nfrom seed.data_importer.views import convert_first_five_rows_to_list\nfrom seed.landing.models import SEEDUser as User\nfrom seed.lib.mcm.reader import ROW_DELIMITER\nfrom seed.models import (\n PORTFOLIO_RAW,\n)\nfrom seed.tests.util import DataMappingBaseTestCase\n\n\ndef first_five_rows_helper(headers, raw_data):\n save_format = '\\n'.join([ROW_DELIMITER.join(row) for row in raw_data])\n expected = [dict(zip(headers, row)) for row in raw_data]\n return save_format, expected\n\n\nclass DataImporterViewTests(DataMappingBaseTestCase):\n \"\"\"\n Tests of the data_importer views (and the objects they create).\n \"\"\"\n\n def setUp(self):\n user_details = {\n 'username': 'test_user@demo.com',\n 'password': 'test_pass',\n }\n self.user = User.objects.create_superuser(email='test_user@demo.com', **user_details)\n self.client.login(**user_details)\n\n def test_get_raw_column_names(self):\n \"\"\"Make sure we get column names back in a format we expect.\"\"\"\n import_record = ImportRecord.objects.create()\n expected_raw_columns = ['tax id', 'name', 'etc.']\n expected_saved_format = ROW_DELIMITER.join(expected_raw_columns)\n import_file = ImportFile.objects.create(\n import_record=import_record,\n cached_first_row=expected_saved_format\n )\n\n # Just make sure we were saved correctly\n self.assertEqual(import_file.cached_first_row, expected_saved_format)\n\n url = reverse_lazy(\"api:v2:import_files-raw-column-names\", args=[import_file.pk])\n resp = self.client.get(\n url, content_type='application/json'\n )\n\n body = json.loads(resp.content)\n\n self.assertEqual(body.get('raw_columns', []), expected_raw_columns)\n\n def test_get_first_five_rows(self):\n \"\"\"Make sure we get our first five rows back correctly.\"\"\"\n import_record = ImportRecord.objects.create()\n expected_raw_columns = ['tax id', 'name', 'etc.']\n expected_raw_rows = [\n ['02023', '12 Jefferson St.', 'etc.'],\n ['12433', '23 Washington St.', 'etc.'],\n ['04422', '4 Adams St.', 'etc.'],\n ]\n\n expected = [\n dict(zip(expected_raw_columns, row)) for row in expected_raw_rows\n ]\n expected_saved_format = '\\n'.join([\n ROW_DELIMITER.join(row) for row\n in expected_raw_rows\n ])\n import_file = ImportFile.objects.create(\n import_record=import_record,\n cached_first_row=ROW_DELIMITER.join(expected_raw_columns),\n cached_second_to_fifth_row=expected_saved_format\n )\n\n # Just make sure we were saved correctly\n self.assertEqual(\n import_file.cached_second_to_fifth_row, expected_saved_format\n )\n\n url = reverse_lazy(\"api:v2:import_files-first-five-rows\", args=[import_file.pk])\n resp = self.client.get(\n url, content_type='application/json'\n )\n\n body = json.loads(resp.content)\n\n self.assertEqual(body.get('first_five_rows', []), expected)\n\n def test_get_first_five_rows_simple(self):\n header = ['id', 'name', 'etc']\n raw_data = [\n ['1', 'test_1', 'simple'],\n ['2', 'test_2', 'example'],\n ]\n save_format, expected = first_five_rows_helper(header, raw_data)\n converted = convert_first_five_rows_to_list(header, save_format)\n self.assertEqual(converted, expected)\n\n def test_get_first_five_rows_newline_middle(self):\n header = ['id', 'name', 'etc']\n raw_data = [\n ['1', 'test\\nmiddle', 'new'],\n ['2', 'test_2', 'single'],\n ]\n save_format, expected = first_five_rows_helper(header, raw_data)\n converted = convert_first_five_rows_to_list(header, save_format)\n self.assertEqual(converted, expected)\n\n def test_get_first_five_rows_newline_end(self):\n header = ['id', 'name', 'etc']\n raw_data = [\n ['1', 'test_1', 'new\\nat_end'],\n ['2', 'test_2', 'single'],\n ]\n save_format, expected = first_five_rows_helper(header, raw_data)\n converted = convert_first_five_rows_to_list(header, save_format)\n self.assertEqual(converted, expected)\n\n def test_get_first_five_rows_newline_various(self):\n header = ['id', 'name', 'etc']\n raw_data = [\n ['1', 'test_1', 'new\\n\\nat_end\\n\\n'],\n ['2', 'test_2', 'single\\nat_end_too\\n'],\n ]\n save_format, expected = first_five_rows_helper(header, raw_data)\n converted = convert_first_five_rows_to_list(header, save_format)\n self.assertEqual(converted, expected)\n\n def test_get_first_five_rows_newline_should_work(self):\n \"\"\"\n This test shows where this logic breaks down. There is no other way around this issue\n unless we move away from the |#*#| syntax and store it in a more supported CSV format\n syntax with quotes and escape characters\n :return:\n \"\"\"\n header = ['id', 'name', 'etc']\n raw_data = [\n ['1', 'test_1', 'new\\n\\nat_end\\n\\n'],\n ['2\\nThisBreaksMe', 'test_2', 'single\\nat_end_too\\n'],\n ]\n save_format, expected = first_five_rows_helper(header, raw_data)\n converted = convert_first_five_rows_to_list(header, save_format)\n\n # This test passes as it is the expected behavior, even though it is wrong.\n # the ID of row 2 should be 2\\nThisBreaksMe, but the convert_first_five_to_list does\n # not know that the crlf was part of the field and not the line break.\n self.assertNotEqual(converted, expected)\n\n def test_get_first_five_rows_one_column(self):\n header = ['id']\n raw_data = [\n ['1'],\n ['2'],\n ]\n save_format, expected = first_five_rows_helper(header, raw_data)\n converted = convert_first_five_rows_to_list(header, save_format)\n self.assertEqual(converted, expected)\n\n def test_get_first_five_rows_one_column_with_crlf(self):\n header = ['id']\n raw_data = [\n ['1'],\n ['2\\nshould_be_the_id'],\n ]\n save_format, expected = first_five_rows_helper(header, raw_data)\n converted = convert_first_five_rows_to_list(header, save_format)\n\n # This test fails on purpose becasue the format of the first five rows will not\n # support this use case.\n self.assertNotEqual(converted, expected)\n\n\nclass TestDataImportViewWithCRLF(DataMappingBaseTestCase):\n \"\"\"Tests for dealing with SEED related tasks for mapping data.\"\"\"\n\n def setUp(self):\n filename = getattr(self, 'filename', 'portfolio-manager-sample-with-crlf.xlsx')\n import_file_source_type = PORTFOLIO_RAW\n self.fake_mappings = FAKE_MAPPINGS['portfolio']\n self.fake_extra_data = FAKE_EXTRA_DATA\n self.fake_row = FAKE_ROW\n selfvars = self.set_up(import_file_source_type)\n self.user, self.org, self.import_file, self.import_record, self.cycle = selfvars\n filepath = osp.join(osp.dirname(__file__), '..', '..', '..', 'tests', 'data', filename)\n self.import_file.file = SimpleUploadedFile(\n name=filename,\n content=open(filepath, 'rb').read()\n )\n self.import_file.save()\n\n def test_cached_first_row_order(self):\n \"\"\"Tests to make sure the first row is saved in the correct order.\n It should be the order of the headers in the original file.\"\"\"\n\n tasks.save_raw_data(self.import_file.pk)\n\n # reload the import file\n self.import_file = ImportFile.objects.get(pk=self.import_file.pk)\n first_row = self.import_file.cached_first_row\n expected_first_row = \"Property Id|#*#|Property Name|#*#|Year Ending|#*#|Property Notes|#*#|Address 1|#*#|Address 2|#*#|City|#*#|State/Province|#*#|Postal Code|#*#|Year Built|#*#|ENERGY STAR Score|#*#|Site EUI (kBtu/ft2)|#*#|Total GHG Emissions (MtCO2e)|#*#|Weather Normalized Site EUI (kBtu/ft2)|#*#|National Median Site EUI (kBtu/ft2)|#*#|Source EUI (kBtu/ft2)|#*#|Weather Normalized Source EUI (kBtu/ft2)|#*#|Parking - Gross Floor Area (ft2)|#*#|Organization|#*#|Generation Date|#*#|Release Date\"\n self.assertEqual(first_row, expected_first_row)\n\n # setup the API access\n user_details = {\n 'username': 'test_user@demo.com',\n 'password': 'test_pass',\n }\n self.client.login(**user_details)\n\n url = reverse_lazy(\"api:v2:import_files-first-five-rows\", args=[self.import_file.pk])\n resp = self.client.get(url, content_type='application/json')\n body = json.loads(resp.content)\n self.assertEqual(body['status'], 'success')\n self.assertEqual(len(body['first_five_rows']), 5)\n\n expected_property_notes = 'These are property notes:\\n- Nice building\\n- Large atrium\\n- Extra crlf here'\n self.assertEqual(body['first_five_rows'][0]['Property Notes'], expected_property_notes)\n","sub_path":"seed/data_importer/tests/views/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":9680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"635937090","text":"from flask import Flask, url_for, request, render_template\nfrom markupsafe import escape\n\napp = Flask(__name__)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n return do_the_login()\n else:\n return show_the_login_form()\n\ndef do_the_login():\n print(request.method)\n return 'do_the_login()'\n\ndef show_the_login_form():\n print(request.method)\n print(url_for('static', filename='styles.css'))\n return 'show_the_login_form()'\n\n@app.route('/hello/')\ndef hello_world():\n return 'Hello, World!'\n\nwith app.test_request_context('/hello', method='POST'):\n # now you can do something with the request until the\n # end of the with block, such as basic assertions:\n assert request.path == '/hello'\n print(request.path)\n assert request.method == 'POST'\n print(request.method)","sub_path":"flask_login/flask_request_context.py","file_name":"flask_request_context.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"216082396","text":"# This compiles all of the areas in the meshblock data from StatsNZ\n# The data takes meshblock_area.csv and produces meshblock_area_compiled.csv\n\ni_data = open('/home/lukelongworth/meshblock_area.csv')\nf_data = open('/home/lukelongworth/meshblock_area_compiled.csv', 'a')\n\nmeshblock_p = '0000100'\narea_t = 0\n\nfor line in i_data:\n data = line.split('\\t')\n meshblock = str(data[0])\n area = float(data[1])\n\n if meshblock == meshblock_p:\n area_t += area\n else:\n f_data.write(meshblock_p+' '+str(area_t)+'\\n')\n meshblock_p = meshblock\n area_t = area\n","sub_path":"scripts/SingleRunScripts/sum_areas.py","file_name":"sum_areas.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"625947797","text":"from __future__ import print_function\n\nimport numpy as np\nimport random\nimport json\nimport re\nimport time\n\nimport networkx as nx\nfrom networkx.readwrite import json_graph\n\ndef _resample_G(G, max_degree):\n \"\"\"\n resize G to have a max degree.\n Assume nodes of G is relabels to be 0,1,2,...,|V|-1\n \"\"\"\n adj_list = []\n nodes = G.nodes()\n for nodeid in nodes:\n neighbors = G.neighbors(nodeid)\n if len(neighbors) == 0:\n adj_list.append([])\n elif len(neighbors) > max_degree:\n adj_list.append(np.random.choice(neighbors,max_degree,replace=False))\n else:\n adj_list.append(np.random.choice(neighbors,max_degree,replace=True))\n G = nx.DiGraph() # DiGraph cuz the resampling process does not maintain the undirected property\n for nodeid in nodes:\n G.add_node(nodeid)\n for nodeid in nodes:\n edges = [(nodeid,i) for i in adj_list[nodeid]]\n G.add_edges_from(edges)\n return G\n\n \ndef _read_from_txt(data_file):\n G = nx.DiGraph()\n with open(data_file, 'r') as inline:\n for line in inline:\n if line[0] == '#':\n continue\n s,t = [v.strip('\\n').strip('\\t') for v in re.split(' |\\t',line)]\n G.add_edge(s,t)\n return G\n\ndef load_data_simple(data_file, max_degree):\n _relabel = True\n ts = time.time()\n if data_file.split('.')[-1] == 'json':\n G_data = json.load(open(data_file))\n G = json_graph.node_link_graph(G_data)\n elif data_file.split('.')[-1] == 'txt':\n G = _read_from_txt(data_file)\n elif data_file.split('.')[-1] == 'edgelist': # written by nx.write_edgelist()\n _relabel = False\n G = nx.read_edgelist(data_file, nodetype=int)\n else:\n raise Exception('unsupported input format')\n te = time.time()\n print('done reading from input file in {:6.2f}s'.format(te-ts))\n import pdb; pdb.set_trace()\n if _relabel:\n ts = time.time()\n mapping = {v:i for i,v in enumerate(G.nodes())}\n G = nx.relabel_nodes(G, mapping)\n te = time.time()\n print('done relabeling nodes in {:6.2f}s'.format(te-ts))\n \n if max_degree > 0:\n ts = time.time()\n G = _resample_G(G, max_degree)\n te = time.time()\n print('done resampling to max degree of {} in {:6.2f}s'.format(max_degree,te-ts))\n\n return G\n\n\ndef rewrite_edgelist(data_file):\n G = load_data_simple(data_file, -1)\n nx.write_edgelist(G, '{}.edgelist'.format(data_file))\n","sub_path":"preproc/data_format.py","file_name":"data_format.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"528290460","text":"# ===============================================\n# Driver for LDC1000 inductance-impedance to digital module\n# (c) 2017 Mihkel Veske\n# ===============================================\n\nimport serial\nimport time\nimport numpy as np\n\nimport constants as const\nimport tools\n\n#===========================================================\n# USB CDC commands\nREAD = '03'\nWRITE = '02'\nSTREAM_ON = '06'\nSTREAM_OFF = '07'\nFIRMWARE ='09'\n\n#===========================================================\n# LDC1000 addressing space\nDevID = '00'\nRpMax = '01'\nRpMin = '02'\nSensorFreq = '03'\nLdcConfic = '04'\nClkConfig = '05'\nThresHiLSB = '06'\nThresHiMSB = '07'\nThresLoLSB = '08'\nThresLoMSB = '09'\nIntConfig = '0A'\nPwrConfig = '0B'\nStatus = '20'\nProxDataLSB = '21'\nProxDataMSB = '22'\nFreqDataLSB = '23'\nFreqDataMID = '24'\nFreqDataMSB = '25'\n\n#===========================================================\n# LDC1000 internal variables\nserial_port = serial.Serial()\n#serial_port = serial.Serial('/dev/cu.usbmodem1411')\n#print(serial_port.name)\n#===========================================================\n\n# Convert proximity data at addresses 0x21 & 0x22 to sensor impedance\ndef prox2impedance(data):\n Y = 1.0 * data / 2**15\n Rp_max = 83.111 # upper limit of resonant impedance input range specified by register 0x01 [kOhm]\n Rp_min = 2.394 # lower limit of resonant impedance input range specified by register 0x02 [kOhm]\n Rp = (Rp_max*Rp_min) / (Rp_min*(1-Y) + Rp_max*Y) # resonant impedance [kOhm]\n return round(Rp, 3)\n\n# Convert frequency counter value at addresses 0x23,0x24,0x25 to sensor inductance \ndef freq2inductance(data):\n Fext = 6.0 # frequency of the external clock or crystal [MHz]\n C = 100.0 # parallel capacitance of the resonator [pF]\n t_resp = 6144 # response time in register 0x04\n \n if data == 0: return 0.0\n \n f_sensor = (Fext / data) * (t_resp / 3.0) # sensor frequency [MHz] \n L = 1e6 / (C * (2*np.pi*f_sensor)**2) # sensor inductance [uH]\n return round(L, 3) \n\n# write data string \ndef write_data(data):\n global serial_port\n \n if (const.PRINT_TX_DATA):\n print (\"Sent:\", data)\n \n try:\n # Read pending input bytes\n while (serial_port.inWaiting() > 0):\n serial_port.read(serial_port.inWaiting())\n\n # Send data\n serial_port.write(data.encode(\"utf-8\"))\n \n # wait for the response\n while (serial_port.inWaiting() < 32):\n time.sleep(0.1)\n \n # read the response\n response = serial_port.read(serial_port.inWaiting())\n if (const.PRINT_RESPONSE_DATA):\n print (\"Response:\", end='')\n for r in response: print (\" %d\" % r, end='')\n print()\n\n except serial.SerialException:\n print (\"Error writing to LCD1000 in\", serial_port.port)\n\n# write value to register\ndef write_reg(reg, data):\n send_data = WRITE + reg + data + '00';\n write_data(send_data)\n \n# read value from register\ndef read_reg(reg):\n global serial_port\n \n send_data = READ + reg + '0000';\n if (const.PRINT_TX_DATA):\n print (\"Sent:\", send_data)\n \n try:\n # clean input buffer\n serial_port.read(serial_port.inWaiting())\n \n # order data from ldc1000\n serial_port.write(send_data.encode('utf-8'))\n \n # wait for the response\n while (serial_port.inWaiting() < 32):\n time.sleep(0.01)\n \n # acquire data\n data = serial_port.read(serial_port.inWaiting())\n if (const.PRINT_RX_DATA):\n print (\"Read:\", end='')\n for d in data: print (\" %d\"%d, end='')\n print()\n \n return data[8]\n \n except serial.SerialException:\n print (\"Error reading LCD1000 register\", reg, \"at port\", serial_port.port)\n return 0\n\n# open serial port and initialise LDC1000 registers\ndef config():\n global serial_port\n \n # open serial port\n serial_port = tools.get_serial(const.LDC1000_PORT, 9600);\n if (not serial_port.isOpen()):\n serial_port.open()\n \n write_reg(RpMax, '0E')\n write_reg(RpMin, '3B')\n write_reg(SensorFreq, '94')\n write_reg(LdcConfic, '17')\n write_reg(ClkConfig, '02')\n \n write_reg(ThresHiLSB, '50')\n write_reg(ThresHiMSB, '14')\n write_reg(ThresLoLSB, 'C0')\n write_reg(ThresLoMSB, '12')\n \n write_reg(IntConfig, '04')\n \n# start continuous streaming \ndef start_stream():\n send_data = STREAM_ON + ProxDataLSB + '0000';\n write_data(send_data)\n\n# stop continuous streaming \ndef stop_stream():\n send_data = STREAM_OFF + ProxDataLSB + '0000';\n write_data(send_data) \n\n# measure sensor inductance\ndef read_inductance(): \n #print (\"read_reg(FreqDataMSB) : \") \n freq_msb = read_reg(FreqDataMSB)\n #print (\"read_reg(FreqDataMSB) : \")\n freq_mid = read_reg(FreqDataMID)\n #print (\"read_reg(FreqDataMSB) : \")\n freq_lsb = read_reg(FreqDataLSB)\n return freq2inductance(65536*freq_msb + 256*freq_mid + freq_lsb)\n \n# measure sensor impedance\ndef read_impedance():\n prox_msb = read_reg(ProxDataMSB)\n prox_lsb = read_reg(ProxDataLSB)\n return prox2impedance(256*prox_msb + prox_lsb) \n \n# read impedance and inductance stream\ndef read_stream():\n global serial_port\n try: \n # wait until sufficient amount of data is available\n while (serial_port.inWaiting() < 2048):\n time.sleep(0.1)\n \n in_waiting = serial_port.inWaiting() \n data_str = serial_port.read(in_waiting)\n \n data = []\n for d in data_str:\n data.append(ord(d))\n \n d1 = d2 = d3 = d4 = 0\n if (in_waiting == 2048 or in_waiting == 4095):\n d1 = np.mean(data[0:1024:2])\n d2 = np.mean(data[1:1024:2])\n d3 = np.mean(data[1024:2048:2])\n d4 = np.mean(data[1025:2048:2])\n elif (in_waiting == 2049):\n d1 = np.mean(data[1:1025:2])\n d2 = np.mean(data[2:1025:2])\n d3 = np.mean(data[1025:2049:2])\n d4 = np.mean(data[1026:2049:2])\n \n return [prox2impedance(256*d1 + d2), freq2inductance(256*d3 + d4)]\n \n except serial.SerialException:\n print (\"Error reading LCD1000 in\", serial_port.port)\n return [0, 0]\n","sub_path":"머신러닝 공부/LG_current_detection/science-basement-d2d1d7809855b0fc99c386628562acd3e71757b0/candy_machine/mac/ldc1000.py","file_name":"ldc1000.py","file_ext":"py","file_size_in_byte":6439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"223055233","text":"import numpy as np\n\nNUM_TERMS = 20+1\nMID = (NUM_TERMS - 1) / 2\n\nCORR_LEN = 0.1\nCORRL2 = CORR_LEN * CORR_LEN\n\ndt = 0.001\nCORR_TIME = 1.0\ndt = CORR_TIME \nTIME_RATE = dt / CORR_TIME\nTIME_DEV = np.sqrt( dt / CORR_TIME )\nTIME_DEV_SQRT2 = np.sqrt( 2 * dt / CORR_TIME )\n\nINV_SQRT_2 = 1.0 / np.sqrt( 2 )\n\nstd_dev = INV_SQRT_2 * TIME_DEV_SQRT2\nstd_dev = INV_SQRT_2\n\nSTD_DEV = 1.0\n\nC0 = 1\nSQRT_C0 = np.sqrt( C0 )\n\nTWO_PI = 2*np.pi\nSQRT_2PI = np.sqrt( TWO_PI )\n\n\nSTR_SEP = '\\n********************************************************\\n'\n","sub_path":"simul/2D/simonvajedi@macserv5.fy.chalmers.se/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"215621302","text":"from atexit import register\nfrom re import compile\nfrom threading import Thread\nfrom time import ctime\nimport urllib\nimport urllib.request\n\n\nREGEX = compile('#([\\d,]+) in Books')\nAMZN = 'https://www.amazon.cn/dp/'\nISBNs = {\n '0132269937':'Core Python Programming',\n}\n\ndef getRanking(isbn):\n page = urllib.request.urlopen('%s%s' %(AMZN, isbn))\n data = page.read()\n print('data:---%s' %data)\n page.close()\n list = REGEX.findall(data.decode('utf-8'))\n if len(list) > 0:\n return list[0]\n else:\n return 'not found'\n\ndef _showRanking(isbn):\n Thread(target=_showRanking, args=())\n # print('---%r ranked %s' %(ISBNs[isbn], getRanking(isbn)))\n\ndef _main():\n print('At : %s' %ctime() + 'on amazon')\n for isbn in ISBNs:\n _showRanking(isbn)\n\n@register\ndef _atexit():\n print('all done:%s' %ctime())\n\nif __name__ == '__main__':\n _main()","sub_path":"CorePythonCode/fourChapter/bookrankmutiple.py","file_name":"bookrankmutiple.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608253413","text":"#! /usr/bin/env python3\n# coding: utf-8\n\n\n'''This is the main module. It contains the main function\nthat enables gameplay loop. It also initializes display window.\n'''\n\n\nimport json\nimport random\nimport pygame\nfrom pygame.locals import *\n\n\n\npygame.init() #enables sprite initialization during Display class declaration\nWINDOW = pygame.display.set_mode((750, 750))\n\nclass Macgyver:\n '''The MacGyver class represents the player-controlled character\n It handles movement, item pick-up, item storage, and game over\n '''\n\n def __init__(self, startPos):\n '''Constructor spawns the character at a given square on the grid'''\n self.position = startPos\n self.items = []\n self.current_square.content = 6\n\n @property\n def current_square(self):\n '''Syntactic sugar'''\n return GameController.SQUARE_ARRAY[self.position]\n\n\n ### SQUARE INTERACTION ###\n\n def touch_square(self):\n '''Triggers various events when the character enters an occupied square\n Items will be added to inventory\n Encounter with the warden results in either victory or defeat'''\n new_square = self.current_square\n if new_square.content == 1:\n GameController.RUNNING = False\n GameController.GAME_OVER = True\n\n if len(self.items) == 3:\n Display.STATE = \"Victory\"\n\n else:\n Display.STATE = \"Defeat\"\n \n pygame.display.flip()\n\n elif new_square.content in (2, 3, 4):\n self.add_item(new_square.content)\n\n def add_item(self, content_id):\n '''Reads entered square's content and add corresponding item to array'''\n switcher = {\n 2: \"needle\",\n 3: \"pipe\",\n 4: \"ether\"\n }\n self.items.append(switcher.get(content_id, \"invalid content_id\"))\n\n\n ### MOVEMENT ###\n\n def move_right(self):\n '''Checks grid borders using square logic, then check walls\n Moves the character using square id logic if all clear'''\n if self.current_square.x_pos < 14:\n next_position = self.position + 1\n if GameController.SQUARE_ARRAY[next_position].content != 5:\n self.position = next_position\n\n def move_up(self):\n '''Same as above'''\n if self.current_square.y_pos > 0:\n next_position = self.position - 15\n if GameController.SQUARE_ARRAY[next_position].content != 5:\n self.position = next_position\n\n def move_left(self):\n '''Same as above'''\n if self.current_square.x_pos > 0:\n next_position = self.position - 1\n if GameController.SQUARE_ARRAY[next_position].content != 5:\n self.position = next_position\n\n def move_down(self):\n '''Same as above'''\n if self.current_square.y_pos < 14:\n next_position = self.position + 15\n if GameController.SQUARE_ARRAY[next_position].content != 5:\n self.position = next_position\n\nclass Square:\n '''Square object is used to store coordinates and id\n Attributes are called to locate items and agents on the grid'''\n def __init__(self, x_pos, y_pos):\n self.x_pos = x_pos\n self.y_pos = y_pos\n self.content = 0\n\n\nclass GameController:\n '''Handles the labyrinth grid creation using dedicated json file\n Created grid is stored as an array of squares used for navigation\n Also contains useful variable to check game state'''\n\n RUNNING = True\n GAME_OVER = False\n START_SQUARE_ID = 0\n SQUARE_ARRAY = []\n\n @classmethod\n def initialize_squares(cls):\n '''Generates fresh empty grid and add items on it using the method below'''\n cls.SQUARE_ARRAY = []\n\n for i in range(0, 15):\n for j in range(0, 15):\n\n square = Square(j, i)\n cls.SQUARE_ARRAY.append(square)\n\n cls.populate_squares()\n\n\n @classmethod\n def populate_squares(cls):\n '''Creates items on squares. Nature of item is defined by an int\n that is stored in the content attribute of the square :\n 1 is warden, 2 to 4 are pick-ups, 5 is wall, 6 is character'''\n for counter, id_key in enumerate(\n json.load(open(\"ressources/wall-layout.json\"))):\n\n if counter == 0:\n cls.SQUARE_ARRAY[id_key].content = 6\n START_SQUARE_ID = id_key\n elif counter == 1:\n cls.SQUARE_ARRAY[id_key].content = 1\n else:\n cls.SQUARE_ARRAY[id_key].content = 5\n\n for i in range(2, 5):\n random_id = random.randrange(0, 225)\n\n while cls.SQUARE_ARRAY[random_id].content != 0:\n random_id = random.randrange(0, 225)\n #select new random square if current one already has content\n\n cls.SQUARE_ARRAY[random_id].content = i\n\n\nclass Display:\n '''handles sprites loading from ressources folder\n also displays them in the window, based on their position on the grid'''\n\n SPRITE_WIDTH = 50\n\n TILE_SPRITE = pygame.image.load(\"ressources/tile.png\")\n CHARACTER_SPRITE = pygame.image.load(\"ressources/character.png\")\n WARDEN_SPRITE = pygame.image.load(\"ressources/warden.png\").convert_alpha()\n NEEDLE_SPRITE = pygame.image.load(\"ressources/needle.png\").convert_alpha()\n PIPE_SPRITE = pygame.image.load(\"ressources/pipe.png\").convert_alpha()\n ETHER_SPRITE = pygame.image.load(\"ressources/ether.png\").convert_alpha()\n WALL_SPRITE = pygame.image.load(\"ressources/wall.png\")\n VICTORY_SCREEN = pygame.image.load(\"ressources/victory.jpg\")\n DEFEAT_SCREEN = pygame.image.load(\"ressources/defeat.jpg\")\n\n STATE = None\n\n @classmethod\n def refresh_display(cls):\n '''The method is called after each action (i.e when the character moves)\n Each square is refreshed, displaying eventual content atop standard tile'''\n\n if cls.STATE == \"Victory\":\n WINDOW.blit(Display.VICTORY_SCREEN, (0, 0))\n\n elif cls.STATE == \"Defeat\":\n WINDOW.blit(Display.DEFEAT_SCREEN, (0, 0))\n\n else: \n\n for square in GameController.SQUARE_ARRAY:\n\n x_pix_pos = square.x_pos * cls.SPRITE_WIDTH\n y_pix_pos = square.y_pos * cls.SPRITE_WIDTH\n\n WINDOW.blit(cls.TILE_SPRITE, (x_pix_pos, y_pix_pos))\n\n #standard tile is blitted before adding eventual content\n\n if square.content == 1:\n WINDOW.blit(cls.WARDEN_SPRITE, (x_pix_pos, y_pix_pos))\n\n elif square.content == 2:\n WINDOW.blit(cls.NEEDLE_SPRITE, (x_pix_pos, y_pix_pos))\n\n elif square.content == 3:\n WINDOW.blit(cls.PIPE_SPRITE, (x_pix_pos, y_pix_pos))\n\n elif square.content == 4:\n WINDOW.blit(cls.ETHER_SPRITE, (x_pix_pos, y_pix_pos))\n\n elif square.content == 5:\n WINDOW.blit(cls.WALL_SPRITE, (x_pix_pos, y_pix_pos))\n\n elif square.content == 6:\n WINDOW.blit(cls.CHARACTER_SPRITE, (x_pix_pos, y_pix_pos))\n\n \n pygame.display.flip()\n\n\ndef main():\n '''Initializes the grid, player's agent, and handles gameplay loop'''\n\n GameController.initialize_squares()\n character = Macgyver(GameController.START_SQUARE_ID)\n Display.refresh_display()\n\n while GameController.RUNNING:\n for event in pygame.event.get():\n if event.type == QUIT:\n GameController.RUNNING = False\n\n if (event.type == KEYDOWN and\n event.key in (K_LEFT, K_UP, K_RIGHT, K_DOWN)):\n\n character.current_square.content = 0\n\n if event.key == K_LEFT:\n character.move_left()\n\n elif event.key == K_UP:\n character.move_up()\n\n elif event.key == K_RIGHT:\n character.move_right()\n\n elif event.key == K_DOWN:\n character.move_down()\n\n character.touch_square()\n character.current_square.content = 6\n Display.refresh_display()\n\n while GameController.GAME_OVER:\n for event in pygame.event.get():\n if event.type == QUIT:\n GameController.GAME_OVER = False\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"labyrinthe.py","file_name":"labyrinthe.py","file_ext":"py","file_size_in_byte":8429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"302099176","text":"import copy\r\nimport math\r\nclass Graph(object):\r\n \r\n def __init__(self, vertices):\r\n self.__dictionaryIn = {}\r\n self.__dictionaryOut = {}\r\n self.__dictionaryCosts = {}\r\n\r\n for i in range(vertices):\r\n self.__dictionaryOut[i] = []\r\n self.__dictionaryIn[i] = []\r\n\r\n def parse_keys(self):\r\n return list(self.__dictionaryOut.keys())\r\n\r\n def parse_out_neighbours(self, vertex):\r\n try:\r\n return list(self.__dictionaryOut[vertex])\r\n except KeyError:\r\n raise Exception(\"Inexistent vertex\")\r\n\r\n \r\n '''\r\n --> breadth-first traversal\r\n input: the source vertex\r\n output: the list of visited nodes during traversal, the list of predecessors for each visited node\r\n '''\r\n def minimum_path(self, first_vertex):\r\n tail= [] #used for breadth-first traversal\r\n predecessor= [] # list of predecessors, where predecessor[x] is the predecessor of node x\r\n for i in range(0,self.get_nr_of_vertices()):\r\n predecessor.append(None)\r\n visited= [] # list of visited nodes during traversal\r\n tail.append(first_vertex)\r\n visited.append(first_vertex)\r\n while(len(tail) != 0):\r\n x = tail.pop(0);\r\n for y in self.parse_out_neighbours(x):\r\n if y not in visited:\r\n tail.append(y)\r\n visited.append(y)\r\n predecessor[y] = x\r\n accessible = visited.copy()\r\n return accessible, predecessor\r\n \r\n \r\n # In this function, we are going to build the minimal cost path between two vertices\r\n # input: -> two vertices, the source and the destination\r\n # -> a list with predecessors\r\n # output: -> a list containing all the vertices that are used in the minimal cost walk\r\n def getMinimalCostPath(self,first_vertex,second_vertex,previous):\r\n path = []\r\n destination_path = second_vertex\r\n path.append(destination_path)\r\n while(destination_path != first_vertex):\r\n destination_path = previous[destination_path]\r\n path.append(destination_path)\r\n return path\r\n \r\n \r\n # Bellman-Ford Algorithm\r\n # input: two vertices, the source and the destination\r\n # output: -> distance - a list of minimal cost walks from the source to each vertex\r\n # -> path - a list containing all the vertices used in the minimal cost walk between source and destination\r\n def minimumCostWalk(self,first_vertex,second_vertex): \r\n \r\n distance = []\r\n previous = []\r\n negative_cost_cycle = False;\r\n edges = self.return_edges()\r\n #we create a list with nr_of_vertices positions, containing infinity values\r\n for _ in range(0,self.get_nr_of_vertices()):\r\n distance.append(math.inf)\r\n #create a list with nr_of_vertices positions, containing initially -1 value\r\n for _ in range(0,self.get_nr_of_vertices()):\r\n previous.append(-1)\r\n #we initialize the starting distance path with 0\r\n distance[first_vertex] = 0\r\n \r\n for _ in self.parse_keys():\r\n changed = False\r\n \r\n for (x,y) in edges:\r\n # for each edge we check if there is a better walk cost\r\n if distance[y] > distance[x] + self.__dictionaryCosts[(x,y)]:\r\n distance[y] = distance[x] + self.__dictionaryCosts[(x,y)]\r\n previous[y] = x\r\n changed = True\r\n if changed == False:\r\n #if there are no changes on the distance list, we exit the loop\r\n break\r\n \r\n #now, we are looking for negative cost cycles , and if so, we raise an exception\r\n for (x,y) in edges:\r\n if distance[y] > distance[x] + self.__dictionaryCosts[(x,y)]:\r\n negative_cost_cycle = True;\r\n break;\r\n if negative_cost_cycle == True:\r\n raise Exception(\"This graph have negative cost cycles !\") \r\n \r\n #we are building the path of the minimal cost walk using getMinimalCostPath function\r\n path = self.getMinimalCostPath(first_vertex,second_vertex,previous) \r\n \r\n return distance, path\r\n \r\n \r\n \r\n def parse_in_neighbours(self, vertex):\r\n try:\r\n return list(self.__dictionaryIn[vertex])\r\n except KeyError:\r\n raise Exception(\"Inexistent vertex\")\r\n\r\n \r\n def is_edge(self, vertex1, vertex2):\r\n try:\r\n return vertex2 in self.__dictionaryOut[vertex1]\r\n except KeyError:\r\n raise Exception(\"Non existent edge !\")\r\n\r\n\r\n def add_edge(self, vertex1, vertex2, cost):\r\n exception_message = \"\"\r\n if self.is_edge(vertex1, vertex2):\r\n exception_message += \"The edge from vertex1 to vertex 2 already exists! \"\r\n if len(exception_message) > 0:\r\n raise Exception(exception_message)\r\n self.__dictionaryOut[vertex1].append(vertex2)\r\n self.__dictionaryIn[vertex2].append(vertex1)\r\n self.__dictionaryCosts[(vertex1, vertex2)] = cost\r\n\r\n\r\n def add_vertex(self, vertex):\r\n if vertex in self.parse_keys():\r\n raise Exception(\"This vertex already exists in the graph\")\r\n self.__dictionaryOut[vertex] = []\r\n self.__dictionaryIn[vertex] = []\r\n\r\n def get_cost(self, vertex1, vertex2):\r\n if self.is_edge(vertex1, vertex2):\r\n return self.__dictionaryCosts[(vertex1, vertex2)]\r\n else:\r\n raise Exception(\"Non existent edge!\")\r\n\r\n \r\n def isolated_vertices(self):\r\n vertices = []\r\n for key in self.parse_keys():\r\n if self.__dictionaryIn[key] == [] and self.__dictionaryOut == []:\r\n vertices.append(key)\r\n return vertices[:]\r\n\r\n \r\n def remove_vertex(self, vertex):\r\n if vertex not in self.parse_keys():\r\n raise Exception(\"Vertex doesn't exist\")\r\n for vertex2 in self.__dictionaryOut[vertex]:\r\n self.__dictionaryIn[vertex2].remove(vertex)\r\n del self.__dictionaryCosts[(vertex, vertex2)]\r\n del self.__dictionaryOut[vertex]\r\n for vertex2 in self.__dictionaryIn[vertex]:\r\n self.__dictionaryOut[vertex2].remove(vertex)\r\n del self.__dictionaryCosts[(vertex2, vertex)]\r\n del self.__dictionaryIn[vertex]\r\n\r\n \r\n def remove_edge(self, vertex1, vertex2):\r\n if not self.is_edge(vertex1, vertex2):\r\n raise Exception(\"This edge doesn't exist\")\r\n del self.__dictionaryCosts[(vertex1, vertex2)]\r\n self.__dictionaryOut[vertex1].remove(vertex2)\r\n self.__dictionaryIn[vertex2].remove(vertex1)\r\n\r\n def get_nr_of_vertices(self):\r\n return len(self.parse_keys())\r\n\r\n \r\n def get_out_degree(self, vertex):\r\n try:\r\n return len(self.__dictionaryOut[vertex])\r\n except KeyError:\r\n raise Exception(\"The vertex doesn't exist\")\r\n\r\n \r\n def get_in_degree(self, vertex):\r\n try:\r\n return len(self.__dictionaryIn[vertex])\r\n except KeyError:\r\n raise Exception(\"The vertex doesn't exist\")\r\n\r\n \r\n def change_edge_cost(self, vertex1, vertex2, cost):\r\n if (vertex1, vertex2) in self.__dictionaryCosts:\r\n self.__dictionaryCosts[(vertex1, vertex2)] = cost\r\n else:\r\n raise Exception(\"The edge doesn't exist\")\r\n\r\n def copy_the_graph(self):\r\n new_graph = Graph(10)\r\n new_graph.__dictionaryIn = copy.deepcopy(self.__dictionaryIn)\r\n new_graph.__dictionaryOut = copy.deepcopy(self.__dictionaryOut)\r\n new_graph.__dictionaryCosts = copy.deepcopy(self.__dictionaryCosts)\r\n return new_graph\r\n\r\n \r\n def return_edges(self):\r\n edges = []\r\n for edge in self.__dictionaryCosts:\r\n edges.append(edge)\r\n return edges[:]\r\n\r\n \r\n def return_costs(self):\r\n costs = []\r\n for cost in self.__dictionaryCosts:\r\n costs.append(self.__dictionaryCosts[cost])\r\n return costs[:]\r\n\r\n \r\n def save_to_file(self, fileName):\r\n with open(fileName,\"w\") as f:\r\n f.write(str(self))\r\n\r\n def __str__(self):\r\n string = \"\"\r\n for key in self.__dictionaryCosts:\r\n string += \"Source: \"\r\n string+= str(key[0])\r\n string+=\" // \"\r\n string+= \"Destination: \"\r\n string+=str(key[1])\r\n string+=\" // \"\r\n string+= \"Cost: \"\r\n string+=str(self.__dictionaryCosts[key])\r\n string+='\\n'\r\n return string\r\n\r\n","sub_path":"Practical work no.3/GraphsLab3/Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"261958686","text":"\"\"\"\n\nhttps://leetcode.com/problems/longest-repeating-character-replacement/\n대문자로 구성된 문자열 s가 주어졌을 때 k번 만큼의 변경으로 만들 수 있는,\n연속으로 반복된 문자열의 가장 긴 길이를 출력하라\n\nInput: s = \"ABAB\", k = 2\nOutput: 4\nExplanation: Replace the two 'A's with two 'B's or vice versa.\n\nInput: s = \"AABABBA\", k = 1\nOutput: 4\nExplanation: Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.\n\n\"\"\"\n\n\n# AABABBA\n#\nfrom collections import Counter\n\n\nclass Solution:\n\n def characterReplacement(self, s: str, k: int) -> int:\n\n # 가장 많이 사용된 값이 유리?\n right = left = 0\n\n counter = Counter()\n for right in range(1, len(s) + 1):\n counter[s[right - 1]] += 1\n # 가장 흔하게 등장하는 문자 탐색\n max_char_n = counter.most_common(1)[0][1]\n\n # 가장 흔하게 등장하는 문자를 카운트하는데, 오른쪽 - 왼쪽 - 흔문자 가 k보다 크다는건,\n # 교체할 수 있는 조건이 더이상 성립되지 않는다.\n # 그러므로, 가장 왼쪽의 값을 뺀다.\n if right - left - max_char_n > k:\n counter[s[left]] -= 1\n left += 1\n return right - left\n\n\n# def characterReplacement(self, s, k):\n# result, max_count = 0, 0\n# count = collections.Counter()\n# for i in xrange(len(s)):\n# count[s[i]] += 1\n# max_count = max(max_count, count[s[i]])\n# if result - max_count >= k:\n# count[s[i-result]] -= 1\n# else:\n# result += 1\n# return result\n\n\nSolution().characterReplacement(\"AABABBA\", 1)\n","sub_path":"archive-len/leetcode/ch20-sliding-window/p77-longest-repeating-charater-replacement.py","file_name":"p77-longest-repeating-charater-replacement.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383290356","text":"class Solution:\n def longestPalindrome(self, s: str) -> str:\n n, start, end = len(s), 0, 0\n if n in [0, 1]:\n return s\n def palindromeLength(l, r):\n while l >= 0 and r < n and s[l] == s[r]:\n l, r = l - 1, r + 1\n return r - l - 1\n for i in range(n):\n maxPalindromeLength = max(palindromeLength(i, i), palindromeLength(i, i + 1))\n if maxPalindromeLength > end - start:\n end, start = i + (maxPalindromeLength // 2), i - ((maxPalindromeLength - 1) // 2)\n return s[start : end + 1]","sub_path":"LeetCode/January Leetcoding Challenge/Longest Palindromic Substring.py","file_name":"Longest Palindromic Substring.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113910379","text":"# additional test for comparing tables\ndef tables_are_same(t1, t2):\n same_labels = set(t1.labels) == set(t2.labels)\n if not same_labels:\n return f\"Expected labels '{', '.join(t1.labels)}', found labels '{', '.join(t2.labels)}''\"\n \n for label in t1.labels:\n t1_sorted = t1.sort(label)\n t2_sorted = t2.sort(label)\n c1 = t1_sorted.column(label)\n c2 = t2_sorted.column(label)\n \n if c1.dtype == float:\n if not all((c1 - c2) < 1e-6):\n return f\"Column '{label}' has values that don't match expected values\"\n else:\n if not all(c1 == c2):\n return f\"Column '{label}' has values that don't match expected values\"\n \n return True\n \n","sub_path":"utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"564841898","text":"from django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom .views import (\n TrackListAPIView,\n TrackDetailAPIView,\n TrackCreateAPIView,\n TrackUpdateAPIView,\n TrackDeleteAPIView,\n TrackFeaturedListAPIView,\n)\n\n\nurlpatterns = [\n url(r'^$', TrackListAPIView.as_view(), name='track_list'),\n url(r'^create/$', TrackCreateAPIView.as_view(), name='track_create'),\n url(r'^featured/$', TrackFeaturedListAPIView.as_view(), name='track_featured_list'),\n url(r'^(?P[\\w-]+)/$', TrackDetailAPIView.as_view(), name='track_detail'),\n url(r'^(?P[\\w-]+)/edit/$', TrackUpdateAPIView.as_view(), name='track_update'),\n url(r'^(?P[\\w-]+)/delete/$', TrackDeleteAPIView.as_view(), name='track_delete'),\n # url(r'^posts/$', \".views.\"),\n\n\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"track/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"162218252","text":"import pandas as pd\nimport numpy as np\n\nCSV_COLUMN_NAMES = [\n \"service1_inst\",\n \"service2_inst\",\n \"service3_inst\",\n \"service1_mem\",\n \"service2_mem\",\n \"service3_mem\",\n \"time_span\",\n \"result\"\n]\n\nCSV_COLUNV_TYPE = {\n \"service1_inst\": np.int32,\n \"service2_inst\": np.int32,\n \"service3_inst\": np.int32,\n \"service1_mem\": np.int32,\n \"service2_mem\": np.int32,\n \"service3_mem\": np.int32,\n \"time_span\": pd.Categorical,\n \"result\": np.int32\n\n\n}\n\ntrain_path = \"train_origin.csv\"\ntrain = pd.read_csv(train_path,\n names=CSV_COLUMN_NAMES,\n header=0)\n\ntrain[\"time_span\"] = train[\"time_span\"].astype(\"category\")\n\ntrain[\"time_span\"] = train[\"time_span\"].cat.set_categories([\n \"below 1\",\n \"below 2\",\n \"below 3\",\n \"below 6\",\n \"below 10\",\n \"above 10\"])\n\n# 特征有大小意义的采用映射编码\n\ntime_span_mapping = {\n \"below 1\": 1,\n \"below 2\": 2,\n \"below 3\": 3,\n \"below 6\": 4,\n \"below 10\": 5,\n \"above 10\": 6\n}\n\ntrain[\"time_span\"] = train[\"time_span\"].map(time_span_mapping)\n\nprint(train)\n\n# 特征有大小无意义采用独热编码\n\ntrain = pd.read_csv(train_path,\n names=CSV_COLUMN_NAMES,\n header=0)\n\ndf = pd.get_dummies(train, prefix=['time_span'])\n\ndf.to_csv('dummy_train.csv')\n\n# 区间编码\n\nbin = [0, 100, 200, 300, 1500]\n\ntrain = pd.read_csv(train_path,\n names=CSV_COLUMN_NAMES,\n header=0)\n\n\n\n# train[\"service1_mem\"] = pd.cut(train[\"service1_mem\"], bin)\n#\n# print(train[\"service1_mem\"])\n\n# 区间编码分区并打label\n\ntrain[\"service1_mem\"] = pd.cut(train[\"service1_mem\"], bin, labels=['Low', 'Middle', 'High', 'Senior'])\n\n\nprint(train[\"service1_mem\"])\n\nprint(train[\"service1_mem\"].values)\n\n","sub_path":"ml/log_analyzer/python3/sklearn/decsion_tree/data_manage.py","file_name":"data_manage.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"481455867","text":"# Time complexity - O(logn)\n# Space complexity - O(1)\n# Works on leetcode - yes \n\nclass Solution(object):\n #function to find the target element in sorted array of infinite size\n # to apply binary search, we find the bounds first and then perform binary search within bounds\n # low and high bound start from 0 and 1 respectively. We see if the high element is less than target.\n # if it is, then the high index becomes the low index and we double the high index. \n def search(self, arr, target):\n \"\"\"\n :type reader: Array\n :type target: int\n :rtype: int\n \"\"\"\n low,high, val = 0,1, arr[0]\n while valtarget:\n h = mid -1\n else:\n l = mid +1\n return -1","sub_path":"Problem2.py","file_name":"Problem2.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"352155940","text":"__author__ = 'Muneer'\n\nimport pygame\nSCREENW = 1440\nSCREENH = 700\nscreen = pygame.display.set_mode((SCREENW, SCREENH))\nclock = pygame.time.Clock()\nBLACK = (0,0,0)\nASTSPEED = 5\nCENTER = (SCREENW/2, SCREENH/2)\nSCREENLENGTHS = (SCREENW, SCREENH)\nMAX_BULLETS = 3","sub_path":"Consts.py","file_name":"Consts.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"648806826","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .backbones import resnet\nfrom nn import Conv2d, fcos_loss\n\n\nclass FCOS(nn.Module):\n def __init__(self,\n device,\n input_size=None,\n num_classes=20,\n trainable=False,\n conf_thresh=0.01,\n nms_thresh=0.5):\n super(FCOS, self).__init__()\n self.device = device\n self.num_classes = num_classes\n self.trainable = trainable\n self.conf_thresh = conf_thresh\n self.nms_thresh = nms_thresh\n self.input_size = input_size\n self.location_weight = torch.tensor([[-1, -1, 1, 1]]).float().to(device)\n self.stride = [8, 16, 32, 64]\n self.scale_thresholds = [0, 49, 98, 196, 1e10]\n self.grid_cell = self._create_grid(input_size)\n self.scale = np.array([[input_size[1], input_size[0], input_size[1], input_size[0]]])\n self.scale_torch = torch.tensor(self.scale.copy()).float()\n\n self.backbone = resnet('resnet18', pretrained=trainable)\n\n # neck:FPN P6 P5 P4 P3\n self.neck = FPN()\n\n self.pred_6 = nn.Sequential(Conv2d(512, 1024, 3, padding=1),\n nn.Conv2d(1024, 1 + self.num_classes + 1 + 4, 1))\n self.pred_5 = nn.Sequential(Conv2d(256, 512, 3, padding=1),\n nn.Conv2d(512, 1 + self.num_classes + 1 + 4, 1))\n self.pred_4 = nn.Sequential(Conv2d(128, 256, 3, padding=1),\n nn.Conv2d(256, 1 + self.num_classes + 1 + 4, 1))\n self.pred_3 = nn.Sequential(Conv2d(64, 128, 3, padding=1),\n nn.Conv2d(128, 1 + self.num_classes + 1 + 4, 1))\n\n def _create_grid(self, input_size):\n grid_length = sum([(input_size[0] // s) * (input_size[1] // s) for s in self.stride])\n grid_xy = torch.zeros(grid_length, 4)\n start_idx = 0\n\n for idx in range(len(self.stride)):\n s = self.stride[idx]\n w, h = input_size[1] // s, input_size[0] // s\n for y in range(h):\n for x in range(w):\n x_y = y * w + x\n index = x_y + start_idx\n xx = x * s + s // 2\n yy = y * s + s // 2\n grid_xy[index, :] = torch.tensor([xx, yy, xx, yy]).float()\n start_idx += w * h\n return grid_xy.to(self.device)\n\n def set_grid(self, input_size):\n self.input_size = input_size\n self.grid_cell = self._create_grid(input_size)\n\n def _clip_boxes(self, boxes, im_shape):\n \"\"\"\n Clip boxes to image boundaries.\n \"\"\"\n if boxes.shape[0] == 0:\n return boxes\n # assert x1 >= 0\n boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)\n # y1 >= 0\n boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)\n # x2 < im_shape[1]\n boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0)\n # y2 < im_shape[0]\n boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0)\n return boxes\n\n def _nms(self, dets, scores):\n # From faster rcnn nms\n \"\"\"\"Pure Python NMS baseline.\"\"\"\n x1 = dets[:, 0] #xmin\n y1 = dets[:, 1] #ymin\n x2 = dets[:, 2] #xmax\n y2 = dets[:, 3] #ymax\n\n areas = (x2 - x1) * (y2 - y1) # bbox的宽w和高h\n order = scores.argsort()[::-1] # 按照降序对bbox的得分进行排序\n\n keep = [] # 用于保存经过筛的最终bbox结果\n while order.size > 0:\n i = order[0] # 得到最高的那个bbox\n keep.append(i)\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(1e-28, xx2 - xx1)\n h = np.maximum(1e-28, yy2 - yy1)\n inter = w * h\n\n # Cross Area / (bbox + particular area - Cross Area)\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n #reserve all the boundingbox whose ovr less than thresh\n inds = np.where(ovr <= self.nms_thresh)[0]\n order = order[inds + 1]\n\n return keep\n\n def _postprocess(self, bbox_pred, prob_pred):\n \"\"\"\n Arguments:\n bbox_pred: (W*H, 4), bsize = 1\n prob_pred: (W*H, num_classes), bsize = 1\n \"\"\"\n # Get the most possilble class pred in each grid\n class_idx = np.argmax(prob_pred, axis=1)\n prob_pred = prob_pred[(np.arange(prob_pred.shape[0]), class_idx)]\n\n # filter out preds with low score\n pred_keep = np.where(prob_pred >= self.conf_thresh)\n bbox_pred = bbox_pred[pred_keep]\n prob_pred = prob_pred[pred_keep]\n class_idx = class_idx[pred_keep]\n\n keep = np.zeros(len(bbox_pred), dtype=np.int)\n for i in range(self.num_classes):\n idxs = np.where(class_idx == i)[0]\n if len(idxs) == 0:\n continue\n cls_bboxes = bbox_pred[idxs]\n cls_scores = prob_pred[idxs]\n cls_keep = self._nms(cls_bboxes, cls_scores)\n keep[idxs[cls_keep]] = 1\n\n keep = np.where(keep > 0)\n bbox_pred = bbox_pred[keep]\n prob_pred = prob_pred[keep]\n class_idx = class_idx[keep]\n\n return bbox_pred, prob_pred, class_idx\n\n def forward(self, x, targets=None):\n backbone_out = self.backbone(x)\n neck_out = self.neck(backbone_out)\n P3, P4, P5, P6 = neck_out\n batch_size = P3.shape[0]\n\n pred_3 = self.pred_3(P3).view(batch_size, 1 + self.num_classes + 1 + 4, -1)\n pred_4 = self.pred_4(P4).view(batch_size, 1 + self.num_classes + 1 + 4, -1)\n pred_5 = self.pred_5(P5).view(batch_size, 1 + self.num_classes + 1 + 4, -1)\n pred_6 = self.pred_6(P6).view(batch_size, 1 + self.num_classes + 1 + 4, -1)\n\n total_pred = torch.cat([pred_3, pred_4, pred_5, pred_6], dim=-1).permute(0, 2, 1)\n\n if self.trainable:\n cls_loss, ctn_loss, box_loss, total_loss = fcos_loss(total_pred,\n targets,\n num_classes=self.num_classes)\n return cls_loss, ctn_loss, box_loss, total_loss\n else:\n with torch.no_grad():\n # batch size = 1\n # Be careful, the index 0 in all_cls is background !!\n all_class_pred = torch.sigmoid(total_pred[0, :, 1:1 + self.num_classes])\n all_centerness = torch.sigmoid(total_pred[0, :, 1 + self.num_classes:1 +\n self.num_classes + 1])\n all_bbox_pred = torch.exp(total_pred[0, :, 1 + self.num_classes +\n 1:]) * self.location_weight + self.grid_cell\n # separate box pred and class conf\n all_class_pred = all_class_pred.to('cpu').numpy()\n all_centerness = all_centerness.to('cpu').numpy()\n all_bbox_pred = all_bbox_pred.to('cpu').numpy()\n\n bboxes, scores, cls_inds = self._postprocess(all_bbox_pred, all_class_pred)\n # clip the boxes\n bboxes = self._clip_boxes(bboxes, self.input_size) / self.scale\n\n return bboxes, scores, cls_inds\n\n\nclass FPN(nn.Module):\n \"\"\"yolov3like\n \"\"\"\n def __init__(self):\n super(FPN, self).__init__()\n # process c5 to c6\n self.conv_3x3_6 = Conv2d(512, 1024, 3, padding=1, stride=2)\n\n # c projects to p\n self.conv_set_6 = nn.Sequential(\n Conv2d(1024, 512, 1),\n Conv2d(512, 1024, 3, padding=1),\n Conv2d(1024, 512, 1),\n )\n self.conv_set_5 = nn.Sequential(Conv2d(512, 256, 1), Conv2d(256, 512, 3, padding=1),\n Conv2d(512, 256, 1))\n self.conv_set_4 = nn.Sequential(Conv2d(384, 128, 1), Conv2d(128, 256, 3, padding=1),\n Conv2d(256, 128, 1))\n self.conv_set_3 = nn.Sequential(Conv2d(192, 64, 1), Conv2d(64, 128, 3, padding=1),\n Conv2d(128, 64, 1))\n self.conv_1x1_5 = Conv2d(256, 128, 1)\n self.conv_1x1_4 = Conv2d(128, 64, 1)\n\n def upsamplelike(self, inputs, do_conv_fn=None):\n src, target = inputs\n if do_conv_fn is not None:\n src = do_conv_fn(src)\n return F.interpolate(src,\n size=(target.shape[2], target.shape[3]),\n mode='bilinear',\n align_corners=True)\n\n def forward(self, x):\n C3, C4, C5 = x\n C6 = self.conv_3x3_6(C5)\n\n P6 = self.conv_set_6(C6)\n\n P5 = self.conv_set_5(C5)\n P5_up = self.upsamplelike([P5, C4], self.conv_1x1_5)\n\n P4 = torch.cat([C4, P5_up], dim=1)\n P4 = self.conv_set_4(P4)\n P4_up = self.upsamplelike([P4, C3], self.conv_1x1_4)\n\n P3 = torch.cat([C3, P4_up], dim=1)\n P3 = self.conv_set_3(P3)\n\n return [P3, P4, P5, P6]\n","sub_path":"models/tinyfcos.py","file_name":"tinyfcos.py","file_ext":"py","file_size_in_byte":9374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"477677831","text":"import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nimport csv\n\ncap = cv.VideoCapture(0)\ncenter = np.array([[100,100]])\nhwidth = 1\n\nface_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')\n\nfeature_params = {'maxCorners': 100, 'qualityLevel': 0.3, 'minDistance': 7, 'blockSize': 7}\n\nlk_params = dict(winSize=(20, 20),\n maxLevel=2,\n criteria=(cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 5, 0.01))\n# Create some random colors\ncolor = np.random.randint(0, 255, (100, 3))\n# Take first frame and find corners in it\nret, old_frame = cap.read()\nold_gray = cv.cvtColor(old_frame, cv.COLOR_BGR2GRAY)\np0 = cv.goodFeaturesToTrack(old_gray, 5, 0.01, 5)\n\n\n# Create a mask image for drawing purposes\nmask = np.zeros_like(old_frame)\nwhile True:\n ret, frame = cap.read()\n frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n # calculate optical flow\n\n num = len(p0)\n # if num < 5:\n faces = face_cascade.detectMultiScale(old_gray, 1.3, 5)\n for (x, y, w, h) in faces:\n hwidth = 0.5 * w\n center = ([[x + (0.5 * w), y + (0.5 * h)]])\n cv.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\n j=0 \n print('hwidth', hwidth)\n print('before fix', p0)\n for i in p0:\n dist = np.linalg.norm(i[0] - center[0])\n print('dist', dist)\n # or np.sum(i[0]) < 0\n if dist > hwidth :\n print('should fix')\n p0 = np.delete(p0, j, axis = 0)\n j=j-1\n j=j+1\n print('after fix', p0)\n\n while len(p0) < 5:\n ret, frame = cap.read()\n frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(frame_gray, 1.3, 5)\n for (x, y, w, h) in faces: # draw the boxes around any face detections\n old_gray = cv.cvtColor(old_frame, cv.COLOR_BGR2GRAY)\n crop_img = old_gray[y:y + h, x:x + w]\n temp = cv.goodFeaturesToTrack(crop_img, 5, 0.1, 5)\n print('look here t', temp)\n for i in temp:\n i[0] = i[0] + [x, y]\n num = len(p0)\n print('num',num)\n if num < 1:\n p0 = temp\n print('called first')\n else:\n print('called concate')\n p0 = np.concatenate((p0, temp))\n print('look here p', p0)\n\n print('p0', p0)\n print('centre',center)\n p1, st, err = cv.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)\n # Select good points\n good_new = p1\n d = np.squeeze(p1, axis=None)\n \n with open('data.csv', 'a') as csvFile:\n writer = csv.writer(csvFile)\n print('output', d[0])\n writer.writerow(d[0])\n \n \n\n csvFile.close()\n # np.savetxt(\"data.csv\", d, delimiter=',')\n good_old = p0\n # draw the tracks\n for i, (new, old) in enumerate(zip(good_new, good_old)):\n a, b = new.ravel()\n c, d = old.ravel()\n # mask = cv.line(mask, (a,b),(c,d), color[i].tolist(), 2)\n frame = cv.circle(frame, (a, b), 5, color[i].tolist(), -1)\n # crop_img = cv.circle(crop_img,(a,b),5,color[i].tolist(),-1)\n img = frame\n\n cv.imshow('frame', img)\n # if len(crop_img) > 0:\n # cv.imshow('frame2',crop_img)\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n # Now update the previous frame and previous points\n old_gray = frame_gray.copy()\n p0 = good_new.reshape(-1, 1, 2)\n\ncv.destroyAllWindows()\ncap.release()\n","sub_path":"lkTracker.py","file_name":"lkTracker.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"116409376","text":"from django.http import HttpResponse\nfrom django.template import loader\nfrom ..db import get_instrument, get_instrument_albums, get_instruments, get_instrument_albums_search, delete_instrument\nfrom django.conf import settings\n\n\ndef instrument_delete(request, instrument_id):\n instrument = get_instrument(instrument_id)\n delete_instrument(instrument_id)\n template = loader.get_template('flac/instrument_deleted.html')\n return HttpResponse(template.render({\n 'instrument': instrument,\n }, request))\n\n\ndef instrument_search(request, instrument_id, query):\n template = loader.get_template('flac/instrument.html')\n context = {\n 'items': get_instrument_albums_search(instrument_id, query),\n 'instrument': get_instrument(instrument_id),\n 'instruments_path': settings.INSTRUMENTS_PATH,\n 'instrument_id': instrument_id,\n 'query': query,\n }\n return HttpResponse(template.render(context, request))\n\n\ndef instrument(request, instrument_id):\n template = loader.get_template('flac/instrument.html')\n context = {\n 'items': get_instrument_albums(instrument_id),\n 'instrument': get_instrument(instrument_id),\n 'instruments_path': settings.INSTRUMENTS_PATH,\n 'instrument_id': instrument_id,\n }\n return HttpResponse(template.render(context, request))\n\n\ndef instrumenten(request):\n context = {\n 'items': get_instruments(),\n 'instruments_path': settings.INSTRUMENTS_PATH\n }\n template = loader.get_template('flac/instrumenten.html')\n return HttpResponse(template.render(context, request))\n","sub_path":"views/instrument.py","file_name":"instrument.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"88250441","text":"import os\nfrom dotenv import load_dotenv\nfrom discord.ext import commands\nfrom requests import Request, Session\nfrom requests.exceptions import ConnectionError, Timeout, TooManyRedirects\nimport json\nimport datetime\n\nload_dotenv()\nCMC_KEY = os.getenv('CMC_KEY')\nBOT_CRYPTO_CHANNEL = int(os.getenv('BOT_CRYPTO_CHANNEL'))\n\n\nclass Crypto(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n def getprice(self):\n url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'\n parameters = {\n 'start': '1',\n 'limit': '10',\n 'convert': 'USD'\n }\n headers = {\n 'Accepts': 'application/json',\n 'X-CMC_PRO_API_KEY': CMC_KEY,\n }\n\n session = Session()\n session.headers.update(headers)\n\n try:\n response = session.get(url, params=parameters)\n data = json.loads(response.text)\n price = data['data'][0]['quote']['USD']['price']\n time = data['data'][0]['last_updated']\n newtime = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S.%fZ')\n return (price, newtime)\n except (ConnectionError, Timeout, TooManyRedirects) as e:\n print(e)\n return ('error', 'error')\n\n @commands.command(name='BTC')\n @commands.has_role('neab')\n async def BTC(self, message):\n #print('made it to BTC2')\n message_channel = self.bot.get_channel(BOT_CRYPTO_CHANNEL)\n #print('made it to crypto.message_channel')\n price, newtime = Crypto.getprice(self)\n #print('made it to Crypto price and newtime')\n await message.send('The CoinMarketCap price of Bitcoin is ${0:,.2f} USD as of {1}'.format(price, newtime))\n\n\ndef setup(bot):\n bot.add_cog(Crypto(bot)) # instantiates Crypto cog","sub_path":"cogs/Crypto.py","file_name":"Crypto.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"273465499","text":"import json\nfrom urllib import urlopen\nimport sqlite3\n\n#Issac Rodriguez sprint 2\n#Take api and put data into SQL database table\n#Page 3 _\nconn=sqlite3.connect('GithubJobs.db')\nc=conn.cursor()\n\ndef loading():\n url = 'https://jobs.github.com/positions.json?page=3' # URL for API 1-5json_obj = urllib.urlopen(url)\n response = urlopen(url)\n data = json.load(response) # loads the url and set it into data variable\n\n for item in data[0].keys():\n return data # Get the keys\n\ndef createDB(data):\n conn = sqlite3.connect('GithubJobs.db')\n c = conn.cursor()\n # Create table\n c.execute('''CREATE TABLE IF NOT EXISTS comp\n (description text primary key, title text ,url text,compnay_logo text, company text ,id text ,company_url text,how_to_apply text, location text, type text ,created_at timestamp\n )''') #company, compnay_logo text ,company_url text,created_at timestamp,description,how_to_apply text ,id text,location text,title text,type text ,url text \n temp_values = list(tuple())\n for item in data:\n list_of_values = [v for k, v in item.items()]\n tuple_of_values = tuple(list_of_values)\n temp_values.append(tuple_of_values)\n\n\n c.executemany('INSERT INTO comp VALUES (?,?,?,?,?,?,?,?,?,?,?)', temp_values)\n conn.commit()\n print(\"Table Sucessfull! page 3\")\n\ndef ParseData():\n c.execute(\"\"\" SELECT * FROM comp \"\"\")\n data=c.fetchall\n for row in data(): #automated test to show data being stored in database\n print(len(row)) #automated test to show how many rows in database stored \n print(\"Rows Sucessfully stored in Database\")\n\ndef main():\n data = loading()\n createDB(data)\n\nmain()\nParseData()\n\n\n\n","sub_path":"SQLDataEntry3.py","file_name":"SQLDataEntry3.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497458509","text":"#!/usr/bin/env python\n# _*_coding:utf-8_*_\n# Author: create by yang.hong\n# Time: 2018-11-06 14:05\n\nimport sys\nimport re\nfrom subprocess import check_output\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nbranch = sys.argv[1].split('/')[2]\nold_commit = sys.argv[2]\nnew_commit = sys.argv[3]\ntag_re = re.compile(r\"^[0-9]{1,}\\.[0-9]{1,}\\.[0-9]{1,}$\")\ntag_branch = check_output(['git', 'branch', '--contains', new_commit]).strip('* ').strip('\\n')\n\nprint(\"%s from %s to %s\" % (branch, old_commit, new_commit))\n\n\ndef check_tips():\n print(u'''%s 更新失败.\n分支命名规则: dev_xxxx、test_xxxx、hotfix_xxxx、master.\n版本命名规则: 0.0.1, Tag必须从master创建.\n关于代码规范请参考 http://172.28.250.117:8090/pages/viewpage.action?pageId=5996643''' % branch)\n sys.exit(1)\n\n\n# 规则1 检查tag规范\ndef check_tag():\n if tag_re.findall(branch) and tag_branch == 'master':\n print(u'%s 版本更新成功.' % branch)\n sys.exit(0)\n\n\n# 规则2 检查分支命名\ndef check_branch():\n if branch.startswith('dev_') or branch.startswith('test_') or branch.startswith('hotfix_') or branch == 'master':\n print(u'%s 分支更新成功.' % branch)\n sys.exit(0)\n else:\n return check_tips()\n\n\n# 规则启用\ncheck_tag()\ncheck_branch()\n","sub_path":"devops/gitlab-api/git-hook/server/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"166297561","text":"import os\nimport cv2\nimport numpy as np\nfrom pycocotools.coco import COCO\nfrom torch.utils.data import Dataset\n\n\nclass COCODataset(Dataset):\n def __init__(self, root_dir, set_name='train2017', transform=None):\n self.root_dir = root_dir\n self.set_name = set_name\n self.transform = transform\n\n self.coco = COCO(os.path.join(self.root_dir, 'annotations', 'instances_' + self.set_name + '.json'))\n self.image_ids = self.coco.getImgIds()\n self.load_classes()\n\n def load_classes(self):\n # load class names (name -> label)\n categories = self.coco.loadCats(self.coco.getCatIds())\n categories.sort(key=lambda x: x['id'])\n\n self.classes = {}\n for c in categories:\n self.classes[c['name']] = len(self.classes)\n\n # also load the reverse (label -> name)\n self.labels = {}\n for key, value in self.classes.items():\n self.labels[value] = key\n\n def __len__(self):\n return len(self.image_ids)\n\n def __getitem__(self, idx):\n img = self.load_image(idx)\n annot = self.load_annotations(idx)\n sample = {'img': img, 'annot': annot}\n if self.transform:\n sample = self.transform(sample)\n return sample\n\n def load_image(self, image_index):\n image_info = self.coco.loadImgs(self.image_ids[image_index])[0]\n path = os.path.join(self.root_dir, self.set_name, image_info['file_name'])\n img = cv2.imread(path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n return img.astype(np.float32) / 255.\n\n def load_annotations(self, image_index):\n # get ground truth annotations\n annotations_ids = self.coco.getAnnIds(imgIds=self.image_ids[image_index], iscrowd=False)\n annotations = np.zeros((0, 5))\n\n # some images appear to miss annotations\n if len(annotations_ids) == 0:\n return annotations\n\n # parse annotations\n coco_annotations = self.coco.loadAnns(annotations_ids)\n for idx, a in enumerate(coco_annotations):\n\n # some annotations have basically no width / height, skip them\n if a['bbox'][2] < 1 or a['bbox'][3] < 1:\n continue\n\n annotation = np.zeros((1, 5))\n annotation[0, :4] = a['bbox']\n annotation[0, 4] = a['category_id'] - 1\n annotations = np.append(annotations, annotation, axis=0)\n\n # transform from [x, y, w, h] to [x1, y1, x2, y2]\n annotations[:, 2] = annotations[:, 0] + annotations[:, 2]\n annotations[:, 3] = annotations[:, 1] + annotations[:, 3]\n\n return annotations\n","sub_path":"datasets/coco.py","file_name":"coco.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"221809946","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 19 16:27:46 2021\n\n@author: lucg\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport gdal\nfrom optparse import OptionParser\nfrom matplotlib import pyplot\nimport plyfile\nimport time\n\n\ndef RotMatrixFromAngles(O,P,K):\n \n RX=np.array([[1,0,0],\n [0,np.cos(O),-np.sin(O)],\n [0,np.sin(O),np.cos(O)]]) \n RY=np.array([[np.cos(P),0,np.sin(P)],\n [0,1,0], \n [-np.sin(P),0,np.cos(P)]])\n RZ=np.array([[np.cos(K),-np.sin(K),0],\n [np.sin(K),np.cos(K),0],\n [0,0,1]])\n \n return RX.dot(RY.dot(RZ)).dot(np.array([[1,0,0],[0,-1,0],[0,0,-1]]))\n\n\ndef XYZ2Im(aPtWorld,aCam,aImSize):\n '''\n Function to project a point in world coordinate into an image\n\n :param aPtWorld: 3d point in world coordinates\n :param aCam: array describing a camera [position, rotation, focal]\n :param aImSize: Size of the image\n :return: 2d point in image coordinates\n '''\n # World to camera coordinate\n aPtCam=np.linalg.inv(aCam[1]).dot(aPtWorld-aCam[0])\n # Test if point is behind camera (Z positive in Cam coordinates)\n if aPtCam[2]<0:\n return None\n #print(\"PtCam =\", aPtCam)\n # Camera to 2D projected coordinate\n aPtProj=[aPtCam[0]/aPtCam[2],aPtCam[1]/aPtCam[2]]\n #print(\"PtProj =\", aPtProj)\n # 2D projected to image coordinate\n aPtIm=[aImSize[0]/2,aImSize[1]/2]+np.array(aCam[2]).dot(aPtProj)\n if aPtIm[0]>0 and aPtIm[1]>0 and aPtIm[0] File changed: %s\" % fname ) \n self.execute( fname ) \n\n def fileAdded( self, fname ): \n if self.verbose: print(\"---> File added %s\" % fname ) \n self.execute( fname ) \n n = WatchNode( fname ) \n self.files.append( n ) \n\n def fileRemoved( self, fname ): \n if self.verbose: print(\"---> File removed %s\" % fname ) \n # TODO: Make some action on removal \n for x in self.files: \n if x.name == fname: \n self.files.remove( x ) \n return\n \n def execute(self, targetFile ):\n if self.verbose: print( \"---> Running commands at %s\" % datetime.datetime.now() )\n for cmd in self.cmds: \n # for backward compat \n if cmd.__class__ == 'str':\n os.system( cmd ) \n else: \n cmd.runCmds( targetFile ) \n \n self.num_runs += 1\n return self.num_runs\n\n def addNode( self, fname ):\n # check it doesn't exists \n for x in self.files: \n if x.name == fname:\n return \n n = WatchNode( fname ) \n self.files.append( n ) \n\n def addDirs(self, dirnames):\n for dirname in dirnames:\n for path, dirs, files in os.walk(dirname):\n for f in files:\n self.addNode( os.path.join( path, f) ) \n for d in dirs: \n self.addNode( os.path.join( path, d) ) \n\n def add_files(self, *files):\n onlyfiles = [ os.path.realpath(f) for f in files if os.path.exists(f) and os.path.isfile(f) ]\n for f in onlyfiles: \n self.addNode( f ) \n \n onlydirs = [ os.path.realpath(f) for f in files if os.path.exists(f) and os.path.isdir(f) ]\n self.addDirs(onlydirs)\n\n\n def add_cmds(self, *cmds):\n unique_cmds = [ c for c in cmds if c not in self.cmds ]\n self.cmds = self.cmds + unique_cmds\n","sub_path":"src/pywatch/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":5065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424842500","text":"import json\nimport os\nimport webapp2\n\nfrom google.appengine.api import memcache\n\nimport imdb\n\n\ndef Title(q):\n titles = imdb.SearchTitle(q)\n results = []\n for t in titles:\n results.append({'id': t.id, 'name': t.name, 'year': t.year})\n return json.dumps(results, indent=2)\n\n\nclass Handler(webapp2.RequestHandler):\n def get(self):\n s, q = self.request.get('s'), self.request.get('q')\n if not s or not q:\n self.abort(501)\n key = 's=%s&q=%s' % (s, q)\n reply = memcache.get(key)\n if not reply:\n if s == 'tt':\n reply = Title(q)\n else:\n self.abort(501)\n memcache.add(key, reply)\n self.response.headers['Content-Type'] = 'application/json'\n self.response.write(reply)\n\n\napp = webapp2.WSGIApplication([\n (r'/find', Handler),\n], debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'))\n","sub_path":"imdb/appengine/find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"525432333","text":"\"\"\"\nhttps://en.wikipedia.org/wiki/Q-Pochhammer_symbol\n\"\"\"\n\n\ndef qPochhammer(a, q, n):\n if n < 1:\n return 1\n product = 1\n for k in range(n):\n product *= (1 - a * q**k)\n return product\n\n\n# コンピュータで計算は無理。\ndef phi(q):\n return qPochhammer(q, q, infinity)\n\n\ndef binomialCoefficient(n, k):\n r = 1\n for i in range(1, k + 1):\n r *= n\n n -= 1\n r /= i\n return r\n\n\n# これはだめ。\ndef mockModularOrder2A(q):\n if q <= 0:\n return 0\n if q == 1:\n return 1\n sum = 0\n qq = q * q\n for n in range(100):\n sum += (q**(n + 1)) * qPochhammer(-qq, qq, n) / \\\n qPochhammer(q, qq, n + 1)\n return sum\n\nfor i in range(32):\n print(mockModularOrder2A(i))\n\nprint(\"qPochhammer Test:\")\na = 4\nq = 11\nprint(\"a = \" + str(a))\nprint(\"q = \" + str(q))\nprint(\"n = 1\")\nprint(qPochhammer(a, q, 1) - (1 - a))\nprint(\"n = 2\")\nprint(qPochhammer(a, q, 2) - (1 - a) * (1 - a * q**1))\nprint(\"n = 3\")\nprint(qPochhammer(a, q, 3) - (1 - a) * (1 - a * q**1) * (1 - a * q**2))\nprint(\"n = 4\")\nprint(qPochhammer(a, q, 4) - (1 - a) * (1 - a * q**1)\n * (1 - a * q**2) * (1 - a * q**3))\n","sub_path":"q_pochhammer_symbol.py","file_name":"q_pochhammer_symbol.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46474458","text":"\n\"\"\"\nCONSTRAINTS\n\n The first player always places \"X\" characters\n No more moves can be played if the game is over\n\nIMPLIED CHECKS\n\n count(\"X\") - count(\"0\") <= 1\n\n checking rows, cols and diagonals, we may only have one winner, so\n in rows, cols and diagonals, if we find:\n\n 3 consecutive \"X\"s AND\n 3 consecutive \"O\"s\n\n then the board is illegal. For example:\n\n X X X\n X X O\n O O O\n\n we may have two instances of\n\n 3 consecutive \"X\"s OR\n 3 consecutive \"O\"s\n\n but they must share a square:\n\n X X X\n O O X\n O O X\n\n Fortunately, given a max of 5 moves (for X), we cannot construct two\n separate consecutive instance of 3, because that would require 6\n moves, so we need not explicitly check this case\n\n\"\"\"\n\nclass Solution:\n\n def validTicTacToe(self, board):\n \"\"\"\n :type board: List[str]\n :rtype: bool\n\n ACE\n 35 ms\n\n with Alex Wice's clever validation logic:\n\n if xwin and owin then count is not 1 or not 0\n\n https://leetcode.com/problems/valid-tic-tac-toe-state/solution/\n \"\"\"\n rows, cols = [0] * 3, [0] * 3\n diagonal, antidiagonal = 0, 0\n count, wins = 0, []\n for i, row_string in enumerate(board):\n for j, char in enumerate(row_string):\n if char == \"X\" or char == \"O\":\n v = 1 if char == \"X\" else -1\n rows[i] += v\n cols[j] += v\n if i == j:\n diagonal += v\n if i + j == 2:\n antidiagonal += v\n count += v\n tallies = rows + cols + [diagonal, antidiagonal]\n xwin = any(t == 3 for t in tallies)\n owin = any(t == -3 for t in tallies)\n if count not in (0, 1): return False\n if xwin and count != 1: return False\n if owin and count != 0: return False\n return True\n\n def validTicTacToeV3(self, board):\n \"\"\"\n :type board: List[str]\n :rtype: bool\n\n ACE\n 60 ms\n\n CHANGES FROM PREVIOUS VERSION\n\n use x_win and o_win to simplify the logic\n \"\"\"\n rows, cols = [0] * 3, [0] * 3\n diagonal, antidiagonal = 0, 0\n count, wins = 0, []\n for i, row_string in enumerate(board):\n for j, char in enumerate(row_string):\n if char == \"X\" or char == \"O\":\n v = 1 if char == \"X\" else -1\n rows[i] += v\n cols[j] += v\n if i == j:\n diagonal += v\n if i + j == 2:\n antidiagonal += v\n count += v\n tallies = rows + cols + [diagonal, antidiagonal]\n xwin = any(t == 3 for t in tallies)\n owin = any(t == -3 for t in tallies)\n return ((xwin and not owin and count == 1)\n or (owin and not xwin and count == 0)\n or (not xwin and not owin and count in [0, 1]))\n\n def validTicTacToeV2(self, board):\n \"\"\"\n :type board: List[str]\n :rtype: bool\n\n ACE\n 35 ms\n\n CHANGES FROM PREVIOUS VERSION\n\n (1) winner must win on their turn\n\n if \"X\" wins then count == 1\n if \"O\" wins then count == 0\n\n (2) cell's participation in diagonal and anti-diagonal is not mutally exclusive:\n use two \"if\" statements instead of \"if-elif\"\n\n Note: this may add the same value to wins multiple times. This does\n not impact the correctness of the algorithm\n \"\"\"\n rows, cols = [0] * 3, [0] * 3\n diagonal, antidiagonal = 0, 0\n count, wins = 0, []\n for i, row_string in enumerate(board):\n for j, char in enumerate(row_string):\n if char == \"X\" or char == \"O\":\n v = 1 if char == \"X\" else -1\n rows[i] += v\n cols[j] += v\n if i == j:\n diagonal += v\n if i + j == 2:\n antidiagonal += v\n wins.extend(x for x in (rows[i], cols[j], diagonal, antidiagonal) if abs(x) == 3)\n count += v\n if any(wins[i-1] == -wins[i] for i in range(1, len(wins))):\n return False\n if not wins:\n return count in (0, 1)\n else:\n return (wins[0] > 0 and count == 1) or (wins[0] < 0 and count == 0)\n\n def validTicTacToeV1(self, board):\n \"\"\"\n :type board: List[str]\n :rtype: bool\n\n Wrong Answer\n\n Close ... but\n\n if \"X\" wins then count == 1\n if \"O\" wins then count == 0\n\n we can let\n\n X = +1\n O = -1\n\n and keep\n\n a list for row\n a list for col\n an int for diagonal\n an int for antidiagonal\n\n if we find one of these 8 int values has absolute value equal to 3\n then we can add it to a list \"wins\".\n if two consecutive values in wins have different signs we can return False\n \"\"\"\n rows, cols = [0] * 3, [0] * 3\n diagonal, antidiagonal = 0, 0\n count, wins = 0, []\n for i, row_string in enumerate(board):\n for j, char in enumerate(row_string):\n if char == \"X\" or char == \"O\":\n v = 1 if char == \"X\" else -1\n rows[i] += v\n cols[j] += v\n if i == j:\n diagonal += v\n elif i + j == 2:\n antidiagonal += v\n wins.extend(x for x in (rows[i], cols[j], diagonal, antidiagonal) if abs(x) == 3)\n count += v\n return count in (0, 1) and not any(wins[i-1] == -wins[i] for i in range(1, len(wins)))\n\n\nif __name__ == '__main__':\n s = Solution()\n tests = [\n (\n [\n \"O \",\n \" \",\n \" \"\n ],\n False\n ),\n (\n [\n \"XOX\",\n \" X \",\n \" \"\n ],\n False\n ),\n (\n [\n \"XXX\",\n \" \",\n \"OOO\"\n ],\n False\n ),\n (\n [\n \"XOX\",\n \"O O\",\n \"XOX\"\n ],\n True\n ),\n (\n [\n \"XXX\",\n \"XOO\",\n \"OO \"\n ],\n False\n ),\n (\n [\n \"XXX\",\n \"XOO\",\n \"OO \"\n ],\n False\n ),\n (\n [\n \"XXO\",\n \"XOX\",\n \"OXO\"\n ],\n False\n ),\n (\n [\n \"XXX\",\n \"X \",\n \"OOO\"\n ],\n False\n )\n\n ]\n for board, exp in tests:\n res = s.validTicTacToe(board)\n print(res)\n assert res == exp\n\n\n\n","sub_path":"794_valid_tic_tac_toe_state.py","file_name":"794_valid_tic_tac_toe_state.py","file_ext":"py","file_size_in_byte":7221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"569910079","text":"from conans import ConanFile, tools\nimport os\n\n\nclass NasmConan(ConanFile):\n name = \"nasm\"\n version = \"2.13.01\"\n license = \"BSD-2-Clause\"\n url = \"https://github.com/lasote/conan-nasm-installer\"\n settings = \"os\"\n build_policy = \"missing\"\n description=\"Nasm for windows. Useful as a build_require.\"\n \n def configure(self):\n if self.settings.os != \"Windows\":\n raise Exception(\"Only windows supported for nasm\")\n \n @property\n def nasm_folder_name(self):\n return \"nasm-%s\" % self.version\n\n def build(self):\n def get_version(suffix):\n nasm_zip_name = \"%s-%s.zip\" % (self.nasm_folder_name, suffix)\n tools.download(\"http://www.nasm.us/pub/nasm/releasebuilds/%s/%s/%s\" % (self.version, suffix, nasm_zip_name), nasm_zip_name)\n self.output.warn(\"Downloading nasm: http://www.nasm.us/pub/nasm/releasebuilds/%s/%s/%s\" % (self.version, suffix, nasm_zip_name))\n tools.unzip(nasm_zip_name)\n os.unlink(nasm_zip_name)\n os.mkdir(\"x86\")\n with tools.chdir(\"x86\"):\n get_version(\"win32\")\n \n os.mkdir(\"x86_64\")\n with tools.chdir(\"x86_64\"):\n get_version(\"win64\")\n \n\n def package(self):\n self.copy(\"*\", dst=\"\", keep_path=True)\n self.copy(\"license*\", dst=\"\", src=os.path.join(tools.detected_architecture(), self.nasm_folder_name), \n keep_path=False, ignore_case=True)\n\n def package_info(self):\n self.output.info(\"Using %s version\" % tools.detected_architecture())\n self.env_info.path.append(os.path.join(self.package_folder, tools.detected_architecture(), self.nasm_folder_name))\n\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"636180574","text":"\"\"\"Helpers for generating the right code\"\"\"\n\nfrom asm import C, Y, hi, jmp, ld, lo\n\n\ndef next(cycles_so_far):\n \"\"\"Jump to the next instruction\"\"\"\n cost = cycles_so_far + cost_of_next\n if cost % 2 == 0:\n target = \"forth.next2.even\"\n else:\n target = \"forth.next2.odd\"\n cost += 1 # We're gaining a nop\n ld(hi(\"forth.next2\"), Y) # 1\n C(\"NEXT\")\n jmp(Y, lo(target)) # 2\n ld(-(cost / 2)) # 3\n\n\nNEXT = next\ncost_of_next = 3\n\n\ndef add_cost_of_next(cycles_before):\n cost = cycles_before + cost_of_next\n if cost % 2 != 0:\n cost += 1\n return cost\n\n\n\"add_cost_of_reenter\"\n\n\ndef reenter(cycles_so_far):\n \"\"\"Dispatch to the word in W\"\"\"\n cost = cycles_so_far + cost_of_reenter\n if cost % 2 == 0:\n target = \"forth.next1.reenter.even\"\n else:\n target = \"forth.next1.reenter.odd\"\n cost -= 1 # We're skipping a nop\n ld(hi(\"forth.next1.reenter\"), Y) # 1\n C(\"REENTER\")\n jmp(Y, lo(target)) # 2\n ld(-cost / 2) # 3\n\n\nREENTER = reenter\ncost_of_reenter = 3\n\n\ndef add_cost_of_reenter(cycles_before):\n cost = cycles_before + cost_of_reenter\n if cost % 2 != 0:\n cost -= 1\n return cost\n\n\n__all__ = [\n \"next\",\n \"NEXT\",\n \"reenter\",\n \"REENTER\",\n \"add_cost_of_reenter\",\n \"add_cost_of_next\",\n]\n","sub_path":"Contrib/psr/Forth/forth/_utilities.py","file_name":"_utilities.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"12037793","text":"\nstudent_number = 5\ngrade_number = 3\n\nMatrix = [[0 for x in range(grade_number)] for y in range(student_number)]\n\n#print(Matrix[1][2])\n\ntotal = 0\nhigh_avg = 0\nhigh_stu = 0\n\nprint(\"請輸入同學的成績(三個成績分別用空白隔開)\")\n\nfor i in range(student_number):\n\tstrin = input(\"同學\"+str(i+1)+\" : \")\n\tstrlist = strin.split(\" \") #String will be a list after split.\n\tfor j in range(grade_number):\n\t\tMatrix[i][j] = int(strlist[j])\n\t#print(Matrix[i])\n\n\t\nfor i in range(student_number):\n\tprint(\"student\",i+1)\n\tsum = 0\n\tfor j in range(grade_number):\n\t\tprint(\" \",j+1,\": \",Matrix[i][j],sep=\"\")\n\t\tsum += Matrix[i][j]\n\tprint(\" sum:\",sum)\n\tprint(\" avg:\",format(sum/grade_number,\".2f\"))\n\tif sum/grade_number>high_avg:\n\t\thigh_avg = sum/grade_number\n\t\thigh_stu = i+1\n\ttotal += sum\n\nprint(\"total: \",total,\", \",\"avg: \",format(total/(student_number*grade_number),\".2f\"),sep=\"\")\nprint(\"highest avg: student \",high_stu,\": %.2f\" %high_avg,sep=\"\")\n\n\n","sub_path":"Python/Onlinejudge/two dimension array(hw4).py","file_name":"two dimension array(hw4).py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"288649439","text":"from tkinter import *\nimport random\nfrom tkinter import messagebox\n\nroot = Tk()\nroot.title(\"ABC PAIRS\")\nroot.config(bg=\"black\")\nroot.geometry('600x640')\n\n# Assign variables\n# count for buttons in first row\ncount00 = 0\ncount01 = 0\ncount02 = 0\ncount03 = 0\n\n# count for buttons in second row\ncount10 = 0\ncount11 = 0\ncount12 = 0\ncount13 = 0\n\n# count for buttons in third row\ncount20 = 0\ncount21 = 0\ncount22 = 0\ncount23 = 0\n\n# score variables\nscore = 0\ncount_X = 0\ncount_O = 0\ncount_I = 0\n\nscore_x = 0\nscore_o = 0\nscore_i = 0\n\nbol = True\n\n\nclass ABCPairs:\n def __init__(self, master):\n\n self.start_game() # Start game message box\n\n self.top_frame = Frame(master) # Creating frames\n self.top_frame.grid()\n\n self.middle_frame = Frame(master)\n self.middle_frame.grid()\n\n self.bottom_frame = Frame(master)\n self.bottom_frame.grid()\n\n self.buttons = [[Button(self.middle_frame, width=15, height=7, bg='sky blue',\n command=lambda row=row, column=column: self.main_game(row, column))\n for column in range(4)] for row in range(3)]\n\n for row in range(3): # Creating buttons for 3 rows and 4 columns\n for column in range(4):\n self.buttons[row][column].grid(row=row + 1, column=column) # Packing buttons to grid\n\n self.first_click = None\n self.draw_buttons()\n\n self.time_label = Label(\n self.top_frame, width=5, height=5, fg='red', bg=\"black\") # Creating labels\n self.instruction_label = Label(self.top_frame, text='Click a tile and click another to match it', fg=\"white\",\n bg=\"black\", width=45, height=5)\n self.level_label = Label(self.bottom_frame, text='Level : 1', width=55, height=3, bg=\"black\", fg=\"white\",\n font=20)\n self.score_label = Label(\n self.bottom_frame, width=55, height=4, bg=\"black\", font=20)\n\n self.create_labels()\n self.count_down(60) # Start countdown from 60 seconds\n\n def draw_buttons(self):\n self.answer = ['X', 'X', 'X', 'X', 'O',\n 'O', 'O', 'O', 'I', 'I', 'I', 'I']\n random.shuffle(self.answer) # Randomly shuffling answers\n\n self.answer = [self.answer[0:4], # Slicing list\n self.answer[4:8],\n self.answer[8:12]]\n\n for m in range(len(self.answer)): # Print answer grid layout\n print(self.answer[m])\n\n def count_down(self, secs):\n global bol\n if bol is True:\n # Text of time label set to secs variable\n self.time_label.config(text=\"00:\" + str(secs))\n if secs > 0:\n self.top_frame.after(1000, self.count_down, secs - 1)\n if secs == 0:\n self.time_out()\n\n def create_labels(self):\n self.score_label.grid(row=6, column=0)\n\n self.level_label.grid(row=7, column=0)\n\n self.instruction_label.config(font=30)\n self.instruction_label.grid(row=0, column=3)\n\n self.time_label.config(font=30)\n self.time_label.grid(row=0, column=12)\n\n def main_game(self, row, column):\n print(row, column)\n # Assign a letter to a button Disable button when clicked\n self.buttons[row][column].config(text=self.answer[row][column], state=DISABLED)\n\n if self.first_click is None: # if first clicked tile has no row or column to compare\n # Then assign coordinates to first click\n self.first_click = [row, column]\n else:\n r, c = self.first_click # r, c = coordinates of the first click\n\n # Check if the answer of first click is same as answer of second click\n if self.answer[r][c] == self.answer[row][column]:\n print('Match!')\n\n # Change color of buttons when matched\n self.buttons[row][column].config(bg=\"light green\")\n self.buttons[r][c].config(bg=\"light green\")\n\n self.positive_scoring() # Add score when two tiles are matched\n self.score_label.config(fg=\"white\", text=\"Score: \" + str(score)) # Show score on label\n self.first_click = None\n self.matched() # call function to display message box if all 12 matched\n else:\n self.count(row, column)\n self.middle_frame.after(800, self.hide_buttons, row, column, r, c) # Hide tiles if not matched\n print(\"No match! You suck!\")\n\n self.negative_scoring(row, column)\n self.score_label.config(fg=\"white\", text=\"Score:\" + str(score))\n self.first_click = None\n\n def hide_buttons(self, row_a, column_a, row_b, column_b):\n # Reset first button if not matched\n self.buttons[row_a][column_a].config(text='', state=NORMAL)\n # Reset second button if not matched\n self.buttons[row_b][column_b].config(text='', state=NORMAL)\n\n def count(self, row, column): # score -5 if not matched\n global score\n\n if row == 0 and column == 0:\n global count00\n count00 += 1\n print(count00)\n elif row == 0 and column == 1:\n global count01\n count01 += 1\n elif row == 0 and column == 2:\n global count02\n count02 += 1\n elif row == 0 and column == 3:\n global count03\n count03 += 1\n\n if row == 1 and column == 0:\n global count10\n count10 += 1\n elif row == 1 and column == 1:\n global count11\n count11 += 1\n elif row == 1 and column == 2:\n global count12\n count12 += 1\n elif row == 1 and column == 3:\n global count13\n count13 += 1\n\n if row == 2 and column == 0:\n global count20\n count20 += 1\n elif row == 2 and column == 1:\n global count21\n count21 += 1\n elif row == 2 and column == 2:\n global count22\n count22 += 1\n elif row == 2 and column == 3:\n global count23\n count23 += 1\n\n # if self.answer[row][column] == \"X\":\n # global count_X\n # count_X += 1\n # print(\"count x : \", count_X)\n # elif self.answer[row][column] == \"O\":\n # global count_O\n # count_O += 1\n # print(\"count o : \", count_O)\n # elif self.answer[row][column] == \"I\":\n # global count_I\n # count_I += 1\n # print(\"count I : \", count_I)\n\n def positive_scoring(self): # score +20 if matched\n global score\n score = score + 20\n print(\"score:\", score)\n\n def negative_scoring(self, row, column):\n global score_x\n global score_o\n global score_i\n global score\n\n # Calculating negative score for first row\n if row == 0 and column == 0:\n if self.answer[row][column] == \"X\":\n score_x = count00 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count00 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count00 * (-5)\n elif row == 0 and column == 1:\n if self.answer[row][column] == \"X\":\n score_x = count01 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count01 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count01 * (-5)\n elif row == 0 and column == 2:\n if self.answer[row][column] == \"X\":\n score_x = count02 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count02 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count02 * (-5)\n elif row == 0 and column == 3:\n if self.answer[row][column] == \"X\":\n score_x = count03 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count03 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count03 * (-5)\n\n # Calculating negative score for second row\n if row == 1 and column == 0:\n if self.answer[row][column] == \"X\":\n score_x = count10 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count10 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count10 * (-5)\n elif row == 1 and column == 1:\n if self.answer[row][column] == \"X\":\n score_x = count11 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count11 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count11 * (-5)\n elif row == 1 and column == 2:\n if self.answer[row][column] == \"X\":\n score_x = count12 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count12 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count12 * (-5)\n elif row == 1 and column == 3:\n if self.answer[row][column] == \"X\":\n score_x = count13 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count13 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count13 * (-5)\n\n # Calculating negative score for third row\n if row == 2 and column == 0:\n if self.answer[row][column] == \"X\":\n score_x = count20 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count20 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count20 * (-5)\n elif row == 2 and column == 1:\n if self.answer[row][column] == \"X\":\n score_x = count21 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count21 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count21 * (-5)\n elif row == 2 and column == 2:\n if self.answer[row][column] == \"X\":\n score_x = count22 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count22 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count22 * (-5)\n elif row == 2 and column == 3:\n if self.answer[row][column] == \"X\":\n score_x = count23 * (-5)\n if self.answer[row][column] == \"O\":\n score_o = count23 * (-5)\n if self.answer[row][column] == \"I\":\n score_i = count23 * (-5)\n # if count_X == 1:\n # score_x = 0\n # if count_X > 1:\n # score_x = count_X * (-5)\n # print(\"score_x:\", score_x)\n\n # if count_O == 1:\n # score_o = 0\n # if count_O > 1:\n # score_o = count_O * (-5)\n # print(\"score_o:\", score_o)\n\n # if count_I == 1:\n # score_i = 0\n # if count_I > 1:\n # score_i = count_I * (-5)\n # print(\"score_i:\", score_i)\n\n score = score + score_x + score_o + score_i\n print(score)\n\n def matched(self): # check if all 12 tiles are matched and display message box\n global bol\n count = 0\n for row in range(3):\n for column in range(4):\n if self.buttons[row][column][\"state\"] == DISABLED:\n count += 1\n if count == 12:\n print(\"You Win!\")\n bol = False\n self.end_game()\n\n def start_game(self):\n messagebox.showinfo(\"ABC PAIRS\", \"Click a tile then click another to match it! \\n \"\n \"Do you want to start game?\")\n\n def end_game(self):\n messagebox.showinfo(\"ABC PAIRS\", \"You Win! \\n Your Score : \")\n if messagebox.askyesno(\"ABC PAIRS\", \"Do you wish to play again?\"):\n self.replay_game()\n print(\"OK\")\n else:\n root.quit()\n\n def time_out(self):\n messagebox.showinfo(\"ABC PAIRS\", \"Out of time! \\n You suck!\")\n root.quit()\n\n def replay_game(self):\n global bol\n bol = True\n\n self.draw_buttons()\n self.reset_all()\n self.count_down(60)\n self.create_labels()\n\n def reset_all(self):\n global score\n global count_X\n global count_O\n global count_I\n global score_x\n global score_o\n global score_i\n\n for row in range(3):\n for column in range(4):\n self.buttons[row][column].config(text='', state=NORMAL)\n\n score = 0\n count_X = 0\n count_O = 0\n count_I = 0\n score_x = 0\n score_o = 0\n score_i = 0\n print(score)\n\n self.score_label.config(text=\"\")\n self.buttons[row][column].config(bg=\"sky blue\")\n\n\nX = ABCPairs(root)\nroot.mainloop()\n","sub_path":"negative score test 4.py","file_name":"negative score test 4.py","file_ext":"py","file_size_in_byte":13191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"128669330","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nThis experiment was created using PsychoPy2 Experiment Builder (v1.82.01),\n on 2017_03_16_1436\nIf you publish work using this script please cite the PsychoPy publications:\n Peirce, JW (2007) PsychoPy - Psychophysics software in Python.\n Journal of Neuroscience Methods, 162(1-2), 8-13.\n Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.\n Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008\n\"\"\"\n\nfrom __future__ import absolute_import, division\nfrom psychopy import locale_setup, gui, visual, core, data, event, logging, sound\nfrom psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,\n STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)\nimport numpy as np # whole numpy lib is available, prepend 'np.'\nfrom numpy import (sin, cos, tan, log, log10, pi, average,\n sqrt, std, deg2rad, rad2deg, linspace, asarray)\nfrom numpy.random import random, randint, normal, shuffle\nimport os # handy system and path functions\nimport sys # to get file system encoding\n\n# Ensure that relative paths start from the same directory as this script\n_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding())\nos.chdir(_thisDir)\n\n# Store info about the experiment session\nexpName = 'aqv2' # from the Builder filename that created this script\nexpInfo = {u'session': u'001', u'participant': u''}\ndlg = gui.DlgFromDict(dictionary=expInfo, title=expName)\nif dlg.OK == False:\n core.quit() # user pressed cancel\nexpInfo['date'] = data.getDateStr() # add a simple timestamp\nexpInfo['expName'] = expName\n\n# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\nfilename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])\n\n# An ExperimentHandler isn't essential but helps with data saving\nthisExp = data.ExperimentHandler(name=expName, version='',\n extraInfo=expInfo, runtimeInfo=None,\n originPath=None,\n savePickle=True, saveWideText=False,\n dataFileName=filename)\nlogging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file\n\nendExpNow = False # flag for 'escape' or other condition => quit the exp\n\n# Start Code - component code to be run before the window creation\n\n# Setup the Window\nwin = visual.Window(\n size=(1440, 900), fullscr=True, screen=0,\n allowGUI=True, allowStencil=False,\n monitor='testMonitor', color=[-1, -1, -1], colorSpace='rgb',\n blendMode='avg', useFBO=True)\n# store frame rate of monitor if we can measure it\nexpInfo['frameRate'] = win.getActualFrameRate()\nif expInfo['frameRate'] != None:\n frameDur = 1.0 / round(expInfo['frameRate'])\nelse:\n frameDur = 1.0 / 60.0 # could not measure, so guess\n\n# Initialize components for Routine \"instructions\"\ninstructionsClock = core.Clock()\ntitle = visual.TextStim(win=win, name='title',\n text=u'Avalia\\xe7\\xe3o de Qualidade Visual',\n font='Times New Roman',\n pos=(0, 0.8), height=0.1, wrapWidth=None, ori=0, \n color='white', colorSpace='rgb', opacity=1,\n depth=0.0);\nquestion = visual.TextStim(win=win, name='question',\n text=u'Dada a imagem apresentada, qual seria o seu diagn\\xf3stico?',\n font='Times New Roman',\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0, \n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0);\ngoon = visual.TextStim(win=win, name='goon',\n text='Aperte qualquer tecla para continuar...',\n font='Times New Roman',\n pos=(0, -0.9), height=0.1, wrapWidth=None, ori=0, \n color='white', colorSpace='rgb', opacity=1,\n depth=-3.0);\n\n# Initialize components for Routine \"trial\"\ntrialClock = core.Clock()\nimage_2 = visual.ImageStim(\n win=win, name='image_2',units='pix', \n image='sin', mask=None,\n ori=0, pos=(0, 0), size=(512, 512),\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=0.0)\ntext_3 = visual.TextStim(win=win, name='text_3',\n text='Fase de aquecimento\\n',\n font='Times New Roman',\n pos=(0, 0.9), height=0.1, wrapWidth=None, ori=0, \n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0);\nmouse = event.Mouse(win=win)\nx, y = [None, None]\nrating_2 = visual.RatingScale(win=win, name='rating_2', marker='triangle', size=1.0, pos=[0.0, -0.7], choices=[u'Normal', u'Inconclusivo', u'Alterado'], tickHeight=-1)\n\n# Initialize components for Routine \"lets\"\nletsClock = core.Clock()\ntext_4 = visual.TextStim(win=win, name='text_4',\n text=u'Aperte qualquer tecla para come\\xe7ar o experimento...',\n font='Times New Roman',\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0, \n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0);\n\n# Initialize components for Routine \"experiment\"\nexperimentClock = core.Clock()\nimage_test = visual.ImageStim(\n win=win, name='image_test',units='pix', \n image='sin', mask=None,\n ori=0, pos=(0, 0), size=(512, 512),\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=0.0)\nrating = visual.RatingScale(win=win, name='rating', marker='triangle', size=1.0, pos=[0.0, -0.7], choices=[u'Normal', u'Inconclusivo', u'Alterado'], tickHeight=-1)\nmouse_2 = event.Mouse(win=win)\nx, y = [None, None]\n\n# Create some handy timers\nglobalClock = core.Clock() # to track the time since experiment started\nroutineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine \n\n# ------Prepare to start Routine \"instructions\"-------\nt = 0\ninstructionsClock.reset() # clock\nframeN = -1\ncontinueRoutine = True\n# update component parameters for each repeat\nkey_resp_2 = event.BuilderKeyResponse()\n# keep track of which components have finished\ninstructionsComponents = [title, question, key_resp_2, goon]\nfor thisComponent in instructionsComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n# -------Start Routine \"instructions\"-------\nwhile continueRoutine:\n # get current time\n t = instructionsClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *title* updates\n if t >= 0.0 and title.status == NOT_STARTED:\n # keep track of start time/frame for later\n title.tStart = t\n title.frameNStart = frameN # exact frame index\n title.setAutoDraw(True)\n \n # *question* updates\n if t >= 0.0 and question.status == NOT_STARTED:\n # keep track of start time/frame for later\n question.tStart = t\n question.frameNStart = frameN # exact frame index\n question.setAutoDraw(True)\n \n # *key_resp_2* updates\n if t >= 0.0 and key_resp_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_2.tStart = t\n key_resp_2.frameNStart = frameN # exact frame index\n key_resp_2.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_2.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_2.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_2.keys = theseKeys[-1] # just the last key pressed\n key_resp_2.rt = key_resp_2.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *goon* updates\n if t >= 0.0 and goon.status == NOT_STARTED:\n # keep track of start time/frame for later\n goon.tStart = t\n goon.frameNStart = frameN # exact frame index\n goon.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in instructionsComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n# -------Ending Routine \"instructions\"-------\nfor thisComponent in instructionsComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_2.keys in ['', [], None]: # No response was made\n key_resp_2.keys=None\nthisExp.addData('key_resp_2.keys',key_resp_2.keys)\nif key_resp_2.keys != None: # we had a response\n thisExp.addData('key_resp_2.rt', key_resp_2.rt)\nthisExp.nextEntry()\n# the Routine \"instructions\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n# set up handler to look after randomisation of conditions etc\ntrials_2 = data.TrialHandler(nReps=1, method='random', \n extraInfo=expInfo, originPath=-1,\n trialList=data.importConditions('trial.xlsx'),\n seed=None, name='trials_2')\nthisExp.addLoop(trials_2) # add the loop to the experiment\nthisTrial_2 = trials_2.trialList[0] # so we can initialise stimuli with some values\n# abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)\nif thisTrial_2 != None:\n for paramName in thisTrial_2.keys():\n exec(paramName + '= thisTrial_2.' + paramName)\n\nfor thisTrial_2 in trials_2:\n currentLoop = trials_2\n # abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)\n if thisTrial_2 != None:\n for paramName in thisTrial_2.keys():\n exec(paramName + '= thisTrial_2.' + paramName)\n \n # ------Prepare to start Routine \"trial\"-------\n t = 0\n trialClock.reset() # clock\n frameN = -1\n continueRoutine = True\n # update component parameters for each repeat\n image_2.setImage(Imagemteste)\n # setup some python lists for storing info about the mouse\n rating_2.reset()\n # keep track of which components have finished\n trialComponents = [image_2, text_3, mouse, rating_2]\n for thisComponent in trialComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n \n # -------Start Routine \"trial\"-------\n while continueRoutine:\n # get current time\n t = trialClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *image_2* updates\n if t >= 0.0 and image_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n image_2.tStart = t\n image_2.frameNStart = frameN # exact frame index\n image_2.setAutoDraw(True)\n \n # *text_3* updates\n if t >= 0.0 and text_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_3.tStart = t\n text_3.frameNStart = frameN # exact frame index\n text_3.setAutoDraw(True)\n # *rating_2* updates\n if t >= 0.0 and rating_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n rating_2.tStart = t\n rating_2.frameNStart = frameN # exact frame index\n rating_2.setAutoDraw(True)\n continueRoutine &= rating_2.noResponse # a response ends the trial\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n \n # -------Ending Routine \"trial\"-------\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n # store data for trials_2 (TrialHandler)\n x, y = mouse.getPos()\n buttons = mouse.getPressed()\n trials_2.addData('mouse.x', x)\n trials_2.addData('mouse.y', y)\n trials_2.addData('mouse.leftButton', buttons[0])\n trials_2.addData('mouse.midButton', buttons[1])\n trials_2.addData('mouse.rightButton', buttons[2])\n # store data for trials_2 (TrialHandler)\n trials_2.addData('rating_2.response', rating_2.getRating())\n trials_2.addData('rating_2.rt', rating_2.getRT())\n # the Routine \"trial\" was not non-slip safe, so reset the non-slip timer\n routineTimer.reset()\n thisExp.nextEntry()\n \n# completed 1 repeats of 'trials_2'\n\n# get names of stimulus parameters\nif trials_2.trialList in ([], [None], None):\n params = []\nelse:\n params = trials_2.trialList[0].keys()\n# save data for this loop\ntrials_2.saveAsText(filename + 'trials_2.csv', delim=',',\n stimOut=params,\n dataOut=['n','all_mean','all_std', 'all_raw'])\n\n# ------Prepare to start Routine \"lets\"-------\nt = 0\nletsClock.reset() # clock\nframeN = -1\ncontinueRoutine = True\n# update component parameters for each repeat\nkey_resp_3 = event.BuilderKeyResponse()\n# keep track of which components have finished\nletsComponents = [key_resp_3, text_4]\nfor thisComponent in letsComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n# -------Start Routine \"lets\"-------\nwhile continueRoutine:\n # get current time\n t = letsClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *key_resp_3* updates\n if t >= 0.0 and key_resp_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_3.tStart = t\n key_resp_3.frameNStart = frameN # exact frame index\n key_resp_3.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_3.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_3.status == STARTED:\n theseKeys = event.getKeys()\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_3.keys = theseKeys[-1] # just the last key pressed\n key_resp_3.rt = key_resp_3.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *text_4* updates\n if t >= 0.0 and text_4.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_4.tStart = t\n text_4.frameNStart = frameN # exact frame index\n text_4.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in letsComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n# -------Ending Routine \"lets\"-------\nfor thisComponent in letsComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_3.keys in ['', [], None]: # No response was made\n key_resp_3.keys=None\nthisExp.addData('key_resp_3.keys',key_resp_3.keys)\nif key_resp_3.keys != None: # we had a response\n thisExp.addData('key_resp_3.rt', key_resp_3.rt)\nthisExp.nextEntry()\n# the Routine \"lets\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n# set up handler to look after randomisation of conditions etc\ntrials = data.TrialHandler(nReps=1, method='random', \n extraInfo=expInfo, originPath=-1,\n trialList=data.importConditions('arquivo (1).xlsx'),\n seed=None, name='trials')\nthisExp.addLoop(trials) # add the loop to the experiment\nthisTrial = trials.trialList[0] # so we can initialise stimuli with some values\n# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)\nif thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n\nfor thisTrial in trials:\n currentLoop = trials\n # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)\n if thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n \n # ------Prepare to start Routine \"experiment\"-------\n t = 0\n experimentClock.reset() # clock\n frameN = -1\n continueRoutine = True\n # update component parameters for each repeat\n image_test.setImage(Imagemteste)\n rating.reset()\n # setup some python lists for storing info about the mouse_2\n mouse_2.x = []\n mouse_2.y = []\n mouse_2.leftButton = []\n mouse_2.midButton = []\n mouse_2.rightButton = []\n mouse_2.time = []\n # keep track of which components have finished\n experimentComponents = [image_test, rating, mouse_2]\n for thisComponent in experimentComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n \n # -------Start Routine \"experiment\"-------\n while continueRoutine:\n # get current time\n t = experimentClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *image_test* updates\n if t >= 0.0 and image_test.status == NOT_STARTED:\n # keep track of start time/frame for later\n image_test.tStart = t\n image_test.frameNStart = frameN # exact frame index\n image_test.setAutoDraw(True)\n # *rating* updates\n if t >= 0.0 and rating.status == NOT_STARTED:\n # keep track of start time/frame for later\n rating.tStart = t\n rating.frameNStart = frameN # exact frame index\n rating.setAutoDraw(True)\n continueRoutine &= rating.noResponse # a response ends the trial\n # *mouse_2* updates\n if t >= 0.0 and mouse_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n mouse_2.tStart = t\n mouse_2.frameNStart = frameN # exact frame index\n mouse_2.status = STARTED\n event.mouseButtons = [0, 0, 0] # reset mouse buttons to be 'up'\n if mouse_2.status == STARTED: # only update if started and not stopped!\n buttons = mouse_2.getPressed()\n if sum(buttons) > 0: # ie if any button is pressed\n x, y = mouse_2.getPos()\n mouse_2.x.append(x)\n mouse_2.y.append(y)\n mouse_2.leftButton.append(buttons[0])\n mouse_2.midButton.append(buttons[1])\n mouse_2.rightButton.append(buttons[2])\n mouse_2.time.append(experimentClock.getTime())\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in experimentComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n \n # -------Ending Routine \"experiment\"-------\n for thisComponent in experimentComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n # store data for trials (TrialHandler)\n trials.addData('rating.response', rating.getRating())\n trials.addData('rating.rt', rating.getRT())\n # store data for trials (TrialHandler)\n trials.addData('mouse_2.x', mouse_2.x)\n trials.addData('mouse_2.y', mouse_2.y)\n trials.addData('mouse_2.leftButton', mouse_2.leftButton)\n trials.addData('mouse_2.midButton', mouse_2.midButton)\n trials.addData('mouse_2.rightButton', mouse_2.rightButton)\n trials.addData('mouse_2.time', mouse_2.time)\n # the Routine \"experiment\" was not non-slip safe, so reset the non-slip timer\n routineTimer.reset()\n thisExp.nextEntry()\n \n# completed 1 repeats of 'trials'\n\n# get names of stimulus parameters\nif trials.trialList in ([], [None], None):\n params = []\nelse:\n params = trials.trialList[0].keys()\n# save data for this loop\ntrials.saveAsText(filename + 'trials.csv', delim=',',\n stimOut=params,\n dataOut=['n','all_mean','all_std', 'all_raw'])\n# these shouldn't be strictly necessary (should auto-save)\nthisExp.saveAsPickle(filename)\n# make sure everything is closed down\nthisExp.abort() # or data files will save again on exit\nwin.close()\ncore.quit()\n","sub_path":"Capítulo 4/aqv2.py","file_name":"aqv2.py","file_ext":"py","file_size_in_byte":22094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"514825288","text":"\"\"\"\r\n---------------\r\nSM FastEdit |\r\n---------------\r\nThis file is a part of SM FastEdit 2.0.0!\r\n\r\nCOPYRIGHT SM 2021:\r\n AS YOU KNOW SM FASTEDIT 2.0.0 IS A OPEN SOURCE APPLICATION SO YOU CAN MODIFY IT AND CAN TELL ISSUES YOU NOTICED\r\n IN THIS APPLICATION. BUT IT WILL BE VERY WRONG IF YOU COPIED SOURCE AND THEN PUBLISHED IT. THANK YOU!\r\n\"\"\"\r\nimport json\r\n\r\ndef update(filePath, key, value):\r\n jsonFile = open(filePath, \"r\")\r\n data = json.load(jsonFile) \r\n jsonFile.close()\r\n tmp = data[key] \r\n data[key] = value\r\n jsonFile = open(filePath, \"w+\")\r\n jsonFile.write(json.dumps(data))\r\n jsonFile.close()","sub_path":"FastEdit2/jsonManager.py","file_name":"jsonManager.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"122278726","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 4 13:35:53 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom skimage import data, io, segmentation, color\r\nfrom math import ceil\r\nimport math\r\nfrom scipy import misc, ndimage\r\n\r\nimgo = cv2.imread('1002m.png')\r\nimg = cv2.imread('slic_rag_signal.png')\r\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\nedges = cv2.Canny(gray,50,150,apertureSize = 3)\r\n\t\r\n#霍夫变换\r\nlines = cv2.HoughLines(edges,1,np.pi/180,0)\r\nfor rho,theta in lines[0]:\r\n a = np.cos(theta)\r\n b = np.sin(theta)\r\n x0 = a*rho\r\n y0 = b*rho\r\n x1 = int(x0 + 1000*(-b))\r\n y1 = int(y0 + 1000*(a))\r\n x2 = int(x0 - 1000*(-b))\r\n y2 = int(y0 - 1000*(a))\r\n\r\n\r\nt = float(y2-y1)/(x2-x1)\r\nrotate_angle = math.degrees(math.atan(t))\r\nif rotate_angle > 45:\r\n rotate_angle = -90 + rotate_angle\r\nelif rotate_angle < -45:\r\n rotate_angle = 90 + rotate_angle\r\n\r\n\r\n# 旋转angle角度,缺失背景白色(255, 255, 255)填充\r\ndef rotate_bound_white_bg(image, angle):\r\n # grab the dimensions of the image and then determine the\r\n # center\r\n (h, w) = image.shape[:2]\r\n (cX, cY) = (w // 2, h // 2)\r\n \r\n # grab the rotation matrix (applying the negative of the\r\n # angle to rotate clockwise), then grab the sine and cosine\r\n # (i.e., the rotation components of the matrix)\r\n # -angle位置参数为角度参数负值表示顺时针旋转; 1.0位置参数scale是调整尺寸比例(图像缩放参数),建议0.75\r\n M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)\r\n cos = np.abs(M[0, 0])\r\n sin = np.abs(M[0, 1])\r\n \r\n # compute the new bounding dimensions of the image\r\n nW = int((h * sin) + (w * cos))\r\n nH = int((h * cos) + (w * sin))\r\n \r\n # adjust the rotation matrix to take into account translation\r\n M[0, 2] += (nW / 2) - cX\r\n M[1, 2] += (nH / 2) - cY\r\n \r\n # perform the actual rotation and return the image\r\n # borderValue 缺失背景填充色彩,此处为白色,可自定义\r\n return cv2.warpAffine(image, M, (nW, nH),borderValue=(255,255,255))\r\n # borderValue 缺省,默认是黑色(0, 0 , 0)\r\n # return cv2.warpAffine(image, M, (nW, nH))\r\n \r\n\r\nimgRotation = rotate_bound_white_bg(imgo, -rotate_angle)\r\nio.imshow(imgRotation )\r\nio.show()\r\n#io.imsave('rotate_signal.png', imgRotation)\r\n\r\n\r\n","sub_path":"untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"630054447","text":"from flask import Flask, jsonify, request\r\nfrom utils import *\r\nimport csv\r\n\r\napp = Flask(__name__)\r\n\r\n# PIP API\r\n@app.route('/pip', methods=['POST'])\r\ndef index():\r\n # get concrete entities\r\n json_content = request.get_json()\r\n org = json_content['org']\r\n sub = json_content['subject']\r\n obj = json_content['object']\r\n act = json_content['action']\r\n ctx = json_content['ctx']\r\n\r\n # match concrete and abstract entities\r\n role = empower(org, sub)[2]\r\n view = use(org, obj)[2]\r\n ay = consider(org, act)[2]\r\n context = check_context(ctx[0], ctx[1])[2]\r\n\r\n fields = [org, role, view, ay, context]\r\n \r\n # save fields in request.csv\r\n with open(r'request.csv', 'a') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(fields)\r\n return str(fields)\r\n\r\n# PAP API\r\n@app.route('/pap', methods=['POST'])\r\ndef pap_func():\r\n # get abstract entities\r\n json_content = request.get_json()\r\n org = json_content['org']\r\n role = json_content['role']\r\n view = json_content['view']\r\n activity = json_content['activity']\r\n context = json_content['context']\r\n\r\n # get decision from PAP\r\n response = check_decision(org, role, view, activity, context)\r\n\r\n # save reponse in reponse.csv\r\n with open(r'response.csv', 'a') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(response)\r\n \r\n return str(response)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","sub_path":"PIP/API_pip_process.py","file_name":"API_pip_process.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"503957084","text":"\n\"\"\"Generating notes for a midi file using the trained RNN\"\"\"\n\nimport pickle\nimport numpy\nimport music21\nfrom music21 import instrument, note, stream, chord\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.models import load_model\n\n\nmodel_path = '/content/drive/My Drive/Midi_Dataset/RNN_percussion-0.17.hdf5'\n\ndef generate():\n \"\"\"Generate a midi file\"\"\"\n #load the notes used to train the model\n with open('/content/notes', 'rb') as filepath:\n notes = pickle.load(filepath)\n\n # Get all pitch names\n pitchnames = sorted(set(item for item in notes))\n # Get all pitch names\n n_vocab = len(set(notes))\n\n network_input, normalized_input = prepare_sequences(notes, pitchnames, n_vocab)\n model = load_rnn(model_path)\n prediction_output = generate_notes(model, network_input, pitchnames, n_vocab)\n create_midi(prediction_output)\n \ndef prepare_sequences(notes, pitchnames, n_vocab):\n \"\"\"Prepare the sequences used by the RNN\"\"\"\n # map between notes and integers and back\n note_to_int = dict((note, number) for number, note in enumerate(pitchnames))\n\n sequence_length = 128\n network_input = []\n output = []\n for i in range(0, len(notes) - sequence_length, 1):\n sequence_in = notes[i:i + sequence_length]\n sequence_out = notes[i + sequence_length]\n network_input.append([note_to_int[char] for char in sequence_in])\n output.append(note_to_int[sequence_out])\n\n n_patterns = len(network_input)\n\n # reshape the input into a format compatible with LSTM layers\n normalized_input = numpy.reshape(network_input, (n_patterns, sequence_length, 1))\n # normalize input\n normalized_input = normalized_input / float(n_vocab)\n\n return (network_input, normalized_input)\n \n \ndef load_rnn(saved_model_path):\n \"\"\"Load your saved model with the weights\"\"\"\n model = load_model(saved_model_path)\n\n return model\n \n \ndef generate_notes(model, network_input, pitchnames, n_vocab):\n \"\"\" Generate notes from the RNN based on a sequence of notes \"\"\"\n # pick a random sequence from the input as a starting point for the prediction\n start = numpy.random.randint(0, len(network_input)-1)\n\n int_to_note = dict((number, note) for number, note in enumerate(pitchnames))\n\n pattern = network_input[start]\n prediction_output = []\n\n # generate 128 notes\n for note_index in range(128):\n prediction_input = numpy.reshape(pattern, (1, len(pattern), 1))\n prediction_input = prediction_input / float(n_vocab)\n\n prediction = model.predict(prediction_input, verbose=0)\n\n index = numpy.argmax(prediction)\n result = int_to_note[index]\n prediction_output.append(result)\n\n pattern.append(index)\n pattern = pattern[1:len(pattern)]\n\n return prediction_output\n \n \ndef create_midi(prediction_output):\n \"\"\"Convert the numerical output values \n from the prediction to notes and create a midi file\"\"\"\n offset = 0\n output_notes = []\n\n # create note and chord objects based on the values generated by the model\n for pattern in prediction_output:\n # pattern is a chord\n if ('.' in pattern) or pattern.isdigit():\n notes_in_chord = pattern.split('.')\n notes = []\n for current_note in notes_in_chord:\n new_note = note.Note(int(current_note))\n new_note.storedInstrument = instrument.BongoDrums()\n notes.append(new_note)\n new_chord = chord.Chord(notes)\n new_chord.offset = offset\n output_notes.append(new_chord)\n # pattern is a note\n else:\n new_note = note.Note(pattern)\n new_note.offset = offset\n new_note.storedInstrument = instrument.BongoDrums()\n output_notes.append(new_note)\n\n # increase offset each iteration so that notes do not stack\n offset += 0.5\n\n midi_stream = stream.Stream(output_notes)\n\n midi_stream.write('midi', fp='test_output.mid')\n \n \nif __name__ == '__main__':\n generate()\n","sub_path":"rnn_generate.py","file_name":"rnn_generate.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"457328759","text":"def even_number_of_evens(numbers):\n \"\"\"\n Returns the number of even numbers contained in a list of numbers.\n\n `numbers` should be a list containing numbers\n \n Returns either True or False based on a number of criteria.\n - if `numbers` is empty, return `False`\n - if the number of even numbers is odd, return `False`\n - if the number of even numbers is 0, return `False`\n - if the number od even numbers is even, return `True`\n \"\"\"\n\n # Check to see if the list is empty\n if numbers == []:\n return False\n else:\n # Set a `number_of_evens` variable that will be incremented each time\n # an even number is found\n evens = 0\n \n # Iterate of over each item and if it's an even number, increment the\n # `evens` variable\n for number in numbers:\n if number % 2 == 0:\n evens += 1\n \n if evens == 0:\n return False\n else:\n return evens % 2 == 0\n\n# Our set of test cases\nassert even_number_of_evens([]) == False, \"No numbers\"\nassert even_number_of_evens([2]) == False, \"One even number\"\nassert even_number_of_evens([2, 4]) == True, \"Two even numbers\"\nassert even_number_of_evens([2, 3]) == False, \"Two numbers, only one even\"\nassert even_number_of_evens([2, 3, 9, 10, 13, 7, 8]) == False, \"Multiple numbers, three even\"\nassert even_number_of_evens([2, 3, 9, 10, 13, 7, 8, 5, 12]) == True, \"Multiple numbers, four even\"\nassert even_number_of_evens([1, 3, 9]) == False, \"No even numbers\"\n\n# If all the test cases pass, print some successful info to the console to let\n# the developer know\nprint(\"All tests passed!\")","sub_path":"04-test_driven_development/evens.py","file_name":"evens.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"45744998","text":"from . import models\nfrom rest_framework import serializers\n\nfrom users.serializers import UserSerializer, AgentSerializer\nfrom sales.models import Sale\n\n\nclass InvoiceDocSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.InvoiceDoc\n fields = '__all__'\n\n\nclass LightSaleSerializer(serializers.ModelSerializer):\n class Meta:\n model = Sale\n fields = ['id']\n\n\nclass InvoiceSerializer(serializers.ModelSerializer):\n sales = LightSaleSerializer(many=True, read_only=True)\n agent = AgentSerializer(many=False, read_only=True)\n docs = InvoiceDocSerializer(many=True, read_only=True)\n\n class Meta:\n model = models.Invoice\n fields = '__all__'\n","sub_path":"backend_rest/invoices/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"462228250","text":"\"\"\"\n1137. N-th Tribonacci Number\n- Easy\n- DP\n- Link: https://leetcode.com/problems/n-th-tribonacci-number/\n\"\"\"\n\n\n# Solution 1: DP\n# Time: O(N) | Space: O(N)\nclass Solution:\n def tribonacci(self, n: int) -> int:\n trib = {0: 0, 1: 1, 2: 1}\n\n if n < 3:\n return trib[n]\n\n for i in range(3, n+1):\n trib[i] = trib[i-1] + trib[i-2] + trib[i-3]\n\n return trib[n]\n\n\n# Solution 1-1: DP with constant space\n# Time: O(N) | Space: O(1)\nclass Solution:\n def tribonacci(self, n: int) -> int:\n trib1, trib2, trib3 = 0, 1, 1\n if n == 0:\n return trib1\n if n == 1 or n == 2:\n return trib2\n\n for i in range(3, n+1):\n trib = trib1 + trib2 + trib3\n trib1 = trib2\n trib2 = trib3\n trib3 = trib\n\n return trib3\n","sub_path":"leetcode/dp/1137_nth_tribonacci_number.py","file_name":"1137_nth_tribonacci_number.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"628603635","text":"#!/practice/Study_Test python\n# -*- coding: utf-8 -*-\n# @Time : 2019/1/1 0:29\n# @Author : yb.w\n# @File : 拉钩.py\n\n\nimport requests\nimport math\nimport pandas as pd\nimport time\n\ndef get_json(url,num):\n\n headers = {\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 8.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\n \"Accept\":\"application/json, text/javascript, */*; q=0.01\",\n \"Cookie\":\"_ga=GA1.2.638044571.1520341071; user_trace_token=20180306205751-fa94dc20-213d-11e8-b12a-5254005c3644; LGUID=20180306205751-fa94e400-213d-11e8-b12a-5254005c3644; _gid=GA1.2.1115326601.1546259516; JSESSIONID=ABAAABAABEEAAJA1A9E8BD18BB416B213DBA414723C2E86; _gat=1; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1546259534,1546273934,1546273940,1546326319; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1546326319; LGSID=20190101150518-98e89d2e-0d93-11e9-b765-525400f775ce; PRE_UTM=; PRE_HOST=www.baidu.com; PRE_SITE=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DRvFvawzoR0eq43i7836lyqOqa_tf8leLr7IC1Q7dDuw3Xj46gE8ezerz-p9Z7TW8%26wd%3D%26eqid%3Dfb37f67400071a9c000000035c2b1122; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2Fzhaopin%2F; LGRID=20190101150518-98e89fdf-0d93-11e9-b765-525400f775ce; SEARCH_ID=0bc733db9e7e4609915dde3b136e9169\",\n \"Host\":\"www.lagou.com\",\n \"Origin\":\"https://www.lagou.com\",\n \"Referer\":\"https://www.lagou.com/jobs/list_python?city=%E5%85%A8%E5%9B%BD&cl=false&fromSearch=true&labelWords=&suginput=\",\n 'X-Anit-Forge-Code':'0',\n 'X-Anit-Forge-Token': 'None',\n 'X-Requested-With':'XMLHttpRequest'\n }\n\n data = {\n 'first':'true',\n 'pn': num,\n 'kd': '自动化测试工程师',\n }\n\n res = requests.post(url,headers=headers,data=data)\n res.raise_for_status()\n res.encoding = 'utf-8'\n\n page = res.json()\n return page\n\ndef get_page_num(count):\n #计算要抓取的页数\n #每页15个岗位,向上取整\n res = math.ceil(count/15)\n #拉钩网最多显示30页结果\n\n if res > 30:\n return 30\n else:\n return res\n\ndef get_page_info(jobs_list):\n #获取网页信息\n page_info_list = []\n for i in jobs_list:\n job_info = []\n job_info.append(i['companyShortName'])\n job_info.append(i['companySize'])\n job_info.append(i['positionName'])\n job_info.append(i['salary'])\n job_info.append(i['workYear'])\n job_info.append(i['education'])\n job_info.append(i['district'])\n job_info.append(i['positionAdvantage'])\n page_info_list.append(job_info)\n return page_info_list\n\n\ndef main(page_num):\n url = 'https://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false'\n #先设定页数为1,获取总得职位数\n page_1 = get_json(url,1)\n total_count = page_1['content']['positionResult']['totalCount']\n\n num = get_page_num(total_count)\n\n total_info = []\n time.sleep(20)\n print('职位总数{},页数{}'.format(total_count,num))\n\n for n in range(1,page_num+1):\n page = get_json(url,n)\n\n print(\"开始抓取第{}页数据\".format(n))\n\n job_list = page['content']['positionResult']['result']\n\n page_info = get_page_info(job_list)\n\n total_info += page_info\n\n time.sleep(30) #每次抓取完成后,暂停一会,防止被服务器拉黑\n\n print(\"第{}页数据抓取完毕\".format(n))\n\n #将总数据转化为 data frame 再输出\n\n df = pd.DataFrame(data = total_info,columns=['公司全名','公司规模','职位名称','薪资水平','工作经验','学历要求','区域','职位福利'])\n df.to_csv('lagou_job.csv',index = False)\n print('已保存为CSV文件')\n\n\n\nif __name__ == '__main__':\n # 从外部获取页数\n page_num = int(input(\"请输入页数\"))\n if page_num < 30:\n page_num = page_num\n else:\n page_num = 30\n\n main(page_num)\n\n\n\n\n# #遍历数据\n# for i in result:\n# # 公司名称\n# companyShortName = i['companyShortName']\n# # 职位\n# positionName = i['positionName']\n# #学历要求\n# education = i['education']\n# #\n# firstType = i['firstType']\n# #\n# industryField = i['industryField']\n# #薪资\n# salary = i['salary']\n# #开发类型\n# secondType = i['secondType']\n# #工作年限\n# workYear = i['workYear']\n# #地区\n# businessZones = i['businessZones']\n# #福利\n# companyLabelList = i['companyLabelList']\n#\n# # 保存数据\n# with open(region+word+'.csv','a') as f:\n# f.write('{},{},{},{},{},{},{},{},{},{}\\n'.format(companyShortName,positionName,education,salary,workYear,firstType,industryField,secondType,businessZones,companyLabelList))\n\n\n\n\n\n","sub_path":"StudyPacticePython/WebCrawler/拉钩网数据抓取+数据分析(直方图,饼图,词云图)/拉钩.py","file_name":"拉钩.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"280446517","text":"from pyquery import PyQuery as pq\n\ndoc = pq(url='https://www.python.org/events/python-events/')\n\ntitle = list(doc('.event-title').items())\ntime = list(doc('time').items())\nlocation = list(doc('.event-location').items())\n\ni = 0\nfor i in range(len(title)):\n print('会议: %s,\\n会议时间:%s,\\t会议地点:%s\\n' % (title[i].text(), time[i].text(), location[i].text()))","sub_path":"test/my_pyquery.py","file_name":"my_pyquery.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"543887140","text":"from django.shortcuts import render, render_to_response\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.conf import settings\nfrom models import UserImage,Car\nfrom forms import UploadFileForm\n\nfrom PIL.ExifTags import TAGS\nimport requests\nimport json\nimport random\nimport os\n\n\nAPI_KEY = 'b830d9398448bf6f676a59da4f0ca2e1'\nAPI_SECRET = 'GQIIGswjJAoqfPvNVJKPCVvfHwVpJbOR'\n\n# Create your views here.\ndef home(request):\n return render_to_response('youreyecar.html')\n\ndef upload(request):\n return render_to_response('upload.html')\n\n\n@csrf_exempt\ndef test(request):\n # if request.method == 'POST':\n # form = UploadFileForm(request.POST, request.FILES)\n # if form.is_valid():\n user_image = request.FILES['user_image']\n im = UserImage(image = user_image)\n im.save()\n img_path = settings.MEDIA_URL + str(im.image)\n face_detect_url = \"http://apicn.faceplusplus.com/v2/detection/detect\"\n post_data = {\n \"api_key\": API_KEY,\n \"api_secret\": API_SECRET,\n \"url\": img_path,\n \"attribute\": 'gender,age,smiling,glass,pose,race',\n }\n result = requests.post(face_detect_url, data=post_data)\n im.detect_result = result.text\n im.save()\n\n rlt_json= result.json()\n\n #return json format\n # user_image: int\n # eyes: [{x: int, y:int}, ]\n # img_height: int\n # img_width: int\n result_data = {}\n result_data['user_image'] = im\n\n if rlt_json.has_key('face'):\n eyes = []\n for face in rlt_json['face']:\n if face['position'].has_key('eye_left'):\n eye_left = {}\n eye_left['x'] = (int)(rlt_json['img_width'] * face['position']['eye_left']['x'] / 100)\n eye_left['y']= (int)(rlt_json['img_height'] * face['position']['eye_left']['y'] / 100)\n eyes.append(eye_left)\n\n if face['position'].has_key('eye_right'):\n eye_right = {}\n eye_right['x'] = (int)(rlt_json['img_width'] * face['position']['eye_right']['x'] / 100)\n eye_right['y'] = (int)(rlt_json['img_height'] * face['position']['eye_right']['y'] / 100)\n eyes.append(eye_right)\n result_data['eyes'] = eyes\n result_data['img_height'] = rlt_json['img_height']\n result_data['img_width'] = rlt_json['img_width']\n return render_to_response('open.html', result_data)\n # else:\n # return render_to_response('upload.html')\n # else:\n # return render_to_response('upload.html')\n\n@csrf_exempt\ndef result(request):\n if request.POST.has_key('user_image_id'):\n user_image_id = request.POST['user_image_id']\n try:\n img = UserImage.objects.get(id=user_image_id)\n result = json.loads(img.detect_result)\n result_data = {}\n result_data['user_image'] = img\n if result.has_key('face') and result['face']:\n if result['face'][0]['position']['eye_left'] or result['face'][0]['position']['eye_right']:\n result_data['eyes'] = 1\n cars = Car.objects.all()\n result_data['car'] = cars[random.randint(0,len(cars)-1)]\n return render_to_response('result.html',result_data)\n except ObjectDoesNotExist:\n render_to_response('404.html')\n\n else:\n return render_to_response('youreyecar.html')\n\ndef delete(request):\n image_id = request.GET['id']\n try:\n img = UserImage.objects.get(id=image_id)\n img.delete()\n except ObjectDoesNotExist:\n return render_to_response('youreyecar.html')","sub_path":"getyourcar_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"312431879","text":"import matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.feature import hog\n\n# Functions for vehicle detect features extraction\n\ndef convertColorSpace(img, color_space_in):\n if color_space_in == 'RGB':\n return cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n if color_space_in == 'BGR':\n return cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\n \ndef extractHog(img, orient, pix_per_cell, n_cell_per_block, \n vis=False, feature_vec=True):\n # Call with two outputs if an image of the HOG is requested\n if vis == True:\n features, hog_image = hog(img, orientations=orient, \n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(n_cell_per_block, n_cell_per_block), \n block_norm='L2-Hys', transform_sqrt=True, \n visualise=vis, feature_vector=feature_vec)\n return features, hog_image\n # Otherwise call with one output\n else: \n features = hog(img, orientations=orient, \n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(n_cell_per_block, n_cell_per_block), \n block_norm='L2-Hys', transform_sqrt=True, \n visualise=vis, feature_vector=feature_vec)\n return features\n\ndef binColorsSpatially(img, size):\n # Down sample the image and stack\n color1 = cv2.resize(img[:,:,0], size).ravel()\n color2 = cv2.resize(img[:,:,1], size).ravel()\n color3 = cv2.resize(img[:,:,2], size).ravel()\n return np.hstack((color1, color2, color3))\n \ndef computeColorHistogram(img, n_bins):\n # Compute the histogram of the color channels separately\n channel1_hist = np.histogram(img[:,:,0], bins=n_bins)\n channel2_hist = np.histogram(img[:,:,1], bins=n_bins)\n channel3_hist = np.histogram(img[:,:,2], bins=n_bins)\n # Concatenate the histograms into a single feature vector\n hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))\n # Return the individual histograms, bin_centers and feature vector\n return hist_features\n\ndef extractImgFeatures(img, color_space_in, hog_orient, hog_pix_per_cell, \n hog_cells_per_block, spatial_size, hist_bins, \n vis, hog_channel):\n # Extract the features from the image\n img_features = []\n imgC = convertColorSpace(img, color_space_in)\n\n # First the HOG\n if hog_channel == 'ALL':\n hog_features = []\n for channel in range(imgC.shape[2]):\n hog = extractHog(imgC[:,:,channel], hog_orient, hog_pix_per_cell, \n hog_cells_per_block, vis=False, feature_vec=True)\n hog_features.append(hog)\n hog_features = np.ravel(hog_features)\n else:\n if vis == True:\n hog_features, hog_image = extractHog(imgC[:,:,hog_channel], hog_orient, \n hog_pix_per_cell, hog_cells_per_block,\n vis=True, feature_vec=True)\n else:\n hog_features = extractHog(imgC[:,:,hog_channel], hog_orient, \n hog_pix_per_cell, hog_cells_per_block,\n vis=False, feature_vec=True)\n img_features.append(hog_features)\n\n # Second the color binning\n spatial_features = binColorsSpatially(imgC, spatial_size)\n img_features.append(spatial_features)\n\n # Third the color histogram\n hist_features = computeColorHistogram(imgC, hist_bins)\n img_features.append(hist_features)\n\n # Concatenate features and return\n if vis == True:\n return np.concatenate(img_features), hog_image\n else:\n return np.concatenate(img_features)\n \ndef extractFeatures(imgs, color_space_in, hog_orient, hog_pix_per_cell, \n hog_cells_per_block, spatial_size, hist_bins):\n # Extract features from a list of images\n features = []\n for img in imgs:\n img_features = extractImgFeatures(img, color_space_in, \n hog_orient, hog_pix_per_cell, hog_cells_per_block,\n spatial_size, hist_bins, \n vis=False, hog_channel='ALL')\n \n # Concatenate features and append to the imgs' list\n features.append(img_features)\n return features","sub_path":"vehicle_features.py","file_name":"vehicle_features.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"552909181","text":"#!/usr/bin/env python3\n\n\"\"\"Module containing the StructureCheck class and the command line interface.\"\"\"\nimport argparse\nfrom biobb_common.configuration import settings\nfrom biobb_common.tools import file_utils as fu\nfrom biobb_common.tools.file_utils import launchlogger\nfrom biobb_common.command_wrapper import cmd_wrapper\nfrom biobb_structure_utils.utils.common import *\n\nclass StructureCheck():\n \"\"\"\n | biobb_structure_utils StructureCheck\n | This class is a wrapper of the Structure Checking tool to generate summary checking results on a json file.\n | Wrapper for the `Structure Checking `_ tool to generate summary checking results on a json file from a given structure and a list of features.\n\n Args:\n input_structure_path (str): Input structure file path. File type: input. `Sample file `_. Accepted formats: pdb (edam:format_1476).\n output_summary_path (str): Output summary checking results. File type: output. `Sample file `_. Accepted formats: json (edam:format_3464).\n properties (dic - Python dictionary object containing the tool parameters, not input/output files):\n * **features** (*list*) - (None) Features to summarize. If None, all the features will be computed. Values: models (multiple molecules or coordinate sets in a single file), chains (multiple chains in a single file), altloc (atom alternative conformation given an alternate location indicator and occupancy), metals (metals present in the structure), ligands (heteroatoms present in the structure), chiral (to say that a structure is chiral is to say that its mirror image is not the same as it self), getss (detect SS bonds or disulfides), cistransbck (detact cis/trans backbone), backbone (detect backbone breaks), amide (detect too close amides), clashes (detect clashes).\n * **check_structure_path** (*string*) - (\"check_structure\") path to the check_structure application\n * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.\n * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.\n\n Examples:\n This is a use example of how to use the building block from Python::\n\n from biobb_structure_utils.utils.structure_check import structure_check\n prop = { \n 'features': ['models', 'chains', 'ligands']\n }\n structure_check(input_structure_path='/path/to/myInputStr.pdb, \n output_summary_path='/path/to/newSummary.json', \n properties=prop)\n\n Info:\n * wrapped_software:\n * name: Structure Checking from MDWeb\n * version: >=3.0.3\n * license: Apache-2.0\n * ontology:\n * name: EDAM\n * schema: http://edamontology.org/EDAM.owl\n \n \"\"\"\n\n def __init__(self, input_structure_path, \n output_summary_path, properties=None, **kwargs) -> None:\n properties = properties or {}\n\n # Input/Output files\n self.input_structure_path = str(input_structure_path)\n self.output_summary_path = str(output_summary_path)\n\n # Properties specific for BB\n self.check_structure_path = properties.get('check_structure_path', 'check_structure')\n self.features = properties.get('features', None)\n self.properties = properties\n\n # Common in all BB\n self.can_write_console_log = properties.get('can_write_console_log', True)\n self.global_log = properties.get('global_log', None)\n self.prefix = properties.get('prefix', None)\n self.step = properties.get('step', None)\n self.path = properties.get('path', '')\n self.remove_tmp = properties.get('remove_tmp', True)\n self.restart = properties.get('restart', False)\n\n def check_data_params(self, out_log, err_log):\n \"\"\" Checks all the input/output paths and parameters \"\"\"\n self.input_structure_path = check_input_path(self.input_structure_path, out_log, self.__class__.__name__)\n self.output_summary_path = check_output_path_json(self.output_summary_path, out_log, self.__class__.__name__)\n\n @launchlogger\n def launch(self) -> int:\n \"\"\"Execute the :class:`StructureCheck ` utils.structure_check.StructureCheck object.\"\"\"\n\n # Get local loggers from launchlogger decorator\n out_log = getattr(self, 'out_log', None)\n err_log = getattr(self, 'err_log', None)\n\n # check input/output paths and parameters\n self.check_data_params(out_log, err_log)\n\n # Check the properties\n fu.check_properties(self, self.properties)\n\n #Restart if needed\n if self.restart:\n output_file_list = [self.output_summary_path]\n if fu.check_complete_files(output_file_list):\n fu.log('Restart is enabled, this step: %s will the skipped' % self.step, out_log, self.global_log)\n return 0\n\n if not self.features:\n fu.log('No features provided, all features will be computed: %s' % 'models, chains, altloc, metals, ligands, chiral, getss, cistransbck, backbone, amide, clashes', out_log)\n self.features = ['models', 'chains', 'altloc', 'metals', 'ligands', 'chiral', 'getss', 'cistransbck', 'backbone', 'amide', 'clashes']\n else: \n fu.log('Computing features: %s' % ', '.join(self.features), out_log)\n\n # create temporary folder\n self.tmp_folder = fu.create_unique_dir()\n fu.log('Creating %s temporary folder' % self.tmp_folder, out_log)\n\n command_list = self.tmp_folder + '/command_list.lst'\n\n with open(command_list, 'w') as f:\n for item in self.features:\n f.write(\"%s\\n\" % item)\n\n # run command line\n cmd = [self.check_structure_path,\n '-i', self.input_structure_path,\n '--json', self.output_summary_path,\n '--check_only',\n '--non_interactive',\n 'command_list',\n '--list',\n command_list]\n\n returncode: int = cmd_wrapper.CmdWrapper(cmd, out_log, err_log, self.global_log).launch()\n\n fu.log('File %s created' % self.output_summary_path, out_log, self.global_log)\n\n # remove temporary folder\n if self.remove_tmp:\n fu.rm(self.tmp_folder)\n fu.log('Removing %s temporary folder' % self.tmp_folder, out_log)\n\n return returncode\n\ndef structure_check(input_structure_path: str, output_summary_path: str, properties: dict = None, **kwargs) -> int:\n \"\"\"Execute the :class:`StructureCheck ` class and\n execute the :meth:`launch() ` method.\"\"\"\n\n return StructureCheck(input_structure_path=input_structure_path, \n output_summary_path=output_summary_path,\n properties=properties, **kwargs).launch()\n\ndef main():\n \"\"\"Command line execution of this building block. Please check the command line documentation.\"\"\"\n parser = argparse.ArgumentParser(description=\"This class is a wrapper of the Structure Checking tool to generate summary checking results on a json file.\", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))\n parser.add_argument('-c', '--config', required=False, help=\"This file can be a YAML file, JSON file or JSON string\")\n\n #Specific args of each building block\n required_args = parser.add_argument_group('required arguments')\n required_args.add_argument('-i', '--input_structure_path', required=True, help=\"Input structure file path. Accepted formats: pdb.\")\n required_args.add_argument('-o', '--output_summary_path', required=True, help=\"Output summary checking results. Accepted formats: json.\")\n\n args = parser.parse_args()\n config = args.config if args.config else None\n properties = settings.ConfReader(config=config).get_prop_dic()\n\n #Specific call of each building block\n structure_check(input_structure_path=args.input_structure_path, \n output_summary_path=args.output_summary_path, \n properties=properties)\n\nif __name__ == '__main__':\n main()\n","sub_path":"biobb_structure_utils/utils/structure_check.py","file_name":"structure_check.py","file_ext":"py","file_size_in_byte":8591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"269747723","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom our_lib import tables\r\nimport synthetic_data\r\n\r\nsynthetic_data.set_seed(42)\r\n\r\nn = 100\r\n\r\nmu_key = 'exp_y'\r\n\r\nsigma_key = 'err'\r\n\r\ntable_keys = ('Dpp', 'Dpm', 'Ppp', 'Ppm')\r\n\r\nsynth_tables = {}\r\n\r\nfor key in table_keys:\r\n table = tables[key]\r\n\r\n synth_tables[key] = synthetic_data.synth_data_from_table(\r\n table, mu_key, sigma_key, n\r\n )\r\n\r\n synth_tables[key].to_excel('data/synthetic/{}.xlsx'.format(key),\r\n index=False)","sub_path":"TMD/generate_synth_data.py","file_name":"generate_synth_data.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"99701388","text":"#! /usr/bin/env python3\n\nimport argparse\nimport io\nimport os\nimport re\nimport shutil\nimport struct\nimport subprocess\nimport sys\nimport tempfile\nfrom textwrap import dedent\n\nclass ShaderCompileError(RuntimeError):\n def __init__(self, *args):\n super(ShaderCompileError, self).__init__(*args)\n\ntarget_env_re = re.compile(r'QO_TARGET_ENV\\s+(\\S+)')\nversion_re = re.compile(r'QO_VERSION\\s+(\\S+)')\n\nstage_to_glslang_stage = {\n 'VERTEX': 'vert',\n 'TESSELLATION_CONTROL': 'tesc',\n 'TESSELLATION_EVALUATION': 'tese',\n 'GEOMETRY': 'geom',\n 'FRAGMENT': 'frag',\n 'COMPUTE': 'comp',\n 'TASK': 'task',\n 'MESH': 'mesh',\n 'RAYGEN': 'rgen',\n 'ANY_HIT': 'rahit',\n 'CLOSEST_HIT': 'rchit',\n 'MISS': 'rmiss',\n 'INTERSECTION': 'rint',\n 'CALLABLE': 'rcall',\n}\n\nclass Shader:\n def __init__(self, stage):\n self.glsl = None\n self.stream = io.StringIO()\n self.stage = stage\n self.dwords = None\n self.target_env = \"\"\n\n def add_text(self, s):\n self.stream.write(s)\n\n def finish_text(self, start_line, end_line):\n self.glsl = self.stream.getvalue()\n self.stream = None\n\n # Handle the QO_EXTENSION macro\n self.glsl = self.glsl.replace('QO_EXTENSION', '#extension')\n\n # Handle the QO_DEFINE macro\n self.glsl = self.glsl.replace('QO_DEFINE', '#define')\n\n m = target_env_re.search(self.glsl)\n if m:\n self.target_env = m.group(1)\n self.glsl = self.glsl.replace('QO_TARGET_ENV', '// --target-env')\n\n if self.glsl.find('QO_VERSION') != -1:\n self.glsl = self.glsl.replace('QO_VERSION', '#version')\n else:\n self.glsl = \"#version 450\\n\" + self.glsl\n\n self.start_line = start_line\n self.end_line = end_line\n\n def __run_glslang(self, extra_args=[]):\n stage = stage_to_glslang_stage[self.stage]\n stage_flags = ['-S', stage]\n\n in_file = tempfile.NamedTemporaryFile(suffix='.'+stage)\n src = self.glsl.encode('utf-8')\n in_file.write(src)\n in_file.flush()\n out_file = tempfile.NamedTemporaryFile(suffix='.spirv')\n args = [glslang, '-H'] + extra_args + stage_flags\n if self.target_env:\n args += ['--target-env', self.target_env]\n args += ['-o', out_file.name, in_file.name]\n with subprocess.Popen(args,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE,\n stdin = subprocess.PIPE) as proc:\n\n out, err = proc.communicate(timeout=30)\n in_file.close()\n\n if proc.returncode != 0:\n # Unfortunately, glslang dumps errors to standard out.\n # However, since we don't really want to count on that,\n # we'll grab the output of both\n message = out.decode('utf-8') + '\\n' + err.decode('utf-8') + '\\nGLSL:\\n' + self.glsl\n raise ShaderCompileError(message.strip())\n\n out_file.seek(0)\n spirv = out_file.read()\n out_file.close()\n return (spirv, out)\n\n def compile(self):\n def dwords(f):\n while True:\n dword_str = f.read(4)\n if not dword_str:\n return\n assert len(dword_str) == 4\n yield struct.unpack('I', dword_str)[0]\n\n (spirv, assembly) = self.__run_glslang()\n self.dwords = list(dwords(io.BytesIO(spirv)))\n self.assembly = str(assembly, 'utf-8')\n\n def _dump_glsl_code(self, f):\n # Dump GLSL code for reference. Use // instead of /* */\n # comments so we don't need to escape the GLSL code.\n # We also ask the compiler to not complain about multi-line comments\n # that are created if a line of the GLSL ends in \"\\\"\n f.write('#pragma GCC diagnostic push //\"warning: multi-line comment\"\\n')\n f.write('#pragma GCC diagnostic ignored \"-Wcomment\"\\n')\n f.write('// GLSL code:\\n')\n f.write('//')\n for line in self.glsl.splitlines():\n f.write('\\n// {0}'.format(line))\n f.write('\\n\\n')\n f.write('#pragma GCC diagnostic pop\\n')\n\n def _dump_spirv_code(self, f, var_name):\n f.write('/* SPIR-V Assembly:\\n')\n f.write(' *\\n')\n for line in self.assembly.splitlines():\n f.write(' * ' + line + '\\n')\n f.write(' */\\n')\n\n f.write('static const uint32_t {0}[] = {{'.format(var_name))\n line_start = 0\n while line_start < len(self.dwords):\n f.write('\\n ')\n for i in range(line_start, min(line_start + 6, len(self.dwords))):\n f.write(' 0x{:08x},'.format(self.dwords[i]))\n line_start += 6\n f.write('\\n};\\n')\n\n def dump_c_code(self, f):\n f.write('\\n\\n')\n var_prefix = '__qonos_shader{0}'.format(self.end_line)\n\n self._dump_glsl_code(f)\n self._dump_spirv_code(f, var_prefix + '_spir_v_src')\n\n f.write(dedent(\"\"\"\\\n static const QoShaderModuleCreateInfo {0}_info = {{\n .spirvSize = sizeof({0}_spir_v_src),\n .pSpirv = {0}_spir_v_src,\n \"\"\".format(var_prefix)))\n\n if self.stage in ['RAYGEN', 'ANY_HIT', 'CLOSEST_HIT',\n 'MISS', 'INTERSECTION', 'CALLABLE']:\n f.write(\" .stage = VK_SHADER_STAGE_{0}_BIT_KHR,\\n\".format(self.stage))\n elif self.stage in ['TASK', 'MESH']:\n f.write(\" .stage = VK_SHADER_STAGE_{0}_BIT_NV,\\n\".format(self.stage))\n else:\n f.write(\" .stage = VK_SHADER_STAGE_{0}_BIT,\\n\".format(self.stage))\n\n f.write('};\\n')\n\n f.write('#define __qonos_shader{0}_info __qonos_shader{1}_info\\n'\\\n .format(self.start_line, self.end_line))\n\ntoken_exp = re.compile(r'(qoShaderModuleCreateInfoGLSL|qoCreateShaderModuleGLSL|\\(|\\)|,)')\n\nclass Parser:\n def __init__(self, f):\n self.infile = f\n self.paren_depth = 0\n self.shader = None\n self.line_number = 1\n self.shaders = []\n\n def tokenize(f):\n leftover = ''\n for line in f:\n pos = 0\n while True:\n m = token_exp.search(line, pos)\n if m:\n if m.start() > pos:\n leftover += line[pos:m.start()]\n pos = m.end()\n\n if leftover:\n yield leftover\n leftover = ''\n\n yield m.group(0)\n\n else:\n leftover += line[pos:]\n break\n\n self.line_number += 1\n\n if leftover:\n yield leftover\n\n self.token_iter = tokenize(self.infile)\n\n def handle_shader_src(self):\n paren_depth = 1\n for t in self.token_iter:\n if t == '(':\n paren_depth += 1\n elif t == ')':\n paren_depth -= 1\n if paren_depth == 0:\n return\n\n self.current_shader.add_text(t)\n\n def handle_macro(self, macro):\n t = next(self.token_iter)\n assert t == '('\n\n start_line = self.line_number\n\n if macro == 'qoCreateShaderModuleGLSL':\n # Throw away the device parameter\n t = next(self.token_iter)\n t = next(self.token_iter)\n assert t == ','\n\n stage = next(self.token_iter).strip()\n\n t = next(self.token_iter)\n assert t == ','\n\n self.current_shader = Shader(stage)\n self.handle_shader_src()\n self.current_shader.finish_text(start_line, self.line_number)\n\n self.shaders.append(self.current_shader)\n self.current_shader = None\n\n def run(self):\n for t in self.token_iter:\n if t in ('qoShaderModuleCreateInfoGLSL', 'qoCreateShaderModuleGLSL'):\n self.handle_macro(t)\n\ndef open_file(name, mode):\n if name == '-':\n if mode == 'w':\n return sys.stdout\n elif mode == 'r':\n return sys.stdin\n else:\n assert False\n else:\n return open(name, mode)\n\ndef parse_args():\n description = dedent(\"\"\"\\\n This program scrapes a C file for any instance of the\n qoShaderModuleCreateInfoGLSL and qoCreateShaderModuleGLSL macaros,\n grabs the GLSL source code, compiles it to SPIR-V. The resulting\n SPIR-V code is written to another C file as an array of 32-bit\n words.\n\n If '-' is passed as the input file or output file, stdin or stdout\n will be used instead of a file on disc.\"\"\")\n\n p = argparse.ArgumentParser(\n description=description,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n p.add_argument('-o', '--outfile', default='-',\n help='Output to the given file (default: stdout).')\n p.add_argument('--with-glslang', metavar='PATH',\n default='glslangValidator',\n dest='glslang',\n help='Full path to the glslangValidator shader compiler.')\n p.add_argument('infile', metavar='INFILE')\n\n return p.parse_args()\n\n\nargs = parse_args()\ninfname = args.infile\noutfname = args.outfile\nglslang = args.glslang\n\nwith open_file(infname, 'r') as infile:\n parser = Parser(infile)\n parser.run()\n\nfor shader in parser.shaders:\n shader.compile()\n\nwith open_file(outfname, 'w') as outfile:\n outfile.write(dedent(\"\"\"\\\n /* ========================== DO NOT EDIT! ==========================\n * This file is autogenerated by glsl_scraper.py.\n */\n\n #include \n\n #define __QO_SHADER_INFO_VAR2(_line) __qonos_shader ## _line ## _info\n #define __QO_SHADER_INFO_VAR(_line) __QO_SHADER_INFO_VAR2(_line)\n\n #define qoShaderModuleCreateInfoGLSL(stage, ...) \\\\\n __QO_SHADER_INFO_VAR(__LINE__)\n\n #define qoCreateShaderModuleGLSL(dev, stage, ...) \\\\\n __qoCreateShaderModule((dev), &__QO_SHADER_INFO_VAR(__LINE__))\n \"\"\"))\n\n for shader in parser.shaders:\n shader.dump_c_code(outfile)\n","sub_path":"misc/glsl_scraper.py","file_name":"glsl_scraper.py","file_ext":"py","file_size_in_byte":10291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"519306486","text":"import numpy as np\nimport os,sys,copy\nvar,F,hold,Committed={},{},[],[]\n# hold=[]\nmaxi = 1e14\ndef execute():\n global maxi\n check = 0\n # print(hold)\n size = len(hold)\n for i in range(size-1,0,-1):\n data = hold[i]\n if data[0] == 'S':\n if i == maxi:\n break\n if data[0] == 'SC':\n if check == 1:\n break\n else:\n for j, data1 in enumerate(data):\n if j>=1 :\n try:\n maxi = min(maxi,F[data1])\n except:\n pass\n\n if data[0] == 'E':\n check=1\n if data[0] == 'C':\n Committed.append(data[1])\n if data[0] == 'V':\n if data[1] not in Committed:\n var[data[2]] = data[3]\n printans()\n\ndef printans():\n temp1 = []\n for key,data in var.items():\n temp1.append([key,data])\n temp1.sort(key=lambda x: x[0])\n\n for i in range(len(temp1)-1):\n print(temp1[i][0],temp1[i][1],end=' ')\n if len(temp1) >0:\n print(temp1[len(temp1)-1][0],temp1[len(temp1)-1][1],end='')\n print()\n\n\ndef parse_command(filename):\n with open(filename,'r') as file:\n lines = file.readlines()\n temp = [((line.strip('\\n')).strip('<')).strip('>') for line in lines]\n for i in range(len(lines)):\n if len(lines[i]) > 1:\n temp1 = temp[i]\n hold.append(temp1)\n # print(hold)\n for ind, line in enumerate(hold):\n temp = line.split(' ')\n hold[ind] = temp\n # print(temp)\n for ind2,j in enumerate(temp):\n temp2 = ((j.strip(',')).strip(')')).strip('(')\n hold[ind][ind2] = temp2\n\n \n for i in range(1,len(hold[0]),2):\n prev = hold[0][i-1]\n var[prev] = int(hold[0][i])\n \n for ind,data in enumerate(hold):\n if ind == 0:\n continue\n if data[0] == 'END':\n log = []\n log.append('E')\n\n elif data[0] == 'START':\n if(len(data)==2):\n log = []\n log.append('S')\n log.append(data[1])\n if data[1] not in F:\n F[data[1]] = ind\n else:\n log = []\n log.append('SC')\n for j,data1 in enumerate(data):\n if j>=2:\n log.append(data1)\n\n elif data[0] == 'COMMIT':\n log = []\n log.append('C')\n log.append(data[1])\n \n else:\n log = ['V']\n log.append(data[0])\n log.append(data[1])\n log.append(int(data[2]))\n \n hold[ind] = log\n \n # print(hold[ind])\n # print(data)\n\n \n\n\nif __name__ == '__main__':\n \n if(len(sys.argv)!=2):\n print(\"Wrong Input Format\")\n exit()\n \n filename = sys.argv[1]\n parse_command(filename)\n execute()","sub_path":"redo.py","file_name":"redo.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"395906671","text":"#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nfrom bes.system.log import log\nfrom bes.system.check import check\nfrom .storage_registry import storage_registry\n\nfrom collections import namedtuple\n\nclass storage_factory(object):\n\n config = namedtuple('config', 'local_cache_dir, sub_repo, no_network, storage_config')\n check.register_class(config, name = 'storage_factory_config')\n \n @classmethod\n def create(clazz, config):\n provider = config.storage_config.provider\n clazz.log_i('provider=%s; config=%s' % (provider, str(config)))\n clazz = storage_registry.get(provider)\n if not clazz:\n raise TypeError('Unknown provider type: \\\"%s\\\"' % (provider))\n return clazz(config)\n \n @classmethod\n def has_provider(clazz, provider):\n return storage_registry.get(provider) is not None\n\nlog.add_logging(storage_factory, 'storage_factory')\n","sub_path":"lib/rebuild/storage/storage_factory.py","file_name":"storage_factory.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"1359921","text":"from flask import Flask, request, jsonify,render_template\nimport os\nimport subprocess\nfrom firebase import firebase\nimport pyrebase\nimport base64\nimport json\nimport webbrowser\nimport urllib\nimport glob\nimport cv2\nimport PyPDF2\nimport sys\nfrom PIL import Image, ImageChops\nimport numpy as np\nimport requests \nimport tabula\nimport lineseg\nimport textseg\nimport char_binarize\nimport char_padding\napp = Flask(__name__)\n\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__)) \n\n@app.route('/', methods = [\"GET\",\"POST\"])\ndef index():\n\treturn render_template('index.html')\t\n\t\n@app.route('/select', methods = [\"GET\",\"POST\"])\ndef select():\n\treturn render_template('upload.html')\t\n\n@app.route('/pdf_to_word_result', methods = [\"POST\"])\ndef pdf_to_word_result():\n\t\n\ttarget = os.path.join(APP_ROOT, 'pdfs/')\n\tprint(target)\n\tif not os.path.isdir(target):\n\t\tos.mkdir(target)\n\t\tprint(request.files.getlist(\"file\"))\n\tfor upload in request.files.getlist(\"file\"):\n\t\tprint(upload)\n\t\tprint(\"{} is the file name\".format(upload.filename))\n\t\tfilename = 'outputGenerated.pdf'\n\t\t# This is to verify files are supported\n\t\text = os.path.splitext(filename)[1]\n\t\tif ext == \".pdf\":\n\t\t print(\"File supported moving on...\")\n\t\telse:\n\t\t render_template(\"Error.html\", message=\"Files uploaded are not supported...\")\n\t\tdestination = \"/\".join([target, filename])\n\t\tprint(\"Accept incoming file:\", filename)\n\t\tprint(\"Save it to:\", destination)\n\t\tupload.save(destination)\n\t\t\n\n\tpdfFileObj = open('/home/abid/Android_Projects/Android_and_Web/pdfs/outputGenerated.pdf', 'rb')\n\t# df = tabula.read_pdf('/home/abid/Android_Projects/Android_and_Web/pdfs/'+upload.filename)\n\t# tabula.convert_into('/home/abid/Android_Projects/Android_and_Web/pdfs/'+upload.filename,'output.csv',output_format='csv')\n\t# pdfReader = PyPDF2.PdfFileReader(pdfFileObj)\n \n\t# # printing number of pages in pdf file\n\t# n=pdfReader.numPages\n\t# #redirect output to file\n\t# orig_stdout = sys.stdout\n\t# f=open(\"/home/abid/Android_Projects/Android_and_Web/pdfs/pdf.txt\",\"w\")\n\t# sys.stdout = f\n\t# for i in range(0,n):\n\t# # creating a page object\n\t# \tpageObj = pdfReader.getPage(i)\n\t# \tprint(pageObj.extractText())\n\n\t# sys.stdout = orig_stdout\n\t# f.close()\n\t \n\t# # closing the pdf file object\n\t# pdfFileObj.close()\n\tos.system('pdftotext -layout /home/abid/Android_Projects/Android_and_Web/pdfs/outputGenerated.pdf')\n\t\n\twith open (\"/home/abid/Android_Projects/Android_and_Web/pdfs/outputGenerated.txt\", \"r\") as myfile:\n\t\tdata=myfile.read().replace('\\n', '')\n\treturn \"File downloaded\"\n\t# return render_template('')\t\n\n\ndef black_and_white(input_image_path,\n output_image_path):\n color_image = Image.open(input_image_path)\n bw = color_image.convert('L')\n bw.save(output_image_path)\n\n\n\n@app.route('/retrive', methods = ['GET','POST'])\ndef retrive():\t\n\tfirebase1 = firebase.FirebaseApplication('https://friendlychat-3d8f7.firebaseio.com/imgPath/', None)\n\tresult = firebase1.get('/imgPath', None)\n\tprint(type(result))\n\tfor i in result:\n\t\tfor k in result[i]:\n\t\t\timageurl = result[i][k]\n\tprint(imageurl)\n\n\t# for k in result.items():\n\t# \tprint(k);\n\n\t# return jsonify({'ans':result})\n\t# webbrowser.open(result)\t\t\n\tr = requests.get(imageurl, allow_redirects=True)\n\topen('google.jpeg', 'wb').write(r.content)\n\t\n\t# col = Image.open(\"google.jpeg\")\n\t# gray = col.convert('L')\n\t# bw = gray.point(lambda x: 0 if x<128 else 255, '1')\n\t# bw.save(\"result_bw.jpeg\")\n\t\n\t\n\t# img = cv2.imread('google.jpeg',0)\n\t# ret,thresh=cv2.threshold(img, 100, 255, cv2.THRESH_OTSU)\n\n\t# cv2.imshow('image',thresh)\n\t# cv2.waitKey(1000)\n\t# cv2.destroyAllWindows()\n\t# # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t# cv2.imwrite('google1.jpeg',thresh)\n\t\n\t\t\t# size = (700,700)\n\n\t\t\t# image = Image.open('google.jpeg')\n\t\t\t# image.thumbnail(size, Image.ANTIALIAS)\n\t\t\t# image_size = image.size\n\t\t\t# thumb = image.crop( (0, 0, size[0], size[1]) )\n\n\t\t\t# offset_x = max( (size[0] - image_size[0]) // 2, 0 )\n\t\t\t# offset_y = max( (size[1] - image_size[1]) // 2, 0 )\n\n\t\t\t# image = ImageChops.offset(thumb, offset_x, offset_y)\n\t\t\t# thumb.save('cropped.jpg')\n\t\t\t# black_and_white('cropped.jpg',\n\t\t # 'bw_cropped.jpg')\n\n\t\t\t# lineseg.Lineseg()\n\t\t\t# textseg.Textseg()\n\t\t\t# cv2.destroyWindow(\"Detected text\")\n\t\t\t# char_binarize.Char_binarize()\n\t\t\t# char_padding.Char_padding()\n\tresult = \"Abid Harsh Vishal Simran Riya Nausheen\"\n\treturn render_template(\"retrive.html\",result = result)\n\t# open('google.jpeg', 'wb').write(r.content)\n\n\t# return (\"Image Downloaded\")\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8098, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15331008","text":"def paliandrome(string):\n\tnewtstring = []\n\tfor i in range(len(string)-1,-1,-1):\n\t\tnewtstring.append(string[i])\n\tif ''.join(newtstring)==string:\n\t\tprint(string + ' is paliandrome')\n\telse:\n\t\tprint(string + ' is not paliandrome')\n\n#paliandrome('malayalam')\n#paliandrome('vishnu')\n#paliandrome('meera')\n\ndef newpaliandrome(string):\n\tfor i in range(0,len(string)-1):\n\t\tif (string[i].lower() != string[len(string)-1-i].lower()) :\n\t\t\tprint(string + ' is not paliandrome')\n\t\t\treturn\n\tprint(string + ' is paliandrome')\n\n#newpaliandrome('vishnu')\n#newpaliandrome('Saippuakivikauppias')\n#newpaliandrome('tattarrattat')\n\ndef palianRecur(string,start,end):\n\tprint(palianRecur)\n\tif(end==-1):\n\t\tprint(string + ' is paliandrome')\n\t\treturn\n\telse:\n\t\tif(string[start].lower() != string[end].lower()):\n\t\t\tprint(string + ' is not paliandrome')\n\t\t\treturn\n\t\telse:\n\t\t\tpalianRecur(string, start+1, end-1)\n\npalianRecur('malayalam', 0, len('malayalam')-1)\n#palianRecur('vishnu', 0, len('vishnu')-1)","sub_path":"notes/paliandrome.py","file_name":"paliandrome.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"150654699","text":"# -*- coding: utf-8 -*-\r\n# Copyright (c) 2015-2016, Exa Analytics Development Team\r\n# Distributed under the terms of the Apache License 2.0\r\n\"\"\"\r\nJob Table\r\n#############\r\nA job is a single experiment, typically resulting in a number of \"raw\" data\r\nfiles (inputs and outputs) that can be represented in memory by a single\r\ncontainer. Since this is not always the case, jobs have a many to many\r\nrelationship with container files.\r\n\"\"\"\r\nfrom sqlalchemy import String, Integer, ForeignKey, Table, Column\r\nfrom sqlalchemy.orm import relationship\r\nfrom exa.relational.base import Name, Time, Size, Base\r\n\r\n\r\njobdatafile = Table( # Many to many relationship; Job - DataFile\r\n 'jobdatafile',\r\n Base.metadata,\r\n Column('job_pkid', Integer, ForeignKey('job.pkid', onupdate='CASCADE', ondelete='CASCADE')),\r\n Column('datafile_pkid', Integer, ForeignKey('datafile.pkid', onupdate='CASCADE', ondelete='CASCADE'))\r\n)\r\n\r\n\r\njobcontainerfile = Table( # Many to many relationship; Job - ContainerFile\r\n 'jobcontainerfile',\r\n Base.metadata,\r\n Column('job_pkid', Integer, ForeignKey('job.pkid', onupdate='CASCADE', ondelete='CASCADE')),\r\n Column('containerfile_pkid', Integer, ForeignKey('containerfile.pkid', onupdate='CASCADE', ondelete='CASCADE'))\r\n)\r\n\r\n\r\nclass Job(Name, Time, Size, Base):\r\n \"\"\"\r\n Specific task in a :class:`~exa.relational.Program` or\r\n :class:`~exa.relational.Project`.\r\n \"\"\"\r\n datafiles = relationship('DataFile', secondary=jobdatafile, backref='jobs',\r\n cascade='all, delete')\r\n containerfiles = relationship('ContainerFile', secondary=jobcontainerfile,\r\n backref='jobs', cascade='all, delete')\r\n","sub_path":"exa/relational/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377598751","text":"import json\nimport logging\nimport os\nfrom src.worker_lookup.worker_lookup_params \\\n import WorkerLookUp\nfrom src.work_order_receipt.work_order_receipt_params \\\n import WorkOrderReceipt\nfrom src.work_order_receipt.work_order_receipt_retrieve_params \\\n import WorkOrderReceiptRetrieve\nfrom src.libs import constants\nfrom src.worker_retrieve.worker_retrieve_params \\\n import WorkerRetrieve\nfrom src.worker_register.worker_register_params \\\n import WorkerRegister\nfrom src.worker_set_status.worker_set_status_params \\\n import WorkerSetStatus\nfrom src.worker_update.worker_update_params \\\n import WorkerUpdate\nfrom src.work_order_get_result.work_order_get_result_params \\\n import WorkOrderGetResult\nfrom src.work_order_submit.work_order_submit_params \\\n import WorkOrderSubmit\nfrom src.utilities.submit_request_utility import \\\n submit_request_listener, submit_lookup_sdk, \\\n submit_retrieve_sdk, submit_create_receipt_sdk, \\\n submit_work_order_sdk, submit_register_sdk, \\\n submit_setstatus_sdk, submit_retrieve_receipt_sdk, \\\n submit_update_sdk\nfrom src.libs.direct_listener import ListenerImpl\nfrom src.libs.direct_sdk import SDKImpl\nimport globals\nimport avalon_sdk.worker.worker_details as worker\nTCFHOME = os.environ.get(\"TCF_HOME\", \"../../\")\nlogger = logging.getLogger(__name__)\n\n\ndef read_json(request_file):\n # Read the method name from JSON file\n with open(request_file, \"r\") as file:\n input_json = file.read().rstrip('\\n')\n\n input_json_obj = json.loads(input_json)\n\n return input_json_obj\n\n\ndef build_request_obj(input_json_obj,\n pre_test_output=None, pre_test_response=None):\n \"\"\"\n This function is used after the pre_test_env and for the\n actual request method passed in the test JSON file. Depending on the\n test mode and the request method, it will call the corresponding\n configure_data function.\n\n Output: request obj which is the final JSON object in case of the\n listener mode, for SDK mode it is the parameter required by the SDK\n function of the request method\n action_obj is the object of the request method class.\n\n For ex:\n worker_lookup SDK function requires worker_type parameter\n worker_retrieve SDK function requires worker_id parameter.\n \"\"\"\n request_method = input_json_obj[\"method\"]\n if request_method == \"WorkerUpdate\":\n action_obj = WorkerUpdate()\n elif request_method == \"WorkerSetStatus\":\n action_obj = WorkerSetStatus()\n elif request_method == \"WorkerRegister\":\n action_obj = WorkerRegister()\n elif request_method == \"WorkerLookUp\":\n action_obj = WorkerLookUp()\n elif request_method == \"WorkerRetrieve\":\n action_obj = WorkerRetrieve()\n elif request_method == \"WorkOrderSubmit\":\n action_obj = WorkOrderSubmit()\n elif request_method == \"WorkOrderGetResult\":\n action_obj = WorkOrderGetResult()\n elif request_method == \"WorkOrderReceiptCreate\":\n action_obj = WorkOrderReceipt()\n elif request_method == \"WorkOrderReceiptRetrieve\":\n action_obj = WorkOrderReceiptRetrieve()\n if constants.direct_test_mode == \"listener\":\n request_obj = action_obj.configure_data(\n input_json_obj, pre_test_output, pre_test_response)\n else:\n request_obj = action_obj.configure_data_sdk(\n input_json_obj, pre_test_output, pre_test_response)\n\n return request_obj, action_obj\n\n\ndef submit_request(uri_client, output_obj, output_file, input_file):\n \"\"\"\n Single function that is called from the test with the relevant input parameters.\n For listener, output_obj is the JSON obj, for SDK it is the parameter that is received\n as an output from build_request_obj function.\n \"\"\"\n request_method = input_file[\"method\"]\n if constants.direct_test_mode == \"listener\":\n submit_response = submit_request_listener(\n uri_client, output_obj, output_file)\n else:\n if request_method == \"WorkerLookUp\":\n submit_response = submit_lookup_sdk(\n output_obj, input_file)\n elif request_method == \"WorkerRetrieve\":\n submit_response = submit_retrieve_sdk(\n output_obj, input_file)\n elif request_method == \"WorkOrderSubmit\":\n submit_response = submit_work_order_sdk(\n output_obj, input_file)\n elif request_method == \"WorkOrderReceiptCreate\":\n submit_response = submit_create_receipt_sdk(\n output_obj, input_file)\n elif request_method == \"WorkOrderReceiptRetrieve\":\n submit_response = submit_retrieve_receipt_sdk(\n output_obj, input_file)\n elif request_method == \"WorkerRegister\":\n submit_response = submit_register_sdk(\n output_obj, input_file)\n elif request_method == \"WorkerSetStatus\":\n submit_response = submit_setstatus_sdk(\n output_obj, input_file)\n elif request_method == \"WorkerUpdate\":\n submit_response = submit_update_sdk(\n output_obj, input_file)\n return submit_response\n\n\n\ndef impl_instance():\n if constants.direct_test_mode == \"sdk\":\n logger.info(\"Inside SDK instance\\n\")\n return SDKImpl()\n elif constants.direct_test_mode == \"listener\":\n logger.info(\"Inside Listener instance\\n\")\n return ListenerImpl()\n\n\ndef pre_test_env(input_file):\n \"\"\"\n This function sets up the environment required to run the test.\n For ex: Work Order Submit test requires worker_lookup, retrieve\n the worker details and pass that as the output.\n \"\"\"\n request_method = input_file[\"method\"]\n impl_type = impl_instance()\n\n if request_method == \"WorkerRetrieve\" or \\\n request_method == \"WorkerUpdate\" or \\\n request_method == \"WorkerSetStatus\":\n lookup_response = impl_type.worker_lookup()\n logger.info(\"******Received Response******\\n%s\\n\", lookup_response)\n return lookup_response\n\n if request_method == \"WorkOrderSubmit\":\n lookup_response = impl_type.worker_lookup()\n worker_obj = impl_type.worker_retrieve(lookup_response)\n return worker_obj\n\n if request_method == \"WorkOrderReceiptCreate\":\n lookup_response = impl_type.worker_lookup()\n worker_obj = impl_type.worker_retrieve(lookup_response)\n wo_submit = impl_type.work_order_submit(worker_obj)\n return worker_obj, wo_submit\n\n if request_method == \"WorkOrderReceiptRetrieve\":\n lookup_response = impl_type.worker_lookup()\n worker_obj = impl_type.worker_retrieve(lookup_response)\n wo_submit = impl_type.work_order_submit(worker_obj)\n wo_create_receipt = impl_type.work_order_create_receipt(wo_submit)\n return worker_obj, wo_submit\n\n if request_method == \"WorkerRegister\":\n logger.info(\"No setup required for \\n%s\\n\", request_method)\n return 0\n","sub_path":"tests/automation_framework/src/libs/avalon_test_wrapper.py","file_name":"avalon_test_wrapper.py","file_ext":"py","file_size_in_byte":6932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"199871122","text":"from Utilities import tfs_pandas as tfs\nfrom Utilities import logging_tools as logtools\nimport os\n\nLOG = logtools.get_logger(__name__)\n\n\ndef clean_files(list_of_files, replace=False):\n for filepath in list_of_files:\n try:\n df = tfs.read_tfs(filepath)\n LOG.info(\"Read file {:s}\".format(filepath))\n except (IOError, tfs.TfsFormatError):\n LOG.info(\"Skipped file {:s}\".format(filepath))\n else:\n df = df.dropna(axis='index')\n if not replace:\n filepath += \".dropna\"\n tfs.write_tfs(filepath, df)\n\n\nif __name__ == \"__main__\":\n dirs = [\"/media/jdilly/Storage/Repositories/Gui_Output/2017-12-06/LHCB1/Results/15-45-45_WANALYSIS_SUSSIX_2\"]\n\n # dirs = [os.path.join(\"/\", \"afs\", \"cern.ch\", \"user\", \"j\", \"jdilly\", dir)\n # for dir in [\"w_afterGlobal\", \"w_afterGlobalCorrection\"]]\n\n\n for dir_path in dirs:\n all_files = os.listdir(dir_path)\n clean_files([os.path.join(dir_path, f) for f in all_files], replace=True)\n","sub_path":"Utilities/tfs_remove_nan.py","file_name":"tfs_remove_nan.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482618921","text":"# -*- coding:utf-8 -*-\nfrom typing import List\n\n\nclass Solution:\n def dailyTemperatures(self, T: List[int]) -> List[int]:\n res = [0 for _ in T]\n stack = list()\n for index, item in enumerate(T):\n while stack and item > T[stack[-1]]:\n temp = stack.pop()\n res[temp] = index - temp\n stack.append(index)\n\n return res\n","sub_path":"src/Algorithms/739每日温度/739.py","file_name":"739.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"400127562","text":"#! /usr/bin/env python3\n# coding: utf-8\n\n\nimport pygame # Pygame module for graphic interface\nfrom pygame.locals import * # Pygame constantes\n\nfrom area import *\nfrom character import *\nfrom item import *\n\n\ndef game_restart(needle, tube, ether, mac_gyver):\n \"\"\"When the game is waiting, the player can restart the game\n this function will reinitialize everything that is needed to\n play again\n\n \"\"\"\n Area.clear()\n Area.show_zones()\n mac_gyver.character_reset()\n Item.list_reset()\n needle.item_reset(Area.needle)\n tube.item_reset(Area.tube)\n ether.item_reset(Area.ether)\n pygame.display.flip()\n\n\n\n\n##############################################################################\n####################### RUNNING GAME LOOPS ##################################\n##############################################################################\ndef running_game(needle, tube, ether, mac_gyver):\n RUNNING = True\n while RUNNING:\n \"\"\"RUNNING loop is the main loop.\n When you leave this loop, the program is closed\n \n \"\"\"\n PLAYING = True\n while PLAYING:\n \"\"\" PLAYING loop is the playing mode loop\"\"\"\n for event in pygame.event.get():\n if event.type == QUIT:\n \"\"\"Exit the game\"\"\"\n PLAYING = False\n RUNNING = False\n WAITING = False\n if Character.GAME_END == True:\n \"\"\"When the player have found the 3 items and the guardian,\n GAME_END become true, so the playing loop is leaved\"\"\"\n WAITING = True\n PLAYING = False\n if Character.GAME_END == False and event.type == KEYDOWN:\n \"\"\"Control key to move in the game \"\"\"\n if event.key == K_UP or event.key == K_w:\n mac_gyver.up()\n if event.key == K_DOWN or event.key == K_s:\n mac_gyver.down()\n if event.key == K_LEFT or event.key == K_a:\n mac_gyver.left()\n if event.key == K_RIGHT or event.key == K_d:\n mac_gyver.right()\n \"\"\"Show updated game\"\"\"\n pygame.display.flip()\n\n\n while WAITING:\n \"\"\"WAITING loop is the end game loop. when the player have found\n the guardian, he have to choose if he wants to continue or is he \n wants to leave\n \n \"\"\"\n for event in pygame.event.get():\n if event.type == QUIT:\n WAITING = False\n RUNNING = False\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n WAITING = False\n RUNNING = False\n if event.key == K_SPACE:\n \"\"\"The player want to restart the game,\n so this loop is leaved, game_restart reinit game and\n the playing game loop come again.\n\n \"\"\"\n game_restart(needle, tube, ether, mac_gyver)\n WAITING = False\n\n","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"481530160","text":"'''\nBy starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n\n3\n7 4\n2 4 6\n8 5 9 3\n\nThat is, 3 + 7 + 4 + 9 = 23.\n\nFind the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.\n\nNOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)\n'''\nimport numpy as np\nfile_read=open(\"p_triangle.txt\",\"r\")\ntri_value=[]\nline=file_read.readline()\nwhile line:\n\ttri_value.append(list(map(int,line.split())))\n\tline=file_read.readline()\ntri_zero=[i+[0]*(len(tri_value)-len(i)) for i in tri_value]\ntri_matrix=np.matrix(tri_zero)\nm,n=tri_matrix.shape\nprint(m,n)\nfor j in range(m-1,0,-1):\n\tfor k in range(0,n-1):\n\t\t\ttri_matrix[j-1,k]+=max([tri_matrix[j,k],tri_matrix[j,k+1]])\nprint(tri_matrix[0,0])\n","sub_path":"50_100/p67_max_path_sum2.py","file_name":"p67_max_path_sum2.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78877108","text":"\"\"\"\nIdeas:\n Snooze timers automatically, repeat until acknowledged - just add another timer for 5 min later, and add emoji to react and acknowledge\n Reminders have option of whether they need to be acknowledged\n Filter naughty words\n\"\"\"\n\nimport datetime\nimport logging\nimport random\nimport time\nimport traceback\nfrom datetime import timedelta\n\nfrom bot_data_store import ConvoSubscription\nfrom client import Client\nfrom data_store import Data\nfrom db import DB\nfrom enums import Days\nfrom interface import (get_menu_selections, get_next_response,\n get_utc_offset_mins, get_yes_no, prompt)\nfrom misc import (capitalize, get_alarm_description, get_formatted_datetime,\n get_local_time_from_offset, remove_all_punctuation,\n remove_trailing_punctuation, seconds_to_string, str_to_time,\n uncapitalize)\nfrom user import User\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\nCOMMAND_DESCRIPTIONS = {\n \"ping\": \"check that I\\'m listening!\",\n \"help\": \"display available commands\",\n #\"dm\": \"I'll send you a friendly DM!\",\n \"timer\": \"Set a timer!\",\n \"list timers\": \"List all of the timers I'm keeping track of for you!\",\n \"delete timer\": \"Delete an existing timer\",\n \"alarm\": \"Set an alarm!\",\n \"list alarms\": \"List all of your alarms!\",\n \"delete alarm\": \"Delete an existing alarm\"\n\n}\n\n\nclient = Client.get_client()\n\n\nasync def ping_command(message, command_arg):\n await message.channel.send('Pong!')\n\n\nasync def help_command(message, command_arg):\n if command_arg is None:\n max_command_width = max([len(x) for x in COMMAND_DESCRIPTIONS.keys()])\n\n help_str = ''\n for key in sorted(list(COMMAND_DESCRIPTIONS.keys())):\n description_lines = COMMAND_DESCRIPTIONS[key].split('\\n')\n separator = '\\n' + ''.join([' ' for _ in range(max_command_width + 2)])\n description_lines = separator.join(description_lines)\n help_str += f'{key:>{max_command_width}}: {description_lines}\\n'\n help_str = help_str.rstrip()\n\n await message.channel.send(\n \"Hi, I'm Ayu! I'm here to help!\\n\\n\"\n \"Here's what I can do (make sure you say `!ayu` first!):\"\n f\"```{help_str}```\\n\"\n \"If you want to know about a single command, you can say `!ayu help `\\n\\n\"\n \"I've also got a few hidden commands ^-^\"\n )\n else:\n command_arg = remove_trailing_punctuation(command_arg).lower()\n if command_arg in command_handlers and command_arg not in COMMAND_DESCRIPTIONS:\n await message.channel.send(\n \"Shhhhhh, that's a secret command!\"\n )\n elif command_arg in COMMAND_DESCRIPTIONS:\n help_str = f\"Here's what you need to know about the `{command_arg}` command!\\n\\n```\" + \\\n COMMAND_DESCRIPTIONS[command_arg] + \"```\"\n await message.channel.send(help_str)\n else:\n await message.channel.send(\"I'm sorry, I don't know that command! ^^'\")\n\n\nasync def hi_command(message, command_arg):\n msg = Data.phrases.get_greeting_phrase()\n if random.random() < .35:\n msg += '\\n\\n' + Data.images.get_greeting_image()\n await message.channel.send(msg)\n\n\nasync def dm_command(message, command_arg):\n await User.send_dm(message.author.id, Data.phrases.get_dm_message())\n\n\nasync def timer_command(message, command_arg):\n timer_name = await prompt(message.author.id, message.channel, \"What is the timer for?\")\n if timer_name is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set a timer then ask me again!\")\n return\n if timer_name.lower() in [x.lower() for x in DB.get_timers(message.author.id).keys()]:\n await message.channel.send(\"You already have a timer with that name! Check your existing timers with \\\"!ayu list timers\\\"\")\n return\n\n timer_args = await prompt(message.author.id, message.channel, \"How soon do you want the timer to go off? For example, \\\"in 5 hours and 30 min\\\"\")\n if timer_args is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set a timer then ask me again!\")\n return\n\n if timer_args.strip().startswith('in '):\n timer_args = timer_args.strip()[3:]\n timer_args = timer_args.replace('and', '').replace(',', '')\n timer_args = remove_all_punctuation(timer_args).split()\n if len(timer_args) % 2 != 0:\n raise RuntimeError('Timer args not divisible by 2')\n\n i = 0\n delta = timedelta()\n for _ in range(len(timer_args) // 2):\n val = int(timer_args[i])\n denom = timer_args[i + 1].lower()\n i += 2\n if denom in ['week', 'weeks', 'wks']:\n delta += timedelta(weeks=val)\n elif denom in ['day', 'days']:\n delta += timedelta(days=val)\n elif denom in ['hour', 'hours', 'hr', 'hrs']:\n delta += timedelta(hours=val)\n elif denom in ['minute', 'minutes', 'min', 'mins']:\n delta += timedelta(minutes=val)\n elif denom in ['second', 'seconds', 'sec', 'secs']:\n delta += timedelta(seconds=val)\n end = time.time() + delta.total_seconds()\n\n await DB.add_timer(message.author.id, timer_name, end)\n remaining_time_str = seconds_to_string(round(end - time.time()))\n await message.channel.send(f\"OK, I'll tell you to {uncapitalize(timer_name)} in {remaining_time_str}!\")\n\n\nasync def list_timers_command(message, command_arg):\n timers = DB.get_timers(message.author.id)\n if len(timers) == 0:\n await message.channel.send(\"You don't have any timers right now... But you could make some! Say `!ayu help timer` to find out how!\")\n else:\n msg = ''\n for timer_name, timer_end in timers.items():\n remaining_time = timer_end - time.time()\n if remaining_time <= 0:\n msg += f'{timer_name} right now!\\n'\n else:\n remaining_time_str = seconds_to_string(remaining_time)\n msg += f'{capitalize(timer_name)} in {remaining_time_str}\\n'\n msg = msg.strip()\n await message.channel.send(f\"Here's all of your timers!\\n```{msg}```\")\n\n\nasync def delete_timer_command(message, command_arg):\n await list_timers_command(message, None)\n random_timer_name = random.choice(list(DB.get_timers(message.author.id).keys()))\n prompt_str = f\"Which timer would you like to delete? For example, \\\"{random_timer_name}\\\"\"\n timer_name = await prompt(message.author.id, message.channel, prompt_str)\n if timer_name is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set a timer then ask me again!\")\n return\n if timer_name.lower() not in [x.lower() for x in DB.get_timers(message.author.id)]:\n await message.channel.send(f\"You don't have a timer for that! Check your current timers with `!ayu list timers`\")\n else:\n await DB.delete_timer(message.author.id, timer_name)\n await message.channel.send(f\"Ok, I'll forget about that timer :)\")\n\n\nasync def alarm_command(message, command_arg):\n alarm_name = await prompt(message.author.id, message.channel, \"What is the alarm for?\")\n if alarm_name is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set an alarm then ask me again!\")\n return\n if alarm_name.lower() in [x.lower() for x in DB.get_alarms(message.author.id).keys()]:\n await message.channel.send(\"You already have an alarm with that name! Check your existing alarms with \\\"!ayu list alarms\\\"\")\n return\n\n times = await prompt(message.author.id, message.channel, \"What times do you want the alarm to go off? (for example, \\\"10 AM and 5:30 PM\\\")\")\n if times is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set an alarm then ask me again!\")\n return\n\n if times.strip().startswith('at '):\n times = times.strip()[3:]\n time_segments = times.replace('and', '').replace(',', '').split()\n\n if len(time_segments) % 2 != 0:\n raise RuntimeError('Time args not divisible by 2')\n\n normalized_times = []\n i = 0\n for _ in range(len(time_segments) // 2):\n hours, mins = str_to_time(time_segments[i], time_segments[i + 1])\n normalized_times.append((hours, mins))\n i += 2\n\n if DB.get_utc_time_offset_mins(message.author.id) is None:\n offset_mins = await get_utc_offset_mins(message.author.id, message.channel, message.created_at)\n await DB.set_utc_time_offset_mins(message.author.id, offset_mins)\n else:\n local_time = get_local_time_from_offset(DB.get_utc_time_offset_mins(message.author.id))\n confirmed = await get_yes_no(\n message.author.id,\n message.channel,\n f\"Based on what I know, I think your local time is {get_formatted_datetime(local_time)}. Is that right?\")\n if confirmed is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set an alarm then ask me again!\")\n return\n if not confirmed:\n offset_mins = await get_utc_offset_mins(message.author.id, message.channel, message.created_at)\n await DB.set_utc_time_offset_mins(message.author.id, offset_mins)\n\n days = await get_menu_selections(\n message.author.id,\n message.channel,\n \"What days should the alarm go off? Select the numbers corresponding\\n\"\n \"to the days you want, then select the checkmark when you're done!\",\n Days.ordered_days())\n\n if days is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set an alarm then ask me again!\")\n return\n\n # Convert to ints\n days = [Days.str_to_int(x) for x in days]\n\n alarm_data = {'times': normalized_times, 'days': days, 'created_at': datetime.datetime.utcnow()}\n\n confirmed = await get_yes_no(\n message.author.id,\n message.channel,\n \"I'm setting an alarm for you to \" +\n get_alarm_description(uncapitalize(alarm_name), days, normalized_times) +\n \"! Does that look right?\")\n\n if confirmed is None:\n await message.channel.send(\"I got tired of waiting, but if you want to set an alarm then ask me again!\")\n elif not confirmed:\n await message.channel.send(\"Ok, if you still want to set an alarm then ask me again!\")\n else:\n await message.channel.send(\" All right, you're all set!\")\n await DB.add_alarm(message.author.id, alarm_name, alarm_data)\n\n\nasync def delete_alarm_command(message, command_arg):\n await list_alarms_command(message, None)\n with ConvoSubscription(message.author.id, message.channel.id) as queue:\n random_alarm_name = random.choice(list(DB.get_alarms(message.author.id).keys()))\n await message.channel.send(f\"Which alarm would you like to delete? For example, \\\"{random_alarm_name}\\\"\")\n alarm_name = await get_next_response(queue)\n if alarm_name.lower() not in [x.lower() for x in DB.get_alarms(message.author.id)]:\n await message.channel.send(f\"You don't have an alarm for that! Check your current alarms with `!ayu list alarms`\")\n else:\n await DB.delete_alarm(message.author.id, alarm_name)\n await message.channel.send(f\"Ok, I'll forget about that alarm :)\")\n\n\nasync def list_alarms_command(message, command_arg):\n alarms = DB.get_alarms(message.author.id)\n if len(alarms) == 0:\n await message.channel.send(\"You don't have any alarms right now... But you could set some! Say `!ayu help alarm` to find out how!\")\n else:\n msg = \"Here's the alarms I'm keeping for you!```\"\n for alarm_name, alarm_data in alarms.items():\n msg += '\\n' + get_alarm_description(capitalize(alarm_name), alarm_data['days'], alarm_data['times'])\n msg += '```'\n await message.channel.send(msg)\n\n\nasync def restart_command(message, command_arg):\n await message.channel.send('Reloading resources...')\n Data.reload_all()\n await message.channel.send('Finished reloading resources!')\n\n\nasync def admin_help(message, command_arg):\n normal_commands = ''\n for key in sorted(list(command_handlers.keys())):\n normal_commands += key + '\\n'\n normal_commands = normal_commands.rstrip()\n\n admin_commands = ''\n for key in sorted(list(admin_command_handlers.keys())):\n admin_commands += key + '\\n'\n admin_commands = admin_commands.rstrip()\n\n await message.channel.send(\n 'Available normal commands:'\n f'```\\n{normal_commands}``` \\n' # Leading newline needed to avoid losing the first line for some reason\n 'Available admin commands:'\n f'```\\n{admin_commands}```'\n )\n\ncommand_handlers = {\n 'ping': ping_command,\n 'help': help_command,\n 'dm': dm_command,\n 'timer': timer_command,\n 'delete': {\n 'timer': delete_timer_command,\n 'alarm': delete_alarm_command\n },\n 'alarm': alarm_command,\n 'list': {\n 'timers': list_timers_command,\n 'alarms': list_alarms_command\n },\n 'hi': hi_command,\n 'hello': hi_command,\n 'hey': hi_command,\n 'yo': hi_command,\n}\n\nadmin_command_handlers = {\n 'reload': restart_command,\n 'admin': admin_help\n}\n\n\nasync def handle_command(message):\n\n command = message.content.split('!ayu', maxsplit=1)[1].strip()\n command_arg = None\n if len(command) == 0:\n await help_command(message, command_arg)\n else:\n command_segments = command.split(maxsplit=1)\n first_word = remove_trailing_punctuation(command_segments[0]).lower()\n if len(command_segments) > 1:\n command_arg = command_segments[1]\n\n if first_word in admin_command_handlers and message.author.id == Data.config.owner_user_id:\n await admin_command_handlers[first_word](message, command_arg)\n elif first_word in command_handlers:\n try:\n # Handle nested commands\n val = command_handlers[first_word]\n while isinstance(val, dict):\n if ' ' in command_arg:\n next_index, command_arg = command_arg.split(' ', maxsplit=1)\n next_index = next_index.strip()\n command_arg = command_arg.strip()\n else:\n next_index = command_arg\n command_arg = None\n val = val[next_index]\n except:\n await message.channel.send(\n \"Sorry, I don't know how to help with that ^^' \"\n \"if you want to know what I can do, simply type `!ayu`\")\n else:\n try:\n await val(message, command_arg)\n except Exception:\n user = await User.get_user(message.author.id)\n await client.get_channel(Data.config.debug_channel_id).send(\n f'ERROR: Failed while processing command `{message.content}` from user {user}: ```{traceback.format_exc()}```')\n await message.channel.send(\n \"I'm sorry, something went wrong! Double-check what you typed and try again?\")\n else:\n await message.channel.send(\n \"Sorry, I don't know how to help with that ^^' \"\n \"if you want to know what I can do, simply type `!ayu`\")\n","sub_path":"handlers/command_handler.py","file_name":"command_handler.py","file_ext":"py","file_size_in_byte":15517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"216130093","text":"# 题目描述:\r\n# 给定一个n个整数的数组nums和一个目标值target,找出数组中三个数,使它们的和与target最相近\r\n# 返回他们的和\r\nclass Solution:\r\n def threeSum(self, nums, target):\r\n nums.sort()\r\n # 双指针模板\r\n i = 0 # 指向头\r\n j = len(nums) - 1\r\n minnum = 2**31 - 1\r\n number = 0\r\n print(nums)\r\n while (i < j):\r\n # 先确定 i,j,然后在k里面挑出一个最接近的\r\n for k in range(i + 1, j):\r\n now = nums[i] + nums[j] + nums[k]\r\n # print(now)\r\n # print (now - target)\r\n # print(now - target)\r\n # print(minnum)\r\n if abs(now - target) < minnum:\r\n minnum = abs(now - target)\r\n number = now\r\n print(number)\r\n if number < target:\r\n i += 1\r\n elif number > target:\r\n j -= 1\r\n else:\r\n return number\r\n return number\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # nums = [-1, 2, 1, -4]\r\n nums = [4, 0, 5, -5, 3, 3, 0, -4, -5]\r\n target = -2\r\n print(Solution().threeSum(nums, target))\r\n\r\n\r\n# 要点:这样遍历会少一些样本,多一些重复的样本。应该是二分放在移动点的里面\r\n","sub_path":"Leetcode_math_double/threeSum_1.py","file_name":"threeSum_1.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"354255874","text":"import sqlite3\nfrom datetime import datetime\nfrom checkin_inventory import var\n\ndef device_checkout(cursor, employee_dict):\n \n try:\n\n for index, device in enumerate(employee_dict['devices']):\n\n if is_checked_in(cursor, employee_dict):\n\n cursor.execute(''' UPDATE timesheet\n SET check_out = :check_in,\n WHERE id = :last_entry ''',\n {'check_out': str(datetime.datetime.now()),\n 'last_entry': device['last_entry']\n }\n )\n\n else:\n \n cursor.execute(''' INSERT INTO timesheet\n (employee_id, \n device_id, \n check_out)\n VALUES\n (:employee_id,\n :device_id, \n :check_out)\n ''',\n {\n 'employee_id':employee_dict.get('employee').get('id'), \n 'device_id': device['id'],\n 'check_out': str(datetime.now())\n }\n )\n\n except:\n raise\n\ndef device_checkin(cursor, employee_dict):\n \n try:\n\n for index, device in enumerate(employee_dict['devices']):\n\n if is_checked_out(cursor, employee_dict):\n\n cursor.execute(''' UPDATE timesheet\n SET check_in = :check_in,\n WHERE id = :last_entry ''',\n {'check_in': str(datetime.datetime.now()),\n 'last_entry': device['last_entry']}\n )\n\n else:\n \n cursor.execute('''\n INSERT INTO timesheet\n (employee_id, \n device_id, \n check_in)\n VALUES\n (:employee_id,\n :device_id, \n :check_in)\n ''',\n {\n 'employee_id':employee_dict.get('employee').get('id'), \n 'device_id': device['id'],\n 'check_in': str(datetime.now())\n }\n )\n\n except:\n raise\n\ndef is_checked_in(cursor, employee_dict):\n \n try: \n\n for index, device in enumerate(employee_dict['devices']):\n \n cursor.execute('''\n SELECT * FROM timesheet \n WHERE employee_id = :employee_id AND device_id = :device_id\n ''',\n\n {\n 'employee_id':employee_dict.get('employee').get('id'),\n 'device_id':device['id']\n }\n )\n\n try:\n\n device['last_entry'] = cursor.fetchall()[-1][0]\n last_entry = cursor.fetchall()[-1]\n\n except IndexError:\n continue\n\n if last_entry[-1] and not last_entry[-2]:\n\n return employee_dict\n \n except:\n raise\n\ndef is_checked_out(cursor, employee_dict):\n\n try:\n for index, device in enumerate(employee_dict['devices']):\n \n cursor.execute('''\n SELECT * FROM timesheet \n WHERE employee_id = :employee_id AND device_id = :device_id\n ''',\n\n {'employee_id':employee_dict.get('employee').get('id'),\n 'device_id':device['id']\n }\n )\n\n try: \n device['last_entry'] = cursor.fetchall()[-1][0]\n last_entry = cursor.fetchall()[-1]\n\n except IndexError:\n continue\n\n try: \n if last_entry[-2] and not last_entry[-1]:\n return last_entry[0]\n\n except IndexError:\n continue\n\n except:\n raise\n\ndef device_lookup(cursor, employee_dict):\n\n try:\n\n for index, device in enumerate(employee_dict['devices']):\n\n cursor.execute('''\n SELECT id FROM device WHERE serial = :serial OR asset_tag = :asset_tag\n ''', \n device\n )\n \n employee_dict['devices'][index]['id'] = cursor.fetchone()[0]\n\n return employee_dict\n\n except:\n raise\n\ndef device_entry(cursor, employee_dict):\n\n try:\n\n for index, device in enumerate(employee_dict['devices']):\n\n cursor.execute('''\n INSERT INTO device(model, serial, asset_tag, employee_id)\n SELECT :model, :serial, :asset_tag, :employee_id\n WHERE NOT EXISTS(\n SELECT 1 FROM device WHERE model = :model AND serial = :serial AND asset_tag = :asset_tag \n )''',\n {\n 'model':device.get('model'), \n 'serial':device.get('serial'), \n 'asset_tag':device.get('asset_tag'), \n 'employee_id':employee_dict.get('employee').get('id')\n }\n )\n\n return employee_dict\n\n except:\n raise\n\ndef list_employees(cursor):\n\n try:\n \n for row in cursor.execute('''SELECT * FROM employee ORDER BY last_name'''):\n print(row)\n\n except: \n raise\n\ndef employee_lookup(cursor, employee_dict):\n\n try:\n \n cursor.execute('''\n SELECT id FROM employee WHERE name = :first_name AND last_name = :last_name\n ''', \n employee_dict['employee']\n )\n\n employee_dict['employee']['id'] = cursor.fetchone()[0]\n\n return employee_dict\n\n except: \n raise\n\ndef employee_entry(cursor, employee_dict):\n\n try:\n cursor.execute('''\n INSERT INTO employee(name, last_name, email, phone)\n SELECT :first_name, :last_name, :email, :phone \n WHERE NOT EXISTS(\n SELECT 1 FROM employee WHERE name = :first_name AND last_name = :last_name AND email = :email\n )''',\n employee_dict['employee']\n )\n\n except:\n raise\n\ndef db_setup(cursor):\n\n try:\n cursor.executescript('''\n CREATE TABLE \n IF NOT EXISTS employee (\n id INTEGER PRIMARY KEY AUTOINCREMENT, \n name TEXT,\n last_name TEXT,\n email TEXT,\n phone TEXT\n );\n\n CREATE TABLE \n IF NOT EXISTS device (\n id INTEGER PRIMARY KEY AUTOINCREMENT, \n model TEXT, \n serial TEXT, \n asset_tag TEXT,\n employee_id INTEGER,\n FOREIGN KEY (employee_id) REFERENCES employee(id)\n );\n\n CREATE TABLE \n IF NOT EXISTS timesheet (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n employee_id INTEGER,\n device_id INTEGER,\n check_in TEXT,\n check_out TEXT,\n FOREIGN KEY (employee_id) REFERENCES employee(id),\n FOREIGN KEY (device_id) REFERENCES device(id)\n )\n ''')\n\n except:\n raise\n\ndef db_connect(sqlite_file):\n\n try:\n \n db = sqlite3.connect(sqlite_file)\n cursor = db.cursor()\n\n return db, cursor\n\n except:\n raise\n\ndef main():\n\n db, cursor = db_connect('db\\database.sqlite')\n\n with db:\n db_setup(cursor)\n\n list_employees(cursor)\n \nif __name__ == '__main__':\n main()\n","sub_path":"byod_checkin/timesheet.py","file_name":"timesheet.py","file_ext":"py","file_size_in_byte":7544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"73535741","text":"import sqlite3\r\n\r\nclass dbmanager:\r\n\r\n def file_info_insert(self, file_info, c, volume_info):\r\n #for info in file_info:\r\n c.executemany(\"INSERT INTO \"+volume_info[4]+\" VALUES(?, ?, ?, ?, ?, ?, ? \\\r\n , ?, ?, ?, ?, ?, ?, ?\\\r\n , ?, ?, ?, ?, ?, ?, ?);\", file_info)#(info,))\r\n\r\n def __init__(self, file_info, volume_info):\r\n conn=sqlite3.connect(\"apfs.db\", isolation_level=None)\r\n c=conn.cursor()\r\n c.execute(\"CREATE TABLE \"+volume_info[4]+\" \\\r\n (ParentFolderID text, \\\r\n FileID text PRIMARY KEY, \\\r\n CreatedDate text, \\\r\n LastWrittenDate text, \\\r\n iNodeChangeDate text, \\\r\n LastAccessDate text, \\\r\n HardlinktoFile text, \\\r\n OwnPermission text, \\\r\n GroupPermission text, \\\r\n NameLength1 text, \\\r\n NameLength text, \\\r\n NameLength2 text, \\\r\n Name text, \\\r\n FileSize text, \\\r\n CalculatedinBlockSize text, \\\r\n Length text, \\\r\n HardLinkCount text, \\\r\n FileOffset text, \\\r\n BlockCount text, \\\r\n NodeID text, \\\r\n CreatedDate2 text)\")\r\n\r\n\r\n c.execute(\"INSERT INTO \"+volume_info[4]+\" (FileID, Name) VALUES('0x1', '\"+volume_info[4]+\"');\")\r\n #conn.commit()\r\n\r\n self.file_info_insert(file_info, c, volume_info)\r\n conn.close()","sub_path":"dbmanager.py","file_name":"dbmanager.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"394231277","text":"from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Flatten, Reshape\nfrom keras.callbacks.callbacks import EarlyStopping\nfrom keras.models import Model, load_model\nfrom keras import backend as K\nfrom keras.callbacks import TensorBoard\nimport numpy as np\n\nfrom ..data import loaddata\n\nmodel_weight_name = f\"weights/{__file__}_weights.h5\"\n\n## Encoder\ndef getEncoder():\n input_img = Input(shape=(32, 32, 1))\n x = Conv2D(4, (3, 3), activation='relu', padding='same')(input_img)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Flatten()(x)\n encoded = Dense(1024, activation=\"relu\")(x)\n\n encoder = Model(input_img, encoded)\n encoder.name = \"encoder\"\n return encoder\n\ndef getDecoder():\n ## Decoder\n input_encoded = Input(shape=(1024,))\n x = Dense(1024, activation=\"relu\")(input_encoded)\n x = Reshape((16,16,4))(x)\n x = UpSampling2D((2, 2))(x)\n decoded = Conv2D(1, (3, 3), activation='relu', padding='same')(x)\n decoder = Model(input_encoded, decoded)\n decoder.name = \"decoder\"\n return decoder\n\ndef getAutoEncoder(encoder: Model, decoder: Model):\n ## Connect Encoder and Decoder\n ae_in = Input(shape=(32, 32, 1))\n ae_out = decoder(encoder(ae_in))\n autoencoder = Model(ae_in, ae_out)\n autoencoder.name = \"autoencoder\"\n autoencoder.compile(optimizer='adadelta', loss='mean_squared_error')\n return autoencoder\n\ndef trainAutoEncoder(autoencoder: Model):\n\n try:\n autoencoder.load_weights(model_weight_name)\n except (OSError, ValueError):\n x,_ = loaddata.loadImages()\n autoencoder.fit(x, x,\n epochs=100,\n batch_size=128,\n shuffle=True,\n validation_split=0.2,\n callbacks=[EarlyStopping(patience=20), TensorBoard(log_dir='/tmp/autoencoder')])\n autoencoder.save_weights(model_weight_name)\n return autoencoder","sub_path":"ml/cnnautoencoder.py","file_name":"cnnautoencoder.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"605996519","text":"# -*- coding: utf-8 -*-\r\n'''\r\nCreated on 18 janv. 2018\r\n\r\n@author: filipix\r\n'''\r\nimport os\r\nimport sys\r\nimport ast\r\nfrom pathlib import Path\r\nimport uuid\r\nimport random as rn\r\n\r\nimport itertools\r\nfrom abc import abstractmethod\r\n\r\nfrom xlrd import open_workbook\r\n\r\nimport numpy as np\r\nimport pandas as pd \r\n\r\nimport core.dataset as dts\r\nimport core.result as rslt\r\nfrom core.model_factory import ModelFactory\r\nfrom core.generator_factory import GeneratorFactory \r\nfrom core.loss_functions import loss_functions_map\r\nfrom core.metrics import metrics_functions_map\r\nimport tensorflow as tf\r\n\r\nfrom sklearn.utils import class_weight\r\nfrom sklearn.metrics import silhouette_score, f1_score\r\n\r\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\r\nfrom keras.models import load_model\r\nfrom keras.utils import plot_model\r\n\r\nimport core.callbacks as ccalb\r\nfrom core.callbacks import reduceLR_functions_map\r\nfrom keras import backend as K\r\n\r\nfrom keras.layers import (\r\n GlobalAveragePooling3D, GlobalAveragePooling2D,\r\n GlobalMaxPooling3D, GlobalMaxPooling2D,\r\n Concatenate,\r\n BatchNormalization,\r\n Input,\r\n AlphaDropout,\r\n Dropout,\r\n Activation,\r\n Conv3D, Conv2D,\r\n Flatten ,\r\n Dense\r\n )\r\nfrom keras.models import Model\r\nfrom keras.optimizers import Adam, SGD, Adamax\r\n#------------------------------------------------------------------------------\r\nclass HyperP(object):\r\n\r\n def __init__(self, hyperp=None):\r\n if hyperp is None:\r\n self.hyperp = HyperP.get_default()\r\n else:\r\n self.hyperp = hyperp\r\n\r\n @staticmethod\r\n def get_default():\r\n return {\r\n 'General/reproductibility' : True,\r\n 'General/seed' : 1234,\r\n 'General/memory_growth' : False,\r\n 'Data/with_features': True,\r\n 'Data/zification' : False,\r\n 'Data/equalise_classes' : False,\r\n 'Data/features_insertion_level' : 2, ## features insertion level is relative to number of top layers ! 0 = before the first dense layer. \r\n # if insertion_level = top_layers or NONE, features are inserted just before the output layer\r\n 'Data/with_images': True,\r\n 'Data/multilabel': False,\r\n 'Data/normalisation': dts.NormalisationEnum.NONE,\r\n 'Data/categorical': True,\r\n 'Data/filter_channels': None,\r\n 'Data/filter_features': None, # features à conserver si with_features=True\r\n 'Data/generated' : False, # False/None, or a string representing the type of generator as in core.generator_factory\r\n 'Data/generator/weight': 'tnormal',\r\n 'Data/generator/lowerbound': 0.2,\r\n 'Data/generator/upperbound': 0.8,\r\n 'Data/generator/mean':0.5,\r\n 'Data/generator/std':0.1, \r\n 'Data/generator/use_multiprocessing' : False,\r\n 'Data/generator/workers' : 1,\r\n 'Model/plot_model': False,\r\n 'Model/reset' : True,\r\n 'Model/activation': 'relu',\r\n 'Model/classname': 'CNN',\r\n 'Model/kernel_nb_init': 32,\r\n 'Model/block_nb' : 5,\r\n 'Model/conv_by_block' : 2,\r\n 'Model/cnn_dropout': None,\r\n 'Model/separable_first_layer' : False,\r\n 'Model/FineTuning' : False,\r\n 'Model/final_image_layer': 'Flatten',\r\n 'Model/learning_rate': 0.0001,\r\n 'Model/top_dropout': 0.33,\r\n 'Model/top_layers': 2,\r\n 'Model/top_unit': 512, \r\n 'Model/last_activation' : 'softmax',\r\n 'Model/optimizer' : 'Adam',\r\n 'Model/loss' : 'categorical_crossentropy',\r\n 'Model/metrics': ['accuracy'],\r\n 'Run/weigth_balanced_classes' : False,\r\n 'Run/tensorboard': False,\r\n 'Run/monitor' : 'val_loss',\r\n 'Run/monitor_mode' : 'auto',\r\n 'Run/patience': 16,\r\n 'Run/verbose': 2,\r\n 'Run/gen_steps_per_epoch' : 64,\r\n 'Run/epochs' : 1000,\r\n 'Run/reduceLR' : 'ReduceLROnPlateauWithReload',\r\n 'Run/reduceLR_factor' : 0.5,\r\n 'Run/reduceLR_patience_ratio' : 0.1,\r\n 'Run/batch_size': 64\r\n }\r\n @staticmethod\r\n def from_excel(filepath):\r\n '''\r\n Get a hyperp definition table from excel :\r\n - only the first sheet is read\r\n - The hyperparameter name is on the first line\r\n - subsequent lines are values for hyperparameters\r\n :filepath: string - the path of the excel file\r\n :return: list - a list of hyperparameter (dict)\r\n\r\n note : to get adequate type casting each hyper paramter value goes \r\n through Python eval(), side effects may occurs if the value is interpretable\r\n by the interpreter. That may be a good thing,... probably not.\r\n '''\r\n\r\n def parse_xlsx(filepath):\r\n '''\r\n Generator tp get the content of the excel file containing hyperparameters\r\n :filepath: string - the path of the excel file\r\n :return: list - a list of hyperparameter (dict)\r\n '''\r\n workbook = open_workbook(filepath)\r\n sheets = workbook.sheet_names()\r\n active_sheet = workbook.sheet_by_name(sheets[0])\r\n num_rows = active_sheet.nrows\r\n num_cols = active_sheet.ncols\r\n header = [active_sheet.cell_value(0, cell) for cell in range(num_cols)]\r\n for row_idx in range(1, num_rows):\r\n row_cell = [active_sheet.cell_value(row_idx, col_idx) for col_idx in range(num_cols)]\r\n yield dict(zip(header, row_cell))\r\n \r\n lhyperp = []\r\n for di in parse_xlsx(filepath) : \r\n do = dict()\r\n for key, value in di.items(): \r\n try:\r\n # test for boolean\r\n if value == 'true':\r\n value = True\r\n elif value == 'false':\r\n value = False\r\n elif value == '?':\r\n value = None\r\n elif value == 'NaN':\r\n value = None\r\n elif isinstance(value, (int, float)):\r\n value = float(value)\r\n if value.is_integer():\r\n value = int(value)\r\n else:\r\n value = ast.literal_eval(value)\r\n except:\r\n # the value will stay as a string\r\n pass\r\n do[key] = value\r\n lhyperp.append(do)\r\n return lhyperp\r\n \r\n @staticmethod\r\n def from_knime(table):\r\n '''\r\n Get a hyperp definition table from knime where :\r\n - the RowId is the name of the hyper parameter\r\n - the first column are the values for the hyper parameter\r\n note : to get adequate type casting each hyper paramter value goes \r\n through Python eval(), side effects may occurs if the value is interpretable\r\n by the interpreter. That may be a good thing,... probably not.\r\n '''\r\n di = table.T.to_dict('record')[0]\r\n do = dict()\r\n for key, value in di.items(): \r\n try:\r\n # test for boolean\r\n if value == 'true':\r\n value = True\r\n elif value == 'false':\r\n value = False\r\n elif value == '?':\r\n value = None\r\n elif value == 'NaN':\r\n value = None\r\n elif isinstance(value, (int, float)):\r\n value = float(value)\r\n if value.is_integer():\r\n value = int(value)\r\n else:\r\n value = ast.literal_eval(value)\r\n except:\r\n # the value will stay as a string\r\n pass\r\n do[key] = value\r\n return do\r\n \r\n @staticmethod\r\n def get_default_set():\r\n d = {}\r\n for key, value in HyperP.get_default().items():\r\n d[key] = [value]\r\n return d \r\n\r\n @staticmethod\r\n def get_set_cartesian_product(hyperp_set):\r\n return [dict(zip(hyperp_set, x)) for x in itertools.product(*hyperp_set.values())]\r\n\r\n#------------------------------------------------------------------------------\r\nclass PredictiveModel(object):\r\n\r\n def __init__(self,\r\n rundir='./',\r\n logdir='./',\r\n hyperp=HyperP.get_default()):\r\n self.rundir = rundir\r\n self.logdir = logdir\r\n \r\n self.hyperp = HyperP.get_default()\r\n self.hyperp.update(hyperp)\r\n\r\n self.runName = \"r\"\r\n self.model = None\r\n self.history = None\r\n self.custom_objects = {}\r\n\r\n def _callbacks(self, weightsfilepath = None, finetuning = False):\r\n if weightsfilepath is None:\r\n weightsfilepath = os.path.join(self.rundir, 'weights-' + self.runName + '.hdf5')\r\n if finetuning:\r\n monitored = self.hyperp['Run/FineTuning/monitor']\r\n monitoredmode = self.hyperp['Run/FineTuning/monitor_mode']\r\n else:\r\n monitored = self.hyperp['Run/monitor']\r\n monitoredmode = self.hyperp['Run/monitor_mode']\r\n \r\n msave = ModelCheckpoint(weightsfilepath,\r\n monitor=monitored, \r\n mode=monitoredmode, \r\n save_best_only=True, \r\n save_weights_only=True)\r\n es = EarlyStopping(monitor=monitored, \r\n mode=monitoredmode, \r\n patience=self.hyperp['Run/patience'], \r\n verbose=1, \r\n min_delta=1e-4)\r\n\r\n # Legacy LR strategy\r\n if self.hyperp.get('Run/myReduceLR') is not None:\r\n if self.hyperp['Run/myReduceLR']:\r\n self.hyperp['Run/reduceLR'] = 'ReduceLROnPlateauWithReload'\r\n else:\r\n self.hyperp['Run/reduceLR'] = 'ReduceLROnPlateau'\r\n \r\n reduce_strategy = self.hyperp.get('Run/reduceLR')\r\n if reduce_strategy == 'ReduceLROnPlateauWithReload': \r\n lr = ccalb.ReduceLROnPlateauWithReload(weightsfilepath, monitor=monitored,\r\n mode=monitoredmode, \r\n factor=self.hyperp['Run/reduceLR_factor'],\r\n patience=max(1, self.hyperp['Run/patience'] * self.hyperp['Run/reduceLR_patience_ratio']),\r\n verbose=1, \r\n min_lr=1e-7)\r\n elif reduce_strategy in reduceLR_functions_map.keys():\r\n reduce=reduceLR_functions_map[reduce_strategy]\r\n if self.hyperp.get('Run/reduceLR/param') is None:\r\n lr = reduce()\r\n else:\r\n lr = reduce(**self.hyperp.get('Run/reduceLR/param'))\r\n else:\r\n self.hyperp['Run/reduceLR'] = 'ReduceLROnPlateau'\r\n lr = ReduceLROnPlateau(monitor=monitored,\r\n mode=monitoredmode, \r\n factor=self.hyperp['Run/reduceLR_factor'],\r\n patience=max(1, self.hyperp['Run/patience'] * self.hyperp['Run/reduceLR_patience_ratio']),\r\n verbose=1, \r\n min_lr=1e-7)\r\n callb = [msave, es, lr]\r\n if self.hyperp.get('Run/plotlosses') :\r\n callb.append(ccalb.PlotLosses(monitored, monitoredmode, finetuning))\r\n if self.hyperp.get('Run/tensorboard') :\r\n callb.append(TensorBoard(log_dir=os.path.join(self.logdir, self.runName), \r\n write_graph=True,\r\n write_grads=False, \r\n write_images=False, \r\n batch_size=self.hyperp['Run/batch_size'],\r\n histogram_freq=0,\r\n update_freq='epoch')\r\n )\r\n\r\n return callb\r\n\r\n @staticmethod\r\n def from_h5(filepath, \r\n classname = None,\r\n rundir='./',\r\n logdir='./',\r\n custom_objects = None,\r\n factory = ModelFactory(),\r\n hyperp=HyperP.get_default()):\r\n '''\r\n Create a model from a previously saved file.\r\n '''\r\n modelObj = factory.makeModel(classname, rundir=rundir, logdir=logdir, hyperp=hyperp)\r\n if custom_objects is None:\r\n modelObj.model = load_model(filepath, custom_objects={**loss_functions_map, **metrics_functions_map})\r\n else:\r\n modelObj.model = load_model(filepath, custom_objects=custom_objects)\r\n return modelObj\r\n \r\n def build(self, shape_image=(10, 10, 1), shape_features = [1]):\r\n '''\r\n Method for building the model : may be overrided\r\n '''\r\n return self.build_top_layers(shape_image, shape_features)\r\n\r\n @abstractmethod\r\n def build_image_layers(self):\r\n '''\r\n Abstract method for building the image analysis layers\r\n Must return a function that takes a input layer and return a layer\r\n '''\r\n raise NotImplementedError(f'build_image_layers method not implemented for :{ type(self).__name__}') \r\n \r\n def build_feature_layers(self, shape = None):\r\n '''\r\n Basic method for building the feature analysis layers\r\n '''\r\n def f(layer):\r\n return BatchNormalization(scale=False)(layer)\r\n \r\n return f\r\n \r\n def build_top_layers(self, shape_image=(10, 10, 1), shape_features = (1)):\r\n '''\r\n Generic method for Dense top layers : call self.build_image_layers(....)\r\n '''\r\n if (self.hyperp.get('Data/with_images')):\r\n input_1 = Input(shape=shape_image, name=\"image\")\r\n \r\n image_layer = self.build_image_layers()(input_1)\r\n\r\n if (self.hyperp['Model/final_image_layer'] == 'GlobalAveragePooling3D'):\r\n image_layer = GlobalAveragePooling3D()(image_layer)\r\n elif (self.hyperp['Model/final_image_layer'] == 'GlobalMaxPooling3D') :\r\n image_layer = GlobalMaxPooling3D()(image_layer)\r\n elif (self.hyperp['Model/final_image_layer'] == 'GlobalAveragePooling2D'):\r\n image_layer = GlobalAveragePooling2D()(image_layer)\r\n elif (self.hyperp['Model/final_image_layer'] == 'GlobalMaxPooling2D') :\r\n image_layer = GlobalMaxPooling2D()(image_layer)\r\n elif (self.hyperp['Model/final_image_layer'] == 'Conv3DFlatten') :\r\n if self.hyperp.get('Data/nb_category'):\r\n image_layer = Conv3D(self.hyperp.get('Data/nb_category')*2, \r\n kernel_size = 1, \r\n padding='same')(image_layer)\r\n else:\r\n image_layer = Conv3D(32, kernel_size = 1, \r\n padding='same')(image_layer)\r\n image_layer = BatchNormalization()(image_layer)\r\n image_layer = Activation(self.hyperp['Model/activation'])(image_layer)\r\n image_layer = Flatten() (image_layer)\r\n elif (self.hyperp['Model/final_image_layer'] == 'Conv2DFlatten') :\r\n if self.hyperp.get('Data/nb_category'):\r\n image_layer = Conv2D(self.hyperp.get('Data/nb_category')*2, \r\n kernel_size = 1, \r\n padding='same')(image_layer)\r\n else:\r\n image_layer = Conv2D(32, kernel_size = 1, \r\n padding='same')(image_layer)\r\n image_layer = BatchNormalization()(image_layer)\r\n image_layer = Activation(self.hyperp['Model/activation'])(image_layer)\r\n image_layer = Flatten() (image_layer)\r\n else:\r\n image_layer = Flatten() (image_layer)\r\n\r\n if self.hyperp.get('Data/with_features'):\r\n input_2 = Input(shape=shape_features, name=\"features\")\r\n \r\n feature_layer = self.build_feature_layers(shape_features)(input_2)\r\n\r\n if (self.hyperp.get('Data/with_images')):\r\n local_input = [input_1, input_2] \r\n if 'Data/features_insertion_level' not in self.hyperp:\r\n # default insertion point in the top level layers : just before the final level\r\n self.hyperp['Data/features_insertion_level'] = self.hyperp['Model/top_layers']\r\n # The features layer will be inserted later\r\n layer = image_layer\r\n else:\r\n local_input = input_2\r\n # No Image data : the feature are at the bottom of the network\r\n self.hyperp['Data/features_insertion_level'] = 0\r\n layer = feature_layer\r\n\r\n elif self.hyperp.get('Data/with_images'):\r\n local_input = input_1\r\n layer = image_layer\r\n\r\n else:\r\n print('No features and no images : what should I do ? Things are not going to end well')\r\n\r\n if self.hyperp.get('Model/kernel_initializer') is not None: \r\n kernel_initializer=self.hyperp.get('Model/kernel_initializer')\r\n else:\r\n kernel_initializer='glorot_uniform'\r\n\r\n for iLayer in range(self.hyperp['Model/top_layers']):\r\n if self.hyperp.get('Data/with_features') and iLayer == self.hyperp['Data/features_insertion_level']:\r\n if self.hyperp.get('Data/with_images'):\r\n layer = Concatenate()([layer, feature_layer])\r\n else :\r\n layer = feature_layer # redondant since if no images the insertion is at the bottom... \r\n\r\n if self.hyperp.get('Model/top_BatchNormalization'):\r\n layer = Dense(self.hyperp['Model/top_unit'], \r\n kernel_initializer=kernel_initializer,\r\n use_bias=False\r\n ) (layer)\r\n layer = BatchNormalization()(layer)\r\n layer = Activation(self.hyperp['Model/activation'])(layer)\r\n else:\r\n layer = Dense(self.hyperp['Model/top_unit'], \r\n kernel_initializer=kernel_initializer,\r\n activation=self.hyperp['Model/activation']) (layer)\r\n\r\n if self.hyperp.get('Model/top_dropout') is not None:\r\n if self.hyperp['Model/activation'] == 'selu':\r\n layer = AlphaDropout(self.hyperp['Model/top_dropout']) (layer)\r\n else:\r\n layer = Dropout(self.hyperp['Model/top_dropout']) (layer)\r\n\r\n # if insertion of feature is defined too large w.r.t. the size of the top layers, features are inserted before the output layer\r\n if self.hyperp.get('Data/with_features') and iLayer < self.hyperp['Data/features_insertion_level']:\r\n layer = Concatenate()([layer, feature_layer]) \r\n\r\n if self.hyperp.get('Model/last_activation'):\r\n output = Dense(self.hyperp['Data/nb_category'], \r\n activation=self.hyperp['Model/last_activation'])(layer)\r\n else:\r\n output = Dense(self.hyperp['Data/nb_category'], \r\n activation='softmax')(layer) \r\n \r\n self.model = Model(local_input, output)\r\n \r\n return self.compile(self.model)\r\n\r\n def compile(self, model, fineTuning = None):\r\n if fineTuning is None:\r\n losskey = 'Model/loss'\r\n metrickey = 'Model/metrics'\r\n if self.hyperp.get('Model/learning_rate') is None:\r\n self.hyperp['Model/learning_rate'] = 0.01\r\n learning_rate_key = 'Model/learning_rate'\r\n else :\r\n losskey = 'Model/FineTuning/loss'\r\n metrickey = 'Model/FineTuning/metrics'\r\n if self.hyperp.get('Model/FineTuning/learning_rate') is None:\r\n self.hyperp['Model/FineTuning/learning_rate'] = 0.01\r\n learning_rate_key = 'Model/FineTuning/learning_rate'\r\n\r\n if self.hyperp.get('Model/optimizer') == 'SGD' :\r\n opt = SGD(lr=self.hyperp[learning_rate_key], \r\n decay=1e-6, momentum=0.9, nesterov=True)\r\n elif self.hyperp.get('Model/optimizer') == 'Adamax' :\r\n opt = Adamax(lr=self.hyperp[learning_rate_key], \r\n beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\r\n else:\r\n opt = Adam(lr=self.hyperp[learning_rate_key], \r\n beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\r\n\r\n \r\n if self.hyperp.get(losskey) is None :\r\n loss = self.hyperp[losskey] = 'binary_crossentropy'\r\n elif isinstance(self.hyperp[losskey], str) and self.hyperp[losskey] in loss_functions_map.keys():\r\n loss = loss_functions_map[self.hyperp[losskey]]\r\n self.custom_objects[self.hyperp[losskey]] = loss\r\n else :\r\n loss = self.hyperp[losskey] \r\n \r\n metrics = []\r\n if self.hyperp.get(metrickey) is None :\r\n metrics = self.hyperp[metrickey] = ['accuracy']\r\n else :\r\n for metric1 in self.hyperp.get(metrickey): \r\n if metric1 in metrics_functions_map.keys():\r\n self.custom_objects[metric1] = metrics_functions_map[metric1]\r\n metrics.append(metrics_functions_map[metric1])\r\n elif metric1 in loss_functions_map.keys():\r\n self.custom_objects[metric1] = loss_functions_map[metric1]\r\n metrics.append(loss_functions_map[metric1])\r\n elif metric1 == 'accuracy':\r\n metrics.append(metric1)\r\n else:\r\n metrics.append(metric1)\r\n \r\n model.compile(loss=loss, \r\n loss_weights=self.hyperp.get('Model/loss_weights'),\r\n optimizer=opt, metrics=metrics)\r\n \r\n return model\r\n\r\n def finetune(self, model):\r\n '''\r\n Typically if finetuning is needed then this function may modify the model :\r\n e.g. remove or modify last layer\r\n :return: The modified model that should be recompiled and fitted\r\n '''\r\n print('Warning : this model has not been modified for finetuning')\r\n return model\r\n \r\n def run(self, \r\n dataset,\r\n fold=None,\r\n train_size=0.8,\r\n hyperp=None\r\n ):\r\n\r\n # Setting reproductibility\r\n # Technically, a seed is always used, but it will either be randomly generated or choosed by user\r\n if not self.hyperp.get('General/reproductibility'):\r\n self.hyperp['General/seed']=rn.randint()\r\n \r\n seed = self.hyperp['General/seed'] \r\n os.environ['PYTHONHASHSEED'] = '0' \r\n np.random.seed(seed)\r\n rn.seed(seed)\r\n tf.set_random_seed(seed) \r\n\r\n if self.hyperp is None :\r\n self.hyperp = HyperP.get_default()\r\n \r\n if hyperp is not None :\r\n self.hyperp.update(hyperp)\r\n self.hyperp['learn_uuid'] = str(uuid.uuid4())\r\n self.runName = self.hyperp['learn_uuid']\r\n if hasattr(dataset, 'trainfilename'):\r\n self.hyperp['Data/trainfilename']=dataset.trainfilename\r\n if hasattr(dataset, 'testfilename'):\r\n self.hyperp['Data/testfilename']=dataset.testfilename\r\n\r\n if not self.hyperp.get('Data/generated') and (self.hyperp.get('Data/filter_features') is not None or self.hyperp.get('Data/filter_channels') is not None):\r\n run_dataset = dataset.filter(keep_channel = self.hyperp.get('Data/filter_channels') , \r\n keep_features = self.hyperp.get('Data/filter_features'))\r\n else:\r\n run_dataset = dataset\r\n \r\n if self.hyperp.get('Data/nb_category') is None:\r\n self.hyperp['Data/nb_category'] = run_dataset.nb_category\r\n \r\n if self.hyperp.get('Model/reset'):\r\n K.clear_session()\r\n \r\n # Memory Growth\r\n session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) \r\n # Does not allow memory growth by default, because performance are better without\r\n session_conf.gpu_options.allow_growth = self.hyperp['General/memory_growth'] \r\n sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\r\n K.set_session(sess) \r\n \r\n if self.hyperp.get('Data/with_features') and self.hyperp.get('Data/with_images'):\r\n self.model = self.build(shape_image = run_dataset.shape, shape_features = run_dataset.train_features[1:])\r\n elif self.hyperp.get('Data/with_images'):\r\n self.model = self.build(shape_image = run_dataset.shape, shape_features = None)\r\n elif self.hyperp.get('Data/with_features'):\r\n self.model = self.build(shape_image = None, shape_features = run_dataset.train_features[1:])\r\n else:\r\n print('No features and no images : what should I do ? Things are not going to end well') \r\n\r\n if self.hyperp.get('Model/load_weights') is not None:\r\n fname = self.hyperp.get('Model/load_weights')\r\n print(f'Loading weights from : {fname}')\r\n self.model.load_weights(fname)\r\n\r\n self.model.summary(line_length = 128)\r\n if self.hyperp.get('Model/plot_model'):\r\n plot_model(self.model, to_file=os.path.join(self.rundir, self.runName + '.png'), show_shapes = True) \r\n \r\n # put the actual model type in the hyperparameters \r\n self.hyperp['Model/classname'] = self.__class__.__name__\r\n # The name of the model file\r\n self.hyperp['Model/modelfile'] = os.path.join(self.rundir, 'model-' + self.runName + '.hdf5')\r\n self.hyperp['Model/weightsfile'] = os.path.join(self.rundir, 'weights-' + self.runName + '.hdf5')\r\n\r\n if self.hyperp.get('Run/epochs') is None:\r\n self.hyperp['Run/epochs'] = 1000\r\n \r\n if self.hyperp.get('Data/generated') :\r\n generator = GeneratorFactory.makeGen(self.hyperp.get('Data/generated'), self.hyperp)\r\n gen_iter, id_t, id_v, Xt, Xv, Yt, Yv, T, normer = run_dataset.get_generated_datasets(\r\n image_data_generator=generator,\r\n filter_channels = self.hyperp.get('Data/filter_channels'),\r\n zification = self.hyperp.get('Data/zification'),\r\n fold=fold,\r\n normalise_images=self.hyperp.get('Data/normalisation'),\r\n batch_size=self.hyperp.get('Run/batch_size'),\r\n with_features=self.hyperp.get('Data/with_features'),\r\n categorical=self.hyperp.get('Data/categorical'),\r\n equalise_classes = self.hyperp.get('Data/equalise_classes'),\r\n random_state= self.hyperp.get('General/seed'),\r\n multilabel = self.hyperp.get('Data/multilabel'))\r\n self.hyperp['Data/training_img_mean'] = normer.amean\r\n self.hyperp['Data/training_img_std'] = normer.astd\r\n self.hyperp['Data/training_img_min'] = normer.amin\r\n self.hyperp['Data/training_img_max'] = normer.amax\r\n \r\n validation_set = run_dataset.get_train_generator(id_v, \r\n filter_channels = self.hyperp.get('Data/filter_channels'),\r\n zification = self.hyperp.get('Data/zification'),\r\n class_mode = 'other',\r\n random_state= self.hyperp.get('General/seed'),\r\n shuffle=False,\r\n batch_size=self.hyperp.get('Run/batch_size'))\r\n\r\n if validation_set is None:\r\n validation_set = (Xv, Yv)\r\n self.history = self.model.fit_generator(gen_iter,\r\n epochs=self.hyperp.get('Run/epochs'),\r\n steps_per_epoch=self.hyperp.get('Run/gen_steps_per_epoch'),\r\n verbose=self.hyperp.get('Run/verbose'),\r\n workers=self.hyperp.get('Data/generator/workers'), \r\n use_multiprocessing=self.hyperp.get('Data/generator/use_multiprocessing'),\r\n shuffle=True,\r\n validation_data=validation_set,\r\n callbacks=self._callbacks(weightsfilepath = self.hyperp.get('Model/weightsfile')))\r\n else:\r\n id_t, id_v, Xt, Xv, Yt, Yv, T, normer = run_dataset.get_splitted_datasets(\r\n fold=fold,train_size=train_size,\r\n random_state= self.hyperp.get('General/seed'),\r\n normalise_images=self.hyperp.get('Data/normalisation'),\r\n with_features=self.hyperp.get('Data/with_features'),\r\n feature=self.hyperp.get('Data/stratification_feature'),\r\n categorical= self.hyperp.get('Data/categorical'),\r\n multilabel = self.hyperp.get('Data/multilabel'))\r\n self.hyperp['Data/training_img_mean'] = normer.amean\r\n self.hyperp['Data/training_img_std'] = normer.astd\r\n self.hyperp['Data/training_img_min'] = normer.amin\r\n self.hyperp['Data/training_img_max'] = normer.amax\r\n\r\n if self.hyperp.get('Run/weigth_balanced_classes'):\r\n # Using weighted classes to fit the model\r\n cw = dict(enumerate(class_weight.compute_class_weight('balanced', np.unique(run_dataset.Y), run_dataset.Y)))\r\n else:\r\n cw = None\r\n\r\n self.history = self.model.fit(Xt, Yt,\r\n epochs=self.hyperp['Run/epochs'],\r\n verbose=self.hyperp['Run/verbose'],\r\n validation_data=(Xv, Yv),\r\n class_weight=cw,\r\n shuffle=True,\r\n batch_size=self.hyperp['Run/batch_size'],\r\n callbacks=self._callbacks(weightsfilepath = self.hyperp['Model/weightsfile']))\r\n\r\n # load best weights saved by callback\r\n wfname = self.hyperp['Model/weightsfile']\r\n if (os.path.isfile(wfname)) :\r\n self.model.load_weights(wfname)\r\n else: # Save current weights\r\n self.model.save_weights(wfname)\r\n #Save the whole model\r\n self.model.save(self.hyperp['Model/modelfile'])\r\n \r\n return self.get_run_results(run_dataset, id_t, id_v, Xt, Xv, Yt, Yv, T, normer)\r\n\r\n def get_run_results(self, run_dataset, id_t, id_v, Xt, Xv, Yt, Yv, T, normer):\r\n # Get the inverse encoding for the labels\r\n result_labels = run_dataset.get_result_labels()\r\n \r\n #Format the result_labels, will be a problem if more than 100 labels\r\n try:\r\n columns=[f'{fea:02d}' for fea in result_labels]\r\n except: # labels are not integers\r\n columns=result_labels\r\n # Store the inverse encoding in hyperparameters (as a string to comme across csv, excel,...)\r\n self.hyperp['Data/inverse_label_transform'] = str(columns)\r\n\r\n # get the evaluations/predictions for the training set\r\n if self.hyperp.get('Data/generated') :\r\n train_set = run_dataset.get_train_generator(id_t, \r\n filter_channels = self.hyperp['Data/filter_channels'],\r\n zification = self.hyperp['Data/zification'],\r\n class_mode = 'other',\r\n random_state= self.hyperp['General/seed'],\r\n shuffle=False,\r\n batch_size=self.hyperp['Run/batch_size'])\r\n evaluations = self.model.evaluate_generator(train_set,\r\n workers=self.hyperp['Data/generator/workers'], \r\n use_multiprocessing=self.hyperp['Data/generator/use_multiprocessing'],\r\n verbose=self.hyperp['Run/verbose'])\r\n predictions_train = self.model.predict_generator(\r\n run_dataset.get_train_generator(id_t, \r\n filter_channels = self.hyperp['Data/filter_channels'],\r\n zification = self.hyperp['Data/zification'],\r\n class_mode = None,\r\n random_state= self.hyperp['General/seed'],\r\n shuffle=False,\r\n batch_size=self.hyperp['Run/batch_size']),\r\n workers=self.hyperp['Data/generator/workers'], \r\n use_multiprocessing=self.hyperp['Data/generator/use_multiprocessing'],\r\n verbose=self.hyperp['Run/verbose'])\r\n else:\r\n evaluations = self.model.evaluate(Xt, Yt, verbose=self.hyperp['Run/verbose'],\r\n batch_size=self.hyperp['Run/batch_size'])\r\n predictions_train = self.model.predict(Xt, verbose=self.hyperp['Run/verbose'], \r\n batch_size=self.hyperp['Run/batch_size'])\r\n print('\\n----------------------------------------------------------------------------------')\r\n for name, val in zip(self.model.metrics_names, evaluations):\r\n self.hyperp[f'Result/{name}(TrainingSet)'] = val\r\n print(f\" Result/{name}(TrainingSet) : {val}\")\r\n\r\n # get the evaluations/predictions for the validation set\r\n if len(Yv) > 0:\r\n if self.hyperp.get('Data/generated') :\r\n validation_set = run_dataset.get_train_generator(id_v, \r\n filter_channels = self.hyperp['Data/filter_channels'],\r\n class_mode = 'other',\r\n zification = self.hyperp['Data/zification'],\r\n random_state= self.hyperp['General/seed'],\r\n shuffle=False,\r\n batch_size=self.hyperp['Run/batch_size'])\r\n evaluations = self.model.evaluate_generator(\r\n validation_set,\r\n workers=self.hyperp['Data/generator/workers'], \r\n use_multiprocessing=self.hyperp['Data/generator/use_multiprocessing'],\r\n verbose=self.hyperp['Run/verbose'])\r\n predictions_valid = self.model.predict_generator(\r\n run_dataset.get_train_generator(id_v, \r\n filter_channels = self.hyperp['Data/filter_channels'],\r\n zification = self.hyperp['Data/zification'],\r\n class_mode = None,\r\n random_state= self.hyperp['General/seed'],\r\n shuffle=False,\r\n batch_size=self.hyperp['Run/batch_size']),\r\n workers=self.hyperp['Data/generator/workers'], \r\n use_multiprocessing=self.hyperp['Data/generator/use_multiprocessing'],\r\n verbose=self.hyperp['Run/verbose'])\r\n else:\r\n evaluations = self.model.evaluate(Xv, Yv, verbose=self.hyperp['Run/verbose'],\r\n batch_size=self.hyperp['Run/batch_size'])\r\n predictions_valid = self.model.predict(Xv, verbose=self.hyperp['Run/verbose'], \r\n batch_size=self.hyperp['Run/batch_size'])\r\n \r\n print('\\n----------------------------------------------------------------------------------')\r\n for name, val in zip(self.model.metrics_names, evaluations):\r\n self.hyperp[f'Result/{name}(ValidationSet)'] = val\r\n print(f\" Result/{name}(ValidationSet) : {val}\")\r\n else:\r\n predictions_valid = pd.DataFrame([], columns=columns)\r\n \r\n # Get the predictions for the test set\r\n if len(run_dataset.test_ids) > 0:\r\n if self.hyperp.get('Data/generated') :\r\n test_set = run_dataset.get_test_generator(run_dataset.test_ids, \r\n filter_channels = self.hyperp['Data/filter_channels'],\r\n zification = self.hyperp['Data/zification'],\r\n batch_size=self.hyperp['Run/batch_size'])\r\n predictions_test = self.model.predict_generator(\r\n test_set,\r\n workers=self.hyperp['Data/generator/workers'], \r\n use_multiprocessing=self.hyperp['Data/generator/use_multiprocessing'],\r\n verbose=self.hyperp['Run/verbose'])\r\n else:\r\n predictions_test = self.model.predict(T, verbose=self.hyperp['Run/verbose'], \r\n batch_size=self.hyperp['Run/batch_size'])\r\n else:\r\n predictions_test = pd.DataFrame([], columns=columns)\r\n\r\n pred = [predictions_test, predictions_train, predictions_valid]\r\n inputsets = [T, Xt, Xv]\r\n truths = [pd.Series([]), Yt, Yv]\r\n txts = ['TestSet', 'TrainingSet', 'ValidationSet']\r\n for iPred, tset, truth, txt in zip(range(0,3), inputsets, truths, txts):\r\n predictions = pred[iPred]\r\n if predictions is None or len(predictions) == 0:\r\n pred[iPred] = pd.DataFrame([], columns=columns)\r\n else:\r\n if self.hyperp['Data/categorical'] or self.hyperp['Data/multilabel'] :\r\n pred[iPred] = pd.DataFrame(predictions, columns=columns)\r\n else:\r\n pred[iPred] = pd.DataFrame(predictions.ravel(), columns=['Prediction'])\r\n\r\n if len(pred[iPred]) != 0: # if there are predicted stuff\r\n predicted_labels = pred[iPred].idxmax(axis=1)\r\n\r\n # Compute f1_score for Training & Validation sets\r\n if len(truth) > 0 and not self.hyperp.get('Data/multilabel'):\r\n predicted_labels = predicted_labels.astype(int)\r\n if self.hyperp.get('Data/categorical'):\r\n # The truth values are one_hot encoded and label encoded\r\n tvalues = run_dataset.get_inverse_encoding(np.argmax(truth, axis=1))\r\n scores = f1_score(tvalues, predicted_labels, average='macro')\r\n else:\r\n scores = f1_score(truth, predicted_labels, average='macro')\r\n self.hyperp[f'Result/f1_score_avg({txt})'] = scores.mean()\r\n self.hyperp[f'Result/f1_score_std({txt})'] = scores.std()\r\n print(f\"f1_score({txt}) average = {self.hyperp[f'Result/f1_score_avg({txt})']} ; std = {self.hyperp[f'Result/f1_score_std({txt})']}\")\r\n print('----------------------------------------------------------------------------------')\r\n\r\n # Compute silhouettes only with images\r\n if self.hyperp.get('Data/with_images') and not self.hyperp.get('Data/with_features'):\r\n try: # in some cases, only one label is predicted and silhouette fails, lazy ay to catch it\r\n print('Computing Silhouette')\r\n silhouette_avg = silhouette_score(np.reshape(tset, (np.shape(tset)[0], -1)), predicted_labels)\r\n print(f'Silhouette average for {txt}: {silhouette_avg:10.6f}')\r\n print('----------------------------------------------------------------------------------')\r\n except:\r\n print(f'Error while computing silhouette : {sys.exc_info()[0]}')\r\n silhouette_avg = np.nan\r\n\r\n self.hyperp[f'Result/SilhouetteAvg({txt})'] = silhouette_avg\r\n \r\n # Hyperparameters, Predictions for : test set, train set, validation set \r\n hp = pd.Series(self.hyperp, name = self.runName)\r\n return (pd.DataFrame(hp), # paramètres\r\n pred[0].set_index(run_dataset.test_ids), # Predictions for : test set\r\n pred[1].set_index(id_t), # Predictions for train set \r\n pred[2].set_index(id_v) # Predictions for validation set\r\n )\r\n \r\n def fold(self, \r\n dataset,\r\n n_splits=None,\r\n hyperp=None\r\n ):\r\n if self.hyperp is None :\r\n self.hyperp = HyperP.get_default()\r\n if hyperp is not None:\r\n self.hyperp.update(hyperp)\r\n \r\n # Create a UUID for this fold\r\n self.hyperp['set_uuid'] = str(uuid.uuid4())\r\n\r\n if n_splits is None:\r\n if hyperp.get('Folds/n_splits') is None:\r\n n_splits = 5\r\n else : \r\n n_splits = hyperp.get('Folds/n_splits')\r\n\r\n hyperp['Folds/n_splits'] = n_splits\r\n \r\n \r\n # See if there is a fold definition in the hyperparameters\r\n if self.hyperp.get('Folds/definition_file') is None:\r\n folds = dts.Fold.create_stratified(dataset, n_splits)\r\n self.hyperp['Folds/definition_file'] = os.path.join(self.rundir, \"folds-\"+self.hyperp['set_uuid']+'.npy')\r\n folds.save(self.hyperp['Folds/definition_file'])\r\n self.hyperp['Folds/n_splits'] = n_splits\r\n elif not Path(self.hyperp['Folds/definition_file']).is_file():\r\n folds = dts.Fold.create_stratified(dataset, n_splits, \r\n multilabel = self.hyperp.get('Data/multilabel'),\r\n random_state = self.hyperp.get('General/seed'),\r\n )\r\n folds.save(self.hyperp['Folds/definition_file'])\r\n self.hyperp['Folds/n_splits'] = n_splits\r\n else:\r\n folds = dts.Fold.from_file(self.hyperp['Folds/definition_file'])\r\n print('Loading Fold definition file : ' + self.hyperp['Folds/definition_file'])\r\n n_splits = folds.number()\r\n self.hyperp['Folds/n_splits'] = n_splits\r\n\r\n # Check if there are weights definition files defined per fold\r\n if self.hyperp.get('Model/load_weights') and len(self.hyperp.get('Model/load_weights')) == n_splits:\r\n weightsfile_per_fold = self.hyperp.get('Model/load_weights')\r\n else:\r\n weightsfile_per_fold = None \r\n \r\n rparam = {}\r\n rtest = {}\r\n rtrain = {}\r\n rvalid = {}\r\n\r\n # Do each fold\r\n for iFold, fold in enumerate(folds):\r\n print(f'------------------------Fold {iFold}---------------------------------------------')\r\n self.hyperp['Folds/fold_nb'] = iFold\r\n if weightsfile_per_fold:\r\n self.hyperp['Model/load_weights'] = weightsfile_per_fold[iFold]\r\n else:\r\n self.hyperp['Model/load_weights'] = None\r\n param, test, train, valid = self.run( dataset, fold=fold, hyperp=self.hyperp )\r\n \r\n key = self.hyperp['set_uuid'] + '@' + str(iFold)\r\n rparam[key] = param\r\n rtest[key] = test\r\n rtrain[key] = train\r\n rvalid[key] = valid\r\n \r\n return rslt.Result(rparam, rtest, rtrain, rvalid)\r\n\r\n @staticmethod\r\n def foldset(dataset,\r\n rundir='./',\r\n logdir='./',\r\n hyperp_set = [HyperP.get_default_set()],\r\n factory = ModelFactory(),\r\n n_splits=None):\r\n '''\r\n Run a model through a set of hyperparameters anc kFold then aggregates \r\n results.\r\n :dataset : the data to be run through the model\r\n :rundir : the running directory\r\n :logdir: the log directory for tensorboard\r\n :hyperp_set: the dictionary of hyperparameters with the list of parameters\r\n :factory: the factory object that knows the model classname to be run\r\n :n_splits: the number of split for the kFold, if None then it's in the hyper_parameters\r\n ''' \r\n if (not isinstance(hyperp_set, (list, tuple, np.ndarray))):\r\n hyperp_set = [hyperp_set]\r\n \r\n result = rslt.Result()\r\n for hyperpdict in hyperp_set:\r\n for hyperp_fold in HyperP.get_set_cartesian_product(hyperpdict):\r\n hyperp = HyperP.get_default()\r\n hyperp.update(hyperp_fold)\r\n if n_splits is None:\r\n if hyperp.get('Folds/n_splits') is None:\r\n n_splits = 5\r\n else : \r\n n_splits = hyperp.get('Folds/n_splits')\r\n\r\n hyperp['Folds/n_splits'] = n_splits\r\n classname = hyperp['Model/classname']\r\n modelObj = factory.makeModel(classname, rundir=rundir, logdir=logdir, hyperp=hyperp)\r\n one_result = modelObj.fold(dataset,\r\n n_splits=n_splits,\r\n hyperp=hyperp)\r\n \r\n result = result.merge(one_result)\r\n #write intermediary results\r\n if hyperp.get('General/resultfilename'):\r\n #result.to_h5(os.path.join(rundir, hyperp['General/resultfilename'])+\".h5\")\r\n result.param_to_excel(os.path.join(rundir, hyperp['General/resultfilename'])+\"_param.xlsx\")\r\n \r\n return result\r\n\r\n def predict(self, dataset, hyperp):\r\n '''\r\n Run the current model on the test subset of a dataset\r\n :data: an instance of a (subclass of) core.Dataset\r\n :hyperp: dict - the set of hyperparameters used for the model\r\n :return: a dataframe with the predictions\r\n '''\r\n if self.model is None:\r\n print('model.predict error : Undefined model, not yet trained or loaded ?')\r\n return pd.DataFrame([])\r\n\r\n # Get the inverse encoding for the labels\r\n result_labels = dataset.get_result_labels()\r\n \r\n #Format the result_labels, will be a problem if more than 100 labels\r\n try:\r\n columns=[f'{fea:02d}' for fea in result_labels]\r\n except: # labels are not integers\r\n columns=result_labels\r\n\r\n # Get the predictions for the test set\r\n if len(dataset.test_ids) > 0:\r\n test_set = dataset.get_test_generator(dataset.test_ids, \r\n zification = self.hyperp['Data/zification'],\r\n filter_channels = self.hyperp['Data/filter_channels'],\r\n batch_size=self.hyperp['Run/batch_size'])\r\n if test_set is None:\r\n predictions_test = self.model.predict(dataset.test_images, verbose=self.hyperp['Run/verbose'], \r\n batch_size=self.hyperp['Run/batch_size'])\r\n else:\r\n predictions_test = self.model.predict_generator(\r\n test_set,\r\n workers=self.hyperp['Data/generator/workers'], \r\n use_multiprocessing=self.hyperp['Data/generator/use_multiprocessing'],\r\n verbose=self.hyperp['Run/verbose'])\r\n else:\r\n predictions_test = None\r\n \r\n if predictions_test is None or len(predictions_test) == 0:\r\n return pd.DataFrame([])\r\n else:\r\n if self.hyperp['Data/categorical']:\r\n predictions = pd.DataFrame(predictions_test, columns=columns)\r\n else:\r\n predictions = pd.DataFrame(predictions.ravel(), columns=['Prediction'])\r\n predictions.set_index(dataset.test_ids)\r\n return predictions\r\n \r\n @staticmethod\r\n def predict_from_param(excelfilepath = None, \r\n data = None,\r\n hyperp_list = None,\r\n rundir='./',\r\n logdir='./',\r\n factory = ModelFactory()):\r\n '''\r\n Predict from models defined by a hyper parameter file stored in excel on the \r\n test subset of a dataset. The model definition files in the hyperparameters \r\n must exist.\r\n :excelfilepath: the file path of the excel file containing the hyper\r\n parameters (including the path of the .h5file for the trained model).\r\n There may be several \r\n see core.Result.param_to_excel() and core.HyperP.from_excel\r\n :hyperp_list: if excelfilepath is None this list of hyperparameter is used\r\n if excelfilepath is not None, then this is not used\r\n :data: an instance of a (subclass of) core.Dataset\r\n :factory: the model factory used to create the model class from its name\r\n \r\n :return: a Result object with a result for each model\r\n '''\r\n \r\n rparam = {}\r\n rtest = {}\r\n rtrain = {}\r\n rvalid = {}\r\n \r\n if data is None or (excelfilepath is None and hyperp_list is None):\r\n return rslt.Result(rparam, rtest, rtrain, rvalid)\r\n \r\n if excelfilepath is not None:\r\n hyperp_list = HyperP.from_excel(excelfilepath)\r\n \r\n for hyperp in hyperp_list:\r\n # Try to find if there is a mapping for label encoding\r\n if hyperp.get('Data/inverse_label_transform') is None:\r\n columns = None\r\n else:\r\n try:\r\n columns=[f'{fea:02d}' for fea in hyperp.get('Data/inverse_label_transform')]\r\n except: # labels are not integers\r\n columns=hyperp.get('Data/inverse_label_transform') \r\n\r\n key = hyperp['learn_uuid']\r\n\r\n K.clear_session()\r\n\r\n model = PredictiveModel.from_h5(filepath = hyperp['Model/modelfile'], \r\n classname = hyperp['Model/classname'],\r\n rundir=rundir,\r\n logdir=logdir,\r\n factory = factory,\r\n hyperp=hyperp)\r\n predictions = model.predict(data, hyperp)\r\n rparam[key] = pd.DataFrame(pd.Series(hyperp, name = key))\r\n if columns is None:\r\n rtest[key] = predictions.set_index(data.test_ids)\r\n rtrain[key] = pd.DataFrame([])\r\n rvalid[key] = pd.DataFrame([])\r\n else:\r\n rtest[key] = predictions.rename(columns=dict(zip(predictions.columns, columns))).set_index(data.test_ids)\r\n rtrain[key] = pd.DataFrame([], columns=columns)\r\n rvalid[key] = pd.DataFrame([], columns=columns)\r\n \r\n return rslt.Result(rparam, rtest, rtrain, rvalid)\r\n def get_encoded_image(self, image):\r\n '''\r\n Run an image through the autoencoder (encode -> decode).\r\n The input image must be compatible with the input shape used to train the autoencoder\r\n The model must have been previously fitted or loaded with a already trained model\r\n '''\r\n return model.predict(np.array([image]))\r\n def get_encoded_batch(self, images, batch_size = 1):\r\n '''\r\n Run a batch of images through the autoencoder (encode -> decode).\r\n The input images must be compatible with the input shape used to train the autoencoder\r\n The model must have been previously fitted or loaded with a already trained model\r\n '''\r\n return model.predict(images, batch_size = batch_size)","sub_path":"core/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":53916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"273714512","text":"def build_leaderboard_for_rack(rack_string, min_length = 3, max_length = 7):\n \"\"\"\n Build a leaderboard of the top scoring words that can be built using only the letters contained in \n a given rack. Words are ordered in the leaderboard by their score (with the highest score first) and then \n alphabetically for words which have the same score.\n :param rack_string: a random string of letters from which to build words that are valid against the contents \n of the scrabble dictionary file (sowpods.txt)\n :param min_length: minimum length of words to be returned in the leaderboard\n :param max_length: maximum length of words to be returned in the leaderboard\n :return:\n \"\"\"\n from collections import Counter\n \n \n # build dictionary for letter values\n letterval_df = pd.read_csv('letterValues.txt', sep = ':', names = ['letter', 'value'])\n letterval_df['letter'] = letterval_df['letter'].str.lower()\n VALUES_DICT = dict(zip(letterval_df.letter, letterval_df.value))\n\n # generate words variable from sowpod.txt\n with open('sowpods.txt', \"r\") as sowpods:\n words = sowpods.read().split(\"\\n\")\n \n allowed_words = []\n for word in words:\n if min_length <= len(word) <= max_length:\n allowed_words.append(word)\n\n # define function to check if word can be spelled from rack\n def can_spell(word, rack_string):\n if not Counter(word) - Counter(rack_string):\n return word\n \n # generate list of spellable words from rack string\n \n spellable_words = []\n for word in allowed_words:\n if can_spell(word, rack_string):\n spellable_words.append(word)\n \n # generate score list for spellable words\n \n score_lst = []\n for word in spellable_words:\n score = sum([VALUES_DICT[c] for c in word])\n score_lst.append(score)\n \n # generate ranking dataframe\n ranking_df = pd.DataFrame(\n {'word': spellable_words,\n 'score': score_lst\n })\n\n ranking_df = ranking_df.sort_values(['score','word'], ascending=[False,True])\n ranking_df = ranking_df[0:100]\n ranking_df.reset_index(inplace = True, drop = True)\n ranking_df.insert(0,'rank',list(range(1,len(spellable_words)+1)))\n\n return(ranking_df)\n \n ","sub_path":"leaderboard_for_rack.py","file_name":"leaderboard_for_rack.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"133589989","text":"import requests as req\nfrom bs4 import BeautifulSoup as bs\nimport urllib.parse as urllib\nimport webbrowser \nimport random\n\nURL = \"https://www.assisi-ni.org/wp-admin/admin-ajax.php\"\nPAYLOAD = {\n \"action\" : \"jet_engine_elementor\", \n \"handler\" : \"listing_load_more\", \n \"query[post_status][]\":\"publish\",\n \"query[post_type]\":\"animals\", \n \"query[posts_per_page]\":6,\n \"query[paged]\":1,\n \"query[suppress_filters]\":\"false\",\n \"query[jet_smart_filters]\":\"jet-engine/default\",\n \"widget_settings[lisitng_id]\":3474,\n \"widget_settings[posts_num]\":6, \n \"page\":1}\n\n\nANIMAL_PARAMETRES = {\n \"query[meta_query][0][key]\" : \"type\",\n \"query[meta_query][0][value]\" : \"Dog\"\n}\n\n\nHEADERS = {\n 'authority': 'www.assisi-ni.org',\n 'Content-type': 'application/json',\n 'x-requested-with': 'XMLHttpRequest',\n 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'origin': 'https://www.assisi-ni.org',\n 'sec-fetch-site': 'same-origin',\n 'sec-fetch-mode': 'cors',\n 'referer': 'https://www.assisi-ni.org/',\n}\n\ndef addSearchParametres(animal):\n if (animal != None):\n PAYLOAD.update(ANIMAL_PARAMETRES)\n PAYLOAD[\"query[meta_query][0][value]\"] = animal\n \n\ndef getListOfAnimals(animal):\n addSearchParametres(animal)\n listOfAnimals = []\n pageNumber = 1\n resultsLength = 99\n while(resultsLength > 0):\n PAYLOAD['page']=pageNumber\n page = req.post(URL, headers=HEADERS, data = urllib.urlencode(PAYLOAD))\n response = page.json()\n soup = bs(response[\"data\"][\"html\"], 'html.parser')\n results = soup.findAll('a')\n resultsLength = len(results)\n for i in range(1, resultsLength, 2):\n listOfAnimals.append(results[i]['href'])\n pageNumber+=1\n return listOfAnimals\n \n\ndef getMyBestFriend(animal = None):\n listOfAnimals = getListOfAnimals(animal)\n lent = len(listOfAnimals)\n randomInt = random.randint(0, lent-1)\n return listOfAnimals[randomInt]\n","sub_path":"findMyAnimals.py","file_name":"findMyAnimals.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"178036903","text":"import heapq\nimport math\n\ndef euclidean_dist(current_position, destination):\n x,y = current_position\n a,b = destination\n \n return math.sqrt((x-a)**2 + (y-b)**2)\n\ndef find_path (source_point, destination_point, mesh):\n #Mesh is a dictionary with box dimensions and lists of adjacent boxes\n #Source and dest are POINTS! Not boxes!\n\n \"\"\"\n Searches for a path from source_point to destination_point through the mesh\n Args:\n source_point: starting point of the pathfinder\n destination_point: the ultimate goal the pathfinder must reach\n mesh: pathway constraints the path adheres to\n Returns:\n A path (list of points) from source_point to destination_point if exists\n A list of boxes explored by the algorithm\n \"\"\"\n\n #First thing we want to try is returning a list of boxes\n\n \"\"\"\n Pseudocode\n Scan through the boxes in mesh to find source_box and dest_box\n for each box in mesh:\n if source_point(x) is between top and bottom right x\n if source_point(y) is between top and bottom right y\n source_box = this box\n create a priority queue, push source_point\n create a dictionary came_from containing previous locations\n while priority queue is not empty:\n current_box = queue.pop\n if current_box = destination\n create list path_taken\n using came_from, starting at the desintation, \n add boxes to path_taken\n return path_taken\n \n for each neighbor of current_box (using mesh)\n (There are no distances so we don't have to worry about that rn)\n if neighbor is not in came_from:\n came_from.append(neighbor)\n queue.push(neighbor)\n \n (did not find a path)\n return None\n \"\"\"\n\n source_box = (0, 0, 0, 0)\n dest_box = (0, 0, 0, 0)\n detail_points = {} #a dictionary the maps boxes to (x,y) pairs.\n\n \"\"\"\n How to do point to point:\n - start w/ source point in first box\n - take current point and constrain it within the bounds of next box\n \"\"\"\n\n #Find the boxes that source and destination are in\n for box in mesh['boxes']:\n if source_point[0] >= box[0] and source_point[0] <= box[1]:\n if source_point[1] >= box[2] and source_point[1] <= box[3]:\n source_box = box #This might not get the key\n\n if destination_point[0] >= box[0] and destination_point[0] <= box[1]:\n if destination_point[1] >= box[2] and destination_point[1] <= box[3]:\n dest_box = box #This might not get the key\n\n #The keys for both parts of the mesh are quadruples\n\n path = []\n #previous boxes that have been traversed\n boxes = {}\n path_taken = []\n\n #the distance traversed thus far\n distance_so_far = {}\n distance_so_far[source_point] = 0\n\n start_heuristic = euclidean_dist(source_point, destination_point)\n\n frontier = [(start_heuristic, source_box, source_point)]\n\n boxes[source_box] = None\n detail_points[source_box] = source_point\n\n while(len(frontier) > 0):\n priority, current_box, current_point = heapq.heappop(frontier)\n\n if current_box == dest_box:\n # Insert current_box into boxes, w/ previous as value\n path.append(destination_point)\n while(current_box != None):\n path_taken.append(current_box)\n path.append(detail_points[current_box])\n current_box = boxes[current_box] #destination point should already have something in boxes\n break\n\n neighbors = mesh['adj'][current_box] #Hopefully this gets the neighbor list?\n for neighbor in neighbors:\n if(neighbor not in boxes):\n\n \"\"\"\n Take current point and constrain it within the range of the current neighbors\n rangeX = currentBox(x1 - x2) * neighborbox(x1 - x2)\n rangeY = currentBox(y1 - y2) * neighborBox(y1 - y2)\n neighborPoint = current_point\n constrain(neighborPoint.x, rangeX)\n constrain(neighborPoint.y, rangeY)\n \"\"\"\n xMin, yMin = max(current_box[0], neighbor[0]), max(current_box[2], neighbor[2])\n xMax, yMax = min(current_box[1], neighbor[1]), min(current_box[3], neighbor[3])\n \n clamp_pointX = max(xMin, min(current_point[0], xMax))\n clamp_pointY = max(yMin, min(current_point[1], yMax))\n neighbor_point = (clamp_pointX, clamp_pointY)\n\n new_distance = distance_so_far[current_point] + euclidean_dist(current_point, neighbor_point)\n\n #if new_distance < distance_so_far[neighbor_point]:\n if neighbor not in boxes or new_distance < distance_so_far[neighbor_point]:\n distance_so_far[neighbor_point] = new_distance\n priority = new_distance + int(euclidean_dist(neighbor_point, destination_point))\n\n boxes[neighbor] = current_box #Add neighbor to list of boxes\n detail_points[neighbor] = neighbor_point #Add neighbor and its point to point list\n heapq.heappush(frontier, (priority, neighbor, neighbor_point))\n\n return path, path_taken #Replaced boxes.keys() w/ path_taken","sub_path":"CMPM-146-Assignment-2-main/P__export/src/p2_pathfinder.py","file_name":"p2_pathfinder.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532471372","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def InversePairs(self, data):\n # write code here\n if len(data)==0:\n \treturn 0\n copy=[i for i in data]\n return self.mergeSort(data,copy,0,len(data)-1)% 1000000007#调用时 self.\n def mergeSort(self,data,copy,start,end):#定义时 增加一个参数 self\n \tif start==end:\n \t\treturn 0\n \tmid=(start+end)//2\n \tleft=self.mergeSort(copy,data,start,mid)\n \tright=self.mergeSort(copy,data,mid+1,end)\n\n \tcnt=0\n \ti=mid\n \tj=end\n \tcopyIndex=end\n \twhile i>=start and j>=mid+1:\n \t\tif data[i]>data[j]:\n \t\t\tcopy[copyIndex]=data[i]\n \t\t\tcnt+=j-mid\n \t\t\ti-=1\n \t\telse:\n \t\t\tcopy[copyIndex]=data[j]\n \t\t\tj-=1\n \t\tcopyIndex-=1\n \twhile i>=start:\n \t\tcopy[copyIndex]=data[i]#下面两个循环哪个放前 哪个放后是无所谓的 上面循环必会使得其中一个(i j)越界\n \t\ti-=1\n \t\tcopyIndex-=1\n \twhile j>=mid+1:\n \t\tcopy[copyIndex]=data[j]\n \t\tj-=1\n \t\tcopyIndex-=1\n \treturn left+right+cnt\n","sub_path":"python/35.py","file_name":"35.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172057554","text":"import math\nimport time\nimport torch as t\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom .decoder import Decoder\nfrom .encoder import Encoder\nfrom .highway import Highway\n\nclass Paraphraser(nn.Module):\n def __init__(self, params):\n super(Paraphraser, self).__init__()\n self.params = params\n self.highway = Highway(self.params.word_embed_size, 2, F.relu)\n self.encoder = Encoder(self.params, self.highway)\n self.decoder = Decoder(self.params, self.highway)\n\n def forward(self, drop_prob, encoder_input=None, decoder_input=None,\n z=None, initial_state=None, use_cuda=True):\n \"\"\"\n :param encoder_word_input: An list of 2 tensors with shape of [batch_size, seq_len] of Long type\n :param decoder_word_input: An An list of 2 tensors with shape of [batch_size, max_seq_len + 1] of Long type\n :param initial_state: initial state of decoder rnn in order to perform sampling\n\n :param drop_prob: probability of an element of decoder input to be zeroed in sense of dropout\n\n :param z: context if sampling is performing\n\n :return: unnormalized logits of sentence words distribution probabilities\n with shape of [batch_size, seq_len, word_vocab_size]\n final rnn state with shape of [num_layers, batch_size, decoder_rnn_size]\n \"\"\"\n\n if z is None:\n ''' Get context from encoder and sample z ~ N(mu, std)\n '''\n [batch_size, _, _] = encoder_input[0].size()\n\n mu, logvar = self.encoder(encoder_input[0], encoder_input[1])\n std = t.exp(0.5 * logvar)\n\n z1 = Variable(t.randn([batch_size, self.params.latent_variable_size]))\n if use_cuda:\n z1 = z1.cuda()\n z1 = z1 * std + mu\n\n kld = (-0.5 * t.sum(logvar - t.pow(mu, 2) - t.exp(logvar) + 1, 1)).mean().squeeze()\n\n if self.params.use_two_path_loss:\n mu2, logvar2 = self.encoder(encoder_input[0], input_target=None)\n std2 = t.exp(0.5 * logvar2)\n\n z2 = Variable(t.randn([batch_size, self.params.latent_variable_size]))\n if use_cuda:\n z2 = z2.cuda()\n z2 = z2 * std2 + mu2\n\n else:\n kld = None\n\n out1, final_state = self.decoder(decoder_input[0], decoder_input[1],\n z1, drop_prob, initial_state)\n if self.params.use_two_path_loss:\n out2, final_state2 = self.decoder(decoder_input[0], decoder_input[1],\n z2, drop_prob, initial_state)\n else:\n out2 = None\n\n return (out1, out2), final_state, kld\n\n def learnable_parameters(self):\n return [p for p in self.parameters() if p.requires_grad]\n\n def trainer(self, optimizer, batch_loader):\n def train(i, batch_size, use_cuda, dropout):\n input = batch_loader.next_batch(batch_size, 'train')\n input = [var.cuda() if use_cuda else var for var in input]\n\n [encoder_input_source,\n encoder_input_target,\n decoder_input_source,\n decoder_input_target, target] = input\n\n (logits, logits2), _, kld = self(dropout,\n (encoder_input_source, encoder_input_target),\n (decoder_input_source, decoder_input_target),\n z=None, use_cuda=use_cuda)\n\n target = target.view(-1)\n cross_entropy, cross_entropy2 = [], []\n\n\n logits = logits.view(-1, self.params.vocab_size)\n cross_entropy = F.cross_entropy(logits, target)\n\n if self.params.use_two_path_loss:\n logits2 = logits2.view(-1, self.params.vocab_size)\n cross_entropy2 = F.cross_entropy(logits2, target)\n else:\n cross_entropy2 = 0\n\n loss = self.params.ce_weight * cross_entropy \\\n + self.params.ce2_weight * cross_entropy2 \\\n + self.params.get_kld_coef(i) * kld\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n return (cross_entropy, cross_entropy2), kld, self.params.get_kld_coef(i)\n\n return train\n\n def validater(self, batch_loader):\n def get_samples(logits, target):\n '''\n logits: [batch, seq_len, vocab_size]\n targets: [batch, seq_len]\n '''\n\n ## for version > 0.4\n prediction = F.softmax(logits, dim=-1).data.cpu().numpy()\n\n\n ## for version < 0.3\n # seq_len = logits.size()[1]\n # prediction = F.softmax(\n # logits.view(-1, self.params.vocab_size)).view(-1, seq_len, self.params.vocab_size)\n # prediction = prediction.data.cpu().numpy()\n\n\n target = target.data.cpu().numpy()\n\n sampled, expected = [], []\n for i in range(prediction.shape[0]):\n sampled += [' '.join([batch_loader.sample_word_from_distribution(d)\n for d in prediction[i]])]\n expected += [' '.join([batch_loader.get_word_by_idx(idx) for idx in target[i]])]\n\n return sampled, expected\n\n\n def validate(batch_size, use_cuda, need_samples=False):\n if need_samples:\n input, sentences = batch_loader.next_batch(batch_size, 'test', return_sentences=True)\n sentences = [[' '.join(s) for s in q] for q in sentences]\n else:\n input = batch_loader.next_batch(batch_size, 'test')\n\n input = [var.cuda() if use_cuda else var for var in input]\n\n [encoder_input_source,\n encoder_input_target,\n decoder_input_source,\n decoder_input_target, target] = input\n\n (logits, logits2), _, kld = self(0., (encoder_input_source, encoder_input_target),\n (decoder_input_source, decoder_input_target),\n z=None, use_cuda=use_cuda)\n\n\n\n if need_samples:\n [s1, s2] = sentences\n sampled, _ = get_samples(logits, target)\n else:\n s1, s2 = (None, None)\n sampled, _ = (None, None)\n\n\n target = target.view(-1)\n\n cross_entropy, cross_entropy2 = [], []\n\n logits = logits.view(-1, self.params.vocab_size)\n cross_entropy = F.cross_entropy(logits, target)\n\n if self.params.use_two_path_loss:\n logits2 = logits2.view(-1, self.params.vocab_size)\n cross_entropy2 = F.cross_entropy(logits2, target)\n else:\n cross_entropy2 = None\n\n\n return (cross_entropy, cross_entropy2), kld, (sampled, s1, s2)\n\n return validate\n\n def sample_with_input(self, batch_loader, seq_len, use_cuda, input, ml=True):\n [encoder_input_source, encoder_input_target, decoder_input_source, _, _] = input\n\n encoder_input = [encoder_input_source, encoder_input_target]\n\n # encode\n [batch_size, _, _] = encoder_input[0].size()\n\n mu, logvar = self.encoder(encoder_input[0], None)\n\n std = t.exp(0.5 * logvar)\n\n\n z = Variable(t.randn([batch_size, self.params.latent_variable_size]))\n if use_cuda:\n z = z.cuda()\n z = z * std + mu\n\n initial_state = self.decoder.build_initial_state(decoder_input_source)\n decoder_input = batch_loader.get_raw_input_from_sentences([batch_loader.go_label])\n\n result = ''\n for i in range(seq_len):\n if use_cuda:\n decoder_input = decoder_input.cuda()\n\n logits, initial_state = self.decoder(None, decoder_input, z, 0.0, initial_state)\n logits = logits.view(-1, self.params.vocab_size)\n prediction = F.softmax(logits, dim=-1)\n if ml:\n word = batch_loader.likely_word_from_distribution(prediction.data.cpu().numpy()[-1])\n else:\n word = batch_loader.sample_word_from_distribution(prediction.data.cpu().numpy()[-1])\n if word == batch_loader.end_label:\n break\n result += ' ' + word\n\n decoder_input = batch_loader.get_raw_input_from_sentences([word])\n\n return result\n\n def sample_with_pair(self, batch_loader, seq_len, use_cuda, source_sent, target_sent):\n input = batch_loader.input_from_sentences([[source_sent], [target_sent]])\n input = [var.cuda() if use_cuda else var for var in input]\n return self.sample_with_input(batch_loader, seq_len, use_cuda, input)\n\n \"\"\" Should only be used with a batch size of 1 \"\"\"\n def sample_from_normal(self, batch_loader, seq_len, use_cuda, input, ml=True):\n [_, _, decoder_input_source, _, _] = input\n [batch_size, _, _] = decoder_input_source.size()\n\n z = Variable(t.randn([batch_size, self.params.latent_variable_size]))\n if use_cuda:\n z = z.cuda()\n\n initial_state = self.decoder.build_initial_state(decoder_input_source)\n decoder_input = batch_loader.get_raw_input_from_sentences([batch_loader.go_label])\n\n result = ''\n for i in range(seq_len):\n if use_cuda:\n decoder_input = decoder_input.cuda()\n\n logits, initial_state = self.decoder(None, decoder_input, z, 0.0, initial_state)\n logits = logits.view(-1, self.params.vocab_size)\n prediction = F.softmax(logits, dim=-1)\n if ml:\n word = batch_loader.likely_word_from_distribution(prediction.data.cpu().numpy()[-1])\n else:\n word = batch_loader.sample_word_from_distribution(prediction.data.cpu().numpy()[-1])\n if word == batch_loader.end_label:\n break\n result += ' ' + word\n\n decoder_input = batch_loader.get_raw_input_from_sentences([word])\n\n return result\n\n def beam_search(self, batch_loader, seq_len, use_cuda, input, k, sample_from_normal):\n [encoder_input_source, _, decoder_input_source, _, _] = input\n\n # encode\n [batch_size, _, _] = decoder_input_source.size()\n\n z = Variable(t.randn([batch_size, self.params.latent_variable_size]))\n if use_cuda:\n z = z.cuda()\n\n if not sample_from_normal:\n mu, logvar = self.encoder(encoder_input_source, None)\n std = t.exp(0.5 * logvar)\n z = z * std + mu\n\n initial_state = self.decoder.build_initial_state(decoder_input_source)\n decoder_input = batch_loader.get_raw_input_from_sentences([batch_loader.go_label])\n if use_cuda:\n decoder_input = decoder_input.cuda()\n\n logits, initial_state = self.decoder(None, decoder_input, z, 0.0, initial_state)\n logits = logits.view(-1, self.params.vocab_size)\n predictions = F.softmax(logits, dim=-1)\n\n # sequences = [[list(), 0.0]]\n sequences = [[list(), 0.0, initial_state, decoder_input, False]]\n\n # walk over each step in sequence\n for seq in range(seq_len):\n all_candidates = list()\n # expand each current candidate\n for i in range(len(sequences)):\n seq, score, initial_state, decoder_input, complete = sequences[i]\n if complete:\n all_candidates.append(sequences[i])\n continue\n if use_cuda:\n decoder_input = decoder_input.cuda()\n\n logits, initial_state = self.decoder(None, decoder_input, z, 0.0, initial_state)\n logits = logits.view(-1, self.params.vocab_size)\n prediction = F.softmax(logits, dim=-1).data.cpu().numpy()[-1]\n for j in range(prediction.shape[0]):\n word = batch_loader.get_word_by_idx(j)\n if word == batch_loader.unk_label:\n continue\n decoder_input = batch_loader.get_raw_input_from_sentences([word])\n if word == batch_loader.end_label:\n candidate = [seq, score - math.log(prediction[j]), initial_state, decoder_input, True]\n else:\n candidate = [seq + [word], score - math.log(prediction[j]), initial_state, decoder_input, False]\n all_candidates.append(candidate)\n # order all candidates by score\n ordered = sorted(all_candidates, key=lambda tup:tup[1])\n # select k best\n sequences = ordered[:k]\n results = []\n for sequence in sequences:\n results.append(' '.join(sequence[0]))\n return results\n\n def sample_with_phrase(self, batch_loader, seq_len, use_cuda, source_sent):\n pass\n","sub_path":"model/paraphraser.py","file_name":"paraphraser.py","file_ext":"py","file_size_in_byte":12936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401502112","text":"def collatz(number):\n\n if (number % 2 == 0):\n value = number // 2\n else:\n value = 3 * number + 1\n\n print(value)\n return value\n\nprint('Enter number:')\n\nwhile True:\n try:\n user_input = int(input())\n if collatz(user_input) == 1:\n break\n except Exception:\n print('the input must be integer')\n","sub_path":"ch_03/the_collatz_sequence.py","file_name":"the_collatz_sequence.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"466399150","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 26 10:46:05 2017\n\n@author: link9\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\n\nclass GRU_Cell(object):\n\n \"\"\"\n GRU\n \"\"\"\n\n def __init__(self, input_size, hidden_layer_size, target_size_code, target_size_time):\n\n # Initialization of given values\n self.input_size = input_size\n self.hidden_layer_size = hidden_layer_size\n self.target_size_code = target_size_code\n self.target_size_time = target_size_time\n\n # Weights for input and hidden tensor\n self.Wx = tf.Variable(tf.truncated_normal([self.input_size, self.hidden_layer_size], stddev=0.04))\n self.Wr = tf.Variable(tf.truncated_normal([self.input_size, self.hidden_layer_size], stddev=0.04))\n self.Wz = tf.Variable(tf.truncated_normal([self.input_size, self.hidden_layer_size], stddev=0.04))\n\n self.br = tf.Variable(tf.truncated_normal([self.hidden_layer_size], stddev=0.04))\n self.bz = tf.Variable(tf.truncated_normal([self.hidden_layer_size], stddev=0.04))\n\n self.Wh = tf.Variable(tf.truncated_normal([self.hidden_layer_size, self.hidden_layer_size], stddev=0.04))\n\n # Weights for output layer\n self.Wc = tf.Variable(tf.truncated_normal([self.hidden_layer_size, self.target_size_code], stddev=0.04))\n self.Wt = tf.Variable(tf.truncated_normal([self.hidden_layer_size, self.target_size_time], stddev=0.04))\n\n self.bc = tf.Variable(tf.truncated_normal([self.target_size_code], stddev=0.04))\n self.bt = tf.Variable(tf.truncated_normal([self.target_size_time], stddev=0.04))\n \n self.initial_hidden = tf.placeholder(tf.float32,\n shape=[None, hidden_layer_size],\n name='initial_hidden')\n \n \n # Function for GRU cell\n def GRU(self, previous_hidden_state, x):\n \"\"\"\n GRU Equations\n \"\"\"\n z = tf.sigmoid(tf.matmul(x, self.Wz) + self.bz) # [batch_size, hidden_size]\n r = tf.sigmoid(tf.matmul(x, self.Wr) + self.br)\n \n h_ = tf.tanh(tf.matmul(x, self.Wx) +\n tf.matmul(previous_hidden_state, self.Wh) * r)\n current_hidden_state = tf.multiply(\n (1 - z), h_) + tf.multiply(previous_hidden_state, z)\n\n return current_hidden_state # [batch_size, hidden_size]\n\n # Function for getting all hidden state.\n def get_states(self, batch_input):\n \"\"\"\n Iterates through time/ sequence to get all hidden state\n \"\"\"\n\n # Getting all hidden state throuh time\n all_hidden_states = tf.scan(self.GRU,\n batch_input,\n initializer=self.initial_hidden,\n name='states')\n\n return all_hidden_states\n\n # Function to get output from a hidden layer\n def get_output_code(self, hidden_state):\n \"\"\"\n This function takes hidden state and returns output\n \"\"\"\n output = tf.matmul(hidden_state, self.Wc) + self.bc\n\n return output\n\n # Function to get output from a hidden layer\n def get_output_time(self, hidden_state):\n \"\"\"\n This function takes hidden state and returns output\n \"\"\"\n output = tf.nn.sigmoid(tf.matmul(hidden_state, self.Wt) + self.bt)\n # sig used for mnist data, relu for original paper\n\n return output\n \n\n # Function for getting all output layers\n def get_outputs_code(self, batch_input):\n \"\"\"\n Iterating through hidden states to get outputs for all timestamp\n \"\"\"\n all_hidden_states = self.get_states(batch_input)\n \n all_outputs = tf.map_fn(self.get_output_code, all_hidden_states) # [timestep, batch_size, target_size]\n\n return all_outputs\n \n # Function for getting all output layers\n def get_outputs_time(self, batch_input):\n \"\"\"\n Iterating through hidden states to get outputs for all timestamp\n \"\"\"\n all_hidden_states = self.get_states(batch_input)\n \n all_outputs = tf.map_fn(self.get_output_time, all_hidden_states) # [timestep, batch_size, target_size]\n \n return all_outputs\n ","sub_path":"doctorai_cdm/tensorflow/class_GRU_mnist.py","file_name":"class_GRU_mnist.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"238140696","text":"#Jacob Kickbush jamakick\n#Programming Assignment 1\n\nimport sys, bs4, urllib.request, os, re, time, urllib.robotparser\nfrom urllib.parse import urlparse\nfrom collections import deque\n\ndef validVars(): \n \n unchecked = sys.argv\n \n try:\n \n pageReq = urllib.request.Request(unchecked[1], headers={'User-Agent': 'IUB-I427-jamakick'})\n \n page = urllib.request.urlopen(pageReq)\n \n page.close()\n \n except:\n print(\"The seed url was not given a proper URL/not in the proper position.\")\n\n try:\n maxPages = int(unchecked[2])\n \n if maxPages < 1:\n print(\"The amount of pages to crawl needs to be at least 1.\")\n except:\n print(\"The amount of pages given is not an integer/not in the proper position.\")\n \n if unchecked[4] not in (\"dfs\", \"bfs\"):\n raise Exception(\"The search type given was invalid/not in the proper position. Valid values are 'dfs' and 'bfs'.\")\n\n try:\n home = os.getcwd()\n \n newDirPath = os.path.join(home, unchecked[3])\n if not os.path.isdir(newDirPath):\n os.mkdir(newDirPath)\n except:\n print(\"Directory name given was not valid/not in the proper position.\")\n print(home)\n print(newDirPath)\n print(unchecked[3])\n\ndef webCrawler(url, maxPages, saveLoc, searchType):\n \n try:\n seedReq = urllib.request.Request(url, headers={'User-Agent': 'IUB-I427-jamakick'})\n \n seed = urllib.request.urlopen(seedReq)\n \n seedContents = seed.read().decode(errors=\"replace\")\n \n seed.close()\n \n fileOut = open(saveLoc + \"/0.html\", \"w\", encoding=\"utf-8\")\n fileOut.write(seedContents)\n fileOut.close()\n \n except:\n raise Exception(\"Seed url could not be accessed.\")\n \n seedContents = bs4.BeautifulSoup(seedContents, \"lxml\")\n \n links = [link.get('href') for link in seedContents.find_all('a', attrs={'href': re.compile(\"http\")})]\n \n hits = []\n \n hits = [link for link in links if link not in hits]\n \n hits = deque(hits)\n \n indexDict = {0: url}\n \n for i in range(int(maxPages)):\n if searchType == \"dfs\":\n current = \"\"\n while True:\n current = hits.pop()\n if current not in indexDict.values():\n break\n \n try:\n rp = urllib.robotparser.RobotFileParser()\n \n robotLink = urlparse(current)\n \n robotLink = '{0}://{1}/robots.txt'.format(robotLink.scheme, robotLink.netloc)\n \n rp.set_url(robotLink)\n rp.read()\n \n if rp.can_fetch(\"IUB-I427-jamakick\", current):\n req = urllib.request.Request(current, headers={'User-Agent': 'IUB-I427-jamakick'})\n \n page = urllib.request.urlopen(req)\n \n contents = page.read().decode(errors=\"replace\")\n \n page.close()\n \n fileOut = open(saveLoc + \"/\" + str(len(indexDict)) + \".html\", \"w\", encoding=\"utf-8\")\n fileOut.write(contents)\n fileOut.close()\n \n \n contents = bs4.BeautifulSoup(contents, \"lxml\")\n \n links = [link.get('href') for link in contents.find_all('a', attrs={'href': re.compile(\"http\")})]\n \n for link in links:\n if link not in hits:\n hits.append(link)\n \n indexDict[len(indexDict)+1] = current\n \n time.sleep(1)\n except:\n pass\n \n elif searchType == \"bfs\":\n current = \"\"\n while True:\n current = hits.popleft()\n if current not in indexDict.values():\n break\n \n try:\n rp = urllib.robotparser.RobotFileParser()\n \n robotLink = urlparse(current)\n \n robotLink = '{0}://{1}/robots.txt'.format(robotLink.scheme, robotLink.netloc)\n \n rp.set_url(robotLink)\n rp.read()\n \n if rp.can_fetch(\"IUB-I427-jamakick\", current):\n req = urllib.request.Request(current, headers={'User-Agent': 'IUB-I427-jamakick'})\n \n page = urllib.request.urlopen(req)\n \n contents = page.read().decode(errors=\"replace\")\n \n page.close()\n \n fileOut = open(saveLoc + \"/\" + str(len(indexDict)) + \".html\", \"w\", encoding=\"utf-8\")\n fileOut.write(contents)\n fileOut.close()\n \n \n contents = bs4.BeautifulSoup(contents, \"lxml\")\n \n links = [link.get('href') for link in contents.find_all('a', attrs={'href': re.compile(\"http\")})]\n \n for link in links:\n if link not in hits:\n hits.append(link)\n \n indexDict[len(indexDict)] = current\n \n time.sleep(1)\n except:\n pass\n \n \n return indexDict\n\n\nvalidVars()\n\nchecked = sys.argv\n\nindexDict = webCrawler(checked[1], checked[2], checked[3], checked[4])\n\n\nfileOut = open(checked[3] + \"/index.dat\", \"w\", encoding=\"utf-8\")\nfor line in indexDict.items():\n fileOut.write(str(line[0]) + \".html \" + line[1] + \"\\n\")\nfileOut.close()\n\nprint(\"finished writing files\")\n \n\n","sub_path":"I427/jamakick_final/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":5912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"209411699","text":"import sqlite3\nimport os, sys\nimport json\nfrom .schema_module import TimeAnalysisSchema\nfrom .utils import find_app_path_root\n\n\nDATA_DIR = \"../data/perf/perf_db.db\"\nERR_CODE = -1\n\n\nclass DBErrLog:\n \n ''' used to track db operation failures without printing to console '''\n \n def __init__(self, verbose=False):\n self.msgList = []\n self.verbose = verbose\n\n def addMsg(self\n ,method_name=None\n ,method_args=None\n ,method_kwargs=None\n ,exception_class=None\n ):\n ''' add a dict of info about the exception thrown '''\n msgDict = {}\n msgDict['method_name'] = method_name\n msgDict['method_args'] = method_args\n msgDict['method_kwargs'] = method_kwargs\n try:\n msgDict['exception_msg'] = exception_class.message\n except:\n msgDict['exception_msg'] = 'could not generate e.message'\n try:\n msgDict['exception_msg'] = exception_class.args\n except:\n msgDict['exception_msg'] = 'could not generate e.args'\n\n #TODO - stacktrace\n \n self.msgList.append(msgDict)\n\n def getMsgList(self):\n return self.msgList\n\n def resetMsgList(self):\n self.msgList = []\n\n def tryWrap(self, wrappedMethod):\n \n ''' Wrap wrappedMethod in try/except, logs function + errMsg.\n Used as a decorator to DBDriver methods'''\n\n def call(*args, **kwargs):\n try:\n result = wrappedMethod(*args, **kwargs)\n \n except Exception as e:\n \n result = ERR_CODE\n \n method_name = wrappedMethod.__name__\n \n self.addMsg( method_name = method_name\n ,method_args = args\n ,method_kwargs = kwargs\n ,exception_class = e\n )\n \n if self.verbose:\n print('failure: ', str(method_name))\n \n return result\n return call\n\n\n#Instantiate now, and pass into DBDriver\n# Note: handling this at module level means only one DBErrLog will be created,\n# while multiple intances of DBDriver may be created in modules\n# where it is imported, e.g. inside perf_test\n\nerrLog = DBErrLog()\ntryWrap = errLog.tryWrap\n\n\nclass DBDriver:\n\n ''' A generic db class for inheritance into task-specific-db class'''\n \n def __init__(self, data_dir=DATA_DIR, **kwargs):\n\n self.conn = None\n self.c = None\n\n self.errLog = errLog\n self.errLog.resetMsgList()\n \n @tryWrap\n def initConnect():\n self.conn = sqlite3.connect(data_dir)\n self.c = self.conn.cursor()\n initConnect()\n\n \n def getErrLog(self):\n return self.errLog.getMsgList()\n \n @tryWrap\n def verifyTable(self, tbl_name):\n ''' see if tbl_name exists '''\n s = (\"SELECT * FROM \" + tbl_name)\n self.c.execute(s)\n \n @tryWrap\n def closeConn(self):\n self.c.close()\n self.conn.close()\n\n @tryWrap\n def execStr(self, s_sql, b_commit=False, b_fetch=False):\n self.c.execute(s_sql)\n if b_commit:\n self.conn.commit()\n if b_fetch:\n return self.c.fetchall()\n\n\n#Task specific DB classes ---------------------------------------------\n\nPOPULATE_GAMES_DATA_DIR = \"../data/\"\nPOPULATE_GAMES_DATA_FN = \"GarryKasparovGames.txt\"\n\nclass TasPerfDB(DBDriver):\n\n def __init__(self, data_dir=DATA_DIR, populate=False):\n\n DBDriver.__init__(self, data_dir = data_dir)\n\n @tryWrap\n def initCreateTas():\n s = \"\"\"CREATE TABLE tas_table\n (id text, analysis_type text, algo_style text, tas text)\"\"\"\n self.c.execute(s)\n self.conn.commit()\n initCreateTas()\n\n @tryWrap\n def initCreateBasic():\n s = \"\"\"CREATE TABLE basic_tas (id text, tas text)\"\"\"\n self.c.execute(s)\n self.conn.commit()\n initCreateBasic()\n\n self.verifyTable(\"tas_table\")\n self.verifyTable(\"basic_tas\")\n\n @tryWrap\n def initCreateGamesTable():\n s = \"\"\"CREATE TABLE games (game_id text, game_instructions text)\"\"\"\n self.c.execute(s)\n self.conn.commit()\n initCreateGamesTable()\n\n self.verifyTable(\"games\")\n\n @tryWrap\n def initPopulateGamesTable():\n \n s = \"SELECT * FROM games\"\n self.c.execute(s)\n if len(self.c.fetchall()) > 1:\n print(str(self.conn))\n print('already populated')\n return\n \n print('Populating games table:')\n fn = os.path.join(POPULATE_GAMES_DATA_DIR + POPULATE_GAMES_DATA_FN)\n with open(fn,'r') as f:\n instructions = f.readlines()\n game_records = [ (\n POPULATE_GAMES_DATA_FN + \"-\" + str(i+1)\n ,instructions[i]\n )\n for i in range(len(instructions))\n ]\n\n # print game_records[:3]\n \n self.insert_many_games(game_records)\n\n self.conn.commit()\n \n s = \"SELECT * FROM games\"\n self.c.execute(s)\n rows = self.c.fetchall()\n numRows = len(rows)\n if numRows < 1:\n print('failed to load!')\n errLog = self.getErrLog()\n print('ErrLog length: ', str(len(errLog)))\n # print 'first seven errors: '\n # print errLog[:min(len(errLog), 7)]\n else:\n print('Num Rows in game table: ', str(numRows))\n print('First 3 rows...')\n print(rows[:3])\n\n if populate:\n print('starting populate')\n initPopulateGamesTable()\n \n \n \n @tryWrap\n def insert_many_games(self, game_records):\n s = \"\"\"INSERT INTO games(game_id, game_instructions) VALUES(?,?)\"\"\"\n self.c.executemany(s, game_records)\n self.conn.commit()\n \n\n @tryWrap\n def drop_table_basic_tas(self):\n self.c.execute(\"drop table basic_tas\")\n self.conn.commit()\n return 0\n\n @tryWrap\n def drop_table_tas_table(self):\n pass\n\n @tryWrap\n def build_games_table(self, games_fn):\n ''' take a pgn file and create a table with an id and insturctions '''\n pass\n\n @tryWrap\n def update_tas_record(self, tas_id, trials_data):\n ''' update instead of insert '''\n pass\n\n @tryWrap\n def add_tas_record(self, tas, tas_id = \"DUMMY\"):\n \n tas_tuple = (tas_id, tas['log'], tas['meta_analysis'], tas['trials'])\n s = \"INSERT INTO tas_table VALUES (?,?,?,?)\"\n self.c.execute(s, tas_tuple)\n self.conn.commit()\n\n @tryWrap\n def add_tas_record(self, id, tas, b_basic=False):\n \n if b_basic:\n tas_tuple = (id, tas.to_json(data_dir=None))\n s = \"INSERT INTO basic_tas VALUES (?,?)\"\n \n else:\n _analysis_type = tas.get_all()['meta_analysis']['analysis_type'] \n _algo_style = tas.get_all()['meta_analysis']['algo_style'] \n \n tas_tuple = (id, _analysis_type, _algo_style, tas.to_json(data_dir=None))\n s = \"INSERT INTO tas_table VALUES (?,?,?,?)\"\n\n self.c.execute(s, tas_tuple)\n self.conn.commit()\n\n @tryWrap\n def update_tas_record(self, id, tas, b_basic=False):\n \n if b_basic:\n tas_tuple = (tas.to_json(data_dir=None), id)\n s = \"update basic_tas set tas=? where id=?\"\n \n else:\n _analysis_type = tas.get_all()['meta_analysis']['analysis_type'] \n _algo_style = tas.get_all()['meta_analysis']['algo_style'] \n \n \n tas_tuple = (tas.to_json(data_dir=None), id, _analysis_type, _algo_style)\n s = \"\"\"update tas_table set tas=? where id=? \n and analysis_type=? and algo_style=?\"\"\"\n\n self.c.execute(s, tas_tuple)\n self.conn.commit()\n\n @tryWrap\n def check_for_tas_record(self, game_id, analysis_type=None, algo_style=None\n ,b_basic=False):\n ''' returns true if record exists in basic_tas tbl '''\n if b_basic:\n self.c.execute(\"select id from basic_tas where id=?\", (game_id,))\n else:\n self.c.execute(\"\"\"select id from tas_table \n where id=? and analysis_type=? and algo_style=?\"\"\"\n ,(game_id, analysis_type, algo_style)\n )\n return len(self.c.fetchall()) == 1\n\n # @tryWrap\n def get_tas_from_tbl(self, game_id, analysis_type=None, algo_style=None\n ,b_basic=False):\n ''' returns true if record exists in basic_tas tbl '''\n \n if b_basic:\n self.c.execute(\"select tas from basic_tas where id=?\", (game_id,))\n \n else:\n tas_tuple = (game_id, analysis_type, algo_style)\n self.c.execute(\"\"\"select tas from tas_table where id=? and analysis_type=? and algo_style=?\"\"\"\n ,tas_tuple)\n\n fetched = self.c.fetchall()\n tas = TimeAnalysisSchema()\n tas.from_json(path_fn=None, s_json=fetched[0][0])\n return tas\n\n @tryWrap\n def get_instructions_from_games(self, game_id):\n ''' return game_instructions from games tbl '''\n self.c.execute(\"select game_instructions from games where game_id=?\", (game_id,))\n return self.c.fetchall()[0][0] #first row, first elem of tuple\n\n @tryWrap\n def select_all_tas(self):\n s = \"select * from tas_table\"\n self.c.execute(s)\n ret = self.c.fetchall()\n\n tas_list = []\n\n for line in ret:\n tas_temp = TimeAnalysisSchema()\n temp = {}\n temp['log'] = line[1]\n temp['meta_analysis'] = line[2]\n temp['trials'] = line[3]\n tas_temp.from_json(json.dumps(temp))\n tas_list.append(tas_temp)\n\n return tas_list\n\n @tryWrap\n def select_all_basic(self):\n s = \"select * from basic_tas\"\n self.c.execute(s)\n return self.c.fetchall()\n\n\n\nif __name__ == \"__main__\":\n pass\n \n\n#Unit Tests ----------------------------------------------------------\n\n# def test_reveal_sys_vars():\n# print('+++++++++++++++++++++++++++++++++++++++++++++')\n# print('__name__:', __name__)\n# print('__package__:', __package__)\n# print('cwd:', os.getcwd())\n# print(\"\\n\".join([str(x) for x in sys.path]))\n# print('+++++++++++++++++++++++++++++++++++++++++++++')\n# assert False\n \n\ndef test_calling_instance_method_in_init():\n ''' Testing Design Pattern: call function below init, in init '''\n\n class MyClass:\n def __init__(self):\n self.data = 1\n self.data2 = self.bottomFunc(self.data)\n\n def bottomFunc(self, val):\n return val + 1\n\n mc = MyClass()\n assert mc.data2 == 2\n\n\ndef test_class_wrapper_1():\n ''' Testing Desgin Pattern: wrapper/decorators within classes '''\n\n def decorate(func):\n def call(*args, **kwargs):\n try:\n print('starting calc')\n result = func(*args, **kwargs)\n except:\n print('failure! ', str( func.__name__ ))\n return -1\n return result\n return call\n \n class MyClass:\n\n def __init__(self):\n self.z = 1\n\n @decorate\n def calc(self,x, y):\n print('executing function')\n return (x // y) + self.z\n\n mc = MyClass()\n assert mc.calc(1,2) == 1\n assert mc.calc(1,0) == -1\n assert mc.calc(1,2) == 1\n\n\ndef test_different_errlogs_respectively_1():\n ''' if you create 2 db drivers, then do you have different errLogs?'''\n \n db = DBDriver(data_dir=\"../data/perf/mock_db.db\")\n db.execStr(\"select * from BAD_TABLE\", b_fetch=True)\n db.execStr(\"select * from BAD_TABLE\", b_fetch=True)\n assert len(db.getErrLog()) == 2\n\n db = DBDriver(data_dir=\"../data/perf/mock_db.db\")\n db.execStr(\"select * from BAD_TABLE\", b_fetch=True)\n \n assert len(db.getErrLog()) == 1\n\n\ndef test_errlog_msg_1():\n ''' Build a DB class that inherits DBDriver, like TasPerfDB, check msgList '''\n \n class MockDB(DBDriver):\n def __init__(self, data_dir):\n DBDriver.__init__(self, data_dir)\n @tryWrap\n def good_calc(self):\n return 1\n @tryWrap\n def bad_calc(self):\n return (1/0)\n\n db = MockDB(\"../data/perf/mock_db.db\")\n assert len(db.getErrLog()) == 0\n db.good_calc()\n assert len(db.getErrLog()) == 0\n db.bad_calc()\n assert len(db.getErrLog()) == 1\n \n\n\ndef test_errlog_msg_2():\n ''' verify args and function name are present in in errLog.'''\n \n db = DBDriver(data_dir=\"../data/perf/mock_db.db\")\n\n db.execStr(\"select * from BAD_TABLE\")\n errLog = db.getErrLog()\n\n e1 = errLog[0]\n assert e1['method_name'] == \"execStr\"\n assert e1['method_args'][1] == \"select * from BAD_TABLE\"\n assert e1['method_kwargs'] == {}\n \n answer = 'no such table: BAD_TABLE'\n if sys.version_info.major == 3:\n answer = (answer,)\n \n assert e1['exception_msg'] == answer\n\n\n\ndef test_errlog_msg_3():\n ''' verify args and function name are present in in errLog.'''\n \n db = TasPerfDB()\n\n _tas = TimeAnalysisSchema()\n \n db.add_tas_record(id=(1,1), tas=_tas, b_basic=True) #Tas id not a tuple, should break\n\n errLog = db.getErrLog()\n\n badOperationItem = None\n for errItem in errLog:\n if errItem.get('method_name', None) == 'add_tas_record':\n badOperationItem = errItem\n break\n \n assert badOperationItem is not None\n\n answer = 'Error binding parameter 0 - probably unsupported type.'\n if sys.version_info.major == 3:\n answer = (answer,)\n \n assert badOperationItem['exception_msg'] == answer\n\n assert badOperationItem['method_kwargs']['id'] == (1, 1)\n assert badOperationItem['method_kwargs']['b_basic'] == True\n\n\ndef test_execmany_1():\n ''' what happens when one of the many executemany() ops fails? \n in an insert? in a select? '''\n db = DBDriver(data_dir=\"../data/perf/mock_db.db\")\n db.execStr(\"drop table mocktbl\")\n db.execStr(\"create table mocktbl (id int, s str)\")\n vals = [(1,\"a\"),(2,\"b\")]\n db.c.executemany(\"insert into mocktbl(id, s) values(?,?)\", vals)\n db.conn.commit()\n fetched = db.execStr(\"select * from mocktbl\", b_fetch=True)\n assert len(fetched) == 2\n assert fetched[1][1] == \"b\"\n\n\ndef test_populate_games_table_1():\n \n db = TasPerfDB(data_dir = \"../data/perf/mock_db.db\", populate=False)\n db.execStr(\"drop table games\")\n \n fetched = db.execStr(\"select * from games\", b_fetch=True)\n assert fetched == -1\n \n db = TasPerfDB(data_dir = \"../data/perf/mock_db.db\", populate=True)\n\n fetched = db.execStr(\"select * from games\", b_fetch=True)\n assert len(fetched) > 1\n\ndef test_non_basic_tas_1():\n ''' using b_basic=False'''\n db = TasPerfDB(data_dir=\"../data/perf/mock_db.db\")\n db.c.execute('delete from tas_table where id = \"dummy\"')\n db.conn.commit()\n tas0 = TimeAnalysisSchema()\n with open('../data/perf/demo.tas', 'r') as f:\n lines = f.readlines()\n tas_json = lines[0]\n tas0.from_json(path_fn=None, s_json=tas_json)\n db.add_tas_record(\"dummy\", tas0, b_basic=False)\n db.c.execute('select * from tas_table where id = \"dummy\"')\n ret = db.c.fetchall()\n db.closeConn()\n assert len(ret) == 1\n \n\ndef test_err_execmany_1():\n ''' what happens when one of the many executemany() ops fails? \n in an insert? in a select? '''\n pass\n\n\nif __name__ == \"__main__\":\n # test_errlog_msg_2()\n # test_reveal_sys_vars()\n test_different_errlogs_respectively_1()\n pass","sub_path":"basic_engine/tools/db_module.py","file_name":"db_module.py","file_ext":"py","file_size_in_byte":16303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217156683","text":"\"\"\" test for app action functionality \"\"\"\nfrom unittest.mock import patch\nfrom django.contrib.auth.models import Group, Permission\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.template.response import TemplateResponse\nfrom django.test import TestCase\nfrom django.test.client import RequestFactory\n\nfrom bookwyrm import models, views\nfrom bookwyrm.activitypub import ActivitypubResponse\n\n\nclass TagViews(TestCase):\n \"\"\" tag views\"\"\"\n\n def setUp(self):\n \"\"\" we need basic test data and mocks \"\"\"\n self.factory = RequestFactory()\n self.local_user = models.User.objects.create_user(\n \"mouse@local.com\",\n \"mouse@mouse.com\",\n \"mouseword\",\n local=True,\n localname=\"mouse\",\n remote_id=\"https://example.com/users/mouse\",\n )\n self.group = Group.objects.create(name=\"editor\")\n self.group.permissions.add(\n Permission.objects.create(\n name=\"edit_book\",\n codename=\"edit_book\",\n content_type=ContentType.objects.get_for_model(models.User),\n ).id\n )\n self.work = models.Work.objects.create(title=\"Test Work\")\n self.book = models.Edition.objects.create(\n title=\"Example Edition\",\n remote_id=\"https://example.com/book/1\",\n parent_work=self.work,\n )\n models.SiteSettings.objects.create()\n\n def test_tag_page(self):\n \"\"\" there are so many views, this just makes sure it LOADS \"\"\"\n view = views.Tag.as_view()\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n tag = models.Tag.objects.create(name=\"hi there\")\n models.UserTag.objects.create(tag=tag, user=self.local_user, book=self.book)\n request = self.factory.get(\"\")\n with patch(\"bookwyrm.views.tag.is_api_request\") as is_api:\n is_api.return_value = False\n result = view(request, tag.identifier)\n self.assertIsInstance(result, TemplateResponse)\n result.render()\n self.assertEqual(result.status_code, 200)\n\n request = self.factory.get(\"\")\n with patch(\"bookwyrm.views.tag.is_api_request\") as is_api:\n is_api.return_value = True\n result = view(request, tag.identifier)\n self.assertIsInstance(result, ActivitypubResponse)\n self.assertEqual(result.status_code, 200)\n\n def test_tag_page_activitypub_page(self):\n \"\"\" there are so many views, this just makes sure it LOADS \"\"\"\n view = views.Tag.as_view()\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n tag = models.Tag.objects.create(name=\"hi there\")\n models.UserTag.objects.create(tag=tag, user=self.local_user, book=self.book)\n request = self.factory.get(\"\", {\"page\": 1})\n with patch(\"bookwyrm.views.tag.is_api_request\") as is_api:\n is_api.return_value = True\n result = view(request, tag.identifier)\n self.assertIsInstance(result, ActivitypubResponse)\n self.assertEqual(result.status_code, 200)\n\n def test_tag(self):\n \"\"\" add a tag to a book \"\"\"\n view = views.AddTag.as_view()\n request = self.factory.post(\n \"\",\n {\n \"name\": \"A Tag!?\",\n \"book\": self.book.id,\n },\n )\n request.user = self.local_user\n\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n view(request)\n\n tag = models.Tag.objects.get()\n user_tag = models.UserTag.objects.get()\n self.assertEqual(tag.name, \"A Tag!?\")\n self.assertEqual(tag.identifier, \"A+Tag%21%3F\")\n self.assertEqual(user_tag.user, self.local_user)\n self.assertEqual(user_tag.book, self.book)\n\n def test_untag(self):\n \"\"\" remove a tag from a book \"\"\"\n view = views.RemoveTag.as_view()\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n tag = models.Tag.objects.create(name=\"A Tag!?\")\n models.UserTag.objects.create(user=self.local_user, book=self.book, tag=tag)\n request = self.factory.post(\n \"\",\n {\n \"user\": self.local_user.id,\n \"book\": self.book.id,\n \"name\": tag.name,\n },\n )\n request.user = self.local_user\n\n with patch(\"bookwyrm.models.activitypub_mixin.broadcast_task.delay\"):\n view(request)\n\n self.assertTrue(models.Tag.objects.filter(name=\"A Tag!?\").exists())\n self.assertFalse(models.UserTag.objects.exists())\n","sub_path":"bookwyrm/tests/views/test_tag.py","file_name":"test_tag.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"465958204","text":"\"\"\"\nO Sr. Manoel Joaquim expandiu seus negócios para além dos negócios de 1,99 e agora possui uma loja de conveniências.\nFaça um programa que implemente uma caixa registradora rudimentar. O programa deverá receber um número desconhecido\nde valores referentes aos preços das mercadorias.\nUm valor zero deve ser informado pelo operador para indicar o final da compra.\nO programa deve então mostrar o total da compra e perguntar o valor em dinheiro que o cliente forneceu, para então\ncalcular e mostrar o valor do troco.\nApós esta operação, o programa deverá voltar ao ponto inicial, para registrar a próxima compra.\nA saída deve ser conforme o exemplo abaixo:\nLojas Tabajara \nProduto 1: R$ 3.20\nProduto 2: R$ 5.80\nProduto 3: R$ 0\nTotal: R$ 9.00\nDinheiro: R$ 20.00\nTroco: R$ 11.00\n\"\"\"\ncont = 1\ntotal = 0.0\n\nwhile True:\n print('-=' * 15)\n print('Lojas Tabajara'.center(30))\n print('-=' * 15)\n while True:\n while True:\n try:\n valor = float(input(f'Produto {cont}: R$'))\n break\n except ValueError:\n print('Digite apenas números!\\n')\n cont += 1\n if valor == 0:\n cont = 1\n break\n\n total += valor\n\n print('-' * 30)\n print(f'Total: R${total:.2f}')\n print('-' * 30)\n dinheiro = float(input('Dinheiro: R$'))\n print('-' * 30)\n troco = dinheiro - total\n print(f'Troco: R${troco:.2f}')\n","sub_path":"03_Estrutura_de_Repeticao/31-CaixaRegistradora.py","file_name":"31-CaixaRegistradora.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92554575","text":"from django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, HttpRequest, HttpResponse, JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\nfrom files.forms import DocumentForm\nfrom files.models import Document\nfrom files.views import *\nfrom pprint import pprint\nimport json\nimport string\nimport random\n\nfrom models import Histogram, LinearRegression, Plot, PlotDetails, SummaryStats\nfrom app.utilities import error_response, success_response, SUCCESS, FAILURE\n\n\nSTATS = 'stats'\nLINE = 'line'\nSCATTER = '2d_scatter'\nSCATTER3D = '3d_scatter'\nHISTOGRAM = 'histogram'\nREGRESSION = 'regression'\n\nMULTIPLE_X_COLUMNS_SELECTED = \"Please select only one column for X axis\"\n\ndef default_name():\n \"\"\"\n Helper to return default name string\n \"\"\"\n return 'default_' + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))\n\ndef handle_compute_stats(request):\n data = json.loads(request.body)\n print(data)\n error_status, errors = error_check_stats(data)\n if error_status == 1:\n return JsonResponse({\"status\": -1, \"errors\": errors})\n column_locations = data['file_headers']\n selection = data['stats_types']\n title = data['name']\n \"\"\"\n if not title: # provide default title with random string\n title = default_name()\n \"\"\"\n stats = SummaryStats.generate_stats(column_locations, selection, title, request.user.id)\n return JsonResponse(stats)\n\ndef error_check_stats(data):\n \"\"\"\n Checks valid input and selections for stats\n \"\"\"\n error = 0;\n error_strs = [];\n if not data['file_headers']:\n error = 1\n error_strs.append('Please select header(s) for the selected files')\n if not data['stats_types']:\n error = 1\n error_strs.append('Please select stats to compute for the selected files')\n return (error, error_strs)\n\ndef error_check_histogram(data):\n \"\"\"\n Checks valid input and selections for histogram\n \"\"\"\n error = 0;\n error_strs = [];\n if not data['x_points']:\n error = 1\n error_strs.append(\"Please select header(s) for the histogram\")\n elif len(data['x_points']) > 1:\n error = 1\n error_strs.append(\"Please select only one header for the histogram\")\n if not data['width']:\n error = 1\n error_strs.append(\"Please specify bin width\")\n elif data['width'] <= 0:\n error = 1\n error_strs.append(\"Please specify a positive bin width\")\n return (error, error_strs)\n\ndef error_check_data(data):\n \"\"\"\n Checks valid input and selections for plots\n \"\"\"\n error = 0;\n error_strs = [];\n\n if len(data['x_points']) == 0:\n error = 1\n error_strs.append(\"Please select header(s) for X axis\")\n elif len(data['x_points']) > 1:\n error = 1\n error_strs.append(MULTIPLE_X_COLUMNS_SELECTED)\n if len(data['y_points']) <= 0:\n error = 1\n error_strs.append(\"Please select header(s) for Y axis\")\n if data['type'] == SCATTER3D:\n if len(data['y_points']) > 1:\n error = 1\n error_strs.append(\"Please select only one column for Y axis for 3D scatter plot\")\n if len(data['z_points']) == 0:\n error = 1\n error_strs.append(\"Please select header(s) for Z axis\")\n if data['type'] == REGRESSION:\n if len(data['y_points']) > 1:\n error = 1\n error_strs.append(\"Please select only one column for Y axis for regression plot\")\n return (error, error_strs)\n\ndef handle_compute_plot(request):\n data = json.loads(request.body)\n error_status, errors = error_check_data(data)\n if error_status == 1:\n return JsonResponse({\"status\": -1, \"errors\": errors})\n \"\"\"\n if not data['name']: # provide default title with random string\n data['name'] = default_name()\n \"\"\"\n data['x_points'] = data['x_points'][0]\n if data['type'] == SCATTER3D:\n details = PlotDetails(\n data['type'],\n data['name'],\n data['x_label'],\n data['y_label'],\n data['x_points'],\n data['y_points'],\n data['z_label'],\n data['z_points']\n )\n else:\n details = PlotDetails(\n data['type'],\n data['name'],\n data['x_label'],\n data['y_label'],\n data['x_points'],\n data['y_points']\n )\n new_plot = Plot.save_plot(request.user.id, details)\n plot = Plot.generate_plot(request.user.id, details)\n if 'errors' in plot.values():\n return error_response(plot['errors'])\n plot['id'] = new_plot.id\n return JsonResponse(plot)\n\ndef handle_compute_regression(request):\n data = json.loads(request.body)\n error_status, errors = error_check_data(data)\n if error_status == 1:\n return JsonResponse({\"status\": -1, \"errors\": errors})\n \"\"\"\n if not data['name']: # provide default title with random string\n data['name'] = default_name()\n \"\"\"\n data['x_points'] = data['x_points'][0]\n details = PlotDetails(\n data['type'],\n data['name'],\n data['x_label'],\n data['y_label'],\n data['x_points'],\n data['y_points']\n )\n regression = LinearRegression.generate_reg(request.user.id, details)\n if 'errors' in regression.values():\n return error_response(regression['errors'])\n return JsonResponse(regression)\n\ndef handle_compute_histogram(request):\n data = json.loads(request.body)\n print(data)\n error_status, errors = error_check_histogram(data)\n if error_status == 1:\n return JsonResponse({\"status\": -1, \"errors\": errors})\n \"\"\"\n if not data['name']: # provide default title with random string\n data['name'] = default_name()\n \"\"\"\n histogram = Histogram.generate_histogram(\n request.user.id,\n data['x_points'][0],\n data['width'],\n data['name'],\n data['x_label'],\n data['y_label']\n )\n if 'errors' in histogram.values():\n return error_response(histogram['errors'])\n return JsonResponse(histogram)\n\ndef handle_compute(request):\n data = json.loads(request.body)\n #print \"DATA: \", data\n compute_type = data['type']\n if compute_type == STATS:\n return handle_compute_stats(request)\n else:\n if compute_type == SCATTER or compute_type == LINE:\n return handle_compute_plot(request)\n elif compute_type == SCATTER3D:\n return handle_compute_plot(request)\n elif compute_type == REGRESSION:\n return handle_compute_regression(request)\n elif compute_type == HISTOGRAM:\n return handle_compute_histogram(request)\n return JsonResponse({\"foo\": \"bar\"})\n\ndef list_computations(request):\n computations = {}\n computations['stats'] = SummaryStats.get_user_stats(request.user.id)\n computations['plots'] = Plot.get_user_plots(request.user.id)\n return JsonResponse(computations)\n\ndef handle_get_panes(account):\n panes = []\n p1 = []\n p2 = []\n stats = SummaryStats.get_user_stats(account)\n plots = Plot.get_user_plots(account)\n histograms = Histogram.get_user_histograms(account)\n regressions = LinearRegression.get_user_regressions(account)\n while len(stats) + len(plots) > 0:\n if len(stats) == 0:\n p1 += plots\n break\n elif len(plots) == 0:\n p1 += stats\n break\n elif stats[0]['timestamp'] > plots[0]['timestamp']:\n p1.append(stats.pop(0))\n else:\n p1.append(plots.pop(0))\n while len(histograms) + len(regressions) > 0:\n if len(histograms) == 0:\n p2 += regressions\n break\n elif len(regressions) == 0:\n p2 += histograms\n break\n elif histograms[0]['timestamp'] > regressions[0]['timestamp']:\n p2.append(histograms.pop(0))\n else:\n p2.append(regressions.pop(0))\n while len(p1) + len(p2) > 0:\n if len(p1) == 0:\n panes += p2\n break\n elif len(p2) == 0:\n panes += p1\n break\n elif p1[0]['timestamp'] > p2[0]['timestamp']:\n panes.append(p1.pop(0))\n else:\n panes.append(p2.pop(0))\n return panes\n\ndef handle_delete(request):\n data = json.loads(request.body)\n compute_type = data['type']\n if compute_type == STATS:\n SummaryStats.remove_user_stat(data['id'])\n return JsonResponse({\"foo\": \"bar\"})\n elif compute_type == SCATTER or compute_type == LINE or compute_type == SCATTER3D:\n Plot.remove_user_plot(data['id'])\n return JsonResponse({\"foo\": \"bar\"})\n elif compute_type == REGRESSION:\n LinearRegression.remove_user_regression(data['id'])\n return JsonResponse({\"foo\": \"bar\"})\n elif compute_type == HISTOGRAM:\n Histogram.remove_user_histogram(data['id'])\n return JsonResponse({\"foo\": \"bar\"})\n else:\n return JsonResponse({\"foo\": \"bar\"})\n\ndef clear_computations(request):\n errors = []\n SummaryStats.clear_stats()\n Plot.clear_plots()\n LinearRegression.clear_regressions()\n Histogram.clear_histograms()\n if SummaryStats.objects.all().count():\n errors.append('Failed to clear all summary stats')\n if Plot.objects.all().count():\n errors.append('Failed to clear all scatter plots')\n if LinearRegression.objects.all().count():\n errors.append('Failed to clear all linear regressions')\n if Histogram.objects.all().count():\n errors.append('Failed to clear all histograms')\n if len(errors):\n return error_response(errors)\n else:\n return success_response([],[])\n","sub_path":"compute/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"192970029","text":"import sys\nimport xlrd\nskipRow = 4\n\ndef ReadOldFile(OldFilePath):\n print(\"=== Read Excel ===================================\")\n WorkBook = xlrd.open_workbook(OldFilePath)\n print(\"WorkBook pointer:\", WorkBook)\n AllSheetName = WorkBook.sheet_names()\n #------------------------------------\n WorkBookDict = {} #inner has PNAME DICT, inner PNAME has test(key) result(value)\n \n PnameEmpIdDict = {}\n for SheetName in AllSheetName:\n print(\"Process SheetName:\",SheetName)\n WorkSheet = WorkBook.sheet_by_name(SheetName)\n WorkBookDict,PnameEmpIdDict = AddPNameDict(WorkSheet,WorkBookDict,PnameEmpIdDict)\n return WorkBook,WorkBookDict,PnameEmpIdDict\n\ndef AddPNameDict(WorkSheet,WorkBookDict,PnameEmpIdDict):\n for i in range(WorkSheet.nrows):\n if i == skipRow-3:\n HeadCol = WorkSheet.row_values(i)\n continue\n if i>=skipRow: #Table Value\n \n RowList = WorkSheet.row_values(i)\n PNAME = RowList[4]\n #---------------------------------\n if PNAME not in WorkBookDict:\n WorkBookDict[PNAME] = {}\n for idx in range(13,len(HeadCol)):\n Col = HeadCol[idx]\n Value = RowList[idx]\n WorkBookDict[PNAME][Col] = Value\n PnameEmpIdDict[PNAME] = RowList[2] \n #print(PnameEmpIdDict)\n return WorkBookDict,PnameEmpIdDict\n\n#ReadOldFile(OldFilePath)\n\n\n\n","sub_path":"Model/ReadCore.py","file_name":"ReadCore.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"499581410","text":"# Problem from Hackerrank\n# https://www.hackerrank.com/challenges/qheap1/problem\n\n\n# Using not in and index is faster than checking manually using for loop\nimport heapq\n\n\ndef solution():\n Q = int(input())\n my_list = []\n delete_list = []\n for i in range(Q):\n query = input()\n if query.startswith('3'):\n while True:\n if my_list[0] not in delete_list:\n break\n pos = delete_list.index(my_list[0])\n delete_list.pop(pos)\n heapq.heappop(my_list)\n\n print(my_list[0])\n else:\n command, param = map(int, query.split())\n if command == 1:\n heapq.heappush(my_list, param)\n else:\n delete_list.append(param)\n\n\nsolution()\n\n\n#\n# from queue import PriorityQueue\n#\n# def main():\n# n = int(input())\n# q = PriorityQueue()\n# remove = []\n# for i in range(n):\n# line = list(map(int, input().split()))\n# if line[0] == 1:\n# q.put(line[1])\n# elif line[0] == 2:\n# remove.append(line[1])\n# else:\n# while q.queue[0] in remove:\n# remove.pop(remove.index(q.get()))\n# print(q.queue[0])\n#\n# if __name__ == '__main__':\n# main()","sub_path":"Blue/Session 08 - Heap/Hackerrank_qheap1.py","file_name":"Hackerrank_qheap1.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"103571301","text":"import arcpy\r\nfrom openpyxl import Workbook\r\nfrom openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font\r\nfrom datetime import datetime\r\n\r\n\r\nclass clsField(object):\r\n \"\"\" Class to hold properties and behavior of the output fields\r\n \"\"\"\r\n @property\r\n def alias(self):\r\n return self._field.aliasName\r\n\r\n @property\r\n def name(self):\r\n return self._field.name\r\n\r\n @property\r\n def domain(self):\r\n return self._field.domain\r\n\r\n @property\r\n def type(self):\r\n return self._field.type\r\n\r\n @property\r\n def length(self):\r\n return self._field.length\r\n\r\n def __init__(self, f, i, subtypes):\r\n \"\"\" Create the object from a describe field object\r\n \"\"\"\r\n self.index = None\r\n self._field = f\r\n self.subtype_field = ''\r\n self.domain_desc = {}\r\n self.subtype_desc = {}\r\n self.index = i\r\n\r\n for st_key, st_val in subtypes.iteritems():\r\n if st_val['SubtypeField'] == f.name:\r\n self.subtype_desc[st_key] = st_val['Name']\r\n self.subtype_field = f.name\r\n for k, v in st_val['FieldValues'].iteritems():\r\n if k == f.name:\r\n if len(v) == 2:\r\n if v[1]:\r\n self.domain_desc[st_key]= v[1].codedValues\r\n self.subtype_field = st_val['SubtypeField']\r\n\r\n def __repr__(self):\r\n \"\"\" Nice representation for debugging \"\"\"\r\n return ''.format(self.name,\r\n self.alias,\r\n self.domain_desc)\r\n\r\n def updateValue(self, row, fields):\r\n \"\"\" Update value based on domain/subtypes \"\"\"\r\n value = row[self.index]\r\n if self.subtype_field:\r\n subtype_val = row[fields.index(self.subtype_field)]\r\n else:\r\n subtype_val = 0\r\n\r\n if self.subtype_desc:\r\n value = self.subtype_desc[row[self.index]]\r\n\r\n if self.domain_desc:\r\n try:\r\n value = self.domain_desc[subtype_val][row[self.index]]\r\n except:\r\n pass # not all subtypes will have domain\r\n\r\n return value\r\n\r\ndef get_field_defs(in_table, use_domain_desc):\r\n desc = arcpy.Describe(in_table)\r\n\r\n subtypes ={}\r\n if use_domain_desc:\r\n subtypes = arcpy.da.ListSubtypes(in_table)\r\n\r\n fields = []\r\n for i, field in enumerate([f for f in desc.fields\r\n if f.type in [\"Date\",\"Double\",\"Guid\",\r\n \"Integer\",\"OID\",\"Single\",\r\n \"SmallInteger\",\"String\"]]):\r\n fields.append(clsField(field, i, subtypes))\r\n\r\n return fields\r\n\r\n\r\n\r\n \r\ndef table_to_excel(in_table, output, use_field_alias=False, use_domain_desc=False):\r\n\r\n currentDateTime = datetime.now()\r\n expirationDate = datetime(2017, 7,7)\r\n\r\n if expirationDate < currentDateTime:\r\n arcpy.AddMessage(\"\\n\\nThis script has expired and must be renewed for further use. Please contact Justin Hawley at justinhawley01@gmail.com\\n\\n\")\r\n return\r\n fieldNames_forExcel = []\r\n wb = Workbook()\r\n ws = wb.active\r\n #font = Font(name='Calibri',size=11,bold=True,italic=False,vertAlign=None,underline='none',strike=False,color='FF000000')\r\n \r\n arcpy.AddMessage(\"Creating Excel file here: \" + output)\r\n\r\n fields = get_field_defs(in_table, use_domain_desc)\r\n field_names = [i.name for i in fields]\r\n\r\n \r\n checkedFields = arcpy.GetParameter(4)\r\n stringCheckedFields = []\r\n\r\n\r\n arcpy.AddMessage(\"\\n\")\r\n\r\n if len(checkedFields) > 0:\r\n for check in checkedFields:\r\n stringCheckedFields.append(str(check))\r\n for field in fields:\r\n if (use_field_alias == \"true\"):\r\n if str(field.name) in stringCheckedFields:\r\n fieldNames_forExcel.append(field.alias)\r\n else:\r\n if str(field.name) in stringCheckedFields:\r\n fieldNames_forExcel.append(field.name)\r\n else:\r\n stringCheckedFields = field_names\r\n if use_field_alias == True:\r\n fieldNames_forExcel = [i.alias for i in fields]\r\n else:\r\n fieldNames_forExcel = [i.name for i in fields]\r\n\r\n\r\n inputDesc = arcpy.Describe(in_table)\r\n sheetName = arcpy.GetParameterAsText(5)\r\n if sheetName == \"\":\r\n ws.title = inputDesc.name\r\n else:\r\n ws.title = sheetName\r\n \r\n ws.append(fieldNames_forExcel)\r\n \r\n columnList = list(ws.column_dimensions)\r\n \r\n excelFieldList = list(ws)\r\n \r\n for excelField in excelFieldList:\r\n for field in excelField:\r\n field.font = Font(bold=True)\r\n field.alignment=Alignment(horizontal='center')\r\n ws.column_dimensions[field.column].width = 25\r\n \r\n \r\n with arcpy.da.SearchCursor(in_table, stringCheckedFields) as cursor: #(field_names)\r\n for row in cursor:\r\n dataRowList = []\r\n for col_index, value in enumerate(row):\r\n if (fields[col_index].domain_desc or fields[col_index].subtype_desc):\r\n #value = fields[col_index].updateValue(row, field_names)\r\n value = fields[col_index].updateValue(row, stringCheckedFields)\r\n dataRowList.append(value)\r\n ws.append(dataRowList)\r\n \r\n \r\n #wb.save(\"sample.xlsx\")\r\n wb.save(output)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n table_to_excel(arcpy.GetParameter(0), arcpy.GetParameterAsText(1), arcpy.GetParameterAsText(2), arcpy.GetParameterAsText(3))\r\n","sub_path":"ExportToXLSX.py","file_name":"ExportToXLSX.py","file_ext":"py","file_size_in_byte":5802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"601466075","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function\n\n\n__doc__ = '''\\\nСистемная таблица Meta для хранения версий схемы БД\n'''\n\n\ndef upgrade(conn):\n sql = [\n # Создаём таблицу для хранения метаинформации\n '''\\\ncreate table if not exists `Meta` (\n `name` varchar(100) not null,\n `value` text,\n primary key (`name`)\n)\n''',\n # Записываем начальную версию 0 схемы БД\n '''\\\ninsert into `Meta` (`name`, `value`)\nvalues (\"schema_version\", \"0\")\non duplicate key update `value` = \"0\"\n''',\n # Записываем тип схемы БД\n '''\\\ninsert into `Meta` (`name`, `value`)\nvalues (\"schema_type\", \"trfu\")\non duplicate key update `value` = \"trfu\"\n''',\n ]\n c = conn.cursor()\n for s in sql:\n c.execute(s)\n\n\ndef downgrade(conn):\n sql = [\n # Удаляем таблицу метаинформации\n '''\\\ndrop table `Meta`\n''',\n ]\n c = conn.cursor()\n for s in sql:\n c.execute(s)\n\n","sub_path":"trfu/updates/db001.py","file_name":"db001.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"419214859","text":"import numpy as np\nimport pandas as pd\nimport yaml\nimport logging\nimport sys\nimport psycopg2\nimport datetime\nimport json\nimport pdb\nimport uuid\nimport metta\n\nfrom . import setup_environment\nfrom .features import class_map\n\n# inherit format from root level logger (specified in eis/run.py)\nlog = logging.getLogger(__name__)\n\ntry:\n engine = setup_environment.get_database()\n db_conn = engine.raw_connection()\n log.debug('Connected to the database')\nexcept:\n log.warning('Could not connect to the database')\n raise\n\n\ndef change_schema(schema):\n db_conn.cursor().execute(\"SET SCHEMA '{}'\".format(schema))\n log.debug('Changed the schema to {}'.format(schema))\n return None\n\ndef enter_into_db(timestamp, config, auc):\n query = (\"INSERT INTO models.full (id_timestamp, config, auc) \"\n \"VALUES ('{}', '{}', {}) \".format(timestamp, json.dumps(config), auc))\n db_conn.cursor().execute(query)\n db_conn.commit()\n return None\n\ndef generate_matrix_id(config):\n blocks = '-'.join(config[\"officer_features\"])\n time_aggregations = '-'.join(config[\"timegated_feature_lookback_duration\"])\n \n return blocks + ' ' + time_aggregations\n\ndef store_matrices(to_save, config):\n date_fmt = \"%Y-%m-%d\"\n label_name = \"_\".join(sorted(to_save[\"config\"][\"officer_labels\"]))\n train_df = pd.DataFrame(to_save[\"train_x\"], columns=to_save[\"features\"], index=to_save[\"officer_id_train\"])\n train_df[label_name] = to_save[\"train_y\"]\n train_config = {'start_time': datetime.datetime.strptime(to_save[\"config\"][\"train_start_date\"], date_fmt),\n 'end_time': datetime.datetime.strptime(to_save[\"config\"][\"train_end_date\"], date_fmt),\n 'prediction_window': to_save[\"config\"][\"prediction_window\"],\n 'label_name': label_name,\n 'feature_names': sorted(to_save[\"features\"].tolist()),\n 'unit_id': to_save[\"officer_id_train\"].tolist(),\n 'matrix_id': generate_matrix_id(config) }\n\n test_df = pd.DataFrame(to_save[\"test_x\"], columns=to_save[\"features\"], index=to_save[\"officer_id_test\"])\n test_df[label_name] = to_save[\"test_y\"]\n test_config = {'start_time': datetime.datetime.strptime(to_save[\"config\"][\"test_start_date\"], date_fmt),\n 'end_time': datetime.datetime.strptime(to_save[\"config\"][\"test_end_date\"], date_fmt),\n 'prediction_window': to_save[\"config\"][\"prediction_window\"],\n 'label_name': label_name,\n 'feature_names': sorted(to_save[\"features\"].tolist()),\n 'unit_id': to_save[\"officer_id_test\"].tolist(),\n 'matrix_id': generate_matrix_id(config)}\n\n metta.archive_train_test(train_config, train_df,\n test_config, test_df,\n directory = config[\"directory\"], format = 'hdf5')\n \n return None\n\ndef store_model_info( timestamp, batch_comment, batch_timestamp, config, paths={}):\n \"\"\" Write model configuration into the results.model table\n\n :param str timestamp: the timestamp at which this model was run.\n :param str batch_comment: the user-defined comment string.\n :param str batch_timestamp: the timestamp that this batch of models was run.\n :param dict config: the configuration dictionary that contains all model parameters.\n :param str filename: the path and name of the pickle file.\n \"\"\"\n\n # set some parameters model comment\n model_comment = config['model_comment'] # TODO: feature not implemented, should read from config.\n\n # insert into the models table.\n query = ( \" INSERT INTO results.models( run_time, batch_run_time, model_type, model_parameters, model_comment, batch_comment, config, test) \"\n \" VALUES( %s, %s, %s, %s, %s, %s, %s, %s )\" )\n\n db_conn.cursor().execute(query, ( timestamp,\n batch_timestamp,\n config[\"model\"],\n json.dumps(config[\"parameters\"]),\n model_comment,\n batch_comment,\n json.dumps(config),\n config[\"test_flag\"]\n ) )\n db_conn.commit()\n\n ## add model group_id\n add_model_group_id( timestamp )\n\n return None\n\ndef add_model_group_id(timestamp):\n \"\"\" \n Set model group id in results.models for the model given the same model type, model parameters, prediction window and list of features\n Using the store procedure: get_model_group_id\n \n :param str timestamp: the timestamp at which the model was run \n \"\"\"\n\n query = (\" UPDATE results.models \" \n \" SET model_group_id = get_model_group_id(model_type, model_parameters, (config -> 'prediction_window') :: TEXT, \"\n \" ARRAY(SELECT jsonb_array_elements_text(config -> 'officer_features') \"\n \" ORDER BY 1) :: TEXT []) \"\n \" WHERE run_time = '{}'::timestamp \".format(timestamp)) \n db_conn.cursor().execute(query)\n db_conn.commit()\n\n return None\n\ndef store_feature_importances( timestamp, to_save):\n \"\"\" Write the feature importances of the model into the results schema\n\n :param str timestamp: the timestamp at which this model was run.\n :param dict to_save: \n \"\"\"\n\n # get the model primary key corresponding to this timestamp.\n query = ( \" SELECT model_id FROM results.models WHERE models.run_time = '{}'::timestamp \".format( timestamp ) )\n cur = db_conn.cursor()\n cur.execute(query)\n this_model_id = cur.fetchone()\n this_model_id = this_model_id[0]\n\n # Create pandas db of features importance\n dataframe_for_insert = pd.DataFrame( { \"model_id\": this_model_id,\n \"feature\": to_save[\"feature_importances_names\"],\n \"feature_importance\": to_save[\"feature_importances\"] })\n # Insert\n dataframe_for_insert.to_sql( \"feature_importances\", engine, if_exists=\"append\", schema=\"results\", index=False )\n\n return None\n\ndef obtain_top5_risk(row):\n ind = sorted(range(len(row)), key=lambda i: abs(row[i]), reverse=True)[:min(len(row),5) ]\n important_names = [row.index[i] if row[i] > 0 else '-{}'.format(row.index[i]) if row[i] < 0 else None for i in ind ]\n return [ important_names[i] if i < len(important_names) else None for i in range(5) ]\n \n\ndef store_individual_feature_importances(timestamp, to_save):\n\n query = ( \" SELECT model_id FROM results.models WHERE models.run_time = '{}'::timestamp \".format( timestamp ) )\n cur = db_conn.cursor()\n cur.execute(query)\n this_model_id = cur.fetchone()\n this_model_id = this_model_id[0]\n\n # get json of individual feature importances into df\n df_individual_importances = pd.DataFrame(to_save[\"individual_importances\"])\n df_individual_importances.columns = to_save[\"feature_importances_names\"]\n # Obtain the top 5 risks\n df_individual_importances[\"risks\"] = df_individual_importances.apply(lambda x: obtain_top5_risk(x), axis=1)\n df_individual_importances['officer_id_test'] = to_save['officer_id_test']\n df_risks = pd.DataFrame(df_individual_importances[\"risks\"].tolist(), )\n df_risks[\"unit_id\"] = df_individual_importances[\"officer_id_test\"]\n df_risks.columns = [\"risk_1\", \"risk_2\",\"risk_3\",\"risk_4\",\"risk_5\",\"unit_id\"]\n df_risks[\"model_id\"] = this_model_id\n\n df_risks.to_sql( \"individual_importances\", engine, if_exists=\"append\", schema=\"results\", index=False )\n\ndef store_prediction_info( timestamp, unit_id_train, unit_id_test, unit_predictions, unit_labels, my_exp_config ):\n \"\"\" Write the model predictions (officer or dispatch risk scores) to the results schema.\n\n :param str timestamp: the timestamp at which this model was run.\n :param list unit_id_train: list of unit id's used in the training set.\n :param list unit_id_test: list of unit id's used in the test set.\n :param list unit_predictions: list of risk scores.\n :param list unit_labels: list of true labels.\n :param dict my_exp_config: configuration of the experiment\n \"\"\"\n\n # get the model primary key corresponding to this timestamp.\n query = ( \" SELECT model_id FROM results.models WHERE models.run_time = '{}'::timestamp \".format( timestamp ) )\n cur = db_conn.cursor()\n cur.execute(query)\n this_model_id = cur.fetchone()\n this_model_id = this_model_id[0]\n\n # round unit_id's to integer type.\n unit_id_train = [int(unit_id) for unit_id in unit_id_train]\n unit_id_test = [int(unit_id) for unit_id in unit_id_test]\n unit_labels = [int(unit_id) for unit_id in unit_labels]\n\n # append data into predictions table. there is probably a faster way to do this than put it into a\n # dataframe and then use .to_sql but this works for now.\n dataframe_for_insert = pd.DataFrame( { \"model_id\": this_model_id,\n \"entity_id\": unit_id_test,\n \"score\": unit_predictions,\n \"as_of_date\": my_exp_config['test_end_date'],\n \"label_value\": unit_labels } )\n \n # Add rank columns\n dataframe_for_insert['rank_abs'] = dataframe_for_insert['score'].rank(method='dense', ascending=False)\n dataframe_for_insert['rank_pct'] = dataframe_for_insert['score'].rank(method='dense', ascending=False, pct=True)\n\n dataframe_for_insert.to_sql( \"predictions\", engine, if_exists=\"append\", schema=\"results\", index=False )\n\n return None\n\ndef store_evaluation_metrics( timestamp, evaluation, metric, as_of_date, parameter=None, comment=None):\n \"\"\" Write the model evaluation metrics into the results schema\n\n :param str timestamp: the timestamp at which this model was run.\n :param dict evaluation_metrics: dictionary whose keys correspond to metric names in the features.evaluations columns.\n \"\"\"\n\n # get the model primary key corresponding to this timestamp.\n query = ( \" SELECT model_id FROM results.models WHERE models.run_time = '{}'::timestamp \".format( timestamp ) )\n cur = db_conn.cursor()\n cur.execute(query)\n this_model_id = cur.fetchone()\n this_model_id = this_model_id[0]\n\n #No parameter and no comment\n if parameter is None and comment is None:\n comment = 'Null'\n parameter = 'Null'\n query = ( \" INSERT INTO results.evaluations( model_id, metric, parameter, value, comment, as_of_date)\"\n \" VALUES( '{}', '{}', {}, '{}', {}, '{}'::timestamp) \".format( this_model_id,\n metric,\n parameter,\n evaluation,\n comment,\n as_of_date ) )\n\n #No parameter and a comment\n elif parameter is None and comment is not None:\n parameter = 'Null'\n query = ( \" INSERT INTO results.evaluations( model_id, metric, parameter, value, comment, as_of_date)\"\n \" VALUES( '{}', '{}', {}, '{}', '{}', '{}'::timestamp) \".format( this_model_id,\n metric,\n parameter,\n evaluation,\n comment,\n as_of_date ) )\n\n #No comment and a parameter\n elif parameter is not None and comment is None:\n comment = 'Null'\n query = ( \" INSERT INTO results.evaluations( model_id, metric, parameter, value, comment, as_of_date)\"\n \" VALUES( '{}', '{}', '{}', '{}', {}, '{}'::timestamp) \".format( this_model_id,\n metric,\n parameter,\n evaluation,\n comment,\n as_of_date ) )\n\n #A comment and a parameter\n elif parameter is not None and comment is not None:\n query = ( \" INSERT INTO results.evaluations( model_id, metric, parameter, value, comment)\"\n \" VALUES( '{}', '{}', '{}', '{}', '{}', '{}'::timestamp) \".format( this_model_id,\n metric,\n parameter,\n evaluation,\n comment,\n as_of_date ) )\n else:\n pass\n\n db_conn.cursor().execute(query)\n db_conn.commit()\n return None\n\n\ndef format_officer_ids(ids):\n formatted = [\"{}\".format(each_id) for each_id in ids]\n formatted = \", \".join(formatted)\n return formatted\n\n\ndef get_baseline(start_date, end_date):\n \"\"\"\n Gets EIS baseline - get officers that are flagged\n by the EIS at any point in the labelling window.\n\n Inputs:\n ids: officer ids\n start_date: beginning of training period\n end_date: end of training period\n\n Returns: dataframe with ids of those officers flagged by EIS\n\n Example:\n df_comparison = get_baseline('2010-01-01', '2011-01-01')\n \"\"\"\n\n query_flagged_officers = (\"SELECT DISTINCT officer_id from {} \"\n \"WHERE date_created >= '{}'::date \"\n \"AND date_created <='{}'::date\".format(\n config[\"eis_table\"],\n start_date,\n end_date))\n\n # TODO: have this check the actual 2016 EIS table\n #query_flagged_officers = ( \"SELECT DISTINCT officer_id \"\n # \"FROM officers_hub\" )\n\n df_eis_baseline = pd.read_sql(query_flagged_officers, con=con)\n\n return df_eis_baseline.dropna()\n\n\ndef get_interventions(ids, start_date, end_date):\n \"\"\"\n Gets whether or not an officer has an intervention after\n the EIS flags them.\n\n Inputs:\n ids: officer ids\n start_date: beginning of testing period\n end_date: end of testing period\n\n Returns: dataframe with ids and boolean value corresponding to if an\n officer was intervened on or not in the time period.\n \"\"\"\n\n intervened_officers = (\"select distinct officer_id from {} \"\n \"WHERE intervention != 'No Intervention Required' \"\n \"AND datecreated >= '{}'::date \"\n \"AND datecreated <='{}'::date \"\n \"AND officer_id in ({}) \").format(\n config[\"eis_table\"],\n start_date, end_date,\n format_officer_ids(ids))\n\n no_intervention_officers = (\"select distinct officer_id from {} \"\n \"WHERE intervention = 'No Intervention Required' \"\n \"AND datecreated >= '{}'::date \"\n \"AND datecreated <='{}'::date \"\n \"AND officer_id in ({}) \").format(\n config[\"eis_table\"],\n start_date, end_date,\n format_officer_ids(ids))\n\n # read the data from the database\n df_intervention = pd.read_sql(intervened_officers, con=db_conn)\n df_no_intervention = pd.read_sql(no_intervention_officers, con=db_conn)\n\n df_intervention[\"intervention\"] = 1\n df_action = df_intervention.merge(df_no_intervention, how='right', on='officer_id')\n df_action = df_action.fillna(0)\n\n return df_action\n\n\ndef get_labels_for_ids(ids, start_date, end_date):\n \"\"\"Get the labels for the specified officer_ids, for the specified time period\n\n Args:\n\n Returns:\n outcomes(pd.DataFrame):\n \"\"\"\n\n # required by FeatureLoader but not used in officer_labeller()\n fake_today = datetime.date.today()\n\n # load labelling and def_adverse from experiment config file\n exp_config = setup_environment.get_experiment_config()\n officer_labels = exp_config['officer_labels']\n\n return (FeatureLoader(start_date, end_date, fake_today)\n .officer_labeller(officer_labels, ids_to_label=ids))\n\n\ndef imputation_zero(df, ids):\n fulldf = pd.DataFrame(ids, columns=[\"officer_id\"] + [df.columns[0]])\n df[\"officer_id\"] = df.index\n newdf = df.merge(fulldf, how=\"right\", on=\"officer_id\")\n newdf = newdf.fillna(0)\n newdf[df.columns[0]] = newdf[df.columns[0] + \"_x\"] + newdf[df.columns[0] + \"_y\"]\n newdf = newdf.drop([df.columns[0] + \"_x\", df.columns[0] + \"_y\"], axis=1)\n newdf = newdf.set_index(\"officer_id\")\n return newdf\n\n\ndef imputation_mean(df, featurenames):\n try:\n newdf = df.set_index(\"officer_id\")\n except:\n newdf = df\n for i in range(len(newdf.columns)):\n this_col = newdf.columns[i]\n imp_dummy_name = \"imputation_{}\".format(this_col)\n newdf[imp_dummy_name] = newdf[this_col].isnull().map(lambda x: 1 if x == True else 0)\n newdf[this_col] = newdf[this_col].fillna(np.mean(newdf[this_col]))\n return newdf, newdf.columns.values\n\n\ndef convert_series(df):\n onecol = df.columns[0]\n numcols = len(df[onecol].iloc[0])\n newcols = [onecol + '_' + str(i) for i in range(numcols)]\n\n newdf = pd.DataFrame(columns=newcols, index=df.index)\n for i in range(len(df)):\n newdf.iloc[i] = df[onecol].iloc[i]\n\n return newdf.astype(int), newcols\n\n\ndef convert_categorical(feature_df, feature_columns):\n \"\"\"\n Convert a dataframe with columns containing categorical variables to\n a dataframe with dummy variables for each category.\n\n Args:\n feature_df(pd.DataFrame): A dataframe containing the features, some\n of which may be categorical\n feature_columns(list): A list of the feature column names\n\n Returns:\n feature_df_w_dummies(pd.DataFrame): The features dataframe, but with\n categorical features converted to dummy variables\n \"\"\"\n\n log.info('Converting categorical features to dummy variables')\n\n # note: feature names will be lowercased when returned from the db\n categorical_features = [name.lower() for name in class_map.find_categorical_features(feature_columns)]\n\n log.info('... {} categorical features'.format(len(categorical_features)))\n\n # add dummy variables to feature dataframe\n feature_df_w_dummies = pd.get_dummies(feature_df, columns=categorical_features, sparse=True)\n\n log.info('... {} dummy variables added'.format(len(feature_df_w_dummies.columns)\n - len(feature_df.columns)))\n\n return feature_df_w_dummies\n\nclass FeatureLoader():\n\n def __init__(self, start_date=None, end_date=None, end_label_date=None, table_name=None):\n\n self.start_date = start_date\n self.end_date = end_date\n self.end_label_date = end_label_date\n self.table_name = table_name\n\n\n\n\ndef get_dataset(start_date, end_date, prediction_window, officer_past_activity_window, features_list,\n label_list, features_table, labels_table, as_of_dates_to_use):\n '''\n This function returns dataset and labels to use for training / testing\n It is splitted in two queries:\n - query_labels: which joins the features table with labels table\n - query_active: using the first table created in query_labels, and returns it only \n for officers that are have any activity given the officer_past_activity_window\n \n Inputs:\n -------\n start_date: start date for selecting officers in features table\n end_date: end date for selecting officers in features table\n prediction_window: months, used for selecting labels proceding the as_of_date in features_table\n officer_past_activity_window: months, to select officers with activity preceding the as_of_date in features_table\n features_list: list of features to use\n label_list: outcome name to use \n features_table: name of the features table\n labels_table: name of the labels table \n '''\n features_list_string = \", \".join(['{}'.format(feature) for feature in features_list])\n label_list_string = \", \".join([\"'{}'\".format(label) for label in label_list])\n as_of_dates_string = \", \".join([\"'{}'\".format(as_of_date) for as_of_date in as_of_dates_to_use])\n # convert features to string for querying while replacing NULL values with ceros in sql\n features_coalesce = \", \".join(['coalesce(\"{0}\",0) as {0}'.format(feature) for feature in features_list])\n\n \n # First part of the query that joins the features table with labels table\n #NOTE: The lateral join with LIMIT 1 constraint is used for speed optimization \n # as we assign a positive label to the officers as soon as there is one designated event in the prediction windows\n query_labels = (\"\"\" WITH features_labels as ( \"\"\"\n \"\"\" SELECT officer_id, {0}, \"\"\"\n \"\"\" as_of_date, \"\"\" \n \"\"\" coalesce(outcome,0) as outcome \"\"\"\n \"\"\" FROM features.{2} f \"\"\"\n \"\"\" LEFT JOIN LATERAL ( \"\"\"\n \"\"\" SELECT 1 as outcome \"\"\"\n \"\"\" FROM features.{3} l \"\"\"\n \"\"\" WHERE f.officer_id = l.officer_id \"\"\"\n \"\"\" AND l.outcome_datetime - INTERVAL '{4}' <= f.as_of_date \"\"\"\n \"\"\" AND l.outcome_datetime > f.as_of_date \"\"\"\n \"\"\" AND l.event_datetime > f.as_of_date \"\"\"\n \"\"\" AND outcome in ({1}) LIMIT 1\"\"\"\n \"\"\" ) AS l ON TRUE \"\"\"\n \"\"\" WHERE f.as_of_date > '{5}'::date AND f.as_of_date <= '{6}' \"\"\"\n \"\"\" AND f.as_of_date in ({7}) )\"\"\"\n .format(features_coalesce,\n label_list_string,\n features_table,\n labels_table,\n prediction_window,\n start_date,\n end_date,\n as_of_dates_string))\n\n # We only want to train and test on officers that have been active (any logged activity in events_hub)\n # NOTE: it uses the feature_labels created in query_labels \n query_active = (\"\"\" SELECT officer_id, {0}, outcome \"\"\"\n \"\"\" FROM features_labels as f, \"\"\"\n \"\"\" LATERAL \"\"\"\n \"\"\" (SELECT 1 \"\"\"\n \"\"\" FROM staging.events_hub e \"\"\"\n \"\"\" WHERE f.officer_id = e.officer_id \"\"\"\n \"\"\" AND e.event_datetime + INTERVAL '{1}' > f.as_of_date \"\"\"\n \"\"\" AND e.event_datetime <= f.as_of_date \"\"\"\n \"\"\" LIMIT 1 ) sub; \"\"\"\n .format(features_list_string,\n officer_past_activity_window))\n \n # join both queries together and load data\n query = (query_labels + query_active)\n all_data = pd.read_sql(query, con=db_conn)\n\n \n query_dates = (\"\"\" SELECT distinct as_of_date as as_of_date\"\"\"\n \"\"\" FROM features.{0} \"\"\"\n \"\"\" WHERE as_of_date > '{1}'::date AND as_of_date <= '{2}' \"\"\"\n \"\"\" AND as_of_date in ({3}) \"\"\"\n .format(features_table,\n start_date,\n end_date,\n as_of_dates_string))\n\n as_of_dates_used = pd.read_sql(query_dates, con=db_conn)\n log.debug('as_of_dates_used: {}'.format(as_of_dates_used['as_of_date'].tolist()))\n \n # remove rows with only zero values\n features_list = [ feature.lower() for feature in features_list]\n\n ## TODO: remove all zero value columns\n #all_data = all_data.loc[~(all_data[features_list]==0).all(axis=1)]\n\n all_data = all_data.set_index('officer_id')\n log.debug('length of data_set: {}'.format(len(all_data)))\n log.debug('number of officers with adverse incident: {}'.format( all_data['outcome'].sum() ))\n return all_data[features_list], all_data.outcome\n\ndef grab_officer_data(features, start_date, end_date, end_label_date, labelling, table_name ):\n \"\"\"\n Function that defines the dataset.\n\n Inputs:\n -------\n features: list containing which features to use\n start_date: start date for selecting officers\n end_date: end date for selecting officers\n end_label_date: build features with respect to this date\n labelling: dict containing options to label officers\n by IA should be labelled, if False then only those investigated will\n be labelled\n \"\"\"\n\n start_date = start_date.strftime('%Y-%m-%d')\n end_date = end_date.strftime('%Y-%m-%d')\n log.debug(\"Calling FeatureLoader with: {},{},{},{}\".format(start_date, end_date, end_label_date, table_name))\n data = FeatureLoader(start_date, end_date, end_label_date, table_name)\n\n # get the officer labels and make them the key in the dataframe.\n officers = data.officer_labeller(labelling)\n officers.officer_id = officers.officer_id.astype(int)\n\n # select all the features which are set to True in the config file\n features_data = data.load_all_features( features, feature_type=\"officer\" )\n\n # join the data to the officer labels.\n dataset = officers\n dataset = dataset.join( features_data, how='left', on=\"officer_id\" )\n dataset.set_index([\"officer_id\"], inplace=True )\n dataset = dataset.fillna(0)\n\n labels = dataset[\"adverse_by_ourdef\"].values\n feats = dataset.drop([\"adverse_by_ourdef\"], axis=1)\n ids = dataset.index.values\n\n # make sure we return a non-zero number of labelled officers\n assert sum(labels) > 0, 'Labelled officer selection returned no officers'\n\n log.debug(\"Dataset has {} rows and {} features\".format(\n len(labels), len(feats.columns)))\n\n return feats, labels, ids, features\n\n\ndef grab_dispatch_data(features, start_date, end_date, def_adverse, table_name):\n \"\"\"Function that returns the dataset to use in an experiment.\n\n Args:\n features: dict containing which features to use\n start_date(datetime.datetime): start date for selecting dispatch\n end_date(datetime.datetime): end date for selecting dispatch\n def_adverse: dict containing options for adverse incident definitions\n labelling: dict containing options to select which dispatches to use for labelling\n\n Returns:\n feats(pd.DataFrame): the array of features to train or test on\n labels(pd.DataFrame): n x 1 array with 0 / 1 adverse labels\n ids(pd.DataFrame): n x 1 array with dispatch ids\n featnames(list): the list of feature column names\n \"\"\"\n\n feature_loader = FeatureLoader(start_date = start_date,\n end_date = end_date,\n table_name = table_name)\n\n # select all the features which are set to True in the config file\n # NOTE: dict.items() is python 3 specific. for python 2 use dict.iteritems()\n features_to_use = [feat for feat, is_used in features.items() if is_used]\n\n features_df = feature_loader.load_all_features(features_to_use,\n feature_type = 'dispatch')\n # encode categorical features with dummy variables, and fill NAN with 0s\n dataset = convert_categorical(features_df, features_to_use)\n dataset = dataset.fillna(0)\n\n log.debug('... dataset dataframe is {} GB'.format(dataset.memory_usage().sum() / 1E9))\n\n # determine which labels to use based on def_adverse\n # note: need to lowercase the column name b/c postgres lowercases everything\n label_columns = [col.lower() for col in class_map.find_label_features(features_to_use)]\n def_adverse_to_label = {'accidents': 'LabelPreventable',\n 'useofforce': 'LabelUnjustified',\n 'complaint': 'LabelSustained'}\n label_cols_to_use = [def_adverse_to_label[key].lower() for key, is_true in def_adverse.items() if is_true]\n\n # select the active label columns, sum for each row, and set true when sum > 0\n labels = dataset[label_cols_to_use].sum(axis=1).apply(lambda x: x > 0)\n\n features = dataset.drop(label_columns, axis=1)\n ids = dataset.index\n feature_names = features.columns\n\n # make sure we return a non-zero number of labelled dispatches\n assert sum(labels.values) > 0, 'No dispatches were labelled adverse'\n\n log.debug(\"Dataset has {} rows and {} features\".format(\n len(labels), len(feature_names)))\n\n return features, labels, ids, feature_names\n","sub_path":"eis/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":29568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"100762189","text":"# This Python file uses the following encoding: utf-8\nimport fileinput\nimport re\nimport os\nimport time\nimport lxml\nfrom lxml import etree\n\n\"\"\"\nThis programs purpose is to extract entities from parsed texts on the basis of a given set of rules and write them sortedly\ninto an *.a2 file.\nIt is called with a *.txt file and later on opens the corresponding .xml-file in the same directory\n\"\"\"\n\nstart = time.time()\nlinestring = []\t\nlinestring_sentence = []\ncounter = 1\nrules = open(\"keywords_revised_deleted_out.txt\", \"r\")\t\t#open the given rule-book\nborders_end = 0\nphrase_counter = 0\nphrases_to_sort = [[]]\nfirst = False\nphrases_to_print = []\n\nfor line_a in fileinput.input():\n\tfile_name = os.path.splitext(fileinput.filename())[0]\t\t#get file-name without file-type extension\n\nfor line_b in rules:\n\trule_tofind = re.search(r'(\\w+[.]*|%)\\s[+]\\s(\\w+\\S*)', line_b)\t#for every line in the rule book read out the dependency relation and the keyword\n\tkeyword = rule_tofind.group(1)\n\trelation = rule_tofind.group(2)\n\ttree = etree.parse(file_name + \".txt.xml\")\t\t\t\t\t\t#make the .xml-file an object so as to enable deleting out all\n\troot = tree.getroot()\t\t\t\t\t\t\t\t\t\t\t#dependencies except the enhanced-plus-plus-dependencies\n\n\tfor dependencies in root.iter('dependencies'):\n\t\tif dependencies.get('type') != 'enhanced-plus-plus-dependencies':\n\t\t\tdependencies.getparent().remove(dependencies)\n\ttree.write('output.xml')\n\ttreenew = open('output.xml')\t\t\t\t\t\t\t\t\t#write the stripped tree into a new file\n\t\n\tif linestring == []:\t\t\t\t\t\t\t\t\t#turn it into on long string \n\t\tfor line_c in treenew :\n\t\t\tlinestring.append(line_c)\n\t\t\tjoined= ' '.join(linestring)\n\t\t\t\t\t\n\t\n\tfind_relation = re.findall(r'\\s*' + re.escape(keyword) + '\\s*(.*?).*?', joined, flags=re.DOTALL)\n\t\t\t\t\t\t#find every word where the keyword is the governor and stands in the rule-given relation to this word\n\t\t\t\t\t\t#output is a list of lists which in turn contain the words index, the word, and the sentence index of the next sentence\n\t\n\tphrase_list = []\t\t\t\n\tlooked_up = []\t\t\t\t\t\n\n\tfor head in find_relation:\t\t#find all dependency-subtrees of the found word, which the is the head of those subtrees\n\t\tphrase_list.append(head)\n\n\t\ttree = etree.parse(\"output.xml\")\t\t\t\t\t\t#make the .xml-file an object so as to enable deleting out all sentences but the one we found the relation in \n\t\troot = tree.getroot()\n\t\tfor sentence in root.iter('sentence'):\n\t\t\t\tif sentence.get('id') != str(int(head[2])-1):\n\t\t\t\t\tsentence.getparent().remove(sentence)\n\t\ttree.write('sentence.xml')\n\t\ttree_sentence = open('sentence.xml')\t\t\t\t\t\t\t\t\t#write the stripped tree into a new file\n\t\n\t\tfor line_d in tree_sentence :\t\t\t\t\t\t\t\t\t\t\t#turn it into on long string \n\t\t\tlinestring_sentence.append(line_d)\n\t\t\tjoined_sentence= ' '.join(linestring_sentence)\n\t\t\t\n\t\t\n\t\tfor word in phrase_list:\t\n\t\t\t\n\t\t\ttry:\n\t\t\t\tfind_phrase = re.findall(r'' + word[1] + '\\s*(.*?)', joined_sentence)\n\t\t\t\t# find every word, and its index, where the head is the governor\n\t\t\t\trelative_clauses = re.search(r'who|\\'\\,\\'|where|which|that', str(find_phrase)) #trigger for relative-clauses, which will be deleted out\n\t\t\t\tif relative_clauses:\n\t\t\t\t\tsorted_for_delete = sorted(find_phrase, key=lambda is_this_comma: int(is_this_comma[0]))\n\t\n\t\t\t\t\tgo_on = []\n\t\t\t\t\tfor comma_search in sorted_for_delete:\n\t\t\t\t\t\tif comma_search[1] in (\",\",\"who\",\"where\",\"which\",\"that\"):\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tgo_on.append(comma_search)\n\t\t\t\t\t\t\n\t\t\t\t\tfind_phrase = go_on\t\n\t\t\t\t\n\t\t\t\tlooked_up.append(word) #keep track of every word that was already searched for subtrees\n\n\t\t\t\tif find_phrase != []:\n\t\t\t\t\tfor i in range(len(find_phrase)):\n\t\t\t\t\t\tphrase_list.append(find_phrase[i-1])\t#append the found words to also find their subtrees\t\t\t\n\t\t\n\t\t\texcept IndexError:\t\t#if nothing is found there is no subtree. continue with the next word\n\t\t\t\tcontinue\t\n\t\t\t\n\t\tlinestring_sentence = []\n\t\t\t\n\t\tsorted_lookup = sorted(looked_up, key=lambda word: int(word[0])) #sort the whole subtree by word-index to get the word-phrase\n\t\t\n\t\tentities = open(file_name + \".a2\", \"a+\")\n\t\t\n\t\tphrase = []\n\t\t\n\t\t#instead of writing the found phrase directly into the output file, we collect every phrase that was found in the text to\n\t\t#sort them by onset in the text first\n\t\t#a list of lists is used, where every list will contain a line to be printed in the output-file\n\t\t\n\t\tfor entity in sorted_lookup:\n\t\t\tif entity[1] in [\"the\", \"from\", \"in\", \"-LRB-\", \"-RRB-\", \"a\"]: \t#delete articles, brackets and prepositions\n\t\t\t\tcontinue\n\t\t\telif entity[1] == \"and\":\t\t#if there is a conjunction open up a new list\n\t\t\t\tphrase_counter += 1\n\t\t\t\tphrases_to_sort.append([])\n\t\t\telse: \n\t\t\t\tphrases_to_sort[phrase_counter].append(entity)\t#add word into list\n\t\t\n\t\t#phrases_to_sort is just the mere collection of all the found word phrases in the text\n\t\t#phrases_to_print integrates the phrases in the necessary format of the lines in the output file\n\n\t\tfor i in range(len(phrases_to_sort)):\n\t\t\tphrases_to_print.append([])\n\t\t\tphrases_to_print[counter-1].append(\"Habitat \")\t\t#start the line with \"Habitat\"\n\t\t\t\n\t\t\tfor k in phrases_to_sort[i]:\t#for every word in the phrase find out its on- and offset\n\t\t\t\tborders = re.search(r'\\s*' + re.escape(k[1]) + '\\s*.*\\s*(\\d+)\\s*(\\d+)', joined_sentence)\n\t\t\t\t\n\t\t\t\tif first == False:\n\t\t\t\t\tborders_start = borders.group(1)\t\n\t\t\t\t\tphrases_to_print[counter-1].append(borders_start + \" \")\t\t#add to the line the onset of the first word\n\t\t\t\t\tfirst = True\n\t\t\t\t\n\t\t\t\tif int(borders_end) < int(borders.group(2)):\n\t\t\t\t\t\tborders_end = borders.group(2)\t\t\t#update the offset until the last word\n\n\t\t\tphrases_to_print[counter-1].append(borders_end + \"\\t\")\t#add to the line the offset of the last word\n\t\t\t\n\t\t\tfirst_word_seen = False\n\t\t\t\n\t\t\tfor k in phrases_to_sort[i]:\n\t\t\t\tif first_word_seen == True:\n\t\t\t\t\tphrases_to_print[counter-1].append(\" \" + k[1])\t#finally add to the line the phrase of words\n\t\t\t\telse: \n\t\t\t\t\tphrases_to_print[counter-1].append(k[1])\n\t\t\t\t\tfirst_word_seen = True\n\t\t\t\t\t\n\t\t\tphrases_to_print[counter-1].append(\"\\n\")\t#also add a newline\n\t\t\t\n\t\t\tfirst = False\t\t\t#reset variables\n\t\t\tborders_end = 0 \n\t\t\tborder_start = 0\n\t\t\tcounter +=1\n\t\t\t\n\t\tphrases_to_sort = [[]]\n\t\tphrase_counter = 0\n\t\tphrase_list = []\n\t\tlooked_up = []\n\t\nsorted_phrases_back = sorted(phrases_to_print, key=lambda phrase: int(phrase[2]))\t#sort all the lines by offset\nsorted_phrases = sorted(sorted_phrases_back, key=lambda phrase: int(phrase[1]))\t\t#sort all the lines by onset\n\nt_counter = 1\nfor single_phrase in sorted_phrases:\t\t\t\t#for every line write a \"T\" and a counting up number behind and then the line\n\tentities.write(\"T\" + str(t_counter) + \"\\t\")\n\tt_counter +=1\n\tfor l in single_phrase:\n\t\tentities.write(l)\t\t\t\t\t\t\t#into the output-file","sub_path":"entity_extract.py","file_name":"entity_extract.py","file_ext":"py","file_size_in_byte":6980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"353988298","text":"\n\nimport json\nimport requests\n\n\nREGIONS_OSM_CODES = \\\n\t{'Qassim':'3679872',\n\t'Riyadh':'3678409',\n\t'Tabuk':'3679867',\n\t'Madinah':'3679869',\n\t'Makkah':'3678639',\n\t'Northern Region':'3673927',\n\t'Jawf':'3842543',\n\t'Hail':'3676707',\n\t'Bahah':'3679888',\n\t'Jizan':'3679903',\n\t'Asir':'3678598',\n\t'Najran':'3667317',\n\t'Eastern Region':'3667294'}\n\n\noutput = dict([('type', 'FeatureCollection'), ('features', [])]) \nheader = {'User-Agent': 'Mozilla/5.0'}\n\nfor k in REGIONS_OSM_CODES:\n\turl = \"https://nominatim.openstreetmap.org/reverse?osm_type=R&osm_id=%s&format=json&polygon_geojson=1\" % REGIONS_OSM_CODES[k]\n\n\tr = requests.get(url)\n\tdata = r.json()\n\n\tfeature = dict([('type', 'Feature'), ('properties', dict()), ('geometry', dict())])\n\tfeature['properties']['name'] = k\n\tfeature['geometry']['type'] = data['geojson']['type']\n\tfeature['geometry']['coordinates'] = data['geojson']['coordinates']\n\t\n\toutput['features'].append(feature)\n\nwith open('SA_regions.json', 'w', encoding='utf-8') as f:\n json.dump(output, f, ensure_ascii=False, indent=4)\n","sub_path":"SA_regions_geojsons_builder.py","file_name":"SA_regions_geojsons_builder.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"223994009","text":"#PARNAME=nfs #LOC=1,1\n#PARNAME=sigma_g #LOC=2,1\n#PARNAME=gain_g #LOC=2,2\n#PARNAME=lambda_s #LOC=3,1\n#PARNAME=gain_s #LOC=3,2\n#PARNAME=dir_s #LOC=4,1\n#PARNAME=W_cut #LOC=4,2\n#PARNAME=max_n_weights #LOC=5,1\n#HASWEIGHT\n\n# This implements a Gabor connection; a 2-D Gaussian multiplied by a\n# 1-D sine. Arguments are:\n#\n# sigma_g - sigma of the gaussian\n# gain_g - a gain for the gaussian\n# lambda_s - wavelength of sine\n# gain_s - gain of sine\n# dir_s - direction of (1-D) sine in degrees\n# W_cut - weight cut-off; weights below this considered to be 0\n#\n# max_n_weights is the size of the array to allocate to contain the\n# generated weights. In principle this could be nfs^4, but for a 150\n# side neural field side, that would result in a requirement for 8 GB\n# of device RAM. Instead, specify max_n_weights and hope you chose\n# enough! 20,000,000 is reasonable.\n\ndef connectionFunc(srclocs,dstlocs,nfs,sigma_g,gain_g,lambda_s,gain_s,dir_s,W_cut,max_n_weights):\n\n from numba import cuda, float32, int32\n import math\n import numpy as np\n from operator import gt\n import time # for code profiling\n\n # Shifts index to avoid bank conflicts (CC 6.1)\n @cuda.jit(device=True)\n def shifted_idx (idx):\n # 16 and 768 works for GTX1070,1080 and 1080Ti with Compute\n # capability 6.1; makes 48 KB of shared memory. This is the\n # maximum that can be allocated with non-dynamic shared\n # memory. GTX 1080 apparently has 96 KB but it's still CC\n # 6.1.\n num_banks = 16\n bank_width_int32 = 768\n # max_idx = (bank_width_int32 * num_banks)\n idx_idiv_num_banks = idx // num_banks\n idx_mod_num_banks = idx % num_banks\n offs_idx = ((bank_width_int32 * idx_mod_num_banks) + (idx_idiv_num_banks))\n return offs_idx\n\n @cuda.jit(device=True)\n def shifted_idx3 (thread_idx):\n # How many int32 memory locations being used in each thread:\n memorywidth = 3 # 12//4\n # The width of a bank in int32s:\n bank_width_int32 = 192 # 768//4\n #num_banks = 16\n bankwidth = 3072 # bank_width_int32 * num_banks\n\n offs_idx = (bank_width_int32 * thread_idx)\n idx_idiv_bw = offs_idx // bankwidth\n idx_mod_bw = offs_idx % bankwidth\n offs_idx = idx_mod_bw + idx_idiv_bw * memorywidth\n\n return offs_idx\n\n ### GPU SCAN CODE GOES HERE\n ###############################################################################\n # Like prefixscan_gpu, but returning the non-zero values from\n # weight_ar in d_out\n #\n # d_weight_ar - A memory area on the GPU memory containing a sparse\n # matrix of results (floating point, probably)\n #\n # arraysz - The length of the sparse matrix contained in\n # d_weight_ar (this will be the same as nfs_sq * nfs_sq)\n #\n # arrayszplus - The size of the memory area d_weight_ar. This should\n # be an integer multiple of threadsperblock\n #\n # threadsperblock - how many threads to launch per threadblock on the\n # GPU.\n #\n # d_out - Array for results in connectionFunc output format: 4\n # columns of data. Populated by extract_nonzero()\n #\n # _nfs_sq square of neural field size (nfs is the side length of\n # the square neural field).\n #\n def reduce_nonzero_gpu (d_weight_ar, arraysz, arrayszplus, threadsperblock, _d_out, _nfs_sq):\n import math\n from operator import gt\n\n # Detect non-zero values in weight_ar_. Update each element of the\n # identically shaped nonzero_ar_ to hold 1 for non-zero values in\n # weight_ar_ and 0 for zero values in weight_ar_\n @cuda.jit(\"void(float32[:], int32[:], int32)\")\n def detect_nonzero (weight_ar_, nonzero_ar_, arraysz):\n thid = cuda.threadIdx.x + (cuda.blockIdx.x*cuda.blockDim.x)\n if thid < arraysz:\n nonzero_ar_[thid] = 1 if abs(weight_ar_[thid]) > 0.0 else 0\n # debug:\n #if nonzero_ar_[thid] == 1:\n # print ('nonzero_ar_[{0}] = {1}, weight_ar_[{0}] = {2}'.format(thid, nonzero_ar_[thid], weight_ar_[thid]))\n\n #\n # parallel prefix scan for stream compaction (See sect. 39.3\n # https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch39.html)\n #\n # This sums up the values in input_ar_, placing the running\n # total in scan_ar_. The final carry value is placed in carry_\n #\n # This kernel carries out the prefix scan for a single threadblock.\n #\n # scan_ar_ - The result of the prefix scan. Array of uint32s\n # (could be float32s)\n #\n # input_ar_ - The input for the algorithm. Array of uint32s (could\n # be float32s)\n #\n # carry_ - The carry array - carry_[cuda.blockIdx.x] is updated\n # with the final value in scan_ar_\n #\n # threadsperblock_ - The number of CUDA threads per threadblock\n #\n # inputsz - The size of the arrays scan_ar_ and input_ar_\n #\n @cuda.jit()\n def one_block_scan (scan_ar_, input_ar_, carry_, threadsperblock_, inputsz):\n thid = cuda.threadIdx.x # Thread ID\n tb_offset = cuda.blockIdx.x*cuda.blockDim.x # Threadblock offset\n d = threadsperblock_//2 # d starts out as half the block\n\n # This runs for every element in input_ar_\n if (thid+tb_offset) < (inputsz-d):\n\n # Allocate ALL shared memory here. Use float32 as type; could be uint32.\n shmem = cuda.shared.array(12288, dtype=float32)\n ai = thid # within one block\n bi = ai + d # ai and bi are well separated across the shared memory. bi = ai+1 could also work?\n\n # Compute shifted indices for efficient use of shared memory\n ai_s = shifted_idx(ai)\n bi_s = shifted_idx(bi)\n\n # Copy input into local shared memory array\n shmem[ai_s] = input_ar_[ai+tb_offset]\n shmem[bi_s] = input_ar_[bi+tb_offset]\n\n offset = 1\n # Upsweep: Build sum in place up the tree\n while (d > 0):\n cuda.syncthreads()\n if thid < d:\n # Block B\n ai = offset*(2*thid+1)-1\n bi = offset*(2*thid+2)-1\n ai_s = shifted_idx(ai)\n bi_s = shifted_idx(bi)\n shmem[bi_s] += shmem[ai_s]\n\n offset *= 2\n d >>= 1\n\n cuda.syncthreads()\n\n # Block C: clear the last element - the first step of the downsweep\n if (thid == 0):\n nm1s = shifted_idx(threadsperblock-1)\n # Carry last number in the block\n carry_[cuda.blockIdx.x] = shmem[nm1s];\n shmem[nm1s] = 0\n\n # Downsweep: traverse down tree & build scan\n d = 1\n while d < threadsperblock_:\n offset >>= 1\n cuda.syncthreads()\n if (thid < d):\n # Block D\n ai = offset*(2*thid+1)-1\n bi = offset*(2*thid+2)-1\n ai_s = shifted_idx(ai)\n bi_s = shifted_idx(bi)\n t = shmem[ai_s]\n shmem[ai_s] = shmem[bi_s]\n shmem[bi_s] += t\n d *= 2\n cuda.syncthreads()\n\n # Block E: write results to device memory\n scan_ar_[ai+tb_offset] = shmem[ai_s]\n if bi < threadsperblock_:\n scan_ar_[bi+tb_offset] = shmem[bi_s]\n #print ('Set scan_ar_[{0}] to shmem[{1}] = {2}'.format(bi+tb_offset, bi_s, shmem[bi_s]))\n\n return # End of one_block_scan()\n\n # Last job is to add on the carry to each part of scan_ar WHILE AT THE SAME TIME SUMMING WITHIN A BLOCK\n @cuda.jit\n def sum_scans(new_carry_ar_, scan_ar_, scan_ar_sz, carry_ar_):\n thid = cuda.threadIdx.x\n tb_offset = cuda.blockIdx.x*cuda.blockDim.x # threadblock offset\n arr_addr = thid+tb_offset\n\n # Try replacing with ternarys at some point:\n if cuda.blockIdx.x > 0 and arr_addr < scan_ar_sz:\n new_carry_ar_[arr_addr] = scan_ar_[arr_addr] + carry_ar_[cuda.blockIdx.x]\n elif cuda.blockIdx.x == 0 and arr_addr < scan_ar_sz:\n new_carry_ar_[arr_addr] = scan_ar_[arr_addr]\n\n cuda.syncthreads()\n\n @cuda.jit\n def sum_scans_destructively(scan_ar_, scan_ar_sz, carry_ar_):\n thid = cuda.threadIdx.x\n tb_offset = cuda.blockIdx.x*cuda.blockDim.x # threadblock offset\n arr_addr = thid+tb_offset\n\n if cuda.blockIdx.x > 0 and arr_addr < scan_ar_sz:\n #print ('scan_ar_[{0}] += carry_ar_[{1}] ||| {2} += {3}'\n # .format(arr_addr, cuda.blockIdx.x, scan_ar_[arr_addr], carry_ar_[cuda.blockIdx.x]))\n scan_ar_[arr_addr] = scan_ar_[arr_addr] + carry_ar_[cuda.blockIdx.x]\n #print ('scan_ar_[{0}] = {1}'.format (arr_addr, scan_ar_[arr_addr]))\n\n # Extract non zero weights from d_weight_ar and place them\n # into the array d_out.\n @cuda.jit\n def extract_nonzero (d_weight_ar, weight_sz, d_scan_ar, __d_out, __nfs_sq):\n thid = cuda.threadIdx.x + (cuda.blockIdx.x*cuda.blockDim.x)\n #print ('thread id: {0}, weight_sz: {1}'.format(thid, weight_sz))\n if thid < weight_sz and abs(d_weight_ar[thid]) > 0.0:\n # Populate d_out in the correct format:\n src_idx = thid%__nfs_sq\n dst_idx = thid//__nfs_sq\n jj = d_scan_ar[thid]\n __d_out[jj][0] = src_idx\n __d_out[jj][1] = dst_idx\n __d_out[jj][2] = 0.0 # delay - unused\n __d_out[jj][3] = d_weight_ar[thid]\n\n # END of kernel definitions\n\n # reduce_nonzero_gpu code proper starts:\n print ('--- reduce_nonzero_gpu ---')\n print ('threadsperblock: {0}'.format(threadsperblock))\n print ('arrayszplus: {0}'.format(arrayszplus))\n print ('arraysz: {0}'.format(arraysz)) # Set by code above - size of the weight array. Quite big\n\n #\n # Build input data for the test\n #\n\n blockspergrid = math.ceil(arraysz/threadsperblock)\n print ('blockspergrid: {0}'.format(blockspergrid))\n\n # nonzero_ar is set to 1 for every element for which weight_ar is >0\n print ('allocate arrayszplus={0} uint32s in nonzero_ar'.format(arrayszplus))\n nonzero_ar = np.zeros((arrayszplus,), dtype=np.uint32)\n\n # scan_ar is going to hold the result of scanning the input\n scan_ar = np.zeros((arrayszplus,), dtype=np.uint32)\n\n # Explicitly copy working data to device (two lots of arraysz data on GPU memory)\n print (\"Allocating \" + str(4*arrayszplus/1048576) + \" MBytes on the GPU memory (d_nonzero_ar)\")\n d_nonzero_ar = cuda.to_device (nonzero_ar)\n print (\"Allocating \" + str(4*arrayszplus/1048576) + \" MBytes on the GPU memory (d_scan_ar)\")\n d_scan_ar = cuda.to_device (scan_ar)\n\n # Make up a list of carry vectors and allocate device memory\n carrylist = []\n d_carrylist = []\n # And containers for the scan\n scanlist = []\n d_scanlist = []\n asz = arraysz\n print ('asz: {0} threadsperblock: {1}'.format(asz, threadsperblock))\n while asz > threadsperblock:\n\n carrysz = math.ceil (asz / threadsperblock)\n # Ensure carrysz is a multiple of threadsperblock:\n if carrysz%threadsperblock:\n carrysz = carrysz + threadsperblock - carrysz%threadsperblock\n\n print (\"Allocating \" + str(4*carrysz/1024) + \" KBytes on the GPU memory (carrylist)\")\n carrylist.append (np.zeros((carrysz,), dtype=np.float32))\n d_carrylist.append (cuda.to_device(carrylist[-1]))\n asz = math.ceil (asz / threadsperblock)\n scansz = asz\n if scansz%threadsperblock:\n scansz = scansz + threadsperblock - scansz%threadsperblock\n print (\"Allocating \" + str(4*scansz/1024) + \" KBytes on the GPU memory (scanlist)\")\n scanlist.append (np.zeros((scansz,), dtype=np.float32))\n d_scanlist.append (cuda.to_device(scanlist[-1]))\n\n # Add a last carrylist, as this will be required as a dummy\n # carry list for the last call to one_block_scan()\n carrylist.append (np.zeros((1,), dtype=np.int32))\n d_carrylist.append (cuda.to_device(carrylist[-1]))\n\n #\n # Compute partial scans of the top-level weight_ar and the lower level\n # partial sums\n #\n # The first input is the weight array, compute block-wise prefix-scan sums:\n detect_nonzero[blockspergrid, threadsperblock] (d_weight_ar, d_nonzero_ar, arraysz)\n print ('First one_block_scan...')\n one_block_scan[blockspergrid, threadsperblock] (d_scan_ar, d_nonzero_ar, d_carrylist[0], threadsperblock, arrayszplus)\n\n asz = math.ceil (arrayszplus / threadsperblock)\n j = 0\n print ('asz: {0} threadsperblock: {1}'.format(asz, threadsperblock))\n while asz > threadsperblock:\n scanblocks = math.ceil (asz / threadsperblock)\n scanblocks = scanblocks + threadsperblock - scanblocks%threadsperblock\n print ('while loop one_block_scan...')\n one_block_scan[scanblocks, threadsperblock](d_scanlist[j], d_carrylist[j], d_carrylist[j+1], threadsperblock, len(carrylist[j]))\n asz = scanblocks\n j = j+1\n # Plus one more iteration:\n scanblocks = math.ceil (asz / threadsperblock)\n scanblocks = scanblocks + threadsperblock - scanblocks%threadsperblock\n print ('last one_block_scan. scanblock: {0} threadsperblock: {1}, j is {2}'.format(scanblocks, threadsperblock, j))\n one_block_scan[scanblocks, threadsperblock](d_scanlist[j], d_carrylist[j], d_carrylist[j+1], threadsperblock, len(carrylist[j]))\n\n #\n # Construct the scans back up the tree by summing the \"carry\" into the \"scans\"\n #\n ns = len(scanlist)\n j = ns\n while j > 0:\n sumblocks = math.ceil(len(scanlist[j-1])/threadsperblock)\n sum_scans[sumblocks, threadsperblock](d_carrylist[j-1], d_scanlist[j-1], len(scanlist[j-1]), d_carrylist[j])\n # Now d_carrylist[j-1] has had its carrys added from the lower level\n j = j-1\n\n # The final sum_scans() call. I sum within d_scan_ar destructively at this point.\n sum_scans_destructively[blockspergrid, threadsperblock](d_scan_ar, arrayszplus, d_carrylist[0])\n\n # Get the total number of weights from the final carrylist:\n n_weights = 0\n local_carrylist = d_carrylist[ns].copy_to_host()\n last_cl_len = len(local_carrylist)\n if last_cl_len == 1:\n n_weights = local_carrylist[0]\n else:\n print (\"ERROR. Length of last carry list should be 1\")\n\n # Finally, in parallel, populate d_out.\n extract_nonzero[blockspergrid, threadsperblock] (d_weight_ar, arraysz, d_scan_ar, _d_out, _nfs_sq)\n\n return n_weights # END reduce_nonzero_gpu()\n ###############################################################################\n ### GPU SCAN CODE TO HERE\n\n ### CONNECTION FUNCTION-COMPUTING CODE HERE\n #\n @cuda.jit(\"void(int32,int32[:,:],int32[:,:],float32[:],float32, float32,float32, float32, float32,float32)\", nopython=True)\n def dowork (nfs_sq, d_src_ar, d_dst_ar, weight_ar, sigma_g, gain_g, lambda_s, gain_s, dir_s, W_cut):\n # Work out i_src and i_dst based on the 2-D thread index\n i_src, i_dst = cuda.grid(2)\n twopi = float32(6.283185307)\n\n if i_src < nfs_sq and i_dst < nfs_sq:\n\n # Temporary shared memory for weights\n tmp_w = cuda.shared.array(12288, dtype=float32) # Note - allocating ALL shared memory here.\n myidx = (cuda.threadIdx.y*cuda.blockDim.x + cuda.threadIdx.x)\n offsidx = shifted_idx3 (myidx)\n tmp_w[offsidx] = float32(0.0)\n tmp_w[offsidx+1] = float32(0.0)\n tmp_w[offsidx+2] = float32(0.0)\n cuda.syncthreads()\n\n # Avoid many tanh, sin, cos, pow and exp computations for well-separated neurons:\n xdist = d_src_ar[i_src,0] - d_dst_ar[i_dst,0]\n ydist = d_src_ar[i_src,1] - d_dst_ar[i_dst,1]\n\n # Testing the region of interest gives a slight speed up\n # (7 s vs 8 s) at a cost of having one extra parameter to\n # set.\n # zdist = d_src_ar[i_src,2] - d_dst_ar[i_dst,2] # ignore z component for now\n dist = math.sqrt(math.pow(xdist,2) + math.pow(ydist,2)) # + math.pow(zdist,2))\n # Direction from source to dest\n top = float32(d_dst_ar[i_dst,1]-d_src_ar[i_src,1])\n bot = float32(d_dst_ar[i_dst,0]-d_src_ar[i_src,0])\n dir_d = math.atan2 (top, bot)\n # Find the projection of the source->dest direction onto the sine wave direction. Call this distance dprime.\n dprime = dist*math.cos(dir_d + twopi - ((dir_s*twopi)/float32(360)));\n # Use dprime to figure out what the sine weight is.\n sine_weight = gain_s*math.sin(dprime*twopi/lambda_s);\n gauss_weight = gain_g*math.exp(-0.5*math.pow(dist/sigma_g,2))\n combined_weight = sine_weight * gauss_weight;\n\n if abs(combined_weight) > W_cut:\n tmp_w[offsidx] = float32(combined_weight)\n tmp_w[offsidx+1] = float32(i_src)\n tmp_w[offsidx+2] = float32(i_dst)\n\n # Sync threads, then access device memory with any results\n cuda.syncthreads()\n\n if cuda.threadIdx.x == 0 and cuda.threadIdx.y == 0:\n tpb = cuda.blockDim.x * cuda.blockDim.y\n # Write data from tmp_w to res_ar, but only in ONE thread from the threadblock. Should avoid racing.\n for idx in range(0,tpb): # 512 was hard coded here; changed it for tpb\n offsidx2 = shifted_idx3 (idx)\n theweight = tmp_w[offsidx2] # weight should be the first one, so no +1 or +2\n # Add to weight_ar\n weight_idx = int32(tmp_w[offsidx2+2])*nfs_sq + int32(tmp_w[offsidx2+1])\n weight_ar[weight_idx] = theweight\n\n return # end dowork()\n\n # Initialise a device array with a value. Use with a 1D grid of 1D threadblocks\n @cuda.jit(\"void(uint32[:],uint32,uint32)\")\n def init_array (d_array, d_array_sz, value):\n thid = cuda.threadIdx.x + (cuda.blockIdx.x*cuda.blockDim.x)\n if thid < d_array_sz:\n d_array[thid] = value\n\n # Compute once only\n nfs_sq = int(nfs*nfs)\n\n # Copy srclocs and dstlocs to device memory before starting.\n src_ar = np.array(srclocs, dtype=np.int32)\n dst_ar = np.array(dstlocs, dtype=np.int32)\n d_src_ar = cuda.to_device (src_ar)\n d_dst_ar = cuda.to_device (dst_ar)\n\n # Device array to have the weights computed into\n weight_sz = int(nfs_sq*nfs_sq) # Take care to cast to int numbers which should not be floats.\n print('cuda.device_array: weight_sz: {0}, dtype is np.float32.'.format(weight_sz))\n d_weight_ar = cuda.device_array ((weight_sz,), dtype=np.float32)\n\n # COMPUTE WEIGHTS. Call function to compute weights in d_weight_ar\n threadsperblock = (int(16),int(32)) # 16 warps to a block; 512 threads\n #threadsperblock = (16,2) # 16 warps to a block; 512 threads\n print ('threadsperblock: {0}'.format(threadsperblock))\n blockspergrid = (int(1+(nfs_sq // threadsperblock[0])), int(1+(nfs_sq // threadsperblock[1])))\n print ('blockspergrid: {0}'.format(blockspergrid)) # 157 by 79. Gives 2500 by 2500 computations - that's each of 2500 inputs to each of 2500 outs\n\n time_start = int(round(time.time() * 1000))\n\n # Do the work of computing the connections:\n dowork[blockspergrid, threadsperblock](nfs_sq, d_src_ar, d_dst_ar, d_weight_ar, sigma_g, gain_g, lambda_s, gain_s, dir_s, W_cut)\n time_donework = int(round(time.time() * 1000))\n print (\"computed weights after {0} ms\".format(time_donework - time_start));\n\n # EXTRACT NONZERO WEIGHTS. For the reduce operation, I adopt a 1-D grid of threadblocks\n threadsperblock = int(128)\n blockspergrid = int(math.ceil(weight_sz/threadsperblock))\n print ('blockspergrid: {0}'.format(blockspergrid))\n if weight_sz%threadsperblock:\n weight_sz_plus = int(weight_sz + threadsperblock - weight_sz%threadsperblock)\n else:\n weight_sz_plus = int(weight_sz)\n\n # Allocate device memory for the reduce_nonzero_gpu result. In\n # principle this could be as large as nfs^4, but that can call for\n # too much device memory. A max_n_weights parameter of\n # connectionFunc() is passed in to set out_sz.\n out_sz = int(max_n_weights)\n\n # First we'll place the output in device memory\n print (\"Allocating \" + str(4*4*out_sz/1048576) + \" MBytes on the GPU memory (d_out)\")\n d_out = cuda.device_array((out_sz,4), dtype=np.float32)\n\n # Reduce it down\n dummy = 0\n print (\"Reduce down to just the non-zero weights\")\n n_weights = reduce_nonzero_gpu(d_weight_ar, weight_sz, weight_sz_plus, threadsperblock, d_out, nfs_sq)\n time_reduced = int(round(time.time() * 1000))\n print (\"Completed reduce down after {0} ms. n_weights={1}\".format(time_reduced-time_donework, n_weights))\n\n # Copy the device memory back with the result.\n out = d_out.copy_to_host()\n\n time_arraycreated = int(round(time.time() * 1000))\n print (\"Got final result after {0} ms\".format(time_arraycreated-time_reduced))\n\n print (\"Total number of non-zero weights: {0}. out_sz: {1}.\".format (n_weights, out_sz))\n if n_weights > max_n_weights:\n print (\"---------------\\nWARNING WARNING:\\n---------------\\nUser chose {0} as max_n_weights, but {1} weights were generated.\\nMemory corruption may have occurred!!\\n---------------\".format(max_n_weights, n_weights))\n\n # Truncate out at length n_weights. Note we're returning a Numpy\n # array cast to a list.\n return out[0:n_weights,:].tolist() # end connectionFunc\n#######################################################################\n","sub_path":"connectionFuncs/gabor_gpu.py","file_name":"gabor_gpu.py","file_ext":"py","file_size_in_byte":22705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"168081564","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 6 16:17:08 2021\r\n\r\n@author: ersoy\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom Location import *\r\n\r\ndef walk(f, d, num_steps):\r\n \"\"\"Assumes: f a Field, d a Drunk in f, and num_steps an int >= 0.\r\n Moves d num_steps times; returns the distance between the\r\n final location and the location at the start of the walk.\"\"\"\r\n \r\n start = f.get_loc(d)\r\n for s in range(num_steps):\r\n f.move_drunk(d)\r\n return start.dist_from(f.get_loc(d))\r\n\r\ndef sim_walks(num_steps, num_trials, d_class):\r\n \"\"\"Assumes num_steps an int >= 0, num_trials an int > 0,\r\n d_class a subclass of Drunk\r\n Simulates num_trials walks of num_steps steps each.\r\n Returns a list of the final distances for each trial\"\"\"\r\n \r\n Homer = d_class()\r\n origin = Location(0, 0)\r\n distances = []\r\n for t in range(num_trials):\r\n f = Field()\r\n f.add_drunk(Homer, origin)\r\n distances.append(round(walk(f, Homer, num_steps), 1))\r\n return distances\r\n\r\ndef drunk_test(walk_lenghts, num_trials, d_class):\r\n \"\"\"Assumes walk_lenghts a sequence of ints >= 0\r\n num_trials an int > 0, d_class a subclass of Drunk\r\n For each number of steps in walk_lenghts, runs sim_walks with\r\n num_trials walk and prints results\"\"\"\r\n \r\n for num_steps in walk_lenghts:\r\n distances = sim_walks(num_steps, num_trials, d_class)\r\n print(d_class.__name__, 'walk of', num_steps, 'steps: Mean =',\r\n f'{sum(distances)/len(distances):.3f}, Max =',\r\n f'{max(distances)}, Min = {min(distances)}')\r\n\r\ndef sim_all(drunk_kinds, walk_lenghts, num_trials):\r\n \r\n for d_class in drunk_kinds:\r\n drunk_test(walk_lenghts, num_trials, d_class)\r\n \r\ndef sim_drunk(num_trials, d_class, walk_lenghts):\r\n \r\n mean_distances = []\r\n for num_steps in walk_lenghts:\r\n print('Starting simulation of', num_steps, 'steps')\r\n trials = sim_walks(num_steps, num_trials, d_class)\r\n mean = sum(trials)/len(trials)\r\n mean_distances.append(mean)\r\n return mean_distances\r\n\r\ndef sim_all_plot(drunk_kinds, walk_lenghts, num_trials):\r\n \r\n style_choice = style_iterator(('m-', 'r:', 'k-.'))\r\n for d_class in drunk_kinds:\r\n cur_style = style_choice.next_style()\r\n print('Starting simulation of', d_class.__name__)\r\n means = sim_drunk(num_trials, d_class, walk_lenghts)\r\n plt.plot(walk_lenghts, means, cur_style, label = d_class.__name__)\r\n \r\n plt.title(f'Mean Distance from Origin ({num_trials} trials)')\r\n plt.xlabel('Number of Steps')\r\n plt.ylabel('Distance from Origin')\r\n plt.legend(loc = 'best')\r\n plt.semilogx()\r\n plt.semilogy()\r\n \r\ndef get_final_locs(num_steps, num_trials, d_class):\r\n locs = []\r\n d = d_class\r\n for t in range(num_trials):\r\n f = Field()\r\n f.add_drunk(d, Location(0, 0))\r\n for s in range(num_steps):\r\n f.move_drunk(d)\r\n locs.append(f.get_loc(d))\r\n return locs\r\n\r\ndef plot_locs(drunk_kinds, num_steps, num_trials):\r\n style_choice = style_iterator(('k+', 'r^', 'mo'))\r\n for d_class in drunk_kinds:\r\n locs = get_final_locs(num_steps, num_trials, d_class)\r\n x_vals, y_vals = [], []\r\n for loc in locs:\r\n x_vals.append(loc.get_x())\r\n y_vals.append(loc.get_y())\r\n meanX = sum(x_vals) / len(x_vals)\r\n meanY = sum(y_vals) / len(y_vals)\r\n cur_style = style_choice.next_style()\r\n plt.plot(x_vals, y_vals, cur_style, \r\n label = (f'{d_class.__name__} mean loc. = <' +\r\n f'{meanX}, {meanY} >'))\r\n plt.title(f'Location at End of Walks ({num_steps} steps)')\r\n plt.xlabel('Steps East / West of Origin')\r\n plt.ylabel('Steps North / South of Origin')\r\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\r\n\r\ndef trace_walk(drunk_kinds, num_steps):\r\n style_choice = style_iterator(('k+', 'r^', 'mo'))\r\n # f = Field()\r\n f = Odd_field(1000, 100, 200)\r\n for d_class in drunk_kinds:\r\n d = d_class()\r\n f.add_drunk(d, Location(0, 0))\r\n locs = []\r\n for s in range(num_steps):\r\n f.move_drunk(d)\r\n locs.append(f.get_loc(d))\r\n x_vals, y_vals = [], []\r\n for loc in locs:\r\n x_vals.append(loc.get_x())\r\n y_vals.append(loc.get_y())\r\n cur_style = style_choice.next_style()\r\n plt.plot(x_vals, y_vals, cur_style, label = d_class.__name__)\r\n plt.title('Spots Visited on Walk (' + str(num_steps) +' steps)')\r\n plt.xlabel('Steps East / West of Origin')\r\n plt.ylabel('Steps North / South of Origin')\r\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')\r\n\r\n \r\n### CODE TESTRUNS\r\n\r\n# drunk_test((10, 100, 1000, 10000), 100, Usual_drunk)\r\n# sim_all((Usual_drunk, Cold_drunk, EW_drunk), (100, 1000), 10)\r\n# sim_all_plot((Usual_drunk, Cold_drunk, EW_drunk), (10, 100, 1000, 10000, 100000), 100)\r\n# plot_locs((Usual_drunk, Cold_drunk, EW_drunk), 100, 200)\r\n# trace_walk((Usual_drunk, Cold_drunk, EW_drunk), 200)\r\ntrace_walk((Usual_drunk, Cold_drunk, EW_drunk), 500) # For Treachorus Fields example\r\n\r\n### Finger exercise p365\r\n# Lengths = [10, 100, 1000, 10000, 100000]\r\n# Sqrt = list(map(lambda x: math.sqrt(x), Lengths))\r\n# Distance = []\r\n# for steps in Lengths:\r\n# Result = sim_walks(steps, 100, Usual_drunk)\r\n# Distance.append(sum(Result)/len(Result))\r\n\r\n# plt.clf()\r\n# plt.axes(xscale = 'log', yscale = 'log')\r\n# plt.ylabel(\"Distance from Origin\", fontsize = 15)\r\n# plt.xlabel(\"Number of Steps\", fontsize = 15)\r\n# plt.title(\"Mean Distance from Origin (100 Trials)\", fontsize = 15)\r\n# plt.plot(Lengths, Distance, 'b-', label ='Usual_drunk', linewidth = 2.0)\r\n# plt.plot(Lengths, Sqrt, 'g--', label ='sqrt(steps)', linewidth = 2.0)\r\n# plt.legend(loc = 'upper left')\r\n\r\n","sub_path":"Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":5942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"455422396","text":"import discord\nfrom discord.ext import commands\nimport os\nimport shutil\nfrom os import system\n\n\nfrom discord.utils import get\nimport time\nfrom discord.ext.commands import check\nfrom mal import *\n\nclass misc(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n \n @commands.command()\n async def info(self, ctx):\n #await ctx.send(f'My ping is {round(self.latency*1000, 2)} ms!')\n await ctx.send(f'`-play\\n-pause\\n-resume\\n-skip\\n-stop\\n-queue\\n-userinfo\\n-as anime\\n-ms manga\\n-invite`')\n\n @commands.command()\n async def invite(self, ctx):\n await ctx.send(f'https://discord.com/api/oauth2/authorize?client_id=893777032423571457&permissions=0&scope=bot')\n\n @commands.command()\n async def userinfo(self, ctx, member: discord.Member = None):\n member = ctx.author if not member else member\n roles = [role for role in member.roles]\n embed = discord.Embed(colour=member.colour, timestamp=ctx.message.created_at)\n embed.set_author(name=f\"User Info - {member}\")\n embed.set_thumbnail(url=member.avatar_url)\n embed.set_footer(text=f\"Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n embed.add_field(name=\"ID:\", value=member.id)\n embed.add_field(name=\"Nickname:\", value=member.display_name, inline=\"False\")\n embed.add_field(name=\"Created On:\", value=member.created_at.strftime(\"%a, %d, %B, %Y, %I:%M %p UTC\"), inline=\"False\")\n embed.add_field(name=\"Joined On:\", value=member.joined_at.strftime(\"%a, %d, %B, %Y, %I:%M %p UTC\"), inline=\"False\")\n embed.add_field(name=f\"Roles ({len(roles)})\", value=\" \".join([role.mention for role in roles]), inline=\"False\")\n embed.add_field(name=\"Highest Role:\", value=member.top_role.mention, inline=\"False\")\n embed.add_field(name=\"Bot:\", value=member.bot, inline=\"False\")\n await ctx.send(embed=embed)\n\n @commands.command()\n @commands.has_permissions(manage_messages=True)\n async def clear(self, ctx, amount: int):\n await ctx.channel.purge(limit=amount+1)\n\n @commands.command(aliases = ['as'])\n async def animesearch(self, ctx, an: str, ):\n start = time.time()\n search = AnimeSearch(f\"{an}\") # Search for \"cowboy bebop\"\n id_ = search.results[0].mal_id\n url_ = search.results[0].url\n img_url = search.results[0].image_url\n ti = search.results[0].title\n sy = search.results[0].synopsis\n ty = search.results[0].type\n ep = search.results[0].episodes\n sc = search.results[0].score\n anime = Anime(id_)\n st = anime.status\n ai = anime.aired\n ra = anime.rank\n embed = discord.Embed(colour=ctx.author.colour, timestamp=ctx.message.created_at)\n embed.set_thumbnail(url=img_url)\n embed.set_footer(text=f\"Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n embed.add_field(name=\"Anime Name:\", value=ti, inline=\"False\")\n embed.add_field(name=\"Synopsis:\", value=sy, inline=\"False\")\n embed.add_field(name=\"Contd:\", value=url_, inline=\"False\")\n embed.add_field(name=\"Type\", value=ty, inline=\"False\")\n embed.add_field(name=\"Episodes:\", value=ep, inline=\"False\")\n embed.add_field(name=\"Score:\", value=sc, inline=\"False\")\n embed.add_field(name=\"Status:\", value=st, inline=\"False\")\n embed.add_field(name=\"MAL_ID:\", value=id_, inline=\"False\")\n embed.add_field(name=\"Aired:\", value=ai, inline=\"False\")\n embed.add_field(name=\"Rank:\", value=ra, inline=\"False\")\n await ctx.send(embed=embed)\n end = time.time()\n await ctx.send(f\"`Time taken: {round(end-start, 2)} seconds`\")\n\n @commands.command(aliases = ['ms'])\n async def mangasearch(self, ctx, an: str, ):\n start = time.time()\n search = MangaSearch(f\"{an}\") # Search for \"cowboy bebop\"\n id_ = search.results[0].mal_id\n url_ = search.results[0].url\n img_url = search.results[0].image_url\n ti = search.results[0].title\n sy = search.results[0].synopsis\n ty = search.results[0].type\n vol = search.results[0].volumes\n sc = search.results[0].score\n manga = Manga(id_)\n st = manga.status\n ra = manga.rank\n ch = manga.chapters\n vol = manga.volumes\n embed = discord.Embed(colour=ctx.author.colour, timestamp=ctx.message.created_at)\n embed.set_thumbnail(url=img_url)\n embed.set_footer(text=f\"Requested by {ctx.author}\", icon_url=ctx.author.avatar_url)\n embed.add_field(name=\"Manga Name:\", value=ti, inline=\"False\")\n embed.add_field(name=\"Synopsis:\", value=sy, inline=\"False\")\n embed.add_field(name=\"Contd:\", value=url_, inline=\"False\")\n embed.add_field(name=\"Type\", value=ty, inline=\"False\")\n embed.add_field(name=\"Episodes:\", value=vol, inline=\"False\")\n embed.add_field(name=\"Score:\", value=sc, inline=\"False\")\n embed.add_field(name=\"Status:\", value=st, inline=\"False\")\n embed.add_field(name=\"MAL_ID:\", value=id_, inline=\"False\")\n embed.add_field(name=\"Chapters:\", value=ch, inline=\"False\")\n embed.add_field(name=\"Volumes:\", value=vol, inline=\"False\")\n embed.add_field(name=\"Rank:\", value=ra, inline=\"False\")\n await ctx.send(embed=embed)\n end = time.time()\n await ctx.send(f\"`Time taken: {round(end-start, 2)} seconds`\")\n\n\n \n\n\n @commands.command()\n async def say(self, ctx, say: str, id: int):\n channel = self.bot.get_channel(id)\n await ctx.channel.purge(limit=1)\n await channel.send(f\"{say}\")\n\n\n\ndef setup(client):\n client.add_cog(misc(client))\n","sub_path":"Cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"395069106","text":"import sys\n\nclass PyFilterClass():\n\tdef isFilteredObject(self,Object):\n\t\tif self['Type']=='Allower':\n\t\t\tif self['NeededTagsNumber']=='All':\n\t\t\t\tIsAllowed=True;\n\t\t\t\tTagIdx=0;\n\t\t\t\tTagsIterator=iter(self['Contents']);\n\t\t\t\twhile IsAllowed and TagIdx div.container.p-t-md > div.content-container > div.content-container-primary.character-list \" \\\n \"> ul > li.media.list-group-item.p-0.b-t-0 > div > table > tbody > tr > td\"\n\n members = soup.select(base)\n i = 1\n j = 1\n mem_local = []\n table_data = []\n for m in members:\n if i % 5 == 1:\n a = m.find('a')\n user_id = a['href'].split(\"/\")[2]\n name = a.find(\"strong\").text\n self.member_to_toons_dict[name] = []\n self.member_to_ships_dict[name] = []\n self.members_name_list.append(name)\n \n mem_local.append(j)\n mem_local.append(user_id)\n mem_local.append(name)\n\n j = j + 1\n if i % 5 == 2:\n mem_local.append(m.text)\n table_data.append(mem_local)\n mem_local = []\n\n i = i + 1\n\n # Manual entries\n with open('data/members.csv', 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n name = row[1]\n self.member_to_toons_dict[name] = []\n self.member_to_ships_dict[name] = []\n self.members_name_list.append(name)\n table_data.append([j, row[0], row[1], \"\"])\n j = j + 1\n\n self.members_table = table_data\n\n def populate_guild_data(self):\n s = web_pages_cache.get_from_cache(self.html_cache_dir, \"guild_toons.dict\", self.guild_toons_url, self.refresh)\n dict = eval(s)\n for key, values in dict.items():\n name = self.base_id_to_toon_name_dict.get(key, None)\n if name is not None:\n for value in values:\n self.toon_to_members_dict[name].append({\"gear_level\": value['gear_level'], \\\n \"power\": value['power'], \\\n \"level\": value['level'], \\\n \"rarity\": int(value['rarity']), \\\n \"player\": value['player']})\n self.member_to_toons_dict[value['player']].append({\"gear_level\": value['gear_level'], \\\n \"power\": value['power'], \\\n \"level\": value['level'], \\\n \"rarity\": value['rarity'], \\\n \"toon\": name})\n # ship\n else:\n ship = self.base_id_to_ship_name_dict.get(key, None)\n if ship is None:\n print(\"Skipping\")\n continue\n\n for value in values:\n self.ship_to_members_dict[ship].append({\"power\": value['power'], \\\n \"level\": value['level'], \\\n \"rarity\": value['rarity'], \\\n \"player\": value['player']})\n self.member_to_ships_dict[value['player']].append({\"power\": value['power'], \\\n \"level\": value['level'], \\\n \"rarity\": value['rarity'], \\\n \"ship\": ship})\n\n # Manually added data\n with open('data/members.csv', 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n user = row[0]\n if os.path.isfile('data/' + user + '.csv'):\n print('Fetching data for the user ' + user)\n with open('data/' + user + '.csv', 'r') as user_file:\n user_reader = csv.reader(user_file)\n for user_reader_row in user_reader:\n name = self.base_id_to_toon_name_dict[user_reader_row[0]];\n self.toon_to_members_dict[name].append({\"gear_level\": \"-\", \\\n \"power\": 0, \\\n \"level\": \"-\", \\\n \"rarity\": int(user_reader_row[1]), \\\n \"player\": row[1]})\n self.member_to_toons_dict[row[1]].append({\"gear_level\": \"-\", \\\n \"power\": 0, \\\n \"level\": \"-\", \\\n \"rarity\": user_reader_row[1], \\\n \"toon\": name})\n else:\n print('Data not available for the user ' + user)\n\n\n def toons_for_member(self, name):\n table_data = []\n\n list = self.member_to_toons_dict[name]\n list = sorted(list, key=itemgetter(1, 3), reverse=True)\n\n i = 1\n for elem in list:\n table_data.append([i, elem['toon'], elem['rarity'], elem['gear_level'], elem['power']])\n i = i + 1\n\n return table_data\n\n def players_with_toon(self, name):\n table_data = []\n\n list = self.toon_to_members_dict[name]\n list = sorted(list, key=itemgetter('rarity', 'power'), reverse=True)\n\n i = 1\n for elem in list:\n table_data.append([i, elem['player'], elem['rarity'], elem['gear_level'], elem['power']])\n i = i + 1\n\n return table_data\n\n def players_with_ship(self, name):\n table_data = []\n\n list = self.ship_to_members_dict[name]\n list = sorted(list, key=itemgetter('power'), reverse=True)\n\n i = 1\n for elem in list:\n table_data.append([i, elem['player'], elem['rarity'], elem['power']])\n i = i + 1\n\n return table_data\n\n def get_specific_toons_data_for_member(self, member, toons_names):\n toons_list = self.member_to_toons_dict[member]\n\n table_data = []\n for elem in toons_list:\n name = elem['toon']\n if utils.find_case_insensitive_exact_match(name, toons_names) is None:\n continue\n rarity = elem['rarity']\n table_data.append([name, rarity])\n\n return table_data\n\n def populate_platoons(self, platoons_file, platoons_dict):\n obj_list = json.load(open(platoons_file))\n for i in obj_list:\n phase = i['phase']\n level = i['level']\n items = i.get('toons', None)\n if items is None:\n items = i['ships']\n platoons_dict[phase] = {'rarity':level, 'items':items}\n\n def zetas(self):\n s = web_pages_cache.get_from_cache(self.html_cache_dir, \"zetas.html\", self.zetas_url, self.refresh)\n soup = BeautifulSoup(s, 'html.parser')\n\n base = \"body > div.container.p-t-md > div.content-container > div.content-container-primary.character-list \" \\\n \"> ul > li.media.list-group-item.p-0.b-t-0 > div > table > tbody > tr\"\n\n all_zetas = soup.select(base)\n # every --> 1 player\n for z in all_zetas:\n zeta_details_for_member = z.findAll('td')\n member_name = zeta_details_for_member[0].find(\"strong\").text\n zetas_for_member = zeta_details_for_member[2].findAll(\"div\", class_=\"guild-member-zeta\")\n for zeta in zetas_for_member:\n toon = zeta.find('div', class_='guild-member-zeta-character').find('img')['alt']\n abilities = zeta.find('div', class_='guild-member-zeta-abilities').findAll('img')\n for ability in abilities:\n m_name = \"\"\n t_name = \"\"\n\n if member_name is not None:\n m_name = member_name\n member_name = None\n\n if toon is not None:\n t_name = toon\n toon = None\n\n self.zetas_data.append([m_name, t_name, ability['title']])\n","sub_path":"inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":13077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"79992283","text":"# -*- coding: utf-8 -*-\n# Copyright 2021 \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nContains a backend that can handle parametric (symbolic) gates.\n\nContains a compiler engine which stores all the commands it receives in an\ninternal storage, effectively storing the result of a compilation run. The\nuser can then send the list of saved commands onto some other engine or\nbackend at a later time. In this second step, the user may also specify the\nvalue of parameters for some parametric gates (if any).\n\"\"\"\n\n# pylint: disable=no-name-in-module\n\nfrom projectq.cengines import BasicEngine\nfrom projectq.ops import AllocateQubitGate, Command, DeallocateQubitGate, FlushGate\nfrom projectq.types import WeakQubitRef\n\n\ndef _noop(arg): # pylint: disable=unused-argument\n \"\"\"Define a no-op function.\"\"\"\n\n\nclass DestinationEngineGateUnsupported(Exception):\n \"\"\"Exception raised when sending to another compiler engine and some commands are not supported by it.\"\"\"\n\n\nclass ParametricGateBackend(BasicEngine):\n \"\"\"\n ParametricGateBackend used in conjunction with parametric gates.\n\n The ParametricGateBackend stores all commands in an internal storage, typically *without* passing them onto the\n next engine.\n\n The user can later send the commands to another compiler engine by calling the provided methods (ie. preferrably\n send_to() to allow for some symbolic substitutions)\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize a PartialCompilationEngine.\"\"\"\n BasicEngine.__init__(self)\n self._received_commands = []\n self._last_sent_gate_idx = {}\n self._main_engine_qubit_idx = {}\n self._min_allocated_id = None\n self._max_allocated_id = None\n\n def clear(self):\n \"\"\"Clear the state of the backend (saved commands, internal state, etc.).\"\"\"\n self._received_commands.clear()\n self._last_sent_gate_idx = {}\n self._main_engine_qubit_idx = {}\n self._min_allocated_id = None\n self._max_allocated_id = None\n\n def is_available(self, cmd):\n \"\"\"\n Test whether a Command is supported by a compiler engine.\n\n This backend accepts all commands.\n\n Args:\n cmd (Command): Command for which to check availability.\n\n Returns:\n True\n \"\"\"\n # Accept all commands\n return True\n\n def receive(self, command_list):\n \"\"\"Forward all commands to the next engine.\"\"\"\n self._received_commands.extend(command_list)\n if not self.is_last_engine:\n raise RuntimeError('ParametricGateBackend must be the last engine!')\n # Recalculate the minimum/maximum allocated qubit ID\n # (required for when we eventually send the commands to some other\n # engine)\n\n qubit_ids = [cmd.qubits[0][0].id for cmd in command_list if isinstance(cmd.gate, AllocateQubitGate)]\n\n if qubit_ids:\n min_id = min(qubit_ids)\n if self._min_allocated_id is None:\n self._min_allocated_id = min_id\n else:\n self._min_allocated_id = min(self._min_allocated_id, min_id)\n\n max_id = max(qubit_ids)\n if self._max_allocated_id is None:\n self._max_allocated_id = max_id\n else:\n self._max_allocated_id = max(self._max_allocated_id, max_id)\n\n def send_to(self, engine, subs=None): # pylint: disable=too-many-branches\n \"\"\"\n Send the commands stored in an instance of ParametricGateBackend to some other engine.\n\n The commands are passed onto the next engine, with parametric gates evaluated according to the substitutions\n passed in as argument, by calling the .receive() method of the receiving engine.\n\n Args:\n engine (BasicEngine): Some ProjectQ compiler engine. This may be another MainEngine instance or directly\n some ProjectQ backend or other compiler engine.\n subs (dict): Symbol substitutions to perform.\n\n Returns:\n A list of all the qubits that were allocated and will still be alive after sending the commands (ie. if a\n qubit is allocated and then de-allocated then it will not be returned).\n\n This can be useful in order to apply some additional gates to those qubits *after* having sent the\n commands to some other compiler engine.\n\n .. code-block:: python\n\n from projectq import MainEngine\n from projectq.backends import ParametricGateBackend\n\n eng = MainEngine(backend=ParametricGateBackend())\n qubit = eng.allocate_qubit()\n qureg = eng.allocate_qureg(10)\n eng.flush()\n\n other = MainEngine(engine_list=[]) # No compilation, only\n # simulation\n other_qureg = eng.backend.send_to(other)\n # NB: other_qureg has size 11 (1 + 10)!\n\n All(X) | other_qureg[1:] # Apply some X gates on the qubits\n # allocated by the `other`\n # MainEngine, leaving the ones from\n # the `eng` MainEngine untouched.\n\n Note:\n It is possible to make multiple calls to `send_to` with the same `ParametricGateBackend` and target\n engine. In that case, the backend will only send the commands it has received since the last call to\n `send_to`.\n\n See also:\n :py:meth:`ParametricGate.evaluate`\n \"\"\"\n # pylint: disable=protected-access\n\n if self == engine:\n return []\n\n if None in (self._min_allocated_id, self._max_allocated_id) and self._received_commands:\n raise RuntimeError(\n 'It appears there was no qubit allocation, so how come you have commands acting on qubits?'\n )\n\n qubit_id_shift = 0\n\n parent = engine\n add_qubits = _noop\n remove_qubits = _noop\n\n if engine.main_engine is not None:\n parent = engine.main_engine\n add_qubits = engine.main_engine.active_qubits.add\n remove_qubits = engine.main_engine.active_qubits.discard\n\n if engine.main_engine is self.main_engine:\n raise RuntimeError('Cannot send these commands to an engine with the same MainEngine!')\n\n # If there is a MainEngine on the other side, we might need to\n # adjust qubit IDs in order to avoid ID collisions.\n qubit_id_shift = 0\n if engine.main_engine in self._main_engine_qubit_idx:\n # At the moment, we do not support sending commands to a main engine if that main engine has allocated\n # new qubits since the last time we sent commands to it.\n if self._main_engine_qubit_idx[engine.main_engine] != engine.main_engine._qubit_idx:\n raise RuntimeError(\n 'MainEngine receiving the commands has allocated some qubits since the last time we sent to '\n 'it. Aborting.'\n )\n elif engine.main_engine._qubit_idx > self._min_allocated_id:\n qubit_id_shift = engine.main_engine._qubit_idx - self._min_allocated_id\n\n start_idx = self._last_sent_gate_idx.setdefault(parent, 0)\n allocated_qubits = []\n\n command_list = []\n for cmd in self._received_commands[start_idx:]:\n if isinstance(cmd.gate, FlushGate):\n command_list.append(Command(parent, gate=FlushGate(), qubits=([WeakQubitRef(parent, -1)],)))\n\n else:\n if subs is not None and cmd.gate.is_parametric():\n gate = cmd.gate.evaluate(subs=subs)\n else:\n gate = cmd.gate\n\n targets = tuple(\n [WeakQubitRef(parent, qubit.id + qubit_id_shift) for qubit in qureg] for qureg in cmd.qubits\n )\n\n new_cmd = Command(\n parent,\n gate,\n targets,\n [WeakQubitRef(parent, qubit.id + qubit_id_shift) for qubit in cmd.control_qubits],\n cmd.tags,\n )\n\n if isinstance(new_cmd.gate, AllocateQubitGate):\n allocated_qubits.append(new_cmd.qubits[0][0])\n add_qubits(new_cmd.qubits[0][0])\n elif isinstance(new_cmd.gate, DeallocateQubitGate):\n if new_cmd.qubits[0][0] in allocated_qubits:\n allocated_qubits.remove(new_cmd.qubits[0][0])\n remove_qubits(new_cmd.qubits[0][0])\n\n print(parent)\n if not parent.is_available(new_cmd):\n raise DestinationEngineGateUnsupported(\n 'Command not supported by destination engine: {}'.format(new_cmd)\n )\n\n command_list.append(new_cmd)\n\n if engine.main_engine is not None:\n # Set qubit ID in main engine so that subsequent qubit allocations\n # do not create collisions with our qubits\n engine.main_engine._qubit_idx = self._max_allocated_id + qubit_id_shift + 1\n self._main_engine_qubit_idx[engine.main_engine] = engine.main_engine._qubit_idx\n\n self._last_sent_gate_idx[parent] += len(command_list)\n engine.receive(command_list)\n return allocated_qubits\n","sub_path":"projectq/backends/_base/_parametric_backend.py","file_name":"_parametric_backend.py","file_ext":"py","file_size_in_byte":10121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"626755284","text":"from .models import Category\nimport moneyed\nfrom moneyed.localization import _FORMATTER\nfrom decimal import ROUND_HALF_EVEN\n\n_FORMATTER.add_sign_definition(\"DEFAULT\", moneyed.RUB, suffix=' ₽')\n_FORMATTER.add_formatting_definition(\n 'ru_RU', group_size=3, group_separator=\" \", decimal_point=\".\",\n positive_sign=\"\", trailing_positive_sign=\"\",\n negative_sign=\"-\", trailing_negative_sign=\"\",\n rounding_method=ROUND_HALF_EVEN\n)\n\n\ndef categories(request):\n return {\n 'abstract_categories': Category.objects.filter(parent_category__isnull=True)\n }\n","sub_path":"categories/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"387809935","text":"# Med 1 40ms min_heap\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n min_heap = [-float(\"inf\")] * k\n heapq.heapify(min_heap)\n for num in nums:\n if num > min_heap[0]:\n heapq.heappop(min_heap)\n heapq.heappush(min_heap, num)\n return(min_heap[0])\n \n \n \n \n \n \n# Med 2 44ms max_heap\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n nums = [-num for num in nums]\n heapq.heapify(nums)\n for i in range(k):\n res = heapq.heappop(nums)\n return(-res)\n\n \n \n \n \n# Med 3 20ms sort\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n return(sorted(nums, reverse = True)[k-1])\n","sub_path":"215. Kth Largest Element in an Array.py","file_name":"215. Kth Largest Element in an Array.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"329464401","text":"\"\"\"\r\nML Project\r\nSVM Classifier\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import *\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\n\r\ndef get_data():\r\n \"\"\"Reads the data from defined file names features.csv and tracks.csv and returns them\r\n\r\n This function gives the data frames new indices, because some indices are skipped and\r\n that gives us some troubles when using k-fold cross validation.\r\n We tested whether the order of original track indices (2.3.5,10,20... etc) is equal in\r\n both data frames, and it turns out it is the case. The indices are thus safely removed.\r\n \"\"\"\r\n features_file = \"fma_metadata/features.csv\"\r\n genres_file = \"fma_metadata/tracks.csv\"\r\n\r\n features = pd.read_csv(features_file, header=[0, 1, 2], skiprows=[3])\r\n print(\"The shape of features is:{}\".format(features.shape))\r\n\r\n genres = pd.read_csv(genres_file, header=[0, 1], skiprows=[2])\r\n # Picked the most generic \"genres\" column\r\n genres = genres[\"track\", \"genres\"]\r\n print(\"The shape of genres is:{}\".format(genres.shape))\r\n\r\n # The number of rows should be equal in the shapes (106574)\r\n return features, genres\r\n\r\n\r\ndef clean_data(features, genres):\r\n \"\"\"Some rows in the csv files have missing values or worse, wrong values. For example,\r\n see tracks 1020, 1021, 1022 and 1023 in tracks.csv. Their genres are messed up, because\r\n all values seem to have shifted one column to the right in these rows.\r\n Therefore, we check whether the genre in the row has the correct format:\r\n [x] where x is an integer or multiple integers separated by commas.\"\"\"\r\n\r\n features = features.drop(labels=('feature', 'statistics', 'number'), axis=1) # Drop track_id\r\n\r\n drop_indices = []\r\n for index, genre in genres.items():\r\n if not (genre.startswith(\"[\") and genre.endswith(\"]\") and len(genre) > 2):\r\n # This is a row with a missing or corrupted value, we remove the row\r\n drop_indices.append(index)\r\n\r\n genres = genres.drop(labels=drop_indices, axis=0)\r\n features = features.drop(labels=drop_indices,\r\n axis=0) # We have to remove the same track from the features data frame\r\n\r\n # Reset indices, so that we do not get NaNs in shuffle split\r\n genres = genres.reset_index(drop=True).squeeze()\r\n features = features.set_index(pd.Index([i for i in range(len(features))]), drop=True)\r\n\r\n print(\"The shape of features after cleaning is:{}\".format(features.shape))\r\n print(\"The shape of genres after cleaning is:{}\".format(genres.shape))\r\n\r\n return features, genres\r\n\r\n\r\ndef single_genres(genres):\r\n \"\"\"Takes the genres list and returns only one genre back if multiple genres are present\"\"\"\r\n for index, genre in genres.items():\r\n split = genre.split(\",\")\r\n new_genre = split[0]\r\n new_genre = new_genre.strip(\"[]\")\r\n genres[index] = int(new_genre)\r\n print(\"The shape of genres after single is:{}\".format(genres.shape))\r\n\r\n return genres\r\n\r\n\r\ndef new_single_genres(genres, val):\r\n \"\"\"Takes the genres list and returns only one genre back if multiple genres are present\"\"\"\r\n genres_file = \"fma_metadata/genres.csv\"\r\n reference_genres = pd.read_csv(genres_file)\r\n reference_tracks = reference_genres.iloc[:, 1]\r\n reference_genres = reference_genres.iloc[:, 0]\r\n\r\n for index, genre in genres.items():\r\n split = genre.split(\",\")\r\n if len(split) == 1:\r\n new_genre = split[0]\r\n new_genre = new_genre.strip(\"[]\")\r\n genres[index] = int(new_genre)\r\n elif len(split) > 1:\r\n new_genre = [int(item.strip(\" [ ] \")) for item in split]\r\n count = {}\r\n for indices, value in reference_genres.items():\r\n if value in new_genre:\r\n count[value] = reference_tracks[indices]\r\n counts = {k: v for k, v in sorted(count.items(), key=lambda item: item[1])}\r\n if val == \"high\":\r\n genres[index] = int(list(counts.keys())[-1])\r\n elif val == \"low\":\r\n genres[index] = int(list(counts.keys())[0])\r\n print(\"The shape of genres after single is:{}\".format(genres.shape))\r\n\r\n return genres\r\n\r\n\r\ndef threshold_genres_classes(features, genres, threshold):\r\n \"\"\"Limits the number of classes as per the threshold\"\"\"\r\n drop_indices = []\r\n drop_index = []\r\n value_counts = genres.value_counts()\r\n for index, value in value_counts.items():\r\n if value < threshold:\r\n drop_index.append(index)\r\n for values in drop_index:\r\n for index, value in genres.items():\r\n if value == values:\r\n drop_indices.append(index)\r\n\r\n genres = genres.drop(labels=drop_indices, axis=0)\r\n features = features.drop(labels=drop_indices,\r\n axis=0) # We have to remove the same track from the features data frame\r\n\r\n # Reset indices, so that we do not get NaNs in shuffle split\r\n genres = genres.reset_index(drop=True).squeeze()\r\n features = features.set_index(pd.Index([i for i in range(len(features))]), drop=True)\r\n\r\n print(\"The shape of features after threshold is:{}\".format(features.shape))\r\n print(\"The shape of genres after threshold is:{}\".format(genres.shape))\r\n\r\n return features, genres\r\n\r\n\r\ndef accuracy(c_m):\r\n \"\"\"Accuracy of Confusion Matrix\"\"\"\r\n diagonal_sum = c_m.trace()\r\n sum_of_all_elements = c_m.sum()\r\n\r\n return diagonal_sum / sum_of_all_elements\r\n\r\n\r\nFeatures, Genres = get_data()\r\nFeatures, Genres = clean_data(Features, Genres)\r\nGenres = new_single_genres(Genres, \"high\")\r\nFeatures, Genres = threshold_genres_classes(Features, Genres, 2500)\r\n# Genres = Genres.astype('int')\r\n\r\nprint(\"Genre Classes\", len(set(Genres)))\r\n\r\n\"\"\"\r\nFeatures = normalize(Features)\r\npca = PCA(n_components=100)\r\npca.fit(Features)\r\nFeatures = pca.transform(Features)\r\n\"\"\"\r\n\r\nScale = StandardScaler()\r\nScale.fit(Features)\r\nFeatures = Scale.transform(Features)\r\nEncoder = LabelEncoder()\r\nEncoder.fit(Genres)\r\nGenres = Encoder.transform(Genres)\r\n\r\n# {'C': [1, 10, 100, 1000, 10000], 'gamma': [0.01, 0.001, 0.0001], 'kernel': ['polynomial'], 'degree':[3, 4]}\r\nparameter_candidates = [\r\n {'C': [1, 10, 100], 'gamma': [0.01, 0.001, 0.0001], 'kernel': ['rbf']},\r\n]\r\n\r\nSeenFeatures, UnseenFeatures, SeenGenres, UnseenGenres = train_test_split(Features, Genres, train_size=0.8,\r\n stratify=Genres)\r\n\r\nprint(SeenFeatures)\r\nprint(SeenFeatures.shape)\r\nprint(SeenGenres)\r\nprint(SeenGenres.shape)\r\nprint(\"Genre Classes\", len(set(SeenGenres)))\r\nprint(UnseenFeatures)\r\nprint(UnseenFeatures.shape)\r\nprint(UnseenGenres)\r\nprint(UnseenGenres.shape)\r\nprint(\"Genre Classes\", len(set(UnseenGenres)))\r\n\r\nSVCClassifier = SVC(C=10)\r\nprint(SVCClassifier)\r\nSVCClassifier.fit(SeenFeatures, SeenGenres)\r\nPredictGenres = SVCClassifier.predict(UnseenFeatures)\r\ncm = confusion_matrix(PredictGenres, UnseenGenres)\r\n\r\n\"\"\"\r\nclf = GridSearchCV(estimator=SVC(), param_grid=parameter_candidates, n_jobs=-1)\r\nprint(parameter_candidates)\r\nprint(clf)\r\nclf.fit(SeenFeatures, SeenGenres)\r\nprint('Best score for data1:', clf.best_score_)\r\nprint(clf.score(UnseenFeatures, UnseenGenres))\r\nprint('Best C:', clf.best_estimator_.C)\r\nprint('Best Kernel:', clf.best_estimator_.kernel)\r\nprint('Best Gamma:', clf.best_estimator_.gamma)\r\n\"\"\"\r\n\r\nprint(SVCClassifier.score(SeenFeatures, SeenGenres))\r\nprint(SVCClassifier.score(UnseenFeatures, UnseenGenres))\r\nprint(\"Accuracy:\", accuracy(cm))\r\nprint(classification_report(PredictGenres, UnseenGenres))\r\nprint(cm)\r\n","sub_path":"SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"626135815","text":"#L(M1-18): {w | w contains the substring '00' or '11'}\r\n\r\ndef problem_1_18(test):\r\n\r\n #Defining required variables and methods\r\n \r\n acceptable = None #boolean value: returns true if it is acceptable, false otherwise\r\n i = 0 #our incrementor variable\r\n\r\n #This is the initial state, represented by q0\r\n def q0(test):\r\n nonlocal i\r\n nonlocal acceptable\r\n acceptable = False\r\n if len(test) > 0:\r\n if test[i:i+1] == \"0\":\r\n q1(test[i+1:])\r\n else: #assuming char is '1'\r\n q2(test[i+1:])\r\n \r\n def q1(test):\r\n nonlocal i\r\n nonlocal acceptable\r\n acceptable = False\r\n if len(test) > 0:\r\n if test[i:i+1] == \"0\":\r\n q3(test[i+1:])\r\n else: #assuming char is '1'\r\n q2(test[i+1:])\r\n \r\n def q2(test):\r\n nonlocal i\r\n nonlocal acceptable\r\n acceptable = False\r\n if len(test) > 0:\r\n if test[i:i+1] == \"0\":\r\n q1(test[i+1:])\r\n else: #assuming char is '1'\r\n q3(test[i+1:])\r\n \r\n def q3(test):\r\n nonlocal i\r\n nonlocal acceptable\r\n acceptable = True\r\n if len(test) > 0:\r\n if test[i:i+1] == \"0\" or test[i:i+1] == \"1\":\r\n q3(test[i+1:])\r\n\r\n ##########################################################################################################\r\n\r\n #start of FA. Begins at q0, the initial state \r\n\r\n q0(test)\r\n\r\n #Returns the boolean value (Acceptable -> True, Rejectable -> False)\r\n return acceptable\r\n\r\n\r\n ###########################################################################################################\r\n\r\nif __name__ == \"__main__\":\r\n \r\n #Creating Test Cases for the Finite Automata\r\n \r\n test1 = \"00\" #acceptable\r\n test2 = \"01010101\" #rejectable\r\n test3 = \"\" #rejectable\r\n test4 = \"10101\" #rejectable\r\n test5 = \"101011010\" #acceptable\r\n test6 = \"11\" #acceptable\r\n\r\n print(\"Test Case 1: \\\"00\\\"\", problem_1_18(test1),'', sep=\"\\n\")\r\n print(\"Test Case 2: \\\"01010101\\\"\", problem_1_18(test2),'', sep=\"\\n\")\r\n print(\"Test Case 3: \\\"\\\"\", problem_1_18(test3),'', sep=\"\\n\")\r\n print(\"Test Case 4: \\\"10101\\\"\", problem_1_18(test4),'', sep=\"\\n\")\r\n print(\"Test Case 5: \\\"101011010\\\"\", problem_1_18(test5),'', sep=\"\\n\")\r\n print(\"Test Case 6: \\\"11\\\"\", problem_1_18(test6),'', sep=\"\\n\")\r\n","sub_path":"Part 1 Python Code/1-18 comp algs_Eric Einhaus.py","file_name":"1-18 comp algs_Eric Einhaus.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598399805","text":"import termcolor\n\nclass Cell:\n def __init__(self, is_mine, adj_mines):\n self.is_covered = True\n self.is_lethal = False\n self.is_flagged = False\n self.is_mine = is_mine\n self.adj_mines = adj_mines\n self.mine_colors = {1 : 'blue',\n 2 : 'green',\n 3 : 'red',\n 4 : 'magenta',\n 5 : 'yellow',\n 6 : 'cyan',\n 7 : 'grey',\n 8 : 'white',\n 9 : 'white'}\n\n def __repr__(self):\n if self.is_flagged:\n s = 'F'\n elif self.is_covered:\n s = '.'\n elif self.is_mine:\n if self.is_lethal:\n s = termcolor.colored('*', 'white', 'on_red')\n else:\n s = '*'\n elif self.adj_mines == 0:\n s = ' '\n else:\n color = self.mine_colors[self.adj_mines]\n s = termcolor.colored(str(self.adj_mines), color) \n return s\n","sub_path":"cell.py","file_name":"cell.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609850382","text":"import math\n\nimport cv2\nimport numpy as np\nfrom scipy.ndimage import morphology as spndm\n\n\ndef pad_or_crop_to_shape(I, out_shape, border_color=(255, 255, 255)):\n\tborder_size = (out_shape[0] - I.shape[0], out_shape[1] - I.shape[1])\n\tif border_size[0] > 0:\n\t\tI = cv2.copyMakeBorder(I,\n\t\t int(math.floor(border_size[0] / 2.0)),\n\t\t int(math.ceil(border_size[0] / 2.0)), 0, 0,\n\t\t cv2.BORDER_CONSTANT, value=border_color)\n\telif border_size[0] < 0:\n\t\tI = I[-int(math.floor(border_size[0] / 2.0)): I.shape[0]\n\t\t + int(math.ceil(border_size[0] / 2.0)), :, :]\n\n\tif border_size[1] > 0:\n\t\tI = cv2.copyMakeBorder(I, 0, 0,\n\t\t int(math.floor(border_size[1] / 2.0)),\n\t\t int(math.ceil(border_size[1] / 2.0)),\n\t\t cv2.BORDER_CONSTANT, value=border_color)\n\telif border_size[1] < 0:\n\t\tI = I[:, -int(math.floor(border_size[1] / 2.0)): I.shape[1]\n\t\t + int(math.ceil(border_size[1] / 2.0)), :]\n\n\treturn I\n\n\ndef normalize(X):\n\tif X is None:\n\t\treturn None\n\treturn np.clip(X * 2.0 - 1.0, -1., 1.)\n\n\ndef inverse_normalize(X):\n\treturn np.clip((X + 1.0) * 0.5, 0., 1.)\n\n\ndef seg_to_bounds(seg, delete_bound=5, save_raw_bounds_to_file=None, dilate_size=5, blur_size=5):\n\tseg = np.mean(seg, axis=-1) # grayscale\n\tbounds = segutils.seg2contour(seg, contour_type='both')\n\tbounds[bounds > 0] = 1\n\n\t# delete any boundaries that are too close to the edge\n\tbounds[:delete_bound, :] = 0\n\tbounds[-delete_bound:, :] = 0\n\tbounds[:, :delete_bound] = 0\n\tbounds[:, -delete_bound:] = 0\n\n\tif save_raw_bounds_to_file:\n\t\tcv2.imwrite(save_raw_bounds_to_file, bounds * 255)\n\n\tif dilate_size > 0:\n\t\tdilate_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (dilate_size, dilate_size))\n\t\tbounds = cv2.dilate(bounds.astype(np.float32), dilate_kernel)\n\n\tif blur_size > 0:\n\t\tbounds = cv2.GaussianBlur(bounds, ksize=(0, 0), sigmaX=blur_size, sigmaY=blur_size)\n\tif np.max(bounds) > 0:\n\t\tbounds = bounds / np.max(bounds)\n\treturn bounds\n\n\ndef get_segmentation_mask(I, mask_color=(1., 1., 1.)):\n\tchannel_masks = I.copy()\n\tfor c in range(3):\n\t\tchannel_masks[:, :, c] = (I[:, :, c] == mask_color[c]).astype(int)\n\tmask = np.prod(channel_masks, axis=-1)\n\tk = np.ones((3, 3), dtype=np.float32)\n\tmask = spndm.grey_closing(mask, footprint=k)\n\tmask = spndm.grey_opening(mask, footprint=k)\n\tmask = np.clip(mask, 0., 1.)\n\treturn mask\n\n\ndef create_gaussian_kernel(sigma, n_sigmas_per_side=8, n_dims=2):\n\tt = np.linspace(-sigma * n_sigmas_per_side / 2, sigma * n_sigmas_per_side / 2, int(sigma * n_sigmas_per_side + 1))\n\tgauss_kernel_1d = np.exp(-0.5 * (t / sigma) ** 2)\n\n\tif n_dims == 2:\n\t\tgauss_kernel_2d = gauss_kernel_1d[:, np.newaxis] * gauss_kernel_1d[np.newaxis, :]\n\telse:\n\t\tgauss_kernel_2d = gauss_kernel_1d[:, np.newaxis, np.newaxis] * gauss_kernel_1d[np.newaxis, np.newaxis,\n\t\t :] * gauss_kernel_1d[np.newaxis, :, np.newaxis]\n\tgauss_kernel_2d = gauss_kernel_2d / np.sum(gauss_kernel_2d)\n\n\t#\tcv2.imwrite('gauss_x.jpg', gauss_kernel_2d[gauss_kernel_2d.shape[0]/2, :, :]*255)\n\t#\tcv2.imwrite('gauss_y.jpg', gauss_kernel_2d[:,gauss_kernel_2d.shape[1]/2, :, ]*255)\n\t#\tcv2.imwrite('gauss_z.jpg', gauss_kernel_2d[:, :,gauss_kernel_2d.shape[2]/2 ]*255)\n\t# gauss_kernel_2d = np.reshape(gauss_kernel_2d, gauss_kernel_2d.shape + (1,1))\n\treturn gauss_kernel_2d\n","sub_path":"image_utils.py","file_name":"image_utils.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"534191207","text":"\nimport calendar\nimport datetime\nimport json\nimport os\nimport os.path\nimport shutil\nimport traceback\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport urllib.error\nimport urllib.parse\n\nfrom sqlalchemy import and_\nfrom sqlalchemy import or_\nimport sqlalchemy.exc\nfrom sqlalchemy_continuum.utils import version_table\n\nif __name__ == \"__main__\":\n\timport logSetup\n\tlogSetup.initLogging()\n\nfrom WebMirror.Engine import SiteArchiver\nimport WebMirror.OutputFilters.util.feedNameLut as feedNameLut\nimport WebMirror.rules\nimport WebMirror.SiteSync.fetch\nimport WebMirror.SpecialCase\nimport WebMirror.NewJobQueue\n\nimport RawArchiver.RawActiveModules\nimport RawArchiver.RawEngine\n\nimport common.database as db\nimport common.Exceptions\nimport common.management.file_cleanup\n\nimport Misc.HistoryAggregator.Consolidate\n\nimport flags\nimport config\nfrom config import C_RAW_RESOURCE_DIR\n\nimport WebMirror.TimedTriggers.QueueTriggers\nimport WebMirror.OutputFilters.rss.FeedDataParser\n\ndef exposed_remote_fetch_enqueue(url):\n\t'''\n\tPlace a normal fetch request for url `url` into the remote fetch queue.\n\n\tRequires the FetchAgent service to be running.\n\t'''\n\n\tprint(\"Enqueueing \")\n\ttrig = WebMirror.TimedTriggers.QueueTriggers.NuQueueTrigger()\n\ttrig.enqueue_url(url)\n\ndef exposed_trigger_nu_homepage_fetch():\n\t'''\n\tTrigger testing for the QueueTrigger system\n\t'''\n\ttrig = WebMirror.TimedTriggers.QueueTriggers.NuQueueTrigger()\n\ttrig.go()\n\n\ndef exposed_fetch(url, debug=True, rss_debug=False):\n\t'''\n\tDo a synchronous fetch of content from url `url`.\n\t'''\n\n\t# try:\n\t# \tWebMirror.SpecialCase.startAmqpFetcher()\n\t# except RuntimeError: # Fetcher already started\n\t# \tpass\n\n\tif rss_debug:\n\t\tprint(\"Debugging RSS\")\n\t\tflags.RSS_DEBUG = True\n\n\tparsed = urllib.parse.urlparse(url)\n\troot = urllib.parse.urlunparse((parsed[0], parsed[1], \"\", \"\", \"\", \"\"))\n\n\tnew = db.WebPages(\n\t\turl = url,\n\t\tstarturl = root,\n\t\tnetloc = parsed.netloc,\n\t\tdistance = 50000,\n\t\tis_text = True,\n\t\tpriority = 500000,\n\t\ttype = 'unknown',\n\t\tfetchtime = datetime.datetime.now(),\n\t\t)\n\n\tif debug:\n\t\tprint(new)\n\n\ttry:\n\t\tarchiver = SiteArchiver(None, db.get_db_session(), None)\n\t\tjob = archiver.synchronousJobRequest(url, ignore_cache=True)\n\texcept Exception as e:\n\t\ttraceback.print_exc()\n\tfinally:\n\t\tdb.delete_db_session()\n\ndef exposed_fetch_silent(tgt):\n\t'''\n\tIdentical to `test_retrieve`, except debug printing is supressed.\n\t'''\n\texposed_fetch(tgt, debug=False)\n\ndef exposed_fetch_rss(tgt):\n\t'''\n\tIdentical to `test_retrieve`, except debug printing is supressed and RSS debugging is enabled.\n\t'''\n\texposed_fetch(tgt, debug=False, rss_debug=True)\n\ndef exposed_raw_test_retrieve(url):\n\t'''\n\tLower level fetch test, otherwise similar to `test_retreive`\n\t'''\n\n\t# try:\n\t# \tWebMirror.SpecialCase.startAmqpFetcher()\n\t# except RuntimeError: # Fetcher already started\n\t# \tpass\n\n\n\tparsed = urllib.parse.urlparse(url)\n\troot = urllib.parse.urlunparse((parsed[0], parsed[1], \"\", \"\", \"\", \"\"))\n\n\n\tsess = db.get_db_session()\n\n\trow = sess.query(db.RawWebPages).filter(db.RawWebPages.url == url).scalar()\n\tif row:\n\t\trow.state = 'new'\n\telse:\n\t\trow = db.RawWebPages(\n\t\t\turl = url,\n\t\t\tstarturl = root,\n\t\t\tnetloc = parsed.netloc,\n\t\t\tdistance = 50000,\n\t\t\tpriority = 500000,\n\t\t\tstate = 'new',\n\t\t\tfetchtime = datetime.datetime.now(),\n\t\t\t)\n\t\tsess.add(row)\n\n\n\ttry:\n\t\tarchiver = RawArchiver.RawEngine.RawSiteArchiver(\n\t\t\ttotal_worker_count = 1,\n\t\t\tworker_num = 0,\n\t\t\tnew_job_queue = None,\n\t\t\tcookie_lock = None,\n\t\t\tdb_interface = sess,\n\t\t\tresponse_queue = None\n\t\t\t)\n\t\tjob = archiver.do_job(row)\n\texcept Exception as e:\n\t\ttraceback.print_exc()\n\tfinally:\n\t\tdb.delete_db_session()\n\ndef exposed_test_head(url, referrer):\n\t'''\n\tDo a HTTP HEAD for url `url`, passing the referrer `referrer`.\n\t'''\n\n\ttry:\n\t\tWebMirror.SpecialCase.startAmqpFetcher()\n\texcept RuntimeError: # Fetcher already started\n\t\tpass\n\n\ttry:\n\t\tWebMirror.SpecialCase.blockingRemoteHead(url, referrer)\n\texcept Exception as e:\n\t\ttraceback.print_exc()\n\tfinally:\n\t\tWebMirror.SpecialCase.stopAmqpFetcher()\n\n\tprint(\"exposed_test_head complete!\")\n\ndef exposed_test_all_rss():\n\t'''\n\tFetch all RSS feeds and process each. Done with 8 parallel workers.\n\t'''\n\tprint(\"fetching and debugging RSS feeds\")\n\trules = WebMirror.rules.load_rules()\n\tfeeds = [item['feedurls'] for item in rules]\n\tfeeds = [item for sublist in feeds for item in sublist]\n\n\tflags.RSS_DEBUG = True\n\twith ThreadPoolExecutor(max_workers=8) as executor:\n\t\tfor url in feeds:\n\t\t\ttry:\n\t\t\t\texecutor.submit(exposed_fetch, url, debug=False)\n\t\t\texcept common.Exceptions.DownloadException:\n\t\t\t\tprint(\"failure downloading page!\")\n\t\t\texcept urllib.error.URLError:\n\t\t\t\tprint(\"failure downloading page!\")\n\ndef exposed_longest_rows():\n\t'''\n\tFetch the rows from the database where the `content` field is longest.\n\tReturn is limited to the biggest 50 rows.\n\tVERY SLOW (has to scan the entire table)\n\t'''\n\tprint(\"Getting longest rows from database\")\n\thave = db.get_db_session().execute(\"\"\"\n\t\tSELECT\n\t\t\tid, url, length(content), content\n\t\tFROM\n\t\t\tweb_pages\n\t\tORDER BY\n\t\t\tLENGTH(content) DESC NULLS LAST\n\t\tLIMIT 50;\n\t\t\"\"\")\n\tprint(\"Rows:\")\n\n\timport os\n\timport os.path\n\n\tsavepath = \"./large_files/\"\n\tfor row in have:\n\t\tprint(row[0], row[1])\n\t\ttry:\n\t\t\tos.makedirs(savepath)\n\t\texcept FileExistsError:\n\t\t\tpass\n\t\twith open(os.path.join(savepath, \"file %s.txt\" % row[0]), \"wb\") as fp:\n\t\t\turlst = \"URL: %s\\n\\n\" % row[1]\n\t\t\tsize = \"Length: %s\\n\\n\" % row[2]\n\t\t\tfp.write(urlst.encode(\"utf-8\"))\n\t\t\tfp.write(size.encode(\"utf-8\"))\n\t\t\tfp.write(\"{}\".format(row[3]).encode(\"utf-8\"))\n\ndef exposed_fix_null():\n\t'''\n\tReset any rows in the table where the `ignoreuntiltime` column\n\tis null. Updates in 50K row increments.11\n\t'''\n\tstep = 50000\n\n\n\tend = db.get_db_session().execute(\"\"\"SELECT MAX(id) FROM web_pages WHERE ignoreuntiltime IS NULL;\"\"\")\n\tend = list(end)[0][0]\n\n\tstart = db.get_db_session().execute(\"\"\"SELECT MIN(id) FROM web_pages WHERE ignoreuntiltime IS NULL;\"\"\")\n\tstart = list(start)[0][0]\n\n\tchanged = 0\n\n\tif not start:\n\t\tprint(\"No null rows to fix!\")\n\t\treturn\n\n\tstart = start - (start % step)\n\n\tfor x in range(start, end, step):\n\t\t# SQL String munging! I'm a bad person!\n\t\t# Only done because I can't easily find how to make sqlalchemy\n\t\t# bind parameters ignore the postgres specific cast\n\t\t# The id range forces the query planner to use a much smarter approach which is much more performant for small numbers of updates\n\t\thave = db.get_db_session().execute(\"\"\"UPDATE web_pages SET ignoreuntiltime = 'epoch'::timestamp WHERE ignoreuntiltime IS NULL AND id < %s AND id >= %s;\"\"\" % (x, x-step))\n\t\t# print()\n\t\tprint('%10i, %7.4f, %6i' % (x, x/end * 100, have.rowcount))\n\t\tchanged += have.rowcount\n\t\tif changed > 10000:\n\t\t\tprint(\"Committing (%s changed rows)....\" % changed, end=' ')\n\t\t\tdb.get_db_session().commit()\n\t\t\tprint(\"done\")\n\t\t\tchanged = 0\n\tdb.get_db_session().commit()\n\ndef exposed_delete_comment_feed_items():\n\t'''\n\tIterate over all retreived feed article entries, and delete any that look\n\tlike they're comment feed articles.\n\t'''\n\tsess = db.get_db_session()\n\tbad = sess.query(db.FeedItems) \\\n\t\t\t.filter(or_(\n\t\t\t\tdb.FeedItems.contenturl.like(\"%#comment-%\"),\n\t\t\t\tdb.FeedItems.contenturl.like(\"%CommentsForInMyDaydreams%\"),\n\t\t\t\tdb.FeedItems.contenturl.like(\"%www.fanfiction.net%\"),\n\t\t\t\tdb.FeedItems.contenturl.like(\"%www.fictionpress.com%\"),\n\t\t\t\tdb.FeedItems.contenturl.like(\"%www.booksie.com%\"))) \\\n\t\t\t.order_by(db.FeedItems.contenturl) \\\n\t\t\t.all()\n\n\tcount = 0\n\tfor bad in bad:\n\t\tprint(bad.contenturl)\n\n\t\twhile bad.author:\n\t\t\tbad.author.pop()\n\t\twhile bad.tags:\n\t\t\tbad.tags.pop()\n\t\tsess.delete(bad)\n\t\tcount += 1\n\t\tif count % 1000 == 0:\n\t\t\tprint(\"Committing at %s\" % count)\n\t\t\tsess.commit()\n\n\tprint(\"Done. Committing...\")\n\tsess.commit()\n\ndef exposed_update_feed_names():\n\t'''\n\tApply any new feednamelut names to existing fetched RSS posts.\n\t'''\n\tfor key, value in feedNameLut.mapper.items():\n\t\tfeed_items = db.get_db_session().query(db.FeedItems) \\\n\t\t\t\t.filter(db.FeedItems.srcname == key) \\\n\t\t\t\t.all()\n\t\tif feed_items:\n\t\t\tfor item in feed_items:\n\t\t\t\titem.srcname = value\n\t\t\tprint(len(feed_items))\n\t\t\tprint(key, value)\n\t\t\tdb.get_db_session().commit()\n\ndef exposed_clear_bad():\n\t'''\n\tIterate over all blocked strings from the various YAML rules,\n\tdeleting any occurances of each from the database.\n\tSLOW\n\t'''\n\tfrom sqlalchemy.dialects import postgresql\n\n\trules = WebMirror.rules.load_rules()\n\n\tfor ruleset in rules:\n\n\t\tprint(\"Cleaning ruleset\")\n\t\t# print(ruleset['netlocs'])\n\t\t# print(ruleset.keys())\n\t\tfor badword in ruleset['badwords']:\n\t\t\tif not ruleset['netlocs']:\n\t\t\t\tcontinue\n\t\t\tif \"%\" in badword:\n\t\t\t\tprint(badword)\n\t\t\telse:\n\t\t\t\tprint(\"Deleting items containing string: '%s'\" % badword)\n\t\t\t\tq = db.get_db_session().query(db.WebPages) \\\n\t\t\t\t\t.filter(db.WebPages.netloc.in_(ruleset['netlocs'])) \\\n\t\t\t\t\t.filter(db.WebPages.url.like(\"%{}%\".format(badword)))\n\t\t\t\titems = q.count()\n\t\t\t\tif items:\n\t\t\t\t\tprint(\"%s results for : '%s'\" % (items, badword))\n\n\t\t\t\t\tq = db.get_db_session().query(db.WebPages) \\\n\t\t\t\t\t\t.filter(db.WebPages.netloc.in_(ruleset['netlocs'])) \\\n\t\t\t\t\t\t.filter(db.WebPages.url.like(\"%{}%\".format(badword))) \\\n\t\t\t\t\t\t.delete(synchronize_session=False)\n\t\t\t\t\tdb.get_db_session().commit()\n\ndef exposed_purge_invalid_urls(selected_netloc=None):\n\t'''\n\tIterate over each ruleset in the rules directory, and generate a compound query that will\n\tdelete any matching rows.\n\tFor rulesets with a large number of rows, or many badwords, this\n\tcan be VERY slow.\n\n\tSimilar in functionality to `clear_bad`, except it results in many fewer queryies,\n\tand is therefore likely much more performant.\n\t'''\n\n\tsess = db.get_db_session()\n\tfor ruleset in WebMirror.rules.load_rules():\n\n\t\tif (\n\t\t\t\t\t\t(ruleset['netlocs'] and ruleset['badwords'])\n\t\t\t\t\tand\n\t\t\t\t\t(\n\t\t\t\t\t\t(ruleset['netlocs'] and ruleset['badwords'] and selected_netloc is None)\n\t\t\t\t\t\tor\n\t\t\t\t\t\t(selected_netloc != None and selected_netloc in ruleset['netlocs'])\n\t\t\t\t\t)\n\t\t\t\t):\n\t\t\t# We have to delete from the normal table before the versioning table,\n\t\t\t# because deleting from the normal table causes inserts into the versioning table\n\t\t\t# due to the change tracking triggers.\n\n\t\t\tcount = 1\n\t\t\tands = [\n\t\t\t\t\tor_(*(db.WebPages.url.like(\"%{}%\".format(badword)) for badword in ruleset['badwords']))\n\t\t\t\t]\n\n\t\t\tif selected_netloc:\n\t\t\t\tands.append((db.WebPages.netloc == selected_netloc))\n\t\t\telse:\n\t\t\t\tands.append(db.WebPages.netloc.in_(ruleset['netlocs']))\n\n\n\t\t\tloc = and_(*ands)\n\t\t\t# print(\"Doing count on table \")\n\t\t\t# count = sess.query(db.WebPages) \\\n\t\t\t# \t.filter(or_(*opts)) \\\n\t\t\t# \t.count()\n\n\t\t\tif selected_netloc:\n\t\t\t\tprint(loc)\n\n\t\t\tif count == 0:\n\t\t\t\tprint(\"{num} items match badwords from file {file}. No deletion required \".format(file=ruleset['filename'], num=count))\n\t\t\telse:\n\t\t\t\tprint(\"{num} items match badwords from file {file}. Deleting \".format(file=ruleset['filename'], num=count))\n\n\t\t\t\tsess.query(db.WebPages) \\\n\t\t\t\t\t.filter(or_(*loc)) \\\n\t\t\t\t\t.delete(synchronize_session=False)\n\n\n\t\t\t# # Do the delete from the versioning table now.\n\t\t\tctbl = version_table(db.WebPages)\n\t\t\tloc2 = and_(\n\t\t\t\t\tctbl.c.netloc.in_(ruleset['netlocs']),\n\t\t\t\t\tor_(*(ctbl.c.url.like(\"%{}%\".format(badword)) for badword in ruleset['badwords']))\n\t\t\t\t)\n\t\t\t# print(\"Doing count on Versioning table \")\n\t\t\t# count = sess.query(ctbl) \\\n\t\t\t# \t.filter(or_(*opts)) \\\n\t\t\t# \t.count()\n\n\t\t\tif count == 0:\n\t\t\t\tprint(\"{num} items in versioning table match badwords from file {file}. No deletion required \".format(file=ruleset['filename'], num=count))\n\t\t\telse:\n\t\t\t\tprint(\"{num} items in versioning table match badwords from file {file}. Deleting \".format(file=ruleset['filename'], num=count))\n\n\t\t\t\tsess.query(ctbl) \\\n\t\t\t\t\t.filter(or_(*loc2)) \\\n\t\t\t\t\t.delete(synchronize_session=False)\n\n\n\n\t\t\tsess.commit()\n\n\n\t\t# print(ruleset['netlocs'])\n\t\t# print(ruleset['badwords'])\n\ndef exposed_sort_json(json_name):\n\t'''\n\tLoad a file of feed missed json entries, and sort it into\n\ta much nicer to read output format.\n\n\tUsed internally by the rss_db/rss_day/week/month functionality.\n\t'''\n\twith open(json_name) as fp:\n\t\tcont = fp.readlines()\n\tprint(\"Json file has %s lines.\" % len(cont))\n\n\tdata = {}\n\tfor line in cont:\n\t\tval = json.loads(line)\n\t\tname = val['SourceName']\n\t\tif not name in data:\n\t\t\tdata[name] = []\n\n\t\tdata[name].append(val)\n\tout = []\n\tfor key in data:\n\n\t\tout.append((data[key][0]['Have Func'], len(data[key]), data[key]))\n\n\tout.sort(key=lambda x: (x[0], x[1]*-1))\n\tout.sort(key=lambda x: (x[1]*-1))\n\n\tkey_order = [\n\t\t\"Have Func\",\n\t\t\"SourceName\",\n\t\t\"Title\",\n\t\t\"Tags\",\n\t\t\"Feed URL\",\n\t\t\"Vol\",\n\t\t\"Chp\",\n\t\t\"Frag\",\n\t\t\"Postfix\",\n\t\t\"GUID\",\n\t]\n\n\toutf = json_name+\".pyout\"\n\ttry:\n\t\tos.unlink(outf)\n\texcept FileNotFoundError:\n\t\tpass\n\n\twith open(outf, \"w\") as fp:\n\t\tfor item in out:\n\t\t\t# print(item[1])\n\t\t\titems = item[2]\n\t\t\t[tmp['Tags'].sort() for tmp in items]\n\t\t\titems.sort(key=lambda x: (x['Tags'], x['Title']))\n\n\t\t\tfor value in items:\n\t\t\t\tfor key in key_order:\n\t\t\t\t\tfp.write(\"%s, \" % ((key, value[key]), ))\n\t\t\t\tfp.write(\"\\n\")\n\ndef exposed_rss_db_sync(target = None, days=False, silent=False):\n\t'''\n\tFeed RSS feed history through the feedparsing system, generating a log\n\tfile of the feed articles that were not captured by the feed parsing system.\n\n\tTarget is an optional netloc. If not none, only feeds with that netloc are\n\t\tprocessed.\n\tDays is the number of days into the past to process. None results in all\n\t\tavailable history being read.\n\tSilent suppresses some debug printing to the console.\n\t'''\n\n\tjson_file = 'rss_filter_misses-1.json'\n\n\twrite_debug = True\n\tif silent:\n\t\tconfig.C_DO_RABBIT = False\n\tif target:\n\t\tconfig.C_DO_RABBIT = False\n\t\tflags.RSS_DEBUG = True\n\t\twrite_debug = False\n\telse:\n\t\ttry:\n\t\t\tos.unlink(json_file)\n\t\texcept FileNotFoundError:\n\t\t\tpass\n\n\timport WebMirror.processor.RssProcessor\n\tparser = WebMirror.processor.RssProcessor.RssProcessor(loggerPath = \"Main.RssDb\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageUrl = 'http://www.example.org',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpgContent = '',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype = 'application/atom+xml',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttransfer = False,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdebug_print = True,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdb_sess = None,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twrite_debug = write_debug)\n\n\n\tprint(\"Getting feed items....\")\n\n\tif target:\n\t\tprint(\"Limiting to '%s' source.\" % target)\n\t\tfeed_items = db.get_db_session().query(db.FeedItems) \\\n\t\t\t\t.filter(db.FeedItems.srcname == target) \\\n\t\t\t\t.order_by(db.FeedItems.srcname) \\\n\t\t\t\t.order_by(db.FeedItems.title) \\\n\t\t\t\t.all()\n\telif days:\n\t\tprint(\"RSS age override: \", days)\n\t\tcutoff = datetime.datetime.now() - datetime.timedelta(days=days)\n\t\tfeed_items = db.get_db_session().query(db.FeedItems) \\\n\t\t\t\t.filter(db.FeedItems.published > cutoff) \\\n\t\t\t\t.order_by(db.FeedItems.srcname) \\\n\t\t\t\t.order_by(db.FeedItems.title) \\\n\t\t\t\t.all()\n\telse:\n\t\tfeed_items = db.get_db_session().query(db.FeedItems) \\\n\t\t\t\t.order_by(db.FeedItems.srcname) \\\n\t\t\t\t.order_by(db.FeedItems.title) \\\n\t\t\t\t.all()\n\n\n\tprint(\"Feed items: \", len(feed_items))\n\n\tfor item in feed_items:\n\t\tctnt = {}\n\t\tctnt['srcname'] = item.srcname\n\t\tctnt['title'] = item.title\n\t\tctnt['tags'] = item.tags\n\t\tctnt['linkUrl'] = item.contenturl\n\t\tctnt['guid'] = item.contentid\n\t\tctnt['published'] = calendar.timegm(item.published.timetuple())\n\n\t\t# Pop()ed off in processFeedData().\n\t\tctnt['contents'] = 'wat'\n\n\t\ttry:\n\t\t\tparser.processFeedData(ctnt, tx_raw=False, tx_parse=not bool(days))\n\t\texcept ValueError:\n\t\t\tpass\n\t\t# print(ctnt)\n\tif target == None:\n\t\texposed_sort_json(json_file)\n\ndef exposed_rss_db_silent():\n\t'''\n\tEqivalent to rss_db_sync(None, False, True)\n\t'''\n\texposed_rss_db_sync(silent=True)\n\ndef exposed_rss_day():\n\t'''\n\tEqivalent to rss_db_sync(1)\n\n\tEffectively just processes the last day of feed entries.\n\t'''\n\texposed_rss_db_sync(days=1)\n\ndef exposed_rss_week():\n\t'''\n\tEqivalent to rss_db_sync(7)\n\n\tEffectively just processes the last week of feed entries.\n\t'''\n\texposed_rss_db_sync(days=7)\n\ndef exposed_rss_month():\n\t'''\n\tEqivalent to rss_db_sync(45)\n\n\tEffectively just processes the last 45 days of feed entries.\n\t'''\n\texposed_rss_db_sync(days=45)\n\n\ndef exposed_rss_missing_functions():\n\t'''\n\tPrint skeleton functions for the RSS source names that are\n\tnot present in the lookup map.\n\t'''\n\tWebMirror.OutputFilters.rss.FeedDataParser.print_missing_functions()\n\ndef exposed_filter_links(path):\n\t\"\"\"\n\tFilter a file of urls at `path`. If a url in the file\n\tis not already a start url in the mirror system, it\n\tis printed to the console.\n\t\"\"\"\n\tif not os.path.exists(path):\n\t\traise IOError(\"File at path '%s' doesn't exist!\" % path)\n\n\twith open(path, \"r\") as fp:\n\t\turls = fp.readlines()\n\turls = [item.strip() for item in urls if item.strip()]\n\n\t# print(urls)\n\n\thavestarts = []\n\tfor ruleset in WebMirror.rules.load_rules():\n\t\tif ruleset['starturls']:\n\t\t\thavestarts += ruleset['starturls']\n\n\tfor item in urls:\n\t\tif item not in havestarts:\n\t\t\tprint(item)\n\ndef get_page_title(wg, url):\n\tchunks = url.split(\"/\")\n\tbaseurl = \"/\".join(chunks[:3])\n\ttitle = urllib.parse.urlsplit(url).netloc\n\n\ttry:\n\t\tsoup = wg.getSoup(baseurl)\n\t\tif soup.title:\n\t\t\ttitle = soup.title.get_text().strip()\n\texcept Exception:\n\t\tpass\n\n\treturn title\n\ndef exposed_missing_lut(fetchTitle=False):\n\t'''\n\tIterate over distinct RSS feed sources in database,\n\tand print any for which there is not an entry in\n\tfeedDataLut.py to the console.\n\t'''\n\timport WebMirror.OutputFilters.util.feedNameLut as fnl\n\timport common.util.webFunctions as webFunctions\n\twg = webFunctions.WebGetRobust()\n\trules = WebMirror.rules.load_rules()\n\tfeeds = [item['feedurls'] for item in rules]\n\tfeeds = [item for sublist in feeds for item in sublist]\n\t# feeds = [urllib.parse.urlsplit(tmp).netloc for tmp in feeds]\n\tfor feed in feeds:\n\t\tif not fnl.getNiceName(feed):\n\t\t\tnetloc = urllib.parse.urlsplit(feed).netloc\n\t\t\ttitle = netloc\n\t\t\tif fetchTitle:\n\t\t\t\ttitle = get_page_title(wg, feed)\n\t\t\tprint('Missing: \"%s\" %s: \"%s\",' % (netloc, \" \" * (50 - len(netloc)), title))\n\ndef exposed_delete_feed(feed_name, do_delete, search_str):\n\t'''\n\tFeed name is the readable name of the feed, from feedNameLut.py.\n\tdo delete is a boolean that determines if the deletion is actually done, or the actions are\n\t\tjust previewed. Unless do_delete.lower() == \"true\", no action will actually be\n\t\ttaken.\n\tsearch_str is the string of items to search for. Searches are case sensitive, and the only\n\t\tcomponent of the feed that are searched within is the title.\n\t\tsearch_str is split on the literal character \"|\", for requiring multiple substrings\n\t\tbe in the searched title.\n\n\tDelete the rss entries for a feed, using a search key.\n\n\t'''\n\n\tsess = db.get_db_session()\n\titems = sess.query(db.FeedItems) \\\n\t\t.filter(db.FeedItems.srcname == feed_name) \\\n\t\t.all()\n\n\tdo_delete = \"true\" in do_delete.lower()\n\n\tsearchitems = search_str.split(\"|\")\n\tfor item in items:\n\t\titemall = \" \".join([item.title] + item.tags)\n\t\tif all([searchstr in itemall for searchstr in searchitems]):\n\t\t\tprint(itemall)\n\t\t\tif do_delete:\n\t\t\t\tprint(\"Deleting item\")\n\t\t\t\tsess.delete(item)\n\n\tsess.commit()\n\n\ndef exposed_nu_new():\n\t'''\n\tParse outbound netlocs from NovelUpdates releases, extracting\n\tany sites that are not known in the feednamelut.\n\t'''\n\n\timport WebMirror.OutputFilters.util.feedNameLut as fnl\n\tsess = db.get_db_session()\n\n\tnu_items = sess.query(db.NuReleaseItem) \\\n\t\t.filter(db.NuReleaseItem.validated == True) \\\n\t\t.filter(db.NuReleaseItem.actual_target != None) \\\n\t\t.all()\n\n\tnetlocs = [urllib.parse.urlsplit(row.actual_target).netloc for row in nu_items]\n\tprint(\"Nu outbound items: \", len(netlocs))\n\tnetlocs = set(netlocs)\n\n\tmissing = 0\n\tfor netloc in netlocs:\n\t\tif not fnl.getNiceName(None, netloc):\n\t\t\tfnl.getNiceName(None, netloc, debug=True)\n\t\t\tprint(\"Missing: \", netloc)\n\t\t\tmissing += 1\n\tprint(\"Nu outbound items: \", len(netlocs), \"missing:\", missing)\n\n\ndef exposed_fetch_other_feed_sources():\n\t'''\n\tWalk the listed pages for both AhoUpdates and NovelUpdates,\n\tretreiving a list of the translators from each.\n\t'''\n\tWebMirror.SiteSync.fetch.fetch_other_sites()\n\n\ndef exposed_fix_missing_history():\n\t'''\n\tFix any items that don't have an entry in the history table.\n\t'''\n\tMisc.HistoryAggregator.Consolidate.fix_missing_history()\n\ndef exposed_flatten_history():\n\t'''\n\tFlatten the page change history.\n\tThis limits the retained page versions to one-per-hour for the\n\tlast 48 hours, once per day for the last 32 days, and once per\n\tweek after that.\n\t'''\n\tMisc.HistoryAggregator.Consolidate.consolidate_history()\n\ndef exposed_flatten_fix_missing_history():\n\t'''\n\tFunctionally equivalent to `flatten_history`, `fix_missing_history`\n\t'''\n\tMisc.HistoryAggregator.Consolidate.consolidate_history()\n\tMisc.HistoryAggregator.Consolidate.fix_missing_history()\n\n\ndef exposed_test_new_job_queue():\n\t'''\n\tTesting function for NewJobQueue components\n\t'''\n\n\tinstance = WebMirror.NewJobQueue.JobAggregatorInternal(None, None)\n\n\twant = instance.outbound_job_wanted(\"www.novelupdates.com\", \"http://www.novelupdates.com/\")\n\tprint(want)\n\twant = instance.outbound_job_wanted(\"twitter.com\", \"https://twitter.com/Baka_Tsuki\")\n\tprint(want)\n\twant = instance.outbound_job_wanted(\"twitter.com\", \"https://twitter.com/Nano_Desu_Yo\")\n\tprint(want)\n\n\ndef exposed_drop_priorities():\n\t'''\n\tReset the priority of every row in the table to the IDLE_PRIORITY level\n\t'''\n\n\tstep = 10000\n\n\tsess = db.get_db_session()\n\tprint(\"Getting minimum row in need or update..\")\n\tstart = sess.execute(\"\"\"SELECT min(id) FROM web_pages WHERE priority < 500000\"\"\")\n\tstart = list(start)[0][0]\n\tprint(\"Minimum row ID: \", start, \"getting maximum row...\")\n\tstop = sess.execute(\"\"\"SELECT max(id) FROM web_pages WHERE priority < 500000\"\"\")\n\tstop = list(stop)[0][0]\n\tprint(\"Maximum row ID: \", stop)\n\n\tif not start:\n\t\tprint(\"No null rows to fix!\")\n\t\treturn\n\n\tprint(\"Need to fix rows from %s to %s\" % (start, stop))\n\tstart = start - (start % step)\n\n\tchanged = 0\n\tfor idx in range(start, stop, step):\n\t\ttry:\n\t\t\t# SQL String munging! I'm a bad person!\n\t\t\t# Only done because I can't easily find how to make sqlalchemy\n\t\t\t# bind parameters ignore the postgres specific cast\n\t\t\t# The id range forces the query planner to use a much smarter approach which is much more performant for small numbers of updates\n\t\t\thave = sess.execute(\"\"\"update web_pages set priority = 500000 where priority < 500000 AND id > {} AND id <= {};\"\"\".format(idx, idx+step))\n\t\t\t# print()\n\n\t\t\tprocessed = idx - start\n\t\t\ttotal_todo = stop - start\n\t\t\tprint('%10i, %10i, %7.4f, %6i' % (idx, stop, processed/total_todo * 100, have.rowcount))\n\t\t\tchanged += have.rowcount\n\t\t\tif changed > step:\n\t\t\t\tprint(\"Committing (%s changed rows)....\" % changed, end=' ')\n\t\t\t\tsess.commit()\n\t\t\t\tprint(\"done\")\n\t\t\t\tchanged = 0\n\n\t\texcept sqlalchemy.exc.OperationalError:\n\t\t\tsess.rollback()\n\t\texcept sqlalchemy.exc.InvalidRequestError:\n\t\t\tsess.rollback()\n\n\n\tsess.commit()\n","sub_path":"common/management/WebMirrorManage.py","file_name":"WebMirrorManage.py","file_ext":"py","file_size_in_byte":22811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"97590335","text":"\"\"\" Write a python function that takes no arguments,\n but will read the files in the current working directory and return a list of them.\n Test it while in a couple of directories. \"\"\"\nfrom pathlib import Path\n\n\ndef main():\n \"\"\" Prints each file in the current directory \"\"\"\n for file in Path('.').iterdir():\n print(file)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"solutions/mf/01/list_files_cwd.py","file_name":"list_files_cwd.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"610304513","text":"#!/usr/bin/env python\nimport re, os, sys, shutil\nfrom math import * \nfrom string import *\nfrom optparse import OptionParser\nimport operator\nimport bisect\n\n#from gene_set_manipulation import *\n#import BED\n\nplus = re.compile(\"\\+\");\nminus = re.compile(\"\\-\");\n\nDir = os.getcwd();\n\n\ndef summit_region_to_bed(infile, outfile, column = -1, width = 100):\n\tfile = open(infile,'r')\n\toutput = open(outfile, 'w')\n\tfor line in file:\n\t\tif not re.match(\"#\", line):\n\t\t\tline = line.strip()\n\t\t\tsline = line.split()\n\t\t\tif (len(sline)>0):\n\t\t\t\tchrom = sline[0]\n\t\t\t\tstart = atoi(sline[1])\n\t\t\t\tend = atoi(sline[2])\n\t\t\t\tlength = end - start\n\t\t\t\tif length <= width: \n\t\t\t\t\toutput.write(sline[0] + '\\t' + sline[1] + '\\t' + sline[2] + '\\n')\n\t\t\t\telse:\n\t\t\t\t\thalfwidth = width / 2\n\t\t\t\t\tif column > 0:\n\t\t\t\t\t\tmid = start + atoi(sline[column - 1]) - 1\n\t\t\t\t\t\toutput_start = max(mid - halfwidth, start)\n\t\t\t\t\t\toutput_end = min(mid + halfwidth, end)\n\t\t\t\t\telse:\n\t\t\t\t\t\tmid = (start + end) / 2\n\t\t\t\t\t\toutput_start = mid - halfwidth\n\t\t\t\t\t\toutput_end = mid + halfwidth\n\t\t\t\t\toutput.write(sline[0] + '\\t' + str(output_start) + '\\t' + str(output_end) + '\\n')\n\tfile.close()\n\toutput.close()\n\n\ndef main(argv):\n\tparser = OptionParser()\n\tparser.add_option(\"-a\", \"--infile\", action=\"store\", type=\"string\", dest=\"inputfile\", metavar=\"\", help=\"input file with complete data\")\n\tparser.add_option(\"-w\", \"--maxwidth\", action=\"store\", type=\"int\", dest=\"width\", help=\"maximum width of output sites\", metavar=\"\")\n\tparser.add_option(\"-c\", \"--column\", action=\"store\", type=\"int\", dest=\"column\", help=\"column number of summits, start from 1, negative if using the middle position\", metavar=\"\")\n\tparser.add_option(\"-o\", \"--output_file\", action=\"store\", type=\"string\", dest=\"out_file\", metavar=\"\", help=\"output file name\")\n\n\t(opt, args) = parser.parse_args(argv)\n\tif len(argv) < 8:\n \tparser.print_help()\n \tsys.exit(1)\n\t\n\tsummit_region_to_bed(opt.inputfile, opt.out_file, opt.column, opt.width)\n\n\nif __name__ == \"__main__\":\n\tmain(sys.argv)","sub_path":"macs-summit-2-bed.py","file_name":"macs-summit-2-bed.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93795181","text":"from django.test import TestCase\n\nfrom tests.models import Author, Record\n\n\nclass LookupTests(TestCase):\n\n def setUp(self):\n self.a1 = Author.objects.create()\n self.r1 = Record.objects.create(author=self.a1)\n self.r2 = Record.objects.create(author=self.a1)\n self.r3 = Record.objects.create(author=self.a1)\n\n def test_exists(self):\n self.assertTrue(Author.objects.exists())\n self.assertTrue(Record.objects.exists())\n Author.objects.all().delete()\n self.assertFalse(Author.objects.exists())\n\n def test_count(self):\n self.assertEqual(1, Author.objects.count())\n self.assertEqual(3, Record.objects.count())\n Record.objects.all().delete()\n self.assertEqual(0, Record.objects.count())\n\n def test_in(self):\n self.assertQuerysetEqual(Author.objects.filter(id__in=[]), [])\n self.assertEqual(1, Author.objects.filter(id__in=[self.a1.id]).count())\n","sub_path":"tests/test_lookup.py","file_name":"test_lookup.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"572540326","text":"from .base import FunctionalTest\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nclass NewVisitorTest(FunctionalTest):\r\n\r\n def test_can_add_schooll_class_children_and_retrieve_them_later(self):\r\n # Анна як староста класу слідкує за\r\n # актуальністю даних про учнів свого класу\r\n # в класному журналі. Тож на початку навчального року\r\n # вона заходить і оновлює данні(видаляє або додає учнів)\r\n self.browser.get(self.server_url)\r\n\r\n # Дивиться на назву сторінки і заголовок\r\n self.assertIn('Class journal', self.browser.title)\r\n header_text = self.browser.find_element_by_tag_name('h1').text\r\n self.assertIn('Fill your school class', header_text)\r\n\r\n # Перевіряє форму перед заповненням\r\n form = self.browser.find_element_by_id('addStudentForm')\r\n # if no element NoSuchElementException will be raised\r\n form.find_element_by_tag_name('fieldset')\r\n legend = form.find_element_by_tag_name('legend').text\r\n self.assertIn('Add a new student', legend)\r\n labels = form.find_elements_by_tag_name('label')\r\n labels = [label.text for label in labels]\r\n self.assertIn('Surname', labels)\r\n self.assertIn('Name', labels)\r\n self.assertIn('Patronymic', labels)\r\n\r\n # і додає в клас нового учня вказуючи його ПІБ та натискаючи ДОДАТИ\r\n self.fill_and_send_students_full_name('Pupkin', 'Vasya', 'Ivanovych')\r\n\r\n # отримує новий урл, де вже присутні введені данні учня\r\n annas_students_url = self.browser.current_url\r\n self.assertRegex(annas_students_url, '/journals/.+')\r\n self.check_for_row_in_full_name_table('1 Pupkin V.I.')\r\n\r\n # знову додає в клас нового учня вказуючи його ПІБ та натискаючи ДОДАТИ\r\n self.fill_and_send_students_full_name('Ivanov', 'Ivan', 'Ivanovych')\r\n\r\n # Перевіряє чи відображаються дані учнів\r\n self.check_for_row_in_full_name_table('1 Pupkin V.I.')\r\n self.check_for_row_in_full_name_table('2 Ivanov I.I.')\r\n\r\n # Інша староста - Марина заходить на сайт\r\n ## Використовуємо нову сесію браузера,\r\n ## перевіримо чи інформація введена Анною не зявиться в куках\r\n self.browser.quit()\r\n self.browser = webdriver.Firefox()\r\n\r\n # На домашній сторінці Марини відсутня інформація, що вносила Анна\r\n self.browser.get(self.server_url)\r\n page_text = self.browser.find_element_by_tag_name('body').text\r\n self.assertNotIn('Pupkin V.I.', page_text)\r\n self.assertNotIn('Ivanov I.I.', page_text)\r\n\r\n # Марина вносить данні учнів свого класу\r\n self.fill_and_send_students_full_name('Smolynsky', 'Ruslan', 'Volodymyrovych')\r\n\r\n # Марина отримує власний унікальний урл\r\n marinas_students_url = self.browser.current_url\r\n self.assertRegex(marinas_students_url, '/journals/.+')\r\n self.assertNotEqual(annas_students_url, marinas_students_url)\r\n\r\n # Перевіряє чи відображаються тільки данні введені нею\r\n page_text = self.browser.find_element_by_tag_name('body').text\r\n self.assertNotIn('Pupkin V.I.', page_text)\r\n self.assertIn('Smolynsky R.V.', page_text)\r\n","sub_path":"functional_tests/test_simple_school_class_creation.py","file_name":"test_simple_school_class_creation.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420029591","text":"import io\nimport itertools\nimport logging\nimport logging.handlers # noqa\nimport operator\nimport os\nimport warnings\n\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nfrom tensorflow.keras.callbacks import Callback\nfrom tensorflow.python.keras.utils import tf_utils\n\n\nclass ModelCheckpointLogged(tf.keras.callbacks.ModelCheckpoint):\n \"\"\"\n This class add a log file with the saved model. It is helpful to see the metrics about the model when it was saved.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n See more information in tensorflow.keras.callbacks.ModelCheckPoint\n\n :param args:\n :param kwargs:\n \"\"\"\n super().__init__(*args, **kwargs)\n log_level = logging.INFO\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n file_handler = logging.handlers.RotatingFileHandler(f\"{os.path.splitext(self.filepath)[0]}.log\")\n file_handler.setLevel(log_level)\n file_handler.setFormatter(formatter)\n\n self._logger = logging.getLogger(f\"ModelCheckpointLogged_{self.monitor}\")\n self._logger.addHandler(file_handler)\n self._logger.setLevel(log_level)\n\n def on_epoch_end(self, batch, logs=None):\n if isinstance(self.save_freq, int) or self.epochs_since_last_save + 1 >= self.period:\n logs = logs or {}\n logs = tf_utils.to_numpy_or_python_type(logs)\n current = logs.get(self.monitor)\n if self.monitor_op(current, self.best):\n log_message = f\"last_best: {self.best}\"\n for key in logs:\n log_message = \", \".join([log_message, f\"{key}: {logs[key]}\"])\n self._logger.info(log_message)\n super().on_epoch_end(batch, logs)\n\n\nclass ConfusionMatrixTB(Callback):\n \"\"\"\n Callback that generate a confusion matrix and plot this image into the tensorboard.\n \"\"\"\n def __init__(self, data_val, class_names, logdir, period=1, monitor=None, mode=None):\n \"\"\"\n\n :param data_val: [tuple[numpy.ndarray, [numpy.ndarray]]] A tuple with tha index 0 as the input data and index 1\n as output data.\n :param class_names:[list[str]] A list with all labels.\n :param logdir: [str] Path where the tensorboard log file will be saved.\n :param period: [int] The period tha this callback will be executed. If the monitor arg was set, this parameter\n will be ignored.\n :param monitor: [str] Set some metric in the training to execute this callback whenever this metric improves.\n :param mode: [str] \"max\" or \"min\" Set the direction of the monitor.\n \"\"\"\n super().__init__()\n self._logdir = logdir\n self._class_names = class_names\n self._data_val = data_val\n self._file_writer_cm = tf.summary.create_file_writer(self._logdir + '/cm')\n self._period = period\n self._monitor = monitor\n\n if self._monitor is not None and mode is None:\n raise ValueError(\"Please set 'mode' with parameters 'max' or 'min'\")\n if mode not in [\"max\", \"min\"]:\n raise ValueError(\"The argument 'mode' must be 'max' or 'min'\")\n self._mode = mode\n\n self._operator = operator.gt if mode == \"max\" else operator.lt\n self._best = np.inf if self._mode is not None and self._mode == \"min\" else -np.inf\n\n @staticmethod\n def _plot_confusion_matrix(cm, class_names):\n \"\"\"\n Returns a matplotlib figure containing the plotted confusion matrix.\n\n Args:\n cm (array, shape = [n, n]): a confusion matrix of integer classes\n class_names (array, shape = [n]): String names of the integer classes\n \"\"\"\n figure = plt.figure(figsize=(8, 8))\n plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title(\"Confusion matrix\")\n plt.colorbar()\n tick_marks = np.arange(len(class_names))\n plt.xticks(tick_marks, class_names, rotation=45)\n plt.yticks(tick_marks, class_names)\n\n # Compute the labels from the normalized confusion matrix.\n labels = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2)\n\n # Use white text if squares are dark; otherwise black.\n threshold = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n color = \"white\" if cm[i, j] > threshold else \"black\"\n plt.text(j, i, labels[i, j], horizontalalignment=\"center\", color=color)\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n return figure\n\n @staticmethod\n def _plot_to_image(figure, path=None):\n \"\"\"\n Converts the matplotlib plot specified by 'figure' to a PNG image and\n returns it. The supplied figure is closed and inaccessible after this call.\n \"\"\"\n # Save the plot to a PNG in memory.\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n # Closing the figure prevents it from being displayed directly inside\n # the notebook.\n plt.close(figure)\n buf.seek(0)\n # Convert PNG buffer to TF image\n image = tf.image.decode_png(buf.getvalue(), channels=4)\n # Add the batch dimension\n image = tf.expand_dims(image, 0)\n return image\n\n def log_confusion_matrix(self, epoch, logs):\n # Use the model to predict the values from the test_images.\n\n true_labels = []\n pred_labels = []\n\n pred_raw = self.model.predict(self._data_val[0])\n if len(self._class_names) > 2:\n true_labels += list(self._data_val[1])\n pred_labels += list(pred_raw.argmax(axis=1))\n else:\n true_labels += list(self._data_val[1])\n pred_labels += list(np.round(pred_raw.flatten()))\n # Calculate the confusion matrix using sklearn.metrics\n cm = confusion_matrix(true_labels, pred_labels)\n\n figure = self._plot_confusion_matrix(cm, class_names=self._class_names)\n cm_image = self._plot_to_image(figure)\n\n with self._file_writer_cm.as_default():\n tf.summary.image(f\"Confusion Matrix ({self._monitor})\", cm_image, step=epoch)\n\n def on_epoch_end(self, epoch, logs=None):\n if self._monitor is not None:\n logs = tf_utils.to_numpy_or_python_type(logs)\n if self._monitor not in logs:\n warnings.warn(f\"'{self._monitor}' does not exist, ignoring confusion matrix for this epoch.\")\n return\n value = logs[self._monitor]\n if self._operator(value, self._best):\n self._best = value\n self.log_confusion_matrix(epoch, logs)\n elif epoch % self._period == 0:\n self.log_confusion_matrix(epoch, logs)\n","sub_path":"training/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":6916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"333952415","text":"import os\nfrom glob import glob\nimport torch\nfrom transformers import (\n BertForSequenceClassification, BertTokenizer,\n Trainer, TrainingArguments\n)\nfrom datasets import Dataset, Value, ClassLabel, Features\nimport pandas as pd\nfrom pysentimiento.preprocessing import preprocess_tweet\nimport fire\nfrom sklearn.metrics import precision_recall_fscore_support, accuracy_score\n\ndef compute_metrics(pred):\n \"\"\"\n Compute metrics for Trainer\n \"\"\"\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='macro')\n acc = accuracy_score(labels, preds)\n return {\n 'accuracy': acc,\n 'f1': f1,\n 'precision': precision,\n 'recall': recall\n }\n\ndef get_lang(file):\n return os.path.splitext(os.path.basename(file))[0]\n\n\"\"\"\nLo pongo así por huggingface\n\"\"\"\nid2label = {0: 'N', 1: 'NEU', 2: 'P'}\nlabel2id = {v:k for k,v in id2label.items()}\n\ndef load_df(file):\n #dialect = get_lang(file)\n\n df = pd.read_table(file, names=[\"id\", \"text\", \"polarity\"], index_col=0)\n #df[\"dialect\"] = dialect\n\n for label, idx in label2id.items():\n df.loc[df[\"polarity\"] == label, \"label\"] = idx\n return df\n\n\n\n\ndef load_datasets():\n \"\"\"\n Return train, dev, test datasets\n \"\"\"\n train_files = glob(\"data/tass2020/train/*.tsv\")\n dev_files = glob(\"data/tass2020/dev/*.tsv\")\n test_files = glob(\"data/tass2020/test1.1/*.tsv\")\n\n train_dfs = {get_lang(file):load_df(file) for file in train_files}\n dev_dfs = {get_lang(file):load_df(file) for file in dev_files}\n test_dfs = {get_lang(file):load_df(file) for file in test_files}\n\n train_df = pd.concat(train_dfs.values())\n dev_df = pd.concat(dev_dfs.values())\n test_df = pd.concat(test_dfs.values())\n\n print(len(train_df), len(dev_df), len(test_df))\n\n\n train_df[\"text\"] = train_df[\"text\"].apply(preprocess_tweet)\n dev_df[\"text\"] = dev_df[\"text\"].apply(preprocess_tweet)\n test_df[\"text\"] = test_df[\"text\"].apply(preprocess_tweet)\n\n features = Features({\n 'text': Value('string'),\n 'label': ClassLabel(num_classes=3, names=[\"neg\", \"neu\", \"pos\"])\n })\n\n train_dataset = Dataset.from_pandas(train_df[[\"text\", \"label\"]], features=features)\n dev_dataset = Dataset.from_pandas(dev_df[[\"text\", \"label\"]], features=features)\n test_dataset = Dataset.from_pandas(test_df[[\"text\", \"label\"]], features=features)\n\n return train_dataset, dev_dataset, test_dataset\n\ndef load_model(base_model, device):\n \"\"\"\n Loads model and tokenizer\n \"\"\"\n print(f\"Loading model {base_model}\")\n model = BertForSequenceClassification.from_pretrained(base_model, return_dict=True, num_labels=3)\n\n tokenizer = BertTokenizer.from_pretrained(base_model)\n tokenizer.model_max_length = 128\n\n model.config.hidden_dropout_prob = 0.20\n model.config.id2label = id2label\n model.config.label2id = label2id\n\n model = model.to(device)\n model.train()\n\n return model, tokenizer\n\n\ndef run_sentiment_experiments(base_model, times=5, epochs=5):\n \"\"\"\n \"\"\"\n print(\"Loading dataset\")\n train_dataset, dev_dataset, test_dataset = load_datasets()\n\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n\n model, tokenizer = load_model(base_model, device)\n\n def tokenize(batch):\n return tokenizer(batch['text'], padding='max_length', truncation=True)\n\n batch_size = 64\n eval_batch_size = 16\n\n train_dataset = train_dataset.map(tokenize, batched=True, batch_size=batch_size)\n dev_dataset = dev_dataset.map(tokenize, batched=True, batch_size=eval_batch_size)\n test_dataset = test_dataset.map(tokenize, batched=True, batch_size=eval_batch_size)\n\n\n def format_dataset(dataset):\n dataset = dataset.map(lambda examples: {'labels': examples['label']})\n dataset.set_format(type='torch', columns=['input_ids', 'token_type_ids', 'attention_mask', 'labels'])\n return dataset\n\n train_dataset = format_dataset(train_dataset)\n dev_dataset = format_dataset(dev_dataset)\n test_dataset = format_dataset(test_dataset)\n\n\n epochs = 5\n\n total_steps = (epochs * len(train_dataset)) // batch_size\n warmup_steps = total_steps // 10\n training_args = TrainingArguments(\n output_dir='./results',\n num_train_epochs=epochs,\n per_device_train_batch_size=batch_size,\n per_device_eval_batch_size=eval_batch_size,\n warmup_steps=warmup_steps,\n evaluation_strategy=\"epoch\",\n do_eval=False,\n weight_decay=0.01,\n logging_dir='./logs',\n )\n\n results = []\n\n for run in range(times):\n print(\"=\"*80)\n print(f\"Run {run+1}\")\n model, _ = load_model(base_model, device)\n\n trainer = Trainer(\n model=model,\n args=training_args,\n compute_metrics=compute_metrics,\n train_dataset=train_dataset,\n eval_dataset=dev_dataset,\n )\n\n trainer.train()\n\n results.append({\n **trainer.evaluate(),\n **{\"run\": run+1}\n })\n\n f1_scores = torch.Tensor([r[\"eval_f1\"] for r in results])\n print(f\"Macro F1: {f1_scores.mean():.3f} +- {f1_scores.std():.3f}\")\n\n\nif __name__ == \"__main__\":\n fire.Fire(run_sentiment_experiments)","sub_path":"bin/run_sentiment_experiments.py","file_name":"run_sentiment_experiments.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637094119","text":"# training.py\n\nimport os\nimport torch\nfrom semantic_hashing import SemanticHashing\nfrom conv_decoder import ConvDecoder\nfrom conv_encoder import ConvEncoder\n\nfrom constants import WAV_CHUNK_SIZE, \\\n LOCAL_CHUNK_FILEPATHS, MODEL_SAVE_DIR, \\\n MODEL_SAVE_PATH, TRAINING_BATCH_SIZE\n\nfrom audio_ops import chunks_dir_to_numpy\n\nceloss = torch.nn.CrossEntropyLoss()\n\n\ndef loss_criterion(output, target):\n target_index_vector = torch.argmax(target, dim=1)\n loss_value = celoss(\n input=output,\n target=target_index_vector)\n return loss_value\n\n\ndef train_pytorch(batch_size, n_epochs):\n\n if not os.path.exists(MODEL_SAVE_DIR):\n os.mkdir(MODEL_SAVE_DIR)\n\n x_train = torch.tensor(\n chunks_dir_to_numpy(LOCAL_CHUNK_FILEPATHS))\n\n de = ConvEncoder()\n dd = ConvDecoder()\n model = SemanticHashing(\n encoder=de,\n decoder=dd\n )\n\n criterion = loss_criterion\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)\n\n N = x_train.size()[0]\n print(\"starting training loop ...\")\n for epoch in range(n_epochs):\n permutation = torch.randperm(N)\n epoch_loss = 0.\n n_batches = N / batch_size\n for i in range(0, N, batch_size):\n optimizer.zero_grad()\n if i + batch_size >= N:\n k = i + batch_size - N\n indices = torch.cat((permutation[i:], permutation[:k]), 0)\n else:\n indices = permutation[i:i+batch_size]\n batch_x = x_train[indices]\n output = model.forward(batch_x)\n encoded_entropy = model.encoded_entropy(batch_x)\n loss = criterion(output, batch_x)\n epoch_loss += loss.item()\n loss.backward()\n optimizer.step()\n noise_sigma = model.noise_sigma\n print(\n f\"batch loss: {loss.item()} \"\n f\"batch encoded entropy: {encoded_entropy} \"\n f\"noise sigma: {noise_sigma}\\n\"\n f\"----------------------------\")\n if epoch % 1 == 0:\n loss_criterion(output, target=batch_x)\n print(f\"\"\"\n epoch: {epoch} epoch loss: {epoch_loss / n_batches}\n noise sigma: {noise_sigma}\n encoded entropy: {encoded_entropy}\n \"\"\")\n print(f\"saving model to {MODEL_SAVE_PATH}\")\n print(\"-\" * 20)\n torch.save(model, MODEL_SAVE_PATH)\n\n\nif __name__ == \"__main__\":\n train_pytorch(batch_size=TRAINING_BATCH_SIZE, n_epochs=100)\n\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"100474804","text":"#!/usr/bin/env python\nimport re\nimport time\n\nimport aiohttp\nfrom aiokafka import (\n AIOKafkaConsumer,\n TopicPartition,\n ConsumerRecord\n)\nimport asyncio\nimport logging\nimport pandas as pd\n\nfrom typing import (\n Dict,\n Optional,\n List\n)\n\nfrom sqlalchemy import text\nfrom sqlalchemy.exc import (\n ProgrammingError,\n DatabaseError\n)\nfrom sqlalchemy.sql.elements import TextClause\nimport conf\nimport wings\nfrom wings.data_source.local_cluster_order_book_data_source import LocalClusterOrderBookDataSource\nfrom wings.model.sql_connection_manager import SQLConnectionManager\nfrom wings.order_book_message import (\n OrderBookMessage,\n DDEXOrderBookMessage\n)\nfrom wings.order_book_tracker_entry import (\n RadarRelayOrderBookTrackerEntry\n)\nfrom wings.orderbook.radar_relay_order_book import RadarRelayOrderBook\nfrom wings.tracker.radar_relay_active_order_tracker import RadarRelayActiveOrderTracker\n\nTRADING_PAIR_FILTER = re.compile(r\"(TUSD|ETH|DAI)$\")\n\n\nclass RadarRelayLocalClusterOrderBookDataSource(LocalClusterOrderBookDataSource):\n DIFF_TOPIC_NAME: str = \"radarrelay-order.serialized\"\n SNAPSHOT_TOPIC_NAME: str = \"radarrelay-market-depth.snapshot\"\n\n _hlcobds_logger: Optional[logging.Logger] = None\n\n @classmethod\n def logger(cls) -> logging.Logger:\n if cls._hlcobds_logger is None:\n cls._hlcobds_logger = logging.getLogger(__name__)\n return cls._hlcobds_logger\n\n def __init__(self, sql: SQLConnectionManager):\n super().__init__(sql)\n\n @classmethod\n async def get_active_exchange_markets(cls) -> pd.DataFrame:\n \"\"\"\n Returns all currently active WETH, DAI trading pairs from RadarRelay, sorted by volume in descending order.\n \"\"\"\n async with aiohttp.ClientSession() as client:\n async with client.get(\"https://api.radarrelay.com/v2/markets?include=ticker,stats\") as response:\n response: aiohttp.ClientResponse = response\n if response.status != 200:\n raise IOError(f\"Error fetching active Radar Relay markets. HTTP status is {response.status}.\")\n data = await response.json()\n all_markets: pd.DataFrame = pd.DataFrame.from_records(data=data, index=\"id\")\n fetch_markets: pd.DataFrame = all_markets[\n lambda df: [FETCH_MARKET_SYMBOL_PATTERN.search(i) is not None for i in df.index]\n ]\n\n weth_dai_price: float = float(fetch_markets.loc[\"WETH-DAI\"][\"ticker\"][\"price\"])\n dai_volume: List[float] = []\n for row in fetch_markets.itertuples():\n product_name: str = row.Index\n base_volume: float = float(row.stats[\"volume24Hour\"])\n if product_name.endswith(\"WETH\"):\n dai_volume.append(weth_dai_price * base_volume)\n else:\n dai_volume.append(base_volume)\n fetch_markets.loc[:, \"DAIVolume\"] = dai_volume\n\n return fetch_markets.sort_values(\"DAIVolume\", ascending=False)\n\n def get_snapshot_message_query(self, symbol: str) -> str:\n return f\"SELECT `timestamp` as `timestamp`, `json` \" \\\n f\"FROM `radarrelay_{symbol}_Snapshot` \" \\\n f\"ORDER BY `timestamp` DESC LIMIT 1\"\n\n def get_diff_message_query(self, symbol: str) -> str:\n return f\"SELECT `timestamp` as `ts`, `json` \" \\\n f\"FROM `radarrelay_{symbol}` \" \\\n f\"WHERE `timestamp` > :timestamp \" \\\n f\"ORDER BY `timestamp`\"\n\n @property\n def order_book_class(self) -> RadarRelayOrderBook:\n return RadarRelayOrderBook\n\n async def get_tracking_pairs(self) -> Dict[str, RadarRelayOrderBookTrackerEntry]:\n # Get the currently active markets\n sql: SQLConnectionManager = self._sql\n active_markets: pd.DataFrame = await self.get_active_exchange_markets()\n\n # Get the latest order book snapshots from database\n now: float = time.time()\n yesterday: float = now - 86400.0\n retval: Dict[str, RadarRelayOrderBookTrackerEntry] = {}\n ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()\n\n with sql.engine.connect() as conn:\n for symbol in active_markets.index:\n symbol: str = symbol\n stmt: TextClause = text(self.get_snapshot_message_query(symbol))\n try:\n row = await ev_loop.run_in_executor(wings.get_executor(), lambda: conn.execute(stmt).fetchone())\n except DatabaseError:\n self.logger().warning(\"Cannot find last snapshot for %s, skipping.\", symbol, exc_info=True)\n continue\n if row is None:\n continue\n\n snapshot_timestamp: float = row[0]\n if snapshot_timestamp > yesterday:\n snapshot_timestamp: float = time.time()\n snapshot_msg: DDEXOrderBookMessage = self.order_book_class.snapshot_message_from_db(\n row,\n {\"marketId\": symbol}\n )\n\n order_book: RadarRelayOrderBook = RadarRelayOrderBook()\n radar_relay_active_order_tracker: RadarRelayActiveOrderTracker = RadarRelayActiveOrderTracker()\n bids, asks = radar_relay_active_order_tracker.convert_snapshot_message_to_order_book_row(\n snapshot_msg)\n order_book.apply_snapshot(bids, asks, snapshot_msg.update_id)\n\n retval[symbol] = RadarRelayOrderBookTrackerEntry(\n symbol,\n snapshot_timestamp,\n order_book,\n radar_relay_active_order_tracker\n )\n\n stmt: TextClause = text(self.get_diff_message_query(symbol))\n try:\n rows = await ev_loop.run_in_executor(\n wings.get_executor(),\n lambda: conn.execute(stmt, timestamp=(snapshot_timestamp-60)*1e3).fetchall()\n )\n for row in rows:\n diff_msg: OrderBookMessage = self.order_book_class.diff_message_from_db(row)\n if diff_msg.update_id > order_book.snapshot_uid:\n bids, asks = retval[symbol].active_order_tracker.\\\n convert_diff_message_to_order_book_row(diff_msg)\n order_book.apply_diffs(bids, asks, diff_msg.update_id)\n except DatabaseError:\n continue\n except ProgrammingError:\n continue\n finally:\n self.logger().debug(\"Fetched order book snapshot for %s.\", symbol)\n return retval\n\n async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):\n \"\"\"\n Listens to real-time order book diff messages from Radar Relay.\n \"\"\"\n while True:\n try:\n consumer: AIOKafkaConsumer = AIOKafkaConsumer(self.DIFF_TOPIC_NAME,\n loop=ev_loop,\n bootstrap_servers=conf.kafka_2[\"bootstrap_servers\"])\n await consumer.start()\n partition: TopicPartition = list(consumer.assignment())[0]\n await consumer.seek_to_end(partition)\n\n while True:\n response: Dict[TopicPartition, List[ConsumerRecord]] = await consumer.getmany(partition,\n timeout_ms=1000)\n if partition in response:\n for record in response[partition]:\n output.put_nowait(self.order_book_class.diff_message_from_kafka(record))\n except asyncio.CancelledError:\n raise\n except Exception:\n self.logger().error(\"Unknown error. Retrying after 5 seconds.\", exc_info=True)\n await asyncio.sleep(5.0)\n\n async def listen_for_order_book_snapshots(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):\n \"\"\"\n Listens to real-time order book snapshot messages from Radar Relay.\n \"\"\"\n while True:\n try:\n consumer: AIOKafkaConsumer = AIOKafkaConsumer(self.SNAPSHOT_TOPIC_NAME,\n loop=ev_loop,\n bootstrap_servers=conf.kafka_2[\"bootstrap_servers\"])\n await consumer.start()\n partition: TopicPartition = list(consumer.assignment())[0]\n await consumer.seek_to_end(partition)\n\n while True:\n response: Dict[TopicPartition, List[ConsumerRecord]] = await consumer.getmany(partition,\n timeout_ms=1000)\n if partition in response:\n for record in response[partition]:\n output.put_nowait(self.order_book_class.snapshot_message_from_kafka(record))\n except asyncio.CancelledError:\n raise\n except:\n self.logger().error(\"Unknown error. Retrying after 5 seconds.\", exc_info=True)\n await asyncio.sleep(5.0)\n\n","sub_path":"wings/data_source/radar_relay_local_cluster_order_book_data_source.py","file_name":"radar_relay_local_cluster_order_book_data_source.py","file_ext":"py","file_size_in_byte":9727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152893808","text":"from requests import Session\nfrom functools import reduce\nfrom json import dumps\n\nclass SauresHA:\n def __init__(self, email, password):\n self.__session = Session()\n if not self.__auth(email, password):\n raise Exception('Invalid credentials')\n \n def __auth(self, email, password):\n auth_data = self.__session.post('https://lk.saures.ru/api/auth/login', data={\n 'email': email, \n 'password': password\n }).json()\n return auth_data['status'] != 'bad'\n\n def get_flats(self):\n return self.__session.get(f'https://lk.saures.ru/api/company/flats').json()['data']['flats']\n\n def get_meters(self, flat_id):\n sensors = self.__session.get(f'https://lk.saures.ru/api/meter/meters', params={\n 'flat_id': flat_id\n }).json()['data']['sensors']\n return reduce(list.__add__, map(lambda sensor: sensor['meters'], sensors))\n\n def get_controllers(self, flat_id):\n controllers = self.__session.get(f'https://lk.saures.ru/api/meter/meters', params={\n 'flat_id': flat_id\n }).json()['data']['sensors']\n return reduce(list.__add__, map(lambda sensor: controllers, controllers))\n\n\n def get_meter(self, flat_id, serial_number):\n meters = self.get_meters(flat_id)\n return next((Meter(meter) for meter in meters if meter['sn'] == serial_number), Meter(dict()))\n\n\n def get_controller(self, flat_id, sn):\n controllers = self.get_controllers(flat_id)\n return next((Controller(controller) for controller in controllers if controller['sn'] == sn), Controller(dict()))\n\n\nclass Meter:\n def __init__(self, data):\n self.data = data\n self.name = data.get('meter_name')\n self.type_number = data.get('type', {}).get('number')\n self.type = data.get('type', {}).get('name')\n self.state = data.get('state', {}).get('name')\n self.sn = data.get('sn')\n self.value = data.get('value')\n self.id = data.get('meter_id')\n self.input = data.get('input')\n self.values = data.get('vals', [])\n if len(self.values) == 2:\n self.t1=self.values[0]['value']\n self.t2=self.values[1]['value']\n self.t3='-'\n self.t4='-'\n elif len(self.values)==3:\n self.t1=self.values[0]['value']\n self.t2=self.values[1]['value']\n self.t3=self.values[2]['value']\n self.t4='-'\n elif len(self.values)==4:\n self.t1=self.values[0]['value']\n self.t2=self.values[1]['value']\n self.t3=self.values[2]['value']\n self.t4=self.values[3]['value']\n elif len(self.values)==0:\n self.t1=data.get('value')\n self.t2='-'\n self.t3='-'\n self.t4='-'\n \n\nclass Controller:\n def __init__(self, data):\n self.data = data\n self.name = data.get('sn')\n self.sn = data.get('sn')\n self.batery = data.get('bat')\n self.ssid = data.get('ssid')\n self.local_ip = data.get('local_ip')\n self.firmware = data.get('firmware')\n self.readout_dt = data.get('readout_dt')\n self.request_dt = data.get('request_dt')\n self.last_connection = data.get('last_connection')\n self.state = data.get('state', {}).get('name')\n self.rssi = data.get('rssi')\n self.hardware = data.get('hardware')\n self.new_firmware = data.get('new_firmware') \n\n\nif __name__ == \"__main__\":\n s = SauresHA('demo@saures.ru', 'demo')\n meter = s.get_meter(358, '136661693')\n print(meter.data)\n #controller = s.get_controller(4731, '155100360017')\n #print(controller.data)\n","sub_path":"custom_components/sauresha/sauresha.py","file_name":"sauresha.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620317626","text":"# coding:utf-8\n# Copyright (C)\n# Author: I\n# Contact: 12157724@qq.com\n# 2/2/21\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy\nfrom tensorflow import keras\n\nfrom tools.load_data import keras_load_data\n\n\ndef save_fashion_mnist(workdir=\"/WORK/datasset/fashion_mnist\"):\n class_names = ['T-shirt_top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle_boot']\n train_images, test_images, train_labels, test_labels = keras_load_data(keras.datasets.fashion_mnist)\n __save_dateset(class_names, train_images, train_labels, workdir + \"/train\")\n __save_dateset(class_names, test_images, test_labels, workdir + \"/val\")\n\n\ndef __save_dateset(class_names, train_images, train_labels, workdir):\n for index, (image, lable) in enumerate(zip(train_images, train_labels)):\n workdir_folder = workdir + \"/\" + class_names[lable]\n if os.path.exists(workdir_folder) is False:\n os.mkdir(workdir_folder)\n plt.imsave(workdir_folder + \"/\" + str(index) + \".jpg\", image)\n\n\ndef save_mnist(workdir=\"/WORK/datasset/mnist\"):\n train_images, test_images, train_labels, test_labels = keras_load_data(keras.datasets.mnist)\n class_names = ['0', '1', \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n __save_dateset(class_names, train_images, train_labels, workdir + \"/train\")\n __save_dateset(class_names, test_images, test_labels, workdir + \"/val\")\n\n\ndef save_cifar_10(workdir=\"/WORK/datasset/cifar10\"):\n train_images, test_images, train_labels, test_labels = keras_load_data(keras.datasets.cifar10)\n class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck']\n __save_dateset(class_names, train_images, numpy.array(train_labels).flatten().tolist(), workdir + \"/train\")\n __save_dateset(class_names, test_images, numpy.array(test_labels).flatten().tolist(), workdir + \"/val\")\n\n\nif __name__ == '__main__':\n save_cifar_10()\n","sub_path":"ITensorflow/tools/save_dataset.py","file_name":"save_dataset.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"627352255","text":"#!/usr/bin/env python\n\nfrom flask import Flask, render_template\nimport sys\nimport socket\nfrom time import sleep\nfrom _thread import start_new_thread\n\napp = Flask(__name__)\nport = 8000\n\n@app.route('/')\ndef index(): \n return render_template('index.html', servers=monitor.servers, monitor_status=monitor.status)\n\nclass Monitor():\n \n def init(self, ip_list = []):\n self.ip_list = ip_list\n self.servers = {}\n self.status = \"IDLE\"\n start_new_thread(self.data_refresh_thread, (self,))\n\n def data_refresh_thread(self, monitor):\n print(\"[INFO] Started data refresh thread\")\n while True:\n monitor.status = \"Updating data\"\n print(\"[INFO] Updating data...\")\n for ip in monitor.ip_list:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n s.connect((ip,port))\n except TimeoutError:\n print(\" [ERROR] Server '\" + ip + \"' timed out\")\n monitor.servers[ip] = \"Timeout\"\n continue\n except socket.gaierror:\n print(\" [ERROR] Server '\" + ip + \"' is invalid\")\n monitor.servers[ip] = \"Invalid IP address\"\n continue\n except:\n print(\" [ERROR] Server '\" + ip + \"' thrown an unhandled error\")\n monitor.servers[ip] = \"Down\"\n continue\n\n data = s.recv(1024)\n data = str(data.decode('ascii'))\n monitor.servers[ip] = data\n print(\" [INFO] Server '%s' is %s\" % (ip,data))\n s.close()\n monitor.status = \"IDLE (up to date)\"\n print(\"[INFO] Data updated.\")\n sleep(5)\n\n\nmonitor = Monitor()\n\ndef Main():\n if sys.argv[1] == \"--servers\":\n server_str = sys.argv[2]\n server_list = server_str.split(\",\")\n monitor.init(server_list)\n app.run()\n \n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"You must specify the servers to monitor, give a comma separated list of ip addresses:\\n--server ,,...\")\n sys.exit()\n Main()\n","sub_path":"web_monitor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"576623362","text":"\nfrom typing import Union\nimport pathlib\n\nfrom GANsynth_pytorch.spectrograms_helper import (\n SpectrogramsHelper, MelSpectrogramsHelper\n)\n\n\ndef get_spectrograms_helper(**kwargs\n ) -> SpectrogramsHelper:\n \"\"\"Return a SpectrogramsHelper instance using the provided parameters\"\"\"\n spectrogram_parameters = {\n 'fs_hz': kwargs['fs_hz'],\n 'n_fft': kwargs['n_fft'],\n 'hop_length': kwargs['hop_length'],\n 'window_length': kwargs['window_length'],\n }\n if kwargs['use_mel_scale']:\n return MelSpectrogramsHelper(\n **spectrogram_parameters,\n lower_edge_hertz=kwargs['mel_scale_lower_edge_hertz'],\n upper_edge_hertz=kwargs['mel_scale_upper_edge_hertz'],\n mel_break_frequency_hertz=kwargs['mel_scale_break_frequency_hertz'],\n mel_bin_width_threshold_factor=(\n kwargs['mel_scale_expand_resolution_factor'])\n )\n else:\n return SpectrogramsHelper(**spectrogram_parameters)\n\n\ndef expand_path(p: Union[str, pathlib.Path]) -> pathlib.Path:\n return pathlib.Path(p).expanduser().absolute()\n","sub_path":"interactive_spectrogram_inpainting/utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"37113307","text":"#################################################################################\n# #\n# Universal Extruder #\n# Version 1.0 #\n# #\n# This program generates an SVG file #\n# - Given an SVG file containing a closed path of straight lines #\n# - Generates a paper model containing two copies of the closed path #\n# and an extrusion represented by a strip with tabs and score lines #\n# #\n# Copyright: (c) 2020, Joseph Zakar #\n# GNU General Public License v3.0+ (see LICENSE or #\n# https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3)#fulltext) #\n# #\n#################################################################################\n\n# Init variables\nimport sys\nimport os\nimport math\nimport copy\nimport uuid\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom\nfrom svgpathtools import *\nimport math\nimport tkinter\nfrom tkinter import *\nimport tkinter.filedialog\nimport tkinter.font as font\nfrom tkinter import messagebox\n\n\n# user defaults\ninputfile = 'tgtest.svg'\noutputfile = 'tgresults.svg'\ntab_height = 0.4\ndashlength = 0.25\nextrude = 1.0\n\n# non-user defaults\norientTop = 0\norientBottom = 1\norientRight = 2\norientLeft = 3\ntab_angle = 25.0\n\ndef main(argv):\n global orientTop\n global orientBottom\n global orientRight\n global orientLeft\n global tab_height\n global tab_angle\n global inputfile\n global outputfile\n global dashlength\n\n top = tkinter.Tk()\n top.title(\"Universal Extruder\")\n pane = PanedWindow(top, orient=VERTICAL)\n pane.pack(fill=BOTH, expand=1)\n F1 = Frame(pane)\n L1 = tkinter.Label(F1, text=\"Input File Name \")\n L1.pack( side = tkinter.LEFT)\n E1 = tkinter.Entry(F1, bd =5, width=30)\n E1.pack(side = tkinter.LEFT)\n F2 = Frame(pane)\n L2 = tkinter.Label(F2, text=\"Output File Name\")\n L2.pack( side = tkinter.LEFT)\n E2 = tkinter.Entry(F2, bd =5, width=30)\n E2.pack(side = tkinter.LEFT)\n F3 = Frame(pane)\n L3 = tkinter.Label(F3, text=\"Width of Extrusion in inches\")\n L3.pack( side = tkinter.LEFT)\n E3 = tkinter.Entry(F3, bd =5, width=6)\n E3.insert(0,str(extrude))\n E3.pack(side = tkinter.LEFT)\n F4 = Frame(pane)\n L4 = tkinter.Label(F4, text=\"Length of Dashline in inches (zero for solid line)\")\n L4.pack( side = tkinter.LEFT)\n E4 = tkinter.Entry(F4, bd =5, width=6)\n E4.insert(0,str(dashlength))\n E4.pack(side = tkinter.LEFT)\n F4a = Frame(pane)\n L4a = tkinter.Label(F4a, text=\"Height of Tab in inches\")\n L4a.pack( side = tkinter.LEFT)\n E4a = tkinter.Entry(F4a, bd =5, width=6)\n E4a.insert(0,str(tab_height))\n E4a.pack(side = tkinter.LEFT)\n \n # This is the handler for the input file browse button\n def InfileCallBack():\n ftypes = [('svg files','.svg'), ('All files','*')]\n inputfile = tkinter.filedialog.askopenfilename(title = \"Select File\", filetypes = ftypes, defaultextension='.svg')\n E1.delete(0,tkinter.END)\n E1.insert(0, inputfile)\n\n # This is the handler for the output file browse button\n def OutfileCallBack():\n ftypes = [('svg files','.svg'), ('All files','*')]\n outputfile = tkinter.filedialog.asksaveasfilename(title = \"Save File As\", filetypes = ftypes, defaultextension='.svg')\n E2.delete(0,tkinter.END)\n E2.insert(0,outputfile)\n\n # This is the handler for the cancel button\n def CancelCallBack():\n top.destroy()\n\n # This is the handler for the OK button\n def OKCallBack():\n global inputfile\n global outputfile\n global dashlength\n global nohscores\n global tab_height\n global extrude\n inputfile = E1.get()\n outputfile = E2.get()\n dashlength = float(E4.get())\n tab_height = float(E4a.get())\n extrude = float(E3.get())\n top.destroy()\n \n dscores = [] # temporary list of all score lines\n opaths = [] # all the generated paths will be stored in this list to write an SVG file\n oattributes = [] # each path in opaths has a corresponding set of attributes in this list\n # attributes for body, top, and bottom\n battributes = {'style' : 'fill:#32c864;stroke:#000000;stroke-width:0.96;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1'}\n # attributes for scorelines\n sattributes = {'style' : 'fill:none;stroke:#000000;stroke-width:0.96;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1'}\n B1 = tkinter.Button(F1, text=\"Browse\", command=InfileCallBack)\n B1.pack(side = tkinter.LEFT)\n B2 = tkinter.Button(F2, text=\"Browse\", command=OutfileCallBack)\n B2.pack(side = tkinter.LEFT)\n F6 = Frame(pane)\n bfont = font.Font(size=12)\n B3 = tkinter.Button(F6, text=\"Cancel\", command=CancelCallBack)\n B3['font'] = bfont\n B3.pack(side = tkinter.LEFT, ipadx=30)\n B4 = tkinter.Button(F6, text=\"OK\", command=OKCallBack)\n B4['font'] = bfont\n B4.pack(side = tkinter.RIGHT,ipadx=40)\n pane.add(F1)\n pane.add(F2)\n pane.add(F3)\n pane.add(F4)\n pane.add(F4a)\n pane.add(F6)\n top.mainloop()\n # Parse input file into paths, attributes, and svg_attributes\n ipaths, iattributes, isvg_attributes = svg2paths2(inputfile)\n # determine the units and the scale of the input file\n # Check the units to see if we support them\n hwunits = isvg_attributes['height'][-2:]\n if(hwunits != 'in'):\n root = tkinter.Tk()\n root.withdraw()\n messagebox.showerror('UPC Input Error', 'Document Units Must be in Inches', parent=root)\n sys.exit(6)\n inheight = float(isvg_attributes['height'][:-2])\n inwidth = float(isvg_attributes['width'][:-2])\n invb = isvg_attributes['viewBox'].split()\n # Assumes X and Y scales are equal\n inscale = inwidth/float(invb[2])\n dstr = ipaths[0].d()\n inodes = dstr.split()\n pointype = \"XX\"\n npath = []\n for coord in range(len(inodes)):\n if inodes[coord] == 'M': # Next two comma separted numbers are first XY point\n pointype = 'M'\n elif inodes[coord] == 'L': # Next two comma separted numbers are XY point to line from last point\n pointype = 'L'\n elif inodes[coord] == 'H': # Next number is X value of a line to last point\n pointype = 'H'\n elif inodes[coord] == 'V': # Next number is Y value of a line to last point\n pointype = 'V'\n elif inodes[coord] == 'Z': # End of path. Nothing after Z\n pointype = 'Z'\n else:\n if (pointype == 'M') or (pointype == 'L'):\n ipoint = inodes[coord].split(',')\n elif pointype == 'H':\n ipoint = inodes[coord]+','+inodes[coord-1].split()[1]\n elif pointype == 'V':\n ipoint = inodes[coord-1].split()[0]+','+inodes[coord]\n x1 = float(ipoint[0])*inscale\n y1 = float(ipoint[1])*inscale\n npath.append(complex(x1, y1))\n\n dprop = 'M'\n for nodes in range(len(npath)):\n dprop = dprop + ' ' + str(npath[nodes].real) + ',' + str(npath[nodes].imag)\n ## and close the path\n dprop = dprop + ' z'\n dpaths = parse_path(dprop)\n # Here is the original polygon\n opaths.append(dpaths)\n oattributes.append(battributes)\n # make another copy for the back\n opaths.append(dpaths)\n oattributes.append(battributes)\n\n # Create the extruded strip\n strip = [] # Might be larger than the paper\n scores = []\n spaths = [] # while we're here, generate the score lines\n xpos = 0\n ypos = 0\n segs = [complex(xpos, ypos)]\n # create left edge of strip\n for jnode in range(0,len(npath)-1):\n # calculate length of segment between jnode and jnode+1\n if ypos + abs(npath[jnode] - npath[jnode+1]) + tab_height >= 11.5:\n # have to cut it at last segment\n strip.append(copy.deepcopy(segs))\n segs.clear() # start a new segment\n ypos = 0\n segs.append(complex(xpos,ypos))\n scores.append(copy.deepcopy(dscores))\n dscores.clear()\n ypos = ypos + abs(npath[jnode] - npath[jnode+1])\n segs.append(complex(xpos, ypos))\n if jnode < len(npath)-1:\n # Generate score lines\n spaths = makescore(complex(xpos, ypos), complex(extrude, ypos),dashlength)\n dscores.append(spaths)\n strip.append(copy.deepcopy(segs))\n scores.append(copy.deepcopy(dscores))\n # create right edge of strip\n for knode in range(len(strip)):\n rsegs = strip[knode][::-1]\n for jnode in range(0,len(rsegs)):\n strip[knode].append(complex(extrude, rsegs[jnode].imag))\n rsegs.clear()\n # Add tabs to strip\n for knode in range(len(strip)):\n mpath = [strip[knode][0]]\n for ptn in range(len(strip[knode])-1):\n # Generate score lines\n spaths = makescore(strip[knode][ptn], strip[knode][ptn+1],dashlength)\n scores[knode].append(spaths)\n if strip[knode][ptn].imag == strip[knode][ptn+1].imag:\n # this will either be a top or bottom tab\n if (strip[knode][ptn].real-strip[knode][ptn+1].real) > 0:\n tpnt = complex(strip[knode][ptn+1].real+0.1, strip[knode][ptn].imag + 0.1)\n else:\n tpnt = complex(strip[knode][ptn].real+0.1, strip[knode][ptn].imag + 0.1)\n if insidePath(strip[knode], tpnt) == 0: # Point is inside the path\n tabpt1, tabpt2 = makeTab(strip[knode][ptn], strip[knode][ptn+1], orientTop) # order of points does not matter\n else:\n tabpt1, tabpt2 = makeTab(strip[knode][ptn], strip[knode][ptn+1], orientBottom)\n elif strip[knode][ptn].real == strip[knode][ptn+1].real:\n # This will either be a right or left tab\n if (strip[knode][ptn+1].imag-strip[knode][ptn].imag) > 0:\n tpnt = complex(strip[knode][ptn+1].real+0.1, strip[knode][ptn].imag + 0.1)\n else:\n tpnt = complex(strip[knode][ptn+1].real+0.1, strip[knode][ptn+1].imag + 0.1)\n if insidePath(strip[knode], tpnt) == 0: # Point is inside the path\n tabpt1, tabpt2 = makeTab(strip[knode][ptn], strip[knode][ptn+1], orientLeft)\n else:\n tabpt1, tabpt2 = makeTab(strip[knode][ptn], strip[knode][ptn+1], orientRight)\n else:\n tabpt1, tabpt2 = makeTab(strip[knode][ptn], strip[knode][ptn+1], orientLeft)\n if insidePath(strip[knode], tabpt1) == 0: # Point is inside the path\n tabpt1, tabpt2 = makeTab(strip[knode][ptn], strip[knode][ptn+1], orientRight)\n mpath.append(tabpt1)\n mpath.append(tabpt2)\n mpath.append(strip[knode][ptn+1])\n\n dprop = 'M'\n for nodes in range(len(mpath)):\n dprop = dprop + ' ' + str(mpath[nodes].real) + ',' + str(mpath[nodes].imag)\n ## and close the path\n dprop = dprop + ' z'\n for dndx in scores[knode]:\n dprop = dprop +dndx\n dpaths = parse_path(dprop)\n opaths.append(dpaths)\n oattributes.append(battributes)\n osvg_attributes = {}\n for ia in isvg_attributes:\n if ((((ia != 'xmlns:dc') and (ia != 'xmlns:cc')) and (ia != 'xmlns:rdf')) and (ia != 'xmlns:svg')):\n osvg_attributes[ia] = isvg_attributes[ia]\n tmpfile = str(uuid.uuid4())\n totalpaths = Path()\n for tps in opaths:\n totalpaths.append(tps)\n xmin,xmax,ymin,ymax=totalpaths.bbox()\n #wsvg(opaths, attributes=oattributes, svg_attributes=osvg_attributes, filename=tmpfile)\n wsvg(opaths, filename=tmpfile, attributes=oattributes)\n # Post processing stage\n # Due to issues with svgpathtools, some post processing of the file output from the library is necessary until issues have been resolved\n # The following attributes are suitable for input to inkscape and/or the Cricut Design Space\n # Document properties are 11.5 x 11.5 inches. The viewBox sets the scale at 72 dpi. Change the display units in Inkscape to inches.\n docscale = 72\n isvg_attributes = {'xmlns:dc': 'http://purl.org/dc/elements/1.1/', 'xmlns:cc': 'http://creativecommons.org/ns#',\\\n 'xmlns:rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'xmlns:svg': 'http://www.w3.org/2000/svg',\\\n 'xmlns': 'http://www.w3.org/2000/svg', 'id': 'svg8', 'version': '1.1',\\\n 'viewBox': '0 0 828.0 828.0', 'height': '11.5in', 'width': '11.5in'}\n # Assumes order of paths is front, back, extrusion, scorelines\n ids = ['front','back','extrude','scorelines']\n # Read the xml tree from the file\n DOMTree = xml.dom.minidom.parse(tmpfile)\n # Accessing the svg node (which must be the root element)\n svg =DOMTree.documentElement\n # correct the height, width, and viewBox attributes\n svg.setAttribute('height', isvg_attributes['height'])\n svg.setAttribute('width', isvg_attributes['width'])\n svg.setAttribute('viewBox', isvg_attributes['viewBox'])\n # All path nodes under svg\n paths = svg.getElementsByTagName(\"path\")\n wbbox = xmax-xmin\n hbbox = ymax-ymin\n strwidth = isvg_attributes['width']\n if not(strwidth.isdigit()):\n # For now, assume it is a two character unit at the end of the string\n # TODO: Process the units field and modify paths accordingly\n midbbox = (float(strwidth[:-2])-wbbox)/2 -xmin\n else:\n midbbox = (float(strwidth)-wbbox)/2 -xmin\n strheight = isvg_attributes['height']\n if not(strwidth.isdigit()):\n # For now, assume it is a two character unit at the end of the string\n # TODO: Process the units field and modify paths accordingly\n centerbbox = (float(strheight[:-2])-hbbox)/2 -ymin\n else:\n centerbbox = (float(strheight)-hbbox)/2 -ymin\n extrude_cnt = 0\n for p in range(len(paths)):\n # Change paths to close with z rather than repeating first point\n inodes = paths[p].getAttribute('d').split()\n dstr = ''\n firstpoint = ''\n lastpoint = ''\n rplcoord = 0\n process = 1\n for coord in range(len(inodes)):\n if not((inodes[coord] == 'M') or (inodes[coord] == 'L')):\n if firstpoint == '':\n firstpoint = inodes[coord]\n elif coord == len(inodes)-1: # check last point\n if inodes[coord] == firstpoint: # does it repeat first point\n dstr = dstr + 'z' # yes. replace it with a z\n process = 0 # and stop processing\n else:\n ipoint = inodes[coord].split(',')\n dstr = dstr + cstr + str((float(ipoint[0])+midbbox)*docscale) + ',' + str((float(ipoint[1])+centerbbox)*docscale) + ' '\n process = 0\n if(process == 1):\n ipoint = inodes[coord].split(',')\n dstr = dstr + cstr + str((float(ipoint[0])+midbbox)*docscale) + ',' + str((float(ipoint[1])+centerbbox)*docscale) + ' '\n else:\n paths[p].setAttribute('d', dstr) # and replace the path\n else:\n cstr = inodes[coord] + ' '\n # TODO: Update the path ids to something more meaningful\n # paths[p].setAttribute('id',ids[p])\n with open(outputfile,'w') as xml_file:\n DOMTree.writexml(xml_file, indent=\"\\t\", newl=\"\\n\")\n try:\n os.remove(tmpfile)\n except OSError:\n pass \n root = tkinter.Tk()\n root.withdraw()\n messagebox.showinfo(\"UTG\", \"width = \"+str(round(xmax-xmin,3))+\", height = \"+str(round(ymax-ymin,3)), parent=root)\n\ndef insidePath(path, p):\n point = pnPoint((p.real, p.imag))\n pverts = []\n for pnum in path:\n pverts.append((pnum.real, pnum.imag))\n isInside = point.InPolygon(pverts, True)\n if isInside:\n return 0 # inside\n else:\n return 1 # outside\n\nclass pnPoint(object):\n\tdef __init__(self,p):\n\t\tself.p=p\n\tdef __str__(self):\n\t\treturn self.p\n\tdef InPolygon(self,polygon,BoundCheck=False):\n\t\tinside=False\n\t\tif BoundCheck:\n\t\t\tminX=polygon[0][0]\n\t\t\tmaxX=polygon[0][0]\n\t\t\tminY=polygon[0][1]\n\t\t\tmaxY=polygon[0][1]\n\t\t\tfor p in polygon:\n\t\t\t\tminX=min(p[0],minX)\n\t\t\t\tmaxX=max(p[0],maxX)\n\t\t\t\tminY=min(p[1],minY)\n\t\t\t\tmaxY=max(p[1],maxY)\n\t\t\tif self.p[0]maxX or self.p[1]maxY:\n\t\t\t\treturn False\n\t\tj=len(polygon)-1\n\t\tfor i in range(len(polygon)):\n\t\t\tif ((polygon[i][1]>self.p[1])!=(polygon[j][1]>self.p[1]) and (self.p[0]<(polygon[j][0]-polygon[i][0])*(self.p[1]-polygon[i][1])/( polygon[j][1] - polygon[i][1] ) + polygon[i][0])):\n\t\t\t\tinside =not inside\n\t\t\tj=i\n\t\treturn inside\n\ndef makescore(pt1, pt2, dashlength):\n # Draws a dashed line of dashlength between complex points\n # Assuming pt1y > pt2y\n # Dash = dashlength (in inches) space followed by dashlength mark\n # if dashlength is zero, we want a solid line\n if pt1.imag > pt2.imag:\n apt1 = pt1\n apt2 = pt2\n else:\n apt1 = pt2\n apt2 = pt1\n if dashlength == 0:\n ddash = 'M '+str(apt1.real)+','+str(apt1.imag)+' L '+str(apt2.real)+','+str(apt2.imag)\n else:\n if apt1.imag == apt2.imag:\n # We are drawing horizontal dash lines. Assume pt1x < pt2x\n if pt1.real < pt2.real:\n apt1 = pt1\n apt2 = pt2\n else:\n apt1 = pt2\n apt2 = pt1\n xcushion = apt2.real - dashlength\n ddash = ''\n xpt = apt1.real\n ypt = apt1.imag\n done = False\n while not(done):\n if (xpt + dashlength*2) <= xcushion:\n xpt = xpt + dashlength\n ddash = ddash + 'M ' + str(xpt) + ',' + str(ypt) + ' '\n xpt = xpt + dashlength\n ddash = ddash + 'L ' + str(xpt) + ',' + str(ypt) + ' '\n else:\n done = True\n elif apt1.real == apt2.real:\n # We are drawing vertical dash lines.\n ycushion = apt2.imag + dashlength\n ddash = ''\n xpt = apt1.real\n ypt = apt1.imag\n done = False\n while not(done):\n if(ypt - dashlength*2) >= ycushion:\n ypt = ypt - dashlength \n ddash = ddash + 'M ' + str(xpt) + ',' + str(ypt) + ' '\n ypt = ypt - dashlength\n ddash = ddash + 'L ' + str(xpt) + ',' + str(ypt) + ' '\n else:\n done = True\n else:\n # We are drawing an arbitrary dash line\n m = (apt1.imag-apt2.imag)/(apt1.real-apt2.real)\n theta = math.atan(m)\n msign = (m>0) - (m<0)\n ycushion = apt2.imag + dashlength*math.sin(theta)\n xcushion = apt2.real + msign*dashlength*math.cos(theta)\n ddash = ''\n xpt = apt1.real\n ypt = apt1.imag\n done = False\n while not(done):\n nypt = ypt - dashlength*2*math.sin(theta)\n nxpt = xpt - msign*dashlength*2*math.cos(theta)\n if (nypt >= ycushion) and (((m<0) and (nxpt <= xcushion)) or ((m>0) and (nxpt >= xcushion))):\n # move to end of space / beginning of mark\n xpt = xpt - msign*dashlength*math.cos(theta)\n ypt = ypt - msign*dashlength*math.sin(theta)\n ddash = ddash + 'M ' + str(xpt) + ',' + str(ypt) + ' '\n # draw the mark\n xpt = xpt - msign*dashlength*math.cos(theta)\n ypt = ypt - msign*dashlength*math.sin(theta)\n ddash = ddash + 'L' + str(xpt) + ',' + str(ypt) + ' '\n else:\n done = True\n return ddash\n\ndef makeTab(pt1, pt2, orient):\n global orientTop\n global orientBottom\n global orientRight\n global orientLeft\n global tab_height\n global tab_angle\n switched = 0\n rpt1x = rpt1y = rpt2x = rpt2y = 0.0\n tabDone = False\n currTabHt = tab_height\n currTabAngle = tab_angle\n while not tabDone:\n if (orient == orientTop) or (orient == orientBottom):\n if pt1.real > pt2.real:\n ppt1 = pt2\n ppt2 = pt1\n switched = 1\n else:\n ppt1 = pt1\n ppt2 = pt2\n if orient == orientTop:\n TBset = -1\n elif orient == orientBottom:\n TBset = 1\n tp1 = complex(0, TBset*currTabHt) \n tp2 = complex(0, TBset*currTabHt)\n rtp1x = tp1.real*math.cos(math.radians(-TBset*currTabAngle)) - tp1.imag*math.sin(math.radians(-TBset*currTabAngle)) + ppt1.real\n rtp1y = tp1.imag*math.cos(math.radians(-TBset*currTabAngle)) + tp1.real*math.sin(math.radians(-TBset*currTabAngle)) + ppt1.imag\n rtp2x = tp2.real*math.cos(math.radians(TBset*currTabAngle)) - tp2.imag*math.sin(math.radians(TBset*currTabAngle)) + ppt2.real\n rtp2y = tp2.imag*math.cos(math.radians(TBset*currTabAngle)) + tp2.real*math.sin(math.radians(TBset*currTabAngle)) + ppt2.imag\n elif (orient == orientRight) or (orient == orientLeft):\n if pt1.imag < pt2.imag:\n ppt1 = pt2\n ppt2 = pt1\n switched = 1\n else:\n ppt1 = pt1\n ppt2 = pt2\n if orient == orientRight:\n TBset = -1\n else: # orient == orientLeft\n TBset = 1\n tp1 = complex(-TBset*currTabHt, 0)\n tp2 = complex(-TBset*currTabHt, 0)\n rtp1x = tp1.real*math.cos(math.radians(TBset*currTabAngle)) - tp1.imag*math.sin(math.radians(TBset*currTabAngle)) + ppt1.real\n rtp1y = tp1.imag*math.cos(math.radians(TBset*currTabAngle)) + tp1.real*math.sin(math.radians(TBset*currTabAngle)) + ppt1.imag\n rtp2x = tp2.real*math.cos(math.radians(-TBset*currTabAngle)) - tp2.imag*math.sin(math.radians(-TBset*currTabAngle)) + ppt2.real\n rtp2y = tp2.imag*math.cos(math.radians(-TBset*currTabAngle)) + tp2.real*math.sin(math.radians(-TBset*currTabAngle)) + ppt2.imag\n # Check for vertical line. If so, we are already done\n if (ppt1.real != ppt2.real):\n slope = (ppt1.imag - ppt2.imag)/(ppt1.real - ppt2.real)\n theta = math.degrees(math.atan(slope))\n # create a line segment from ppt1 to rtp1\n td1 = 'M '+str(ppt1.real)+' '+str(ppt1.imag)+' '+str(rtp1x)+' '+str(rtp1y)\n rrtp1 = parse_path(td1)\n # create a line segment from ppt2 to rtp2\n td2 = 'M '+str(ppt2.real)+' '+str(ppt2.imag)+' '+str(rtp2x)+' '+str(rtp2y)\n rrtp2 = parse_path(td2)\n if orient == orientRight:\n # rotate the points theta degrees\n if slope < 0:\n rtp1 = rrtp1.rotated(90+theta, ppt1)\n rtp2 = rrtp2.rotated(90+theta, ppt2)\n else:\n rtp1 = rrtp1.rotated(-90+theta, ppt1)\n rtp2 = rrtp2.rotated(-90+theta, ppt2)\n if orient == orientLeft:\n # rotate the points theta degrees\n if slope < 0:\n rtp1 = rrtp1.rotated(90+theta, ppt1)\n rtp2 = rrtp2.rotated(90+theta, ppt2)\n else:\n rtp1 = rrtp1.rotated(-90+theta, ppt1)\n rtp2 = rrtp2.rotated(-90+theta, ppt2)\n rtp1x = rtp1[0][1].real\n rtp1y = rtp1[0][1].imag\n rtp2x = rtp2[0][1].real\n rtp2y = rtp2[0][1].imag\n if detectIntersect(ppt1.real, ppt1.imag, rtp1x, rtp1y, ppt2.real, ppt2.imag, rtp2x, rtp2y):\n currTabAngle = currTabAngle - 1.0\n if currTabAngle < 2.0:\n currTabHt = currTabHt - 0.1\n currTabAngle = tab_angle\n else:\n tabDone = True\n p1 = complex(rtp1x,rtp1y)\n p2 = complex(rtp2x,rtp2y)\n if switched == 0:\n return p1, p2\n else:\n return p2, p1\n\ndef detectIntersect(x1, y1, x2, y2, x3, y3, x4, y4):\n td = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)\n if td == 0:\n # These line segments are parallel\n return False\n t = ((x1-x3)*(y3-y4)-(y1-y3)*(x3-x4))/td\n if (0.0 <= t) and (t <= 1.0):\n return True\n else:\n return False\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])# Ensure that arguments are valid\n","sub_path":"extruder.py","file_name":"extruder.py","file_ext":"py","file_size_in_byte":24753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"291161588","text":"# models.py\n\nfrom optimizers import *\nfrom nerdata import *\nfrom utils import *\n\nimport random\nimport time\n\nfrom collections import Counter\nfrom typing import List\n\nimport numpy as np\n\n\nclass ProbabilisticSequenceScorer(object):\n \"\"\"\n Scoring function for sequence models based on conditional probabilities.\n Scores are provided for three potentials in the model: initial scores (applied to the first tag),\n emissions, and transitions. Note that CRFs typically don't use potentials of the first type.\n\n Attributes:\n tag_indexer: Indexer mapping BIO tags to indices. Useful for dynamic programming\n word_indexer: Indexer mapping words to indices in the emission probabilities matrix\n init_log_probs: [num_tags]-length array containing initial sequence log probabilities\n transition_log_probs: [num_tags, num_tags] matrix containing transition log probabilities (prev, curr)\n emission_log_probs: [num_tags, num_words] matrix containing emission log probabilities (tag, word)\n \"\"\"\n def __init__(self, tag_indexer: Indexer, word_indexer: Indexer, init_log_probs: np.ndarray, transition_log_probs: np.ndarray, emission_log_probs: np.ndarray):\n self.tag_indexer = tag_indexer\n self.word_indexer = word_indexer\n self.init_log_probs = init_log_probs\n self.transition_log_probs = transition_log_probs\n self.emission_log_probs = emission_log_probs\n\n def score_init(self, sentence_tokens: List[Token], tag_idx: int):\n return self.init_log_probs[tag_idx]\n\n def score_transition(self, sentence_tokens: List[Token], prev_tag_idx: int, curr_tag_idx: int):\n return self.transition_log_probs[prev_tag_idx, curr_tag_idx]\n\n def score_emission(self, sentence_tokens: List[Token], tag_idx: int, word_posn: int):\n word = sentence_tokens[word_posn].word\n word_idx = self.word_indexer.index_of(word) if self.word_indexer.contains(word) else self.word_indexer.index_of(\"UNK\")\n return self.emission_log_probs[tag_idx, word_idx]\n\n\nclass HmmNerModel(object):\n \"\"\"\n HMM NER model for predicting tags\n\n Attributes:\n tag_indexer: Indexer mapping BIO tags to indices. Useful for dynamic programming\n word_indexer: Indexer mapping words to indices in the emission probabilities matrix\n init_log_probs: [num_tags]-length array containing initial sequence log probabilities\n transition_log_probs: [num_tags, num_tags] matrix containing transition log probabilities (prev, curr)\n emission_log_probs: [num_tags, num_words] matrix containing emission log probabilities (tag, word)\n \"\"\"\n def __init__(self, tag_indexer: Indexer, word_indexer: Indexer, init_log_probs, transition_log_probs, emission_log_probs):\n self.tag_indexer = tag_indexer\n self.word_indexer = word_indexer\n self.init_log_probs = init_log_probs\n self.transition_log_probs = transition_log_probs\n self.emission_log_probs = emission_log_probs\n\n def decode(self, sentence_tokens: List[Token]) -> LabeledSentence:\n \"\"\"\n See BadNerModel for an example implementation\n :param sentence_tokens: List of the tokens in the sentence to tag\n :return: The LabeledSentence consisting of predictions over the sentence\n \"\"\"\n scorer = ProbabilisticSequenceScorer(self.tag_indexer, self.word_indexer, self.init_log_probs, self.transition_log_probs, self.emission_log_probs)\n tag_len = len(self.tag_indexer)\n delta = np.ones((len(sentence_tokens),tag_len))*-10000000\n tracker = np.ones((len(sentence_tokens),tag_len))*-10000000\n p_max = -10000000\n path = np.zeros(len(sentence_tokens))\n total_len = len(sentence_tokens)\n result = []\n\n for x in range(tag_len):\n delta[0][x] = scorer.score_init(sentence_tokens, x) + scorer.score_emission(sentence_tokens, x, 0)\n tracker[0][x] = 0\n\n for t in range(1,total_len):\n for from_tag_i in range(tag_len):\n for to_tag_i in range(tag_len):\n prev = delta[t-1][from_tag_i]\n trans = scorer.score_transition(sentence_tokens, from_tag_i, to_tag_i)\n emi = scorer.score_emission(sentence_tokens, to_tag_i, t)\n total = prev+trans+emi\n if delta[t][to_tag_i] < total:\n delta[t][to_tag_i] = total\n tracker[t][to_tag_i] = from_tag_i\n \n for i in range(tag_len):\n curr = delta[total_len-1][i]\n if (p_max < curr):\n p_max = curr\n path[total_len-1] = i\n\n for i in range(1, total_len):\n path[int(total_len-i-1)] = tracker[int(total_len-i)][int(path[total_len-i])]\n \n for i in range(len(path)):\n result.append(self.tag_indexer.get_object(path[i]))\n \n return LabeledSentence(sentence_tokens, chunks_from_bio_tag_seq(result))\n\n\ndef train_hmm_model(sentences: List[LabeledSentence], silent: bool=False) -> HmmNerModel:\n \"\"\"\n Uses maximum-likelihood estimation to read an HMM off of a corpus of sentences.\n Any word that only appears once in the corpus is replaced with UNK. A small amount\n of additive smoothing is applied.\n :param sentences: training corpus of LabeledSentence objects\n :return: trained HmmNerModel\n \"\"\"\n # Index words and tags. We do this in advance so we know how big our\n # matrices need to be.\n tag_indexer = Indexer()\n word_indexer = Indexer()\n word_indexer.add_and_get_index(\"UNK\")\n word_counter = Counter()\n for sentence in sentences:\n for token in sentence.tokens:\n word_counter[token.word] += 1.0\n for sentence in sentences:\n for token in sentence.tokens:\n # If the word occurs fewer than two times, don't index it -- we'll treat it as UNK\n get_word_index(word_indexer, word_counter, token.word)\n for tag in sentence.get_bio_tags():\n tag_indexer.add_and_get_index(tag)\n # Count occurrences of initial tags, transitions, and emissions\n # Apply additive smoothing to avoid log(0) / infinities / etc.\n init_counts = np.ones((len(tag_indexer)), dtype=float) * 0.001\n transition_counts = np.ones((len(tag_indexer),len(tag_indexer)), dtype=float) * 0.001\n emission_counts = np.ones((len(tag_indexer),len(word_indexer)), dtype=float) * 0.001\n for sentence in sentences:\n bio_tags = sentence.get_bio_tags()\n for i in range(0, len(sentence)):\n tag_idx = tag_indexer.add_and_get_index(bio_tags[i])\n word_idx = get_word_index(word_indexer, word_counter, sentence.tokens[i].word)\n emission_counts[tag_idx][word_idx] += 1.0\n if i == 0:\n init_counts[tag_idx] += 1.0\n else:\n transition_counts[tag_indexer.add_and_get_index(bio_tags[i-1])][tag_idx] += 1.0\n # Turn counts into probabilities for initial tags, transitions, and emissions. All\n # probabilities are stored as log probabilities\n if not silent:\n print(repr(init_counts))\n init_counts = np.log(init_counts / init_counts.sum())\n # transitions are stored as count[prev state][next state], so we sum over the second axis\n # and normalize by that to get the right conditional probabilities\n transition_counts = np.log(transition_counts / transition_counts.sum(axis=1)[:, np.newaxis])\n # similar to transitions\n emission_counts = np.log(emission_counts / emission_counts.sum(axis=1)[:, np.newaxis])\n if not silent:\n print(\"Tag indexer: %s\" % tag_indexer)\n print(\"Initial state log probabilities: %s\" % init_counts)\n print(\"Transition log probabilities: %s\" % transition_counts)\n print(\"Emission log probs too big to print...\")\n print(\"Emission log probs for India: %s\" % emission_counts[:,word_indexer.add_and_get_index(\"India\")])\n print(\"Emission log probs for Phil: %s\" % emission_counts[:,word_indexer.add_and_get_index(\"Phil\")])\n print(\" note that these distributions don't normalize because it's p(word|tag) that normalizes, not p(tag|word)\")\n return HmmNerModel(tag_indexer, word_indexer, init_counts, transition_counts, emission_counts)\n\n\ndef get_word_index(word_indexer: Indexer, word_counter: Counter, word: str) -> int:\n \"\"\"\n Retrieves a word's index based on its count. If the word occurs only once, treat it as an \"UNK\" token\n At test time, unknown words will be replaced by UNKs.\n :param word_indexer: Indexer mapping words to indices for HMM featurization\n :param word_counter: Counter containing word counts of training set\n :param word: string word\n :return: int of the word index\n \"\"\"\n if word_counter[word] < 1.5:\n return word_indexer.add_and_get_index(\"UNK\")\n else:\n return word_indexer.add_and_get_index(word)\n\n\n##################\n# CRF code follows\n\nclass FeatureBasedSequenceScorer(object):\n \"\"\"\n Feature-based sequence scoring model. Note that this scorer is instantiated *for every example*: it contains\n the feature cache used for that example.\n \"\"\"\n def __init__(self, tag_indexer, feature_weights, feat_cache):\n self.tag_indexer = tag_indexer\n self.feature_weights = feature_weights\n self.feat_cache = feat_cache\n\n def score_init(self, sentence, tag_idx):\n if isI(self.tag_indexer.get_object(tag_idx)):\n return -1000\n else:\n return 0\n\n def score_transition(self, sentence_tokens, prev_tag_idx, curr_tag_idx):\n prev_tag = self.tag_indexer.get_object(prev_tag_idx)\n curr_tag = self.tag_indexer.get_object(curr_tag_idx)\n if (isO(prev_tag) and isI(curr_tag))\\\n or (isB(prev_tag) and isI(curr_tag) and get_tag_label(prev_tag) != get_tag_label(curr_tag)) \\\n or (isI(prev_tag) and isI(curr_tag) and get_tag_label(prev_tag) != get_tag_label(curr_tag)):\n return -1000\n else:\n return 0\n\n def score_emission(self, sentence_tokens, tag_idx, word_posn):\n feats = self.feat_cache[word_posn][tag_idx]\n return self.feature_weights.score(feats)\n\nclass CrfNerModel(object):\n def __init__(self, tag_indexer, feature_indexer, feature_weights):\n self.tag_indexer = tag_indexer\n self.feature_indexer = feature_indexer\n self.feature_weights = feature_weights\n self.n_tags = len(tag_indexer)\n \n def decode(self, sentence_tokens: List[Token]) -> LabeledSentence:\n \"\"\"\n See BadNerModel for an example implementation\n :param sentence_tokens: List of the tokens in the sentence to tag\n :return: The LabeledSentence consisting of predictions over the sentence\n \"\"\"\n feature_cache = [[[] for k in range(0, len(self.tag_indexer))] for j in range(0, len(sentence_tokens))]\n for word_idx in range(0, len(sentence_tokens)):\n for tag_idx in range(0, len(self.tag_indexer)):\n feature_cache[word_idx][tag_idx] = extract_emission_features(\n sentence_tokens, \n word_idx, \n self.tag_indexer.get_object(tag_idx), \n self.feature_indexer, \n add_to_indexer=False\n )\n n_tokens = len(sentence_tokens)\n delta = np.zeros((n_tokens, self.n_tags))\n tracker = np.zeros((n_tokens, self.n_tags), int)\n Scorer = FeatureBasedSequenceScorer(self.tag_indexer, self.feature_weights, feature_cache)\n\n for token in range(n_tokens):\n for tag in range(self.n_tags):\n emission_score = Scorer.score_emission(sentence_tokens, tag, token)\n if token == 0:\n transition_score = Scorer.score_init(sentence_tokens, tag)\n else:\n transition_score_candidates = []\n for tag_prev in range(self.n_tags):\n score = Scorer.score_transition(sentence_tokens, tag_prev, tag)\n transition_score_candidates.append(score+delta[token-1, tag_prev])\n transition_score_candidates = np.array(transition_score_candidates)\n tracker[token][tag] = np.argmax(transition_score_candidates)\n transition_score = np.max(transition_score_candidates)\n delta[token][tag] = emission_score + transition_score\n\n bio_tags = []\n best_idx = np.argmax(delta[-1][:])\n \n for i in range(n_tokens-1, -1, -1):\n bio_tags.append(self.tag_indexer.ints_to_objs[best_idx])\n best_idx = tracker[i][best_idx]\n \n chunks = chunks_from_bio_tag_seq(bio_tags[::-1])\n return LabeledSentence(sentence_tokens, chunks)\n\n def decode_beam(self, sentence_tokens: List[Token]) -> LabeledSentence:\n \"\"\"\n See BadNerModel for an example implementation\n :param sentence_tokens: List of the tokens in the sentence to tag\n :return: The LabeledSentence consisting of predictions over the sentence\n \"\"\"\n feature_cache = [[[] for k in range(0, len(self.tag_indexer))] for j in range(0, len(sentence_tokens))]\n for word_idx in range(0, len(sentence_tokens)):\n for tag_idx in range(0, len(self.tag_indexer)):\n feature_cache[word_idx][tag_idx] = extract_emission_features(\n sentence_tokens, \n word_idx, \n self.tag_indexer.get_object(tag_idx), \n self.feature_indexer, \n add_to_indexer=False\n )\n Scorer = FeatureBasedSequenceScorer(self.tag_indexer, self.feature_weights, feature_cache)\n n_tokens = len(sentence_tokens)\n beam_size = 2\n beam_list = []\n tracker = np.zeros((n_tokens, self.n_tags), int)\n for token in range(n_tokens):\n beam_t = Beam(beam_size)\n for tag in range(self.n_tags):\n emission_score = Scorer.score_emission(sentence_tokens, tag, token)\n prevs = []\n scores = []\n if token == 0:\n transition_score = Scorer.score_init(sentence_tokens, token)\n else:\n for prev, score in beam_list[token-1].get_elts_and_scores():\n prevs.append(prev)\n scores.append(Scorer.score_transition(sentence_tokens, prev, tag)+score)\n idx = scores.index(max(scores))\n y_prev = prevs[idx]\n tracker[token][tag] = y_prev\n transition_score = scores[idx]\n beam_t.add(tag, emission_score + transition_score)\n beam_list.append(beam_t)\n \n bio_tags = []\n best_idx = beam_list[-1].head()\n \n for i in range(n_tokens-1, -1, -1):\n bio_tags.append(self.tag_indexer.ints_to_objs[best_idx])\n best_idx = tracker[i][best_idx]\n \n chunks = chunks_from_bio_tag_seq(bio_tags[::-1])\n return LabeledSentence(sentence_tokens, chunks)\n\ndef train_crf_model(sentences: List[LabeledSentence], silent: bool=False) -> CrfNerModel:\n \"\"\"\n Trains a CRF NER model on the given corpus of sentences.\n :param sentences: The training data\n :param silent: True to suppress output, false to print certain debugging outputs\n :return: The CrfNerModel, which is primarily a wrapper around the tag + feature indexers as well as weights\n \"\"\"\n tag_indexer = Indexer()\n for sentence in sentences:\n for tag in sentence.get_bio_tags():\n tag_indexer.add_and_get_index(tag)\n if not silent:\n print(\"Extracting features\")\n feature_indexer = Indexer()\n # 4-d list indexed by sentence index, word index, tag index, feature index\n feature_cache = [[[[] for k in range(0, len(tag_indexer))] for j in range(0, len(sentences[i]))] for i in range(0, len(sentences))]\n for sentence_idx in range(0, len(sentences)):\n if sentence_idx % 100 == 0 and not silent:\n print(\"Ex %i/%i\" % (sentence_idx, len(sentences)))\n for word_idx in range(0, len(sentences[sentence_idx])):\n for tag_idx in range(0, len(tag_indexer)):\n feature_cache[sentence_idx][word_idx][tag_idx] = extract_emission_features(sentences[sentence_idx].tokens, word_idx, tag_indexer.get_object(tag_idx), feature_indexer, add_to_indexer=True)\n if not silent:\n print(\"Training\")\n weight_vector = UnregularizedAdagradTrainer(np.zeros((len(feature_indexer))), eta=1.0)\n num_epochs = 3\n random.seed(0)\n for epoch in range(0, num_epochs):\n epoch_start = time.time()\n if not silent:\n print(\"Epoch %i\" % epoch)\n sent_indices = [i for i in range(0, len(sentences))]\n random.shuffle(sent_indices)\n total_obj = 0.0\n for counter, i in enumerate(sent_indices):\n if counter % 100 == 0 and not silent:\n print(\"Ex %i/%i\" % (counter, len(sentences)))\n scorer = FeatureBasedSequenceScorer(tag_indexer, weight_vector, feature_cache[i])\n (gold_log_prob, gradient) = compute_gradient(sentences[i], tag_indexer, scorer, feature_indexer)\n total_obj += gold_log_prob\n weight_vector.apply_gradient_update(gradient, 1)\n if not silent:\n print(\"Objective for epoch: %.2f in time %.2f\" % (total_obj, time.time() - epoch_start))\n return CrfNerModel(tag_indexer, feature_indexer, weight_vector)\n\n\ndef extract_emission_features(sentence_tokens: List[Token], word_index: int, tag: str, feature_indexer: Indexer, add_to_indexer: bool):\n \"\"\"\n Extracts emission features for tagging the word at word_index with tag.\n :param sentence_tokens: sentence to extract over\n :param word_index: word index to consider\n :param tag: the tag that we're featurizing for\n :param feature_indexer: Indexer over features\n :param add_to_indexer: boolean variable indicating whether we should be expanding the indexer or not. This should\n be True at train time (since we want to learn weights for all features) and False at test time (to avoid creating\n any features we don't have weights for).\n :return: an ndarray\n \"\"\"\n feats = []\n curr_word = sentence_tokens[word_index].word\n # Lexical and POS features on this word, the previous, and the next (Word-1, Word0, Word1)\n for idx_offset in range(-1, 2):\n if word_index + idx_offset < 0:\n active_word = \"\"\n elif word_index + idx_offset >= len(sentence_tokens):\n active_word = \"\"\n else:\n active_word = sentence_tokens[word_index + idx_offset].word\n if word_index + idx_offset < 0:\n active_pos = \"\"\n elif word_index + idx_offset >= len(sentence_tokens):\n active_pos = \"\"\n else:\n active_pos = sentence_tokens[word_index + idx_offset].pos\n maybe_add_feature(feats, feature_indexer, add_to_indexer, tag + \":Word\" + repr(idx_offset) + \"=\" + active_word)\n maybe_add_feature(feats, feature_indexer, add_to_indexer, tag + \":Pos\" + repr(idx_offset) + \"=\" + active_pos)\n # Character n-grams of the current word\n max_ngram_size = 3\n for ngram_size in range(1, max_ngram_size+1):\n start_ngram = curr_word[0:min(ngram_size, len(curr_word))]\n maybe_add_feature(feats, feature_indexer, add_to_indexer, tag + \":StartNgram=\" + start_ngram)\n end_ngram = curr_word[max(0, len(curr_word) - ngram_size):]\n maybe_add_feature(feats, feature_indexer, add_to_indexer, tag + \":EndNgram=\" + end_ngram)\n # Look at a few word shape features\n maybe_add_feature(feats, feature_indexer, add_to_indexer, tag + \":IsCap=\" + repr(curr_word[0].isupper()))\n # Compute word shape\n new_word = []\n for i in range(0, len(curr_word)):\n if curr_word[i].isupper():\n new_word += \"X\"\n elif curr_word[i].islower():\n new_word += \"x\"\n elif curr_word[i].isdigit():\n new_word += \"0\"\n else:\n new_word += \"?\"\n maybe_add_feature(feats, feature_indexer, add_to_indexer, tag + \":WordShape=\" + repr(new_word))\n return np.asarray(feats, dtype=int)\n\n\ndef compute_gradient(sentence: LabeledSentence, tag_indexer: Indexer, scorer: FeatureBasedSequenceScorer, feature_indexer: Indexer) -> (float, Counter):\n \"\"\"\n Computes the gradient of the given example (sentence). The bulk of this code will be computing marginals via\n forward-backward: you should first compute these marginals, then accumulate the gradient based on the log\n probabilities.\n :param sentence: The LabeledSentence of the current example\n :param tag_indexer: The Indexer of the tags\n :param scorer: FeatureBasedSequenceScorer is a scoring model that wraps the weight vector and which also contains a\n feat_cache field that will be useful when computing the gradient.\n :param feature_indexer: The Indexer of the features\n :return: A tuple of two items. The first is the log probability of the correct sequence, which corresponds to the\n training objective. This value is only needed for printing, so technically you do not *need* to return it, but it\n will probably be useful to compute for debugging purposes.\n The second value is a Counter containing the gradient -- this is a sparse map from indices (features)\n to weights (gradient values).\n \"\"\"\n n_tokens = len(sentence)\n n_tags = len(tag_indexer)\n\n gold_tags = [tag_indexer.index_of(tag) for tag in bio_tags_from_chunks(sentence.chunks, n_tokens)]\n \n forward_log_probs = np.zeros((n_tokens, n_tags))\n backward_log_probs = np.zeros((n_tokens, n_tags))\n\n emission_matrix = np.zeros((n_tokens, n_tags))\n transition_matrix = np.zeros((n_tags, n_tags))\n\n for tag_idx in range(n_tags): \n forward_log_probs[0][tag_idx] = scorer.score_emission(sentence.tokens, tag_idx, 0)\n backward_log_probs[len(sentence.tokens) - 1][tag_idx] = 0\n\n for token in range(1, n_tokens):\n for tag in range(n_tags):\n emission = scorer.score_emission(sentence.tokens, tag, token)\n emission_matrix[token, tag] = emission\n for tag_prev in range(n_tags):\n tran = scorer.score_transition(sentence.tokens, tag_prev, tag)\n cur_term = emission + tran + forward_log_probs[token-1, tag_prev]\n if tag_prev == 0:\n forward_log_probs[token, tag] = cur_term \n else:\n forward_log_probs[token, tag] = np.logaddexp(forward_log_probs[token, tag], cur_term) \n \n for token in reversed(range(n_tokens-1)):\n for tag in range(n_tags):\n for next_tag in range(n_tags):\n emission = emission_matrix[token+1, next_tag]\n transition= transition_matrix[tag, next_tag]\n cur_term = emission + transition + backward_log_probs[token + 1, next_tag]\n if next_tag == 0:\n backward_log_probs[token, tag] = cur_term \n else:\n backward_log_probs[token, tag] = np.logaddexp(backward_log_probs[token, tag], cur_term)\n\n normalizer = np.zeros(n_tokens)\n for word_idx in range(n_tokens):\n normalizer[word_idx] = forward_log_probs[word_idx, 0] + backward_log_probs[word_idx, 0]\n for tag_idx in range(1, n_tags):\n cur_term = forward_log_probs[word_idx, tag_idx] + backward_log_probs[word_idx, tag_idx]\n normalizer[word_idx] = np.logaddexp(normalizer[word_idx], cur_term)\n\n marginal_probs = np.zeros((n_tokens, n_tags))\n for word_idx in range(n_tokens):\n for tag_idx in range(n_tags):\n cur_term = forward_log_probs[word_idx, tag_idx] + backward_log_probs[word_idx, tag_idx]\n marginal_probs[word_idx, tag_idx] = cur_term - normalizer[word_idx]\n\n grad = None\n for t in range(n_tokens):\n if not grad:\n grad = Counter(scorer.feat_cache[t][gold_tags[t]])\n else:\n grad.update(scorer.feat_cache[t][gold_tags[t]])\n\n for y in range(n_tags):\n for feat in scorer.feat_cache[t][y]:\n grad[feat] -= np.exp(marginal_probs[t, y])\n \n gold_emissions = np.sum([\n emission_matrix[t, y]\n for t, y in enumerate(gold_tags)\n ])\n gold_transitions = np.sum([\n transition_matrix[y, y_next]\n for y, y_next in zip(gold_tags[:-1], gold_tags[1:])\n ])\n gold_log_prob = gold_emissions + gold_transitions - normalizer[0]\n return gold_log_prob, grad","sub_path":"a3-distrib/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":24738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"40253162","text":"import os\nimport os.path\nimport unittest\nfrom cmdstanpy.lib import Model\nfrom cmdstanpy.cmds import compile_model\n\ndatafiles_path = os.path.join('test', 'data')\n\ncode = '''data {\n int N;\n int y[N];\n}\nparameters {\n real theta;\n}\nmodel {\n theta ~ beta(1,1);\n for (n in 1:N)\n y[n] ~ bernoulli(theta);\n}\n'''\n\n\nclass ModelTest(unittest.TestCase):\n def test_model_1arg(self):\n stan = os.path.join(datafiles_path, 'bernoulli.stan')\n model = Model(stan)\n self.assertEqual(stan, model.stan_file)\n self.assertEqual(None, model.exe_file)\n\n def test_model_2arg(self):\n stan = os.path.join(datafiles_path, 'bernoulli.stan')\n exe = os.path.join(datafiles_path, 'bernoulli')\n if not os.path.exists(exe):\n compile_model(stan)\n model = Model(stan, exe_file=exe)\n self.assertEqual(stan, model.stan_file)\n self.assertEqual(exe, model.exe_file)\n\n def test_repr(self):\n stan = os.path.join(datafiles_path, 'bernoulli.stan')\n exe = os.path.join(datafiles_path, 'bernoulli')\n model = Model(exe_file=exe, stan_file=stan)\n s = repr(model)\n self.assertTrue(stan in s)\n self.assertTrue(exe in s)\n\n def test_print(self):\n stan = os.path.join(datafiles_path, 'bernoulli.stan')\n exe = os.path.join(datafiles_path, 'bernoulli')\n model = Model(exe_file=exe, stan_file=stan)\n self.assertEqual(code, model.code())\n\n def test_error_1(self):\n with self.assertRaises(Exception):\n model = Model('xdlfkjx', 'sdfndjsds')\n\n def test_error_2(self):\n stan = os.path.join(datafiles_path, 'b')\n with self.assertRaises(Exception):\n model = Model(stan)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"313581111","text":"from flask import Flask, render_template, request, g, redirect\nimport urllib\nimport urllib.parse\nimport os\nimport sys\n\nsys.path.insert(0, '../training')\n\nimport backend\nfrom common import dataset\nfrom training.unit_rankings import get_top_units_by_class_influences, get_top_units_ranked, get_top_units_by_appearances_in_top_units\nfrom db.database import DB\nfrom metrics import similarity_metric, similarity_metric_for_uploaded_image\n\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\n\nSTATIC_DIR = 'static'\nUPLOAD_FOLDER = os.path.join(STATIC_DIR, 'uploads')\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\nPROCESSED_FOLDER = os.path.join(STATIC_DIR, 'processed')\napp.config['PROCESSED_FOLDER'] = PROCESSED_FOLDER\nPROCESSED_FOLDER = os.path.join(STATIC_DIR, 'activation_maps')\napp.config['ACTIVATIONS_FOLDER'] = PROCESSED_FOLDER\n\nCURRENT_USER = 'default'\nCURRENT_MODEL = 'resnet152'\nCURRENT_RESULT = None\nCURRENT_HEATMAPS = []\nFINDINGS_WITH_UNITS = []\n\n@app.route('/')\ndef index(name=None):\n return render_template('login.html', name=name)\n\n\n@app.route('/handle_login', methods=['POST'])\ndef handle_login():\n global CURRENT_USER\n name = request.form['name']\n backend.register_doctor_if_not_exists(name)\n CURRENT_USER = name\n return redirect('/home')\n\n\n@app.route('/home')\ndef home():\n return render_template('home.html', name=CURRENT_USER)\n\n\n@app.route('/checkpoints')\ndef checkpoints():\n db = DB()\n conn = db.get_connection()\n select_stmt = \"SELECT filename FROM net\"\n result = conn.execute(select_stmt)\n checkpoints = [\"/\".join(r[0].split(\"/\")[-2:]) for r in result]\n return render_template('checkpoints.html',\n checkpoints=checkpoints,\n referrer_url=request.referrer)\n\n\n@app.route('/load_checkpoint//')\ndef load_checkpoint(training_session, checkpoint_name):\n checkpoint_path = os.path.join('..', 'training', 'checkpoints', training_session, checkpoint_name)\n backend.init_single_image_analysis(checkpoint_path)\n return redirect('/home')\n\n\n@app.route('/top_units')\ndef top_units(patch_count=6):\n unit_ids = get_top_units_ranked()[:60]\n top_patches = {}\n unit_annotations = {}\n for unit_id in unit_ids:\n top_patches[unit_id] = backend.get_top_patches_for_unit(unit_id, patch_count, include_normal=False)\n survey = backend.get_survey(CURRENT_USER, CURRENT_MODEL, unit_id)\n unit_annotations[unit_id] = backend.survey2unit_annotations_ui(survey, 'german')\n return render_template('unit_ranking_by_score.html',\n unit_ids=unit_ids,\n top_patches=top_patches,\n unit_annotations=unit_annotations)\n\n\n@app.route('/top_units_by_weights')\ndef unit_ranking_by_weights(unit_count=20, patch_count=6):\n sorted_influences = get_top_units_by_class_influences(unit_count)\n top_patches = {}\n unit_annotations = {}\n\n for class_id, count in ((0, 4), (1, unit_count), (2, unit_count)):\n for unit_id, influence, appearances in sorted_influences[class_id][:count]:\n top_patches[unit_id] = backend.get_top_patches_for_unit(unit_id, patch_count, include_normal=class_id == 0)\n survey = backend.get_survey(CURRENT_USER, CURRENT_MODEL, unit_id)\n unit_annotations[unit_id] = backend.survey2unit_annotations_ui(survey, 'german')\n\n for i in sorted_influences[1]:\n print(i[0])\n return render_template('unit_ranking_by_weights_for_checkpoint.html',\n sorted_weights_class_0=sorted_influences[0][:4],\n sorted_weights_class_1=sorted_influences[1][:unit_count],\n sorted_weights_class_2=sorted_influences[2][:unit_count],\n top_patches=top_patches,\n ranking_type=\"Weights\",\n unit_annotations=unit_annotations)\n\n\n@app.route('/top_units_by_appearances')\ndef unit_ranking_by_appearances(unit_count=20, patch_count=6):\n sorted_influences = get_top_units_by_appearances_in_top_units(unit_count)\n top_patches = {}\n unit_annotations = {}\n\n for class_id, count in ((0, 4), (1, unit_count), (2, unit_count)):\n for unit_id, influence, appearances in sorted_influences[class_id][:count]:\n top_patches[unit_id] = backend.get_top_patches_for_unit(unit_id, patch_count, include_normal=class_id == 0)\n survey = backend.get_survey(CURRENT_USER, CURRENT_MODEL, unit_id)\n unit_annotations[unit_id] = backend.survey2unit_annotations_ui(survey, 'german')\n\n return render_template('unit_ranking_by_weights_for_checkpoint.html',\n sorted_weights_class_0=sorted_influences[0][:4],\n sorted_weights_class_1=sorted_influences[1][:unit_count],\n sorted_weights_class_2=sorted_influences[2][:unit_count],\n top_patches=top_patches,\n ranking_type=\"Appearances in Top Units\",\n unit_annotations=unit_annotations)\n\n\n@app.route('/unit/')\ndef unit(unit_id):\n if not backend.single_image_analysis:\n return redirect('/checkpoints')\n top_patches, patch_heatmaps = backend.get_top_patches_and_heatmaps_for_unit(unit_id, 12)\n patch_ground_truth = [path.split(\"/\")[-1][:6] for path in top_patches]\n patch_full_images = [\"-\".join(path.split(\"/\")[-1].split(\"-\")[:2]) + '.jpg' for path in top_patches]\n\n previous_survey = backend.get_survey(CURRENT_USER, CURRENT_MODEL, int(unit_id))\n if previous_survey:\n shows_phenomena, description = previous_survey\n if shows_phenomena:\n shows_phenomena = 'true'\n previous_annotations = {a: a for a in description} # turn into dict for flask\n else:\n shows_phenomena = 'false'\n previous_annotations = {}\n else:\n shows_phenomena = 'true'\n previous_annotations = {}\n\n return render_template('unit.html',\n unit_id=unit_id,\n name=CURRENT_USER,\n model='resnet152',\n top_patches=top_patches,\n patch_ground_truth=patch_ground_truth,\n patch_full_images=patch_full_images,\n patch_heatmaps=patch_heatmaps,\n shows_phenomena=shows_phenomena,\n referrer_url=request.referrer,\n **previous_annotations)\n\n\n@app.route('/handle_survey', methods=['POST'])\ndef handle_survey():\n name = urllib.parse.unquote_plus(request.form['name']) # doctor username\n model = request.form['model'] # resnet152\n unit = request.form['unit'] # unit_0076\n referrer_url = request.form['referrer_url'] # unit_0076\n shows_phenomena = request.form['shows_phenomena']\n phenomena = [p for p in request.form if p.startswith('phe')]\n backend.store_survey(name, model, unit, shows_phenomena, phenomena)\n return redirect(referrer_url)\n\n\n@app.route('/upload', methods=['POST'])\ndef upload_file():\n file = request.files['image']\n full_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)\n file.save(full_path)\n return render_template('single_image.html', success=True, full_path=full_path, image_filename=file.filename)\n\n\n@app.route('/upload_image')\ndef single_image():\n if not backend.single_image_analysis:\n return redirect('/checkpoints')\n return render_template('single_image.html', success=False, processed=False)\n\n\n@app.route('/own_image/')\ndef own_image(image_filename):\n image_path = os.path.join(app.config['UPLOAD_FOLDER'], image_filename)\n image_name = image_filename[:-4]\n\n result = backend.single_image_analysis.analyze_one_image(image_path)\n global CURRENT_RESULT\n CURRENT_RESULT = result\n preprocessed_full_image_path = backend.get_preprocessed_image_path(image_filename)\n\n preprocessed_mask_path = \"\" # no mask available for new images\n preprocessing_descr = dataset.preprocessing_description()\n\n is_correct = 'no_ground_truth'\n\n units_to_show = 10\n top_units_and_activations = result.get_top_units(result.classification, units_to_show)\n heatmap_paths, preprocessed_size = backend.get_heatmap_paths_for_top_units(image_filename, top_units_and_activations, units_to_show, app.config['UPLOAD_FOLDER'])\n\n global FINDINGS_WITH_UNITS\n FINDINGS_WITH_UNITS = []\n\n unique_annotation_ids = []\n clinical_findings = []\n phenomena_heatmaps = []\n unit_annotations = {}\n for unit_index, influence_per_class, activation_map in top_units_and_activations:\n survey = backend.get_survey(CURRENT_USER, CURRENT_MODEL, unit_index + 1)\n unit_annotations[unit_index + 1] = backend.survey2unit_annotations_ui(survey, 'german')\n if survey and survey[0]:\n for annotation_id in survey[1]:\n if annotation_id not in unique_annotation_ids:\n phenomenon_heatmap_path = backend.generate_phenomenon_heatmap(result, annotation_id, preprocessed_size, CURRENT_USER, CURRENT_MODEL)\n human_readable_description = backend.human_readable_annotation(annotation_id, 'german')\n unique_annotation_ids.append(annotation_id)\n clinical_findings.append(human_readable_description)\n phenomena_heatmaps.append(phenomenon_heatmap_path)\n FINDINGS_WITH_UNITS.append([unit_index, human_readable_description])\n\n global CURRENT_HEATMAPS\n CURRENT_HEATMAPS = phenomena_heatmaps\n if not clinical_findings:\n clinical_findings = [\"None\"]\n\n return render_template('image.html',\n image_path=result.image_path,\n image_name=image_name,\n preprocessed_full_image_path=preprocessed_full_image_path,\n preprocessed_mask_path=preprocessed_mask_path,\n checkpoint_path=result.checkpoint_path,\n preprocessing_descr=preprocessing_descr,\n classification=result.classification,\n class_probs=result.class_probs,\n top_units_and_activations=top_units_and_activations,\n heatmap_paths=heatmap_paths,\n unit_annotations=unit_annotations,\n clinical_findings=clinical_findings,\n phenomena_heatmaps=phenomena_heatmaps,\n is_correct=is_correct,\n ground_truth_of_similar=[],\n top20_image_paths=[],\n ground_truth_of_top20=[]\n )\n\n\n@app.route('/correct_classified_images')\ndef correct_classified_images():\n images = {0: backend.get_correct_classified_images(class_id=0, count=6),\n 1: backend.get_correct_classified_images(class_id=1, count=12),\n 2: backend.get_correct_classified_images(class_id=2, count=24)}\n return render_template('correct_classified_images.html',\n images=images)\n\n\n@app.route('/similar_images/', methods=['POST', 'GET'])\ndef similar_images(image_name):\n chosen_findings = []\n if request.method == \"POST\":\n chosen_findings = request.form.getlist('checkboxes') # by user chosen findings that should be displayed\n\n chosen_findings_with_units = []\n for f in FINDINGS_WITH_UNITS:\n for cf in chosen_findings:\n if f[1] == cf:\n chosen_findings_with_units.append(f)\n\n preprocessed_full_image_path = backend.get_preprocessed_image_path(image_name+\".jpg\")\n ground_truth_of_similar, top20_image_paths = similarity_metric_for_uploaded_image(chosen_findings_with_units, CURRENT_RESULT, CURRENT_MODEL)\n phenomena_heatmaps = CURRENT_HEATMAPS\n\n return render_template('similar_images.html',\n preprocessed_full_image_path=preprocessed_full_image_path,\n phenomena_heatmaps=phenomena_heatmaps,\n preprocessed_mask_path=\"\",\n findings=chosen_findings,\n image_name=image_name,\n ground_truth_of_similar=ground_truth_of_similar,\n top20_image_paths=top20_image_paths\n )\n\n\n# for fast testing\n@app.route('/image/')\ndef image(image_filename):\n if not backend.single_image_analysis:\n return redirect('/checkpoints')\n image_path = os.path.join('../data/ddsm_raw/', image_filename)\n image_name = image_filename[:-4]\n preprocessed_full_image_path = backend.get_preprocessed_image_path(image_filename)\n preprocessed_mask_path = backend.get_preprocessed_mask_path(image_filename)\n preprocessing_descr = dataset.preprocessing_description()\n\n result = backend.single_image_analysis.analyze_one_image(image_path)\n ground_truth = dataset.get_ground_truth_from_filename(image_filename)\n is_correct = ground_truth == result.classification\n\n units_to_show = 10\n top_units_and_activations = result.get_top_units(result.classification, units_to_show)\n heatmap_paths, preprocessed_size = backend.get_heatmap_paths_for_top_units(image_filename, top_units_and_activations, units_to_show)\n\n unique_annotation_ids = []\n clinical_findings = []\n phenomena_heatmaps = []\n unit_annotations = {}\n for unit_index, influence_per_class, activation_map in top_units_and_activations:\n survey = backend.get_survey(CURRENT_USER, CURRENT_MODEL, unit_index + 1)\n unit_annotations[unit_index + 1] = backend.survey2unit_annotations_ui(survey, 'german')\n if survey and survey[0]:\n for annotation_id in survey[1]:\n if annotation_id not in unique_annotation_ids:\n phenomenon_heatmap_path = backend.generate_phenomenon_heatmap(result, annotation_id, preprocessed_size, CURRENT_USER, CURRENT_MODEL)\n human_readable_description = backend.human_readable_annotation(annotation_id, 'german')\n unique_annotation_ids.append(annotation_id)\n clinical_findings.append(human_readable_description)\n phenomena_heatmaps.append(phenomenon_heatmap_path)\n\n ground_truth_of_similar, top20_image_paths, ground_truth_of_top20 = similarity_metric(image_filename, CURRENT_USER, CURRENT_MODEL)\n\n return render_template('image.html',\n image_path=result.image_path,\n image_name=image_name,\n preprocessed_full_image_path=preprocessed_full_image_path,\n preprocessed_mask_path=preprocessed_mask_path,\n checkpoint_path=result.checkpoint_path,\n preprocessing_descr=preprocessing_descr,\n classification=result.classification,\n class_probs=result.class_probs,\n top_units_and_activations=top_units_and_activations,\n heatmap_paths=heatmap_paths,\n unit_annotations=unit_annotations,\n unique_annotation_ids=unique_annotation_ids,\n clinical_findings=clinical_findings,\n phenomena_heatmaps=phenomena_heatmaps,\n ground_truth=ground_truth,\n is_correct=is_correct,\n ground_truth_of_similar=ground_truth_of_similar,\n top20_image_paths=top20_image_paths,\n ground_truth_of_top20=ground_truth_of_top20)\n\n\n@app.route('/example_analysis')\ndef example_analysis():\n # good examples:\n # cancer_15-B_3504_1.RIGHT_CC.LJPEG.1.jpg -> 99% cancer, two spots\n # cancer_09-B_3410_1.LEFT_CC.LJPEG.1.jpg -> one round mass\n # cancer_09-C_0049_1.LEFT_MLO.LJPEG.1.jpg -> speculated mass\n # benign_09-D_4075_1.LEFT_CC.LJPEG.1.jpg -> three different masses\n return image('cancer_09-B_3134_1.RIGHT_CC.LJPEG.1.jpg')\n\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":16460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124433515","text":"#Josh Cohen\n#10/21/14\n#Double Linked List Implementation\n\nclass DoublyLinkedBase:\n\n class Node:\n\n def __init__(self,element,prev,nxt):\n\n self.element = element\n self.prev = prev\n self.nxt = nxt\n\n def __init__(self):\n \n self.header = self.Node(None,None,None)\n self.trailer = self.Node(None,None,None)\n self.header.nxt = self.trailer\n self.trailer.prev = self.header\n self.size = 0\n \n\n def __len__(self):\n\n return self.size\n\n def is_empty(self):\n\n return not self.size\n\n def insert_between(self, elt, pred, suc):\n\n new = self.Node(elt, pred, suc)\n pred.nxt = new\n suc.prev = new\n self.size += 1\n return new\n\n def delete_node(self, node):\n\n pred = node.prev\n suc = node.nxt\n pred.nxt = suc\n suc.prev = pred\n element = node.element\r\n node.prev = node.nxt = node.element = None\n self.size -= 1\n return element\n\n \n","sub_path":"DoublyLinkedBase.py","file_name":"DoublyLinkedBase.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"567118557","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('courses', '0019_auto_20150614_1506'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='certificate',\n name='type',\n field=models.CharField(unique=True, default='NI', choices=[('CC', 'Certificate of Completion'), ('CA', 'Certificate of Accomplishment'), ('HCC', 'Honor Code Certificate'), ('VC$', 'Verified Certificate'), ('VCA$', 'Verified Certificate of Accomplishment'), ('SA', 'Statement of Accomplishment'), ('SP$', 'Statement of Participation'), ('CM', 'Certificate of Mastery'), ('NI', 'No Information About Certificate Available'), ('NC', 'No Certificate')], max_length=4),\n ),\n ]\n","sub_path":"courses/migrations/0020_auto_20150614_1518.py","file_name":"0020_auto_20150614_1518.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"397484583","text":"# Import needed libraries\nimport os\nimport csv\nfrom decimal import Decimal\n\ncsvpath = os.path.join('Resources', 'budget_data.csv')\n\nwith open(csvpath, newline='') as csvfile:\n\n # CSV reader specifies delimiter and variable that holds contents\n csvreader = csv.reader(csvfile, delimiter=',')\n\n # Read the header row first (skip this step if there is now header)\n csv_header = next(csvreader)\n\n # Read each row of data after the header \n months = 0\n total = 0.0\n compare_list = []\n str_list = []\n change_list = []\n \n\n for row in csvreader:\n \n months = months + 1\n total = total + int(row[1])\n \n # Make a list to find greatest increase and decrease\n compare_list.append(int(row[1]))\n str_list.append(row[0])\n \n for i in range(len(compare_list)-1):\n \n # Make a list of every month changes\n change = compare_list[i+1] - compare_list[i]\n change_list.append(change)\n\n \n\n print(\"\\nFinancial Analysis\")\n print(\"----------------------------\")\n print(f\"Total Months: {months}\")\n print(f\"Total: ${'{:.2f}'.format(round(total))}\")\n print(f\"Average Change: ${'{:.2f}'.format(round(sum(change_list)/len(compare_list)))}\")\n print(f\"Greatest Increase in Profits: {str_list[compare_list.index(max(compare_list))]} (${max(compare_list)})\")\n print(f\"Greatest Decrease in Profits: {str_list[compare_list.index(min(compare_list))]} (${min(compare_list)})\")\n \n# Write it into a txt file\nfile = open(\"Financial Analysis.txt\", \"w\")\n\nfile.write(\"Financial Analysis\\n\")\nfile.write(\"----------------------------\\n\")\nfile.write(f\"Total Months: {months}\\n\")\nfile.write(f\"Total: ${total}\\n\")\nfile.write(f\"Average Change: ${sum(change_list)/len(compare_list)}\\n\")\nfile.write(f\"Greatest Increase in Profits: {str_list[compare_list.index(max(compare_list))]} (${max(compare_list)})\\n\")\nfile.write(f\"Greatest Decrease in Profits: {str_list[compare_list.index(min(compare_list))]} (${min(compare_list)})\\n\")\n\nfile.close()\n \n\n \n ","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63270399","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 25 18:18:17 2016\n\n@author: yos1up\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport os\nimport h5py\n\nfrom . import WSH5\n\ndef musicnet_to_wsh5(file, meta, out_dir, ensemble=None):\n '''\n musicnet の曲を wsh5 形式 (wave-score-h5) に変換します\n\n musicnet の中には「4ケタのID番号」でナンバリングされた曲が数百曲収録されています.\n それらを {out_dir}/{ID}.h5 という名前の wsh5 ファイルに変換していきます. \n\n ------\n Args:\n file (str):\n musicnet.npzのパス\n meta (str):\n musicnet_metadata.csvのパス\n out_dir (str):\n wsh5 ファイルたちを保存するディレクトリ\n ensemble (str or None):\n どの楽器編成の曲を,wsh5 にするか. 例: \"Solo Piano\"\n Noneの時は,全曲を wsh5 にします.\n (楽器編成を指定する文字列については musicnet_metadata.csv 参照)\n '''\n data = np.load(open(file,'rb'), encoding='latin1', allow_pickle=True)\n os.makedirs(out_dir, exist_ok=True)\n meta = pd.read_csv(meta)\n if ensemble is None:\n ids = meta[\"id\"].astype(str).tolist()\n else:\n ids = meta[meta['ensemble']==ensemble][\"id\"].astype(str).tolist()\n for h, id_str in enumerate(ids):\n # wsdata = wavescoredata()\n print('processing: id =',id_str,'(',h+1,'/',len(ids),')')\n x, y = data[id_str] # x: 波形 (ndarray (num_of_sample,))\n # y: 楽譜データ (intervaltree)\n in_npy = x.astype(np.float32).reshape(1, -1) # [パート,時間]\n intvl = 512\n out_sample = np.arange(0, len(x), intvl, dtype=np.int64)\n out_npy = np.zeros([1, 128, len(out_sample)], dtype=np.float32) # [パート,音高,時刻]\n # NOTE: 音量情報も込められうるように int ではなく float にしておく.\n\n # outを集計\n for i,s in enumerate(out_sample):\n nns = [n[2][1] for n in y[s]]\n for nn in nns:\n out_npy[0, nn, i] = 1.\n print(' .wave.shape:', in_npy.shape, '.score.shape:', out_npy.shape, 'score_sample.shape:', out_sample.shape)\n print(' .wave.dtype:', in_npy.dtype, '.score.dtype:', out_npy.dtype, 'score_sample.dtype:', out_sample.dtype)\n\n\n savefilename = out_dir + '/' + str(id_str) + '.h5'\n WSH5.save_wsh5(savefilename, wave=in_npy, score=out_npy, score_sample=out_sample)\n print(' saved:', savefilename)\n print('Done.')\n","sub_path":"mimicopynet/data/musicnet_to_wsh5.py","file_name":"musicnet_to_wsh5.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"11923788","text":"import pandas as pd\nfrom pandas import DataFrame\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)\n\n\n# Solution\ndef plot_deliveries_by_team():\n teams=np.unique(ipl_df['batting_team'])\n ipl_df['count']=1\n deliveries=ipl_df.pivot_table(index='batting_team',aggfunc=np.sum )\n deliveries_count=deliveries['count']\n\n plt.xlabel('Teams')\n plt.ylabel('Deliveries Played ')\n plt.bar(teams,deliveries_count)\n plt.xticks(teams,rotation='vertical')\n plt.show()\n","sub_path":"q01_plot_deliveries_by_team/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"53252058","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n__author__ = 'Lin'\n\nimport codecs\nimport string\n\n\ndef test():\n \"先测试一下一句话的词频分析法,参考上一题的数据\"\n # 好吧,只有一行数据果然太少了,字典对应的61才是正确的,可是61只出现了1次\n # 这里采取的思路是,这里面肯定有一个对应着e,所以把每个都遍历一遍就是了\n # 判断是否为英文语句的标准是,空格的数量,嘿嘿~~\n hex_string = \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\"\n bytes_string = codecs.decode(hex_string, \"hex\")\n\n characters = []\n for value in set(bytes_string):\n character = chr(value ^ ord('e'))\n if character in string.ascii_letters:\n characters.append(character)\n\n for each_ch in characters:\n each_ch = codecs.encode(each_ch, \"ascii\") * len(bytes_string)\n decrypto_text = byte_xor(each_ch, bytes_string)\n if decrypto_text.count(b' ') > 3:\n print(decrypto_text)\n\n\ndef byte_xor(bytes1, bytes2):\n return bytes([a ^ b for a, b in zip(bytes1, bytes2)])\n\n\ndef main():\n blocks = []\n with open(\"task4.txt\", \"r\") as f:\n # block_size = 60 # 坑了,有一部分没有60字节,所以不能这样读\n data = f.readline().strip()\n while data != '':\n blocks.append(data)\n data = f.readline().strip()\n\n for each_block in blocks:\n each_block = codecs.decode(each_block, \"hex\")\n value_set = set(each_block)\n\n for value in value_set:\n character = hex(value ^ ord('e'))[2:].zfill(2) # 之前错误的原因在于以为异或的只有英文字母\n character_string = codecs.decode(character, \"hex\") * len(each_block)\n decrypto_text = byte_xor(each_block, character_string)\n if decrypto_text.count(b' ') > 3: # 3这个基准可以修改的\n print(decrypto_text)\n\n\nif __name__ == '__main__':\n main()\n # test()","sub_path":"Hackathon-submit/Set 1 Basics/4 Detect single-character XOR/4.Detect single-character XOR.py","file_name":"4.Detect single-character XOR.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"509564976","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom girder.api import access\nfrom girder.api.describe import Description, autoDescribeRoute\nfrom girder.api.docs import addModel\nfrom girder.api.rest import Resource, RestException\n\nfrom girder.plugins.wholetale.lib.dataone import DataONELocations\nfrom ..lib import RESOLVERS, IMPORT_PROVIDERS\nfrom ..lib.entity import Entity\nfrom ..lib.resolvers import ResolutionException\nfrom ..lib.data_map import dataMapDoc\nfrom ..lib.file_map import fileMapDoc\n\n\naddModel('dataMap', dataMapDoc)\naddModel('fileMap', fileMapDoc)\n\n\nclass Repository(Resource):\n def __init__(self):\n super(Repository, self).__init__()\n self.resourceName = 'repository'\n\n self.route('GET', ('lookup',), self.lookupData)\n self.route('GET', ('listFiles',), self.listFiles)\n\n @staticmethod\n def _buildAndResolveEntity(dataId, base_url, user):\n entity = Entity(dataId, user)\n entity['base_url'] = base_url\n # resolve DOIs, etc.\n return RESOLVERS.resolve(entity)\n\n @access.public\n @autoDescribeRoute(\n Description('Create data mapping to an external repository.')\n .notes('Given a list of external data identifiers, '\n 'returns mapping to specific repository '\n 'along with a basic metadata, such as size, name.')\n .jsonParam('dataId', paramType='query', required=True,\n description='List of external datasets identificators.')\n .param('base_url', 'The node endpoint url. This can be used '\n 'to register datasets from custom networks, '\n 'such as the DataONE development network. This can '\n 'be passed in as an ordinary string. Examples '\n 'include https://dev.nceas.ucsb.edu/knb/d1/mn/v2 and '\n 'https://cn.dataone.org/cn/v2',\n required=False, dataType='string', default=DataONELocations.prod_cn)\n .responseClass('dataMap', array=True))\n def lookupData(self, dataId, base_url):\n # methinks all logic should be in the model or lib and the resource should only\n # delegate to the model/lib.\n # also, why is size required at this point?\n results = []\n try:\n for pid in dataId:\n entity = Repository._buildAndResolveEntity(\n pid.strip(), base_url, self.getCurrentUser())\n provider = IMPORT_PROVIDERS.getProvider(entity)\n results.append(provider.lookup(entity))\n except ResolutionException:\n raise RestException(\n 'Id \"{}\" was categorized as DOI, but its resolution failed.'.format(pid))\n except Exception as exc:\n raise RestException(\n 'Lookup for \"{}\" failed with: {}'.format(pid, str(exc)))\n\n results = [x.toDict() for x in results]\n return sorted(results, key=lambda k: k['name'])\n\n @access.public\n @autoDescribeRoute(\n Description('Retrieve a list of files and nested packages in a DataONE repository')\n .notes('Given a list of external data identifiers, '\n 'returns a list of files inside along with '\n 'their sizes')\n .jsonParam('dataId', paramType='query', required=True,\n description='List of external datasets identificators.')\n .param('base_url', 'The member node base url. This can be used '\n 'to search datasets from custom networks ,'\n 'such as the DataONE development network.',\n required=False, dataType='string',\n default=DataONELocations.prod_cn)\n .responseClass('fileMap', array=True))\n def listFiles(self, dataId, base_url):\n results = []\n try:\n for pid in dataId:\n entity = Repository._buildAndResolveEntity(\n pid.strip(), base_url, self.getCurrentUser())\n provider = IMPORT_PROVIDERS.getProvider(entity)\n results.append(provider.listFiles(entity))\n except ResolutionException:\n raise RestException(\n 'Id \"{}\" was categorized as DOI, but its resolution failed.'.format(pid))\n except Exception as exc:\n raise RestException(\n 'Listing files at \"{}\" failed with: {}'.format(pid, str(exc)))\n return sorted([x.toDict() for x in results], key=lambda k: list(k))\n","sub_path":"server/rest/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"224594273","text":"import bibtexparser\n\ndef format_authors(entry):\n return \" and \".join([\" \".join([author.split()[0][0].upper(), author.split()[1]]) for author in entry[\"author\"].split(\" and \")])\n\ndef format_volume(entry):\n x = entry.get(\"volume\", \"\")\n return \"Vol. \" + x + \". \" if len(x) else \"\"\n\ndef format_year_pages(entry):\n year = entry.get(\"year\", \"\")\n pages = entry.get(\"pages\", \"\")\n if len(year) and len(pages):\n return \"%s, %s. \" % (year, pages)\n elif len(year):\n return \"%s. \" % (year,)\n return \"%s.\" % (pages,)\n\ndef format_download(entry):\n link = entry.get(\"link\", \"\")\n if len(link):\n return 'get_app' % (link,)\n return \"\"\n\ndef entry_to_text(entry):\n return '%s. \"%s\". In %s. %s%s%s' % (\n format_authors(entry), \n entry[\"title\"], \n entry[\"booktitle\"], \n format_volume(entry),\n format_year_pages(entry),\n entry.get(\"addendum\",\"\"))\n\ndef entry_to_html(entry):\n return '%s %s. \"%s\". In %s. %s%s%s' % (\n format_download(entry),\n format_authors(entry), \n entry[\"title\"], \n entry[\"booktitle\"], \n format_volume(entry),\n format_year_pages(entry),\n entry.get(\"addendum\",\"\"))\n\nif __name__ == \"__main__\":\n\n path = \"/Users/Jeff/SFU/PhD/CV/pub.bib\"\n with open(path) as bibtex_file:\n bib_database = bibtexparser.load(bibtex_file)\n \n for entry in bib_database.entries:\n print(entry_to_html(entry) + \"

\")","sub_path":"test/pub.py","file_name":"pub.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322220835","text":"#encoding:utf-8\n\n#\n#Canny边缘检测\n#\n\nimport numpy as np\nimport cv2\n\nimage = cv2.imread(\"../dataset/Planes/AC-130/AC-130_10_r0.bmp\")#读入图像\n\nimage = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)#将图像转化为灰度图像\ncv2.imshow(\"Image\",image)#显示图像\nprint(image)\ncv2.waitKey()\n#Canny边缘检测\ncanny = cv2.Canny(image,30,150)\nprint(canny.shape)\ncv2.imshow(\"Canny\",canny)\ncv2.waitKey()","sub_path":"hypercols/run_edges_planes.py","file_name":"run_edges_planes.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"473355754","text":"'''\npython2 ./src/add_data.py $INPUT_FILE results/rule_data_list results/similarity tmp 3\n'''\n\nimport sys\ntrain_data = open(sys.argv[1], 'r')\nrule_data = open(sys.argv[2], 'r')\nrule_similarity = open(sys.argv[3], 'r')\nnew_train_data = open(sys.argv[4], 'w')\n\nrule_line = rule_data.readlines()\nrule_index = [[int(i) for i in rule.split()] for rule in rule_line]\nrule_len = [len(i) for i in rule_index]\n## print(rule_len)\n\nline = rule_similarity.readline()\nrule_similarity = [float(i) for i in line.split()]\n## print(rule_similarity)\n\nn = len(rule_similarity)\n\nsimilarity_threshold = 5000\nrule_len_threshold = 100 \n\nfunc = lambda i: rule_len[i] < rule_len_threshold and rule_similarity[i] < similarity_threshold\nindx = filter(func,[i for i in range(n)])\nprint(indx)\n\nindx = [rule_index[i] for i in indx]\n\n#for i in indx:\n#\tprint(len(i))\n#for i in rule_index:\n#\tprint(len(i))\n\norigin_train_line = train_data.readlines()\nnew_train_data.write(''.join(origin_train_line))\n\nnew_add_data = [[origin_train_line[j + 1] for j in i] for i in indx]\nnew_add_data = [ ''.join(i) for i in new_add_data ]\nnew_add_data = ''.join(new_add_data)\n\nrepeat_times = int(sys.argv[5])\nfor i in range(repeat_times):\n\tnew_train_data.write(new_add_data)\n\n\n\n","sub_path":"update_rule/src/add_data.py","file_name":"add_data.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212292721","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\nSECRET_KEY = 'xhcg42=d%md&1jcy$c8%#p5e+59!)25v$m$%uq*^1hfx%23i+p'\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nSTATIC_URL = '/static/'\n\n# for deployment, collects the static files into STATIC_ROOT\nSTATIC_ROOT = os.path.join(BASE_DIR, 'collectedstatic')\n\n# STATICFILES_DIRS = (\n# os.path.join(BASE_DIR, \"static\"),\n# )\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates').replace('\\\\', '/'),\n os.path.join(BASE_DIR, 'django_blog/apps/blog/templates').replace('\\\\', '/'),\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.request',\n 'django.core.context_processors.i18n',\n 'django.contrib.messages.context_processors.messages',\n 'apps.blog.processor.tag_list',\n)\n\nALLOWED_HOSTS = []\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.sitemaps',\n 'reversion',\n 'apps.blog',\n 'pagedown',\n]\n\nMIDDLEWARE_CLASSES = (\n\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'django_blog.urls'\n\nWSGI_APPLICATION = 'django_blog.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'blog',\n\t'USER': 'song',\n\t'PASSWORD': 'etaoin',\n\t'HOST': 'localhost',\n\t'PORT': '3306',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\nTIME_ZONE = 'Etc/GMT%+-d' % (time.timezone / 3600)\n# LANGUAGE_CODE = 'zh-cn'\nLANGUAGE_CODE = 'en-us'\nSITE_ID = 1\n\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = False\n\n# TINYMCE_JS_URL = 'http://debug.example.org/tiny_mce/tiny_mce_src.js'\nTINYMCE_DEFAULT_CONFIG = {\n 'plugins': \"table,spellchecker,paste,searchreplace\",\n # 'plugins': [\n # \"advlist autolink lists link image charmap print preview anchor\",\n # \"searchreplace visualblocks code fullscreen\",\n # \"insertdatetime media table contextmenu paste moxiemanager\"\n # ],\n # 'theme': \"simple\",\n 'cleanup_on_startup': True,\n 'custom_undo_redo_levels': 10,\n}\nTINYMCE_SPELLCHECKER = True\n# TINYMCE_COMPRESSOR = True\n\nPAGE_SIZE = 7\n\n# compressor\nINSTALLED_APPS += (\"compressor\",)\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'compressor.finders.CompressorFinder',\n)\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt' : \"%d/%b/%Y %H:%M:%S\"\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'file': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': '/home/yangjinsong/log/mysite.log',\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers':['file'],\n 'propagate': True,\n 'level':'DEBUG',\n },\n }\n}\n","sub_path":"django_blog/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"273753741","text":"import zipfile, os, pathlib\n\n\ndef to_zip(path_to_zip: str, objects: list):\n\n with zipfile.ZipFile(path_to_zip, 'w') as ZipArchive:\n for object in objects:\n if os.path.isdir(object):\n folder = os.path.abspath(object)\n for foldername, subfolders, filenames in os.walk(folder):\n\n if foldername == folder:\n archive_folder_name = ''\n else:\n archive_folder_name = os.path.relpath(foldername, folder)\n ZipArchive.write(foldername, arcname=archive_folder_name)\n\n for filename in filenames:\n ZipArchive.write(os.path.join(foldername, filename), arcname=os.path.join(archive_folder_name, filename))\n elif os.path.isfile(object):\n ZipArchive.write(object, arcname=os.path.basename(object))\n \n\ndef unzipping(path_to_zip: str, where_to_extract: str = None):\n if where_to_extract == None:\n where_to_extract = path_to_zip\n output_name = os.path.splitext(os.path.basename(where_to_extract))[0]\n where_to_extract = pathlib.Path(path_to_zip).resolve().parent\n where_to_extract = os.path.join(where_to_extract, output_name)\n\n with zipfile.ZipFile(path_to_zip, 'r') as zipEx:\n zipEx.extractall(where_to_extract)\n\n","sub_path":"pyArchiver/pyArchiver.py","file_name":"pyArchiver.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"393909080","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom dwitter.models import Dweet\nfrom django.utils import timezone\nfrom datetime import timedelta\n\n\nclass DweetTestCase(TestCase):\n def setUp(self):\n user1 = User.objects.create(username=\"user1\", password=\"\")\n user2 = User.objects.create(username=\"user2\", password=\"\")\n\n now = timezone.now()\n\n dweet1 = Dweet.objects.create(id=1,\n code=\"dweet1 code\",\n posted=now - timedelta(minutes=1),\n author=user1)\n\n dweet2 = Dweet.objects.create(id=2,\n code=\"dweet2 code\",\n posted=now,\n reply_to=dweet1,\n author=user2)\n dweet2.likes.add(user1, user2)\n\n def test_dweet_renders_to_string_correctly(self):\n self.assertEqual(Dweet.objects.get(id=1).__unicode__(), \"d/1 (user1)\")\n self.assertEqual(Dweet.objects.get(id=2).__unicode__(), \"d/2 (user2)\")\n\n def test_dweet_reply_to_set_deleted_field_on_delete(self):\n dweet1 = Dweet.objects.get(id=1)\n dweet1.delete()\n self.assertEqual(dweet1.deleted, True)\n self.assertEqual(Dweet.objects.get(id=2).reply_to, dweet1)\n\n def test_dweet_author_set_null_on_delete(self):\n User.objects.get(username=\"user1\").delete()\n self.assertTrue(Dweet.with_deleted.get(id=1).deleted)\n self.assertEqual(Dweet.objects.get(id=2).author,\n User.objects.get(username=\"user2\"))\n\n def test_dweet_has_correct_likes(self):\n dweet1 = Dweet.objects.get(id=1)\n dweet2 = Dweet.objects.get(id=2)\n all_users = [repr(u) for u in User.objects.all()]\n\n self.assertQuerysetEqual(dweet1.likes.all(), [])\n self.assertQuerysetEqual(dweet2.likes.order_by('id'), all_users)\n\n def test_default_manager_does_not_include_deleted_dweets(self):\n second_dweet = [repr(Dweet.objects.get(id=2))]\n Dweet.objects.get(id=1).delete()\n self.assertQuerysetEqual(Dweet.objects.all(), second_dweet)\n\n def test_with_deleted_manager_includes_deleted_dweets(self):\n all_dweets = [repr(d) for d in Dweet.objects.all()]\n Dweet.objects.get(id=1).delete()\n self.assertQuerysetEqual(Dweet.with_deleted.all(), all_dweets)\n","sub_path":"dwitter/tests/models/test_dweet.py","file_name":"test_dweet.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"281799174","text":"#translates and splits up the last column\nimport csv\nimport sys\n\nfile = sys.argv[1]\n\nreader = csv.DictReader(open(file))\nwith open('jiko.csv', 'w', newline='') as jiko:\n\tfieldnames = ['\\ufeff日時','路線','場所','被害']\n\twriter = csv.DictWriter(jiko, fieldnames = fieldnames)\n\twriter.writeheader()\n\tfor row in reader:\n\t\titem = row['被害']\n\t\t#add // if it's empty\n\t\tif len(item) == 0:\n\t\t\titem += '//'\n\n\t\t#add / between items\n\t\telif len(item) > 0:\n\t\t\tif item[0] == '男' or item[0] == '女':\n\t\t\t\titem = '/' + item\n\t\t\tif item[0] == '死' or item[0]=='重'or item[0] =='軽' or item[0] =='無' or item[0]== '被': \n\t\t\t\titem = '//' + item\n\t\t\tif item[len(item)-1] == '性':\n\t\t\t\titem = item + '/'\n\t\t\tif item[len(item)-1]=='歳':\n\t\t\t\titem = item + '//'\n\n\t\trow['被害'] = item\n\t\t#print(row['被害'])\n\n\t\tcount = 0\n\t\titemcount = row['被害']\n\t\t#count how many / there are\n\t\tfor i in itemcount:\n\t\t\tif i == '/':\n\t\t\t\tcount +=1\n\t\tindex = 0\n\t\t#if there is only one / add another inbetween\n\t\tif count ==1:\n\t\t\t#print(itemcount)\n\t\t\ta, b = itemcount.split('/')\n\t\t\titemcount = a + '//' + b\n\t\t\trow['被害'] = itemcount\n\t\t\t#print(row['被害'])\n\n\t\t#add another / based on how many other people died\n\t\titem = row['被害']\n\t\tif len(item)> 0:\n\t\t\t#if no one died\n\t\t\tif item[len(item)-1] != '名':\n\t\t\t\titem = item + '/'\n\t\t\t#if other people died\n\t\t\telif item[len(item)-1] =='名':\n\t\t\t\ta = item[0:len(item)-4]\n\t\t\t\tb = item[len(item)-4: len(item)]\n\n\t\t\t\titem = a + '/' + b\n\t\t\trow['被害'] = item\n\t\t\n\t\ttransitem = row['被害']\n\t\t\n\t\t#brute force translation\n\t\t#if it's 不明 leave it as is\n\t\tif len(transitem) > 0:\n\t\t\tif transitem == '不明' or transitem == '不明/':\n\t\t\t\t#ADD CODE\n\t\t\t\tthing = transitem\n\n\t\t\t\n\t\t\telse:\n\t\t\t\t#split it \n\t\t\t\ttry:\n\t\t\t\t\ta, b, c, d = transitem.split('/')\n\t\t\t\texcept ValueError:\n\t\t\t\t\tprint(\"Error!\")\n\t\t\t\t\tprint(transitem)\n\t\t\t\t#translate age\n\t\t\t\tif len(a) > 0:\n\t\t\t\t\tif a[len(a)-1] == '歳':\n\t\t\t\t\t\t#print(a)\n\t\t\t\t\t\ta = a[0:len(a)-1]\n\t\t\t\t\t#if decade make it 10s etc\n\t\t\t\t\tif a[len(a)-1] == '代':\n\t\t\t\t\t\ta = a[0:len(a)-1]\n\t\t\t\t\t\ta = a + 's'\n\t\t\t\t#translate gender\n\t\t\t\tif len(b) > 0:\n\t\t\t\t\tif b[0] == '男':\n\t\t\t\t\t\tb = 'Male'\n\t\t\t\t\tif b[0] =='女':\n\t\t\t\t\t\tb = 'Female'\n\t\t\t\t#translate injury\n\t\t\t\tif len(c) > 0:\n\t\t\t\t\tif c[0] == '死':\n\t\t\t\t\t\tc = 'Fatal'\n\t\t\t\t\tif c[0] == '重':\n\t\t\t\t\t\tc = 'Severe Injury'\n\t\t\t\t\tif c[0] == '軽':\n\t\t\t\t\t\tc = 'Minor Injury'\n\t\t\t\t\tif c[0] == '無':\n\t\t\t\t\t\tc = 'No Injury'\n\t\t\t\t\tif c[0] == '被':\n\t\t\t\t\t\tc = 'Injury Unknown'\n\t\t\t\t#translate how many others involved\n\t\t\t\tif len(d) == 0 and (len(a) > 0 or len(b) >0 or len(c) >0):\n\t\t\t\t\tdig = '0'\n\t\t\t\telif len(d) > 0:\n\t\t\t\t\tdigit = ''\n\t\t\t\t\tfor i in d:\n\t\t\t\t\t\tif i.isdigit():\n\t\t\t\t\t\t\tdigit += i\n\t\t\t\t\tdig = digit\n\t\t\t\t\t#print(digit)\n\t\t\t\telse:\n\t\t\t\t\tdig = d\n\t\t\t\tthing = a + '/' + b + '/' + c + '/' + dig\n\t\t#update row\n\t\trow['被害'] = thing\n\t\twriter.writerow(row)\n\n\t\t#ADD CODE\n\t\t#replace thing in csv file\n\t\t#writer.writerow(row)\n\n\t\t\n\n\t\t#print(row['被害'])\n\t\t#print(row['被害'])\n\t\t#print(transitem)\n\t\t#print(row['被害'])\n\n","sub_path":"pre_processing_scripts/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"192467768","text":"import cv2\n\n# Including Haarcascade which contains informations about many faces already detected.\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n# Switching on the camera to detect video.\ncap = cv2.VideoCapture(0)\n\n# When camera will be opened\nwhile cap.isOpened():\n _, img = cap.read()\n \n # Changing the frame to grayscale \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n # Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles.\n faces = face_cascade.detectMultiScale(gray, 1.1, 4)\n \n # Drawing the rectangles at the co-ordinates returned from the 'detectMultiScale' method. \n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 3)\n \n # Showing the image.\n cv2.imshow('img', img)\n \n if cv2.waitKey(1) & 0xFF == 27:\n break\ncap.release()\n","sub_path":"Face_Detection/Face_Detection.py","file_name":"Face_Detection.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"401336158","text":"from wisemailer.models import Campaign, MailList, Subscriber, Unsubscribe, Segment\nfrom ckeditor.widgets import CKEditorWidget\nfrom mongodbforms import MongoCharField\nfrom mongodbforms.widgets import HiddenInput\nfrom wiseutils.forms import BootstrapForm, WiseDateTimeWidget\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\n\nclass SegmentForm(BootstrapForm):\n class Meta:\n document = Segment\n fields = ['title', 'archive', 'query', 'query_builder']\n widgets = {\n 'query': HiddenInput(),\n 'query_builder': HiddenInput(),\n }\n\n\nclass MailListForm(BootstrapForm):\n class Meta:\n document = MailList\n fields = ['title', 'active', 'archive']\n\n\nclass CampaignFormDoc(BootstrapForm):\n class Meta:\n document = Campaign\n fields = ['title', 'subject', 'email_from', 'email_from_name', 'lists', 'template', 'send_at', 'utm_campaign', 'utm_content']\n widgets = {\n 'send_at': WiseDateTimeWidget(attrs={'class': 'input-small', 'style': 'display:inline'})\n }\n template = MongoCharField(widget=CKEditorWidget(), required=True)\n\n def __init__(self, *args, **kwargs):\n super(CampaignFormDoc, self).__init__(*args, **kwargs)\n if kwargs.get('instance'):\n self.fields['template'].initial = kwargs.get('instance').get_template()\n\n def save(self, commit=True):\n campaign = super(CampaignFormDoc, self).save(commit=False)\n campaign.set_template(self.cleaned_data['template'])\n if commit:\n campaign.save()\n return campaign","sub_path":"wiseadmin/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"381203186","text":"import os\n\n\nQPATH = '../questions/'\nOUTPATH = 'static/angulartemplates/'\n\n\ndef find_2nd(string, substring):\n return string.find(substring, string.find(substring) + 1)\n\n\nif __name__ == '__main__':\n for subject in next(os.walk(QPATH))[1]:\n if subject == 'Geography' or subject == 'Psychology' or subject == 'History' or subject == 'BusinessManagement' or subject == 'Economics':\n continue\n\n print(subject)\n\n for question in next(os.walk(os.path.join(QPATH, subject)))[2]:\n qid = question.strip('.html')\n\n with open(os.path.join(QPATH, subject, question)) as f:\n contents = f.read()\n contents = contents.replace('../../../../../../../ib-questionbank-attachments.s3.amazonaws.com/uploads/tinymce_asset/asset', 'static/tinymce_asset')\n\n i = contents.find('

Question

')\n contents = contents[i:]\n\n i = find_2nd(contents, ' x\r\n \"\"\"\r\n\r\n def __init__(self):\r\n self._axes = ['x0', 'x1'] # real-world name of axes\r\n self._reference = None # reference point\r\n self._values = None # 2D array of values\r\n self._statuses = None # 1D array of statuses\r\n self.expected = None\r\n self.tolerated = None\r\n self.local = None\r\n self.Global = None\r\n\r\n @property\r\n def axes(self):\r\n return self._axes\r\n\r\n @axes.setter\r\n def axes(self, value):\r\n if value is None:\r\n self._axes = None\r\n return\r\n self._axes = np.atleast_1d(value)\r\n assert self._values is None or self._axes.size <= self._values.shape[1]\r\n\r\n @property\r\n def reference(self):\r\n return self._reference\r\n\r\n @reference.setter\r\n def reference(self, value):\r\n if value is None:\r\n self._reference = None\r\n return\r\n self._reference = np.atleast_1d(value)\r\n assert self._values is None or \\\r\n self._reference.size <= self._values.shape[1]\r\n\r\n @property\r\n def values(self):\r\n return self._values\r\n\r\n @values.setter\r\n def values(self, X):\r\n if X is None:\r\n self._values = None\r\n return\r\n self._values = np.atleast_2d(X)\r\n assert self._axes is None or self._axes.size <= self._values.shape[1]\r\n assert self._statuses is None or \\\r\n self._statuses.size == self._values.shape[0]\r\n\r\n @property\r\n def statuses(self):\r\n return self._statuses\r\n\r\n @statuses.setter\r\n def statuses(self, value):\r\n \"\"\"\r\n Sets status array\r\n\r\n Args:\r\n value (Status or array of Status):\r\n single Status or array of statuses. If single array, status\r\n array will be extended to numer of rows of values array\r\n \"\"\"\r\n if value is None:\r\n self._statuses = None\r\n return\r\n self._statuses = np.atleast_1d(value)\r\n if self._values is None and \\\r\n self._statuses.size == 1 and self.values.shape[0] > 1:\r\n self._statuses = np.full(shape=self.values.shape[0],\r\n fill_value=value, dtype=Status)\r\n\r\n assert self._values is None or \\\r\n self._statuses.size == self.values.shape[0]\r\n\r\n def evaluate(self, P=None, tolerance=1e-10):\r\n \"\"\"\r\n Checks that point P or all points are in \"expected\" or \"tolerated\"\r\n ranges\r\n\r\n Args:\r\n P (tuple of float, optional):\r\n data point. If None, all 'self._values' will be checked\r\n\r\n tolerance (float);\r\n tolerance for checking\r\n\r\n Returns:\r\n status over all points (expected, tolerated, failed)\r\n \"\"\"\r\n if self._statuses is None:\r\n self._statuses = np.full(shape=self.values.shape[0],\r\n fill_value=Status.FAIL, dtype=Status)\r\n if P is None:\r\n b = True\r\n for i in range(self._values.shape[0]):\r\n self._statuses[i] = Status.FAIL\r\n b = True\r\n for j in range(self._axes.size):\r\n b = b and inRange(self._values[i][j], self.expected[j],\r\n tolerance)\r\n if b:\r\n self._statuses[i] = Status.SUCCESS\r\n else:\r\n b = True\r\n for j in range(self._axes.size):\r\n b = b and inRange(self._values[i][j],\r\n self.tolerated[j], tolerance)\r\n if b:\r\n self._statuses[i] = Status.TOLERATE\r\n\r\n for stat in [Status.FAIL, Status.TOLERATE, Status.SUCCESS]:\r\n if stat in self._statuses:\r\n return stat\r\n assert 0\r\n else:\r\n b = True\r\n for j in range(self._axes.size):\r\n b = b and inRange(P, self.expected, tolerance)\r\n if b:\r\n return Status.SUCCESS\r\n b = True\r\n for j in range(self._axes.size):\r\n b = b and inRange(P, self.tolerated, tolerance)\r\n if b:\r\n return Status.TOLERATE\r\n return Status.FAIL\r\n\r\n\r\n# Examples ####################################################################\r\n\r\nif __name__ == '__main__':\r\n test = ToleranceRange()\r\n\r\n test.axes = ['U', 'I']\r\n test.reference = (230, 80)\r\n test.tolerated = ((0, 245), (0, 100))\r\n test.expected = ((4, 241), (0, 90))\r\n test.local = ((0, 300), (0, 1000))\r\n test.Global = ((0, 10e3), (0, 20e3))\r\n test.values = ((3, 355), (30, 50), (7, 66), (9, 77), (3, 33), (11, 99))\r\n\r\n stat = test.evaluate()\r\n\r\n print('test.statuses:', [Status.symbol(x) for x in test.statuses])\r\n print('stat:', stat)\r\n","sub_path":"coloredlids/data/tolerance_range.py","file_name":"tolerance_range.py","file_ext":"py","file_size_in_byte":7642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"254327459","text":"from elasticsearch_dsl import DocType, String, token_filter, analyzer\nfrom django.conf import settings\n\n__author__ = 'erhmutlu'\n\nturkish_stop = token_filter('turkish_stop', type='stop', stopwords=\"_turkish_\")\nturkish_lowercase = token_filter('turkish_lowercase', type='lowercase', language=\"turkish\")\nturkish_stemmer = token_filter('turkish_stemmer', type='stemmer', language='turkish')\ncustom_shingle_filter = token_filter('custom_shingle_filter', type='shingle', max_shingle_size=3, min_shingle_size=2,\n output_unigrams=True)\n\nentity_synonym_index_analyzer = analyzer('entity_synonym_index_analyzer', tokenizer='keyword', filter=[turkish_lowercase, 'asciifolding', turkish_stemmer])\n\nentity_synonym_search_analyzer = analyzer('entity_synonym_search_analyzer', tokenizer='standard',\n filter=[turkish_lowercase, 'apostrophe', 'asciifolding',\n custom_shingle_filter, turkish_stemmer])\n\n\nclass Entity(DocType):\n entity_synonyms = String(index_analyzer=entity_synonym_index_analyzer,\n search_analyzer=entity_synonym_search_analyzer,\n include_in_all=True)\n entity_key = String(index='not_analyzed', include_in_all=False)\n value = String(index='not_analyzed', include_in_all=False)\n\n @classmethod\n def _get_index(self, index=None):\n return settings.ELASTICSEARCH_INDEX\n\n @classmethod\n def _get_doctype(self):\n return settings.ELASTICSEARCH_ENTITY_DOCTYPE\n\n def dict_with_id(self):\n dict = super(DocType, self).to_dict()\n dict['id'] = self._id\n return dict\n\n class Meta:\n index = settings.ELASTICSEARCH_INDEX\n doc_type = settings.ELASTICSEARCH_ENTITY_DOCTYPE\n","sub_path":"service/apps/defaultapp/es_docs/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"591780871","text":"# ------------------------------------------------------\n# Tested with Ubuntu 18.04.3 LTS and python 3.6.9\n#\n# THIS IS AN OLD VERSION OF THE PROGRAM THAT SHOULD PROCESS DATA FOR LORA EXPERIMENT\n# It is probably bugged and uncommented.\n# Please, refer to trace.py for a cleaner implementation\n#\n# contact : theotime.balaguer@insa-lyon.fr\n# ------------------------------------------------------\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom math import sqrt\n\nN = 100 #Nombre d'échantillons à une puissance et une distance donnée\npas_dist = 6 #Différence de distance entre les expériences, en m.\npas_pow = 3 #différence de puissance entre les expériences, en dB.\n\n\ndef mean(data):\n return sum(data) / len(data)\n\ndef ecart_type(data):\n x = 0\n moyenne = mean(data)\n for val in data:\n x += pow(abs(val-moyenne), 2)\n etype = sqrt(x/len(data))\n return etype\n\ndef read_data(paths):\n datas1 = []\n datas2 = []\n\n for path in paths:\n datas1.append(pd.read_csv(path+'/data1.csv').tail(N))\n datas2.append(pd.read_csv(path+'/data2.csv').tail(N))\n\n return (datas1, datas2)\n\n#data est un tuple de dataframes pandas\ndef error_rate(data):\n data1 = data[0]\n data2 = data[1]\n\n error_rate1 = ((N-len(data1[0]['x_value']))/N)*100\n error_rate2 = ((N-len(data2[0]['x_value']))/N)*100\n return (error_rate1, error_rate2)\n\n#DO: calcule la moyenne des échantillons pour chaque expérience, et trace la courbe du rssi moyen en fonction de la distance entre les noeux\n#en associant chaque donnée à une valeur de distance\n#INPUT: Prend un tableau de tableaux représentant les données ders expériences pour plusieurs distances différentes,\n#classés par ordre de distance montante (datas[0]=distance9, datas[1]=distance12, etc...)\ndef trace_means_dist(dataSet1, datas2 = None):\n means_node_1 = []\n means_node_2 = []\n yerr1 = []\n yerr2 = []\n data1 = dataSet1[0]\n data2 = dataSet1[1]\n\n dist = 6\n distance = []\n\n for serie in data1:\n means_node_1.append(mean(serie['sender_rssi']))\n yerr1.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n for serie in data2:\n means_node_2.append(mean(serie['sender_rssi']))\n yerr2.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n\n for i in range(max(len(data1), len(data2))):\n distance.append(dist)\n dist += pas_dist\n print(\"dist\", distance)\n\n if datas2 != None:\n means_node_1b = []\n means_node_2b = []\n yerr1b = []\n yerr2b = []\n data1b = datas2[0]\n data2b = datas2[1]\n for serie in data1b:\n means_node_1b.append(mean(serie['sender_rssi']))\n yerr1b.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n for serie in data2b:\n means_node_2b.append(mean(serie['sender_rssi']))\n yerr2b.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n\n plt.plot(distance, means_node_1, label='Sender 1 6m')\n plt.plot(distance, means_node_2, label='Sender 2 6m')\n plt.errorbar(distance, means_node_1, yerr=yerr1, fmt='none')\n plt.errorbar(distance, means_node_2, yerr=yerr2, fmt='none')\n if datas2 != None:\n plt.plot(ditance, means_node_1b, label='Sender 1 12m')\n plt.plot(distance, means_node_2b, label='Sender 2 12m')\n plt.errorbar(distance, means_node_1b, yerr=yerr1b, fmt='none')\n plt.errorbar(distance, means_node_2b, yerr=yerr2b, fmt='none')\n plt.xlabel('Distance (m)')\n plt.ylabel('moyenne RSSI sur 100 paquets')\n plt.legend(loc='upper left')\n plt.tight_layout()\n\n plt.show()\n\n#DO: calcule la moyenne des échantillons pour chaque expérience, et trace la courbe du rssi moyen en fonction de la puissance d'émission\n#en associant chaque donnée à une valeur de puissance\n#INPUT: Prend un tableau de tableaux d'entiers, représentant les expériences pour différentes puissanes,\n#classés par ordre de puissance montante (datas[0]=power3, datas[1]=power6, etc...)\ndef trace_means_pow(datas, datas2 = None):\n means_node_1 = []\n means_node_2 = []\n yerr1 = []\n yerr2 = []\n data1 = datas[0]\n data2 = datas[1]\n\n pow = 0\n power = []\n\n for serie in data1:\n means_node_1.append(mean(serie['sender_rssi']))\n yerr1.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n #valeur 2.3263 trouvée sur http://wwwmathlabo.univ-poitiers.fr/~phan/downloads/enseignement/tables-usuelles.pdf\n #pour alpha = 0.02\n for serie in data2:\n means_node_2.append(mean(serie['sender_rssi']))\n yerr2.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n\n for i in range(max(len(data1), len(data2))):\n power.append(pow)\n pow += pas_pow\n print(\"power\", power)\n\n if datas2 != None:\n means_node_1b = []\n means_node_2b = []\n yerr1b = []\n yerr2b = []\n data1b = datas2[0]\n data2b = datas2[1]\n for serie in data1b:\n means_node_1b.append(mean(serie['sender_rssi']))\n yerr1b.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n for serie in data2b:\n means_node_2b.append(mean(serie['sender_rssi']))\n yerr2b.append(2.3263*ecart_type(serie['sender_rssi'])/sqrt(N))\n\n plt.plot(power, means_node_1, label='Sender 1')\n plt.plot(power, means_node_2, label='Sender 2')\n plt.errorbar(power, means_node_1, yerr=yerr1, fmt='none')\n plt.errorbar(power, means_node_2, yerr=yerr2, fmt='none')\n if datas2 != None:\n plt.plot(power, means_node_1b, label='Sender 1 12m')\n plt.plot(power, means_node_2b, label='Sender 2 12m')\n plt.errorbar(power, means_node_1b, yerr=yerr1b, fmt='none')\n plt.errorbar(power, means_node_2b, yerr=yerr2b, fmt='none')\n plt.xlabel('Puissance d\\'émission (dB)')\n plt.ylabel('moyenne RSSI sur 100 paquets')\n plt.legend(loc='upper left')\n plt.tight_layout()\n\n plt.show()\n\n\nif __name__ == '__main__':\n\n dataE1 = read_data(['./data/868_E1/E1_0dB', './data/868_E1/E1_3dB', './data/868_E1/E1_6dB', './data/868_E1/E1_9dB', './data/868_E1/E1_12dB'])\n dataE2 = read_data(['./data/868_E2/E2_0dB', './data/868_E2/E2_3dB', './data/868_E2/E2_6dB', './data/868_E2/E2_9dB', './data/868_E2/E2_12dB'])\n dist24 = trace_means_pow(dataE1)\n dist12 = trace_means_pow(dataE2)\n\n print(error_rate(read_data(['./data/868_E2/E2_0dB', './data/868_E1/E1_0dB'])))\n # dist12 = read_data(['./data/E2/E22', './data/E2/E23', './data/E2/E24', './data/E2/E24'])\n # trace_means_pow(dist6, dist12)\n","sub_path":"Python/data_related_scripts/old/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":6557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"630322127","text":"\"\"\"Application testing module.\"\"\"\nimport unittest\nfrom website import create_app\nfrom flask import Flask\n\n\nclass TestApp(unittest.TestCase):\n \"\"\"Application test class.\"\"\"\n\n def setUp(self):\n \"\"\"Initialise the tests.\"\"\"\n self.app = create_app()\n\n def tearDown(self):\n \"\"\"Clean up after the tests.\"\"\"\n self.app = None\n\n def test_create_app(self):\n \"\"\"App instance initialized correctly.\"\"\"\n self.assertIsInstance(self.app, Flask)\n\n def test_create_app_config(self):\n \"\"\"Application configuration is correct.\"\"\"\n app = self.app\n database = app.config['SQLALCHEMY_DATABASE_URI']\n env = app.config['FLASK_ENV']\n secret = app.config['SECRET_KEY']\n debug = app.config['DEBUG']\n track = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']\n\n self.assertEqual(database, 'sqlite:///sqlite.db')\n self.assertEqual(env, 'development')\n self.assertEqual(secret, 's3cr3t')\n self.assertTrue(debug)\n self.assertFalse(track)\n","sub_path":"tests/app_test.py","file_name":"app_test.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"218594456","text":"from __future__ import print_function, division\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, DataLoader, random_split\nimport numpy as np\nimport torchvision\nfrom torchvision import transforms, datasets, models\nimport os\nimport cv2\nimport time\n# from model.residual_attention_network_pre import ResidualAttentionModel\n# based https://github.com/liudaizong/Residual-Attention-Network\nfrom model.residual_attention_network import ResidualAttentionModel_92_32input_update as ResidualAttentionModel\nfrom lisa_dataset import LisaDataset as lisa_dataset\n\nmodel_file = 'lisa_model_92_mixup300_normal20.pkl'\nsplit_ratio_train = 0.8\nis_train = True\nis_pretrain = False\ntrain_batch_size = 64\ntest_batch_size = 20\n\ndef mixup_data(x, y, alpha=1.0, use_cuda=True):\n '''Returns mixed inputs, pairs of targets, and lambda'''\n if alpha > 0:\n lam = np.random.beta(alpha, alpha)\n else:\n lam = 1\n\n batch_size = x.size()[0]\n if use_cuda:\n index = torch.randperm(batch_size).cuda()\n else:\n index = torch.randperm(batch_size)\n\n mixed_x = lam * x + (1 - lam) * x[index, :]\n y_a, y_b = y, y[index]\n return mixed_x, y_a, y_b, lam\n\ndef mixup_criterion(criterion, pred, y_a, y_b, lam):\n return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)\n\ndef test(model, test_loader, model_file=None):\n if model_file is not None:\n model.load_state_dict(torch.load(model_file))\n model.eval()\n\n correct = 0\n total = 0\n \n class_correct = list(0. for i in range(len(classes)))\n class_total = list(0. for i in range(len(classes)))\n\n for images, labels in test_loader:\n images = Variable(images.cuda())\n labels = Variable(labels.cuda())\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels.data).sum()\n \n c = (predicted == labels.data).squeeze()\n for i in range(len(labels.data)):\n label = labels.data[i]\n class_correct[label] += c[i].item()\n class_total[label] += 1\n\n print('Accuracy of the model on the test images: %.2f %% (%d/%d)' % (100 * float(correct) / total, correct, total))\n # print('Accuracy of the model on the test images:', float(correct)/total)\n for i in range(len(classes)):\n print('Accuracy of %5s : %.2f %% (%d/%d)' % (\n classes[i], 100 * float(class_correct[i]) / class_total[i], class_correct[i], class_total[i]))\n return float(correct) / total # compatible with Python 2.7\n\nif __name__ == '__main__':\n # Image Preprocessing\n data_transform = transforms.ToTensor()\n \n # dataset\n lisa_dataset = lisa_dataset(root = './Residual-Attention-Network/annotations/', # use root = './annotations/' for serve\n transform = data_transform)\n total_num = len(lisa_dataset)\n train_num = int(round(split_ratio_train * total_num)) # compatible with Python 2.7\n test_num = total_num - train_num\n lisa_datasets = random_split(lisa_dataset, [ train_num, test_num ])\n train_dataset = lisa_datasets[0]\n test_dataset = lisa_datasets[1]\n\n # Data Loader (Input Pipeline)\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset, \n batch_size=train_batch_size, \n shuffle=True, \n num_workers=8)\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset, \n batch_size=test_batch_size, \n shuffle=False)\n\n classes = list(lisa_dataset.categories.keys())\n model = ResidualAttentionModel().cuda()\n print(model)\n\n is_mixup = True\n lr = 0.1 # 0.1\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, nesterov=True, weight_decay=0.0001)\n acc_best = 0\n total_epoch = 320\n if is_train is True:\n if is_pretrain is True:\n model.load_state_dict((torch.load(model_file)))\n # Training\n for epoch in range(total_epoch):\n print(\"Epoch [%d/%d]:\" % (epoch+1, total_epoch))\n if epoch > 300:\n is_mixup = False\n else:\n is_mixup = True\n model.train()\n tims = time.time()\n for i, (images, labels) in enumerate(train_loader):\n if is_mixup:\n inputs, targets_a, targets_b, lam = mixup_data(images.cuda(), labels.cuda(), alpha=1.0)\n inputs, targets_a, targets_b = map(Variable, (inputs, targets_a, targets_b))\n outputs = model(inputs)\n optimizer.zero_grad()\n loss = mixup_criterion(criterion, outputs, targets_a, targets_b, lam)\n loss.backward()\n optimizer.step()\n else:\n images = Variable(images.cuda())\n # print(images.data)\n labels = Variable(labels.cuda())\n # Forward + Backward + Optimize\n optimizer.zero_grad()\n outputs = model(images)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n if (i+1) % 10 == 0 or (i+1) == len(train_loader) or i == 0:\n print(\"Epoch [%d/%d], Iter [%d/%d] Loss: %.4f\" %(epoch+1, total_epoch, i+1, len(train_loader), loss.data))\n print('the epoch takes time:',time.time() - tims)\n print('evaluate test set:')\n acc = test(model, test_loader)\n if acc > acc_best:\n acc_best = acc\n print('current best acc,', acc_best)\n torch.save(model.state_dict(), model_file)\n # Decaying Learning Rate\n if (epoch+1) / float(total_epoch) == 0.3 or (epoch+1) / float(total_epoch) == 0.6 or (epoch+1) / float(total_epoch) == 0.9:\n lr /= 10\n print('reset learning rate to:', lr)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n print(param_group['lr'])\n #optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n #optim.SGD(model.parameters(), lr=lr, momentum=0.9, nesterov=True, weight_decay=0.0001)\n\n # Save the Model (epoch==320)\n #torch.save(model.state_dict(), model_file)\n\n # After training test\n print('Training Completed.')\n print('The best accuracy is %.2f %%' % (100 * float(acc_best)))\n\n # model.load_state_dict(torch.load(model_file))\n print('The best accuracy of the model on the train set:')\n test(model, train_loader, model_file)\n print('The best accuracy of the model on the test set:')\n test(model, test_loader, model_file)\n\n else: # is_train is False\n test(model, test_loader, model_file)\n","sub_path":"Residual-Attention-Network/lisa_process.py","file_name":"lisa_process.py","file_ext":"py","file_size_in_byte":7162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"7347953","text":"infile = 'input.in'\n\nlines = [line.rstrip('\\n') for line in open(infile, 'r')]\n\nT = int(lines[0])\nout = None\n\nteststart = 1\nlinespercase = 0\n\n\nfor t in range(1, T + 1):\n\n\ttestcase = lines[t] #list(map(int, lines[t].split(' ')))\n\n\tN = int(lines[teststart])\n\tlinespercase = 2*N\n\n\td = dict()\n\tmissing = []\n\n\tfor n in range(1, linespercase):\n\t\t\n\t\th = [int(x) for x in lines[teststart+n].split(' ')]\n\t\t\n\t\tfor x in h:\n\t\t\tif x not in d:\n\t\t\t\td[x] = 1\n\t\t\telse:\n\t\t\t\td[x] += 1\n\n\n\tfor k in d:\n\t\tif d[k]%2 != 0:\n\t\t\tmissing.append(k)\n\n\tmissing.sort()\n\n\tout = ' '.join(str(x) for x in missing)\n\n\n\n\n\tteststart += linespercase\n\n\n\tprint('Case #{case}: {out}'.format(case=t, out=out))","sub_path":"codes/CodeJamCrawler/16_1_2_neat/16_1_2_vpolisky_codejam1B.py","file_name":"16_1_2_vpolisky_codejam1B.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"527340740","text":"from django.urls import path\nfrom .apiviews import *\n\napp_name = 'polls'\nurlpatterns = [\n # Регистрация пользователя\n path(\"users/\", UserCreate.as_view(), name=\"user_create\"),\n # Получение токена пользователем\n path(\"login/\", LoginView.as_view(), name=\"login\"),\n # Создание опроса\n path('poll/create/', PollCreate.as_view(), name='poll_create'),\n # Редактирование конкретного опроса\n path('poll/update//', PollUpdate.as_view(), name='poll_update'),\n # Удаление конкретного опроса\n path('poll/delete//', PollDelete.as_view(), name='poll_delete'),\n # Просмотр всех опросов\n path('poll/view/', PollView.as_view(), name='polls_view'),\n # Отображение только активных опросов\n path('poll/view/active/', PollActiveView.as_view(), name='active_poll_view'),\n # Создание вопроса\n path('question/create/', QuestionCreate.as_view(), name='question_create'),\n # Редактирование конкретного вопроса\n path('question/update//', QuestionUpdate.as_view(), name='question_update'),\n # Удаление конкретного вопроса\n path('question/delete//', QuestionDelete.as_view(), name='poll_delete'),\n # Создание варианта ответа\n path('choice/create/', ChoiceCreate.as_view(), name='choice_create'),\n # Редактирование конкретного варианта ответа\n path('choice/update//', ChoiceUpdate.as_view(), name='choice_update'),\n # Удаление конкретного варианта ответа\n path('choice/delete//', ChoiceDelete.as_view(), name='choice_delete'),\n # Создание ответа на вопрос. Если пользователь авторизован, то сохраняется ID пользователя.\n # Если пользователь неавторизован, то полю ID задается значение None\n path('answer/create/', AnswerCreate.as_view(), name='answer_create'),\n # Просмотр всех ответов\n path('answer/view/', AnswerView.as_view(), name='answer_view'),\n # Просмотр ответов конкретного пользователя\n path('answer/view//', AnswerViewById.as_view(), name='answer_view'),\n]","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"645864981","text":"#-*- coding: UTF-8 -*-#\n#\n#*******************************************************************************\n# apwds_1.3.10.py\n#\n# Author: zhangjxp\n#\n# Version 1.0.0\n#\n# Copyright (c) 2004-2012 Digital China Networks Co. Ltd\n#\n# Features:\n# 1.3.10\tOpen方式下,satelliteap的vap0与rootap的vapx建立wds\n#\n#*******************************************************************************\n# Change log:\n# - created by zhangjxp 2018.1.25\n#*******************************************************************************\n\n#Package\n\n#Global Definition\n\n#Source files\n\n#Procedure Definition \n\n#Functional Code\n\ntestname = 'TestCase apwds_1.3.10'\navoiderror(testname)\nprintTimer(testname,'Start','Use vap0 of satelliteap and vapx of rootap to establish wds link')\n###############################################################################\n#Step 1\n#操作\n# AP2上进行open模式的WDS配置\n# set wds wds0 wds-mode satelliteap\n# set wds wds0 wds-ssid ${wds_ssid} \n# set wds wds0 remote-mac ap1mac_network2 \n# set wds wds0 wds-security-policy plain-text \n# set wds wds0 wds-status up\n# AC上在network2 配置wds并下发给ap1\n# network 2 \n# wds-mode rootap \n# security mode none \n# wds-remote-vap ap2mac \n# ssid ${wds_ssid}\n#预期\n# 配置成功\n################################################################################\nprintStep(testname,'Step 1','AP2 config wds0 as open mode',\\\n 'Config wds in network 2 on AC1',\\\n 'Apply ap profile 1')\nres1=1\n#operate\n# AP2上配置wds0,mode为satelliteap\nAp_openwds_config(ap2,Ap2cmdtype,\n wds0num,\n ssid=wds_ssid,\n remotemac=ap1mac_type1_network2)\n# AC上配置network2为wds,apmode为rootap,并下发profile 1\nAc_wds_config(switch1,2,\n ssid=wds_ssid,\n remotemac=ap2vapmac)\nres1=WirelessApplyProfileWithCheck(switch1,['1'],[ap1mac])\n#result\nprintCheckStep(testname, 'Step 1',res1)\n\n################################################################################\n#Step 2\n#操作\n#检查AC1是否成功管理AP2,WDS连接是否建立\n#预期\n#AC1 上show wireless ap status可以看到AP2被成功管理\n# AC1上show wireless wds link status可以看到AP1和AP2建立起wds连接\n################################################################################\n\nprintStep(testname,'Step 2',\\\n 'Check WDS is linked and AC1 managed ap2 successfully')\nres1=res2=1\n#operate\nres1 = CheckSutCmd(switch1,'show wireless ap status', \\\n check=[(ap2mac,'Managed','Success')], \\\n retry=40,interval=5,waitflag=False,IC=True)\nres2 = CheckSutCmd(switch1,'show wireless wds link status', \\\n check=[(ap1mac,radionum,'1',ap2mac,radionum,'0','Managed','Managed','Connected')], \\\n waittime=5,retry=5,interval=1,IC=True) \n#result\nprintCheckStep(testname, 'Step 2',res1,res2)\n\n################################################################################\n#Step 3\n#操作\n#恢复默认配置\n################################################################################\nprintStep(testname,'Step 3',\\\n 'Recover initial config for switches.')\n\n#operate\n# 恢复network2配置\nClearNetworkConfig(switch1,2)\nWirelessApplyProfileWithCheck(switch1,['1'],[ap1mac])\n# 恢复AP2初始化配置\nRebootAp(connectTime=1,setdefaut=True,AP=ap2,apcmdtype=Ap2cmdtype)\nInitial_ap2()\n#end\nprintTimer(testname, 'End')","sub_path":"autoTests/module/apwds/apwds_1.3.10.py","file_name":"apwds_1.3.10.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"256742887","text":"\ndef run(l, n) :\n\t\n\tif len(l) < n :\n\t\t\n\t\tn = n - len(l)\n\t\n\tfor i in range(-1, -n-1, -1) :\n\t\t\n\t\tnew = l.pop()\n\t\t\n\t\tl.insert(0, new)\n\t\t\n\t\t\n# funcion que aplana una lista qje tiene sublistas\t\t\nl = [[1, 2, [40, 50, [60, 70]]], 8, [3, 4, [7, 10]]]\n\n\ndef listaplana(l) :\n\t\n\tplana = []\n\t\n\tfor el in l :\n\t\t\n\t\tif type(el) != list :\n\t\t\t\n\t\t\tplana.append(el)\n\t\t\t\n\t\telse :\n\t\t\t\n\t\t\t\n\t\t\tp = listaplana(el)\n\t\t\tplana += p\n\t\t\t\n\t\t\t\t\t\t\n\treturn plana\n\n\t\n\n\t\t\t\n\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n#Funcion Que borra los elementos repetidos de una lista\t\t\t\ndef delRepeat(l) :\n\t\t\t\n\t\tfor i in list(l) :\n\t\t\t\n\t\t\twhile l.count(i) != 1 :\n\t\t\t\t\n\t\t\t\t\tl.remove(i)\n\t\t\t\t\t\t\n\t\t\t\n\n\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\ndef fun(n) :\n\t\n\t#global a\n\t#print(a)\n\t\n\ta = []\n\t\n\tfor i in range(2) :\n\t\t#print(a)\n\t\n\t\tif n :\n\t\t\t\n\t\t\ta.append(i+n)\n\t\t\t\n\t\t\t\n\t\telse :\n\t\t\ta = a + fun(1)\n\t\t\t\n\t\t\n\t\t\n\treturn a\t\n\t\n\n\n\ndef a_matriz(l, sublist = 2) :\t\n\tif sublist == 0 :\n\t\t\n\t\treturn l\n\t\t\n\tsubs = len(l) % sublist\n\ta = len(l) // sublist\n\n\tmatriz = [ ]\n\t\n\tif (subs == 0) :\n\t\t\n\t\tfor i in range(0, len(l), a) :\n\t\t\t\n\t\t\tmatriz.append(l[i:i+a])\n\t\t\t\n\t\treturn matriz\n\t\t\t\t\n\telse :\n\t\t\n\t\treturn \"No Pueden Haber sublustas de tal tamaño\"\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\ndef types(l) :\n\t\t\n\t\tlista = [ ]\n\t\t\n\t\tfor i in l :\n\t\t\t\n\t\t\tif str(type(i)) in lista :\n\t\t\t\t\n\t\t\t\tcontinue\n\t\t\t\t\n\t\t\tlista.append(str(type(i)))\n\t\t\n\t\treturn lista, len(lista)\n\t\t\n\t\t\n\n\t\t\t\t\nb = [1, 2, 1, 1, \"A\", \"C\", \"D\", \"B\", True, 2+0j]\n\ns = \"\\n\"\nl = [3, 6, 3+0j, \"A\", 3.5, 8, True]\ntipos, cant = types(l)\nprint(f\"Hay {cant} tipos de datos y son :\\n{s.join(tipos)}\")\n\t\t\t\n\t\t\t","sub_path":"works_Telegram/funcionesMedias.py","file_name":"funcionesMedias.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"449742498","text":"import nltk\nimport numpy as np\nimport json\nfrom collections import defaultdict\nimport xml.etree.ElementTree as ET\nimport random\nrandom.seed(1337)\nnp.random.seed(1337)\n\n\"\"\"TODO: this file is not well-tested but just copied from another repository.\n\"\"\"\n\nvalid_split=150\ntrain_rate = 0.8\nvalid_rate = 0.1\ntest_rate = 0.1\n\npolar_idx={'+': 0,'positive': 0, '-': 1, 'negative': 1, 'neutral': 2}\nidx_polar={0: 'positive', 1: 'negative', 2: 'neutral'}\n\ndef parse_Bing(fn):\n id=0\n corpus = []\n with open(fn,'r') as review_file:\n reviews = review_file.readlines()\n for review in reviews:\n review = review.lower()\n opins=set()\n if review[:2] != '##' and '##' in review and '[' in review and \\\n ('+' in review.split('##')[0] or '-' in review.split('##')[0]):\n print(review.split('##')[0])\n current_sentence = review.split('##')[1][:-1].replace('\\t',' ')\n #aspects: may be more than one\n aspect_str = review.split('##')[0]\n if ',' in aspect_str:\n aspect_all = aspect_str.split(',')\n for each_aspect in aspect_all:\n current_aspect = each_aspect.split('[')[0]\n opins.add((current_aspect))\n\n elif ',' not in aspect_str:\n current_aspect = aspect_str.split('[')[0]\n opins.add((current_aspect))\n\n tokens=nltk.word_tokenize(current_sentence)\n lb = [\"O\"]*len(tokens)\n\n print('opins: ',opins)\n\n for ix, opin in enumerate(opins):\n aspects_tokens=nltk.word_tokenize(opin)\n if aspects_tokens[0] in tokens:\n for aspect_idx in range(len(aspects_tokens)):\n aspect_index = aspect_index_in_tokens(tokens,aspects_tokens)\n if aspect_index == False: break # discard this instance\n if aspect_idx == 0:\n lb[aspect_index+aspect_idx]='B'\n else:\n lb[aspect_index+aspect_idx]='I'\n\n corpus.append({\"id\": id, \"tokens\": tokens, \"labels\": lb})\n id+=1\n return corpus\n\ndef aspect_index_in_tokens(tokens,aspects_tokens):\n\n candidate_index = 0\n last_index = 0\n\n print('tokens: ',tokens)\n print('aspects_tokens: ',aspects_tokens)\n\n while True:\n valid = True\n\n #if the aspecit is not in the sentence, we discard this instance\n if aspects_tokens[0] not in tokens[last_index:]:\n print('not in')\n return False\n\n candidate_index =tokens[last_index:].index(aspects_tokens[0])\n\n # print('candidate_index: ',candidate_index)\n #but we need to test whether it is a valid one --- we want phrase matching\n for phrase_index in range(len(aspects_tokens)):\n if tokens[last_index+candidate_index+phrase_index] != aspects_tokens[phrase_index]:\n last_index += candidate_index +1 # all after current candidate\n valid = False\n break\n\n if valid == True: break # all correct\n\n return last_index+candidate_index\n\ndomains = ['CanonPowerShotSD500','CanonS100','DiaperChamp','HitachiRouter','ipod', \\\n 'LinksysRouter','MicroMP3','Nokia6600','Norton']\nfor domain in domains:\n train_corpus=parse_Bing('./data/absa/Bing9Domains/'+domain+'.txt')\n print('train_corpus: ',len(train_corpus))\n with open(\"./dat/absa/Bing9Domains/ae/\"+domain+\"/train.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[:int(len(train_corpus)*train_rate)] }, fw, sort_keys=True, indent=4)\n with open(\"./dat/absa/Bing9Domains/ae/\"+domain+\"/dev.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[int(len(train_corpus)*train_rate):int(len(train_corpus)*(train_rate+valid_rate))] }, fw, sort_keys=True, indent=4)\n with open(\"./dat/absa/Bing9Domains/ae/\"+domain+\"/test.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[int(len(train_corpus)*(train_rate+valid_rate)):] }, fw, sort_keys=True, indent=4)\n\n\ndomains = ['Nokia6610','NikonCoolpix4300','CreativeLabsNomadJukeboxZenXtra40GB','CanonG3','ApexAD2600Progressive']\nfor domain in domains:\n train_corpus=parse_Bing('./data/absa/Bing5Domains/'+domain+'.txt')\n with open(\"./dat/absa/Bing5Domains/ae/\"+domain+\"/train.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[:int(len(train_corpus)*train_rate)] }, fw, sort_keys=True, indent=4)\n with open(\"./dat/absa/Bing5Domains/ae/\"+domain+\"/dev.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[int(len(train_corpus)*train_rate):int(len(train_corpus)*(train_rate+valid_rate))] }, fw, sort_keys=True, indent=4)\n with open(\"./dat/absa/Bing5Domains/ae/\"+domain+\"/test.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[int(len(train_corpus)*(train_rate+valid_rate)):] }, fw, sort_keys=True, indent=4)\n\ndomains = ['Speaker','Router','Computer']\nfor domain in domains:\n train_corpus=parse_Bing('./data/absa/Bing3Domains/'+domain+'.txt')\n with open(\"./dat/absa/Bing3Domains/ae/\"+domain+\"/train.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[:int(len(train_corpus)*train_rate)] }, fw, sort_keys=True, indent=4)\n with open(\"./dat/absa/Bing3Domains/ae/\"+domain+\"/dev.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[int(len(train_corpus)*train_rate):int(len(train_corpus)*(train_rate+valid_rate))] }, fw, sort_keys=True, indent=4)\n with open(\"./dat/absa/Bing3Domains/ae/\"+domain+\"/test.json\", \"w\") as fw:\n json.dump({rec[\"id\"]: rec for rec in train_corpus[int(len(train_corpus)*(train_rate+valid_rate)):] }, fw, sort_keys=True, indent=4)\n","sub_path":"src/tools/prep_ae.py","file_name":"prep_ae.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"125983652","text":"class Car:\n def __init__(self, price, speed, fuel, mileage):\n self.price = price\n self.speed = speed\n self.fuel = fuel\n self.mileage = mileage \n self.tax = 0.12\n\n def display_all(self):\n if self.price > 10000:\n self.tax = 0.15\n return(f\"Price: {self.price}\\nSpeed: {self.speed}\\nFuel: {self.fuel}\\nMileage: {self.mileage}\\nTax: {self.tax}\\n\")\n \ncar1 = Car(2000,\"35 mph\",\"Full\",\"15 mpg\")\ncar2 = Car(2000,\"5mph\",\"Not Full\",\"105 mpg\")\ncar3 = Car(2000,\"15mph\",\"Kind of Full\",\"95 mpg\")\ncar4 = Car(2000,\"25mph\",\"Full\",\"25 mpg\")\ncar5 = Car(2000,\"45mph\",\"Empty\",\"25 mpg\")\ncar6 = Car(20000000,\"35mph\",\"Empty\",\"15 mpg\")\n\nprint(car1.display_all())\nprint(car2.display_all())\nprint(car3.display_all())\nprint(car4.display_all())\nprint(car5.display_all())\nprint(car6.display_all())\n","sub_path":"Python/python_OOP/car/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"555899746","text":"import copy, math, random, json\nimport numpy as np\nimport networkx as nx\nfrom .CPPNActivationFunctions import *\n\nactivation_functions = [np.sin, np.abs, neg_abs, np.square, neg_square, sqrt_abs, neg_sqrt_abs]\nactivation_name_to_fn = {}\nfor fn in activation_functions:\n activation_name_to_fn[fn.__name__] = fn\n\n\"\"\"\nfor ALife paper, use (0: empty, 1: passiveSoft, 2: passiveHard, 3: active+, 4:active-)\nshape: 0 or other\nmuscleOrTissue: 1/2 or 3/4\ntissueType: 1 or 2\nmuscleType: 3 or 4\nphaseoffset: not used.\n\"\"\"\n\nclass CPPN:\n input_node_names = ['x', 'y', 'z', 'd', 'b']\n # do resolution, no need. # output_node_names = ['body', 'phaseoffset','bone_proportion']\n output_node_names = ['body', 'shape', 'muscleOrTissue', 'tissueType', 'muscleType', 'phaseoffset']\n def __init__(self):\n # There are many differences between networkx 1.x and 2.x, we'll use 2.x\n assert float(nx.__version__)>2.0\n self.hidden_node_names = []\n self.mutate_history = []\n\n def init(self, hidden_layers, weight_mutation_std):\n self.hidden_layers = hidden_layers\n self.weight_mutation_std = weight_mutation_std\n self.init_graph()\n\n def clone(self):\n ret = copy.copy(self)\n ret.graph = self.graph.copy()\n ret.mutate_history = self.mutate_history.copy()\n return ret\n\n def __str__(self):\n return self.dumps()\n \n def dumps(self):\n \"\"\" Serierize CPPN class. Save all the graph into vxd file, so that we can load from a vxd later. \"\"\"\n ret = {}\n ret[\"input_node_names\"] = self.input_node_names\n ret[\"output_node_names\"] = self.output_node_names\n ret[\"hidden_node_names\"] = self.hidden_node_names\n ret[\"hidden_layers\"] = self.hidden_layers\n ret[\"mutate_history\"] = self.mutate_history\n weights = {}\n activation = {}\n\n for node1,node2 in self.graph.edges:\n weights[f\"{node1}__{node2}\"] = self.graph.edges[node1, node2][\"weight\"]\n \n for name in self.hidden_node_names:\n activation[name] = self.graph.nodes[name][\"function\"].__name__\n\n ret[\"weights\"] = weights\n ret[\"activation\"] = activation\n return json.dumps(ret)\n\n def loads(self, s):\n \"\"\" Load class from a string, which is probably stored in a vxd. \"\"\"\n obj = json.loads(s)\n self.input_node_names = obj[\"input_node_names\"]\n self.output_node_names = obj[\"output_node_names\"]\n self.hidden_node_names = obj[\"hidden_node_names\"]\n self.hidden_layers = obj[\"hidden_layers\"]\n self.mutate_history = obj[\"mutate_history\"]\n self.init_graph()\n for name in obj[\"activation\"]:\n fn = obj[\"activation\"][name]\n self.graph.add_node(name, function=activation_name_to_fn[fn])\n for str_names in obj[\"weights\"]:\n weight = obj[\"weights\"][str_names]\n node1, node2 = str_names.split(\"__\")\n self.graph.add_edge(node1, node2, weight=weight)\n\n def init_graph(self):\n \"\"\"Create a simple graph with each input attached to each output\"\"\"\n self.graph = nx.DiGraph()\n\n nodes_this_layer = []\n for name in self.input_node_names:\n self.graph.add_node(name, type=\"input\", function=None)\n nodes_this_layer.append(name)\n\n for layer_id, layer in enumerate(self.hidden_layers):\n nodes_last_layer = nodes_this_layer\n nodes_this_layer = []\n for node in range(layer):\n name = f\"hidden_{layer_id}_{node}\"\n self.graph.add_node(name, type=\"hidden\", function=random.choice(activation_functions))\n for last in nodes_last_layer:\n self.graph.add_edge(last, name, weight=random.random())\n nodes_this_layer.append(name)\n self.hidden_node_names.append(name)\n\n nodes_last_layer = nodes_this_layer\n nodes_this_layer = []\n for name in self.output_node_names:\n self.graph.add_node(name, type=\"output\", function=sigmoid)\n for last in nodes_last_layer:\n self.graph.add_edge(last, name, weight=random.random())\n nodes_this_layer.append(name)\n\n def _compute_value(self, node, input_data):\n if self.graph.nodes[node][\"evaluated\"]:\n return self.graph.nodes[node][\"value\"]\n if node in input_data:\n return input_data[node]\n predecessors = self.graph.predecessors(node)\n value = 0.0\n for predecessor in predecessors:\n edge = self.graph.get_edge_data(predecessor, node)\n value += self._compute_value(predecessor,input_data) * edge[\"weight\"]\n if self.graph.nodes[node][\"function\"] is not None:\n value = self.graph.nodes[node][\"function\"](value)\n self.graph.nodes[node][\"value\"] = value\n self.graph.nodes[node][\"evaluated\"] = True\n return value\n\n def compute(self, input_data):\n \"\"\" return a dictionary, key is the output nodes, value is the output value \"\"\"\n # for node in self.output_node_names:\n for node in self.graph.nodes:\n self.graph.nodes[node][\"evaluated\"] = False\n ret = {}\n for node in self.output_node_names:\n ret[node] = self._compute_value(node, input_data)\n return ret\n\n def draw(self):\n import matplotlib.pyplot as plt\n nx.draw_networkx(self.graph, pos=nx.drawing.nx_pydot.graphviz_layout(self.graph, prog='dot'))\n edge_labels_1 = nx.get_edge_attributes(self.graph,'weight')\n for key in edge_labels_1:\n edge_labels_1[key] = round(edge_labels_1[key],2)\n nx.draw_networkx_edge_labels(self.graph, pos=nx.drawing.nx_pydot.graphviz_layout(self.graph, prog='dot'), edge_labels=edge_labels_1, rotate=False)\n plt.show()\n\n def mutate(self, num_random_activation_functions=1, num_random_weight_changes=5):\n # for _ in range(num_random_activation_functions):\n # self.change_activation()\n # for _ in range(num_random_weight_changes):\n # self.change_weight()\n # return\n total = num_random_activation_functions + num_random_weight_changes\n # choose a mutation according to probability\n while True:\n fn = np.random.choice( [\n self.change_activation,\n self.change_weight,\n ], size=1, p=[\n num_random_activation_functions / total,\n num_random_weight_changes / total,\n ] )\n # print(fn[0])\n success = fn[0]()\n if success!=\"\":\n break\n print(\"Retry.\")\n self.mutate_history.append(success)\n\n def change_activation(self):\n if len(self.hidden_node_names)==0:\n return \"\"\n node = random.choice(self.hidden_node_names)\n success = \"\"\n for i in range(10):\n activation = random.choice(activation_functions)\n if self.graph.nodes[node][\"function\"] != activation:\n old_function = self.graph.nodes[node][\"function\"].__name__\n self.graph.nodes[node][\"function\"]=activation\n success = f\"({node}) Fn [{old_function}] to [{activation.__name__}].\"\n break\n return success\n\n def change_weight(self):\n edge = random.choice(list(self.graph.edges))\n old_weight = self.graph.edges[edge[0], edge[1]][\"weight\"]\n self.graph.edges[edge[0], edge[1]][\"weight\"] = np.random.normal(loc=self.graph.edges[edge[0], edge[1]][\"weight\"], scale=self.weight_mutation_std)\n return f\"({edge[0]}__{edge[1]}) wt [{old_weight}] to [{self.graph.edges[edge[0], edge[1]]['weight']}].\"\n\n def get_output(self,body_dimension):\n input_x = np.zeros(body_dimension)\n input_y = np.zeros(body_dimension)\n input_z = np.zeros(body_dimension)\n\n for i in range(body_dimension[0]):\n x = i*2/body_dimension[0] - 1\n for j in range(body_dimension[1]):\n y = j*2/body_dimension[1] - 1\n for k in range(body_dimension[2]):\n z = k*2/body_dimension[2] - 1\n input_x[i,j,k] = x\n input_y[i,j,k] = y\n input_z[i,j,k] = z\n\n input_d = np.sqrt(np.power(input_x,2) + np.power(input_y,2) + np.power(input_z,2) )\n ret = self.compute({'x':input_x,'y':input_y,'z':input_z,'d':input_d,'b':1})\n return ret\n","sub_path":"voxelyze/evolution/cppn_alife/CPPN.py","file_name":"CPPN.py","file_ext":"py","file_size_in_byte":8525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"392015130","text":"import broadbean as bb\nramp = bb.PulseAtoms.ramp\n\nfrom qcodes.utils.validators import Ints, Numbers, Lists, Dict\nfrom qcodes.instrument.base import Instrument\n\nimport numpy as np\n\nimport time\n\n\"\"\"\nKnown issues:\n1. capture_2d_trace was not intended to be used with single_point mode. It kind-of\n works but with a number of bugs. In some situations it may still be most efficient\n way of measuring, even if it fails sometimes. \n e.g. capture_2d_trace moves returns the num_sweeps_2d-1 first traces from\n the current acquisition and a last trace from the frevious acquisition.\n Consequently MidasMdacAwg1DFastRasterer now uses repeated capture_1d_trace\n and requires midas_buffer_flushing_time > 10 ms\n Meanwhile MidasMdacAwg1DRasterer often show artifacts.\n Firmware version: midas_release_v1_03_085.hex\n2. Related to previous (probably). Max samples per pixel for 2D raster\n is 128. I think it is because of some data offset by 128 points\n which you start seeing when numper of triggers per ramp exceeds 128.\nSearch for WORKAROUND for places when the tweaks were made to work around\nthe issues\n\nOther comments:\n 1. For simplicity the code allows the resolution and averging to\n set to values 2^N.\n\"\"\"\n\nclass MidasMdacAwgParentRasterer(Instrument):\n \"\"\"\n Parent class to the 1DSlow, 1DFast and 2D rasterers\n \"\"\"\n\n def __init__(self, name, MIDAS_name, MDAC_name, AWG_name, **kwargs):\n \"\"\"\n Create a MidasMdacAwgRasterer instance\n\n Args:\n name (str): rasterer instrument name\n MIDAS_name (str): name of the Midas to be used\n MDAC_name (str): name of the MDAC to be used\n AWG_name (str): name of the Tektronix 5014 to be used\n **kwargs: other kwargs passed to Instrument init\n\n Returns:\n MidasMdacAwgRasterer\n \"\"\"\n\n super().__init__(name, **kwargs)\n\n self.SAMPLE_TIME = (1/1.8e9)*512 # 284.44 ns\n self.POINTS_PER_BUFFER = 2048\n\n self.MIDAS = self.find_instrument(MIDAS_name)\n self.MDAC = self.find_instrument(MDAC_name)\n self.AWG = self.find_instrument(AWG_name)\n\n self.add_parameter('AWG_channel',\n set_cmd=None,\n initial_value=1,\n vals=Ints(min_value=1,max_value=4),\n docstring=\"Channel of AWG used to apply\"\n \" a sawtooth\")\n\n self.add_parameter('AWG_trigger_channel',\n set_cmd=None,\n initial_value=1,\n vals=Ints(min_value=1,max_value=4),\n docstring=\"Channel of AWG used to apply\"\n \" generate a trigger for Midas.\")\n\n self.add_parameter('MIDAS_channel_specs',\n set_cmd=None,\n initial_value={1:'IQ'},\n docstring=\"Dictionary specyfying quantities to\"\n \" measure. Keys are the cjannel numbers (int).\"\n \" Valuses are strings, up to 4 letters from\"\n \" the set I, Q, A, P which stand for\"\n \" (I, Q, Amplitude or Phase).\")\n\n self.add_parameter('samples_per_pixel',\n set_cmd=None,\n initial_value=32,\n vals=Ints(1,2**15),\n docstring=\"Number of 284.44 ns-long samples to\"\n \" be averaged to get a single data pixel.\"\n \" Must be a power of 2.\")\n\n self.add_parameter('midas_retriggering_time',\n set_cmd=None,\n initial_value=100e-9,\n vals=Numbers(1e-9, 1e-3),\n docstring=\"Additional waiting time to let\"\n \" the Midas ready to acquire next sample\")\n\n self.add_parameter('midas_buffer_flushing_time',\n set_cmd=None,\n initial_value=2e-3,\n vals=Numbers(10e-6, 100e-3),\n docstring=\"Additional waiting time to let\"\n \" the Midas flush the buffer\"\n \" and get ready for more triggers\")\n\n self.add_parameter('pre_wait',\n set_cmd=None,\n initial_value=1e-6,\n vals=Numbers(min_value=0, max_value=0.1),\n docstring=\"Duration of the 'wait' segment in the\"\n \" applied sequence of sawtooths. It's purpose is to\"\n \" ensure that MDAC sweep starts synchronously with\"\n \" the Midas acquisition.\")\n\n # only gettable\n self.add_parameter('MIDAS_channels',\n get_cmd=self._get_MIDAS_channels,\n docstring=\"List of Midas channels to return\")\n\n ################### Get functions ###################\n def _get_MIDAS_channels(self):\n return list(self.MIDAS_channel_specs().keys())\n\n ################### Conversion functions ###################\n\n def samples_to_time(self, samples):\n return samples*self.SAMPLE_TIME\n\n def time_to_samples(self, tim, round_down=True):\n if round_down:\n return int(tim/self.SAMPLE_TIME)\n else:\n return tim/self.SAMPLE_TIME\n\n ################### Other functions ###################\n\n def prepare_AWG(self):\n \"\"\"\n Orepares and uploades a needed sequence\n to Tektronix 5014.\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def prepare_MIDAS(self):\n \"\"\"\n Sets up the MIDAS to do the acquisition.\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def prepare_MDAC(self):\n \"\"\"\n Sets up the MDAC to do the acquisition.\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def fn_start(self):\n \"\"\"\n This function will be exectued by\n MIDAS.captire_[...] just before the acquisition.\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def fn_stop(self):\n \"\"\"\n This function will be exectued by\n MIDAS.captire_[...] just after the acquisition.\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def do_acquisition(self):\n \"\"\"\n Executes a MIDAS capture method\n and returns an ndarray with the data.\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def reshape(self):\n \"\"\"\n Reshapes and performs required averaging\n of the data returned by do_acquisition()\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def get_measurement_range(self):\n \"\"\"\n Returns arrays with voltage ranges\n corresponding to the data.\n Should be implemented in a subclass.\n \"\"\"\n raise NotImplementedError(\n 'This method should be implemented in a subclass')\n\n def AWG_channels_on(self):\n self.AWG.ch1_state(1)\n self.AWG.ch2_state(1)\n self.AWG.ch3_state(1)\n self.AWG.ch4_state(1)\n\n def AWG_channels_off(self):\n self.AWG.ch1_state(0)\n self.AWG.ch2_state(0)\n self.AWG.ch3_state(0)\n self.AWG.ch4_state(0)\n\n def prepare_for_acquisition(self):\n self.prepare_AWG()\n self.AWG_channels_on()\n self.prepare_MIDAS()\n self.prepare_MDAC()\n\n def arm_for_acquisition(self):\n self.AWG.stop()\n self.AWG.start()\n\n def arm_acquire_reshape(self):\n self.arm_for_acquisition()\n time.sleep(1e-3)\n data = self.do_acquisition()\n self.data_raw = data\n # return data\n data = self.reshape(data)\n # pick selected MIDAS channels\n self.data = []\n for ch, quadratures in self.MIDAS_channel_specs().items():\n d = data[ch-1]\n phase_offset = self.MIDAS.channels[ch-1].phase_offset()\n for q in quadratures:\n self.data.append(get_quadrature(d, q, phase_offset))\n return np.array(self.data)\n\n##################################################################\n######################## 1D MDAC rasterer ########################\n##################################################################\n\nclass MidasMdacAwg1DSlowRasterer(MidasMdacAwgParentRasterer):\n def __init__(self, name, MIDAS_name, MDAC_name, AWG_name, **kwargs):\n \"\"\"\n How to use:\n 1. Configure Midas channels\n 2. Create a rasterer object:\n >>> rSlow = rast.MidasMdacAwg1DSlowRasterer('rSlow',\n midas.name, mdac.name, AWG.name)\n 3. Set up the MDAC channel, voltage range, averaging\n and resolution:\n >>> rSlow.MDAC_channel(1)\n >>> rSlow.MDAC_Vpp(0.1)\n >>> rSlow.samples_per_pixel(512)\n >>> rSlow.pixels(128)\n 4. Run routines to automatically configure AWG and Midas:\n >>> rSlow.prepare_AWG()\n >>> rSlow.AWG_channels_on()\n >>> rSlow.prepare_MIDAS()\n 5. Measure:\n >>> data = rSlow.arm_acquire_reshape()\n After acquisition the MDAC channel voltage is set to\n the value from the beginning of the measurement.\n 6. \"data\" is an (8 x pixels) array with the obtained data\n At this time no scaling of the sweeped axis is provided.\n The MDAC sweeps the voltage from Vmdac-MDAC_Vpp/2\n to Vmdac+MDAC_Vpp/2, where Vmdac is the channel setting\n at the moment arm_acquire_reshape method is executed.\n 7. Investigate the data to verify if the MDAC sweep\n is synchronized with the AWG. If needed, adjust\n pre_wait parameter and repeat points 4-6\n 8. Executing 4 between measurements is only required\n if you changed any of the following parameters:\n - AWG_channel\n - samples_per_pixel\n - midas_retriggering_time\n - pre_wait\n - pixels\n - AWG parameters\n Executing 4 is NOT required if you change:\n - MDAC_channel\n - MDAC_Vpp\n - MDAC_divider\n - MIDAS_channels\n - Midas channel parameters\n \"\"\"\n\n super().__init__(name,\n MIDAS_name, MDAC_name, AWG_name,\n **kwargs)\n\n self.add_parameter('MDAC_channel',\n set_cmd=None,\n initial_value=None,\n vals=Ints(min_value=1,max_value=64),\n docstring=\"MDAC channels to be sweeped.\")\n\n self.add_parameter('MDAC_Vpp',\n set_cmd=None,\n initial_value=0.1,\n vals=Numbers(min_value=0),\n docstring=\"Amplitude of a single sweep with\"\n \" MDAC. DC offset is given by the current setting\"\n \" of the MDAC channel. After acquisition the channel\"\n \" voltage is set back to the initial value.\")\n\n self.add_parameter('MDAC_divider',\n set_cmd=None,\n initial_value=1,\n vals=Numbers(min_value=1),\n docstring=\"Voltage divider to take into account\")\n\n self.add_parameter('pixels',\n set_cmd=None,\n initial_value=64,\n vals=Ints(1,2048),\n docstring=\"Number of pixels along the axis\"\n \" controlled by the MDAC sweep.\"\n \" Must be a power of 2.\")\n\n # only gettable\n self.add_parameter('time_per_pixel',\n get_cmd=self._get_time_per_pixel)\n\n self.add_parameter('time_per_point',\n get_cmd=self._get_time_per_point)\n\n self.add_parameter('saples_per_point',\n get_cmd=self._saples_per_point)\n\n\n ################### Get functions ###################\n\n def _get_time_per_pixel(self):\n # calculate how much time does it take to measure\n # a single pixel\n tM = self.samples_to_time(self.samples_per_pixel())\n tM += self.midas_retriggering_time()*self.POINTS_PER_BUFFER/self.pixels()\n return tM\n\n def _get_time_per_point(self):\n # calculate how much time does it take to measure\n # a single point\n tM = self.time_per_pixel()\n tM /= self.POINTS_PER_BUFFER/self.pixels()\n return tM\n\n def _saples_per_point(self):\n return int(self.samples_per_pixel()/self.POINTS_PER_BUFFER*self.pixels())\n\n ################### Other functions ###################\n\n def prepare_AWG(self):\n # use 10 MS/s AWG sampling rate\n AWG_sampling_rate = 10e6\n\n # generate a sequence to upload to AWG\n # reuse single_sawtooth_many_triggers\n self.sequence = single_sawtooth_many_triggers(self.AWG,\n AWG_sampling_rate,\n self.AWG_channel(),\n self.time_per_point(),\n 1,\n self.midas_buffer_flushing_time(),\n 0,\n trigger_ch=self.AWG_trigger_channel(),\n pre_wait=self.pre_wait())\n\n # upload\n package = self.sequence.outputForAWGFile()\n AWGfile = self.AWG.make_awg_file(*package[:])\n\n self.AWG.send_awg_file('raster',AWGfile)\n self.AWG.load_awg_file('raster')\n\n self.AWG.clock_freq(AWG_sampling_rate)\n\n return self.sequence\n\n def prepare_MIDAS(self):\n self.MIDAS.sw_mode('single_point')\n self.MIDAS.single_point_num_avgs(self.saples_per_point())\n # self.MIDAS.calibrate_latency()\n # self.MIDAS.trigger_delay(self.MIDAS.trigger_delay())\n\n def prepare_MDAC(self):\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n MDAC_ch.attach_trigger()\n\n def fn_start(self):\n self.MDAC.run()\n\n def fn_stop(self):\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n\n MDAC_ch.attach_trigger()\n MDAC_ch.ramp(self.V_start, ramp_rate=self.ramp_rate*5)\n MDAC_ch.block()\n MDAC_ch.voltage(self.V_start)\n self.AWG.stop()\n\n def do_acquisition(self):\n data = self.MIDAS.capture_1d_trace(\n fn_start=self.fn_start,\n fn_stop=self.fn_stop)\n return data\n\n def reshape(self, data):\n res = np.reshape(data, (8,self.pixels(),-1))\n avg = np.average(res, axis=-1)\n return avg\n\n def arm_for_acquisition(self):\n self.AWG.stop()\n \n # get the MDAC channel\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n self.V_start = MDAC_ch.voltage()\n\n # calculate measurement time:\n sweep_time = self.pixels()*self.time_per_pixel()\n\n # calculate the rate of the MDAC sweep\n self.ramp_rate = self.MDAC_Vpp()/sweep_time\n\n # 0.99/sweep_time frequency is minimally smaller to avoid\n # problems with last pixel in case a few triggers are missed\n MDAC_ch.awg_sawtooth(0.99/sweep_time, self.MDAC_Vpp()*self.MDAC_divider(), offset=self.V_start)\n self.MDAC.stop()\n self.MDAC.sync()\n\n self.AWG.start()\n time.sleep(0.05)\n\n\n def get_measurement_range(self):\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n self.V_start = MDAC_ch.voltage()\n return np.linspace(self.V_start/self.MDAC_divider() - self.MDAC_Vpp()/2,\n self.V_start/self.MDAC_divider() + self.MDAC_Vpp()/2,\n self.pixels())\n\nclass MidasMdacAwg1DSlowMultigateRasterer(MidasMdacAwg1DSlowRasterer):\n def __init__(self, name, MIDAS_name, MDAC_name, AWG_name, **kwargs):\n super().__init__(name,\n MIDAS_name, MDAC_name, AWG_name,\n **kwargs)\n\n self.add_parameter('MDAC_channel_dict',\n set_cmd=None,\n initial_value=None,\n vals=Dict(),\n docstring=\"Dictionary that specifies\"\n \" MDAC channels and amplitudes.\"\n \" Format: {ch1: Vpp1, ch2: Vpp2}\"\n \" where ch# is int anf Vpp# is float\")\n\n self.add_parameter('range_scaling',\n set_cmd=None,\n initial_value=1,\n vals=Numbers(),\n docstring=\"Set scaling of the measurement axis.\"\n \"The returned range will be\"\n \" Vpp*range_scaling + range_offset\"\n \" where Vpp corresponds to a channel with\"\n \" the smallest number.\")\n\n self.add_parameter('range_offset',\n set_cmd=None,\n initial_value=0,\n vals=Numbers(),\n docstring=\"Set offset of the measurement axis.\"\n \"The returned range will be\"\n \" Vpp*range_scaling + range_offset\"\n \" where Vpp corresponds to a channel with\"\n \" the smallest number.\")\n\n ################### Other functions ###################\n\n def prepare_MDAC(self):\n # use channel with the smallest number to trigger on\n ch = min(self.MDAC_channel_dict().keys())\n MDAC_ch = self.MDAC.channels[ch-1]\n MDAC_ch.attach_trigger()\n\n def fn_stop(self):\n for ch, V_start in self.V_start.items():\n MDAC_ch = self.MDAC.channels[ch-1]\n\n MDAC_ch.attach_trigger()\n MDAC_ch.ramp(V_start)\n MDAC_ch.block()\n MDAC_ch.voltage(V_start)\n time.sleep(0.005)\n self.AWG.stop()\n\n def arm_for_acquisition(self):\n self.AWG.stop()\n\n # calculate measurement time:\n sweep_time = self.pixels()*self.time_per_pixel()\n\n # set waveform on all channels\n self.V_start = {}\n for ch, Vpp in self.MDAC_channel_dict().items():\n # get the MDAC channel\n MDAC_ch = self.MDAC.channels[ch-1]\n V_start = MDAC_ch.voltage()\n\n # save initial values\n self.V_start[ch] = V_start\n\n # 0.99/sweep_time frequency is minimally smaller to avoid\n # problems with last pixel in case a few triggers are missed\n if Vpp>0:\n MDAC_ch.awg_sawtooth(0.99/sweep_time, Vpp, offset=V_start)\n else:\n MDAC_ch.awg_sawtooth_falling(0.99/sweep_time, -Vpp, offset=V_start)\n \n\n self.MDAC.stop()\n self.MDAC.sync()\n\n self.AWG.start()\n time.sleep(0.05)\n\n def get_measurement_range(self):\n ch = min(self.MDAC_channel_dict().keys())\n Vpp = self.MDAC_channel_dict()[ch]\n scaling = self.range_scaling()\n offset = self.range_offset()\n\n return np.linspace(-Vpp*scaling/2+offset,\n Vpp*scaling/2+offset,\n self.pixels())\n\n#################################################################\n######################## 1D AWG rasterer ########################\n#################################################################\n\nclass MidasMdacAwg1DFastRasterer(MidasMdacAwgParentRasterer):\n \"\"\"\n How to use:\n 1. Configure Midas channels\n 2. Create a rasterer object:\n >>> rFast = rast.MidasMdacAwg1DFastRasterer('rFast',\n midas.name, mdac.name, AWG.name)\n MDAC name is required but not used anywhere.\n 3. Set up the voltage range, averaging and resolution:\n >>> rFast.AWG_Vpp(0.1)\n >>> rFast.samples_per_pixel(512)\n >>> rFast.pixels(128)\n >>> rFast.midas_buffer_flushing_time(0.01)\n # long buffer flushing time needed at this point\n 4. Run routines to automatically configure AWG and Midas:\n >>> rFast.prepare_AWG()\n >>> rFast.AWG_channels_on()\n >>> rFast.prepare_MIDAS()\n 5. Measure:\n >>> data = rFast.arm_acquire_reshape()\n 6. \"data\" is an (8 x pixels) array with the obtained data\n At this time no scaling of the sweeped axis is provided.\n 7. Investigate the data to verify if Midas\n is synchronized with the AWG sawtooth. If needed, adjust\n pre_wait and trigger_delay parameters and repeat\n points 4-6\n 8. Executing 4 between measurements is only required\n if you changed any of the following parameters:\n - AWG_channel\n - samples_per_pixel\n - midas_retriggering_time\n - pre_wait\n - pixels\n - samples_per_ramp\n - AWG_Vpp\n - AWG parameters\n - high_pass_cutoff\n Executing 4 is NOT required if you change:\n - MIDAS_channels\n - Midas channel parameters\n \"\"\"\n\n def __init__(self, name, MIDAS_name, MDAC_name, AWG_name, **kwargs):\n \"\"\"\n Create a MidasMdacAwgRasterer instance\n\n Args:\n name (str): rasterer instrument name\n MIDAS_name (str): name of the Midas to be used\n MDAC_name (str): name of the MDAC to be used\n AWG_name (str): name of the Tektronix 5014 to be used\n **kwargs: other kwargs passed to Instrument init\n\n Returns:\n MidasMdacAwgRasterer\n \"\"\"\n\n super().__init__(name,\n MIDAS_name, MDAC_name, AWG_name,\n **kwargs)\n\n self.add_parameter('pixels',\n set_cmd=None,\n initial_value=64,\n vals=Ints(1,2048),\n docstring=\"Number of pixels along the axis\"\n \" controlled by the MDAC sweep.\"\n \" Must be a power of 2.\")\n\n self.add_parameter('samples_per_ramp',\n set_cmd=None,\n initial_value=1024,\n vals=Ints(128,4096),\n docstring=\"Number of samples taken per\"\n \" single AWG ramp. Should be the largest\"\n \" number possible that does not lead to\"\n \" the distortions.\"\n \" Must be a power of 2.\")\n\n self.add_parameter('AWG_Vpp',\n set_cmd=None,\n initial_value=0.1,\n vals=Numbers(min_value=0),\n docstring=\"Vpp of the sawtooth applied with AWG,\"\n \" Not adjusted for the attenuation of the\"\n \" high-frequency lines. DC offset of the voltage\"\n \" needs to be set separately with whatever\"\n \" instrument you use for that.\")\n\n self.add_parameter('high_pass_cutoff',\n set_cmd=None,\n initial_value=0,\n vals=Numbers(min_value=0,max_value=1e9),\n docstring=\"Cut off frequency of the high pass filter\"\n \" which is to be compensated by predistorting\"\n \" the AWG waveform.\")\n\n # only gettable\n self.add_parameter('samples_total',\n get_cmd=self._get_samples_total)\n\n self.add_parameter('points_total',\n get_cmd=self._get_points_total)\n\n self.add_parameter('ramp_time_fast',\n get_cmd=self._get_ramp_time_fast)\n\n self.add_parameter('samples_per_point',\n get_cmd=self._get_samples_per_point)\n\n self.add_parameter('ramps_per_acquisition',\n get_cmd=self._get_ramps_per_acquisition)\n\n self.add_parameter('buffers_per_acquisition',\n get_cmd=self._get_buffers_per_acquisition)\n\n ################### Get functions ###################\n\n def _get_samples_total(self):\n return int(self.samples_per_pixel()*self.pixels())\n\n def _get_points_total(self):\n return int(self.ramps_per_acquisition()*self.pixels())\n\n def _get_ramp_time_fast(self):\n # calculate the AWG sawtooth period corresponding to\n # the number of samples per single ramp\n # plus time for the Midas to retrigger\n # in principle time for th emidas to retrigges can be set to 0\n tM = self.samples_to_time(self.samples_per_ramp())\n tW = self.pixels()*self.midas_retriggering_time()\n return tM+tW\n\n def _get_samples_per_point(self):\n return int(self.samples_per_ramp()/self.pixels())\n\n def _get_ramps_per_acquisition(self):\n samples_per_acquisition = self.samples_per_pixel()*self.pixels()\n ramps_per_acquisition = samples_per_acquisition/self.samples_per_ramp()\n return int(max(ramps_per_acquisition,1))\n\n def _get_buffers_per_acquisition(self):\n sample_limited_minimum = self.samples_total()/self.samples_per_point()/self.POINTS_PER_BUFFER\n resolution_limited_minimum = self.pixels()/self.POINTS_PER_BUFFER\n return int(max(sample_limited_minimum, resolution_limited_minimum,1))\n\n ################### Other functions ###################\n\n def prepare_AWG(self):\n # use low AWG sampling rate, but not smaller than\n # minimum 10 MS/s\n AWG_sampling_rate = max(200/self.ramp_time_fast(), 10e6)\n\n # generate a sequence to upload to AWG\n self.sequence = single_sawtooth_many_triggers(self.AWG,\n AWG_sampling_rate,\n self.AWG_channel(),\n self.ramp_time_fast(),\n self.pixels(),\n self.midas_buffer_flushing_time(),\n self.AWG_Vpp(),\n high_pass_cutoff=self.high_pass_cutoff(),\n trigger_ch=self.AWG_trigger_channel(),\n pre_wait=self.pre_wait())\n\n # upload\n package = self.sequence.outputForAWGFile()\n AWGfile = self.AWG.make_awg_file(*package[:])\n\n self.AWG.send_awg_file('raster',AWGfile)\n self.AWG.load_awg_file('raster')\n\n self.AWG.clock_freq(AWG_sampling_rate)\n\n return self.sequence\n\n def prepare_MIDAS(self):\n self.MIDAS.sw_mode('single_point')\n self.MIDAS.single_point_num_avgs(self.samples_per_point())\n self.MIDAS.num_sweeps_2d(self.buffers_per_acquisition())\n # self.MIDAS.calibrate_latency()\n # self.MIDAS.trigger_delay(self.MIDAS.trigger_delay())\n\n def prepare_MDAC(self):\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n MDAC_ch.attach_trigger()\n\n def fn_start(self):\n # trigger AWG\n self.AWG.force_trigger()\n\n def fn_stop(self):\n self.AWG.stop()\n\n def do_acquisition(self):\n if self.buffers_per_acquisition() == 1:\n data = [self.MIDAS.capture_1d_trace(\n fn_start=self.fn_start,\n fn_stop=self.fn_stop)]\n else:\n data = [self.MIDAS.capture_1d_trace(\n fn_start=self.fn_start)]\n for _ in range(self.buffers_per_acquisition()-2):\n data.append(self.MIDAS.capture_1d_trace())\n data.append(self.MIDAS.capture_1d_trace(\n fn_stop=self.fn_stop))\n return np.array(data)\n\n def reshape(self, data):\n reshaped = []\n for i in range(8):\n d = data[:,i,:]\n if self.points_total()<2048:\n d = d[0,:self.points_total()]\n res = np.reshape(d, (self.ramps_per_acquisition(),\n self.pixels()))\n avg = np.average(res, axis=0)\n reshaped.append(avg)\n\n return np.array(reshaped)\n\n def get_measurement_range(self):\n return np.linspace(-self.AWG_Vpp()/2,\n self.AWG_Vpp()/2,\n self.pixels())\n\n########## Testing 1D fast rasterer with capture_2d_trace ##########\n\nclass MidasMdacAwg1DFastRasterer_test(MidasMdacAwg1DFastRasterer):\n\n def __init__(self, name, MIDAS_name, MDAC_name, AWG_name, **kwargs):\n\n super().__init__(name,\n MIDAS_name, MDAC_name, AWG_name,\n **kwargs)\n\n def do_acquisition(self):\n data = self.MIDAS.capture_2d_trace(\n fn_start=self.fn_start,\n fn_stop=self.fn_stop)\n # removing first buffer [WORKAROUND]\n return np.array(data[1:])\n\n#################################################################\n########################## 2D rasterer ##########################\n#################################################################\n\nclass MidasMdacAwg2DRasterer(MidasMdacAwgParentRasterer):\n \"\"\"\n The class responsible for dual gate rastering with\n MIDAS, MDAC and Tektronix 5014.\n\n Relevant parameters:\n - AWG_channel\n - MDAC_channel\n - AWG_Vpp (amplitude of the sawtooth applied by AWG)\n - MDAC_Vpp (amplitude of the MDAC sweep)\n - samples_per_pixel (indicates averaging per point;\n 1 sample = 284.44 ns; only values 2^N will yield\n successful measurement)\n - pixels_per_line (resolution along the axis\n controlled by AWG; only values 2^N will yield\n successful measurement)\n - lines_per_acquisition (resolution along the axis\n controlled by MDAC; only values 2^N will yield\n successful measurement)\n - samples_per_ramp (specifies the length of the sawtooth\n applied by AWG; 1 sample = 284.44 ns; only values 2^N will\n yield successful measurement; should set to the largest\n value, for which the distortions are not observed)\n - midas_buffer_flushing_time (additional waiting time between\n some of the sawtooth teeth, for the Midas to flush the\n FIFO buffer; maual specifies this needs to be no longer\n than 0.6 ms, but I found out that this is often not\n sufficient and recommend using 1 ms to reduce\n how often triggers are missed)\n - high_pass_cutoff (specifies the cutoff frequency of\n the high pass filter on the high frequency (AWG) line)\n\n The idea is that the user only needs to specify an averaging\n time per pixel, resolution and sawtooth period (constrained by\n the bandwidth of the setup). The order in which the data\n is acquired is taken care of automatically.\n \n Naming convention:\n - sample: 284.44 ns long sample measured by Midas\n - point: a number of samples averaged together during a single ramp\n - ramp: a single tooth of an AWG sawtooth\n - pixel: a single data point in the final dataset. Depending on\n demanded samples_per_pixel several points (from consequtive\n ramps) may be averaged together to get a single pixel\n - line: a collection of pixels forming a single line in\n the final dataset. Depending on demanded samples_per_pixel\n data from one or more ramps may be averaged together to\n yield a single line\n - buffer: a collection of 2048 points. This number is strictly\n specified by the Midas user manual\n - acquisition: a collection of buffers with all of the acquired data\n \n How to use:\n 1. Configure Midas channels\n 2. Create a rasterer object:\n >>> r2D = rast.MidasMdacAwg1DFastRasterer('r2D',\n midas.name, mdac.name, AWG.name)\n 3. Set up the MDAC channel, voltage ranges, averaging\n and resolution:\n >>> r2D.MDAC_channel(1)\n >>> r2D.MDAC_Vpp(0.8)\n >>> r2D.AWG_Vpp(0.1)\n >>> r2D.samples_per_pixel(64)\n >>> r2D.pixels_per_line(128)\n >>> r2D.lines_per_acquisition(128)\n 4. Run routines to automatically configure AWG and Midas:\n >>> r2D.prepare_AWG()\n >>> r2D.AWG_channels_on()\n >>> r2D.prepare_MIDAS()\n 5. Measure:\n >>> data = r2D.arm_acquire_reshape()\n 6. \"data\" is an (8 x pixels x lines) array with\n the obtained data. At this time no scaling\n of the sweeped axis is provided.\n The MDAC sweeps the voltage from Vmdac-MDAC_Vpp/2\n to Vmdac+MDAC_Vpp/2, where Vmdac is the channel setting\n at the moment arm_acquire_reshape method is executed.\n 7. Investigate the data to verify if Midas\n is synchronized with the AWG sawtooth and if\n AWG starts in outputting sawtooth in sync with\n MDAC starting the sweep. If needed, adjust\n pre_wait and trigger_delay parameters and repeat\n points 4-6\n 8. Executing 4 between measurements is only required\n if you changed any of the following parameters:\n - AWG_channel\n - samples_per_pixel\n - midas_retriggering_time\n - pre_wait\n - pixels_per_line\n - lines_per_acquisition\n - samples_per_ramp\n - AWG_Vpp\n - AWG parameters\n - high_pass_cutoff\n Executing 4 is NOT required if you change:\n - MDAC_channel\n - MDAC_Vpp\n - MIDAS_channels\n - Midas channel parameters\n \"\"\"\n\n def __init__(self, name, MIDAS_name, MDAC_name, AWG_name, **kwargs):\n \"\"\"\n Create a MidasMdacAwgRasterer instance\n\n Args:\n name (str): rasterer instrument name\n MIDAS_name (str): name of the Midas to be used\n MDAC_name (str): name of the MDAC to be used\n AWG_name (str): name of the Tektronix 5014 to be used\n **kwargs: other kwargs passed to Instrument init\n\n Returns:\n MidasMdacAwgRasterer\n \"\"\"\n\n super().__init__(name,\n MIDAS_name, MDAC_name, AWG_name,\n **kwargs)\n\n self.add_parameter('MDAC_channel',\n set_cmd=None,\n initial_value=None,\n vals=Ints(min_value=1,max_value=64),\n docstring=\"MDAC channels to be sweeped.\")\n\n self.add_parameter('MDAC_channel_for_AWG',\n set_cmd=None,\n initial_value=None,\n vals=Ints(min_value=1,max_value=64),\n docstring=\"MDAC channel corresponding to the gate\"\n \" sweeped by AWG. Needed for axis scaling.\"\n )\n\n self.add_parameter('pixels_per_line',\n set_cmd=None,\n initial_value=64,\n vals=Ints(1,8192),\n docstring=\"Number of pixels along the axis\"\n \" specified by the fast AWG ramp.\"\n \" Must be a power of 2.\")\n\n self.add_parameter('lines_per_acquisition',\n set_cmd=None,\n initial_value=64,\n vals=Ints(1,4096),\n docstring=\"Number of lines in\"\n \" the final 2D diagram.\"\n \" Must be a power of 2.\")\n\n self.add_parameter('samples_per_ramp',\n set_cmd=None,\n initial_value=1024,\n vals=Ints(128,4096),\n docstring=\"Number of samples taken per\"\n \" single AWG ramp. Should be the largest\"\n \" number possible that does not lead to\"\n \" the distortions.\"\n \" Must be a power of 2.\")\n\n self.add_parameter('AWG_Vpp',\n set_cmd=None,\n initial_value=0.1,\n vals=Numbers(min_value=0),\n docstring=\"Vpp of the sawtooth applied with AWG,\"\n \" Not adjusted for the attenuation of the\"\n \" high-frequency lines. DC offset of the voltage\"\n \" needs to be set separately with whatever\"\n \" instrument you use for that.\")\n\n self.add_parameter('MDAC_Vpp',\n set_cmd=None,\n initial_value=0.1,\n vals=Numbers(min_value=0),\n docstring=\"Amplitude of a single sweep with\"\n \" MDAC. DC offset is given by the current setting\"\n \" of the MDAC channel. After acquisition the channel\"\n \" voltage is set back to the initial value.\")\n\n self.add_parameter('MDAC_divider',\n set_cmd=None,\n initial_value=1,\n vals=Numbers(min_value=1),\n docstring=\"Voltage divider to take into account\")\n\n self.add_parameter('AWG_divider',\n set_cmd=None,\n initial_value=1,\n vals=Numbers(min_value=1),\n docstring=\"Voltage divider to take into account\")\n\n self.add_parameter('high_pass_cutoff',\n set_cmd=None,\n initial_value=0,\n vals=Numbers(min_value=0,max_value=1e9),\n docstring=\"Cut off frequency of the high pass filter\"\n \" which is to be compensated by predistorting\"\n \" the AWG waveform.\")\n\n # only gettable\n self.add_parameter('samples_total',\n get_cmd=self._get_samples_total)\n\n self.add_parameter('points_total',\n get_cmd=self._get_points_total)\n\n self.add_parameter('ramp_time_fast',\n get_cmd=self._get_ramp_time_fast)\n\n self.add_parameter('ramps_per_buffer',\n get_cmd=self._get_ramps_per_buffer)\n\n self.add_parameter('samples_per_point',\n get_cmd=self._get_samples_per_point)\n\n self.add_parameter('ramps_per_line',\n get_cmd=self._get_ramps_per_line)\n\n self.add_parameter('buffers_per_acquisition',\n get_cmd=self._get_buffers_per_acquisition) \n\n ################### Get functions ###################\n\n def _get_samples_total(self):\n return int(self.samples_per_pixel()*self.pixels_per_line()*self.lines_per_acquisition())\n\n def _get_points_total(self):\n return int(self.lines_per_acquisition()*self.ramps_per_line()*self.pixels_per_line())\n\n def _get_ramp_time_fast(self):\n # calculate the AWG sawtooth period corresponding to\n # the number of samples per single ramp\n # plus time for the Midas to retrigger\n # in principle time for th emidas to retrigges can be set to 0\n tM = self.samples_to_time(self.samples_per_ramp())\n tW = self.pixels_per_line()*self.midas_retriggering_time()\n return tM+tW\n\n def _get_ramps_per_buffer(self):\n return int(self.POINTS_PER_BUFFER/self.pixels_per_line())\n\n def _get_samples_per_point(self):\n return int(self.samples_per_ramp()/self.pixels_per_line())\n\n def _get_ramps_per_line(self):\n samples_per_line = self.samples_per_pixel()*self.pixels_per_line()\n ramps_per_line = samples_per_line/self.samples_per_ramp()\n return int(max(ramps_per_line,1))\n\n def _get_buffers_per_acquisition(self):\n sample_limited_minimum = self.samples_total()/self.samples_per_point()/self.POINTS_PER_BUFFER\n resolution_limited_minimum = self.pixels_per_line()*self.lines_per_acquisition()/self.POINTS_PER_BUFFER\n return int(max(sample_limited_minimum, resolution_limited_minimum,1))\n\n\n ################### Other functions ###################\n\n def prepare_AWG(self):\n # use low AWG sampling rate, but not smaller than\n # minimum 10 MS/s\n AWG_sampling_rate = max(200/self.ramp_time_fast(), 10e6)\n\n # generate a sequence to upload to AWG\n self.sequence = single_sawtooth_many_triggers(self.AWG,\n AWG_sampling_rate,\n self.AWG_channel(),\n self.ramp_time_fast(),\n self.pixels_per_line(),\n self.midas_buffer_flushing_time(),\n self.AWG_Vpp()*self.AWG_divider(),\n high_pass_cutoff=self.high_pass_cutoff(),\n trigger_ch=self.AWG_trigger_channel(),\n pre_wait=self.pre_wait())\n\n # upload\n package = self.sequence.outputForAWGFile()\n AWGfile = self.AWG.make_awg_file(*package[:])\n\n self.AWG.send_awg_file('raster',AWGfile)\n self.AWG.load_awg_file('raster')\n\n self.AWG.clock_freq(AWG_sampling_rate)\n\n return self.sequence\n\n def prepare_MIDAS(self):\n self.MIDAS.sw_mode('single_point')\n self.MIDAS.single_point_num_avgs(self.samples_per_point())\n\n # +1 as a workaround for the Midas bug [WORKAROUND]\n self.MIDAS.num_sweeps_2d(self.buffers_per_acquisition() + 1)\n # self.MIDAS.calibrate_latency()\n # self.MIDAS.trigger_delay(self.MIDAS.trigger_delay())\n\n def prepare_MDAC(self):\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n MDAC_ch.attach_trigger()\n\n def fn_start(self):\n self.MDAC.run()\n\n def fn_stop(self):\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n\n MDAC_ch.ramp(self.V_start, ramp_rate=self.ramp_rate*5)\n MDAC_ch.block()\n MDAC_ch.voltage(self.V_start)\n self.AWG.stop()\n\n def do_acquisition(self):\n data = self.MIDAS.capture_2d_trace(\n fn_start=self.fn_start,\n fn_stop=self.fn_stop)\n\n # removing first buffer [WORKAROUND]\n return np.array(data[1:])\n\n def reshape(self, data):\n reshaped = []\n for i in range(8):\n d = data[:,i,:]\n if self.points_total()<2048:\n d = d[0,:self.points_total()]\n res = np.reshape(d, (self.lines_per_acquisition(),\n self.ramps_per_line(),\n self.pixels_per_line()))\n avg = np.average(res, axis=1)\n reshaped.append(avg)\n\n return np.array(reshaped)\n\n def arm_for_acquisition(self):\n self.AWG.stop()\n\n # get the MDAC channel\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n self.V_start = MDAC_ch.voltage()\n\n # calculate measurement time:\n ramps = self.ramps_per_buffer()\n buffers = self.buffers_per_acquisition()\n ramp_time = self.ramp_time_fast()\n flushing_time = self.midas_buffer_flushing_time()\n\n sweep_time = ramps*buffers*ramp_time\n sweep_time += (buffers-1)*flushing_time\n\n # calculate the rate of the MDAC sweep\n self.ramp_rate = self.MDAC_Vpp()/sweep_time\n\n # 0.99/sweep_time frequency is minimally smaller to avoid\n # problems with last pixel in case a few triggers are missed\n MDAC_ch.awg_sawtooth(0.99/sweep_time, self.MDAC_Vpp()*self.MDAC_divider(), offset=self.V_start)\n self.MDAC.stop()\n self.MDAC.sync()\n\n self.AWG.start()\n time.sleep(0.1)\n\n def get_measurement_range(self):\n MDAC_ch = self.MDAC.channels[self.MDAC_channel()-1]\n self.V_start = MDAC_ch.voltage()\n MDAC_range = np.linspace(self.V_start - self.MDAC_Vpp()/2,\n self.V_start + self.MDAC_Vpp()/2,\n self.lines_per_acquisition())/self.MDAC_divider()\n\n AWG_range = np.linspace(-self.AWG_Vpp()/2,\n self.AWG_Vpp()/2,\n self.pixels_per_line())\n\n if self.MDAC_channel_for_AWG() is not None:\n MDAC_ch_2 = self.MDAC.channels[self.MDAC_channel_for_AWG()-1]\n AWG_range += MDAC_ch_2.voltage()\n\n\n return AWG_range, MDAC_range\n\n######################################################################\n########################## helper functions ##########################\n######################################################################\n\ndef single_sawtooth_many_triggers(AWG,\n sampling_rate,\n ch,\n rampTime,\n triggersPerRamp,\n flushingTime,\n Vpp,\n high_pass_cutoff=None,\n trigger_ch=1,\n triggersPerFlush=2048,\n pre_wait=None):\n \n # make a wait element\n # by default it has 2 clock cycle length\n # (the least a segmant can have)\n # to ensure that sequence starts and ends\n # with 0V\n # otherwise it has length specified by pre_wait\n if pre_wait is None:\n pre_wait = 2/sampling_rate\n\n wait_blueprint = bb.BluePrint()\n wait_blueprint.setSR(sampling_rate)\n wait_blueprint.insertSegment(-1, ramp, (0, 0),\n name='wait',\n dur=pre_wait)\n wait_element = bb.Element()\n for c in range(1,5):\n wait_element.addBluePrint(c, wait_blueprint)\n\n wait_element.validateDurations()\n\n # make a single-segment sawtooth element\n sawtooth_blueprint = bb.BluePrint()\n sawtooth_blueprint.setSR(sampling_rate)\n sawtooth_blueprint.insertSegment(-1, ramp, (-Vpp/2, Vpp/2),\n name='ramp',\n dur=rampTime)\n\n sawtooth_flat_blueprint = bb.BluePrint()\n sawtooth_flat_blueprint.setSR(sampling_rate)\n sawtooth_flat_blueprint.insertSegment(-1, ramp, (0, 0),\n name='ramp',\n dur=rampTime)\n\n if ch == trigger_ch:\n pointTime = rampTime/triggersPerRamp\n sawtooth_blueprint.marker1 = [(pointTime*i, 200e-9) for i in range(triggersPerRamp)]\n sawtooth_blueprint.marker2 = [(pointTime*i, 200e-9) for i in range(triggersPerRamp)]\n else:\n sawtooth_trigger_blueprint = bb.BluePrint()\n sawtooth_trigger_blueprint.setSR(sampling_rate)\n sawtooth_trigger_blueprint.insertSegment(-1, ramp, (0, 0),\n name='ramp_trig',\n dur=rampTime)\n pointTime = rampTime/triggersPerRamp\n sawtooth_trigger_blueprint.marker1 = [(pointTime*i, 200e-9) for i in range(triggersPerRamp)]\n sawtooth_trigger_blueprint.marker2 = [(pointTime*i, 200e-9) for i in range(triggersPerRamp)]\n\n sawtooth_element = bb.Element()\n for c in range(1,5):\n if c == ch:\n sawtooth_element.addBluePrint(c, sawtooth_blueprint)\n elif c == trigger_ch:\n sawtooth_element.addBluePrint(c, sawtooth_trigger_blueprint)\n else:\n sawtooth_element.addBluePrint(c, sawtooth_flat_blueprint)\n \n\n sawtooth_element.validateDurations()\n\n # make an element what waits for buffer flushing\n flush_blueprint = bb.BluePrint()\n flush_blueprint.setSR(sampling_rate)\n flush_blueprint.insertSegment(-1, ramp, (0, 0),\n name='wait',\n dur=flushingTime)\n flush_element = bb.Element()\n for c in range(1,5):\n flush_element.addBluePrint(c, flush_blueprint)\n\n flush_element.validateDurations()\n\n\n\n # make a sequence\n # wait - sawtooth (repeat) - flush - go to sawtooth\n elem_num = 1\n sequence = bb.Sequence()\n\n sequence.addElement(elem_num, wait_element)\n sequence.setSequencingTriggerWait(elem_num, 1)\n sequence.setSequencingNumberOfRepetitions(elem_num,1)\n sequence.setSequencingGoto(elem_num,0)\n elem_num += 1\n\n sequence.addElement(elem_num, sawtooth_element)\n sequence.setSequencingTriggerWait(elem_num, 0)\n rampsPerFlush = triggersPerFlush/triggersPerRamp\n sequence.setSequencingNumberOfRepetitions(elem_num,rampsPerFlush)\n sequence.setSequencingGoto(elem_num,0)\n elem_num += 1\n\n sequence.addElement(elem_num, flush_element)\n sequence.setSequencingTriggerWait(elem_num, 0)\n sequence.setSequencingNumberOfRepetitions(elem_num,1)\n sequence.setSequencingGoto(elem_num,2)\n elem_num += 1\n\n for c in range(1,5):\n ch_amp = AWG['ch'+str(c)+'_amp']()\n sequence.setChannelAmplitude(c, ch_amp)\n sequence.setChannelOffset(c, 0)\n\n sequence.setSR(sampling_rate)\n\n if high_pass_cutoff is not None:\n if high_pass_cutoff>0:\n sequence.setChannelFilterCompensation(ch, 'HP',\n order=1, f_cut=high_pass_cutoff)\n\n return sequence\n\n\ndef get_quadrature(d, q, phase_offset=0):\n rot_vec = complex(np.cos(phase_offset), -np.sin(phase_offset))\n if q=='A':\n return np.abs(d)\n elif q=='P':\n phases = np.angle(d) - phase_offset\n return (phases + np.pi) % (2*np.pi) - np.pi\n elif q=='I':\n return np.real(d*rot_vec)\n elif q=='Q':\n return np.imag(d*rot_vec)\n else:\n ValueError(\"Quadrature must be specified as I, Q, A or P\")\n\n\n\n","sub_path":"pytopo/fast_reflectometry_measurements/MDAC_MIDAS_rastering_tools.py","file_name":"MDAC_MIDAS_rastering_tools.py","file_ext":"py","file_size_in_byte":51020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"302703774","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\n\nn = int(input())\nphone_book = {}\n\nfor i in range(n):\n input_ = input().split()\n name = input_[0]\n phone = input_[1]\n phone_book[name] = phone\n\nwhile True:\n try:\n name2 = input()\n if name2 in phone_book.keys():\n print(name2 + '=' + phone_book[name2])\n else:\n print('Not found')\n except Exception:\n break\n","sub_path":"30 Days of Code/Dictionaries and Maps/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"245849766","text":"from __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\nfrom six.moves import cPickle as pickle\nfrom six.moves import range\n\n\npickle_file = 'brightnessData.pickle'\n\nwith open(pickle_file, 'rb') as f:\n save = pickle.load(f)\n train_dataset = save['train_dataset']\n train_labels = save['train_labels']\n test_dataset = save['test_dataset']\n test_labels = save['test_labels']\n del save # hint to help gc free up memory\n print('Training set', train_dataset.shape, train_labels.shape)\n print('Test set', test_dataset.shape, test_labels.shape)\n\n# reformat the data to flat matrix and one hot encodings\nimage_size = 28\nnum_labels = 256\n\ndef reformat(dataset, labels):\n dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)\n # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]\n labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n return dataset, labels\ntrain_dataset, train_labels = reformat(train_dataset, train_labels)\ntest_dataset, test_labels = reformat(test_dataset, test_labels)\nprint('Training set', train_dataset.shape, train_labels.shape)\nprint('Test set', test_dataset.shape, test_labels.shape)\n\nimport tensorflow as tf\nsess = tf.InteractiveSession()\n\nx = tf.placeholder(tf.float32, shape=[None, 784])\ny_ = tf.placeholder(tf.float32, shape=[None, 256])\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\nx_image = tf.reshape(x, [-1,28,28,1])\n\nW_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n#h_pool1 = max_pool_2x2(h_conv1)\n\nW_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\n#h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\nh_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2) + b_conv2)\n#h_pool2 = max_pool_2x2(h_conv2)\n\n#W_conv3 = weight_variable([5, 5, 64, 128])\n#b_conv3 = bias_variable([128])\n#h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)\n#h_conv3 = tf.nn.relu(conv2d(h_conv2, W_conv3) + b_conv3)\n#h_pool3 = max_pool_2x2(h_conv3)\n\n#W_conv4 = weight_variable([5, 5, 128, 256])\n#b_conv4 = bias_variable([256])\n#h_conv4 = tf.nn.relu(conv2d(h_pool3, W_conv4) + b_conv4)\n#h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4)\n#h_pool4 = max_pool_2x2(h_conv4)\n\n#W_conv5 = weight_variable([5, 5, 256, 512])\n#b_conv5 = bias_variable([512])\n#h_conv5 = tf.nn.relu(conv2d(h_pool4, W_conv5) + b_conv5)\n#h_conv5 = tf.nn.relu(conv2d(h_conv4, W_conv5) + b_conv5)\n#h_pool5 = max_pool_2x2(h_conv5)\n\n#W_conv6 = weight_variable([5, 5, 512, 1024])\n#b_conv6 = bias_variable([1024])\n#h_conv6 = tf.nn.relu(conv2d(h_pool5, W_conv6) + b_conv6)\n#h_conv6 = tf.nn.relu(conv2d(h_conv5, W_conv6) + b_conv6)\n#h_pool6 = max_pool_2x2(h_conv6)\n\nW_fc1 = weight_variable([28 * 28 * 64, 1024])\nb_fc1 = bias_variable([1024])\n\n#h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\nh_conv2_flat = tf.reshape(h_conv2, [-1, 28*28*64])\n#h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\nh_fc1 = tf.nn.relu(tf.matmul(h_conv2_flat, W_fc1) + b_fc1)\n\n#keep_prob = tf.placeholder(tf.float32)\n#h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\nW_fc2 = weight_variable([1024, 256])\nb_fc2 = bias_variable([256])\n\n#y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\ny_conv = tf.matmul(h_fc1, W_fc2) + b_fc2\n\n\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_conv, y_))\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\ncorrect_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsess.run(tf.global_variables_initializer())\nfor i in range(20000):\n offset = (i * 50) % (train_labels.shape[0] - 50)\n batch_xs = train_dataset[offset:(offset + 50), :]\n batch_ys = train_labels[offset:(offset + 50), :]\n \n if i%100 == 0:\n train_accuracy = accuracy.eval(feed_dict={\n x:batch_xs, y_: batch_ys})\n print(\"step %d, training accuracy %g\"%(i, train_accuracy))\n train_step.run(feed_dict={x: batch_xs, y_: batch_ys})\n\nprint(\"test accuracy %g\"%accuracy.eval(feed_dict={\n x: test_dataset, y_: test_labels}))\n\n","sub_path":"test5.py","file_name":"test5.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"379373927","text":"@staticmethod\ndef grant_sales_rabbit_access(email,first_name,last_name,form_office, office_obj):\n sr_office_id = str(office_obj.sales_rabbit_id)\n sr_area_id = str(office_obj.sales_rabbit_area_id)\n user_payload = {\n \"email\" : email,\n \"first\": first_name,\n \"last\": last_name,\n \"area\": sr_area_id,\n \"office\" : sr_office_id\n }\n user_payload = urllib.urlencode(user_payload)\n\n resp2 = urlfetch.fetch(url=\"https://script.google.com/macros/s/AKfycbxiyWcucD6Mk26Pg_ixtr6t4ooNEyT0aw7xdIFh3Fw44xSkv68/exec\",\n deadline=30,\n headers=\n {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36\",\n },\n payload=user_payload,\n method=urlfetch.POST,\n follow_redirects=False\n )\n\n\n\n return -1\n\n\n","sub_path":"classes/Helpers_/grant_sales_rabbit_access.py","file_name":"grant_sales_rabbit_access.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"578986211","text":"# coding=utf-8\r\nimport numpy as np\r\nimport pandas as pd\r\nimport cv2\r\nimport os\r\nimport time\r\n\r\n\r\ndef getPixelMatrix(filename):\r\n arr = cv2.imread(filename, 0)\r\n return arr.astype(int)\r\n\r\n\r\ndef getGLCM(arr):\r\n a1 = []\r\n for i in range(arr.shape[0]):\r\n for j in range(arr.shape[1]):\r\n a1.append(arr[i][j])\r\n a2 = []\r\n for i in range(1, len(a1)):\r\n a2.append(a1[i])\r\n del a1[-1]\r\n strA = []\r\n for i in range(len(a1)):\r\n strA.append(str(a1[i]) + str(a2[i]))\r\n a3 = []\r\n for i in range(len(strA)):\r\n a3.append(strA.count(strA[i]))\r\n df = pd.DataFrame({'x': a1, 'y': a2, 'z': a3})\r\n df = df.drop_duplicates()\r\n return df.sort_values(by=['x'])\r\n\r\n\r\ndef getX1X2X3(df):\r\n newList = []\r\n a1 = df['x'].tolist()\r\n a2 = df['y'].tolist()\r\n a3 = df['z'].tolist()\r\n max_index = a3.index(max(a3))\r\n result = int(a1[max_index]) * int(a2[max_index])\r\n newList.append(result) # первый признак (x1)\r\n norm_value = pd.Series(a3)\r\n norm_value = (norm_value / sum(norm_value) * 10000).tolist()\r\n tp = np.array(a1)\r\n arr_index = np.where(tp == 53)[0]\r\n result2_array = []\r\n for j in arr_index:\r\n result2_array.append(norm_value[j])\r\n try:\r\n result2 = sum(result2_array) / len(result2_array)\r\n except:\r\n result2 = 0\r\n newList.append(result2) # второй признак (x2)\r\n result3 = int(max(a1)) * int(max(a2))\r\n newList.append(result3) # третий признак (x3)\r\n return newList\r\n\r\n\r\ndef getAll(load_folder1, load_folder2, excel_file):\r\n n = len(os.listdir(load_folder1))\r\n print(n)\r\n listToSave = []\r\n # Norma\r\n for iteration in range(n):\r\n newList = []\r\n filename = load_folder1 + str(iteration + 1) + '.png'\r\n arr = getPixelMatrix(filename) # матрица градаций серого\r\n df = getGLCM(arr) # GLCM\r\n xList = getX1X2X3(df)\r\n newList.append(xList[0])\r\n newList.append(xList[1])\r\n newList.append(xList[2])\r\n newList.append(1)\r\n listToSave.append(newList)\r\n n = len(os.listdir(load_folder2))\r\n print(n)\r\n # Pathology\r\n for iteration in range(n):\r\n newList = []\r\n filename = load_folder2 + str(iteration + 1) + '.png'\r\n arr = getPixelMatrix(filename) # матрица градаций серого\r\n df = getGLCM(arr) # GLCM\r\n xList = getX1X2X3(df)\r\n newList.append(xList[0])\r\n newList.append(xList[1])\r\n newList.append(xList[2])\r\n newList.append(2)\r\n listToSave.append(newList)\r\n df = pd.DataFrame(listToSave)\r\n df.to_excel(excel_file + \".xlsx\", index=False)\r\n\r\n\r\nstart_time = time.time()\r\ngetAll(\"/home/mhoncharuk/Education/liver_disease_recognizer/ROI/Norma/CL/\",\r\n \"/home/mhoncharuk/Education/liver_disease_recognizer/ROI/Norma/CL/\",\r\n \"convex1\")\r\n# print(\"Time: \", time.time() - start_time)\r\n# start_time = time.time()\r\n# getAll(\"D:\\\\Studying\\\\KPI\\\\DataForPreprocessing\\\\Norma\\\\Linear\\\\\",\r\n# \"D:\\\\Studying\\\\KPI\\\\DataForPreprocessing\\\\Pathology\\\\Linear\\\\\",\r\n# \"linear1\")\r\n# print(\"Time: \", time.time() - start_time)\r\n# start_time = time.time()\r\n# getAll(\"D:\\\\Studying\\\\KPI\\\\DataForPreprocessing\\\\Norma\\\\Balls\\\\\",\r\n# \"D:\\\\Studying\\\\KPI\\\\DataForPreprocessing\\\\Pathology\\\\Balls\\\\\",\r\n# \"balls1\")\r\nprint(\"Time: \", time.time() - start_time)\r\n","sub_path":"notebooks/getX1X2X3.py","file_name":"getX1X2X3.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"498490329","text":"from django.db import models\ntry:\n # Django >= 1.10\n from django.urls import reverse\nexcept ImportError:\n # Django < 1.10\n from django.core.urlresolvers import reverse\n\nfrom .fields import NaturalSortField\n\n\nclass TimeStampedModelMixin(models.Model):\n \"Should be mixed in to all models.\"\n time_created = models.DateTimeField(auto_now_add=True,\n help_text=\"The time this item was created in the database.\")\n time_modified = models.DateTimeField(auto_now=True,\n help_text=\"The time this item was last saved to the database.\")\n\n class Meta:\n abstract = True\n\n\nclass BaseRole(TimeStampedModelMixin, models.Model):\n \"\"\"\n Base class for linking a Creator to a Book, Event, Movie, etc.\n\n Child classes should add fields like:\n\n creator = models.ForeignKey('spectator_core.Creator', blank=False,\n on_delete=models.CASCADE, related_name='publication_roles')\n\n publication = models.ForeignKey('spectator_reading.Publication',\n on_delete=models.CASCADE, related_name='roles')\n \"\"\"\n role_name = models.CharField(null=False, blank=True, max_length=50,\n help_text=\"e.g. 'Headliner', 'Support', 'Editor', 'Illustrator', 'Director', etc. Optional.\")\n\n role_order = models.PositiveSmallIntegerField(null=False, blank=False,\n default=1,\n help_text=\"The order in which the Creators will be listed.\")\n\n class Meta:\n abstract = True\n ordering = ('role_order', 'role_name',)\n\n def __str__(self):\n if self.role_name:\n return '{} ({})'.format(self.creator, self.role_name)\n else:\n return str(self.creator)\n\n\nclass Creator(TimeStampedModelMixin, models.Model):\n \"\"\"\n A person or a group/company/organisation that is responsible for making all\n or part of a book, play, movie, gig, etc.\n\n Get the things they've worked on:\n\n creator = Creator.objects.get(pk=1)\n\n # Just Publication titles:\n for publication in creator.publications.distinct():\n print(publication.title)\n\n # You can do similar to that to get lists of `events`, `movies` and,\n # `plays` the Creator was involved with.\n\n\n # Or Publications including the Creator and their role:\n for role in creator.publication_roles.all():\n print(role.publication, role.creator, role.role_name)\n\n # Similarly for Event roles:\n for role in creator.event_roles.all():\n print(role.event, role.creator, role.role_name)\n\n # And for Movie roles:\n for role in creator.movie_roles.all():\n print(role.movie, role.creator, role.role_name)\n\n # And for Play roles:\n for role in creator.play_roles.all():\n print(role.play, role.creator, role.role_name)\n \"\"\"\n\n KIND_CHOICES = (\n ('individual', 'Individual'),\n ('group', 'Group'),\n )\n\n name = models.CharField(max_length=255,\n help_text=\"e.g. 'Douglas Adams' or 'The Long Blondes'.\")\n\n name_sort = NaturalSortField(\n 'name', max_length=255, default='',\n help_text=\"Best for sorting groups. e.g. 'long blondes, the' or 'adams, douglas'.\")\n\n kind = models.CharField(max_length=20, choices=KIND_CHOICES,\n default='individual')\n\n class Meta:\n ordering = ('name_sort',)\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse('spectator:creators:creator_detail', kwargs={'pk':self.pk})\n\n @property\n def sort_as(self):\n \"Used by the NaturalSortField.\"\n if self.kind == 'individual':\n return 'person'\n else:\n return 'thing'\n\n def get_movies(self):\n \"\"\"\n A list of all the Movies the Creator worked on.\n Each one also has these properties:\n * `creator_roles` - QuerySet of MovieRole objects for this Creator.\n * `creator_role_names` - List of the role_names (if any this Creator\n had. Note, this could be empty if none of the roles have names.\n \"\"\"\n movies = []\n for movie in self.movies.distinct():\n movie.creator_roles = movie.roles.filter(creator=self)\n movie.creator_role_names = []\n for role in movie.creator_roles:\n if role.role_name:\n movie.creator_role_names.append(role.role_name)\n movies.append(movie)\n return movies\n\n def get_plays(self):\n \"\"\"\n A list of all the Plays the Creator worked on.\n Each one also has these properties:\n * `creator_roles` - QuerySet of PlayRole objects for this Creator.\n * `creator_role_names` - List of the role_names (if any this Creator\n had. Note, this could be empty if none of the roles have names.\n \"\"\"\n plays = []\n for play in self.plays.distinct():\n play.creator_roles = play.roles.filter(creator=self)\n play.creator_role_names = []\n for role in play.creator_roles:\n if role.role_name:\n play.creator_role_names.append(role.role_name)\n plays.append(play)\n return plays\n\n","sub_path":"spectator/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"538761777","text":"\"\"\"data_index contains all the quantities calculated by the compute functions.\"\"\"\n\ndata_index = {}\n\n\ndef register_compute_fun(\n name,\n label,\n units,\n units_long,\n description,\n dim,\n params,\n transforms,\n profiles,\n coordinates,\n data,\n **kwargs\n):\n \"\"\"Decorator to wrap a function and add it to the list of things we can compute.\n\n Parameters\n ----------\n name : str\n Name of the quantity. This will be used as the key used to compute the\n quantity in `compute` and its name in the data dictionary.\n label : str\n Title of the quantity in LaTeX format.\n units : str\n Units of the quantity in LaTeX format.\n units_long : str\n Full units without abbreviations.\n description : str\n Description of the quantity.\n dim : int\n Dimension of the quantity: 0-D (global qty), 1-D (local scalar qty),\n or 3-D (local vector qty).\n params : list of str\n Parameters of equilibrium needed to compute quantity, eg \"R_lmn\", \"Z_lmn\"\n transforms : dict\n Dictionary of keys and derivative orders [rho, theta, zeta] for R, Z, etc.\n profiles : list of str\n Names of profiles needed, eg \"iota\", \"pressure\"\n coordinates : str\n Coordinate dependency. IE, \"rtz\" for a function of rho, theta, zeta, or \"r\" for\n a flux function, etc.\n data : list of str\n Names of other items in the data index needed to compute qty\n\n Notes\n -----\n Should only list *direct* dependencies. The full dependencies will be built\n recursively at runtime using each quantities direct dependencies.\n \"\"\"\n deps = {\n \"params\": params,\n \"transforms\": transforms,\n \"profiles\": profiles,\n \"data\": data,\n \"kwargs\": list(kwargs.values()),\n }\n\n def _decorator(func):\n d = {\n \"label\": label,\n \"units\": units,\n \"units_long\": units_long,\n \"description\": description,\n \"fun\": func,\n \"dim\": dim,\n \"coordinates\": coordinates,\n \"dependencies\": deps,\n }\n data_index[name] = d\n return func\n\n return _decorator\n","sub_path":"desc/compute/data_index.py","file_name":"data_index.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532829585","text":"def reverse_ll(ll):\n \"\"\"\n Receive a LinkedList as an input and returns a reverse order LL\n\n Steps:\n 1. Each node needs to point aat the previous node\n 2. Head and tail pointers need to be flipped\n\n Cases:\n 1. If the ll is empty return the original that is passed in\n\n reverse_ll()\n \"\"\"\n\n # If LL is empty, return LL\n if ll.head is None:\n return ll\n\n # If LL has one node\n if ll.head is ll.tail:\n return ll\n \n # If LL has more than one node\n current = ll.head\n previous = None\n next_node = None\n while current is not None:\n # store a pointer to the current next value\n next_node = current.get_next()\n\n # switch current's next pointer to the previous\n current.set_next(previous)\n\n # increment logic\n previous = current\n current = next_node\n\nll.head, ll.tail = ll.tail, ll.head\n\nmy_ll = LinkedList()\nmy_ll.add_to_tail(1)\nmy_ll.add_to_tail(2)\nmy_ll.add_to_tail(3)\n\nreverse_ll(my_ll)\n ","sub_path":"reverse_ll.py","file_name":"reverse_ll.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"559136790","text":"# !/usr/bin/env python3.5\n# coding: utf-8\n\nimport smtplib\nimport hashlib\nimport datetime\nimport requests\nimport os.path\nfrom email.mime.application import MIMEApplication\nfrom email.mime.multipart import MIMEMultipart\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nimport xlwt\nimport io\n\n\ndef md5(arg):\n \"\"\"\n MD5加密\n \"\"\"\n md_5 = hashlib.md5()\n md_5.update(arg.encode('utf-8'))\n return md_5.hexdigest()\n\n\ndef send_mail(receivers, files):\n \"\"\"\n 邮件发送\n \"\"\"\n smtpserver = 'smtp.qq.com'\n username = 'xxxxxx'\n password = 'xxxxxxx'\n sender = 'xxxxxxxx'\n\n msg = MIMEMultipart()\n msg['Subject'] = '附件'\n msg['From'] = sender\n msg['To'] = ','.join(receivers)\n\n # 附件\n for file in files:\n last_index = file.rindex('/') + 1\n name = file[last_index:]\n xlsx = MIMEApplication(open(file, 'rb').read())\n xlsx.add_header('Content-Disposition', 'attachment', filename=name)\n msg.attach(xlsx)\n\n try:\n smtp = smtplib.SMTP()\n smtp.connect(smtpserver)\n smtp.login(username, password)\n smtp.sendmail(sender, ','.join(receivers), msg.as_string())\n smtp.quit()\n except smtplib.SMTPRecipientsRefused:\n print('Recipients Refused')\n except smtplib.SMTPAuthenticationError:\n print('Auth error')\n except smtplib.SMTPSenderRefused:\n print('Sender Refused')\n except smtplib.SMTPException as err:\n print(err.message)\n\n\ndef daily_settle(date):\n \"\"\"\n 拉取对账文件\n \"\"\"\n base = os.path.dirname(os.path.realpath(__file__))\n merchant_no = 'xxxxxxx'\n merchant_key = 'xxxxxxx'\n\n uri = 'http://xxxxxxxxxxx'\n\n params_dict = {'merchantNo': merchant_no, 'date': date}\n sign_str = '&'.join([key + '=' + value for key, value in sorted(params_dict.items())])\n sign_str = sign_str + '&key=' + merchant_key\n sign = md5(sign_str)\n sign = md5(sign.upper()) # 双重md5加密\n params_dict['sign'] = sign.upper()\n\n post_data = params_dict\n\n style = xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00')\n wb = xlwt.Workbook()\n ws = wb.add_sheet(date)\n file_name = '{0}.xls'.format(date)\n file_path = os.path.join(base, 'files', file_name)\n\n r = requests.post(uri, data=post_data)\n r.encoding = 'utf-8'\n resp_data = r.text\n\n buf = io.StringIO(resp_data)\n line = buf.readline()\n row = 0\n while line:\n doc = line.split(',')\n for i, v in enumerate(doc):\n ws.write(row, i, v, style)\n row += 1\n line = buf.readline()\n wb.save(file_path)\n return file_path\n\n\ndef do_myjob():\n \"\"\"\n 工作\n \"\"\"\n print('beging...')\n date_today = datetime.date.today()\n file_paths = []\n for i in range(-5,0):\n date = date_today + datetime.timedelta(i)\n date = datetime.datetime.strftime(date, '%Y%m%d')\n file_name = daily_settle(date)\n file_paths.append(file_name)\n tou = ['xxxxx', 'xxxxx']\n send_mail(tou, file_paths)\n\n\ndef main():\n \"\"\"\n main function\n \"\"\"\n sched = BlockingScheduler()\n sched.add_job(do_myjob, 'cron', day_of_week='tue', hour=11, minute=30)\n sched.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15073762","text":"import sys\nimport tensorflow as tf\nimport matplotlib\nfrom abc import abstractmethod\n# matplotlib.use('Agg')\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plot\n\n\nclass RNNLibrary:\n # train Parameters\n seq_length = 0\n input_dim = 0\n output_dim = 0\n batch_size = 36\n hypothesis = None\n cost = None\n optimizer = None\n train = None\n\n X = None\n Y = None\n\n test_loss = 0\n train_errors = []\n validation_errors = []\n epoch_cost = []\n\n @abstractmethod\n def init_rnn_library(self):\n pass\n\n def setParams(self, seq_length, input_dim, output_dim):\n self.seq_length = seq_length\n self.input_dim = input_dim\n self.output_dim = output_dim\n\n def setPlaceholder(self, seq_length=None, input_dim=None):\n self.X = tf.placeholder(tf.float32, [None, seq_length, input_dim])\n self.Y = tf.placeholder(tf.float32, [None, 1])\n\n def setHypothesis(self, hidden_dim, layer=1):\n def lstm_cell():\n cell = tf.contrib.rnn.BasicLSTMCell(\n num_units=hidden_dim, state_is_tuple=True, activation=tf.tanh, forget_bias=1.0, reuse=tf.get_variable_scope().reuse\n )\n return cell\n\n def layer_nomrm_lstm_cell():\n cell = tf.contrib.rnn.LayerNormBasicLSTMCell(\n num_units=hidden_dim, activation=tf.tanh, reuse=tf.get_variable_scope().reuse, dropout_keep_prob=1.0,\n )\n return cell\n\n multi_lstm_cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell() for _ in range(layer)], state_is_tuple=True)\n # multi_norm_cell = tf.nn.rnn_cell.MultiRNNCell([layer_nomrm_lstm_cell() for _ in range(layer)])\n\n # norm_cell = tf.nn.rnn_cell.MultiRNNCell([layer_nomrm_lstm_cell() for _ in range(layer)], state_is_tuple=True)\n # residual_norm_cell = tf.nn.rnn_cell.ResidualWrapper([layer_nomrm_lstm_cell() for _ in range(layer)], state_is_tuple=True)\n\n outputs, _states = tf.nn.dynamic_rnn(multi_lstm_cell, self.X, dtype=tf.float32)\n # outputs, _states = tf.nn.dynamic_rnn(multi_norm_cell, self.X, dtype=tf.float32)\n\n self.hypothesis = tf.contrib.layers.fully_connected(outputs[:, -1], self.output_dim, activation_fn=None)\n\n def setCostfunction(self):\n # self.cost = tf.reduce_sum(tf.square(self.hypothesis - self.Y)) # sum of the squares\n self.cost = tf.reduce_mean(tf.square(self.hypothesis - self.Y)) # sum of the squares\n\n\n def setOptimizer(self, learning_rate):\n self.optimizer = tf.train.AdamOptimizer(learning_rate)\n self.train = self.optimizer.minimize(self.cost)\n\n def showErrors(self, error_save_filename=None):\n # attr = 'o-' # 선 속성\n fig = plot.figure()\n x_label = ''\n y_label = ''\n\n plot.plot(self.train_errors, label='train loss')\n # plot.plot(self.validation_errors, label='validation loss')\n\n plot.xlabel(x_label)\n plot.ylabel(y_label)\n\n plot.savefig(error_save_filename)\n plot.legend(loc='upper left')\n plot.show()\n plot.close()\n\n def showValidationError(self, error_save_filename=None):\n # attr = 'o-' # 선 속성\n fig = plot.figure()\n x_label = ''\n y_label = ''\n\n plot.plot(self.validation_errors, label='train loss')\n # plot.plot(self.validation_errors, label='validation loss')\n\n plot.xlabel(x_label)\n plot.ylabel(y_label)\n\n plot.savefig(error_save_filename)\n plot.legend(loc='upper left')\n plot.show()\n plot.close()\n\n def learning(self, trainX=None, trainY=None, validationX=None, validationY=None, loop=None, total_epoch = 1, check_step=100, name=None):\n\n self.init_rnn_library()\n\n self.sess = tf.Session()\n init = tf.global_variables_initializer()\n self.sess.run(init)\n\n test_validation = self.sess.run(self.hypothesis, feed_dict={self.X: validationX})\n # rmse = tf.sqrt(tf.reduce_mean(tf.square(validationY - test_validation))) # 차의 제곱의 평균의 sqrt\n # validation = tf.reduce_sum(tf.square(validationY - test_validation))\n\n len_data = int(len(trainX)/self.batch_size)\n val_data = int(len(validationX)/len_data)\n\n train_loss = 0\n validation_loss = 0\n\n for epoch in range(1, total_epoch+1):\n print(str(epoch)+\" is doing ...\")\n # 276 = len_data it is 9936 / batch_size (36) = 276\n for i in range(len_data):\n self.sess.run(self.train, feed_dict={\n self.X: trainX[self.batch_size*i : self.batch_size*(i+1)],\n self.Y: trainY[self.batch_size*i : self.batch_size*(i+1)]\n })\n\n train_loss = self.sess.run(self.cost, feed_dict={\n self.X: trainX[self.batch_size*i : self.batch_size*(i+1)],\n self.Y: trainY[self.batch_size*i : self.batch_size*(i+1)]\n })\n\n validation_loss = self.sess.run(self.cost, feed_dict={\n self.X: validationX,\n self.Y: validationY\n })\n self.train_errors.append(train_loss)\n self.validation_errors.append(validation_loss)\n\n import csv\n path = '/Users/masinogns/PycharmProjects/ML/RNN'\n f = open(path+'/'+ name +'total_epoch_train_and_validation.csv', 'a', encoding='utf-8', newline='')\n wr = csv.writer(f)\n # Learning rate, the number of layer, hidden_dimension, loss\n wr.writerow([total_epoch, train_loss, validation_loss])\n f.close()\n\n print('\\nDone!\\n')\n\n def validation(self, validationX, validationY, validation_save_filename=None):\n test_validation = self.sess.run(self.hypothesis, feed_dict={self.X: validationX})\n # pre_loss = self.sess.run(self.cost, feed_dict={self.X: testY, self.Y: test_predict})\n # print(pre_loss)\n\n validation_rmse = tf.sqrt(tf.reduce_mean(tf.square(validationY - test_validation))) # 차의 제곱의 평균의 sqrt\n self.validation_loss = self.sess.run(validation_rmse)\n # rmse2 = tf.reduce_mean(tf.square(validationY - test_validation)) # sum of the squares\n # rmse3 = tf.reduce_sum(tf.square(validationY - test_validation)) # sum of the squares\n\n\n print(\"validation rmse: {}\".format(self.validation_loss))\n # print(\"validation mse: {}\".format(self.sess.run(rmse2)))\n # print(\"validation sse: {}\".format(self.sess.run(rmse3)))\n\n fig = plot.figure()\n # plot.plot(validationY, linestyle='-')\n # plot.plot(test_validation, linestyle='--')\n plot.plot(self.validation_loss, linestyle='--', label='validation')\n plot.xlabel(\"Validation loss\")\n # plot.ylabel(\"Invertor Output\")\n # plot.savefig(validation_save_filename)\n plot.show()\n plot.close()\n\n\n def prediction(self, testX, testY, predict_save_filename=None):\n test_predict = self.sess.run(self.hypothesis, feed_dict={self.X: testX})\n # pre_loss = self.sess.run(self.cost, feed_dict={self.X: testY, self.Y: test_predict})\n # print(pre_loss)\n\n test_rmse = tf.sqrt(tf.reduce_mean(tf.square(testY - test_predict))) # 차의 제곱의 평균의 sqrt\n rmse2 = tf.reduce_mean(tf.square(testY - test_predict)) # sum of the squares\n rmse3 = tf.reduce_sum(tf.square(testY - test_predict)) # sum of the squares\n\n self.test_loss = self.sess.run(test_rmse)\n\n print(\"test rmse: {}\".format(self.test_loss))\n # print(\"test mse: {}\".format(self.sess.run(rmse2)))\n # print(\"test sse: {}\".format(self.sess.run(rmse3)))\n\n fig = plot.figure()\n plot.plot(testY, linestyle='-')\n plot.plot(test_predict, linestyle='--')\n plot.xlabel(\"Test loss\")\n plot.ylabel(\"Invertor Output\")\n plot.savefig(predict_save_filename)\n plot.show()\n plot.close()\n","sub_path":"RNN/MyLib/lib_rnn.py","file_name":"lib_rnn.py","file_ext":"py","file_size_in_byte":7959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"49026362","text":"from libraries_and_data import library_datas\nfrom models import linear_model_3_levels\nimport random\nimport time\n\nrandom.seed(a=1234, version=2)\n\n# LN = LEVEL NIGUARDA\n# LP = LEVEL PADERNO\n# RP = RAIN PLUVIOMETERS\n# LC = LEVEL CANTU\n\n# SAVE HISTORY FILES\nnamed_tuple = time.localtime() # get struct_time\nname_file = time.strftime(\"%m_%d_%Y_%H_%M_%S\" + \"_best_step\", named_tuple)\n\n\nindex_pluviometer = 17\n\n# TRAIN DATA\n\ninput_rain = library_datas.get_data_by_years_and_type(\"RP\", 2015, 2017)\ninput_paderno = library_datas.get_data_by_years_and_type(\"LP\", 2015, 2017)\ninput_niguarda = library_datas.get_data_by_years_and_type(\"LN\", 2015, 2017)\ninput_cantu = library_datas.get_data_by_years_and_type(\"LC\", 2015, 2017)\noutput_niguarda = input_niguarda\n\ninput = [input_rain, input_paderno, input_niguarda]\n\ninput, output = library_datas.apply_step_diff(input, [output_niguarda])\n\ninput_rain = input[0]\ninput_paderno = input[1]\ninput_niguarda = input[2]\noutput_niguarda = output[0]\n\n# VALIDATION DATA\n\ninput_rain_val = library_datas.get_data_by_years_and_type(\"RP\", 2018, 2018)\ninput_paderno_val = library_datas.get_data_by_years_and_type(\"LP\", 2018, 2018)\ninput_niguarda_val = library_datas.get_data_by_years_and_type(\"LN\", 2018, 2018)\ninput_cantu_val = library_datas.get_data_by_years_and_type(\"LC\", 2018, 2018)\noutput_niguarda_val = input_niguarda_val\n\ninput_val = [input_rain_val, input_paderno_val, input_niguarda_val]\n\ninput_val, output_val = library_datas.apply_step_diff(input_val, [output_niguarda_val])\n\ninput_rain_val = input_val[0]\ninput_paderno_val = input_val[1]\ninput_niguarda_val = input_val[2]\noutput_niguarda_val = output_val[0]\n\n# CLEAN_DATA\n\ninput_rain, input_rain_val = library_datas.clean_data_with_val(input_rain, input_rain_val)\ninput_paderno, input_paderno_val = library_datas.clean_data_with_val(input_paderno, input_paderno_val)\ninput_niguarda, input_niguarda_val = library_datas.clean_data_with_val(input_niguarda, input_niguarda_val)\ninput_cantu, input_cantu_val = library_datas.clean_data_with_val(input_cantu, input_cantu_val)\noutput_niguarda, output_niguarda_val = library_datas.clean_data_with_val(output_niguarda, output_niguarda_val)\n\n\nfor i in range(16):\n\n step = 40 + i * 10\n\n # ADDITIONAL TIMESTEP CANTU\n\n input_cantu_try = library_datas.apply_step_diff_input(input_cantu, step)\n input_cantu_val_try = library_datas.apply_step_diff_input(input_cantu_val, step)\n input_rain_try = library_datas.additional_step_diff(input_rain[index_pluviometer], step)\n input_rain_val_try = library_datas.additional_step_diff(input_rain_val[index_pluviometer], step)\n input_paderno_try = library_datas.additional_step_diff(input_paderno, step)\n input_paderno_val_try = library_datas.additional_step_diff(input_paderno_val, step)\n input_niguarda_try = library_datas.additional_step_diff(input_niguarda, step)\n input_niguarda_val_try = library_datas.additional_step_diff(input_niguarda_val, step)\n output_niguarda_try = library_datas.additional_step_diff(output_niguarda, step)\n output_niguarda_val_try = library_datas.additional_step_diff(output_niguarda_val, step)\n\n # RANDOMIZE DATA\n\n data_val_try = list(zip(input_rain_val_try, input_paderno_val_try,\n input_niguarda_val_try, input_cantu_val_try, output_niguarda_val_try))\n random.shuffle(data_val_try)\n input_rain_val_try, input_paderno_val_try, input_niguarda_val_try, \\\n input_cantu_val_try, output_niguarda_val_try = zip(*data_val_try)\n\n input_rain_val_try = list(input_rain_val_try)\n input_paderno_val_try = list(input_paderno_val_try)\n input_niguarda_val_try = list(input_niguarda_val_try)\n input_cantu_val_try = list(input_cantu_val_try)\n output_niguarda_val_try = list(output_niguarda_val_try)\n\n data_try = list(zip(input_rain_try, input_paderno_try, input_niguarda_try, input_cantu_try, output_niguarda_try))\n random.shuffle(data_try)\n input_rain_try, input_paderno_try, input_niguarda_try, input_cantu_try, output_niguarda_try = zip(*data_try)\n\n input_rain_try = list(input_rain_try)\n input_paderno_try = list(input_paderno_try)\n input_niguarda_try = list(input_niguarda_try)\n input_cantu_try = list(input_cantu_try)\n output_niguarda_try = list(output_niguarda_try)\n\n # MODELS\n\n model = linear_model_3_levels.LinearModel()\n\n history = model.fit(x=[input_rain_try, input_paderno_try, input_niguarda_try, input_cantu_try], y=output_niguarda_try, epochs=100, verbose=2, validation_split=None,\n validation_data=([input_rain_val_try, input_paderno_val_try, input_niguarda_val_try, input_cantu_val_try], output_niguarda_val_try))\n\n f = open(\"./logs/best_step_model_3/\" + name_file + \".txt\", \"a\")\n f.write(\"STEP \" + str(step) + \" - RESULT : \" + str(min(history.history[\"val_loss\"])) + \"\\n\")\n f.close()\n\n\n","sub_path":"main_3_levels.py","file_name":"main_3_levels.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"484271197","text":"# Copyright 2020 The FedLearner Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# coding: utf-8\n\nimport time\nimport traceback\nimport json\nimport logging\nimport datetime\nfrom concurrent import futures\n\nimport grpc\nfrom fedlearner import settings\nfrom fedlearner.common import scheduler_service_pb2 as ss_pb\nfrom fedlearner.common import scheduler_service_pb2_grpc as ss_grpc\nfrom fedlearner.common import common_pb2 as common_pb\nfrom .db.db_model import Job, DataSourceMeta, ModelMeta,\\\n change_job_status, JOBSTATUS, \\\n ModelVersion, APPSTATUS\nfrom .kubernetes_client import K8sClient\nfrom .job.job_builder import JobConfigBuidler\nfrom .job.job_resource import PSResourceConfig, MasterResourceConfig,\\\n WorkerResourceConfig\nfrom .scheduler_service import SchedulerServer, SchedulerClient\n\n\ndef receive_job(request):\n logging.debug(\"In Platform Scheduler::_receive_job application_id = %s\",\n request.application_id)\n response = common_pb.Status()\n try:\n model_meta = ModelMeta.get(ModelMeta.name == request.model_uri)\n except Exception: #pylint: disable=W0703\n response.code = common_pb.StatusCode.STATUS_UNKNOWN_ERROR\n response.error_message = 'model_uri [%s] was not authorized.' \\\n % request.model_uri\n return response\n\n try:\n model_version = ModelVersion.get(\n (ModelVersion.commit == request.model_commit)\n and (ModelVersion.model_meta_id == model_meta.id))\n except Exception: #pylint: disable=W0703\n response.code = common_pb.StatusCode.STATUS_UNKNOWN_ERROR\n response.error_message = 'model_uri [%s] model_version [%s] ' \\\n 'was not authorized.' % \\\n (request.model_uri, request.model_commit)\n return response\n\n try:\n data_source = DataSourceMeta.get(\n DataSourceMeta.name == request.data_meta.data_source_name)\n except Exception: #pylint: disable=W0703\n response.code = common_pb.StatusCode.STATUS_UNKNOWN_ERROR\n response.error_message = 'data_source [%s] was not authorized.' \\\n % (request.data_meta.data_source_name)\n return response\n\n job = Job.create(name=request.name,\n description=request.description,\n role='Follower',\n application_id=request.application_id,\n status=JOBSTATUS.SUBMMITTED.value,\n model_version_id=model_version.id,\n serving_version=request.serving_version,\n data_source_id=data_source.id,\n cluster_spec=json.dumps(\n {'worker_replicas': request.pair_num}),\n group_list=json.dumps([]),\n create_time=datetime.datetime.now())\n if not job:\n response.code = common_pb.StatusCode.STATUS_UNKNOWN_ERROR\n response.error_message = 'job [%s] create failed.' % request.name\n return response\n response.code = common_pb.StatusCode.STATUS_SUCCESS\n return response\n\n\ndef send_job_to_follower(job):\n try:\n job = Job.select(Job, ModelMeta, ModelVersion, DataSourceMeta).\\\n join(ModelVersion).join(ModelMeta).\\\n join(DataSourceMeta,\n on=(Job.data_source_id == DataSourceMeta.id)).\\\n where(Job.id == job.id).get()\n\n group_list = json.loads(job.group_list)\n cluster_spec = json.loads(job.cluster_spec)\n request = ss_pb.TrainJobRequest()\n request.name = job.name\n request.application_id = job.application_id\n request.model_uri = job.model_version_id.model_meta_id.name\n request.model_commit = job.model_version_id.commit\n request.serving_version = job.serving_version\n request.data_meta.data_source_name = job.data_source_id.name\n request.pair_num = cluster_spec['worker_replicas']\n request.description = job.description\n\n for group_uuid in group_list:\n scheduler_client = SchedulerClient(group_uuid)\n scheduler_client.submit_train(request)\n logging.info(\n 'send job application_id[%s] model_uri [%s]'\n 'data_source[%s] pair_num[%d] to follower[%s]',\n request.application_id, request.model_uri,\n request.data_meta.data_source_name, request.pair_num,\n group_uuid)\n return True\n\n except Exception as e: #pylint: disable=W0703\n logging.error('send job to follower failed. detail is [%s]', repr(e))\n return False\n\n\nclass Scheduler(object):\n def __init__(self,\n token_path=settings.K8S_TOKEN_PATH,\n ca_path=settings.K8S_CAS_PATH,\n service_host=settings.KUBERNETES_SERVICE_HOST,\n service_port=settings.KUBERNETES_SERVICE_PORT):\n logging.info('KUBERNETES_SERVICE_HOST: [%s]', service_host)\n logging.info('KUBERNETES_SERVICE_PORT: [%s]', service_port)\n self._k8s_client = K8sClient(token_path=token_path,\n ca_path=ca_path,\n service_host=service_host,\n service_port=service_port)\n\n def _retrieval(self, wanted_status_list):\n retrieval_job = Job.select().where(Job.status << wanted_status_list)\n return retrieval_job\n\n def _get_checkpoint_path(self, model_uri, application_id):\n return settings.CHECKPOINT_PATH_PREFIX + '/' + model_uri\\\n + '/'+ application_id\n\n def _get_export_path(self, model_uri, version):\n return settings.EXPORT_PATH_PREFIX + '/' + model_uri + '/' + version\n\n def run(self, listen_port):\n self._server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n ss_grpc.add_SchedulerServicer_to_server(SchedulerServer(receive_job),\n self._server)\n self._server.add_insecure_port('[::]:%d' % listen_port)\n self._server.start()\n logging.info('Scheduler Server start on port[%d].', listen_port)\n while True:\n all_submitted_job = self._retrieval(\n wanted_status_list=[JOBSTATUS.SUBMMITTED.value])\n logging.info('[%d] submitted jobs found', len(all_submitted_job))\n for job in all_submitted_job:\n self.schedule_submitted_job(job)\n\n all_running_job = self._retrieval(\n wanted_status_list=[JOBSTATUS.RUNNING.value])\n logging.info('[%d] running jobs found', len(all_running_job))\n for job in all_running_job:\n self.schedule_running_job(job)\n\n all_killing_job = self._retrieval(wanted_status_list=[\n JOBSTATUS.KILLING.value, JOBSTATUS.FAILING.value\n ])\n logging.info('[%d] killing/failing jobs found',\n len(all_killing_job))\n for job in all_killing_job:\n self.schedule_killing_job(job)\n\n time.sleep(10)\n\n # deal with \"submitted\" job to start a k8s job\n def schedule_submitted_job(self, job):\n logging.info('process submitted job id[%d]', job.id)\n if not job.application_id:\n job.application_id = '{}-{}-{}'.format(\n job.name.replace('_', ''), str(job.id),\n datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\"))\n job.save()\n\n logging.info(job.role)\n try:\n if job.role == 'Leader':\n if not send_job_to_follower(job):\n logging.error(\n 'job [%d] change status to failed.'\n 'reason is [fail send job to follower]', job.id)\n change_job_status(job, JOBSTATUS.SUBMMITTED.value,\n JOBSTATUS.FAILED.value)\n return\n\n data_source = DataSourceMeta.select().where(\n DataSourceMeta.id == job.data_source_id).get()\n model = ModelVersion.select().join(ModelMeta).where(\n ModelVersion.id == job.model_version_id).get()\n\n checkpoint_path = self._get_checkpoint_path(\n model.model_meta_id.name, job.application_id)\n export_path = self._get_export_path(model.model_meta_id.name,\n job.serving_version)\n\n if not data_source or not model:\n logging.error(\n 'job [%d] change status to failed.'\n 'reason is [data_source or model is empty]', job.id)\n change_job_status(job, JOBSTATUS.SUBMMITTED.value,\n JOBSTATUS.FAILED.value)\n return\n\n builder = JobConfigBuidler(name=job.application_id,\n role=job.role,\n application_id=job.application_id)\n cluster_spec = json.loads(job.cluster_spec)\n builder.add_crd(\n PSResourceConfig(application_id=job.application_id,\n image=model.model_meta_id.image,\n replicas=cluster_spec.get('ps_replicas', 2)))\n builder.add_crd(\n MasterResourceConfig(application_id=job.application_id,\n data_path=data_source.path,\n image=model.model_meta_id.image,\n role=job.role.lower(),\n replicas=cluster_spec.get(\n 'master_replicas', 1)))\n builder.add_crd(\n WorkerResourceConfig(application_id=job.application_id,\n checkpoint_path=checkpoint_path,\n export_path=export_path,\n release_pkg='mnist',\n release_tag='0.0.2',\n image=model.model_meta_id.image,\n role=job.role.lower(),\n replicas=cluster_spec.get(\n 'worker_replicas', 2)))\n\n logging.info('create crd body content: %s namespace: %s',\n str(builder.build()), settings.K8S_NAMESPACE)\n self._k8s_client.create_crd(builder.build(),\n namespace=settings.K8S_NAMESPACE)\n change_job_status(job, JOBSTATUS.SUBMMITTED.value,\n JOBSTATUS.RUNNING.value)\n logging.info('job [%d] change status to running', job.id)\n return\n except Exception: #pylint: disable=W0703\n change_job_status(job, JOBSTATUS.SUBMMITTED.value,\n JOBSTATUS.FAILED.value)\n logging.error('job create failed on %s', traceback.format_exc())\n\n def schedule_running_job(self, job):\n logging.info('process running job id[%d]', job.id)\n try:\n response = self._k8s_client.get_crd_object(\n name=job.application_id, namespace=settings.K8S_NAMESPACE)\n if not response:\n logging.error('kubernetes get crd object failed.')\n change_job_status(job, JOBSTATUS.RUNNING.value,\n JOBSTATUS.FAILED.value)\n if response:\n app_state = response.get('status', {}).get('appState', None)\n if not app_state:\n logging.error(\n 'kubernetes get crd object app [%d] status failed.',\n job.id)\n return\n\n job.k8s_status = app_state\n logging.info('job [%d] get kubernetes applicaiton status [%s]',\n job.id, app_state)\n job.save()\n if job.k8s_status == APPSTATUS.FAILED.value:\n change_job_status(job, JOBSTATUS.RUNNING.value,\n JOBSTATUS.FAILED.value)\n elif job.k8s_status == APPSTATUS.SHUTDOWN.value:\n change_job_status(job, JOBSTATUS.RUNNING.value,\n JOBSTATUS.KILLED.value)\n elif job.k8s_status == APPSTATUS.COMPELTE.value:\n change_job_status(job, JOBSTATUS.RUNNING.value,\n JOBSTATUS.SUCCESS.value)\n\n except Exception as e: #pylint: disable=W0703\n logging.error('query running job failed on %s',\n traceback.format_exc())\n\n def schedule_killing_job(self, job):\n logging.info('process killing job id[%d]', job.id)\n try:\n self._k8s_client.delete_crd(name=job.application_id,\n namespace=settings.K8S_NAMESPACE)\n change_job_status(job, JOBSTATUS.KILLING.value,\n JOBSTATUS.KILLED.value)\n except Exception as e: #pylint: disable=W0703\n logging.error('delete job failed on %s', repr(e))\n","sub_path":"fedlearner/scheduler/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":13913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"456253746","text":"\"\"\"\nCopyright 2014 Rackspace\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nimport mock\nimport json\n\nfrom cloudcafe.identity.v3.common.catalog.models.responses import (\n Catalog, Links, Endpoint, Endpoints, Service)\n\n\nclass Mock(object):\n ROOT_TAG = 'endpoints'\n endpoints = 'mocked stuff'\n\n @classmethod\n def _dict_to_obj(cls, data):\n return \"mocked stuff\"\n\n @classmethod\n def _xml_ele_to_obj(cls, data):\n return \"mocked stuff\"\n\n @classmethod\n def _list_to_obj(cls, data):\n return cls\n\n\nclass CatalogResponseTests(unittest.TestCase):\n \"\"\"\n Metatests for v3 Catalog response model\n \"\"\"\n RESPONSES = 'cloudcafe.identity.v3.common.catalog.models.responses'\n\n @mock.patch(RESPONSES+'.Links', Mock)\n @mock.patch(RESPONSES+'.Catalog', Mock)\n def test_json_to_obj(self):\n \"\"\"\n test to verify Catalog.json_to_obj() can convert a JSON\n representation of a Catalog to a Catalog object\n \"\"\"\n # ARRANGE\n catalog_dict = {\n 'catalog': 'test_catalog',\n 'links': 'test_links'\n }\n\n catalog_json = json.dumps(catalog_dict)\n\n expected_catalog_obj = Catalog(catalog='mocked stuff',\n links='mocked stuff')\n # ACT\n catalog_resp_obj = Catalog._json_to_obj(catalog_json)\n # ASSERT\n self.assertEqual(expected_catalog_obj, catalog_resp_obj)\n\n @mock.patch(RESPONSES+'.Service', Mock)\n def test_dict_to_obj(self):\n \"\"\"\n test to verify Catalog.json_to_obj() can convert a JSON\n representation of a Catalog to a Catalog object\n \"\"\"\n # ARRANGE\n catalog_dict = {\n 'catalog': 'test_catalog',\n 'links': 'test_links'\n }\n expected_catalog_obj = ['mocked stuff', 'mocked stuff']\n # ACT\n catalog_resp_obj = Catalog._dict_to_obj(catalog_dict)\n # ASSERT\n self.assertEqual(expected_catalog_obj, catalog_resp_obj)\n\n\nclass LinksResponseTests(unittest.TestCase):\n \"\"\"\n Metatests for v3 Links response model\n \"\"\"\n def test_dict_to_obj(self):\n \"\"\"\n test to verify Links.dict_to_obj() can convert a dictionary\n representation of a Links to a Links object\n \"\"\"\n # ARRANGE\n links_dict = {\n 'self': 'test_self'\n }\n expected_links_obj = Links(self_='test_self')\n # ACT\n links_resp_obj = Links._dict_to_obj(links_dict)\n # ASSERT\n self.assertEqual(expected_links_obj, links_resp_obj)\n\n\nclass ServiceResponseTests(unittest.TestCase):\n \"\"\"\n Metatests for v3 Service response model\n \"\"\"\n RESPONSES = 'cloudcafe.identity.v3.common.catalog.models.responses'\n\n @mock.patch(RESPONSES+'.Endpoints', Mock)\n def test_dict_to_obj(self):\n \"\"\"\n test to verify Service.dict_to_obj() can convert a dictionary\n representation of a Service to a Service object\n \"\"\"\n # ARRANGE\n service_dict = {\n 'endpoints': 'test_endpoints',\n 'type': 'test_type'\n }\n expected_service_obj = Service(endpoints='mocked stuff',\n type='test_type')\n # ACT\n service_resp_obj = Service._dict_to_obj(service_dict)\n # ASSERT\n self.assertEqual(expected_service_obj, service_resp_obj)\n\n\nclass EndpointResponseTests(unittest.TestCase):\n \"\"\"\n Metatests for v3 Endpoint response model\n \"\"\"\n def test_dict_to_obj(self):\n \"\"\"\n test to verify Endpoint.dict_to_obj() can convert a dictionary\n representation of a Endpoint to a Endpoint object\n \"\"\"\n # ARRANGE\n endpoint_dict = {\n 'interface': 'test_interface',\n 'id': 'test_id',\n 'region': 'test_region',\n 'url': 'test_url'\n }\n expected_endpoint_obj = Endpoint(interface='test_interface',\n id='test_id',\n region='test_region',\n url='test_url')\n # ACT\n endpoint_resp_obj = Endpoint._dict_to_obj(endpoint_dict)\n # ASSERT\n self.assertEqual(expected_endpoint_obj, endpoint_resp_obj)\n\n\nclass EndpointsResponseTests(unittest.TestCase):\n \"\"\"\n Metatests for v3 Endpoints response model\n \"\"\"\n RESPONSES = 'cloudcafe.identity.v3.common.catalog.models.responses'\n ROOT_TAG = 'endpoints'\n\n @mock.patch(RESPONSES+'.Endpoint', Mock)\n def test_list_to_obj(self):\n \"\"\"\n test to verify Endpoints.list_to_obj() can convert a list\n representation of Endpoints to an Endpoints object\n \"\"\"\n # ARRANGE\n endpoints_list = ['test_endpoint_1',\n 'test_endpoint_2',\n 'test_endpoint_3']\n expected_endpoints_obj = Endpoints(endpoints=['mocked stuff',\n 'mocked stuff',\n 'mocked stuff'])\n # ACT\n endpoints_resp_obj = Endpoints._list_to_obj(endpoints_list)\n # ASSERT\n self.assertEqual(expected_endpoints_obj, endpoints_resp_obj)\n\n @mock.patch(RESPONSES+'.Endpoint', Mock)\n def test_json_to_obj(self):\n \"\"\"\n test to verify Endpoints.list_to_obj() can convert a list\n representation of Endpoints to an Endpoints object\n \"\"\"\n # ARRANGE\n endpoints_list = ['test_endpoint_1',\n 'test_endpoint_2',\n 'test_endpoint_3']\n endpoints_dict = {\n self.ROOT_TAG: endpoints_list}\n endpoints_json = json.dumps(endpoints_dict)\n expected_endpoints_obj = Endpoints(endpoints=['mocked stuff',\n 'mocked stuff',\n 'mocked stuff'])\n # ACT\n endpoints_resp_obj = Endpoints._json_to_obj(endpoints_json)\n # ASSERT\n self.assertEqual(expected_endpoints_obj, endpoints_resp_obj)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"metatests/identity/v3/common/catalog/models/test_catalog_responses.py","file_name":"test_catalog_responses.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"347682084","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom drf_yasg.openapi import Parameter, IN_PATH\nfrom rest_framework import generics\nfrom .serializers import *\nfrom .models import *\nfrom account.permissions import IsStaffBlogModerator\nfrom rest_framework import views\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom drf_yasg.utils import swagger_auto_schema\nfrom job.views import ErrorResponse, MessageResponse, sample_message_response, sample_error_response\nfrom rest_framework.filters import OrderingFilter\nfrom django.utils.decorators import method_decorator\nfrom drf_yasg import openapi\n\n\nclass TileCreateView(views.APIView):\n permission_classes = [IsStaffBlogModerator]\n\n @swagger_auto_schema(\n request_body=TileSerializer,\n responses={\n 201: \"id: 1 itd.\",\n 400: 'Błędy walidacji (np. brak jakiegoś pola)'\n }\n )\n def post(self, request):\n serializer = TileSerializer(data=request.data)\n if serializer.is_valid():\n instance = serializer.create(serializer.validated_data)\n return Response({\"id\": instance.pk}, status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)\n\n\nclass TileView(views.APIView):\n permission_classes = [IsStaffBlogModerator]\n\n @swagger_auto_schema(\n manual_parameters=[\n Parameter('tile_id', IN_PATH, type='integer')\n ],\n responses={\n 200: '\"message\": \"Kafelek o podanym id został zaktualizowany\"',\n 403: 'Forbidden - no permissions',\n 404: '\"error\": \"Nie znaleziono kafelka o podanym id\"'\n }\n )\n def put(self, request, tile_id):\n try:\n instance = Tile.objects.get(id=tile_id)\n serializer = TileSerializer(instance, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.update(instance, serializer.validated_data)\n response_data = {\"message\": \"Kafelek o podanym id został zaktualizowany\"}\n return Response(response_data, status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)\n except ObjectDoesNotExist:\n return ErrorResponse(\"Nie znaleziono kafelka o podanym id\", status.HTTP_404_NOT_FOUND)\n\n @swagger_auto_schema(\n manual_parameters=[\n Parameter('tile_id', IN_PATH, type='integer'),\n ],\n responses={\n 200: sample_message_response('Kafelek został pomyślnie usunięty'),\n 404: sample_message_response(\"Nie znaleziono kafelka o podanym id\")\n }\n )\n def delete(self, request, tile_id):\n try:\n instance = Tile.objects.get(pk=tile_id)\n except ObjectDoesNotExist:\n return ErrorResponse(\"Nie znaleziono kafelka o podanym id\", status.HTTP_404_NOT_FOUND)\n instance.delete()\n return MessageResponse(\"Kafelek został pomyślnie usunięty\")\n\n\n@method_decorator(name='get', decorator=swagger_auto_schema(\n operation_description=\"Zwraca listę kafelków\"\n))\nclass TileListView(generics.ListAPIView):\n permission_classes = [AllowAny]\n serializer_class = TileSerializer\n filter_backends = [OrderingFilter]\n ordering = ['pk']\n\n def get_queryset(self):\n queryset = Tile.objects.prefetch_related('photo_layer').all()\n return queryset\n\n\nclass TilePhotoView(views.APIView):\n permissions_classes = [IsStaffBlogModerator]\n\n @swagger_auto_schema(\n operation_description=\"Posts photo to be used in Tile.\",\n\n manual_parameters=[\n openapi.Parameter(\n in_='header',\n name='Content-Type',\n type=openapi.TYPE_STRING,\n default='application/x-www-form-urlencoded'\n ),\n openapi.Parameter(\n name='photo',\n in_='form-data',\n type=openapi.TYPE_FILE\n ),\n openapi.Parameter('tile_id', openapi.IN_PATH, type='integer',\n description='Integer będący id danego kafelka')\n ],\n responses={\n '200': 'Zdjęcie dodano pomyślnie',\n '400': 'Upewnij się, że form key to \"photo\" / Błędy walidacji',\n '403': \"Nie masz uprawnień do wykonania tej czynności\",\n '404': 'Nie znaleziono Kafelka. Upewnij się, że uwzględniono tile_id w url-u'\n }\n )\n def post(self, request, tile_id):\n try:\n tile = Tile.objects.get(pk=tile_id)\n except Tile.DoesNotExist:\n return ErrorResponse(\"Nie znaleziono kafelka o podanym id\", status.HTTP_404_NOT_FOUND)\n\n try:\n delete_previous_photo(tile)\n tile.photo = request.FILES['photo']\n except MultiValueDictKeyError:\n return ErrorResponse('Nie znaleziono pliku. Upewnij się, że został on załączony pod kluczem photo'\n , status.HTTP_400_BAD_REQUEST)\n\n tile.save()\n response_data = {\"id\": tile.id, \"attachment_url\": tile.photo.url}\n return Response(response_data, status.HTTP_200_OK)","sub_path":"src/tiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"533992533","text":"#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this\n# software and associated documentation files (the \"Software\"), to deal in the Software\n# without restriction, including without limitation the rights to use, copy, modify,\n# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\nimport boto3, json, time, os, logging, botocore, uuid\nfrom crhelper import CfnResource\nfrom botocore.exceptions import ClientError\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nlogging.getLogger('boto3').setLevel(logging.CRITICAL)\nlogging.getLogger('botocore').setLevel(logging.CRITICAL)\nsession = boto3.Session()\n\nhelper = CfnResource(json_logging=False, log_level='INFO', boto_level='CRITICAL', sleep_on_delete=15)\n\n@helper.create\n@helper.update\n# This module perform the following:\n# 1. attempt to create stackset if one does not exist\n# 2. attempt to deploy stackset instance to target accounts\ndef create(event, context):\n logger.info(json.dumps(event))\n try:\n firstLaunch = False\n stackSetName = os.environ['stackSetName']\n stackSetUrl = os.environ['stackSetUrl']\n newRelicAccId = os.environ['newRelicAccId']\n newRelicSecret = os.environ['newRelicSecret']\n newRelicStackSNS = os.environ['newRelicStackSNS']\n managementAccountId = context.invoked_function_arn.split(\":\")[4]\n cloudFormationClient = session.client('cloudformation')\n regionName = context.invoked_function_arn.split(\":\")[3]\n cloudFormationClient.describe_stack_set(StackSetName=stackSetName)\n logger.info('Stack set {} already exist'.format(stackSetName))\n helper.Data.update({\"result\": stackSetName})\n \n except Exception as describeException:\n logger.info('Stack set {} does not exist, creating it now.'.format(stackSetName))\n cloudFormationClient.create_stack_set(\n StackSetName=stackSetName,\n Description='Adds in New Relic integration to your aws accounts. Launch as Stack Set in your Control Tower landing zone management account.',\n TemplateURL=stackSetUrl,\n Parameters=[\n {\n 'ParameterKey': 'NewRelicAccountNumber',\n 'ParameterValue': newRelicAccId,\n 'UsePreviousValue': False,\n 'ResolvedValue': 'string'\n }\n ],\n Capabilities=[\n 'CAPABILITY_NAMED_IAM'\n ],\n AdministrationRoleARN='arn:aws:iam::' + managementAccountId + ':role/service-role/AWSControlTowerStackSetRole',\n ExecutionRoleName='AWSControlTowerExecution')\n \n try:\n result = cloudFormationClient.describe_stack_set(StackSetName=stackSetName)\n firstLaunch = True\n logger.info('StackSet {} deployed'.format(stackSetName))\n except cloudFormationClient.exceptions.StackSetNotFoundException as describeException:\n logger.error('Exception getting new stack set, {}'.format(describeException))\n raise describeException\n \n try:\n if firstLaunch and len(os.environ['seedAccounts']) > 0 :\n logger.info(\"New accounts : {}\".format(os.environ['seedAccounts']))\n accountList = os.environ['seedAccounts'].split(\",\")\n snsClient = session.client('sns')\n messageBody = {}\n messageBody[stackSetName] = { 'target_accounts': accountList, 'target_regions': [regionName] }\n try:\n snsResponse = snsClient.publish(\n TopicArn=newRelicStackSNS,\n Message = json.dumps(messageBody))\n \n logger.info(\"Queued for stackset instance creation: {}\".format(snsResponse))\n except Exception as snsException:\n logger.error(\"Failed to send queue for stackset instance creation: {}\".format(snsException))\n else:\n logger.info(\"No additional StackSet instances requested\")\n except Exception as create_exception:\n logger.error('Exception creating stack instance with {}'.format(create_exception))\n raise create_exception\n \n helper.Data.update({\"result\": stackSetName})\n \n # To return an error to cloudformation you raise an exception:\n if not helper.Data.get(\"result\"):\n raise ValueError(\"Error occured during solution onboarding\")\n \n return None #Generate random ID\n\n@helper.delete\n# This module perform the following:\n# 1. attempt to delete stackset instances\n# 2. attempt to delete stackset\ndef delete(event, context):\n logger.info(\"Delete StackSet Instances\")\n deleteWaitTime = (int(context.get_remaining_time_in_millis()) - 100)/1000\n deleteSleepTime = 30\n try:\n stackSetName = os.environ['stackSetName']\n stackSetUrl = os.environ['stackSetUrl']\n managementAccountId = context.invoked_function_arn.split(\":\")[4]\n cloudFormationClient = session.client('cloudformation')\n regionName = context.invoked_function_arn.split(\":\")[3]\n cloudFormationClient.describe_stack_set(StackSetName=stackSetName)\n logger.info('Stack set {} exist'.format(stackSetName))\n\n paginator = cloudFormationClient.get_paginator('list_stack_instances')\n pageIterator = paginator.paginate(StackSetName= stackSetName)\n stackSetList = []\n accountList = []\n regionList = []\n for page in pageIterator:\n if 'Summaries' in page:\n stackSetList.extend(page['Summaries'])\n for instance in stackSetList:\n accountList.append(instance['Account'])\n regionList.append(instance['Region'])\n regionList = list(set(regionList))\n accountList = list(set(accountList))\n logger.info(\"StackSet instances found in region(s): {}\".format(regionList))\n logger.info(\"StackSet instances found in account(s): {}\".format(accountList))\n \n try:\n if len(accountList) > 0:\n response = cloudFormationClient.delete_stack_instances(\n StackSetName=stackSetName,\n Accounts=accountList,\n Regions=regionList,\n RetainStacks=False)\n logger.info(response)\n \n status = cloudFormationClient.describe_stack_set_operation(\n StackSetName=stackSetName,\n OperationId=response['OperationId'])\n \n while status['StackSetOperation']['Status'] == 'RUNNING' and deleteWaitTime>0:\n time.sleep(deleteSleepTime)\n deleteWaitTime=deleteWaitTime-deleteSleepTime\n status = cloudFormationClient.describe_stack_set_operation(\n StackSetName=stackSetName,\n OperationId=response['OperationId'])\n logger.info(\"StackSet instance delete status {}\".format(status))\n \n try:\n response = cloudFormationClient.delete_stack_set(StackSetName=stackSetName)\n logger.info(\"StackSet template delete status {}\".format(response))\n except Exception as stackSetException:\n logger.warning(\"Problem occured while deleting, StackSet still exist : {}\".format(stackSetException))\n \n except Exception as describeException:\n logger.error(describeException)\n\n except Exception as describeException:\n logger.error(describeException)\n return None\n \n return None #Generate random ID\ndef lambda_handler(event, context):\n logger.info(json.dumps(event))\n try:\n if 'RequestType' in event: helper(event, context)\n except Exception as e:\n helper.init_failure(e)","sub_path":"functions/source/onboarding/onboarding.py","file_name":"onboarding.py","file_ext":"py","file_size_in_byte":8581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"545895958","text":"class Solution(object):\r\n def twoSum(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n # in the mid of constructing the dictionary we can chek also ....that can reduce some time complexity\r\n # didnt understand how when same key has diff value works\r\n dict_nums = dict(zip(nums, list(range(len(nums)))))\r\n for i in range(0,len(nums)):\r\n if target-nums[i] in dict_nums:\r\n if dict_nums[target-nums[i]]!= i:\r\n return [i,dict_nums[target-nums[i]]]\r\n ","sub_path":"qn1_dictionarydoubt.py","file_name":"qn1_dictionarydoubt.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"165129961","text":"import discord\nimport asyncio\nimport skill_adapter\nimport os\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n global uid\n uid = \"<@\"+client.user.id+\">\"\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('======')\n await skill_adapter.load_skills()\n\n@client.event\nasync def on_message(message):\n print(str(message.content))\n if (client.user in message.mentions or message.channel.is_private) and client.user != message.author:\n phrase = message.content.lstrip(uid)\n print(list(skill_adapter.engine.determine_intent(phrase)))\n intents = sorted(\n skill_adapter.engine.determine_intent(phrase),\n key = lambda x: x[\"confidence\"])\n print(\"Message recieved. Responding\")\n print(intents)\n if len(intents) < 1:\n await client.send_message(message.channel, \"I'm sorry, I couldn't understand you\")\n else:\n intent = intents[0]\n skill = skill_adapter.skills[intent.pop(\"intent_type\")]\n intent.pop(\"target\")\n intent.pop(\"confidence\")\n await client.send_message(message.channel, str(await skill.parse(message, **intent)))\n\ndef main():\n client.run(os.environ[\"DISCORD_KEY\"])\n\nif __name__=='__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"184134689","text":"while 1:\n N = int(input())\n if N == 0:\n break\n li = list(map(int, input().split()))\n j = m = 0\n for n in li:\n if n == 1:\n j += 1\n else:\n m += 1\n print(f\"Mary won {m} times and John won {j} times\")\n","sub_path":"src/BaekJoon/Simple_Implementation/P5751.py","file_name":"P5751.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"47547748","text":"#!/usr/bin/env python\n######################################################################\n# Author: Pourya Shirazian \n# \n# SDAccel Benchmarking System Frontend\n######################################################################\n__version__ = \"0.3\"\nimport getpass\n\n\nfrom classes.taskmanager import *\nfrom classes.task_parallelrun import *\nfrom classes.taskrdi_boardfarm import *\nfrom classes.taskrdi_runsdaccel import *\nfrom classes.taskrdi_compilehost import *\nfrom classes.task_combineresults import *\nfrom optparse import OptionParser\nfrom os.path import expanduser\n\n# print some examples to highlight the correct usecase\ndef print_example():\n print('Example: gauntlet.py -f smith-waterman.yml')\n\n\ndef print_pipeline(start = 'START', stop = 'FINISH'):\n print(\"You selected the following pipeline:\\n\")\n pipeline=('START', 'TCL', 'COMPILE', 'SYNTHESIS', 'PACKAGE', 'SELECT', 'TRANSFER', 'EXEC', 'REPORT', 'FINISH')\n\n doprint = False\n for stage in pipeline:\n if(stage == start):\n doprint = True\n\n if doprint:\n if stage == 'FINISH' or stage == stop:\n sys.stdout.write(stage)\n else:\n sys.stdout.write(\"%s --> \" %stage)\n\n if stage == stop:\n print(\"\\n\")\n return\n print(\"\\n\")\n\n\n\n# find kernel inside a file\ndef find_kernel_func_infile(strFullKernelFP, strKernelName):\n if not os.path.isfile(strFullKernelFP):\n log_error(\"Kernel file %s not found\" %strFullKernelFP)\n return False\n\n with open(strFullKernelFP, \"r\") as f:\n searchlines = f.readlines()\n\n for i, line in enumerate(searchlines):\n if strKernelName in line:\n return True\n return False\n\n\ndef validate_input_commands(commands):\n log_info('validating input commands')\n\n ##check input file\n if commands.boardfarm_only:\n if commands.filename is None:\n log_error(\"The boardonly command requires a valid input file.\")\n return False\n\n n_do_flags = 0\n if commands.do_gen_tcl:\n n_do_flags += 1\n if commands.do_compile_host:\n n_do_flags += 1\n if commands.do_package_system:\n n_do_flags += 1\n if n_do_flags > 1:\n log_error(\"commands starting with do... are mutually exclusive\")\n return False\n return True\n\n\ndef validate_input_project_config(projectcfg, commands):\n log_info('validating input project configuration')\n\n ## define mandatory keys\n mandatory_keys = []\n if commands.boardfarm_only:\n mandatory_keys = [\"name\", \"src\", \"pkg\", \"kernel_names\", \"accelerators\", \"sys_path_root\"]\n else:\n mandatory_keys = [\"name\", \"src\", \"kernel_names\", \"accelerators\", \"sys_path_root\"]\n checklist = mandatory_keys\n\n for k, v in projectcfg.__dict__.iteritems():\n if k in checklist:\n checklist.remove(k)\n\n if len(checklist) > 0:\n log_error(\"The following mandatory attributes are not set in your input yml file: %s\" %checklist)\n return False\n\n # using system root generate all the other paths\n if projectcfg.sys_path_root is None:\n log_warn(\"sys_path_root attribute is not set in project file. The default path is %s\" %settings.storage[\"dir_default_sys_ws\"])\n\n # Check the path to source code\n if not os.path.isdir(projectcfg.src):\n log_error('The src path to source code is not valid!')\n return False\n\n # Check the kernel source file\n if not projectcfg.src.endswith('/'):\n projectcfg.src += '/'\n\n\n # Check if the kernel function names exist in the file\n count_errors = 0\n\n finder = FindFiles()\n cl_source_absolute_filepaths = finder.list_opencl_source_file(projectcfg.src)\n\n for kernel in projectcfg.kernel_names:\n fp = which_file_has_this(cl_source_absolute_filepaths, kernel)\n if fp is None:\n log_error(\"Unable to find kernel %s\" %kernel)\n count_errors += 1\n if(count_errors > 0):\n return False\n\n # Check accelerators\n bf = BoardFarm(settings.storage[\"file_boardfarm\"])\n groups = bf.device_groups()\n for acc in projectcfg.accelerators:\n if not (acc in groups):\n log_error(\"Requested device or group: %s is not recognized\" %acc)\n return False\n\n return True\n\n\ndef policy_fs_get_writeable_path(strAppendName):\n\n strFullPath = \"\"\n if isWritable(expanduser(\"~\")):\n strFullPath = expanduser(\"~\") + \"/\" + strAppendName\n elif isWritable(\"/tmp/\"):\n strFullPath = \"/tmp/\" + strAppendName\n else:\n log_error(\"I don't have write permission! I tried: [%s, %s]\" %(expanduser(\"~\"), \"/tmp/\"))\n return strFullPath\n\n\ndef main():\n parser = OptionParser()\n parser.add_option(\"-f\", \"--file\", action=\"store\", dest=\"filename\", help=\"The fullpath to the projectcfg project.yml file that describes the projectcfg\");\n parser.add_option(\"-b\", \"--boardfarm-only\", action=\"store_true\", dest=\"boardfarm_only\", default=False, help=\"execute on boardfarm only. The src and pkg paths are supplied in input file.\");\n parser.add_option(\"-d\", \"--devices\", action=\"store_true\", dest=\"list_devices_by_group\", default=False, help=\"prints the list of available accelerator devices based on group name\");\n parser.add_option(\"-r\", \"--run-level\", action=\"store\", dest=\"rdi_run_level\", default=5, help=\"sets the default run-level for rdi regression system\");\n parser.add_option(\"-g\", \"--group\", action=\"store\", dest=\"device_group_name\", default=\"all\", help=\"sets the device group-name for the list of available accelerator devices. default is all\");\n parser.add_option(\"-n\", \"--nodes\", action=\"store_true\", dest=\"list_nodes\", default=False, help=\"prints the list of available machine names on the board farm\");\n parser.add_option(\"-u\", \"--update\", action=\"store_true\", dest=\"update_boardfarm_yml\", default=False, help=\"updates the boardfarm.yml file by visiting all nodes in the boardfarm\");\n parser.add_option(\"-v\", \"--verbose\", action=\"store_true\", dest=\"verbose\", default=False, help=\"sets verbose to true to include detailed logs\");\n parser.add_option(\"--gen-tcl\", action=\"store_true\", dest=\"do_gen_tcl\", default=False, help=\"generates tcl script and returns with no execution\");\n parser.add_option(\"--compile-host\", action=\"store_true\", dest=\"do_compile_host\", default=False, help=\"generate tcl script to compile host only\");\n parser.add_option(\"--package-system\", action=\"store_true\", dest=\"do_package_system\", default=False, help=\"generate tcl script to compile and build the FPGA package\");\n parser.add_option(\"--version\", action=\"store_true\", dest=\"version\", default=False, help=\"prints version information\");\n\n ##init global vars\n settings.init()\n settings.storage[\"debug\"] = True\n settings.storage[\"user\"] = getpass.getuser()\n settings.storage[\"dir_root\"] = os.path.dirname(os.path.realpath(__file__)) + \"/\"\n settings.storage[\"dir_data\"] = settings.storage[\"dir_root\"] + \"data/\"\n settings.storage[\"file_boardfarm\"] = settings.storage[\"dir_data\"] + \"boardfarm.yml\"\n\n #logfile should be stored in user's home space\n settings.storage[\"file_log_name\"] = \"gauntlet_backend.log\"\n settings.storage[\"dir_default_sys_ws\"] = \"/proj/picasso/pourya/benchpipe_ws/workspace/\"\n\n #log file path\n strLogFilePath = policy_fs_get_writeable_path(settings.storage[\"file_log_name\"])\n if len(strLogFilePath) == 0:\n sys.exit(-1)\n\n ##init log system\n settings.storage[\"file_log_path\"] = strLogFilePath\n init_log_system(settings.storage[\"file_log_path\"], True)\n\n\n\t#read the user projectcfg arguments, print help in case\n print(\"======================================================================================================\")\n print(\"\\tXilinx SDAccel BenchPipe\")\n print(\"\\tReport comments to: Pourya.Shirazian@xilinx.com\")\n print(\"\\tBoardfarm: %s\" %settings.storage[\"file_boardfarm\"])\n print(\"\\tApplication Dir: %s\" %settings.storage[\"dir_root\"])\n print(\"\\tUser: %s\" %settings.storage[\"user\"])\n print(\"\\tLog: %s\" %settings.storage[\"file_log_path\"])\n print(\"======================================================================================================\")\n (commands, args) = parser.parse_args(sys.argv)\n\n # print usage and example\n if len(sys.argv) < 2:\n parser.print_help()\n print_example()\n sys.exit()\n\n #print version\n if commands.version:\n print(\"Version %s\" %__version__)\n sys.exit()\n\n # Write user commands to file\n strLastCmdPath = policy_fs_get_writeable_path('gauntlet_last_command.yml')\n if len(strLastCmdPath) > 0:\n with open(strLastCmdPath, 'w') as outfile:\n outfile.write( yaml.dump(commands, default_flow_style = False))\n\n # Check if the boardfarm exists\n if not os.path.isfile(settings.storage[\"file_boardfarm\"]):\n log_error(\"Boardfarm file not found\")\n sys.exit()\n\n\n # validate projectcfg commands\n if not validate_input_commands(commands):\n log_error('Input commands were invalid please fix according to the log')\n sys.exit()\n\n # Check if a device query is made\n if commands.list_devices_by_group:\n log_info(\"Listing devices by group name\")\n bf = BoardFarm(settings.storage[\"file_boardfarm\"])\n bf.list_devices_by_group(commands.device_group_name)\n sys.exit()\n\n # Check if command is list nodes\n if commands.list_nodes:\n log_info(\"Listing machine nodes in boardfarm\")\n bf = BoardFarm(settings.storage[\"file_boardfarm\"])\n bf.list_machine_nodes()\n sys.exit()\n\n if commands.update_boardfarm_yml:\n log_info(\"Updating boardfarm.yml file. This process make take longer than usual\")\n sys.exit()\n\n\n # Check if the projectcfg yaml file is supplied\n projectcfg = parse_yaml_to_object(commands.filename)\n if projectcfg is None:\n log_error(\"Unable to parse the projectcfg yaml file %s\" %commands.filename)\n sys.exit()\n\n #print all inputs\n log_info(\"input commands: %s\" %commands)\n log_info(\"input project config: %s\" %projectcfg.__dict__)\n\n\n # validate projectcfg commands\n if not validate_input_project_config(projectcfg, commands):\n log_error('The projectcfg file: %s contains some invalid fields. Please fix according to the log file.' %commands.filename)\n sys.exit()\n\n # print the selected gauntlet\n if commands.do_gen_tcl:\n print_pipeline(\"START\", \"TCL\")\n elif commands.do_compile_host:\n print_pipeline(\"START\", \"COMPILE\")\n elif commands.do_package_system:\n print_pipeline(\"START\", \"PACKAGE\")\n elif commands.boardfarm_only:\n print_pipeline(\"SELECT\")\n else:\n print_pipeline()\n\n # set default root path\n if projectcfg.sys_path_root is None:\n projectcfg[\"sys_path_root\"] = settings.storage[\"dir_default_sys_ws\"]\n log_warn(\"The input yml file did not define the sys_path_root value. Default to %s\" %projectcfg[\"sys_path_root\"])\n elif not projectcfg.sys_path_root.endswith(\"/\"):\n projectcfg[\"sys_path_root\"] = projectcfg[\"sys_path_root\"] + \"/\"\n\n ##Change path\n projectcfg[\"sys_path_root\"] = projectcfg[\"sys_path_root\"].replace(\"~\", expanduser(\"~\"))\n log_info(\"sys_path_root is set to %s\" %projectcfg[\"sys_path_root\"])\n\n\n # set global paths\n projectcfg[\"sys_path_workspace\"] = projectcfg[\"sys_path_root\"] + \"workspace/\"\n projectcfg[\"sys_path_rditemp\"] = projectcfg[\"sys_path_root\"] + \"rdi_temp_data/\"\n projectcfg[\"sys_path_results\"] = projectcfg[\"sys_path_root\"] + \"results/\"\n projectcfg[\"sys_path_logs\"] = projectcfg[\"sys_path_root\"] + \"logs/\"\n\n log_info(\"setup global system directories\")\n make_dir_safe(projectcfg[\"sys_path_workspace\"])\n make_dir_safe(projectcfg[\"sys_path_rditemp\"])\n make_dir_safe(projectcfg[\"sys_path_results\"])\n make_dir_safe(projectcfg[\"sys_path_logs\"])\n\n #create project directory then copy user files to it\n #format for project dir is: user name + date time + project name\n if projectcfg[\"user\"] is None:\n projectcfg[\"user\"] = settings.storage[\"user\"]\n\n strProjectName = projectcfg[\"user\"] + \"_\" + datetime_to_string() + \"_\" + projectcfg[\"name\"]\n strProjectName = strProjectName.lower()\n strFullProjectPath = projectcfg[\"sys_path_workspace\"] + \"/\" + strProjectName + \"/\"\n log_info(\"full project path is: \" + strFullProjectPath)\n\n ##setup project workspace directories\n projectcfg[\"ws_name\"] = strProjectName\n projectcfg[\"ws_path\"] = strFullProjectPath\n projectcfg[\"ws_path_rdi\"] = strFullProjectPath + \"rdi/\"\n projectcfg[\"ws_path_src\"] = strFullProjectPath + \"src/\"\n projectcfg[\"ws_path_build\"] = strFullProjectPath + \"build/\"\n projectcfg[\"ws_path_results\"] = strFullProjectPath + \"results/\"\n\n log_info(\"setup workspace directories\")\n make_dir_safe(projectcfg[\"ws_path\"])\n make_dir_safe(projectcfg[\"ws_path_rdi\"])\n make_dir_safe(projectcfg[\"ws_path_src\"])\n make_dir_safe(projectcfg[\"ws_path_build\"])\n make_dir_safe(projectcfg[\"ws_path_results\"])\n\n ##change log path\n # old_log_path = settings.storage[\"file_log_path\"]\n # new_log_path = projectcfg[\"sys_path_logs\"] + settings.storage[\"file_log_name\"]\n #\n # old_log_content = None\n # with open(old_log_path, 'r') as file:\n # old_log_content = file.read()\n # with open(new_log_path, 'a') as file:\n # file.write(old_log_content)\n #\n # os.remove(old_log_path)\n # settings.storage[\"file_log_path\"] = new_log_path\n # init_log_system(new_log_path, True)\n # log_info(\"Changed log file path from %s to %s\" %(old_log_path, new_log_path))\n\n ##copy sources from the user provided directory\n log_info(\"copy src files and project yml file\")\n log_info(\"copy src files from: {0} to: {1}\".format(projectcfg.src, projectcfg.ws_path_src))\n copytree_safe(projectcfg.src, projectcfg.ws_path_src)\n\n log_info(\"copy input yml file from: {0} to: {1}\".format(commands.filename, projectcfg.ws_path))\n copytree_safe(commands.filename, projectcfg.ws_path)\n\n # Write user commands to file\n with open(strFullProjectPath + 'input_command.yml', 'w') as outfile:\n outfile.write( yaml.dump(commands, default_flow_style = False))\n\n\n ##execute tcl with rdi regression\n manager = TaskManager()\n\n\n #Compile only if the user is NOT selected the boardfarm only\n if not commands.boardfarm_only:\n ##Run SDAccel\n task_runsdaccel = TaskRunSDAccel(projectcfg, commands)\n manager.add(task_runsdaccel)\n\n if not task_runsdaccel.generate_tcl():\n log_error(\"There was an error when generating tcl files\")\n\n if commands.do_gen_tcl:\n log_info(\"do_gen_tcl completed I will exit the app now.\")\n return\n\n\n\n ## exit if the compile host only is selected\n if(commands.do_compile_host):\n manager.runall()\n log_info(\"You selected compile-host-only and it's finished. Exiting...\")\n sys.exit()\n\n ##Compile a generic host\n task_compilehost = TaskCompileHost(projectcfg, commands)\n task_compilehost.generate_cmake()\n manager.add(task_compilehost)\n\n\n #select the boards and run\n task_boardfarm_fpga = TaskBoardFarm(projectcfg, \"opencl-hls-5\", \"AlphaDataADM\")\n task_boardfarm_phi = TaskBoardFarm(projectcfg, \"opencl-hls-8\", \"IntelXeonE5-2603\")\n task_boardfarm_cpu = TaskBoardFarm(projectcfg, \"opencl-hls-8\", \"IntelXeonPhiCoprocessor\")\n #task_boardfarm_gpu = TaskBoardFarm(projectcfg, \"opencl-hls-16\", \"AMD295X2\")\n\n #setup combiner task\n task_results_combiner = TaskCombinePerfResults(projectcfg)\n task_results_combiner.addChild(task_boardfarm_fpga)\n task_results_combiner.addChild(task_boardfarm_cpu)\n task_results_combiner.addChild(task_boardfarm_phi)\n\n #add all tasks\n task_par = TaskParallelRun()\n task_par.addChild(task_boardfarm_fpga)\n task_par.addChild(task_boardfarm_cpu)\n task_par.addChild(task_boardfarm_phi)\n manager.add(task_par)\n # manager.add(ddd)\n # manager.add(task_boardfarm_cpu)\n manager.add(task_results_combiner)\n manager.print_order()\n manager.runall()\n\n ##collect results\n\n\n#main method\nif __name__ == '__main__':\n print ('\\\\\"hello\\\\\"')\n print(\"==============================================================\")\n main()\n\n\n print(\"==============================================================\")\n # print(\"Application profile info:\")\n # print_prof_data()\n print(\"==============================================================\")\n","sub_path":"scripts/gauntlet/gauntlet.py","file_name":"gauntlet.py","file_ext":"py","file_size_in_byte":16540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"504680195","text":"import filelock\nimport logging\nimport logging.config\nimport os\nimport pathlib\nimport requests\nimport shutil\nimport tempfile\nimport torch\nimport tqdm\nimport yaml\nimport zipfile\n\ndef get_device():\n return torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef path_in_cache(file_path):\n textattack_cache_dir = config('CACHE_DIR')\n if not os.path.exists(textattack_cache_dir):\n os.makedirs(textattack_cache_dir)\n return os.path.join(textattack_cache_dir, file_path)\n\ndef s3_url(uri):\n return 'https://textattack.s3.amazonaws.com/' + uri\n\ndef download_if_needed(folder_name):\n \"\"\" Folder name will be saved as `.cache/textattack/[folder name]`. If it\n doesn't exist on disk, the zip file will be downloaded and extracted. \n \n Args:\n folder_name (str): path to folder or file in cache\n \n Returns:\n str: path to the downloaded folder or file on disk\n \"\"\"\n cache_dest_path = path_in_cache(folder_name)\n os.makedirs(os.path.dirname(cache_dest_path), exist_ok=True)\n # Use a lock to prevent concurrent downloads.\n cache_dest_lock_path = cache_dest_path + '.lock'\n cache_file_lock = filelock.FileLock(cache_dest_lock_path)\n cache_file_lock.acquire()\n # Check if already downloaded.\n if os.path.exists(cache_dest_path):\n cache_file_lock.release()\n return cache_dest_path\n # If the file isn't found yet, download the zip file to the cache.\n downloaded_file = tempfile.NamedTemporaryFile(\n dir=config('CACHE_DIR'), \n suffix='.zip', delete=False)\n http_get(folder_name, downloaded_file)\n # Move or unzip the file.\n downloaded_file.close()\n if zipfile.is_zipfile(downloaded_file.name):\n unzip_file(downloaded_file.name, cache_dest_path)\n else:\n get_logger().info(f'Copying {downloaded_file.name} to {cache_dest_path}.')\n shutil.copyfile(downloaded_file.name, cache_dest_path)\n cache_file_lock.release()\n # Remove the temporary file.\n os.remove(downloaded_file.name)\n get_logger().info(f'Successfully saved {folder_name} to cache.')\n return cache_dest_path\n\ndef unzip_file(path_to_zip_file, unzipped_folder_path):\n \"\"\" Unzips a .zip file to folder path. \"\"\"\n get_logger().info(f'Unzipping file {path_to_zip_file} to {unzipped_folder_path}.')\n enclosing_unzipped_path = pathlib.Path(unzipped_folder_path).parent\n with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:\n zip_ref.extractall(enclosing_unzipped_path)\n\ndef http_get(folder_name, out_file, proxies=None):\n \"\"\" Get contents of a URL and save to a file.\n \n https://github.com/huggingface/transformers/blob/master/src/transformers/file_utils.py\n \"\"\"\n folder_s3_url = s3_url(folder_name)\n get_logger().info(f'Downloading {folder_s3_url}.')\n req = requests.get(folder_s3_url, stream=True, proxies=proxies)\n content_length = req.headers.get('Content-Length')\n total = int(content_length) if content_length is not None else None\n if req.status_code == 403: # Not found on AWS\n raise Exception(f'Could not find {folder_name} on server.')\n progress = tqdm.tqdm(unit=\"B\", unit_scale=True, total=total)\n for chunk in req.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n progress.update(len(chunk))\n out_file.write(chunk)\n progress.close()\n \ndef add_indent(s_, numSpaces):\n s = s_.split('\\n')\n # don't do anything for single-line stuff\n if len(s) == 1:\n return s_\n first = s.pop(0)\n s = [(numSpaces * ' ') + line for line in s]\n s = '\\n'.join(s)\n s = first + '\\n' + s\n return s\n\ndef default_class_repr(self):\n extra_params = []\n for key in self.extra_repr_keys():\n extra_params.append(' ('+key+')'+': {'+key+'}')\n if len(extra_params):\n extra_str = '\\n' + '\\n'.join(extra_params) + '\\n'\n extra_str = f'({extra_str})'\n else:\n extra_str = ''\n extra_str = extra_str.format(**self.__dict__)\n return f'{self.__class__.__name__}{extra_str}'\n \nLABEL_COLORS = [\n 'red', 'green', \n 'blue', 'purple', \n 'yellow', 'orange', \n 'pink', 'cyan',\n 'gray', 'brown'\n]\n\ndef color_from_label(label_num):\n \"\"\" Colors for labels (arbitrary). \"\"\"\n label_num %= len(LABEL_COLORS)\n return LABEL_COLORS[label_num]\n \ndef color_text(text, color=None, method=None):\n if method is None:\n return text\n if method == 'html':\n return f'{text}'\n elif method == 'stdout':\n if color == 'green':\n color = ANSI_ESCAPE_CODES.OKGREEN\n elif color == 'red':\n color = ANSI_ESCAPE_CODES.FAIL\n elif color == 'blue':\n color = ANSI_ESCAPE_CODES.OKBLUE\n elif color == 'gray':\n color = ANSI_ESCAPE_CODES.GRAY\n else: \n color = ANSI_ESCAPE_CODES.BOLD\n \n return color + text + ANSI_ESCAPE_CODES.STOP\n elif method == 'file':\n return '[[' + text + ']]'\n\ndef words_from_text(s, words_to_ignore=[]):\n \"\"\" Lowercases a string, removes all non-alphanumeric characters,\n and splits into words. \"\"\"\n words = []\n word = ''\n for c in ' '.join(s.split()):\n if c.isalpha():\n word += c\n elif word:\n if word not in words_to_ignore: words.append(word)\n word = ''\n if len(word) and (word not in words_to_ignore): \n words.append(word)\n return words\n\nclass ANSI_ESCAPE_CODES:\n \"\"\" Escape codes for printing color to the terminal. \"\"\"\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n GRAY = '\\033[37m'\n FAIL = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n \"\"\" This color stops the current color sequence. \"\"\"\n STOP = '\\033[0m'\n\ndef html_style_from_dict(style_dict):\n \"\"\" Turns\n { 'color': 'red', 'height': '100px'}\n into\n style: \"color: red; height: 100px\"\n \"\"\"\n style_str = ''\n for key in style_dict:\n style_str += key + ': ' + style_dict[key] + ';'\n return 'style=\"{}\"'.format(style_str)\n \ndef html_table_from_rows(rows, title=None, header=None, style_dict=None):\n # Stylize the container div.\n if style_dict:\n table_html = '
'.format(style_from_dict(style_dict))\n else:\n table_html = '
'\n # Print the title string.\n if title:\n table_html += '

{}

'.format(title)\n\n # Construct each row as HTML.\n table_html = ''\n if header:\n table_html += ''\n for element in header:\n table_html += ''\n table_html += ''\n for row in rows:\n table_html += ''\n for element in row:\n table_html += ''\n table_html += ''\n\n # Close the table and print to screen.\n table_html += '
'\n table_html += str(element)\n table_html += '
'\n table_html += str(element)\n table_html += '
'\n \n return table_html\n \ndef has_letter(word):\n \"\"\" Returns true if `word` contains at least one character in [A-Za-z]. \"\"\"\n for c in word:\n if c.isalpha(): return True\n return False\n\nLOG_STRING = f'\\033[34;1mtextattack\\033[0m'\nlogger = None\ndef get_logger():\n global logger\n if not logger:\n logger = logging.getLogger(__name__)\n logging.config.dictConfig({'version': 1, 'loggers': {__name__: {'level': logging.INFO}}})\n formatter = logging.Formatter(f'{LOG_STRING}: %(message)s')\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(formatter)\n logger.addHandler(stream_handler)\n logger.propagate = False\n return logger\n\ndef _post_install():\n logger = get_logger()\n logger.info('First time importing textattack: downloading remaining required packages.')\n logger.info('Downloading spaCy required packages.')\n import spacy\n spacy.cli.download('en')\n logger.info('Downloading NLTK required packages.')\n import nltk\n nltk.download('wordnet')\n nltk.download('averaged_perceptron_tagger')\n nltk.download('universal_tagset')\n nltk.download('stopwords')\n\ndef _post_install_if_needed():\n \"\"\" Runs _post_install if hasn't been run since install. \"\"\"\n # Check for post-install file.\n post_install_file_path = os.path.join(config('CACHE_DIR'), 'post_install_check')\n if os.path.exists(post_install_file_path):\n return\n # Run post-install.\n _post_install()\n # Create file that indicates post-install completed.\n open(post_install_file_path, 'w').close()\n\ndef config(key):\n return config_dict[key]\n \nconfig_dict = {'CACHE_DIR': os.environ.get('TA_CACHE_DIR', os.path.expanduser('~/.cache/textattack'))}\nconfig_path = download_if_needed('config.yaml')\nwith open(config_path, 'r') as f:\n config_dict.update(yaml.load(f, Loader=yaml.FullLoader))\n_post_install_if_needed()\n","sub_path":"textattack/shared/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"114054655","text":"# -*- encoding: utf-8 -*-\n\nimport re\nfrom glob import glob\nfrom pathlib import Path\n\nfrom setuptools import find_packages, setup\n\nPACKAGE_NAME = 'condagui'\nDESCRIPTION = 'Graphical user interface to the conda package manager'\nURL = 'https://github.com/LaurentRDC/condagui'\nDOWNLOAD_URL = 'https://github.com/LaurentRDC/condagui'\nAUTHOR = 'Laurent P. René de Cotret'\nAUTHOR_EMAIL = 'laurent.decotret@outlook.com'\nBASE_PATH = Path(__file__).parent\n\nwith open(BASE_PATH / PACKAGE_NAME / '__init__.py') as f:\n module_content = f.read()\n VERSION = re.compile(r'.*__version__ = \\'(.*?)\\'', re.S).match(module_content).group(1)\n LICENSE = re.compile(r'.*__license__ = \\'(.*?)\\'', re.S).match(module_content).group(1)\n\nwith open('README.rst') as f:\n README = f.read()\n\nwith open('requirements.txt') as f:\n REQUIREMENTS = [line for line in f.read().split('\\n') if len(line.strip())]\n\nexclude = {'exclude': []}\nPACKAGES = [PACKAGE_NAME + '.' + x for x in find_packages(str(BASE_PATH / PACKAGE_NAME), **exclude)]\nif PACKAGE_NAME not in PACKAGES:\n PACKAGES.append(PACKAGE_NAME)\n\nif __name__ == '__main__':\n setup(\n name = PACKAGE_NAME,\n description = DESCRIPTION,\n long_description = README,\n license = LICENSE,\n url = URL,\n download_url = DOWNLOAD_URL,\n version = VERSION,\n author = AUTHOR,\n author_email = AUTHOR_EMAIL,\n maintainer = AUTHOR,\n maintainer_email = AUTHOR_EMAIL,\n install_requires = REQUIREMENTS,\n keywords = 'conda GUI packages',\n python_requires = '>=3.6',\n packages = PACKAGES,\n include_package_data = True,\n zip_safe = False,\n classifiers=[\n # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: Unix',\n 'Operating System :: POSIX',\n 'Operating System :: Microsoft :: Windows',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Topic :: Utilities',\n ],\n entry_points={\n 'gui_scripts': [\n 'condagui = condagui.__main__',\n ]\n },\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"149523056","text":"from django.http import Http404, HttpResponseForbidden\nfrom django.shortcuts import redirect, get_object_or_404\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils import timezone\nfrom django.conf import settings\n\nfrom datetime import datetime\n\nfrom django.views.generic.base import RedirectView, View, TemplateResponseMixin\nfrom django.views.generic.edit import FormView\n\nfrom account.utils import default_redirect, user_display\n\nfrom django.template import RequestContext\n\nfrom eve_auth.tasks import update_characters\n\nfrom models import RedditAccount, RedditConfirmation\nfrom forms import RedditAccountForm\n\nimport os\n\nfrom hashlib import sha1\nimport praw\n\nclass OwnerDetailsView(FormView):\n pass\n\ndef generate_state_key(pre_code, secret, username):\n pre_state = \"%s%s\" % (secret,username)\n key = sha1(pre_state).hexdigest()\n state_key = \"%s%s\" % (pre_code,key)\n return \n\ndef get_reddit_client(redirect_uri):\n r = praw.Reddit(\n 'Talk In Local - eve_auth.org reddit verification v1.0'\n )\n\n r.set_oauth_app_info(\n client_id = settings.REDDIT_APP_ID,\n client_secret = settings.REDDIT_APP_SECRET,\n redirect_uri=redirect_uri)\n\n return r\n\nclass RedditVerifyView(View):\n template_name = \"vreddit/verify.html\"\n def get(self, request, *args, **kwargs):\n auth_url = 'https://ssl.reddit.com/api/v1/' # TODO: move this to settings.py\n try:\n redditacct = RedditAccount.objects.get(account=request.user.get_profile())\n if redditacct.access_token:\n messages.error(self.request, mark_safe(\"Your account is already linked to: %s\" % (redditacct.reddit_login)))\n return redirect('/')\n else:\n messages.warning(self.request, mark_safe(\"Old reddit verification found, processed new verification.\"))\n except RedditAccount.DoesNotExist:\n pass\n\n redirect_uri = request.build_absolute_uri(reverse('reddit-return'))\n # This should always be the same.\n state_key = \"TILVerify\"\n # TODO: Make configurable\n r = get_reddit_client(redirect_uri)\n url = r.get_authorize_url(state_key, 'identity', False)\n\n return redirect(url)\n\nclass RedditReturnView(View,TemplateResponseMixin):\n template_name = \"vreddit/oauth_return.html\"\n \n def get(self, request, *args, **kwargs):\n incoming_code = request.GET.get('code', None)\n incoming_state = request.GET.get('state', None)\n if incoming_code and incoming_state:\n state_key = \"TILVerify\"\n if state_key == incoming_state:\n r = get_reddit_client(request.build_absolute_uri(reverse('reddit-return')))\n access_information = r.get_access_information(incoming_code)\n authenticated_user = r.get_me()\n\n try:\n reddit = RedditAccount.objects.get(reddit_login=authenticated_user.name)\n if reddit.access_token:\n messages.error(self.request, mark_safe(\"An account is already linked to: %s\" % (reddit.reddit_login)))\n redirect('/')\n if reddit.account == request.user.get_profile():\n reddit.access_token = access_information['access_token']\n messages.success(self.request, mark_safe(\"Converted old verification for reddit account: %s\" % (authenticated_user.name,)))\n else:\n messages.error(self.request, mark_safe(\"Your account is already linked to: %s and does not match this link request: %s\" % (reddit.reddit_login, authenticated_user.name)))\n redirect('/')\n\n except RedditAccount.DoesNotExist:\n # Good\n reddit = RedditAccount(\n account = request.user.get_profile(),\n reddit_login = authenticated_user.name,\n verified = True,\n access_token = access_information['access_token'],\n refresh_token = access_information['refresh_token'],\n )\n\n finally:\n reddit.save()\n\n else:\n messages.error(request, mark_safe(\"unknown error: %s\" % (request.GET,)))\n\n return redirect('/')\n","sub_path":"eveauth/apps/vreddit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"48373022","text":"# -*- coding: utf-8 -*-\nimport xlwt, os, re,sys\n\ncase_list = []\ncase_name_list = []\n\ndef get_the_case_name_in_one_suit(path):\n with open(path,'r',encoding= 'utf-8') as f:\n b = f.readlines()\n a = 0\n for i in b:\n m = re.match(r'.*',i)\n if m != None:\n a += 1\n case_name_list.append(m.group(1))\n return a\n\ndef write_to_excel():\n wb = xlwt.Workbook()\n ws = wb.add_sheet('Case Info')\n ws.write(0, 0, 'Test Suite')\n ws.write(0, 1, 'Case Name')\n ws.write(0, 2, 'Run')\n ws.write(0, 3, 'Timeout(min)')\n a = len(case_list)\n i = 1\n while i <= a:\n ws.write(i,0,case_list[i-1])\n ws.write(i,1,case_name_list[i-1])\n ws.write(i,2,'1')\n ws.write(i,3,'60')\n i += 1\n wb.save('test.csv')\n\ndef creat_case_list(path):\n og_path = os.listdir(path)\n for i in og_path:\n if i != '.svn':\n feature_path = os.path.join(path ,i)\n feature_name = os.listdir(feature_path)\n for x in feature_name:\n feature_name_path = os.path.join(feature_path,x)\n the_case = os.listdir(feature_name_path)\n for u in the_case:\n if u.find('html') != -1:\n the_case_all_path = os.path.join(feature_name_path,u)\n num = get_the_case_name_in_one_suit(the_case_all_path)\n x = 0\n while x < num:\n case_list.append(the_case_all_path)\n x += 1\n\nif __name__ == '__main__':\n path = 'D:\\DEV-HZ2_case\\TL17SP\\CIT\\ASMI'\n creat_case_list(path)\n write_to_excel()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"little_function/creat_supping_excel.py","file_name":"creat_supping_excel.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"520600691","text":"import email\nimport imaplib\nimport os\n\nclass FetchEmail():\n\n #con = None\n #error = None\n\n def __init__(self, mail_server, username, password):\n self.con = imaplib.IMAP4_SSL(mail_server)\n self.con.login(username, password)\n self.con.select(readonly=True) # do not change read status\n\n def close_connection(self):\n \"\"\"\n Close the connection to the IMAP server\n \"\"\"\n self.con.close()\n\n def save_attachment(self, msg, download_folder=\"/tmp\"):\n \"\"\"\n\n Given a message, save its attachments to the specified\n download folder (default is /tmp)\n\n return: file path to attachment\n \"\"\"\n att_path = \"No attachment found.\"\n for part in msg.walk():\n if part.get_content_maintype() == 'multipart':\n continue\n if part.get('Content-Disposition') is None:\n continue\n\n filename = part.get_filename()\n att_path = os.path.join(download_folder, filename)\n\n if not os.path.isfile(att_path):\n fp = open(att_path, 'wb')\n fp.write(part.get_payload(decode=True))\n fp.close()\n return att_path\n\n def get_messages(self, filter=\"ALL\"):\n result, messages = self.con.search(None, filter)\n\n\n def fetch_messages(self, imap_filter='ALL',\n imap_format='BODY.PEEK[HEADER])',\n save_attachments = False):\n \"\"\"\n Retrieve all messages\n imap_filter: (UNSEEN)\n (FROM \"Doug\" SUBJECT \"test message 2\")\n imap_format: (BODY.PEEK[HEADER])\n (RFC822)\n \"\"\"\n emails = []\n result, messages = self.con.search(None, imap_filter)\n if result == \"OK\":\n for message in messages[0].split():\n try:\n # ret, data = self.con.fetch(message,'(RFC822)')\n ret, data = self.con.fetch(message, imap_format)\n print(data)\n except:\n print( \"No emails found.\")\n self.close_connection()\n exit()\n\n continue\n\n msg = email.message_from_string(data[0][1])\n if isinstance(msg, str) == False:\n if save_attachments == True:\n self.save_attachment(msg)\n else:\n print(msg)\n #emails.append(msg)\n #response, data = self.con.store(message, '+FLAGS','\\\\Seen')\n\n return emails\n\n self.error = \"Failed to retreive emails.\"\n return emails\n\n def parse_email_address(self, email_address):\n \"\"\"\n Helper function to parse out the email address from the message\n\n return: tuple (name, address). Eg. ('John Doe', 'jdoe@example.com')\n \"\"\"\n return email.utils.parseaddr(email_address)\n\n","sub_path":"imap_parse.py","file_name":"imap_parse.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"362926271","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n==============================\nPyOrganism Regulatory Networks\n==============================\n\n:Authors:\n Moritz Emanuel Beber\n:Date:\n 2012-05-22\n:Copyright:\n Copyright(c) 2012 Jacobs University of Bremen. All rights reserved.\n:File:\n networks.py\n\"\"\"\n\n\n__all__ = [\"GRN\", \"TRN\", \"CouplonGenerator\", \"GPNGenerator\"]\n\n\nimport logging\nimport itertools\nimport numpy\nimport networkx as nx\n\nfrom datetime import date\nfrom operator import itemgetter, attrgetter\nfrom .. import miscellaneous as misc\nfrom ..io.generic import open_file, parser_warning\nfrom ..errors import PyOrganismError\nfrom . import elements as elem\n\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.addHandler(misc.NullHandler())\n\nOPTIONS = misc.OptionsManager.get_instance()\n\n\nclass GRN(nx.MultiDiGraph):\n \"\"\"\n GRN - Gene Regulatory Network\n\n A directed network containing genes and connections between them if there\n exists a regulatory interaction. Strictly speaking, the interaction is\n between the product of a gene and a target gene but this network holds only\n genes as nodes. Every link must have an attribute denoting the regulatory\n interaction:\n * inhibitory: -1\n * activating: 1\n * unknown: 0\n * dual: 2\n\n Notes\n -----\n Please also read the documentation for networkx.MultiDiGraph.\n\n Examples\n --------\n >>> trn = GRN(name=\"simple\")\n >>> trn.add_edge(\"lacZ\", \"ada\", interaction=0)\n \"\"\"\n\n def __init__(self, data=None, name=\"\", **kw_args):\n super(GRN, self).__init__(data=data, name=name, **kw_args)\n\n def from_link_list(self, links):\n for (u, v, inter) in links:\n self.add_edge(elem.Gene[u], elem.Gene[v], key=inter)\n\n def to_trn(self):\n trn = TRN(name=\"Transcriptinal Regulatory Network (TRN)\")\n for (gene_u, gene_v, k) in self.edges_iter(keys=True):\n if type(gene_u.regulatory_product) == elem.TranscriptionFactor:\n u = gene_u.regulatory_product\n else:\n u = gene_u\n if type(gene_v.regulatory_product) == elem.TranscriptionFactor:\n v = gene_v.regulatory_product\n else:\n v = gene_v\n trn.add_edge(u, v, key=k)\n return trn\n\n\nclass TRN(nx.MultiDiGraph):\n \"\"\"\n TRN - Transriptional Regulatory Network\n\n A directed network containing containing transcription factors (TFs) and\n their regulatory targets, i.e., genes. Every link must have an attribute\n denoting the regulatory interaction:\n * inhibitory: -1\n * activating: 1\n * unknown: 0\n * dual: 2\n\n Notes\n -----\n Please also read the documentation for networkx.MultiDiGraph.\n\n Examples\n --------\n >>> trn = TRN(name=\"simple\")\n >>> trn.add_edge(\"Ada\", \"ada\", interaction=0)\n \"\"\"\n\n def __init__(self, data=None, name=\"\", **kw_args):\n super(TRN, self).__init__(data=data, name=name, **kw_args)\n\n def from_link_list(self, links):\n for (u, v, inter) in links:\n if u == v:\n try:\n element = elem.TranscriptionFactor[u]\n except KeyError:\n element = elem.Gene[u]\n self.add_edge(element, element, key=inter)\n else:\n try:\n elem_u = elem.TranscriptionFactor[u]\n except KeyError:\n elem_u = elem.Gene[u]\n try:\n elem_v = elem.TranscriptionFactor[v]\n except KeyError:\n elem_v = elem.Gene[v]\n self.add_edge(elem_u, elem_v, key=inter)\n\n def to_couplons(self, sf_links):\n couplon_gen = CouplonGenerator(self)\n couplon_gen.add_edges_from(sf_links)\n return couplon_gen\n\n# def lookup_regulondb(self, tf2gene, name2gene=None, sep=\"\\t\",\n# wsdl=\"http://regulondb.ccg.unam.mx/webservices/NetWork.jws?wsdl\"):\n# \"\"\"\n# Retrieve the current version of the TRN from RegulonDB.\n#\n# Transcription factors in these interactions are replaced by the genes\n# that produce them.\n#\n# Parameters\n# ----------\n# tf2gene: dict\n# An association between transcription factors and their genes. The\n# values in the dict can be lists in case of dimeric transcriptional\n# regulators.\n# name2gene: dict (optional)\n# The genes in the interactions between transcription factors and genes parsed\n# from RegulonDB are given by their name. If instead the desired\n# identifier is their Blattner number or RegulonDB identifier, a\n# mapping is required.\n# sep: str (optional)\n# The column separator; not likely to change.\n# wsdl: str (optional)\n# The url of the WSDL definition for the DBGET server.\n#\n# Notes\n# -----\n# Requires a SOAPpy installation and an active internet connection.\n# \"\"\"\n# def use_mapping(rgltr, gene, effct, evdnc):\n# self.add_edge(name2gene[rgltr], name2gene[gene], interaction=effct,\n# evidence=evdnc)\n#\n# def no_mapping(rgltr, gene, effct, evdnc):\n# self.add_edge(rgltr, gene, interaction=effct, evidence=evdnc)\n#\n# # load the required SOAPpy module\n# SOAPpy = misc.load_module(\"SOAPpy\", url=\"http://pywebsvcs.sourceforge.net/\")\n# # establish connection to DBGET server\n# server = SOAPpy.WSDL.Proxy(wsdl)\n# interactions = server.getTFGene()\n# interactions = interactions.split(\"\\n\")\n# if not self.name:\n# self.name = \"TF Gene Network\"\n# self.graph[\"date\"] = \"{:%Y-%m-%d}\".format(date.today())\n# if name2gene:\n# add_link = use_mapping\n# else:\n# add_link = no_mapping\n# warnings = parser_warning\n# # the last line is an empty one\n# for line in interactions[:-1]:\n# line = line.strip()\n# partners = line.split(sep)\n# regulators = tf2gene[partners[0]]\n# if not isinstance(regulators, list):\n# regulators = list(regulators)\n# for regulator in regulators:\n# if partners[2] == \"repressor\":\n# add_link(regulator, partners[1], -1, partners[3])\n# elif partners[2] == \"activator\":\n# add_link(regulator, partners[1], 1, partners[3])\n# elif partners[2] == \"unknown\":\n# add_link(regulator, partners[1], 0, partners[3])\n# elif partners[2] == \"dual\":\n# add_link(regulator, partners[1], 2, partners[3])\n# else:\n# warnings(line)\n# warnings = LOGGER.warn\n#\n# def read_regulondb(self, filename, tf2gene, name2gene=None, sep=\"\\t\",\n# encoding=\"utf-8\", mode=\"rb\", **kw_args):\n# \"\"\"\n# Retrieve the TRN from a RegulonDB flat file.\n#\n# Transcription factors in these interactions are replaced by the genes\n# that produce them.\n#\n# Parameters\n# ----------\n# filename: str\n# The path to the file containing the interaction information.\n# tf2gene: dict\n# An association between transcription factors and their genes. Parsed\n# from a gene product file.\n# name2gene: dict (optional)\n# The genes in the interactions between transcription factors and genes parsed\n# from RegulonDB are given by their name. If instead the desired\n# identifier is their Blattner number or RegulonDB identifier, a\n# mapping is required.\n# sep: str (optional)\n# The column separator; not likely to change.\n# encoding: str (optional)\n# The file encoding.\n# mode: str (optional)\n# The mode used to open a file, should always be read binary.\n# \"\"\"\n# def use_mapping(rgltr, gene, effct, evdnc):\n# self.add_edge(name2gene[rgltr], name2gene[gene], interaction=effct,\n# evidence=evdnc)\n#\n# def no_mapping(rgltr, gene, effct, evdnc):\n# self.add_edge(rgltr, gene, interaction=effct, evidence=evdnc)\n#\n# if not self.name:\n# self.name = filename\n# kw_args[\"encoding\"] = encoding\n# kw_args[\"mode\"] = mode\n# with open_file(filename, **kw_args) as (file_h, ext):\n# interactions = file_h.readlines()\n# if name2gene:\n# add_link = use_mapping\n# else:\n# add_link = no_mapping\n# warnings = parser_warning\n# for line in interactions:\n# line = line.strip()\n# if line == \"\" or line.startswith(\"#\"):\n# continue\n# partners = line.split(sep)\n# regulators = tf2gene[partners[0]]\n# if not isinstance(regulators, list):\n# regulators = list(regulators)\n# for regulator in regulators:\n# if partners[2] == \"-\":\n# add_link(regulator, partners[1], -1, partners[3])\n# elif partners[2] == \"+\":\n# add_link(regulator, partners[1], 1, partners[3])\n# elif partners[2] == \"?\":\n# add_link(regulator, partners[1], 0, partners[3])\n# elif partners[2] == \"+-\":\n# add_link(regulator, partners[1], 2, partners[3])\n# else:\n# warnings(line)\n# warnings = LOGGER.warn\n\n\nclass CouplonGenerator(nx.DiGraph):\n \"\"\"\n \"\"\"\n def __init__(self, trn, name=\"\", **kw_args):\n \"\"\"\n Creates a CouplonGenerator instance.\n\n The CouplonGenerator should be initialised with a TRN. `trn` is a\n keyword argument here to allow for the networkx subgraphing utility.\n\n Notes\n -----\n `generate_couplon`\n \"\"\"\n super(CouplonGenerator, self).__init__(data=trn, name=name, **kw_args)\n\n def generate_couplon(self, nap, sigma_factor):\n \"\"\"\n Using a network that includes sigma factor, transcription factor, and\n gene interactions, couplons are generated using a nucleoid associated\n protein (NAP) and sigma factor pair to generate subgraphs from the pair\n and their common successors.\n\n Parameters\n ----------\n nap: str\n A NAP name which can be found among the TFs.\n sigma_factor: str\n A sigma factor.\n \"\"\"\n # find NAP successors\n nap_targets = set(self.successors_iter(nap))\n # find sigma factor successors\n sigma_targets = set(self.successors_iter(sigma_factor))\n # find the common regulated targets\n common = nap_targets.intersection(sigma_targets)\n # add NAP and sigma factor\n common.add(nap)\n common.add(sigma_factor)\n # return couplon\n couplon = self.subgraph(common)\n couplon.name = \"%s-%s Couplon\" % (nap, sigma_factor)\n return couplon\n\n def lookup_regulondb(self, name2gene=None, sep=\"\\t\",\n wsdl=\"http://regulondb.ccg.unam.mx/webservices/NetWork.jws?wsdl\"):\n \"\"\"\n Retrieve the current version of the sigma factor and gene interactions\n from RegulonDB.\n\n Parameters\n ----------\n name2gene: dict (optional)\n The genes in the interactions between sigma factors and genes parsed\n from RegulonDB are given by their name. If the genes in the TRN are\n identified by their Blattner number of RegulonDB identifier, a\n mapping is required.\n sep: str (optional)\n The column separator; not likely to change.\n wsdl: str (optional)\n The url of the WSDL definition for the DBGET server.\n\n Notes\n -----\n Requires a SOAPpy installation and an active internet connection.\n \"\"\"\n def use_mapping(tf, gene, effct, evdnc):\n self.add_edge(tf, name2gene[gene], interaction=effct, evidence=evdnc)\n\n def no_mapping(tf, gene, effct, evdnc):\n self.add_edge(tf, gene, interaction=effct, evidence=evdnc)\n\n # load the required SOAPpy module\n SOAPpy = misc.load_module(\"SOAPpy\", url=\"http://pywebsvcs.sourceforge.net/\")\n # establish connection to DBGET server\n server = SOAPpy.WSDL.Proxy(wsdl)\n interactions = server.getTFGene()\n interactions = interactions.split(\"\\n\")\n self.graph[\"date\"] = \"{:%Y-%m-%d}\".format(date.today())\n if not self.name:\n self.name = \"Sigma Factor - Gene Network\"\n if name2gene:\n add_link = use_mapping\n else:\n add_link = no_mapping\n warnings = parser_warning\n # the last line is an empty one\n for line in interactions[:-1]:\n line = line.strip()\n partners = line.split(sep)\n # sigma factors only have activating roles\n if partners[2] == \"activator\":\n add_link(partners[0], partners[1], 1, partners[3])\n else:\n warnings(line)\n warnings = LOGGER.warn\n\n def read_regulondb(self, filename, name2gene=None, sep=\"\\t\",\n encoding=\"utf-8\", mode=\"rb\", **kw_args):\n \"\"\"\n Retrieve sigma factor and gene interactions from a RegulonDB flat file.\n\n Parameters\n ----------\n filename: str\n The path to the file containing the interaction information.\n name2gene: dict (optional)\n The genes in the interactions between sigma factors and genes parsed\n from RegulonDB are given by their name. If the genes in the TRN are\n identified by their Blattner number of RegulonDB identifier, a\n mapping is required.\n sep: str (optional)\n The column separator; not likely to change.\n encoding: str (optional)\n The file encoding.\n mode: str (optional)\n The mode used to open a file, should always be read binary.\n \"\"\"\n def use_mapping(tf, gene, effct, evdnc):\n self.add_edge(tf, name2gene[gene], interaction=effct, evidence=evdnc)\n\n def no_mapping(tf, gene, effct, evdnc):\n self.add_edge(tf, gene, interaction=effct, evidence=evdnc)\n\n if not self.name:\n self.name = filename\n kw_args[\"encoding\"] = encoding\n kw_args[\"mode\"] = mode\n with open_file(filename, **kw_args) as (file_h, ext):\n interactions = file_h.readlines()\n if name2gene:\n add_link = use_mapping\n else:\n add_link = no_mapping\n warnings = parser_warning\n for line in interactions:\n line = line.strip()\n if line == \"\" or line.startswith(\"#\"):\n continue\n partners = line.split(sep)\n # sigma factors only have activating roles\n if partners[2] == \"+\":\n add_link(partners[0], partners[1], 1, partners[3])\n else:\n warnings(line)\n warnings = LOGGER.warn\n\n\nclass GPNGenerator(object):\n \"\"\"\n GPN - Gene Proximity Network\n\n An undirected network that contains lines between genes if they are located\n within a certain neighbourhood on the genome.\n\n\n Examples\n --------\n \"\"\"\n\n def __init__(self, **kw_args):\n \"\"\"\n Creates a GPNGenerator object.\n\n A GPNGenerator instance serves the reuse of gene distance information.\n Multiple GPNs can be generated from this information using different\n proximity thresholds.\n\n Notes\n -----\n `generate_gpn`\n \"\"\"\n super(GPNGenerator, self).__init__(**kw_args)\n self.i2name = None\n self.distances = None\n\n def generate_gpn(self, proximity_threshold, name=\"\", **kw_args):\n \"\"\"\n Generate the GPN based on previously parsed distance information and a\n given proximity threshold.\n\n Parameters\n ----------\n proximity_threshold: int\n Maximal distance in base pairs between ORFs on the genome to consider.\n name: str (optional)\n A name for the network.\n Additional keyword arguments are added to the GPN.graph dictionary.\n\n Notes\n -----\n Please also read the documentation for networkx.Graph.\n \"\"\"\n proximity_threshold = int(proximity_threshold)\n length = self.distances.shape[0]\n gpn = nx.Graph(name=name, window=proximity_threshold, **kw_args)\n valid = self.distances > -1\n for i in xrange(length - 1):\n for j in xrange(i + 1, length):\n if valid[i, j] and self.distances[i, j] <= proximity_threshold:\n gpn.add_edge(self.i2name[i], self.i2name[j])\n return gpn\n\n def parse_genes(self, genes):\n end = attrgetter(\"position_end\")\n # assume the maximal end position of the genes is the total length\n genome_length = end(max(genes, key=end))\n length = len(genes)\n self.i2name = dict(itertools.izip(xrange(length), genes))\n self.distances = numpy.zeros((length, length), dtype=int)\n self.distances.fill(-1)\n diffs = numpy.zeros(4, dtype=int)\n no_position = set()\n for i in xrange(length - 1):\n gene_u = genes[i]\n if gene_u.position is None or None in gene_u.position:\n no_position.add(gene_u)\n continue\n for j in xrange(i + 1, length):\n gene_v = genes[j]\n if gene_v.position is None or None in gene_v.position:\n no_position.add(gene_v)\n continue\n # assuming a circular genome here,\n # since RegulonDB is only for E. coli\n # compute difference between start and end points (with overlap)\n for (k, pair) in enumerate(itertools.product(gene_u.position,\n gene_v.position)):\n diff = abs(pair[0] - pair[1])\n diffs[k] = min(diff, genome_length - diff)\n # we only use the UR triangle of the distances matrix\n self.distances[i, j] = diffs.min()\n for gene in no_position:\n LOGGER.info(\"no position information for gene '{0}'\".format(gene))\n\n def read_regulondb(self, filename, gene_identifier=\"name\", sep=\"\\t\",\n comment=\"#\", encoding=\"utf-8\", mode=\"rb\", **kw_args):\n \"\"\"\n Retrieve the gene locations from a RegulonDB flat file and construct the\n GPN using the `proximity_threshold`.\n\n Parameters\n ----------\n filename: str\n The path to the file containing the interaction information.\n gene_identifier: str (optional)\n Identifiers for the genes used in the network. Can be any of:\n * 'name' for the gene name in that organism\n * 'blattner' for the Blattner number\n * 'regulondb' for the unique identifier assigned by RegulonDB\n sep: str (optional)\n The column separator; not likely to change.\n comment: str (optional)\n The sign denoting a comment line.\n encoding: str (optional)\n The file encoding.\n mode: str (optional)\n The mode used to open a file, should always be read binary.\n \"\"\"\n # choose the column for the gene identifier\n gene_identifier = gene_identifier.lower()\n if gene_identifier == \"name\":\n idn = itemgetter(1)\n elif gene_identifier == \"blattner\":\n idn = itemgetter(2)\n elif gene_identifier == \"regulondb\":\n idn = itemgetter(0)\n else:\n raise PyOrganismError(\"unrecognised gene identifier '%s'\",\n gene_identifier)\n # read information from the file\n kw_args[\"encoding\"] = encoding\n kw_args[\"mode\"] = mode\n with open_file(filename, **kw_args) as (file_h, ext):\n information = file_h.readlines()\n # parse the information\n genes = list()\n phantom_num = 0\n warnings = parser_warning\n for line in information:\n line = line.strip()\n if line == \"\" or line.startswith(comment):\n continue\n partners = line.split(sep)\n if len(partners) > 4 and idn(partners) and partners[3] and partners[4]:\n name = idn(partners)\n if name == \"Phantom Gene\":\n phantom_num += 1\n name = \"%s %d\" % (name, phantom_num)\n # record the identifier, start-, end-position, other information\n genes.append([name, int(partners[3]),\n int(partners[4])] + partners[5:])\n else:\n warnings(line)\n warnings = LOGGER.warn\n LOGGER.warn(\"%d phantom genes included\", phantom_num)\n name = itemgetter(0)\n start = itemgetter(1)\n end = itemgetter(2)\n # assume the maximal end position of the genes is the total length\n genome_length = end(max(genes, key=end))\n length = len(genes)\n self.i2name = dict(itertools.izip(xrange(length),\n (name(gene) for gene in genes)))\n self.distances = numpy.zeros((length, length), dtype=int)\n for i in xrange(length - 1):\n gene_u = genes[i]\n start_u = start(gene_u)\n end_u = end(gene_u)\n for j in xrange(i + 1, length):\n gene_v = genes[j]\n start_v = start(gene_v)\n end_v = end(gene_v)\n # assuming a circular genome here,\n # since RegulonDB is only for E. coli\n # compute difference between start and end points (overlap)\n diff_1 = abs(start_u - end_v)\n diff_1 = min(diff_1, genome_length - diff_1)\n diff_2 = abs(start_v - end_u)\n diff_2 = min(diff_2, genome_length - diff_2)\n diff_3 = abs(start_u - start_v)\n diff_3 = min(diff_3, genome_length - diff_3)\n diff_4 = abs(end_v - end_u)\n diff_4 = min(diff_4, genome_length - diff_4)\n # we only use the UR triangle of the distances matrix\n self.distances[i, j] = min(diff_1, diff_2, diff_3, diff_4)\n\n","sub_path":"pyorganism/regulation/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":22562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"196491658","text":"#example: python3 plot-loss.py --dir ./checkpoints-7Sept2020-chairsSDHom\n\nimport argparse\nimport os\nimport re\nimport matplotlib.pyplot as plt\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--dir\",help=\"Directory of checkpoints which contains screenlog.0\")\nargs = parser.parse_args()\n\nif os.path.isfile(os.path.join(args.dir,\"screenlog.0\")):\n print(\"reading and parsing \"+os.path.join(args.dir,\"screenlog.0\"))\n train_pattern = re.compile(r\"\"\"^\\[\\s+(?P\\d+),\\s+(?P\\d*.?\\d*)]\\s+(?P\\d*.?\\d*),\\s+(?P\\d*.?\\d*),\\s+(?P\\d*.?\\d*),\\s+(?P\\d*.?\\d*)\"\"\", re.VERBOSE)\n with open(os.path.join(args.dir,\"screenlog.0\")) as f:\n iteration = []\n learning_rate = []\n epe = []\n onepx = []\n threepx = []\n fivepx = []\n lines=f.readlines()\n for line in lines:\n match=train_pattern.match(line)\n if match:\n iteration.append(float(match.group(\"iteration\")))\n learning_rate.append(float(match.group(\"learning_rate\")))\n epe.append(float(match.group(\"epe\")))\n onepx.append(float(match.group(\"onepx\")))\n threepx.append(float(match.group(\"threepx\")))\n fivepx.append(float(match.group(\"fivepx\")))\n \n colors = [\"b\",'g','r','c','m','y','k']\n\n # THIS MAKES A GRID OF 1 ROW and len(stocks) COLUMN and figure size as (width, height) in inches.\n fig, axs = plt.subplots(2, 3, figsize=(30, 5))\n\n\n axs[0,0].plot(iteration,learning_rate,color=colors[0])\n axs[0,0].set_title(\"lr vs iter\")\n axs[0,1].plot(iteration,epe,color=colors[1])\n axs[0,1].set_title(\"epe vs iter\")\n axs[0,2].plot(iteration,onepx,color=colors[2])\n axs[0,2].set_title(\"1px vs iter\")\n axs[1,0].plot(iteration,threepx,color=colors[3])\n axs[1,0].set_title(\"3px vs iter\")\n axs[1,1].plot(iteration,fivepx,color=colors[4])\n axs[1,1].set_title(\"5px vs iter\")\n\n #show plot\n plt.show()\n print(len(iteration),len(learning_rate),len(epe),len(onepx),len(threepx),len(fivepx))\nelse:\n print(\"Error: screenlog.0 file does not exist in \"+str(args.dir))\n ","sub_path":"plot-loss.py","file_name":"plot-loss.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"197399458","text":"'''\n - Escrever um programa que recebe alguns produtos como argumento -- OK\n - Validar se esse produtos estão na lista de itens disponíveis do mercado -- OK\n - Caso esteja avisar o usuário quais produtos tem e quais não tem -- OK\n - E por ultimo exibir a lista de produtos disponíveis ordenados por ordem alfabética do mercado para que o usuário possa pedir na próxima vez -- OK\n'''\n\nif __name__ == '__main__':\n #Lista de produtos do usuário\n produtos_usuario = []\n\n #Lista de produtos disponíveis no mercado\n produtos_mercado = ['REFRIGERANTE', 'CERVEJA', 'MAÇÃ', 'PÃO']\n\n #Realiza a leitura dos produtos do usuário\n while True:\n produto = input(\"Digite um produto para adicionar na lista (Digite 'sair' para encerrar): \")\n\n if produto == 'sair':\n break\n\n if not produto.upper() in produtos_usuario:\n produtos_usuario.append(produto.upper())\n\n # Salvar produtos indisponíveis\n produtos_indisponiveis = []\n\n # Percorre a lista de produtos que o usuário digitou\n for p in produtos_usuario:\n\n # Valida se o produto está disponível ou não\n if not p.upper() in produtos_mercado:\n produtos_indisponiveis.append(p)\n\n print(f'Produtos indisponíveis: {produtos_indisponiveis}')\n\n #Ordenar lista de produtos disponíveis no mercado\n produtos_mercado.sort()\n print(f'Produtos disponíveis no Mercado: {produtos_mercado}')\n\n\n","sub_path":"aula-2/desafio-parte2.py","file_name":"desafio-parte2.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"121992159","text":"import matplotlib\nmatplotlib.use('Agg')\nimport json\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics import roc_curve, auc\nfrom scipy import interp\n\ndef plotRoc(fprMicro, tprMicro, roc_aucMicro, fprMacro, tprMacro, roc_aucMacro, name):\n plt.ioff()\n plt.figure()\n plt.plot(fprMicro, tprMicro, lw=2, color='darkorange', label='micro-average ROC curve (area = %0.8f)' % roc_aucMicro)\n plt.plot(fprMacro, tprMacro, lw=2, color='red', label='macro-average ROC curve (area = %0.8f)' % roc_aucMacro)\n plt.plot([0, 1], [0, 1], color='navy', lw = 2)\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title(\"Jaro-Winkler\")\n plt.legend(loc=\"lower right\")\n plt.savefig(name)\n\n\n\n\n\ndef loadJSONFile(fileName):\n with open(fileName, 'r') as file:\n data = json.load(file)\n return data\n\n\ndef createVectors(expRecord, valRecord):\n label = []\n score = []\n for elem in expRecord:\n if elem[0] in valRecord:\n label.append(1)\n else:\n label.append(0)\n score.append(elem[1])\n return (score, label)\n\n\ndef prepareRoc(experimentFilename, validationFileName, outputName):\n valData = loadJSONFile(validationFileName)\n expData = loadJSONFile(experimentFilename)\n data = dict()\n for record in expData.items():\n valRecord = valData[record[0]]\n vectors = createVectors(record[1], valRecord)\n data.update({record[0] : vectors})\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n yscores = []\n ylabels = []\n i = 0\n for item in data.items():\n fpr[i], tpr[i], _ = roc_curve(item[1][1], item[1][0])\n roc_auc[item[0]] = auc(fpr[i], tpr[i])\n yscores.append(item[1][0])\n ylabels.append(item[1][1])\n i+=1 \n\n flatten = lambda l: [item for sublist in l for item in sublist]\n fpr['micro'], tpr['micro'], _ = roc_curve(flatten(ylabels), flatten(yscores))\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n all_fpr = np.unique(np.concatenate([fpr[j] for j in range(i)]))\n\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(i):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n mean_tpr /= i\n\n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n plotRoc(fpr['micro'],tpr['micro'], roc_auc[\"micro\"], fpr['macro'],tpr['macro'], roc_auc[\"macro\"], outputName)\n\n \n\n\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-iv\", '--validation-set-filename')\n parser.add_argument(\"-ie\", '--experiment-set-filename')\n parser.add_argument(\"-o\", '--roc-file')\n args = parser.parse_args()\n\n prepareRoc(args.experiment_set_filename, args.validation_set_filename, args.roc_file)","sub_path":"data2/exp/roc/generateRoc.py","file_name":"generateRoc.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"196204968","text":"from chatterbot.logic import LogicAdapter\nfrom chatterbot.conversation import Statement\nimport constants\n\n\nclass YesNoLogicAdapter(LogicAdapter):\n def __init__(self, chatbot, **kwargs):\n super().__init__(chatbot, **kwargs)\n\n def can_process(self, statement):\n stmnt_text = statement.text.strip('.?!/;:\\'\\\"')\n\n if stmnt_text in constants.AFFIRMATIVES:\n return True\n elif stmnt_text in constants.NEGATIVES:\n return True\n else:\n return False\n\n def process(self, statement, additional_response_selection_parameters=None):\n \"\"\"\n Given an affirmative/negative statement from the user:\n 1. Detect which question from the bot the user in answering.\n 2. Return appropriate response to the user.\n\n \"\"\"\n\n # I found the following three lines to be necessary after quite a bit of debugging.\n # get_last() returns a Statement object with all fields empty except for text and created_at.\n # When chatbot.storage.filter() is used it returns a generator object, not a Statement object.\n # Using next() on the generator object gets us the desired Statement object with all needed data.\n incomplete_direct_question = self.chatbot.get_last()\n generator_direct_question = self.chatbot.storage.filter(text=incomplete_direct_question.text)\n\n direct_question = None\n try:\n direct_question = next(generator_direct_question)\n except StopIteration:\n pass\n\n response_tag = ''\n response_text = ''\n generator_response = None\n\n if direct_question:\n if statement.text.strip('.?!/;:\\'\\\"') in constants.AFFIRMATIVES:\n response_tag = self.get_affirmative_tag(direct_question)\n elif statement.text.strip('.?!/;:\\'\\\"') in constants.NEGATIVES:\n response_tag = self.get_negative_tag(direct_question)\n\n if response_tag:\n generator_response = self.chatbot.storage.filter(text=response_tag)\n try:\n answer = next(generator_response)\n answer.confidence = 1\n return answer\n except StopIteration:\n '''\n There were occasional instances during testing where storage.filter() would return a generator object\n with no items in it, causing a StopIteration error. This happened despite there being a statement in the\n database with a matching text field. The issue was hard to reproduce. This is a workaround.\n '''\n desired_stmnt = Statement(text=response_tag)\n desired_stmnt.confidence = 1\n return desired_stmnt\n\n # Many direct questions are only tagged for AFF or NEG response, not both.\n # This logic adapter should still choose responses for those cases, since BestMatch will always be guessing.\n # SUGGEST response causes the chatbot to query the suggestion tree and bring up undiscussed topics.\n default_response = Statement(text='SUGGEST')\n default_response.confidence = 1\n return default_response\n\n @staticmethod\n def get_affirmative_tag(statement):\n tags = statement.get_tags()\n\n for tag in list(tags):\n if tag[:4] == 'AFF:':\n return tag[4:]\n\n return None\n\n @staticmethod\n def get_negative_tag(statement):\n tags = statement.get_tags()\n\n for tag in list(tags):\n if tag[:4] == 'NEG:':\n return tag[4:]\n\n return None\n","sub_path":"chatterbot/logic/yes_no_response.py","file_name":"yes_no_response.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"471937074","text":"from a10sdk.common.A10BaseClass import A10BaseClass\n\n\nclass Trunk(A10BaseClass):\n \n \"\"\"Class Description::\n preferred-session-sync-port trunk.\n\n Class trunk supports CRUD Operations and inherits from `common/A10BaseClass`.\n This class is the `\"PARENT\"` class for this module.`\n\n :param pre_vlan: {\"description\": \"Interface VLAN (VLAN ID)\", \"format\": \"number\", \"type\": \"number\", \"maximum\": 4094, \"minimum\": 1, \"optional\": true}\n :param uuid: {\"description\": \"uuid of the object\", \"format\": \"string\", \"minLength\": 1, \"modify-not-allowed\": 1, \"optional\": true, \"maxLength\": 64, \"type\": \"string\"}\n :param pre_trunk: {\"optional\": false, \"type\": \"number\", \"description\": \"Trunk Interface number\", \"format\": \"interface\"}\n :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`\n\n \n\n URL for this object::\n `https:////axapi/v3/vrrp-a/preferred-session-sync-port/trunk/{pre_trunk}`.\n\n \n\n \n \"\"\"\n def __init__(self, **kwargs):\n self.ERROR_MSG = \"\"\n self.required = [ \"pre_trunk\"]\n\n self.b_key = \"trunk\"\n self.a10_url=\"/axapi/v3/vrrp-a/preferred-session-sync-port/trunk/{pre_trunk}\"\n self.DeviceProxy = \"\"\n self.pre_vlan = \"\"\n self.uuid = \"\"\n self.pre_trunk = \"\"\n\n for keys, value in kwargs.items():\n setattr(self,keys, value)\n\n\n","sub_path":"a10sdk/core/vrrp/vrrp_a_preferred_session_sync_port_trunk.py","file_name":"vrrp_a_preferred_session_sync_port_trunk.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"362462960","text":"def contains_adjacent(number):\n if len(str(number)) <= 1:\n return False\n\n elts = [int(s) for s in str(number)]\n\n return any(map(lambda t: t[0] == t[1], zip(elts, elts[1:])))\n\n\ngroups_to_remove = set([3 * str(i) for i in range(10)] + [4 * str(i) for i in range(10)])\ngroups_of_five = set([5 * str(i) for i in range(10)])\n\ndef contains_adjacent_not_part_of_larger_group(number):\n number_string = str(number)\n\n # if group contains group of five, it cannot contain adjacent\n for group in groups_of_five:\n if group in number_string:\n return False\n\n # remove groups of three and four, observe the rest\n for group in groups_to_remove:\n if group in number_string:\n rests = number_string.split(group) # substrings that might contain adjacent pair\n rests = list(filter(lambda r: r not in groups_to_remove, rests)) # filter on rests that are not part of groups to remove\n\n # print(rests, any(map(lambda rest: contains_adjacent(rest), rests)))\n return any(map(lambda rest: contains_adjacent(rest), rests))\n\n return contains_adjacent(int(number_string))\n\n\n\ndef is_non_decreasing(number):\n elts = [int(s) for s in str(number)]\n\n return all(map(lambda t: t[0] <= t[1], zip(elts, elts[1:])))\n\n\ndef meets_criteria1(number):\n criteria = [contains_adjacent, is_non_decreasing]\n return all(map(lambda c: c(number), criteria))\n\ndef meets_criteria2(number):\n criteria = [contains_adjacent_not_part_of_larger_group, is_non_decreasing]\n return all(map(lambda c: c(number), criteria))\n\n\nprint(sum([meets_criteria1(number) for number in range(240920, 789857)]))\nprint(sum([meets_criteria2(number) for number in range(240920, 789857)]))\n\n","sub_path":"day4/day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"52586606","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 25 22:29:37 2018\n\n@author: jack.lingheng.meng\n\"\"\"\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 25 22:29:37 2018\n\n@author: jack.lingheng.meng\n\"\"\"\nimport os\nos.system('module load nixpkgs/16.09 gcc/5.4.0 cuda/8.0.44 cudnn/7.0 opencv/3.3.0 boost/1.65.1 openblas/0.2.20 hdf5/1.8.18 leveldb/1.18 mkl-dnn/0.14 python/3.5.2')\nos.system('cd ~')\nos.system('source openposeEnv_Python3/bin/activate')\nos.system('export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/openpose_python_lib/lib:$HOME/openpose_python_lib/python/openpose:$HOME/caffe/build/lib:/cvmfs/soft.computecanada.ca/easybuild/software/2017/avx2/Compiler/gcc5.4/boost/1.65.1/lib')\n\n# From Python\n# It requires OpenCV installed for Python\nimport sys\nimport csv\nimport cv2\nimport os\nfrom sys import platform\nimport argparse\nimport matplotlib\nmatplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport pandas as pd\nimport numpy as np\nimport math\nfrom scipy.stats import mode\n\nimport pdb\nfrom IPython.core.debugger import Tracer\n\n# Remember to add your installation path here\n# Option b\n# If you run `make install` (default path is `/usr/local/python` for Ubuntu), you can also access the OpenPose/python module from there. This will install OpenPose and the python library at your desired installation path. Ensure that this is in your python path in order to use it.\nsys.path.insert(0,r'/home/lingheng/openpose_python_lib/python/openpose') \n\n# Parameters for OpenPose. Take a look at C++ OpenPose example for meaning of components. Ensure all below are filled\ntry:\n from openpose import *\nexcept:\n raise Exception('Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` in CMake and have this Python script in the right folder?')\nparams = dict()\nparams[\"logging_level\"] = 3\nparams[\"output_resolution\"] = \"-1x-1\"\nparams[\"net_resolution\"] = \"-1x736\" # if crop video, this should be changged and must be mutplies of 16.\nparams[\"model_pose\"] = \"COCO\"\nparams[\"alpha_pose\"] = 0.6\nparams[\"scale_gap\"] = 0.25\nparams[\"scale_number\"] = 4\nparams[\"render_threshold\"] = 0.05\n# If GPU version is built, and multiple GPUs are available, set the ID here\nparams[\"num_gpu_start\"] = 0\nparams[\"disable_blending\"] = False\n# Ensure you point to the correct path where models are located\nparams[\"default_model_folder\"] = \"/home/lingheng/openpose/models/\"\n# Construct OpenPose object allocates GPU memory\nopenpose = OpenPose(params)\n\ndef subplot_estimated_occupancy(occupancy_whole, occupancy_core, occupancy_margin, fig_filename, smooth_flag = False):\n \"\"\"\n Plot and save estimated occupancy in Three Interest Area.\n Args:\n occupancy_whole (pd.DataFrame): occupancy in Whole Interest Area\n occupancy_core (pd.DataFrame): occupancy in Core Interest Area\n occupancy_margin (pd.DataFrame): occupancy in Margin Interest Area\n fig_filename (string): filename of the saved figure\n smooth_flag (bool): indicates whether the occupancy is smoothened\n \"\"\"\n ymin = 0\n ymax = 20\n ystep = 4\n lw=1.5\n plt.figure()\n # Whole Interest Area\n plt.subplot(3, 1, 1)\n print(type(occupancy_whole['Time'][0]))\n plt.plot(occupancy_whole['Time']/1000, occupancy_whole['Occupancy'], 'b-', lw, alpha=0.6)\n plt.xlabel('time/second')\n plt.ylabel('# of visitors')\n plt.ylim(ymin, ymax)\n plt.yticks(np.arange(ymin,ymax,ystep))\n if smooth_flag == False:\n plt.title('Estimated # of visitors in Whole Interest Area')\n else:\n plt.title('Smooth Estimated # of visitors in Whole Interest Area')\n plt.grid(True, linestyle=':')\n\n # Core Interest Area\n plt.subplot(3, 1, 2)\n plt.plot(occupancy_core['Time']/1000, occupancy_core['Occupancy'], 'r-', lw, alpha=0.6)\n plt.xlabel('time/second')\n plt.ylabel('# of visitors')\n plt.ylim(ymin, ymax)\n plt.yticks(np.arange(ymin,ymax,ystep))\n plt.title('Estimated # of visitors in Core Interest Area')\n if smooth_flag == False:\n plt.title('Estimated # of visitors in Core Interest Area')\n else:\n plt.title('Smooth Estimated # of visitors in Core Interest Area')\n plt.grid(True, linestyle=':')\n \n # Margin Interest Area\n plt.subplot(3, 1, 3)\n plt.plot(occupancy_margin['Time']/1000, occupancy_margin['Occupancy'], 'g-', lw, alpha=0.6)\n plt.xlabel('time/second')\n plt.ylabel('# of visitors')\n plt.ylim(ymin, ymax)\n plt.yticks(np.arange(ymin,ymax,ystep))\n if smooth_flag == False:\n plt.title('Estimated # of visitors in Margin Interest Area')\n else:\n plt.title('Smooth Estimated # of visitors in Margin Interest Area')\n plt.grid(True, linestyle=':')\n\n plt.tight_layout()\n plt.savefig(fig_filename, dpi = 300)\n\ndef plot_estimated_occupancy(occupancy_whole, occupancy_core, occupancy_margin, fig_filename, smooth_flag = False):\n \"\"\"\n Args:\n \n smooth_flag (bool): indicates whether the occupancy is smoothened\n \"\"\"\n ymin=0\n ymax=20\n ystep=4\n\n plt.figure()\n # Whole Interest Area\n plt.plot(occupancy_whole['Time']/1000, occupancy_whole['Occupancy'], 'r-', lw=1.5, alpha=0.6)\n # Core Interest Area\n plt.plot(occupancy_core['Time']/1000, occupancy_core['Occupancy'], 'g-', lw=1.5, alpha=0.6)\n # Margin Interest Area\n plt.plot(occupancy_margin['Time']/1000, occupancy_margin['Occupancy'], 'b-', lw=1.5, alpha=0.6)\n plt.legend(('Whole Interest Area','Core Interest Area','Margin Interest Area'))\n\n plt.xlabel('time/second')\n plt.ylabel('# of visitors')\n plt.ylim(ymin, ymax, ystep)\n if smooth_flag == False:\n plt.title('Estimated # of visitors in Three Interest Areas')\n else:\n plt.title('Smooth Estimated # of visitors in Three Interest Areas')\n plt.grid(True, linestyle=':')\n\n plt.tight_layout()\n plt.savefig(fig_filename, dpi = 300)\n\ndef moving_smoothing(values, window_size, smooth_type='mode', stride = 1):\n \"\"\"\n Smoothen estimated occupancy.\n Args:\n values (pandas.DataFrame): \n values['Time']: time in millisecond\n values['Occupancy']: estimated # of visitors\n window_size(int): the size of sliding window\n smooth_type (string): \n 1. 'mode'\n 2. 'mean'\n 3. 'min'\n 4. 'median'\n stride (int): the stride between two consecutive windows\n Returns:\n smooth_time (np.array): smooth time i.e. the max time in each window\n smooth_occupancy (np.array): smooth occupancy i.e. the mode occupancy in each window\n \"\"\"\n group_time = []\n group_occupancy = []\n for i in range(0, math.ceil((len(values['Time'])-window_size+1)/stride)):\n group_time.append(values['Time'][i:i+window_size])\n group_occupancy.append(values['Occupancy'][i:i+window_size])\n \n smooth_time = []\n smooth_occupancy = []\n for i in range(len(group_time)):\n smooth_time.append(min(group_time[i])) # max time in the group\n if smooth_type == 'mode':\n smooth_occupancy.append(mode(group_occupancy[i])[0][0]) # mode occupancy in the group\n elif smooth_type == 'mean':\n smooth_occupancy.append(np.round(np.mean(group_occupancy[i])))\n elif smooth_type == 'min':\n smooth_occupancy.append(np.round(np.min(group_occupancy[i])))\n elif smooth_type == 'median':\n smooth_occupancy.append(np.round(np.median(group_occupancy[i])))\n else:\n print('Please choose a proper smooth_type.')\n smooth_values = pd.DataFrame(data={'Time': np.array(smooth_time),\n 'Occupancy': np.array(smooth_occupancy,dtype=int)})\n return smooth_values#np.array(smooth_time), np.array(smooth_occupancy)\n\ndef interpret_senario(occupancy_whole, occupancy_core, occupancy_margin, senarios_truth_table):\n \"\"\"\n Args:\n occupancy_whole (pd.DataFrame): estimation of coccupancy in whole intrest area\n occupancy_core (pd.DataFrame): estimation of coccupancy in core intrest area\n occupancy_margin (pd.DataFrame): estimation of coccupancy in margin intrest area\n senarios_truth_table (pandas.DataFrame): senarios truth table which has information on\n how to interpret senario.\n Returns:\n senario_sequence (np.array): sequnce of interpreted senario discription according to \"Senario Truth Value Table\"\n event_sequence (np.array): sequence of interpreted senario code according to \"Senario Truth Value Table\"\n Note: Different from \"Senario Truth Value Table\", in this sequence we convert all impossible cases into 0 rather than their original senario code.\n event_time (np.array): the time of each event in millisecond.\n \"\"\"\n senario_sequence = []\n event_sequence = []\n event_time = []\n for i in range(len(occupancy_whole['Occupancy'])-1):\n change_x = occupancy_core['Occupancy'][i+1] - occupancy_core['Occupancy'][i]\n change_y = occupancy_margin['Occupancy'][i+1] - occupancy_margin['Occupancy'][i]\n change_z = occupancy_whole['Occupancy'][i+1] - occupancy_whole['Occupancy'][i]\n # code: \n # 0: hold\n # 1: increase\n # 2: decrease\n if change_x == 0:\n x = 0\n elif change_x > 0:\n x = 1\n elif change_x < 0:\n x = 2\n\n if change_y == 0:\n y = 0\n elif change_y > 0:\n y = 1\n elif change_y < 0:\n y = 2\n\n if change_z == 0:\n z = 0\n elif change_z > 0:\n z = 1\n elif change_z < 0:\n z = 2\n # convert ternary to decimal\n senario_index = z + y*3 + x*3^2\n senario_sequence.append(senarios_truth_table['Explanation'][senario_index])\n if senarios_truth_table['Truth value'][senario_index] == 0:\n # convert all impossible cases into 0\n event_sequence.append(0)\n #event_sequence.append(senario_index)\n else:\n event_sequence.append(senario_index)\n event_time.append(occupancy_whole['Time'][i])\n return np.array(senario_sequence), np.array(event_sequence), np.array(event_time)\n\ndef plot_detected_interesting_event(senario_sequence, event_sequence, event_time, fig_filename):\n ymin = 0\n ymax = 26.0005\n ystep = 1\n plt.figure(figsize=(10, 6))\n plt.scatter(event_time/1000, event_sequence)\n plt.xlabel('time/second')\n plt.ylabel('Event Description')\n plt.ylim(ymin, ymax)\n plt.yticks(np.arange(ymin,ymax,ystep), senarios_truth_table['Explanation'],\n rotation=45, fontsize = 6)\n ax2 = plt.twinx()\n plt.ylabel('Event Code')\n plt.yticks(np.arange(ymin,ymax,ystep), np.arange(ymin,ymax,ystep))\n plt.title('Detected Interesting Events')\n plt.grid(True, linestyle=':')\n plt.tight_layout()\n plt.savefig(fig_filename, dpi = 300)\n\ndef tag_interesting_event_description_on_video(video_filename,\n smooth_type, window_size, stride,\n senario_sequence, event_sequence, event_time):\n \"\"\"\n Args:\n video_filename (string): filename of video\n smooth_type (string): smooth type (hyper-parameter of smooth method)\n window_size (int): size of smooth window (hyper-parameter of smooth method)\n stride (int): stride size (hyper-parameter of smooth method)\n senario_sequence (np.array): sequnce of interpreted senario discription according to \"Senario Truth Value Table\"\n event_sequence (np.array): sequence of interpreted senario code according to \"Senario Truth Value Table\"\n Note: Different from \"Senario Truth Value Table\", in this sequence we convert all impossible cases into 0 rather than their original senario code.\n event_time (np.array): the time of each event in millisecond.\n \"\"\"\n camera = cv2.VideoCapture(video_filename)\n (grabbed, frame) = camera.read()\n fheight, fwidth, channels= frame.shape\n\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n out_tagged_camera_frame = cv2.VideoWriter(video_filename.split('.avi')[0]+'_tagged_smooth_type_{}_window_size_{}_stride_{}.avi'.format(smooth_type,window_size,stride),fourcc, camera.get(cv2.CAP_PROP_FPS), (fwidth,fheight))\n # loop over the frames of the video\n total_frame_number = camera.get(cv2.CAP_PROP_FRAME_COUNT)\n max_line_character_num = 60 # 60 characters each line\n detected_event_time = 0\n detected_event_senario = ''\n line_num = 1\n for frame_count in range(len(event_time)):\n if frame_count % 200 == 0:\n print('Processing frame: {}'.format(frame_count))\n (grabbed, frame) = camera.read()\n if grabbed == True:\n cv2.putText(frame, \"smooth_type: {}, window_size: {}, stride: {}.\".format(smooth_type,window_size,stride), (10, 120), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n\n time = camera.get(cv2.CAP_PROP_POS_MSEC) #Current position of the video file in milliseconds.\n event_index = frame_count\n if event_sequence[event_index] != 0: # 0 means 'impossible event'\n detected_event_time = time\n detected_event_senario = senario_sequence[event_index]\n cv2.putText(frame, \"Detect Interesting Event at: {}s.\".format(int(detected_event_time/1000)), (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n line_num = np.ceil(len(detected_event_senario)/max_line_character_num)\n for i in range(int(line_num)):\n if i < line_num:\n cv2.putText(frame, \"{}\".format(detected_event_senario[i*max_line_character_num:(i+1)*max_line_character_num]), (10, 180+30*(i)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n else:\n cv2.putText(frame, \"{}\".format(detected_event_senario[i*max_line_character_num:end]), (10, 180+30*(i)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n else: # repeat text from last detected event\n cv2.putText(frame, \"Detect Interesting Event at:{}s\".format(int(detected_event_time/1000)), (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n for i in range(int(line_num)):\n if i < line_num:\n cv2.putText(frame, \"{}\".format(detected_event_senario[i*max_line_character_num:(i+1)*max_line_character_num]), (10, 180+30*(i)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n else:\n cv2.putText(frame, \"{}\".format(detected_event_senario[i*max_line_character_num:end]), (10, 180+30*(i)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n # save processed videos\n out_tagged_camera_frame.write(frame)\n else:\n # Pass this frame if cannot grab an image.\n print('Frame: {}, grabbed={} and frame={}'.format(frame_count, grabbed, frame))\n\nif __name__ == \"__main__\":\n # construct the argument parser and parse the arguments\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-v\", \"--video\", default='/home/lingheng/project/lingheng/ROM_raw_videos/Camera1_test.mp4', help=\"path to the video file\")\n ap.add_argument(\"-o\", \"--output_directory\", default='/home/lingheng/project/lingheng/ROM_processed_videos', help=\"directory to save processed video\")\n \n args = vars(ap.parse_args())\n \n if args.get(\"video\", None) is None:\n raise Error(\"No input video!!\")\n # otherwise, we are reading from a video file\n else:\n camera = cv2.VideoCapture(args[\"video\"])\n ########################################################################\n # Estimate Occupancy #\n ########################################################################\n # frames per second (fps) in the raw video\n fps = camera.get(cv2.CAP_PROP_FPS)\n frame_count = 1\n print(\"Raw frames per second: {0}\".format(fps))\n # prepare to save video\n (grabbed, frame) = camera.read()\n ## downsample frame\n #downsample_rate = 0.5\n #frame = cv2.resize(frame,None,fx=downsample_rate, fy=downsample_rate, interpolation = cv2.INTER_LINEAR)\n # crop frame\n original_h, original_w, channels= frame.shape\n top_edge = int(original_h*(1/10))\n down_edge = int(original_h*1)\n left_edge = int(original_w*(1/5))\n right_edge = int(original_w*(4/5))\n frame_cropped = frame[top_edge:down_edge,left_edge:right_edge,:].copy() # must use copy(), otherwise slice only return address i.e. not hard copy\n \n cropped_h, cropped_w, channels = frame_cropped.shape\n fwidth = cropped_w \n fheight = cropped_h\n print(\"Frame width:{}, Frame height:{}.\".format(cropped_w , cropped_h))\n # Define the polygon of Core Interest Area\n point_1 = [int(0.17 * cropped_w), int(0.20 * cropped_h)]\n point_2 = [int(0.17 * cropped_w), int(0.62 * cropped_h)]\n point_3 = [int(0.44 * cropped_w), int(0.82 * cropped_h)]\n point_4 = [int(0.61 * cropped_w), int(0.72 * cropped_h)]\n point_5 = [int(0.61 * cropped_w), int(0.20 * cropped_h)]\n core_interest_area_polygon = np.array([point_1,point_2,point_3,point_4,point_5])\n \n # get output video file name\n file_path = args[\"video\"].split('/')\n file_name, _= file_path[-1].split('.')\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n \n output_video_filename = os.path.join(args['output_directory'],'{}_processed.avi'.format(file_name))\n out_camera_frame_whole = cv2.VideoWriter(output_video_filename,fourcc, fps, (fwidth,fheight))\n \n # get output estimated occupancy file name\n out_occupancy_whole = os.path.join(args['output_directory'],'{}_processed_occupancy_whole.csv'.format(file_name))\n out_occupancy_core = os.path.join(args['output_directory'],'{}_processed_occupancy_core.csv'.format(file_name))\n out_occupancy_margin = os.path.join(args['output_directory'],'{}_processed_occupancy_margin.csv'.format(file_name))\n with open(out_occupancy_whole, 'a') as csv_datafile:\n fieldnames = ['Time', 'Occupancy']\n writer = csv.DictWriter(csv_datafile, fieldnames = fieldnames)\n writer.writeheader()\n with open(out_occupancy_core, 'a') as csv_datafile:\n fieldnames = ['Time', 'Occupancy']\n writer = csv.DictWriter(csv_datafile, fieldnames = fieldnames)\n writer.writeheader() \n with open(out_occupancy_margin, 'a') as csv_datafile:\n fieldnames = ['Time', 'Occupancy']\n writer = csv.DictWriter(csv_datafile, fieldnames = fieldnames)\n writer.writeheader() \n \n # loop over the frames of the video\n total_frame_number = camera.get(cv2.CAP_PROP_FRAME_COUNT)\n print('Total frame number: {}'.format(total_frame_number))\n for frame_count in range(int(total_frame_number)):\n if frame_count % 200 == 0:\n print('Processing frame: {}'.format(frame_count))\n (grabbed, frame) = camera.read()\n if grabbed == True:\n time = camera.get(cv2.CAP_PROP_POS_MSEC) #Current position of the video file in milliseconds.\n ## downsample frame\n #frame = cv2.resize(frame,None,fx=downsample_rate, fy=downsample_rate, interpolation = cv2.INTER_LINEAR)\n # crop frame\n frame_cropped = frame[top_edge:down_edge,left_edge:right_edge,:].copy() # must use copy()\n \n # 1. Whole Interest Area\n # Output keypoints and the image with the human skeleton blended on it\n # (num_people, 25_keypoints, x_y_confidence) = keypoints_whole_interest_area.shape\n keypoints_whole_interest_area, output_image_whole_interest_area = openpose.forward(frame_cropped, True)\n \n # 2. Core Interest Area\n core_interest_area_mask = np.zeros(frame_cropped.shape[:2], np.uint8)\n cv2.drawContours(core_interest_area_mask, [core_interest_area_polygon], -1, (255, 255, 255), -1, cv2.LINE_AA)\n core_interest_area = cv2.bitwise_and(output_image_whole_interest_area, frame_cropped, mask=core_interest_area_mask)\n \n # 3. Margin Interest Area\n margin_interest_area = cv2.bitwise_xor(output_image_whole_interest_area, core_interest_area)\n # TODO: infer occupancy from \"keypoints_whole_interest_area\"\n \n # draw the text and timestamp on the frame\n occupancy_whole = keypoints_whole_interest_area.shape[0]\n occupancy_core = 0\n occupancy_margin = 0\n for people in keypoints_whole_interest_area:\n # Sort all keypoints and pick up the one with the highest confidence\n # Meaning of keypoints (https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/doc/output.md)\n ordered_keypoints = people[people[:,2].argsort(),:] # increasing order\n x, y = ordered_keypoints[-1][:2]\n #pdb.set_trace()\n # Choose the one with higher confidence to calculatate occupancy and location\n if cv2.pointPolygonTest(core_interest_area_polygon, (x, y), False) == 1:\n occupancy_core += 1\n else:\n occupancy_margin += 1\n \n cv2.drawContours(output_image_whole_interest_area, [core_interest_area_polygon], -1, (255, 255, 0), 2, cv2.LINE_AA)\n cv2.putText(output_image_whole_interest_area, \"Whole Occupancy: {}, Core Occupancy: {}, Margin Occupancy: {}\".format(occupancy_whole, occupancy_core, occupancy_margin), (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n cv2.putText(core_interest_area, \"Core Occupancy: {}\".format(occupancy_core), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n cv2.putText(margin_interest_area, \"Margin Occupancy: {}\".format(occupancy_margin), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n # save estimated occupancy data\n fieldnames = ['Time', 'Occupancy']\n with open(out_occupancy_whole, 'a') as csv_datafile:\n writer = csv.DictWriter(csv_datafile, fieldnames = fieldnames)\n writer.writerow({'Time':time, 'Occupancy': occupancy_whole})\n with open(out_occupancy_core, 'a') as csv_datafile:\n writer = csv.DictWriter(csv_datafile, fieldnames = fieldnames)\n writer.writerow({'Time':time, 'Occupancy': occupancy_core})\n with open(out_occupancy_margin, 'a') as csv_datafile:\n writer = csv.DictWriter(csv_datafile, fieldnames = fieldnames)\n writer.writerow({'Time':time, 'Occupancy': occupancy_margin})\n # save processed videos\n out_camera_frame_whole.write(output_image_whole_interest_area)\n else:\n # Pass this frame if cannot grab an image.\n print('Frame: {}, grabbed={} and frame={}'.format(frame_count, grabbed, frame))\n\n ########################################################################\n # Smoothen Estimated Occupancy, then detect interesting event #\n ########################################################################\n \n # read estimated occupancy in Three Interest Areas\n occupancy_whole = pd.read_csv(out_occupancy_whole)\n occupancy_core = pd.read_csv(out_occupancy_core)\n occupancy_margin = pd.read_csv(out_occupancy_margin)\n \n # save plot of estimated occupancy in Three Interest Areas\n fig_filename = os.path.join(args['output_directory'], '{}_Subplot_Estimated_Occupancy.png'.format(file_name))\n #subplot_estimated_occupancy(occupancy_whole, occupancy_core, occupancy_margin, fig_filename)\n fig_filename = os.path.join(args['output_directory'], '{}_Plot_Estimated_Occupancy.png'.format(file_name))\n plot_estimated_occupancy(occupancy_whole, occupancy_core, occupancy_margin, fig_filename)\n \n # smoothen\n window_size = 25\n smooth_type='mean'\n stride = 1\n smooth_occupancy_whole = moving_smoothing(occupancy_whole, window_size, smooth_type)\n smooth_occupancy_core = moving_smoothing(occupancy_core, window_size, smooth_type)\n smooth_occupancy_margin = moving_smoothing(occupancy_margin, window_size, smooth_type)\n \n fig_filename = os.path.join(args['output_directory'], '{}_Subplot_Smooth_Estimated_Occupancy.png'.format(file_name))\n #subplot_estimated_occupancy(smooth_occupancy_whole,\n # smooth_occupancy_core,\n # smooth_occupancy_margin, \n # fig_filename, \n # smooth_flag = True)\n# fig_filename = os.path.join(args['output_directory'], '{}_Plot_Smooth_Estimated_Occupancy.png'.format(file_name))\n# plot_estimated_occupancy(smooth_occupancy_whole,\n# smooth_occupancy_core,\n# smooth_occupancy_margin, \n# fig_filename,\n# smooth_flag = True)\n# \n # load Senario Truth Table\n senarios_truth_table = pd.read_csv('analize_visitor_in_and_out_senario_truth_table.csv')\n \n # Interpret\n senario_sequence, event_sequence, event_time = interpret_senario(smooth_occupancy_core, \n smooth_occupancy_margin, \n smooth_occupancy_whole, \n senarios_truth_table)\n# # Plot interesting events\n# fig_filename = os.path.join(args['output_directory'], '{}_Plot_Interesting_Event_smooth_type_{}_window_size_{}_stride{}'.format(file_name, smooth_type, window_size, stride))\n# plot_detected_interesting_event(senario_sequence, event_sequence, event_time, fig_filename)\n \n # Tag\n tag_interesting_event_description_on_video(output_video_filename, \n smooth_type, window_size, stride,\n senario_sequence, event_sequence, event_time)\n \n \n \n\n\n","sub_path":"archived/process_video.py","file_name":"process_video.py","file_ext":"py","file_size_in_byte":26179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"259431976","text":"# Mirjam Hemberger \r\n# 14.03.2018\r\n# this script is used to test the functions in EEG-motor-imaginery-NST_live.py and nst_eeg_live without having to call them from record_data or run_session\r\n# Training of the model with two Run.mat files, testing with one Run.mat file\r\n\r\n\r\n#import matplotlib.pyplot as plt \r\n\r\nimport sys, os, os.path\r\nsys.path.append('C:\\\\Users\\\\mirja\\\\Anaconda3\\\\Lib\\\\site-packages\\\\gumpy-master\\\\gumpy')\r\n\r\nimport numpy as np\r\nimport gumpy\r\n\r\nfrom eeg_motor_imagery_NST_live import liveEEG\r\nfrom gumpy.data.nst_eeg_live import NST_EEG_LIVE\r\n\r\nif __name__ == '__main__':\r\n #save_stdout = sys.stdout\r\n #fh = open('Results_LiveClassfication.txt', 'w')\r\n #sys.stdout = fh\r\n subjects = {'s1'}\r\n print('\\nTraining with Run1.mat and Run2.mat, testing with Run3.mat')\r\n print('Classifier: Quadratic LDA\\n')\r\n \r\n for subject in subjects:\r\n print('\\n\\n\\nData identification:', subject, '\\n')\r\n data_base_dir = 'C:\\\\Users\\\\mirja\\\\Documents\\\\TUM\\\\IP\\\\NST'\r\n base_dir = os.path.join(data_base_dir, subject)\r\n \r\n #isn't used for training with Run1.mat and Run2.mat\r\n file_name = 'Run1.mat'\r\n \r\n file_name2 = 'Run3.mat'\r\n\r\n #used for testing\r\n flag = 1\r\n\r\n myclass = liveEEG(base_dir,file_name, flag)\r\n myclass.fit()\r\n\r\n myclass2 = liveEEG(base_dir, file_name2)\r\n\r\n count_pred_true = 0\r\n count_pred_false = 0\r\n\r\n for i in range(0,myclass2.data_notlive.trials.shape[0]):\r\n fs = myclass2.data_notlive.sampling_freq\r\n label = myclass2.data_notlive.labels[i]+1\r\n trial = myclass2.data_notlive.trials[i]\r\n if i < (myclass2.data_notlive.trials.shape[0] - 1):\r\n next_trial = myclass2.data_notlive.trials[i+1]\r\n X = myclass2.data_notlive.raw_data[trial:next_trial]\r\n else:\r\n X = myclass2.data_notlive.raw_data[trial:]\r\n \r\n trial = 0\r\n nst_eeg_live = NST_EEG_LIVE(base_dir, file_name2)\r\n nst_eeg_live.load_from_mat(label,trial,X,fs)\r\n \r\n current_classifier, pred_true, pred_valid = myclass.classify_live(nst_eeg_live)\r\n \r\n if not pred_valid:\r\n continue\r\n\r\n print('Classification result: ',current_classifier[0],'\\n')\r\n if pred_true:\r\n print('This is true!\\n')\r\n count_pred_true = count_pred_true + 1\r\n else:\r\n count_pred_false += 1\r\n print('This is false!\\n')\r\n\r\n print('Count of true predictions:', count_pred_true)\r\n print('Count of false predictions:', count_pred_false)\r\n print('Percentage of true predictions:', 100*count_pred_true/(count_pred_false+count_pred_true), '\\n\\n')\r\n\r\n #sys.stdout = save_stdout\r\n #fh.close()\r\n","sub_path":"src/Live-EEG_decoding/TEST_live_EEG-Run12_Run3.py","file_name":"TEST_live_EEG-Run12_Run3.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"630317593","text":"#!/usr/bin/python3\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport numpy as np\n\n# displays plot if no filename is\n# specified otherwise save plot\n# using file arg\n# ARGS: plot, filename\n# RETURNS: void\ndef visualize(plt,filename):\n if(filename == None):\n plt.show()\n else:\n plt.savefig(filename)\n\n plt.close();\n return\n\ndef init_axes():\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_axis_bgcolor('black')\n return ax\n\ndef plot_scores(scores,mid,tn,targ_file=None):\n ax = init_axes()\n n = len(scores)\n # bar chart parameters\n bar_idx = np.arange(n)\n bar_width = 0.1\n # use 10% of score range as pad\n pad = 0.1*(max(scores) - min(scores))\n\n # plot bars using alternating colors\n even_frames = [scores[i] for i in range(0,n,2)]\n odd_frames = [scores[i] for i in range(1,n,2)]\n\n ax.bar(bar_idx[0::2], even_frames, color='c')\n ax.bar(bar_idx[1::2], odd_frames, color='y')\n\n plt.title(\"scores for \"+mid+\" t\"+str(tn))\n plt.xlabel(\"trajectory frame\")\n plt.xlim(-1,n+1)\n plt.ylabel(\"score\")\n plt.ylim(min(scores)-pad,max(scores)+pad+1)\n\n visualize(plt,targ_file)\n\n return\n\n# displays plot of non-zero values\n# in matrix where each index represents\n# a block of size bsz. Please pass a\n# sparse matrix.\n# ARGS: matrix (sparse), block size,\n# filename (optional)\n# RETURNS: void\ndef plot_mat(mat,bsz,kern=None,targ_file=None):\n ax = init_axes()\n # get matrix shape\n szx = mat.shape[0]\n szy = mat.shape[1]\n mark_size = bsz*100\n\n if kern == None:\n kern = np.ones((szx,szy),dtype=int)\n\n print(\"plotting mat(\"+str(szx)+\"x\"+str(szy)+\")\")\n for row in range(0,szx):\n for col in range(0,szy):\n # show centers of moth/trees\n if mat[row][col] < 0:\n ax.scatter(row,col,s=mark_size*kern[row][col],c='b',marker='x')\n elif mat[row][col] > 0:\n ax.scatter(row,col,s=mark_size*kern[row][col],c='r',marker='x')\n else:\n continue\n\n\n plt.title(\"matrix (block_size=\"+str(round(bsz,5))\n +\" msize=\"+str(round(bsz*szx,5))+\")\")\n plt.xlabel(\"discritized x\")\n plt.xlim(-1,szx)\n plt.ylabel(\"discritized y\")\n plt.ylim(-1,szy)\n\n visualize(plt,targ_file)\n return\n\n# displays objects in environment and\n# trajectory path. Pass a filename to\n# save the figure.\n# ARGS: trajectory, environment, file (opt)\n# RETURNS: void\ndef plot(traj,env,targ_file=None):\n ax = init_axes()\n\n print(\"plotting trees: \"+str(len(env)))\n for tree in env.values:\n ax.add_patch(plt.Circle((tree[0],tree[1]),tree[2],color='g'))\n\n print(\"plotting pts: \"+str(len(traj)))\n ax.scatter(traj.pos_x,traj.pos_y,s=5,c='b',marker='.')\n\n if('obstacles' in traj.columns):\n plt.title(traj.moth_id.iloc[0]+\" in \"+traj.obstacles.iloc[0]+\" forest\")\n else:\n plt.title(traj.moth_id.iloc[0]+\" in bright forest\")\n plt.xlabel(\"x\")\n plt.xlim(\n min(min(env.x),min(traj.pos_x)),\n max(max(env.x),max(traj.pos_x)))\n plt.ylabel(\"y\")\n plt.ylim(\n min(min(env.y),min(traj.pos_y)),\n max(max(env.y),max(traj.pos_y)))\n\n visualize(plt,targ_file)\n return\n\ndef plot_trees(env,targ_file=None):\n ax = init_axes()\n\n print(\"plotting trees: \"+str(len(env)))\n for tree in env.values:\n ax.add_patch(plt.Circle((tree[0],tree[1]),tree[2],color='g'))\n\n plt.xlabel(\"x\")\n plt.xlim(min(env.x),max(env.x))\n plt.ylabel(\"y\")\n plt.ylim(min(env.y),max(env.y))\n\n visualize(plt,targ_file)\n return\n\n# displays objects in environment, patch,\n# and trajectory point. A box of length\n# 2*patch size is drawn to visually indicate\n# patch boundary. Pass a filename to save\n# the figure.\n# ARGS: point, patch, patch size, env\n# filename (opt)\n# RETURNS: void\ndef plot_frame(pt,patch,size,env,targ_file=None):\n ax = init_axes()\n\n print(\"plotting trees: \"+str(len(env)))\n # plot trees outside of patch\n for tree in env.values:\n if(not(tree[0] in patch.x and tree[1] in patch.y and tree[2] in patch.r)):\n ax.add_patch(plt.Circle((tree[0],tree[1]),tree[2],color='g'))\n\n print(\"plotting patch trees: \"+str(len(patch)))\n ax.scatter(pt.pos_x,pt.pos_y,s=100*max(env.r),c='b',marker='x')\n # plot trees in patch\n for tree in patch.values:\n ax.add_patch(plt.Circle((tree[0],tree[1]),tree[2],color='c'))\n # draw boundary of patch in case no trees are in it\n xoffset = pt.pos_x-size\n yoffset = pt.pos_y-size\n ax.add_patch(patches.Rectangle(\n (xoffset,yoffset)\n ,2*size\n ,2*size\n ,fill=False\n ,edgecolor=\"red\"))\n\n plt.title(\"scoring window centered on moth (patch dim=\"\n +str(2*size)+'x'+str(2*size)+\")\")\n plt.xlabel(\"x\")\n plt.xlim(\n min(min(env.x),pt.pos_x),\n max(max(env.x),pt.pos_x))\n plt.ylabel(\"y\")\n plt.ylim(\n min(min(env.y),pt.pos_y),\n max(max(env.y),pt.pos_y))\n\n visualize(plt,targ_file)\n return","sub_path":"scripts/score_trajs/plotStuff.py","file_name":"plotStuff.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"445515810","text":"#!/usr/bin/env python\n\nimport os\nimport sys\n\nimport binaryornot\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nif sys.argv[-1] == 'publish':\n os.system('python setup.py sdist upload')\n sys.exit()\n\nreadme = open('README.rst').read()\nhistory = open('HISTORY.rst').read().replace('.. :changelog:', '')\n\nsetup(\n name='binaryornot',\n version='0.3.0',\n description='Ultra-lightweight pure Python package to check if a file is binary or text.',\n long_description=readme + '\\n\\n' + history,\n author='Audrey Roy',\n author_email='audreyr@gmail.com',\n url='https://github.com/audreyr/binaryornot',\n packages=[\n 'binaryornot',\n ],\n package_dir={'binaryornot': 'binaryornot'},\n include_package_data=True,\n install_requires=[\n ],\n license=\"BSD\",\n zip_safe=False,\n keywords='binaryornot',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n \"Programming Language :: Python :: 2\",\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n ],\n test_suite='tests',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514880560","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Bool\nfrom dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport\nfrom geometry_msgs.msg import TwistStamped\nimport math\n\nfrom data_types import ControlParameters, Velocity, ControlCommand\nfrom twist_controller import Controller\n\n\"\"\"\nKeep in mind the status of `dbw_enabled`. While in the simulator, its enabled\nall the time, in the real car, that will not be the case. This may cause the\nPID controller to accumulate error because the car could temporarily be driven\n by a human instead of your controller.\n\"\"\"\n\n# The DBW system expects messages at 50Hz, and will disengage (reverting\n# control back to the driver) if control messages are published at less\n# than 10hz.\nFREQUENCY = 50\n\n\"\"\"\nThe car has an automatic transmission, which means the car will roll forward\nif no brake and no throttle is applied. To prevent it from moving requires\nabout 700 Nm of torque.\n\"\"\"\n\n\nclass DBWNode(object):\n def __init__(self):\n rospy.init_node(\"dbw_node\")\n\n # Parameters\n params = ControlParameters()\n params.vehicle_mass = rospy.get_param(\"~vehicle_mass\", 1736.35)\n params.fuel_capacity = rospy.get_param(\"~fuel_capacity\", 13.5)\n params.brake_deadband = rospy.get_param(\"~brake_deadband\", 0.1)\n params.decel_limit = rospy.get_param(\"~decel_limit\", -5)\n params.accel_limit = rospy.get_param(\"~accel_limit\", 5.0)\n params.wheel_radius = rospy.get_param(\"~wheel_radius\", 0.2413)\n params.wheel_base = rospy.get_param(\"~wheel_base\", 2.8498)\n params.steer_ratio = rospy.get_param(\"~steer_ratio\", 14.8)\n params.max_lat_accel = rospy.get_param(\"~max_lat_accel\", 3.0)\n params.max_steer_angle = rospy.get_param(\"~max_steer_angle\", 1.57)\n\n # Publishers\n self.steer_pub = rospy.Publisher(\n \"/vehicle/steering_cmd\", SteeringCmd, queue_size=1\n )\n self.throttle_pub = rospy.Publisher(\n \"/vehicle/throttle_cmd\", ThrottleCmd, queue_size=1\n )\n self.brake_pub = rospy.Publisher(\"/vehicle/brake_cmd\", BrakeCmd, queue_size=1)\n\n # Controller\n self.command = ControlCommand()\n self.controller = Controller(params)\n\n # Subscrptions\n self.target_vel = None\n self.current_vel = None\n self.is_dbw_enabled = None\n rospy.Subscriber(\"/twist_cmd\", TwistStamped, self.twist_cb)\n rospy.Subscriber(\"/current_velocity\", TwistStamped, self.velocity_cb)\n rospy.Subscriber(\"/vehicle/dbw_enabled\", Bool, self.dbw_enabled_cb)\n\n self.loop()\n\n def loop(self):\n rate = rospy.Rate(FREQUENCY)\n while not rospy.is_shutdown():\n # update controller\n if self.is_data_valid():\n self.command = self.controller.control(\n self.current_vel, self.target_vel, self.is_dbw_enabled\n )\n\n # only publish when intended\n if self.is_dbw_enabled:\n self.publish()\n rate.sleep()\n\n def publish(self):\n tcmd = ThrottleCmd()\n tcmd.enable = True\n tcmd.pedal_cmd_type = ThrottleCmd.CMD_PERCENT\n tcmd.pedal_cmd = self.command.throttle\n self.throttle_pub.publish(tcmd)\n\n scmd = SteeringCmd()\n scmd.enable = True\n scmd.steering_wheel_angle_cmd = self.command.steer\n self.steer_pub.publish(scmd)\n\n bcmd = BrakeCmd()\n bcmd.enable = True\n bcmd.pedal_cmd_type = BrakeCmd.CMD_TORQUE\n bcmd.pedal_cmd = self.command.brake\n self.brake_pub.publish(bcmd)\n\n def dbw_enabled_cb(self, msg):\n self.is_dbw_enabled = msg.data\n\n def twist_cb(self, msg):\n linear = msg.twist.linear.x\n angular = msg.twist.angular.z\n self.target_vel = Velocity(linear, angular)\n\n def velocity_cb(self, msg):\n linear = msg.twist.linear.x\n angular = msg.twist.angular.z\n self.current_vel = Velocity(linear, angular)\n\n def is_data_valid(self):\n # TODO: dismiss outdated data\n return self.target_vel and self.current_vel and self.is_dbw_enabled\n\n\nif __name__ == \"__main__\":\n DBWNode()\n","sub_path":"ros/src/twist_controller/dbw_node.py","file_name":"dbw_node.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"409313524","text":"'''\n정수 4를 1, 2, 3의 합으로 나타내는 방법은 총 7가지가 있다. 합을 나타낼 때는 수를 1개 이상 사용해야 한다.\n1+ 1+1+1\n1+ 1+2\n1+ 2+1\n1+ 3\n\n2+ 1+1\n2+ 2\n\n3+ 1\n정수 n이 주어졌을 때, n을 1, 2, 3의 합으로 나타내는 방법의 수를 구하는 프로그램을 작성하시오.\n\n7\n44\n274\n'''\n\nf = open(\"input.txt\", \"r\")\nn = int(f.readline())\n\ndef DP(k): # Top_down\n if k == 0:\n return 1\n elif k <= 2:\n return k\n else:\n return DP(k - 1) + DP(k - 2) + DP(k - 3)\n\nfor _ in range(n):\n k = int(f.readline())\n print(DP(k))","sub_path":"baekjoon/9095.py","file_name":"9095.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134839714","text":"import pygame\nfrom pygame.locals import *\nimport sys\nimport numpy as np\nimport random\n\ndisplay = [1010, 1010]\nworld_size = [100, 50]\nnum_key = [K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9]\n\nclass World:\n def __init__(self):\n #描画速度\n self.speed = 1\n self.world = np.zeros(tuple(world_size + [3]))\n self.color = np.asarray([[255.0, 255.0, 255.0], [255.0, 0.0, 0.0], [0.0, 255.0, 0.0],[0.0, 0.0, 255.0], [0.0, 0.0, 0.0]])\n \n #ランダムに初期化\n def random_init(self, p, color_flag=True):\n for i in range(world_size[0]):\n for j in range(world_size[1]):\n if random.random() > p:\n continue\n \n if color_flag:\n color = self.color[random.randint(0, 3)]\n else:\n color = self.color[0]\n self.world[i, j] = color\n \n def draw(self, screen):\n for i in range(world_size[0]):\n for j in range(world_size[1]):\n pygame.draw.rect(screen, tuple(self.world[i, j]), Rect(10*j + 10, 10*i + 10, 10, 10))\n \n def update(self):\n next_world = np.zeros(tuple(world_size + [3]))\n flags = self.world.sum(axis = 2) > 0\n \n for i in range(world_size[0]):\n for j in range(world_size[1]):\n min_x = max(0, j-1)\n max_x = min(world_size[1], j+2)\n min_y = max(0, i-1)\n max_y = min(world_size[0], i+2)\n count = np.sum(flags[min_y:max_y, min_x:max_x])\n #死んだセル\n if flags[i, j] == 0:\n #セルの誕生\n if count == 3:\n area = self.world[min_y:max_y, min_x:max_x]\n next_world[i, j] = area.reshape(-1, 3).sum(axis=0) / count\n else:\n #not 過疎 または 過密\n if 3 < count < 6:\n next_world[i, j] = self.world[i, j]\n \n self.world = next_world\n \ndef main():\n pygame.init()\n screen = pygame.display.set_mode(display)\n pygame.display.set_caption(\"LifeGame\")\n \n world = World()\n world.random_init(0.3, True)\n counter = 0\n \n while(1):\n screen.fill((0,0,0))\n \n world.draw(screen)\n pygame.display.update()\n pygame.time.wait(5)\n \n counter += 1\n if counter > world.speed:\n world.update()\n counter = 0\n \n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n if event.key == K_DOWN:\n world.speed = world.speed+1\n if event.key == K_UP:\n world.speed = max(0, world.speed-1)\n if event.key in num_key:\n world.random_init((num_key.index(event.key)+1.0) * 0.1, True)\n \nif __name__ == \"__main__\":\n main()\n ","sub_path":"life_game.py","file_name":"life_game.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"191398433","text":"import datetime\nimport os\n\nimport xlsxwriter\nimport openpyxl\nfrom selenium.common.exceptions import WebDriverException\n\nfrom core.abstract import Record\nfrom sched.demorgen import demo\nfrom util.util import schedule_headers_map, alpha, make_soup\n\nfrom enrich import imdb as IMDB\nfrom enrich import wiki as WIKI\n\ntoday = datetime.date.today()\n\n\ndef records_to_schedule_excel_sheet(records: [Record], row_headers):\n year = datetime.datetime.now().year\n workbook_name = f\"core/schedule_{year}.xlsx\"\n\n if os.path.isfile(workbook_name):\n existing_workbook = openpyxl.load_workbook(workbook_name)\n ws = existing_workbook.active\n max_row = ws.max_row\n\n for row_number, record in enumerate(records):\n for c, v in enumerate(row_headers):\n cell_name = alpha[c] + str(row_number+max_row+1)\n ws[cell_name] = str(getattr(record, v))\n\n existing_workbook.save(workbook_name)\n existing_workbook.close()\n else:\n workbook = xlsxwriter.Workbook(workbook_name) # Create new workbook for the year\n worksheet = workbook.add_worksheet()\n\n for c, h in enumerate(row_headers.keys()):\n worksheet.write(alpha[c] + str(1), row_headers[h]) # row_headers[h] to get the formatted row header\n\n for row, record in enumerate(records):\n for c, field_name in enumerate(row_headers.keys()):\n worksheet.write(alpha[c] + str(row + 2), str(getattr(record, field_name)))\n\n workbook.close()\n\n\ndef add_schedule_info_to_record(record: Record): # Return if page was found & information added\n\n imdb_page_url = IMDB.get_page_url_from_title(record.title)\n parsed = False\n\n if imdb_page_url:\n page_soup = make_soup(imdb_page_url)\n IMDB.add_schedule_info_to_record(record, page_soup)\n parsed = True\n\n if not parsed:\n parsed = WIKI.add_en_info(record)\n\n if not parsed:\n WIKI.add_nl_info(record)\n\n\ndef get_schedule_records() -> [Record]:\n\n demoScraper = demo()\n records = demoScraper.get_records()\n\n for record in records:\n try:\n add_schedule_info_to_record(record)\n #print(\"Trying to add info for record with title: \" + record.title)\n except Exception as e:\n print(\"Error when adding info to record: \" + str(e))\n continue\n return records\n\n\ndef run():\n try:\n records = get_schedule_records()\n records_to_schedule_excel_sheet(records, schedule_headers_map)\n print(\"\\nWriting schedule to root directory... \")\n except WebDriverException:\n print(\"Selenium client not reachable, exiting...\")\n\n\nif __name__ == '__main__':\n run()\n\n\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"47563420","text":"from collections import defaultdict\nimport math\n\n\ndef def_value():\n return 0\n\n\ndef def_list():\n return []\n\n\ndef score(motifs):\n \"\"\"\n get score of motifs\n \"\"\"\n score = 0\n for i in range(len(motifs[0])):\n dct = defaultdict(def_value)\n for m in motifs:\n dct[m[i]] += 1\n lst = [dct[\"A\"], dct[\"C\"], dct[\"T\"], dct[\"G\"]]\n lst.sort()\n score += lst[0]+lst[1]+lst[2]\n return score\n\n\ndef pro(motifs):\n \"\"\"\n get the profile of motifs\n \"\"\"\n d = len(motifs) * 1.0\n pro = defaultdict(def_list)\n for i in range(len(motifs[0])):\n dct = defaultdict(def_value)\n for m in motifs:\n dct[m[i]] += 1/d\n pro[\"A\"].append((dct[\"A\"] or 0)+1/d)\n pro[\"C\"].append((dct[\"C\"] or 0)+1/d)\n pro[\"G\"].append((dct[\"G\"] or 0)+1/d)\n pro[\"T\"].append((dct[\"T\"] or 0)+1/d)\n return pro\n\n\ndef kmers(seq, k):\n \"\"\"\n find all the kmers in seq\n \"\"\"\n kmers = []\n for i in range(len(seq)-k+1):\n kmers.append(seq[i:i+k])\n return list(dict.fromkeys(kmers)) # removes duplicates\n\n\ndef pr(mer, profile):\n \"\"\"\n calculate probability of mer fitting into profile\n \"\"\"\n prob = 1\n for i, char in enumerate(mer):\n prob *= profile[char][i]\n return prob\n\n\ndef mostPr(seq, k, profile):\n \"\"\"\n most probable kmer in the seq that fits the profile\n \"\"\"\n km = kmers(seq, k)\n score = -1\n median = \"\"\n for kmer in km:\n p = pr(kmer, profile)\n if p > score:\n score = p\n median = kmer\n return median\n\n\ndef greedyMotifSearch(dna, k, t):\n \"\"\"\n best motif among the dna\n \"\"\"\n bestScore = math.inf\n\n for i in range(len(dna[0])-k+1):\n motif = [dna[0][i:i+k]]\n for j in range(1, t):\n motif.append(mostPr(dna[j], k, pro(motif)))\n if score(motif) < bestScore:\n bestScore = score(motif)\n\n bestList = []\n for i in range(len(dna[0])-k+1):\n motif = [dna[0][i:i+k]]\n for j in range(1, t):\n motif.append(mostPr(dna[j], k, pro(motif)))\n if score(motif) == bestScore:\n bestList.append(motif)\n\n return bestList\n\n\nif __name__ == \"__main__\":\n\n motifs = [\n \"TCGGGGGTTTTT\",\n \"CCGGTGACTTAC\",\n \"ACGGGGATTTTC\",\n \"TTGGGGACTTTT\",\n \"AAGGGGACTTCC\",\n \"TTGGGGACTTCC\",\n \"TCGGGGATTCAT\",\n \"TCGGGGATTCCT\",\n \"TAGGGGAACTAC\",\n \"TCGGGTATAACC\"\n ]\n\n # print(score(motifs))\n # print(pro(motifs))\n\n k = 3\n t = 5\n dna = [\n \"GGCGTTCAGGCA\",\n \"AAGAATCAGTCA\",\n \"CAAGGAGTTCGC\",\n \"CACGTCAATCAC\",\n \"CAATAATATTCG\"\n ]\n\n print((greedyMotifSearch(dna, k, t)))\n\n with open(\"dataset_160_9.txt\", \"r\") as f:\n lines = f.read().splitlines()\n (k, t) = [int(x) for x in lines[0].split(\" \")]\n dna = lines[1:t+1]\n\n print((greedyMotifSearch(dna, k, t)))\n\n k = 7\n t = 3\n dna = [\n \"CTCGATGAGTAGGAAAGTAGTTTCACTGGGCGAACCACCCCGGCGCTAATCCTAGTGCCC\",\n \"GCAATCCTACCCGAGGCCACATATCAGTAGGAACTAGAACCACCACGGGTGGCTAGTTTC\",\n \"GGTGTTGAACCACGGGGTTAGTTTCATCTATTGTAGGAATCGGCTTCAAATCCTACACAG\"\n ]\n\n print((greedyMotifSearch(dna, k, t)))\n","sub_path":"archive-bioinformatics-1/bio-wk3-6_greedy-motif.py","file_name":"bio-wk3-6_greedy-motif.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"623835162","text":"import os.path\nimport sys\nimport numpy as np\nimport pandas as pd\n\nimport pull_soi_corp as corp\nimport pull_soi_partner as prt\nimport pull_soi_proprietorship as prop\n\n_FILE_FCTR = 10**3\n\ndef pull_soi_data():\n\tsector_dfs = {}\n\tsector_dfs.update(corp.load_corp_data())\n\n\tsector_dfs.update(prt.load_partner_data(sector_dfs))\n\n\tsector_dfs.update(prop.load_proprietorship_data(sector_dfs))\n\n\treturn sector_dfs\n\n\ndef format_dataframe(df, crosswalk):\n indices = []\n # Removes the extra characters from the industry names\n for string in df.index:\n indices.append(string.replace('\\n',' ').replace('\\r',''))\n # Adds the industry names as the first column in the dataframe\n df.insert(0,indices[0],indices)\n # Stores the values of the first row in columns\n columns = df.iloc[0].tolist()\n # Drops the first row because it will become the column labels\n df = df[df.Item != 'Item']\n # Removes extra characters from the column labels\n for i in xrange(0,len(columns)):\n columns[i] = columns[i].strip().replace('\\r','')\n # Sets the new column values\n df.columns = columns\n # Creates a new index based on the length of the crosswalk (needs to match)\n df.index = np.arange(0,len(crosswalk['Codes:']))\n # Inserts the codes from the crosswalk as the second column in the df\n df.insert(1,'Codes:',crosswalk['Codes:'])\n names = df['Item']\n codes = df['Codes:']\n # Multiplies the entire dataframe by a factor of a thousand \n df = df * _FILE_FCTR\n # Replaces the industry names and codes to adjust for the multiplication in the previous step\n df['Item'] = names\n df['Codes:'] = codes\n # Returns the newly formatted dataframe\n return df\n\n# Fills in the missing values using the proportion of corporate industry values\ndef interpolate_data(sector_dfs, df):\n # Takes the total corp values as the baseline\n base_df = sector_dfs['tot_corp']\n # Stores the dataframe in a numpy array\n corp_data = np.array(base_df)\n # Stores the partner or prop data in a numpy array\n prt_data = np.array(df)\n # Iterates over each industry in the partner or prop data\n for i in xrange(0, len(prt_data)):\n # If it is a two digit code then it will appear in the denominator of the following calcs\n if(len(str(int(prt_data[i][0]))) == 2):\n # Grabs the parent data from the corporate array\n parent_ind = corp_data[i]\n # Grabs the partner or prop data as well\n prt_ind = prt_data[i][1:]\n # If the partner or prop data is missing a value\n if(prt_data[i][1] == 0):\n # Grabs the corporate data for the minor industry\n corp_ind = corp_data[i]\n # Divides the minor industry corporate data by the major industry data\n ratios = corp_ind / parent_ind\n # Mulitplies the partner or prop data for the major data to find minor partner data\n new_data = prt_ind * ratios[1:]\n # Sets new values in the partner or prop dataframe\n df.set_value(i, 'FA', new_data[0])\n df.set_value(i, 'Inv', new_data[1])\n df.set_value(i, 'Land', new_data[2])\n # Returns the partner or prop dataframe with all the missing values filled in \n return df","sub_path":"Python/btax/soi_processing.py","file_name":"soi_processing.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"537346290","text":"import tensorflow as tf\nimport config as cfg\nimport numpy as np\nclass layermaker():\n def __init__(self,truncated_mean,truncated_stddev,bias,name_scope):\n self.name_scope = name_scope\n self.truncated_mean = truncated_mean\n self.truncated_stddev = truncated_stddev\n self.bias = bias\n self.idx_conv = 1\n self.idx_el = 1\n self.variable_ls = []\n def conv_layer(self,input,size,in_chanel,out_chanel,stride = 1,padding = 'SAME',linear = False,l2 = False):\n kernel_init = tf.Variable(tf.truncated_normal([size,size,in_chanel,out_chanel],mean=self.truncated_mean,stddev=self.truncated_stddev,dtype=tf.float32), name=self.name_scope+'conv_kernel'+str(self.idx_conv))\n conv = tf.nn.conv2d(input,kernel_init,strides=[1,stride,stride,1],padding=padding)\n bias_init = tf.Variable(tf.constant(self.bias, shape=[out_chanel],dtype=tf.float32), name=self.name_scope+'bias'+str(self.idx_conv))\n conv_bias = conv+bias_init\n self.idx_conv = self.idx_conv + 1\n self.variable_ls.append(kernel_init)\n self.variable_ls.append(bias_init)\n if(linear):\n if(l2):\n return conv_bias,kernel_init,bias_init\n else:\n return conv_bias\n else:\n if (l2):\n return tf.maximum(0.1 * conv_bias, conv_bias), kernel_init, bias_init\n else:\n return tf.maximum(0.1 * conv_bias, conv_bias)\n\n\n def pool_layer(self, input, size = 2, stride = 2):\n return tf.nn.max_pool(input, ksize=[1,size,size,1], strides=[1,stride,stride,1],padding='VALID')\n\n def aver_pool_layer(self, input, size=2, stride=2):\n return tf.nn.avg_pool(input, ksize=[1, size, size, 1], strides=[1, stride, stride, 1], padding='VALID')\n\n def bilinear_upsample_layer(self,input,in_chanel,out_size):\n upsample_kernel = np.array([[0.0625, 0.1875, 0.1875, 0.0625], [0.1875, 0.5625, 0.5625, 0.1875],\n [0.1875, 0.5625, 0.5625, 0.1875], [0.0625, 0.1875, 0.1875, 0.0625]],\n dtype=np.float32)\n upsample_filter_np = np.zeros((4, 4, in_chanel, in_chanel), dtype=np.float32)\n for i in range(in_chanel):\n upsample_filter_np[:, :, i, i] = upsample_kernel\n\n upsample_filter_tf = tf.constant(upsample_filter_np,dtype=tf.float32)\n\n out = tf.nn.conv2d_transpose(input, upsample_filter_tf,\n output_shape=[cfg.BATCH_SIZE, out_size, out_size, in_chanel],\n strides=[1, 2, 2, 1])\n return out\n\n def deconv_layer(self,input, scale, out_size, in_chanel, out_chanel,linear = False,l2=False,stride = 2):\n kernel_init = tf.Variable(\n tf.truncated_normal([scale, scale, out_chanel, in_chanel], mean=self.truncated_mean,\n stddev=self.truncated_stddev,\n dtype=tf.float32), name=self.name_scope + 'deconv_kernel' + str(self.idx_conv))\n bias_init = tf.Variable(tf.constant(self.bias, shape=[out_chanel], dtype=tf.float32),\n name=self.name_scope + 'bias' + str(self.idx_conv))\n deconv = tf.nn.conv2d_transpose(input, kernel_init, [cfg.BATCH_SIZE, out_size, out_size, out_chanel],\n strides=[1, stride, stride, 1],padding='VALID')\n deconv_bias = deconv+bias_init\n self.idx_conv = self.idx_conv + 1\n\n if (linear):\n if (l2):\n return deconv_bias, kernel_init, bias_init\n else:\n return deconv_bias\n else:\n if (l2):\n return tf.maximum(0.1 * deconv_bias, deconv_bias), kernel_init, bias_init\n else:\n return tf.maximum(0.1 * deconv_bias, deconv_bias)\n\n def slice_layer(self,input,out_size,chanel,edge_cut=1):\n out = tf.slice(input,[0,edge_cut,edge_cut,0],[cfg.BATCH_SIZE,out_size,out_size,chanel])\n return out\n\n","sub_path":"layer_maker_tradition.py","file_name":"layer_maker_tradition.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"624491296","text":"from django_enumfield import enum\n\n\nclass TransactionStatuses(enum.Enum):\n PENDING = 0\n FINISHED = 1\n ERROR = 2\n\n\nclass AccountStatuses(enum.Enum):\n ACTIVE = 0\n SUSPENDED = 1\n BLOCKED = 2\n\n\nclass Currencies(enum.Enum):\n USD = 0\n EUR = 1\n CNY = 2\n","sub_path":"backend/transactions/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"286820263","text":"\"\"\"\nitemshop.py\nthe itemShop function creates all of the objects needed for the itemshop views.\nThis includes the buying and selling of items.\n\"\"\"\n\nimport pygame\nimport gui as GUI\nfrom gui.shared import menuSpriteGroup\nfrom . import shared\nimport transitions\n\n##\n# This creates the item shop gui, except for the buy and sell windows.\n##\ndef itemShop(parent):\n\tresSettings = shared.getResolutionSettings('shop')\n\t\n\tportraitSettings = resSettings['portrait']\n\tportraitShop = pygame.image.load(\"images/portrait-shop.png\").convert_alpha()\n\tportrait = GUI.PortraitBox(\n\t\tportraitShop,\n\t\tportraitSettings['size'],\n\t\tportraitSettings['location'],\n\t\tportraitSettings['backgroundImage']\n\t\t)\n\n\tbackPanelSettings = resSettings['backPanel']\n\tbackPlate = GUI.BackPanel(\n\t\tbackPanelSettings['size'], \n\t\tbackPanelSettings['location'],\n\t\tdeleteOnClickOff = False,\n\t\tbackgroundImage = backPanelSettings['backgroundImage']\n\t\t)\n\n\tdef makeBuyWindow(x):\n\t\tbuyWindowSettings = resSettings['buyWindow']\n\n\t\tbackPanelSettings = buyWindowSettings['backPanel']\n\t\tbackPanel = GUI.BackPanel(\n\t\t\tbackPanelSettings['size'],\n\t\t\tbackPanelSettings['location'],\n\t\t\tbackgroundImage = backPanelSettings['backgroundImage'],\n\t\t\ttransitionMethod = transitions.presets.slideFromRightAndFadeShort\n\t\t\t)\n\n\t\tmenu = [\n\t\t{'name': \"Buy\", 'description': \"Buy this item?\", 'action': parent.buy, 'object': x},\n\t\t{'name': \"Close\", 'description': \"Close the purchase window\", 'action': backPanel.startClear}\n\t\t]\n\n\t\titemMenuSettings = buyWindowSettings['menu']\n\t\titemMenu = GUI.NavMenu(\n\t\t\tmenu, \n\t\t\titemMenuSettings['size'],\n\t\t\titemMenuSettings['location'],\n\t\t\tparent=backPanel,\n\t\t\tbackgroundImage=itemMenuSettings['backgroundImage']\n\t\t\t)\n\n\t\ttitleSettings = buyWindowSettings['title']\n\t\ttitle = GUI.TextBox(\n\t\t\ttitleSettings['size'],\n\t\t\ttitleSettings['location'],\n\t\t\tparent=backPanel,\n\t\t\twords=x.object.name,\n\t\t\tbackgroundImage=titleSettings['backgroundImage'],\n\t\t\tfont=shared.fontDisplayMedium\n\t\t\t)\n\n\t\tdescriptionSettings = buyWindowSettings['details']\n\t\tdescription = GUI.TextBox(\n\t\t\tdescriptionSettings['size'],\n\t\t\tdescriptionSettings['location'],\n\t\t\tparent=backPanel,\n\t\t\twords=x.object.description,\n\t\t\tbackgroundImage=descriptionSettings['backgroundImage']\n\t\t\t)\n\n\tsubmenu1Settings = resSettings['subMenus']\n\tsubmenu1 = GUI.NavMenu(\n\t\tshared.genObjectMenu(parent.shop.inventory, makeBuyWindow),\n\t\tsubmenu1Settings['size'],\n\t\tsubmenu1Settings['location'],\n\t\tparent=backPlate,\n\t\tvertical=True,\n\t\tscrollable=True,\n\t\tbackgroundImage=submenu1Settings['backgroundImage']\n\t\t)\n\n\tdef makeSellWindow(x):\n\t\tsellWindowSettings = resSettings['sellWindow']\n\n\t\tbackPanelSettings = sellWindowSettings['backPanel']\n\t\tbackPanel = GUI.BackPanel(\n\t\t\tbackPanelSettings['size'],\n\t\t\tbackPanelSettings['location'],\n\t\t\tbackgroundImage=backPanelSettings['backgroundImage'],\n\t\t\ttransitionMethod = transitions.presets.slideFromRightAndFadeShort\n\t\t\t)\n\n\t\tmenu = [\n\t\t{'name': \"Sell\", 'description': \"Sell This Item?\", 'action': parent.sell, 'object': x},\n\t\t{'name': \"Close\", 'description': \"Close the purchase window\", 'action': backPanel.startClear}\n\t\t]\n\n\t\titemMenuSettings = sellWindowSettings['menu']\n\t\titemMenu = GUI.NavMenu(\n\t\t\tmenu, \n\t\t\titemMenuSettings['size'],\n\t\t\titemMenuSettings['location'],\n\t\t\tparent=backPanel,\n\t\t\tbackgroundImage=itemMenuSettings['backgroundImage']\n\t\t\t)\n\n\t\ttitleSettings = sellWindowSettings['title']\n\t\ttitle = GUI.TextBox(\n\t\t\ttitleSettings['size'],\n\t\t\ttitleSettings['location'],\n\t\t\tparent=backPanel,\n\t\t\twords=x.object.name,\n\t\t\tbackgroundImage=titleSettings['backgroundImage'],\n\t\t\tfont=shared.fontDisplayMedium\n\t\t\t)\n\n\t\tdescriptionSettings = sellWindowSettings['details']\n\t\tdescription = GUI.TextBox(\n\t\t\tdescriptionSettings['size'],\n\t\t\tdescriptionSettings['location'],\n\t\t\tparent=backPanel,\n\t\t\twords=x.object.description,\n\t\t\tbackgroundImage=descriptionSettings['backgroundImage']\n\t\t\t)\n\n\tsubmenu2Settings = resSettings['subMenus']\n\tsubmenu2 = GUI.NavMenu(\n\t\tshared.genObjectMenu(parent.player.inventory, makeSellWindow),\n\t\tsubmenu2Settings['size'],\n\t\tsubmenu2Settings['location'],\n\t\tparent=backPlate,\n\t\tvertical=True,\n\t\tscrollable=True,\n\t\tbackgroundImage=submenu2Settings['backgroundImage']\n\t\t)\n\tmenuSpriteGroup.remove(submenu2)\n\n\tdef menuSwitch(x):\n\t\tif submenu2 in menuSpriteGroup:\n\t\t\tmenuSpriteGroup.remove(submenu2)\n\t\t\tsubmenu1.menulist[:] = []\n\t\t\tsubmenu1.menulist = submenu1.populateMenu(shared.genObjectMenu(parent.shop.inventory, makeBuyWindow))\n\t\tif submenu1 in menuSpriteGroup:\n\t\t\tmenuSpriteGroup.remove(submenu1)\n\t\t\tsubmenu2.menulist[:] = []\n\t\t\tsubmenu2.menulist = submenu2.populateMenu(shared.genObjectMenu(parent.player.inventory, makeSellWindow))\n\t\tmenuSpriteGroup.add(x.object)\n\t\tx.parent.highlight = x.parent.menulist.index(x)\n\n\ttopmenu = [\n\t\t{'name': \"BUY\", 'action': menuSwitch, 'object': submenu1}, \n\t\t{'name': \"SELL\", 'action': menuSwitch, 'object': submenu2}\n\t]\n\n\tmenuSettings = resSettings['topMenu']\n\tmenu = GUI.NavMenu(\n\t\ttopmenu,\n\t\tmenuSettings['size'],\n\t\tmenuSettings['location'],\n\t\tparent=backPlate,\n\t\tbackgroundImage=menuSettings['backgroundImage']\n\t\t)\n\n\n\n","sub_path":"views/itemshop.py","file_name":"itemshop.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"605934914","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport socket\nimport threading\nimport time\nimport traceback\n\nimport msgpack\n\n\n_global_sender = None\n\n\ndef _set_global_sender(sender):\n \"\"\" [For testing] Function to set global sender directly\n \"\"\"\n global _global_sender\n _global_sender = sender\n\n\ndef setup(tag, **kwargs):\n global _global_sender\n _global_sender = FluentSender(tag, **kwargs)\n\n\ndef get_global_sender():\n return _global_sender\n\n\nclass FluentSender(object):\n def __init__(self,\n tag,\n host='localhost',\n port=24224,\n bufmax=1 * 1024 * 1024,\n timeout=3.0,\n verbose=False,\n notice=False,\n **kwargs):\n\n self.tag = tag\n self.host = host\n self.port = port\n self.bufmax = bufmax\n self.timeout = timeout\n self.verbose = verbose\n self.notice = notice\n\n self.socket = None\n self.pendings = None\n self.lock = threading.Lock()\n\n try:\n self._reconnect()\n except Exception:\n if self.notice:\n raise\n # will be retried in emit()\n self._close()\n\n def emit(self, label, data):\n cur_time = int(time.time())\n self.emit_with_time(label, cur_time, data)\n\n def emit_with_time(self, label, timestamp, data):\n try:\n bytes_ = self._make_packet(label, timestamp, data)\n except Exception:\n if self.notice:\n raise\n bytes_ = self._make_packet(label, timestamp,\n {\"level\": \"CRITICAL\",\n \"message\": \"Can't output to log\",\n \"traceback\": traceback.format_exc()})\n self._send(bytes_)\n\n def _make_packet(self, label, timestamp, data):\n if label:\n tag = '.'.join((self.tag, label))\n else:\n tag = self.tag\n packet = (tag, timestamp, data)\n if self.verbose:\n print(packet)\n return msgpack.packb(packet)\n\n def _send(self, bytes_):\n self.lock.acquire()\n try:\n self._send_internal(bytes_)\n finally:\n self.lock.release()\n\n def _send_internal(self, bytes_):\n # buffering\n if self.pendings:\n self.pendings += bytes_\n bytes_ = self.pendings\n\n try:\n # reconnect if possible\n self._reconnect()\n\n # send message\n self.socket.sendall(bytes_)\n\n # send finished\n self.pendings = None\n except Exception:\n if self.notice:\n raise\n # close socket\n self._close()\n # clear buffer if it exceeds max bufer size\n if self.pendings and (len(self.pendings) > self.bufmax):\n # TODO: add callback handler here\n self.pendings = None\n else:\n self.pendings = bytes_\n\n def _reconnect(self):\n if not self.socket:\n if self.host.startswith('unix://'):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.settimeout(self.timeout)\n sock.connect(self.host[len('unix://'):])\n else:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.settimeout(self.timeout)\n sock.connect((self.host, self.port))\n self.socket = sock\n\n def _close(self):\n if self.socket:\n self.socket.close()\n self.socket = None\n","sub_path":"fluent/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"637505581","text":"\"\"\"empty message\n\nRevision ID: 18786a2efae7\nRevises: \nCreate Date: 2020-04-20 20:21:34.315497\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '18786a2efae7'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=64), nullable=True),\n sa.Column('email', sa.String(length=120), nullable=True),\n sa.Column('password_hash', sa.String(length=128), nullable=True),\n sa.Column('payPalFixed', sa.String(length=64), nullable=True),\n sa.Column('payPalPercent', sa.String(length=64), nullable=True),\n sa.Column('eBayPercent', sa.String(length=64), nullable=True),\n sa.Column('saleDisplayInfo', sa.Text(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)\n op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)\n op.create_table('items',\n sa.Column('itemName', sa.String(length=50), nullable=False),\n sa.Column('username', sa.String(length=64), nullable=False),\n sa.Column('date', sa.Date(), nullable=False),\n sa.Column('price', sa.String(length=64), nullable=False),\n sa.Column('quantity', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['username'], ['user.username'], ),\n sa.PrimaryKeyConstraint('itemName')\n )\n op.create_index(op.f('ix_items_date'), 'items', ['date'], unique=False)\n op.create_index(op.f('ix_items_itemName'), 'items', ['itemName'], unique=False)\n op.create_index(op.f('ix_items_username'), 'items', ['username'], unique=False)\n op.create_table('sales',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=64), nullable=False),\n sa.Column('itemName', sa.String(length=50), nullable=False),\n sa.Column('date', sa.Date(), nullable=False),\n sa.Column('price', sa.String(length=64), nullable=False),\n sa.Column('priceWithTax', sa.String(length=64), nullable=False),\n sa.Column('quantity', sa.Integer(), nullable=False),\n sa.Column('shipping', sa.String(length=64), nullable=False),\n sa.Column('profit', sa.String(length=64), nullable=False),\n sa.Column('packaging', sa.String(length=64), nullable=True),\n sa.Column('payPalFees', sa.String(length=64), nullable=True),\n sa.Column('eBayFees', sa.String(length=64), nullable=True),\n sa.Column('refund', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['itemName'], ['items.itemName'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_sales_date'), 'sales', ['date'], unique=False)\n op.create_index(op.f('ix_sales_itemName'), 'sales', ['itemName'], unique=False)\n op.create_index(op.f('ix_sales_username'), 'sales', ['username'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_sales_username'), table_name='sales')\n op.drop_index(op.f('ix_sales_itemName'), table_name='sales')\n op.drop_index(op.f('ix_sales_date'), table_name='sales')\n op.drop_table('sales')\n op.drop_index(op.f('ix_items_username'), table_name='items')\n op.drop_index(op.f('ix_items_itemName'), table_name='items')\n op.drop_index(op.f('ix_items_date'), table_name='items')\n op.drop_table('items')\n op.drop_index(op.f('ix_user_username'), table_name='user')\n op.drop_index(op.f('ix_user_email'), table_name='user')\n op.drop_table('user')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/18786a2efae7_.py","file_name":"18786a2efae7_.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"326636112","text":"import sys\n\nsys.stdin = open(\"input.txt\",\"r\")\n\nT = int(input())\n\ndef inRange(a,b,N):\n if 0 <= a < N and 0 <= b < N:\n return True\n return False\n\ndirection = [(-1,0),(1,0),(0,-1),(0,1)]\n\ndef direction_change(dir,triangle):\n if triangle == 1:\n if dir == (0,1):\n dir = (0,-1)\n elif dir == (-1,0):\n dir = (1,0)\n elif dir == (1,0):\n dir = (0,1)\n else:\n dir = (-1,0)\n elif triangle == 2:\n if dir == (0,1):\n dir = (0,-1)\n elif dir == (1,0):\n dir = (-1,0)\n elif dir == (0,-1):\n dir = (1,0)\n else:\n dir = (0,1)\n elif triangle == 3:\n if dir == (0,1):\n dir = (1,0)\n elif dir == (-1,0):\n dir = (0,-1)\n elif dir == (1,0):\n dir = (-1,0)\n else:\n dir = (0,1)\n elif triangle == 4:\n if dir == (0,1):\n dir = (-1,0)\n elif dir == (1,0):\n dir = (0,-1)\n elif dir == (-1,0):\n dir = (1,0)\n else:\n dir = (0,1)\n elif triangle == 5:\n if dir == (0,1):\n dir = (0,-1)\n elif dir == (-1,0):\n dir = (1,0)\n elif dir == (0,-1):\n dir = (0,1)\n else:\n dir = (-1,0)\n return dir\n\ndef start(current,dir,game,N):\n start_pos = current\n count = 0\n while True:\n current = (current[0] + dir[0], current[1] + dir[1])\n\n if inRange(current[0],current[1],N) == False:\n count +=1\n current = (current[0] - dir[0], current[1] - dir[1])\n dir = direction_change(dir,5)\n\n status = game[current[0]][current[1]]\n if current == start_pos:\n return count\n elif status == 0:\n continue\n elif 1 <= status <=5:\n dir = direction_change(dir,status)\n count +=1\n elif 6 <= status <= 10:\n warm = warmhole[status]\n if current == warm[0]:\n current = warm[1]\n else:\n current = warm[0]\n elif status == -1:\n return count\n\nfor test in range(1,T+1):\n N = int(input())\n warmhole = dict()\n game = []\n for i in range(N):\n A = []\n for index,j in enumerate(input().rstrip().split()):\n A.append(int(j))\n if 6<= int(j) <=10:\n try:\n warmhole[int(j)].append((i,index))\n except:\n warmhole[int(j)] = [(i,index)]\n game.append(A)\n\n Max_count = 0\n for x in range(N):\n for y in range(N):\n if game[x][y] == 0:\n #print(x,y)\n for dir in direction:\n result = start((x,y),dir,game,N)\n if result > Max_count:\n Max_count = result\n print('#'+str(test),end=' ')\n print(Max_count)\n","sub_path":"5650. [모의 SW 역량테스트] 핀볼 게임.py","file_name":"5650. [모의 SW 역량테스트] 핀볼 게임.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"17050719","text":"import numpy as np\nimport pandas as pd\nimport spacy\nfrom keras.preprocessing import sequence\n\nnlp = spacy.load('en')\n\n\n# nlp = spacy.load('en_vectors_web_lg')\n\n\ndef get_twets_data():\n data_location = '/home/jehill/python/NLP/datasets/twits/StockTwits_SPY_Sentiment_2017.gz'\n\n data = pd.read_csv(data_location,\n encoding=\"utf-8\",\n compression=\"gzip\",\n index_col=0)\n\n return data\n\n\ndef sentence_embedding(sentence, embedding_dim):\n tokens = nlp(sentence)\n data = np.zeros((len(sentence), embedding_dim))\n k = 0\n for token in tokens:\n data[k, :] = token.vector\n k = k + 1\n\n return data\n\n\ndef get_training_batch_twets(data, batch_size, embedding_dim, num_classes, maxlen):\n num_classes = num_classes\n x = np.zeros([batch_size, maxlen, embedding_dim])\n y = np.zeros([batch_size, num_classes])\n\n index = 0\n\n bullish_count = 0\n bearish_count = 0\n\n for idx, row in data.iterrows():\n x[index, :, :] = sequence.pad_sequences([sentence_embedding(row['message'], embedding_dim)], maxlen=maxlen)\n if (row['sentiment'] == 'bullish'):\n y[index, :] = np.array([0, 1])\n bullish_count = bullish_count + 1\n else:\n y[index, :] = np.array([1, 0])\n bearish_count = bearish_count + 1\n\n index = index + 1\n\n print(\"Total messages in the batch\" + str(len(data)))\n print(\"Bearish messages in the batch\" + str(bearish_count))\n print(\"Bullish messages in the batch\" + str(bullish_count))\n\n return x, y\n\n\nif __name__ == '__main__':\n a = nlp('this')\n look_up = nlp.vocab.vectors.most_similar(a.vector)\n\n print(np.shape(a.vector))\n print(look_up)\n\n \"\"\"\n train_data = get_twets_data();\n train_data = train_data.sample(frac=1).reset_index(drop=True)\n emd_dim = 300\n batch_size = 1000\n\n for index in range(0, len(train_data), batch_size):\n print(index)\n BATCH_X, BATCH_Y = get_training_batch_twets(train_data[index:index + batch_size], batch_size=batch_size,\n embedding_dim=emd_dim, num_classes=2, maxlen=250)\n print(np.shape(BATCH_X))\n print(np.shape(BATCH_Y))\n \"\"\"\n","sub_path":"models/NLP/utilities/StockTwits.py","file_name":"StockTwits.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"100421147","text":"import contextlib\nimport datetime\nimport io\nimport json\nimport pathlib\nimport re\nimport shutil\nimport subprocess\nimport tarfile\nimport tempfile\nimport time\n\nimport click\nimport encapsia_api\nimport requests.exceptions\nimport toml\n\n\ndef log(message=\"\", nl=True):\n click.secho(message, fg=\"yellow\", nl=nl)\n\n\ndef log_output(message=\"\"):\n click.secho(message, fg=\"green\")\n\n\ndef log_error(message=\"\", abort=False):\n click.secho(message, fg=\"red\", err=True)\n if abort:\n raise click.Abort()\n\n\ndef pretty_print(obj, format, output=None):\n if format == \"json\":\n formatted = json.dumps(obj, sort_keys=True, indent=4).strip()\n elif format == \"toml\":\n formatted = toml.dumps(obj)\n if output is None:\n log_output(formatted)\n else:\n output.write(formatted)\n\n\ndef get_api(**obj):\n host = obj.get(\"host\")\n try:\n url, token = encapsia_api.discover_credentials(host)\n except encapsia_api.EncapsiaApiError as e:\n log_error(\"Unable to determine host (or URL/token).\")\n log_error(\n \"Try specifying via the command line, env variable, or ~/.encapsia/config.toml file.\"\n )\n log_error(str(e), abort=True)\n return encapsia_api.EncapsiaApi(url, token)\n\n\ndef add_docstring(value):\n \"\"\"Decorator to add a docstring to a function.\"\"\"\n\n def _doc(func):\n func.__doc__ = value\n return func\n\n return _doc\n\n\n# See http://www.regular-expressions.info/email.html\nEMAIL_REGEX = re.compile(r\"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\")\n\n\ndef validate_email(ctx, param, value):\n if not EMAIL_REGEX.match(value):\n raise click.BadParameter(\"Not a valid email address\")\n return value\n\n\ndef get_utc_now_as_iso8601():\n return str(datetime.datetime.utcnow())\n\n\n@contextlib.contextmanager\ndef temp_directory():\n \"\"\"Context manager for creating a temporary directory.\n\n Cleans up afterwards.\n\n \"\"\"\n directory = tempfile.mkdtemp()\n try:\n yield pathlib.Path(directory)\n finally:\n shutil.rmtree(directory)\n\n\ndef most_recently_modified(directory):\n \"\"\"Return datetime of most recently changed file in directory.\"\"\"\n files = list(directory.glob(\"**/*.*\"))\n if files:\n return datetime.datetime.utcfromtimestamp(max(t.stat().st_mtime for t in files))\n else:\n return None\n\n\ndef run(*args, **kwargs):\n \"\"\"Run external command.\"\"\"\n return subprocess.check_output(args, stderr=subprocess.STDOUT, **kwargs)\n\n\ndef read_toml(filename):\n with filename.open() as f:\n return toml.load(f)\n\n\ndef write_toml(filename, obj):\n with filename.open(\"w\") as f:\n toml.dump(obj, f)\n\n\ndef create_targz(directory, filename):\n with tarfile.open(filename, \"w:gz\") as tar:\n tar.add(directory, arcname=directory.name)\n\n\ndef create_targz_as_bytes(directory):\n data = io.BytesIO()\n with tarfile.open(mode=\"w:gz\", fileobj=data) as tar:\n tar.add(directory, arcname=directory.name)\n return data.getvalue()\n\n\ndef extract_targz(filename, directory):\n with tarfile.open(filename) as tar:\n tar.extractall(directory)\n\n\ndef parse(obj, format):\n if format == \"json\":\n return json.loads(obj)\n elif format == \"toml\":\n return toml.loads(obj)\n\n\ndef visual_poll(message, poll, NoTaskResultYet, wait=0.2):\n log(message, nl=False)\n result = NoTaskResultYet\n count = 0\n while result is NoTaskResultYet:\n progress_char = \".\"\n try:\n result = poll()\n except requests.exceptions.ConnectTimeout:\n progress_char = click.style(\"T\", fg=\"red\")\n except requests.exceptions.ConnectionError:\n progress_char = click.style(\"C\", fg=\"red\")\n log(progress_char, nl=False)\n time.sleep(wait)\n count += 1\n if count < 3:\n log(\".\" * (3 - count), nl=False)\n log(\"Done\")\n return result\n\n\ndef run_task(\n api, namespace, name, params, message, upload=None, download=None, idempotent=False\n):\n \"\"\"Return the raw json result or log (HTTP) error and abort.\"\"\"\n poll, NoTaskResultYet = resilient_call(\n api.run_task,\n namespace,\n name,\n params,\n description=f\"api.run_task({namespace}, {name})\",\n upload=upload,\n download=download,\n idempotent=idempotent,\n )\n try:\n return visual_poll(message, poll, NoTaskResultYet)\n except encapsia_api.EncapsiaApiFailedTaskError as e:\n result = e.payload\n log_error(f\"\\nStatus: {result['status']}\")\n log_error(result.get(\"exc_info\"), abort=True)\n\n\ndef run_plugins_task(\n api, name, params, message, data=None, print_output=True, idempotent=False\n):\n \"\"\"Log the result from pluginmanager, which will either be successful or not.\"\"\"\n reply = run_task(\n api,\n \"pluginsmanager\",\n f\"icepluginsmanager.{name}\",\n params,\n message,\n upload=data,\n idempotent=idempotent,\n )\n if reply[\"status\"] == \"ok\":\n if print_output:\n log_output(reply[\"output\"].strip())\n return True\n else:\n log_error(f\"Status: {reply['status']}\")\n log_error(reply[\"output\"].strip())\n return False\n\n\ndef run_job(\n api,\n namespace,\n function,\n params,\n message,\n upload=None,\n download=None,\n idempotent=False,\n):\n \"\"\"Run job, wait for it to complete, and log all joblogs; or log error from task.\"\"\"\n poll, NoResultYet = resilient_call(\n api.run_job,\n namespace,\n function,\n params,\n description=f\"api.run_job({namespace}, {function})\",\n upload=upload,\n download=download,\n idempotent=idempotent,\n )\n try:\n return visual_poll(message, poll, NoResultYet)\n except encapsia_api.EncapsiaApiFailedTaskError as e:\n result = e.payload\n log_error(f\"\\nStatus: {result['status']}\")\n log_error(result.get(\"exc_info\"), abort=True)\n\n\ndef dbctl_action(api, name, params, message, idempotent=False):\n poll, NoTaskResultYet = resilient_call(\n api.dbctl_action,\n name,\n params,\n description=f\"api.dbctl_action({name})\",\n idempotent=idempotent,\n )\n result = visual_poll(message, poll, NoTaskResultYet)\n if result[\"status\"] != \"ok\":\n raise click.Abort()\n return result[\"result\"]\n\n\nclass MaxRetriesExceededError(Exception):\n pass\n\n\ndef resilient_call(\n fn, *args, description=None, idempotent=False, max_retries=10, **kwargs\n):\n count = 1\n if description is None:\n description = f\"{fn.__qualname__}(...)\"\n while True:\n log(f\"Calling: {description} (attempt {count}/{max_retries})\")\n try:\n return fn(*args, **kwargs)\n except requests.exceptions.ConnectionError:\n pass\n except requests.exceptions.ConnectTimeout:\n if not idempotent:\n raise\n count += 1\n if count > max_retries:\n raise MaxRetriesExceededError\n","sub_path":"encapsia_cli/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"526426006","text":"import youtube_dl\n\nfrom flask_restful import Resource\n\n\nclass StreamResource(Resource):\n\n def get(self):\n url = \"https://www.youtube.com/watch?v=szvFmW_oxeY\"\n\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'ogg',\n 'preferredquality': '192',\n }],\n }\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.to_stdout(url)\n","sub_path":"siano/resources/StreamResource.py","file_name":"StreamResource.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"456688959","text":"from django.shortcuts import render, get_object_or_404, HttpResponseRedirect, reverse\nfrom .models import Course, CourseDiscount\nfrom .forms import CourseAddingForm\nimport string, random\nfrom finalreg.models import FinalRegistration\nfrom .forms import CourseDiscountForm\nfrom django.contrib import messages\nfrom Certification_Request.models import Certificate\nimport datetime\nfrom dateutil import relativedelta\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.contrib.auth.models import User\nimport os\nfrom django.http import JsonResponse\n\ndef course_adding(request):\n if request.user.is_staff:\n form = CourseAddingForm(data=request.POST or None)\n\n if form.is_valid():\n form.save()\n name = form.cleaned_data.get('name')\n course = get_object_or_404(Course, name=name)\n\n code = ''.join(random.choices(string.ascii_lowercase +\n string.ascii_uppercase + string.digits, k=5))\n course.course_code = code\n\n if course.status == \"3\":\n course.status = \"2\"\n course.is_registerable = False\n else:\n pass\n course.save()\n return HttpResponseRedirect(reverse('panel'))\n else:\n return HttpResponseRedirect(reverse('user-panel'))\n return render(request, 'course/course-add.html', context={'form':form})\n\ndef course_edit(request, code):\n if request.user.is_staff:\n course = get_object_or_404(Course, course_code=code)\n form = CourseAddingForm(instance=course, data=request.POST or None)\n\n if form.is_valid():\n status = form.cleaned_data.get('status', '')\n if status == \"3\":\n course.is_registerable = True\n ext = ''.join(random.choices(string.ascii_lowercase +\n string.ascii_uppercase + string.digits, k=25))\n course.registering_extension = ext\n course.save()\n else:\n course.is_registerable = False\n code = ''.join(random.choices(string.ascii_lowercase +\n string.ascii_uppercase + string.digits, k=5))\n course.course_code = code\n course.save()\n\n form.save()\n return HttpResponseRedirect(reverse('panel'))\n else:\n return HttpResponseRedirect(reverse('user-panel'))\n return render(request, 'course/course-edit.html', context={'form':form})\n\ndef course_list(request):\n if request.user.is_staff:\n courses = Course.objects.all()\n else:\n return HttpResponseRedirect(reverse('user-panel'))\n return render(request, 'course/course-list.html', context={'courses':courses})\n\ndef active_courses(request):\n if request.user.is_staff:\n finalregs = FinalRegistration.objects.all()\n else:\n return HttpResponseRedirect(reverse('user-panel'))\n return render(request, 'course/active-courses.html', context={'finalregs':finalregs})\n\ndef course_detail(request, code):\n if not request.user.is_active:\n return HttpResponseRedirect(reverse('login'))\n else:\n course = get_object_or_404(Course, course_code=code)\n return render(request, 'course/course-detail.html', context={'course':course})\n\ndef course_discounts(request):\n if not request.user.is_staff:\n return HttpResponseRedirect(reverse('user-panel'))\n if request.user.is_staff:\n form = CourseDiscountForm(data=request.POST or None)\n discount = CourseDiscount.objects.get(id=2)\n if form.is_valid():\n d1 = form.cleaned_data.get('discount_1')\n d2 = form.cleaned_data.get('discount_2')\n account_info = form.cleaned_data.get('bank_info')\n discount.discount_1 = d1\n discount.discount_2 = d2\n\n if len(account_info) == 0:\n messages.success(request, 'Discount applied', extra_tags='success')\n else:\n discount.bank_info = account_info\n messages.success(request, 'Bank account information and discounts updated.', extra_tags='success')\n\n discount.save()\n return HttpResponseRedirect(reverse('course-discount'))\n else:\n return HttpResponseRedirect(reverse('user-panel'))\n return render(request, 'course/discount-edit.html', context={'form':form, 'discount':discount})\n\ndef send_certificationrequest(request, pk):\n if not request.user.is_active:\n return HttpResponseRedirect(reverse('login'))\n else:\n course = get_object_or_404(Course, id=pk)\n\n today = datetime.date(datetime.datetime.now().year,\n datetime.datetime.now().month,\n datetime.datetime.now().day)\n\n c_date =course.finish_at\n c_finishing_date = datetime.date(c_date.year,\n c_date.month,\n c_date.day)\n\n diff = relativedelta.relativedelta(today, c_finishing_date)\n diff_tuple = diff.years, diff.months, diff.days\n if diff_tuple[0] >= 0 and diff_tuple[1] >= 0 and diff_tuple[2] >= 0:\n if Certificate.objects.filter(user=request.user, course=course).exists():\n messages.success(request, \"You've already sent a request. \"\n \"Please wait until we upload your certification.\",\n extra_tags='danger')\n return HttpResponseRedirect(reverse('user-panel'))\n else:\n Certificate.objects.create(user=request.user, course=course).save()\n subject = \"Course | A new certification request has taken.\"\n from_mail = settings.EMAIL_HOST_USER\n message = \"\"\n html_msg = \"\"\"\n

\n Please check certification request on \"Certification Requests\" from management panel.\n

\n \"\"\"\n\n send_mail(subject, message, from_mail, [os.environ['EMAIL_ADRESS']], html_message=html_msg, fail_silently=True)\n messages.success(request,\n 'Your certification request has taken. When we upload your certification, we will send a e-mail.')\n else:\n messages.success(request, 'You cannot send a request for an unfinished course.', extra_tags=\"danger\")\n return HttpResponseRedirect(reverse('user-panel'))\n\ndef course_user_list(request, code):\n course = get_object_or_404(Course, course_code=code)\n users = course.profile_set.all()\n return render(request, 'course/course-user-list.html', context={'users':users})\n\ndef user_contact_info(request):\n data = {'is_valid': True, 'name': '', 'mail': '', 'phone': '', 'other_phone': ''}\n\n name = request.GET.get('name')\n mail = request.GET.get('mail')\n phone = request.GET.get('phone')\n other_phone = request.GET.get('other_phone')\n\n data.update({'name': name, 'mail': mail, 'phone': phone, 'other_phone': other_phone})\n return JsonResponse(data=data)","sub_path":"courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"56"} +{"seq_id":"232348562","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom SpeechModel251 import ModelSpeech\nfrom LanguageModel import ModelLanguage\nimport pandas as pd\nimport os\nimport Levenshtein\n\ndef pinyin_decode(pinyin):\n id_to_tok = {\"yi\":\"1\", \"er\":\"2\", \"san\":\"3\" ,\"si\":\"4\", \"wu\":\"5\",\"liu\":\"6\",\"qi\":\"7\",\"ba\":\"8\", \"jiu\":\"9\",\"ling\":\"0\"}\n tok = [id_to_tok[p[:-1]] for p in pinyin ] # 忽略音调\n \n return ''.join(tok)\n\ndef recognize_same(x, content, ms):\n \n # 识别的随机码与真实的随机码的距离是否在1以内\n # 距离在1以内的则认为验证码识别通过\n \n r = ms.RecognizeSpeech_FromFile(x)\n r = pinyin_decode(r)\n dist = Levenshtein.distance(content,r)\n return dist <= 1\n\n \ndef recognize_code(x, content, ms):\n \n # 返回识别的随机码\n \n r = ms.RecognizeSpeech_FromFile(x)\n r = pinyin_decode(r)\n \n return r\n \n\nif __name__=='__main__':\n \n datapath = 'model_speech'\n modelpath = 'model_speech'\n ms = ModelSpeech(datapath)\n\n ms.LoadModel(os.path.join(modelpath, 'speech_model251_e_0_step_200.model'))\n\n filename = '/data1/1806_speech-recognition/random_code/wav/00818_VID_20190328_145629.wav'\n\n content = '00818'\n \n print(recognize_same(filename, content, ms))\n print(recognize_code(filename, content, ms))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"apply.py","file_name":"apply.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"427353393","text":"import GPy\nimport sys\nimport os\nsys.path.append(os.getenv(\"HOME\") + \"/Documents/Code/Emulation/GPyDifferentMetrics/\")\nfrom HaversineDist import Exponentialhaversine\nimport numpy as np\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport glob as glob\nfrom cmocean import cm as cm\nfrom Utilities import *\n\n\n\nGCM_dir = os.getenv(\"HOME\")+'/Documents/Code/ModelDataComparison/DMC/Scripts/Model_data/CO2_anom/'\ngcm_SSTs = glob.glob(GCM_dir+'t*.txt')\n\ngcm_mask = np.genfromtxt(GCM_dir+'mask.txt', dtype='int')\n\nobs_dir = os.getenv(\"HOME\")+'/Documents/Code/ModelDataComparison/DMC/Scripts/Observation_data/P3+_SST_anom/'\nfile = 'lambda_10.txt'\nobservations = np.genfromtxt(obs_dir+file, skip_header=1)\n\nX_obs = observations[:,0:2]\ny_obs = observations[:,2].reshape(-1,1)\nvar_ratios = observations[:,3][:,None]**2\n\n# Plot the data locations\nmap = plot_map(X_obs=X_obs)\n#plt.show()\n\n\n######################################\n# Start by just fitting a GP, not a circle, not with heteroscedastic noise.\nk = GPy.kern.Exponential(2, ARD=True)\nm = GPy.models.GPRegression(X_obs, y_obs,k)\nm.optimize_restarts(10)\nprint(m)\nprint(m.rbf.lengthscale)\n#\n\n########################################\n# Create plotting grid on 5 deg grid\nlatsplot = np.arange(-85.0,90.0, 5.)\nlongsplot = np.arange(-180.0,180.0, 5.)\nlonggridplot, latgridplot = np.meshgrid(longsplot, latsplot)\nX_plot=np.column_stack((longgridplot.flatten(), latgridplot.flatten()))\n\n######\n# Predict and plot\n\nmu,V = m.predict(X_plot)\n\nplt.figure(1)\nmap=plot_map(longgridplot, latgridplot, mu, X_obs)\n\nplt.figure(2)\nmap=plot_map(longgridplot, latgridplot, np.sqrt(V), X_obs, levels=np.arange(0,np.sqrt(V).max()+1,0.25))\n\n#plt.show()\n\n\n\n\n###################################################################################\n#\n#\n# Repeat but now with Spherical kernel\n#\n#\n###################################################################################\n\n\n\nk2 = Exponentialhaversine(2, lengthscale=2000)\nm2 = GPy.models.GPRegression(X_obs, y_obs,k2)\nm2.optimize_restarts(10)\nprint(m2)\nmu2,V2 = m2.predict(X_plot)\n\nplt.figure(1)\nmap=plot_map(longgridplot, latgridplot, mu2, X_obs)\nplt.title('Spherical GP - constant error')\n\nplt.figure(2)\nmap=plot_map(longgridplot, latgridplot, V2, X_obs, levels=np.arange(0,V2.max()+1,0.25))\n#plt.show()\n\n\n\n###################################################################################\n#\n#\n# Repeat but now with Spherical kernel and heteroscedastic likelihood.\n#\n#\n###################################################################################\n\nfrom scaledheteroscedasticgaussian import ScaledHeteroscedasticGaussian\nfrom gp_heteroscedastic_ratios import ScaledHeteroscedasticRegression\n\n\nk3 = Exponentialhaversine(2, lengthscale=2000)\nm3 = ScaledHeteroscedasticRegression(X=X_obs, Y=y_obs, kernel=k3, noise_mult=1., known_variances=var_ratios)\nm3.optimize_restarts(10)\nprint(m3)\n\nmu3,V3 = m3.predict_noiseless(X_plot)\n\n\nplt.figure(3)\nmap=plot_map(longgridplot, latgridplot, mu3, X_obs)\nplt.title('Spherical GP - heteroscedastic error')\n\nplt.figure(4)\nmap=plot_map(longgridplot, latgridplot, V3, X_obs, levels=np.arange(0,V3.max()+1,0.25))\n#plt.show()\n\n\n############################################################\n#\n# Let's now evaluate the log-likelihood\n#\n#\n############################################################\n\nfrom scipy.stats import multivariate_normal\n\ncount=0\nloglikes = np.zeros(len(gcm_SSTs))\n\n#\n#tmp = np.column_stack((gcm_grid, gcm_grid))\n#multivariate_normal.logpdf(tmp.T, mu.flatten(), Cov)\n# Is quicker\n\n# Best we can hope for is...\n\nfrom Cholesky import *\n\nmultivariate_normal.logpdf(mu.flatten(), mu.flatten(), Cov)\n\n# What else can we compare with?\n\nfor file_name in gcm_SSTs:\n\n file_nm = file_name.split(GCM_dir)[-1]\n print(file_nm)\n\n # Read in GCM output.\n gcm1 = np.genfromtxt(file_name)\n\n\n X_pred, gcm_grid = ThinGrid(gcm1, gcm_mask, thinby=5)\n mu, Cov = m3.predict_noiseless(X_pred, full_cov=True)\n\n loglikes[count] = multivariate_normal.logpdf(gcm_grid.flatten(), mu.flatten(), Cov)\n\n # what should I do about the measurement error?\n # Or is there no measurement error as we've modelled the underlying surface with a GP!\n count += 1\n\n\n\n\"\"\"\nTo do\n- Check sanity of loglike values\n- why do random values have much smaller values than the simulations?\n- do the tests we discussed\n- describe problem with ARD kernel.\n- robust scoring rules?\n- compare to MSE\n- check likelihood calculation - seems to not be robust to thinning of the grid.\n\n\"\"\"\n\n\n\"\"\"\n\nk._unscaled_dist(X_obs)\n\n###################\nk1 = Exponentialhaversine(2, lengthscale=2000)\n# how do we specify a different noice variance at each locations\n\nm = GPy.models.GPRegression(X_obs, y_obs, k1)\nm.optimize_restarts(10)\nprint(m)\n\n\n#########################\n#\n# Predict at GCM grid locations.\n#\n\n\nlats = np.arange(-89.375,89.375,1.25)\nlongs = np.arange(-180,178.75+0.1, 1.25)\nlonggrid, latgrid = np.meshgrid(longs, lats)\n\nGCM_dir = os.getenv(\"HOME\")+'/Documents/Code/ModelDataComparison/DMC/Scripts/Model_data/CO2_anom/'\nfile_name = 'tczyi.txt'\ngcm1 = np.genfromtxt(GCM_dir+file_name)\ngcm_mask = np.genfromtxt(GCM_dir+'mask.txt', dtype='int')\n\nXpred = np.column_stack((longgrid.flatten()[gcm_mask-1], latgrid.flatten()[gcm_mask-1]))\nypred, Vpred = m.predict_noiseless(Xpred)\n\nyplot = np.zeros(longgrid.size)\nyplot[gcm_mask-1] = ypred\n\n############### Equidistant Cylindrical Projection ####################################\n# The simplest projection, just displays the world in latitude/longitude coordinates.\nm = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\\\n llcrnrlon=-180,urcrnrlon=180,resolution='c')\nm.drawcoastlines()\n#m.fillcontinents(color='coral',lake_color='aqua')\n# draw parallels and meridians.\nm.drawparallels(np.arange(-90.,91.,30.))\nm.drawmeridians(np.arange(-180.,181.,60.))\nm.drawmapboundary(fill_color='aqua')\nplt.xlabel('lon')\nplt.ylabel('lat')\nlevels = np.arange(-10,10,1)\nfrom cmocean import cm as cm\nm.contourf(longgrid,latgrid,yplot.reshape(lats.size,longs.size),15,levels=levels,\n cm = cm.thermal, linewidths=1.5)\nm.colorbar()\nm.scatter(X_obs[:,0],X_obs[:,1] )\nplt.show()\n\"\"\"\n","sub_path":"FitToSSTanom.py","file_name":"FitToSSTanom.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466601876","text":"def solve():\n srcs=input()[1:-1].replace('\"','').split(',')\n res=0\n for i in range(len(srcs)):\n for j in range(i+1,len(srcs)):\n if isOK(srcs[i],srcs[j]):\n current=len(srcs[i])*len(srcs[j])\n if current>res:\n res=current\n print(res)\n\ndef isOK(s1,s2):\n set1=set(s1)\n set2=set(s2)\n return set1.isdisjoint(set2)\n\nif __name__ == '__main__' :\n solve()","sub_path":"Code/CodeRecords/2897/60770/263708.py","file_name":"263708.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}